diff --git a/Code/Mantid/Installers/MacInstaller/adjustPropertiesFile.py b/Code/Mantid/Installers/MacInstaller/adjustPropertiesFile.py
index 91e5d1f9567168bda63a037c310f7a12c96add32..2ab02f471ccb405599bf98ed78e7644709669087 100755
--- a/Code/Mantid/Installers/MacInstaller/adjustPropertiesFile.py
+++ b/Code/Mantid/Installers/MacInstaller/adjustPropertiesFile.py
@@ -1,46 +1,46 @@
-#!/bin/python
-#
-# Copies the default Mantid.properties file, adjusting directories where
-# necessary.
-#
-
-# Field replacements
-replacements = {
-    "plugins.directory":"plugins.directory = ../../plugins",
-    "mantidqt.plugins.directory" : "mantidqt.plugins.directory = ../../plugins/qtplugins/mantid",
-    "instrumentDefinition.directory":"instrumentDefinition.directory = ../../instrument",
-    "parameterDefinition.directory":"parameterDefinition.directory = ../../instrument",    
-    "requiredpythonscript.directories":"""requiredpythonscript.directories = ../../scripts/Crystallography;../../scripts/Disordered Materials;../../scripts/Engineering;\\
-../../scripts/Inelastic;../../scripts/Large Scale Structures;../../scripts/Molecular Spectroscopy;\\
-../../scripts/Muons;../../scripts/Neutrinos;../../scripts/SANS;../../scripts/""",
-    "pythonscripts.directory":"pythonscripts.directory = ../../scripts",
-    "mantidqt.python_interfaces_directory":"mantidqt.python_interfaces_directory = ../../scripts",
-    "pythonscripts.directories":"pythonscripts.directories = ../../scripts",
-    "pythonalgorithms.directories":"pythonalgorithms.directories = ../../plugins/PythonAlgs"
-}
-
-template = open('../../Framework/Properties/Mantid.properties','r')
-original = template.readlines()
-prop_file = open('MantidPlot.app/Contents/MacOS/Mantid.properties','w')
-continuation = False
-nlines = len(original)
-index = 0
-while( index < nlines ):
-    line = original[index]
-    key = ""
-    for rep in replacements.iterkeys():
-        if line.startswith(rep):
-            key = rep
-            break
-    if key != "":
-        prop_file.write(replacements[key] + "\n")
-        # Skip any backslashed lines
-        while line.rstrip().endswith("\\") and index < nlines:
-            index += 1
-            line = original[index]
-    else:
-        prop_file.write(line)
-    index += 1
-    
-template.close()
-prop_file.close()
+#!/bin/python
+#
+# Copies the default Mantid.properties file, adjusting directories where
+# necessary.
+#
+
+# Field replacements
+replacements = {
+    "plugins.directory":"plugins.directory = ../../plugins",
+    "mantidqt.plugins.directory" : "mantidqt.plugins.directory = ../../plugins/qtplugins/mantid",
+    "instrumentDefinition.directory":"instrumentDefinition.directory = ../../instrument",
+    "parameterDefinition.directory":"parameterDefinition.directory = ../../instrument",    
+    "requiredpythonscript.directories":"""requiredpythonscript.directories = ../../scripts/Crystallography;../../scripts/Disordered Materials;../../scripts/Engineering;\\
+../../scripts/Inelastic;../../scripts/Large Scale Structures;../../scripts/Molecular Spectroscopy;\\
+../../scripts/Muons;../../scripts/Neutrinos;../../scripts/SANS;../../scripts/""",
+    "pythonscripts.directory":"pythonscripts.directory = ../../scripts",
+    "mantidqt.python_interfaces_directory":"mantidqt.python_interfaces_directory = ../../scripts",
+    "pythonscripts.directories":"pythonscripts.directories = ../../scripts",
+    "pythonalgorithms.directories":"pythonalgorithms.directories = ../../plugins/PythonAlgs"
+}
+
+template = open('../../Framework/Properties/Mantid.properties','r')
+original = template.readlines()
+prop_file = open('MantidPlot.app/Contents/MacOS/Mantid.properties','w')
+continuation = False
+nlines = len(original)
+index = 0
+while( index < nlines ):
+    line = original[index]
+    key = ""
+    for rep in replacements.iterkeys():
+        if line.startswith(rep):
+            key = rep
+            break
+    if key != "":
+        prop_file.write(replacements[key] + "\n")
+        # Skip any backslashed lines
+        while line.rstrip().endswith("\\") and index < nlines:
+            index += 1
+            line = original[index]
+    else:
+        prop_file.write(line)
+    index += 1
+    
+template.close()
+prop_file.close()
diff --git a/Code/Mantid/Installers/WinInstaller/MantidLauncher/MantidLauncher.cpp b/Code/Mantid/Installers/WinInstaller/MantidLauncher/MantidLauncher.cpp
index c36f826138fcca62abedbed903b6cdab2c3e3445..09b3d9a1adee5379e103f6cc4c2e9c5a7caf18c3 100644
--- a/Code/Mantid/Installers/WinInstaller/MantidLauncher/MantidLauncher.cpp
+++ b/Code/Mantid/Installers/WinInstaller/MantidLauncher/MantidLauncher.cpp
@@ -1,397 +1,397 @@
-// 
-// MantidLauncher.cpp : Launches MantidPlot if there aren't any updates available.
-//                      If there are new updates MantidLauncher downloads them from http://download.mantidproject.org/updates 
-//                      and installs.
-//
-
-#include "stdafx.h"
-#include "Resource.h"
-#include <windows.h>
-#include <winhttp.h>
-#include <commctrl.h>
-
-#include <iostream>
-#include <fstream>
-#include <sstream>
-#include <vector>
-
-
-using namespace std;
-
-class Cancel:public runtime_error
-{
-public:
-    Cancel():runtime_error(""){}
-};
-
-// Download file from website ws and path fn, so that URI is http://<ws>/<fn> and saves it in local file lfn
-void readFile(const wchar_t* ws,const wchar_t* fn,const string& lfn);
-void readFile_tst(const string& url,const string& fn);
-
-// Read version and product GUID from local file
-void readVersion(const string& fn,int& ver_maj,int& ver_min, int& ver_buid, string& guid, int& fSize);
-
-// Launches application with command line cmd. Returns straight away, not waiting for
-// the application to finish.
-void Launch(const string& cmd);
-
-// Progress dialog function
-BOOL CALLBACK ProgressDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam);
-
-// Starts Progress dialog in a separate thread
-DWORD WINAPI ThreadProc(PVOID pParameter);
-
-// Returns true if HKLM\Software\Mantid exists meaning Mantid is installed
-bool ReadMantidRegValue(const std::string& valueName,std::string& value);
-
-void mess(const string& str)
-{
-    MessageBoxA(0,str.c_str(),"Mantid Laincher",MB_OK);
-}
-
-// Global variables
-HINSTANCE hInst;
-HWND hwndPB;
-HWND hwndDialog;
-int fileSize = 35; // Size of Mantid.msi in MB?
-bool cancelDownload = false;
-
-int APIENTRY _tWinMain(HINSTANCE hInstance,
-                     HINSTANCE hPrevInstance,
-                     LPTSTR    lpCmdLine,
-                     int       nCmdShow)
-{
-	UNREFERENCED_PARAMETER(hPrevInstance);
-	UNREFERENCED_PARAMETER(lpCmdLine);
-
-    hInst = hInstance;
-
-    // Get the temporary directory name
-    char tmpBuff[1000];
-    GetTempPathA(1000,tmpBuff);
-    string tmpDir(tmpBuff);
-    string newVersionFN(tmpDir+"mantid_version.txt");
-    string msiFN(tmpDir+"Mantid.msi");
-
-    string MantidInstallDir; 
-    int ver_maj, ver_min, ver_build;
-    string guid;
-    string version;
-
-    if (!ReadMantidRegValue("GUID",guid))
-    {
-        // Mantid is not installed
-
-        if (IDYES == MessageBox(0,L"Mantid Installation was not found on this computer.\n\nWhould you like to download and install it?",
-            L"Mantid Launcher",MB_YESNO | MB_ICONQUESTION))
-        {
-            DWORD dwThreadId;// Start progress bar dialog
-            HANDLE hThread = CreateThread( NULL,0,ThreadProc, 0, 0, &dwThreadId );
-
-            try // to download the installer
-            {
-                readFile(L"download.mantidproject.org",L"updates/Mantid.msi",msiFN);
-            }
-            catch(Cancel& c) // if canceled simply stop
-            {
-                return 0;
-            }
-            catch(runtime_error& e)
-            {
-                MessageBox(0,L"Unable to download Mantid installer",L"Mantid Launcher - Error",MB_OK);
-                return 0;
-            }
-
-            string cmd = string("msiexec /i ")+msiFN;
-            Launch(cmd); // launch the installer
-            
-        }
-        return 0;
-    }
-
-    ReadMantidRegValue("InstallDir",MantidInstallDir);
-    ReadMantidRegValue("Version",version);
-    for(size_t i=0;i<version.size();i++)
-        if ( version[i] == '.' ) version[i] = ' ';
-    istringstream istr(version);
-    istr >> ver_maj >> ver_min >> ver_build;
-
-    // If an exception happens skip the updating part quietly and start MantidPlot
-    try
-    {
-        // Download the new version file
-        readFile(L"download.mantidproject.org",L"updates/mantid_version.txt",newVersionFN);
-        int new_ver_maj, new_ver_min, new_ver_build;
-        string new_guid;
-        readVersion(newVersionFN,new_ver_maj, new_ver_min, new_ver_build, new_guid, fileSize);
-
-        // Install new version
-        if (new_ver_build > ver_build &&
-            IDYES == MessageBoxA(NULL,"New Mantid version is ready.\n\nWould you like to install it?","Message",MB_YESNO | MB_ICONQUESTION))
-        {
-            
-            DWORD dwThreadId;            
-            HANDLE hThread = CreateThread( NULL,0,ThreadProc, 0, 0, &dwThreadId );
-
-            readFile(L"download.mantidproject.org",L"updates/Mantid.msi",msiFN);
-
-            string cmd;
-            if (new_guid != guid) cmd = string("msiexec /i ")+msiFN;
-            else
-                cmd = string("msiexec /i ")+msiFN+" REINSTALL=ALL REINSTALLMODE=vomus";
-
-            Launch(cmd);
-             
-            return 0;
-        }
-
-    }
-    catch(...)
-    {
-        // Do nothing
-    }
-
-    // Launch MantidPlot
-    Launch(MantidInstallDir + "bin/MantidPlot.exe");
-
-	return 0;
-}
-
-void readFile(const wchar_t* ws,const wchar_t* fn,const string& lfn)
-{
-  DWORD dwSize = 0;
-  DWORD dwDownloaded = 0;
-  LPSTR pszOutBuffer;
-  BOOL  bResults = FALSE;
-  HINTERNET  hSession = NULL, 
-             hConnect = NULL,
-             hRequest = NULL;
-
-  // Use WinHttpOpen to obtain a session handle.
-  hSession = WinHttpOpen( L"Mantid update",  
-                          WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
-                          WINHTTP_NO_PROXY_NAME, 
-                          WINHTTP_NO_PROXY_BYPASS, 0 );
-
-  WinHttpSetTimeouts(hSession,1000,1000,1000,1000);
-
-  // Specify an HTTP server.
-  if( hSession )
-  {
-      hConnect = WinHttpConnect( hSession, ws, 
-                               INTERNET_DEFAULT_PORT, 0 );
-  }
-
-  // Create an HTTP request handle.
-  if( hConnect )
-  {
-    hRequest = WinHttpOpenRequest( hConnect, L"GET", fn,
-                                   NULL, WINHTTP_NO_REFERER, 
-                                   WINHTTP_DEFAULT_ACCEPT_TYPES, 
-                                   0 );
-  }
-
-  // Send the request.
-  if( hRequest )
-  {
-    bResults = WinHttpSendRequest( hRequest,
-                                   WINHTTP_NO_ADDITIONAL_HEADERS, 0,
-                                   WINHTTP_NO_REQUEST_DATA, 0, 
-                                   0, 0 );
-  }
-
-  // End the request.
-  if( bResults )
-  {
-    bResults = WinHttpReceiveResponse( hRequest, NULL );
-  }
-
-  ofstream ofil(lfn.c_str(),ios_base::binary);
-  if (!ofil) 
-  {
-      throw runtime_error("");
-  }
-  // Keep checking for data until there is nothing left.
-  if( bResults )
-  {
-      // Check that we receiving what we asked for. Status code must be 200
-      DWORD dwStatusCode = 0;
-      DWORD dwSize = sizeof(DWORD);
-      bResults = WinHttpQueryHeaders( hRequest, 
-                                      WINHTTP_QUERY_STATUS_CODE |
-                                      WINHTTP_QUERY_FLAG_NUMBER,
-                                      NULL, 
-                                      &dwStatusCode, 
-                                      &dwSize, 
-                                      NULL );
-      if (dwStatusCode != 200) throw runtime_error("");
-
-    int nDownloaded = 0;
-    do 
-    {
-        if ( cancelDownload ) throw Cancel();
-      // Check for available data.
-      dwSize = 0;
-      if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) )
-        throw runtime_error("");
-
-      // Allocate space for the buffer.
-      pszOutBuffer = new char[dwSize+1];
-      if( !pszOutBuffer )
-      {
-        throw runtime_error("");
-      }
-      else
-      {
-        // Read the data.
-        ZeroMemory( pszOutBuffer, dwSize+1 );
-
-        if( !WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded ) )
-          throw runtime_error("");
-        else
-        {
-            ofil.write(pszOutBuffer,dwDownloaded);
-            nDownloaded += dwDownloaded;
-            if (nDownloaded > fileSize * 10000)
-            {
-                SendMessage(hwndPB, PBM_STEPIT, 0, 0); 
-                nDownloaded = 0;
-            }
-        }
-
-      }
-    } while( dwSize > 0 );
-  }
-
-  // Close any open handles.
-  if( hRequest ) WinHttpCloseHandle( hRequest );
-  if( hConnect ) WinHttpCloseHandle( hConnect );
-  if( hSession ) WinHttpCloseHandle( hSession );
-
-  // Report any errors.
-  if( !bResults )
-    throw runtime_error("");
-
-}
-
-// Read version and product GUID from local file
-void readVersion(const string& fn,int& ver_maj,int& ver_min, int& ver_build, string& guid, int& fSize)
-{
-    ifstream fil(fn.c_str());
-    if (!fil) throw runtime_error("");
-    string ver;
-    fil >> ver >> guid >> fSize;
-    for(size_t i=0;i<ver.size();i++)
-        if (ver[i] == '.') ver[i] = ' ';
-    istringstream istr(ver);
-    istr >> ver_maj >> ver_min >> ver_build;
-}
-
-void readFile_tst(const string& url,const string& fn)
-{
-    int n = 0;
-    ifstream ifil(url.c_str(),ios_base::binary);
-    ofstream ofil(fn.c_str(),ios_base::binary);
-    if (!ifil || !ofil) throw runtime_error("");
-    while(!ifil.eof())
-    {
-        if ( cancelDownload ) throw Cancel();
-        char buff[1000];
-        ifil.read(buff,1000);
-        int nread = ifil.gcount();
-        ofil.write(buff,nread);
-        n += nread;
-        if (n > fileSize * 10000)
-        {
-            SendMessage(hwndPB, PBM_STEPIT, 0, 0); 
-            n = 0;
-        }
-    }
-}
-
-void Launch(const string& cmd)
-{
-    char *ccmd = new char[cmd.size()+1];
-    strcpy_s(ccmd,cmd.size()+1,cmd.c_str());
-    STARTUPINFOA si;
-    PROCESS_INFORMATION pi;
-    ZeroMemory(&si,sizeof(STARTUPINFO));
-    si.cb = sizeof(STARTUPINFO);
-    ZeroMemory(&pi,sizeof(PROCESS_INFORMATION));
-    CreateProcessA(NULL,ccmd,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi);
-}
-
-
-BOOL CALLBACK ProgressDialogProc(HWND hwndDlg, 
-                             UINT message, 
-                             WPARAM wParam, 
-                             LPARAM lParam) 
-{ 
-    switch (message) 
-    { 
-    case WM_INITDIALOG:
-        hwndDialog = hwndDlg;
-        hwndPB = GetDlgItem(hwndDlg,IDC_PROGRESS1);
-        SendMessage(hwndPB, PBM_SETRANGE, 0,
-            MAKELPARAM(0, 100)); 
-        SendMessage(hwndPB, PBM_SETSTEP, (WPARAM) 1, 0); 
-        return FALSE;
-    case WM_COMMAND: 
-        switch (LOWORD(wParam)) 
-        { 
-            case IDCANCEL: 
-                cancelDownload = true;
-                EndDialog(hwndDlg, wParam); 
-                return TRUE; 
-        } 
-    } 
-    return FALSE; 
-} 
-
-// Runs the dialog in a separate thread
-DWORD WINAPI ThreadProc(PVOID pParameter)
-{
-    InitCommonControls(); 
-
-    int res  = DialogBox(hInst,MAKEINTRESOURCE(IDD_DIALOG2),0,ProgressDialogProc);
-
-    return (DWORD) res;
-}                  
-    
-// Returns true if HKLM\Software\Mantid exists meaning Mantid is installed
-bool ReadMantidRegValue(const std::string& valueName,std::string& value)
-{
-    const int maxSize = 256;
-    char name[maxSize];
-    DWORD sizeOfName = maxSize;
-    const int maxData = 1000;
-    char data[maxData];
-    DWORD sizeOfData;
-    DWORD type;
-    HKEY hKey = HKEY_LOCAL_MACHINE;
-    LONG ret;
-    char subKey[] = "Software\\Mantid";
-
-    ret = RegOpenKeyExA( hKey, subKey, NULL, KEY_READ ,&hKey);
-
-    if (ret != ERROR_SUCCESS)
-    {
-        return false;
-    }
-
-    DWORD i = 0;
-    while(ret == ERROR_SUCCESS)
-    {
-        sizeOfData = maxData;
-        ret =  RegEnumValueA( hKey, i, name, &sizeOfName,  NULL, &type, (LPBYTE)&data, &sizeOfData );
-        if (ret != ERROR_SUCCESS) return false;
-        if (std::string(name) == valueName) 
-        {
-            value = std::string(data);
-            break;
-        }
-        i++;
-    }
-
-    return true;
-}
+// 
+// MantidLauncher.cpp : Launches MantidPlot if there aren't any updates available.
+//                      If there are new updates MantidLauncher downloads them from http://download.mantidproject.org/updates 
+//                      and installs.
+//
+
+#include "stdafx.h"
+#include "Resource.h"
+#include <windows.h>
+#include <winhttp.h>
+#include <commctrl.h>
+
+#include <iostream>
+#include <fstream>
+#include <sstream>
+#include <vector>
+
+
+using namespace std;
+
+class Cancel:public runtime_error
+{
+public:
+    Cancel():runtime_error(""){}
+};
+
+// Download file from website ws and path fn, so that URI is http://<ws>/<fn> and saves it in local file lfn
+void readFile(const wchar_t* ws,const wchar_t* fn,const string& lfn);
+void readFile_tst(const string& url,const string& fn);
+
+// Read version and product GUID from local file
+void readVersion(const string& fn,int& ver_maj,int& ver_min, int& ver_buid, string& guid, int& fSize);
+
+// Launches application with command line cmd. Returns straight away, not waiting for
+// the application to finish.
+void Launch(const string& cmd);
+
+// Progress dialog function
+BOOL CALLBACK ProgressDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam);
+
+// Starts Progress dialog in a separate thread
+DWORD WINAPI ThreadProc(PVOID pParameter);
+
+// Returns true if HKLM\Software\Mantid exists meaning Mantid is installed
+bool ReadMantidRegValue(const std::string& valueName,std::string& value);
+
+void mess(const string& str)
+{
+    MessageBoxA(0,str.c_str(),"Mantid Laincher",MB_OK);
+}
+
+// Global variables
+HINSTANCE hInst;
+HWND hwndPB;
+HWND hwndDialog;
+int fileSize = 35; // Size of Mantid.msi in MB?
+bool cancelDownload = false;
+
+int APIENTRY _tWinMain(HINSTANCE hInstance,
+                     HINSTANCE hPrevInstance,
+                     LPTSTR    lpCmdLine,
+                     int       nCmdShow)
+{
+	UNREFERENCED_PARAMETER(hPrevInstance);
+	UNREFERENCED_PARAMETER(lpCmdLine);
+
+    hInst = hInstance;
+
+    // Get the temporary directory name
+    char tmpBuff[1000];
+    GetTempPathA(1000,tmpBuff);
+    string tmpDir(tmpBuff);
+    string newVersionFN(tmpDir+"mantid_version.txt");
+    string msiFN(tmpDir+"Mantid.msi");
+
+    string MantidInstallDir; 
+    int ver_maj, ver_min, ver_build;
+    string guid;
+    string version;
+
+    if (!ReadMantidRegValue("GUID",guid))
+    {
+        // Mantid is not installed
+
+        if (IDYES == MessageBox(0,L"Mantid Installation was not found on this computer.\n\nWhould you like to download and install it?",
+            L"Mantid Launcher",MB_YESNO | MB_ICONQUESTION))
+        {
+            DWORD dwThreadId;// Start progress bar dialog
+            HANDLE hThread = CreateThread( NULL,0,ThreadProc, 0, 0, &dwThreadId );
+
+            try // to download the installer
+            {
+                readFile(L"download.mantidproject.org",L"updates/Mantid.msi",msiFN);
+            }
+            catch(Cancel& c) // if canceled simply stop
+            {
+                return 0;
+            }
+            catch(runtime_error& e)
+            {
+                MessageBox(0,L"Unable to download Mantid installer",L"Mantid Launcher - Error",MB_OK);
+                return 0;
+            }
+
+            string cmd = string("msiexec /i ")+msiFN;
+            Launch(cmd); // launch the installer
+            
+        }
+        return 0;
+    }
+
+    ReadMantidRegValue("InstallDir",MantidInstallDir);
+    ReadMantidRegValue("Version",version);
+    for(size_t i=0;i<version.size();i++)
+        if ( version[i] == '.' ) version[i] = ' ';
+    istringstream istr(version);
+    istr >> ver_maj >> ver_min >> ver_build;
+
+    // If an exception happens skip the updating part quietly and start MantidPlot
+    try
+    {
+        // Download the new version file
+        readFile(L"download.mantidproject.org",L"updates/mantid_version.txt",newVersionFN);
+        int new_ver_maj, new_ver_min, new_ver_build;
+        string new_guid;
+        readVersion(newVersionFN,new_ver_maj, new_ver_min, new_ver_build, new_guid, fileSize);
+
+        // Install new version
+        if (new_ver_build > ver_build &&
+            IDYES == MessageBoxA(NULL,"New Mantid version is ready.\n\nWould you like to install it?","Message",MB_YESNO | MB_ICONQUESTION))
+        {
+            
+            DWORD dwThreadId;            
+            HANDLE hThread = CreateThread( NULL,0,ThreadProc, 0, 0, &dwThreadId );
+
+            readFile(L"download.mantidproject.org",L"updates/Mantid.msi",msiFN);
+
+            string cmd;
+            if (new_guid != guid) cmd = string("msiexec /i ")+msiFN;
+            else
+                cmd = string("msiexec /i ")+msiFN+" REINSTALL=ALL REINSTALLMODE=vomus";
+
+            Launch(cmd);
+             
+            return 0;
+        }
+
+    }
+    catch(...)
+    {
+        // Do nothing
+    }
+
+    // Launch MantidPlot
+    Launch(MantidInstallDir + "bin/MantidPlot.exe");
+
+	return 0;
+}
+
+void readFile(const wchar_t* ws,const wchar_t* fn,const string& lfn)
+{
+  DWORD dwSize = 0;
+  DWORD dwDownloaded = 0;
+  LPSTR pszOutBuffer;
+  BOOL  bResults = FALSE;
+  HINTERNET  hSession = NULL, 
+             hConnect = NULL,
+             hRequest = NULL;
+
+  // Use WinHttpOpen to obtain a session handle.
+  hSession = WinHttpOpen( L"Mantid update",  
+                          WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
+                          WINHTTP_NO_PROXY_NAME, 
+                          WINHTTP_NO_PROXY_BYPASS, 0 );
+
+  WinHttpSetTimeouts(hSession,1000,1000,1000,1000);
+
+  // Specify an HTTP server.
+  if( hSession )
+  {
+      hConnect = WinHttpConnect( hSession, ws, 
+                               INTERNET_DEFAULT_PORT, 0 );
+  }
+
+  // Create an HTTP request handle.
+  if( hConnect )
+  {
+    hRequest = WinHttpOpenRequest( hConnect, L"GET", fn,
+                                   NULL, WINHTTP_NO_REFERER, 
+                                   WINHTTP_DEFAULT_ACCEPT_TYPES, 
+                                   0 );
+  }
+
+  // Send the request.
+  if( hRequest )
+  {
+    bResults = WinHttpSendRequest( hRequest,
+                                   WINHTTP_NO_ADDITIONAL_HEADERS, 0,
+                                   WINHTTP_NO_REQUEST_DATA, 0, 
+                                   0, 0 );
+  }
+
+  // End the request.
+  if( bResults )
+  {
+    bResults = WinHttpReceiveResponse( hRequest, NULL );
+  }
+
+  ofstream ofil(lfn.c_str(),ios_base::binary);
+  if (!ofil) 
+  {
+      throw runtime_error("");
+  }
+  // Keep checking for data until there is nothing left.
+  if( bResults )
+  {
+      // Check that we receiving what we asked for. Status code must be 200
+      DWORD dwStatusCode = 0;
+      DWORD dwSize = sizeof(DWORD);
+      bResults = WinHttpQueryHeaders( hRequest, 
+                                      WINHTTP_QUERY_STATUS_CODE |
+                                      WINHTTP_QUERY_FLAG_NUMBER,
+                                      NULL, 
+                                      &dwStatusCode, 
+                                      &dwSize, 
+                                      NULL );
+      if (dwStatusCode != 200) throw runtime_error("");
+
+    int nDownloaded = 0;
+    do 
+    {
+        if ( cancelDownload ) throw Cancel();
+      // Check for available data.
+      dwSize = 0;
+      if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) )
+        throw runtime_error("");
+
+      // Allocate space for the buffer.
+      pszOutBuffer = new char[dwSize+1];
+      if( !pszOutBuffer )
+      {
+        throw runtime_error("");
+      }
+      else
+      {
+        // Read the data.
+        ZeroMemory( pszOutBuffer, dwSize+1 );
+
+        if( !WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded ) )
+          throw runtime_error("");
+        else
+        {
+            ofil.write(pszOutBuffer,dwDownloaded);
+            nDownloaded += dwDownloaded;
+            if (nDownloaded > fileSize * 10000)
+            {
+                SendMessage(hwndPB, PBM_STEPIT, 0, 0); 
+                nDownloaded = 0;
+            }
+        }
+
+      }
+    } while( dwSize > 0 );
+  }
+
+  // Close any open handles.
+  if( hRequest ) WinHttpCloseHandle( hRequest );
+  if( hConnect ) WinHttpCloseHandle( hConnect );
+  if( hSession ) WinHttpCloseHandle( hSession );
+
+  // Report any errors.
+  if( !bResults )
+    throw runtime_error("");
+
+}
+
+// Read version and product GUID from local file
+void readVersion(const string& fn,int& ver_maj,int& ver_min, int& ver_build, string& guid, int& fSize)
+{
+    ifstream fil(fn.c_str());
+    if (!fil) throw runtime_error("");
+    string ver;
+    fil >> ver >> guid >> fSize;
+    for(size_t i=0;i<ver.size();i++)
+        if (ver[i] == '.') ver[i] = ' ';
+    istringstream istr(ver);
+    istr >> ver_maj >> ver_min >> ver_build;
+}
+
+void readFile_tst(const string& url,const string& fn)
+{
+    int n = 0;
+    ifstream ifil(url.c_str(),ios_base::binary);
+    ofstream ofil(fn.c_str(),ios_base::binary);
+    if (!ifil || !ofil) throw runtime_error("");
+    while(!ifil.eof())
+    {
+        if ( cancelDownload ) throw Cancel();
+        char buff[1000];
+        ifil.read(buff,1000);
+        int nread = ifil.gcount();
+        ofil.write(buff,nread);
+        n += nread;
+        if (n > fileSize * 10000)
+        {
+            SendMessage(hwndPB, PBM_STEPIT, 0, 0); 
+            n = 0;
+        }
+    }
+}
+
+void Launch(const string& cmd)
+{
+    char *ccmd = new char[cmd.size()+1];
+    strcpy_s(ccmd,cmd.size()+1,cmd.c_str());
+    STARTUPINFOA si;
+    PROCESS_INFORMATION pi;
+    ZeroMemory(&si,sizeof(STARTUPINFO));
+    si.cb = sizeof(STARTUPINFO);
+    ZeroMemory(&pi,sizeof(PROCESS_INFORMATION));
+    CreateProcessA(NULL,ccmd,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi);
+}
+
+
+BOOL CALLBACK ProgressDialogProc(HWND hwndDlg, 
+                             UINT message, 
+                             WPARAM wParam, 
+                             LPARAM lParam) 
+{ 
+    switch (message) 
+    { 
+    case WM_INITDIALOG:
+        hwndDialog = hwndDlg;
+        hwndPB = GetDlgItem(hwndDlg,IDC_PROGRESS1);
+        SendMessage(hwndPB, PBM_SETRANGE, 0,
+            MAKELPARAM(0, 100)); 
+        SendMessage(hwndPB, PBM_SETSTEP, (WPARAM) 1, 0); 
+        return FALSE;
+    case WM_COMMAND: 
+        switch (LOWORD(wParam)) 
+        { 
+            case IDCANCEL: 
+                cancelDownload = true;
+                EndDialog(hwndDlg, wParam); 
+                return TRUE; 
+        } 
+    } 
+    return FALSE; 
+} 
+
+// Runs the dialog in a separate thread
+DWORD WINAPI ThreadProc(PVOID pParameter)
+{
+    InitCommonControls(); 
+
+    int res  = DialogBox(hInst,MAKEINTRESOURCE(IDD_DIALOG2),0,ProgressDialogProc);
+
+    return (DWORD) res;
+}                  
+    
+// Returns true if HKLM\Software\Mantid exists meaning Mantid is installed
+bool ReadMantidRegValue(const std::string& valueName,std::string& value)
+{
+    const int maxSize = 256;
+    char name[maxSize];
+    DWORD sizeOfName = maxSize;
+    const int maxData = 1000;
+    char data[maxData];
+    DWORD sizeOfData;
+    DWORD type;
+    HKEY hKey = HKEY_LOCAL_MACHINE;
+    LONG ret;
+    char subKey[] = "Software\\Mantid";
+
+    ret = RegOpenKeyExA( hKey, subKey, NULL, KEY_READ ,&hKey);
+
+    if (ret != ERROR_SUCCESS)
+    {
+        return false;
+    }
+
+    DWORD i = 0;
+    while(ret == ERROR_SUCCESS)
+    {
+        sizeOfData = maxData;
+        ret =  RegEnumValueA( hKey, i, name, &sizeOfName,  NULL, &type, (LPBYTE)&data, &sizeOfData );
+        if (ret != ERROR_SUCCESS) return false;
+        if (std::string(name) == valueName) 
+        {
+            value = std::string(data);
+            break;
+        }
+        i++;
+    }
+
+    return true;
+}
diff --git a/Code/Mantid/Installers/WinInstaller/MantidLauncher/Resource.h b/Code/Mantid/Installers/WinInstaller/MantidLauncher/Resource.h
index e2b0b8e4aefbb94cfb199ca556669494d3eac3e9..b0b8efd54b66d37c6adf758d537374098186d8be 100644
--- a/Code/Mantid/Installers/WinInstaller/MantidLauncher/Resource.h
+++ b/Code/Mantid/Installers/WinInstaller/MantidLauncher/Resource.h
@@ -1,22 +1,22 @@
-//{{NO_DEPENDENCIES}}
-// Microsoft Visual C++ generated include file.
-// Used by MantidLauncher.rc
-//
-#define IDD_MANTIDLAUNCHER_DIALOG       102
-#define IDM_ABOUT                       104
-#define IDR_MAINFRAME                   128
-#define IDD_DIALOG2                     129
-#define IDC_PROGRESS1                   1003
-#define IDC_STATIC                      -1
-
-// Next default values for new objects
-// 
-#ifdef APSTUDIO_INVOKED
-#ifndef APSTUDIO_READONLY_SYMBOLS
-#define _APS_NO_MFC                     1
-#define _APS_NEXT_RESOURCE_VALUE        130
-#define _APS_NEXT_COMMAND_VALUE         32771
-#define _APS_NEXT_CONTROL_VALUE         1004
-#define _APS_NEXT_SYMED_VALUE           110
-#endif
-#endif
+//{{NO_DEPENDENCIES}}
+// Microsoft Visual C++ generated include file.
+// Used by MantidLauncher.rc
+//
+#define IDD_MANTIDLAUNCHER_DIALOG       102
+#define IDM_ABOUT                       104
+#define IDR_MAINFRAME                   128
+#define IDD_DIALOG2                     129
+#define IDC_PROGRESS1                   1003
+#define IDC_STATIC                      -1
+
+// Next default values for new objects
+// 
+#ifdef APSTUDIO_INVOKED
+#ifndef APSTUDIO_READONLY_SYMBOLS
+#define _APS_NO_MFC                     1
+#define _APS_NEXT_RESOURCE_VALUE        130
+#define _APS_NEXT_COMMAND_VALUE         32771
+#define _APS_NEXT_CONTROL_VALUE         1004
+#define _APS_NEXT_SYMED_VALUE           110
+#endif
+#endif
diff --git a/Code/Mantid/Installers/WinInstaller/MantidLauncher/stdafx.cpp b/Code/Mantid/Installers/WinInstaller/MantidLauncher/stdafx.cpp
index b3747a945d83539059f22473e49b5dcef93981e8..adf9656bbcd22b2db6d4d148468d4eddd7c554b1 100644
--- a/Code/Mantid/Installers/WinInstaller/MantidLauncher/stdafx.cpp
+++ b/Code/Mantid/Installers/WinInstaller/MantidLauncher/stdafx.cpp
@@ -1,8 +1,8 @@
-// stdafx.cpp : source file that includes just the standard includes
-// MantidLauncher.pch will be the pre-compiled header
-// stdafx.obj will contain the pre-compiled type information
-
-#include "stdafx.h"
-
-// TODO: reference any additional headers you need in STDAFX.H
-// and not in this file
+// stdafx.cpp : source file that includes just the standard includes
+// MantidLauncher.pch will be the pre-compiled header
+// stdafx.obj will contain the pre-compiled type information
+
+#include "stdafx.h"
+
+// TODO: reference any additional headers you need in STDAFX.H
+// and not in this file
diff --git a/Code/Mantid/Installers/WinInstaller/MantidLauncher/stdafx.h b/Code/Mantid/Installers/WinInstaller/MantidLauncher/stdafx.h
index 5df7bbe137022b38f5a8b13d4f1bbff36a1ce5e0..63b7c8ffed18d618918357775db5ee9e523de6e2 100644
--- a/Code/Mantid/Installers/WinInstaller/MantidLauncher/stdafx.h
+++ b/Code/Mantid/Installers/WinInstaller/MantidLauncher/stdafx.h
@@ -1,37 +1,37 @@
-// stdafx.h : include file for standard system include files,
-// or project specific include files that are used frequently, but
-// are changed infrequently
-//
-
-#pragma once
-
-// Modify the following defines if you have to target a platform prior to the ones specified below.
-// Refer to MSDN for the latest info on corresponding values for different platforms.
-#ifndef WINVER				// Allow use of features specific to Windows XP or later.
-#define WINVER 0x0501		// Change this to the appropriate value to target other versions of Windows.
-#endif
-
-#ifndef _WIN32_WINNT		// Allow use of features specific to Windows XP or later.                   
-#define _WIN32_WINNT 0x0501	// Change this to the appropriate value to target other versions of Windows.
-#endif						
-
-#ifndef _WIN32_WINDOWS		// Allow use of features specific to Windows 98 or later.
-#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
-#endif
-
-#ifndef _WIN32_IE			// Allow use of features specific to IE 6.0 or later.
-#define _WIN32_IE 0x0600	// Change this to the appropriate value to target other versions of IE.
-#endif
-
-#define WIN32_LEAN_AND_MEAN		// Exclude rarely-used stuff from Windows headers
-// Windows Header Files:
-#include <windows.h>
-
-// C RunTime Header Files
-#include <stdlib.h>
-#include <malloc.h>
-#include <memory.h>
-#include <tchar.h>
-
-
-// TODO: reference additional headers your program requires here
+// stdafx.h : include file for standard system include files,
+// or project specific include files that are used frequently, but
+// are changed infrequently
+//
+
+#pragma once
+
+// Modify the following defines if you have to target a platform prior to the ones specified below.
+// Refer to MSDN for the latest info on corresponding values for different platforms.
+#ifndef WINVER				// Allow use of features specific to Windows XP or later.
+#define WINVER 0x0501		// Change this to the appropriate value to target other versions of Windows.
+#endif
+
+#ifndef _WIN32_WINNT		// Allow use of features specific to Windows XP or later.                   
+#define _WIN32_WINNT 0x0501	// Change this to the appropriate value to target other versions of Windows.
+#endif						
+
+#ifndef _WIN32_WINDOWS		// Allow use of features specific to Windows 98 or later.
+#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
+#endif
+
+#ifndef _WIN32_IE			// Allow use of features specific to IE 6.0 or later.
+#define _WIN32_IE 0x0600	// Change this to the appropriate value to target other versions of IE.
+#endif
+
+#define WIN32_LEAN_AND_MEAN		// Exclude rarely-used stuff from Windows headers
+// Windows Header Files:
+#include <windows.h>
+
+// C RunTime Header Files
+#include <stdlib.h>
+#include <malloc.h>
+#include <memory.h>
+#include <tchar.h>
+
+
+// TODO: reference additional headers your program requires here
diff --git a/Code/Mantid/Installers/WinInstaller/generateWxs.py b/Code/Mantid/Installers/WinInstaller/generateWxs.py
index 4a82e24550e426d0a3d2c70bdae26c835912b5ce..f0a2850f3ff569f955c63b818235c068e106de88 100644
--- a/Code/Mantid/Installers/WinInstaller/generateWxs.py
+++ b/Code/Mantid/Installers/WinInstaller/generateWxs.py
@@ -1,779 +1,779 @@
-# Automatic creation of installer source file (.wxs)
-import os
-import xml
-import xml.dom.minidom
-import msilib
-import md5
-import uuid
-import string
-import platform
-# Use the release_date module in MantidPlot
-import sys
-sys.path.append('../../MantidPlot')
-import release_date
-
-QTDIR = 'c:/qt' #hardcoded to c:/qt location - this is true for build servers and most developers
-QTLIBDIR = QTDIR + '/lib'
-QTPLUGINDIR = QTDIR + '/plugins'
-PYTHONDIR = sys.prefix.replace('\\','/')
-SIPDIR = PYTHONDIR + '/Lib/site-packages'
-PYQTDIR = SIPDIR + '/PyQt4'
-USERALGORITHMSDIR = '../../Framework/UserAlgorithms'
-MANTIDRELEASE = '../../Framework/release/'
-
-MantidVersion = release_date.getMantidPlotVersion()
-print('Mantid version '+ MantidVersion)
-
-# Architecture
-if platform.architecture()[0] == '64bit':
-    ARCH = '64'
-    toget = 'toget64'
-    upgrade_uuid = '{ae4bb5c4-6b5f-4703-be9a-b5ce662b81ce}'
-else:
-    ARCH = '32'
-    toget = 'toget'
-    upgrade_uuid = '{E9B6F1A9-8CB7-4441-B783-4E7A921B37F0}'
-    
-
-# To perform a major upgrade, i.e. uninstall the old version if an old one exists, 
-# the product and package GUIDs need to change everytime
-product_uuid = '{' + str(uuid.uuid1()) + '}'
-package_uuid = '{' + str(uuid.uuid1()) + '}'
-
-# Setup a GUID lookup table for each of the components
-# These are different for each architecture to ensure removal of the correct one when uninstalling
-comp_guid = {}
-if ARCH == '32':
-    comp_guid['MantidDLLs'] = '{FABC0481-C18D-415e-A0B1-CCB76C35FBE8}'
-    comp_guid['QTIPlot'] = '{03ABDE5C-9084-4ebd-9CF8-31648BEFDEB7}'
-    comp_guid['Plugins'] = '{EEF0B4C9-DE52-4f99-A8D0-9D3C3941FA73}'
-    comp_guid['Documents'] = '{C16B2B59-17C8-4cc9-8A7F-16254EB8B2F4}'
-    comp_guid['Logs'] = '{0918C9A4-3481-4f21-B941-983BE21F9674}'
-    comp_guid['IncludeMantidAlgorithms'] = '{EDB85D81-1CED-459a-BF87-E148CEE6F9F6}'
-    comp_guid['IncludeMantidAPI'] = '{4761DDF6-813C-4470-8852-98CB9A69EBC9}'    
-    comp_guid['IncludeMantidCurveFitting'] = '{44d0bdf5-e13a-4a27-8609-e273965ee860}'
-    comp_guid['IncludeMantidDataHandling'] = '{DDD2DD4A-9A6A-4181-AF66-891B99DF8FFE}'
-    comp_guid['IncludeMantidDataObjects'] = '{06445843-7E74-4457-B02E-4850B4911438}'
-    comp_guid['IncludeMantidKernel'] = '{AF40472B-5822-4ff6-8E05-B4DA5224AA87}'
-    comp_guid['IncludeMantidNexus'] = '{BAC18721-6DF1-4870-82FD-2FB37260AE35}'
-    comp_guid['IncludeMantidPythonAPI'] = '{052A15D4-97A0-4ce5-A872-E6871485E734}'
-    comp_guid['Temp'] = '{02D25B60-A114-4f2a-A211-DE88CF648C61}'
-    comp_guid['Data'] = '{6D9A0A53-42D5-46a5-8E88-6BB4FB7A5FE1}'
-    comp_guid['UserAlgorithms'] = '{A82B4540-3CDB-45fa-A7B3-42F392378D3F}'
-    comp_guid['Sip'] = '{A051F48C-CA96-4cd5-B936-D446CBF67588}'
-    comp_guid['Colormaps'] = '{902DBDE3-42AE-49d3-819D-1C83C18D280A}'
-    comp_guid['QtImagePlugins'] = '{6e3c6f03-5933-40b1-9733-1bd71132404c}'
-    comp_guid['MantidQtPlugins'] = '{d035e5aa-2815-4869-836d-8fc4b8e7a418}'
-else:
-    comp_guid['MantidDLLs'] = '{c9748bae-5934-44ab-b144-420589db1623}'
-    comp_guid['QTIPlot'] = '{bfe90c00-9f39-4fde-8dbc-17f419210e12}'
-    comp_guid['Plugins'] = '{8ef1c4db-c54d-4bb1-8b66-a9421db24faf}'
-    comp_guid['Documents'] = '{bb774537-d0c6-4541-93f2-7aa5f5132d21}'
-    comp_guid['Logs'] = '{0cdce87e-976a-40a5-a3d5-73dd8bce9e2e}'
-    comp_guid['IncludeMantidAlgorithms'] = '{e21ee699-be01-419c-8e9a-2678c4da1e6a}'
-    comp_guid['IncludeMantidAPI'] = '{878ff1f2-7d09-4817-972b-3590c45ea0c9}'    
-    comp_guid['IncludeMantidCurveFitting'] = '{a766e379-deb0-4ca3-8578-0036f4722b0a}'
-    comp_guid['IncludeMantidDataHandling'] = '{c937a21a-8fb9-4111-9886-d59d705e2fd8}'
-    comp_guid['IncludeMantidDataObjects'] = '{955f31fd-ac47-475c-911b-55d0cd006fa0}'
-    comp_guid['IncludeMantidKernel'] = '{187317c0-cc23-4a21-bf19-0e347866620c}'
-    comp_guid['IncludeMantidNexus'] = '{7c60491a-36b2-402e-b989-5b8f13667cee}'
-    comp_guid['IncludeMantidPythonAPI'] = '{71c4df47-5564-49ca-8c7c-5ed4d8ceb1e1}'
-    comp_guid['Temp'] = '{212cc3fe-95fb-40d9-a3a7-8421791ac19f}'
-    comp_guid['Data'] = '{c9577b5b-75e5-4a4a-b2d5-f4905174627c}'
-    comp_guid['UserAlgorithms'] = '{496555f0-f719-4db7-bd8e-5bbcd9fe837d}'
-    comp_guid['Sip'] = '{e057fcf0-47ba-4a32-a1af-d6c70e1ff8e4}'
-    comp_guid['Colormaps'] = '{9e4a6fc4-39ea-4b8f-ba49-265d6dcfbb4c}'
-    comp_guid['QtImagePlugins'] = '{7c1ec169-d331-4b9c-b0e4-3214bcf2cbf4}'
-    comp_guid['MantidQtPlugins'] = '{22fa661e-17d5-4e33-8f2c-654c473268c3}'
-    
-MantidInstallDir = 'MantidInstall'
-
-pfile = open('mantid_version.txt','w')
-pfile.write(MantidVersion+'\n')
-pfile.write(product_uuid)
-pfile.close()
-
-globalFileCount = 0
-
-# Adds directory longName to parent.
-# parent is a python variable (not string) representing an xml element
-# Id, name, and longName are strings
-def addDirectory(Id,name,longName,parent):
-    e = doc.createElement('Directory')
-    e.setAttribute('Id',Id)
-    e.setAttribute('Name',name)
-    if name != longName:
-        e.setAttribute('LongName',longName)
-    parent.appendChild(e)
-    return e
-
-def addFile(Id,name,longName,source,vital,parent):
-    e = doc.createElement('File')
-    e.setAttribute('Id',Id)
-    e.setAttribute('Name',name)
-    e.setAttribute('LongName',longName)
-    e.setAttribute('DiskId','1')
-    e.setAttribute('Source',source)
-    e.setAttribute('Vital',vital)
-    parent.appendChild(e)
-    return e
-
-def addFileV(Id,name,longName,source,parent):
-    return addFile(Id,name,longName,source,'yes',parent)
-
-def addFileN(Id,name,longName,source,parent):
-    return addFile(Id,name,longName,source,'no',parent)
-
-def addComponent(Id,guid,parent):
-    e = doc.createElement('Component')
-    e.setAttribute('Id',Id)
-    e.setAttribute('Guid',guid)
-    if ARCH == '64':
-        e.setAttribute('Win64','yes')
-    parent.appendChild(e)
-    return e
-
-# adds all dlls from location to parent.
-# rules are applied to exclude debug libraries
-# name is a short name to which a number will be added
-def addDlls(location,name,parent, exclude_files = []):
-    #print 'Include dlls from',os.path.abspath(location);
-    sdlls = os.listdir(location);
-    i = 0
-    for fil in sdlls:
-        if fil in exclude_files:
-            continue
-        lst = fil.split('.')
-        l = len(lst)
-        if l < 2 or lst[l-1] != 'dll':
-            continue
-        del lst[l-1]
-        fn0 = string.join(lst,'_')
-        fn = fn0.replace('-','_')
-        if not ((fil.find('-gd-') >= 0) or (fil.find('-gyd-') >= 0) or
-                (fil.find('d.dll')>=0 and fil.replace('d.dll','.dll') in sdlls) or
-                (fil.find('d4.dll')>=0 and fil.replace('d4.dll','4.dll') in sdlls) or
-                (fil.find('_d.dll')>=0 and fil.replace('_d.dll','.dll') in sdlls)):
-            #print fil
-            addFileV(fn+'DLL',name+str(i),fil,location+'/'+fil,parent)
-        i += 1
-
-def addAllFiles(location,name,parent):
-    #print 'Include files from',os.path.abspath(location);
-    sfiles = os.listdir(location);
-    i = 0
-    for fil in sfiles:
-        #print fil
-        fn = fil.replace('-','_')
-        fn = fn.replace('+','_')
-        fn = fn.replace(' ','_')
-        if (fil.find('.svn') < 0 and os.path.isfile(location+'/'+fil)):
-            addFileV(name+'_'+fn+'_file',name+str(i),fil,location+'/'+fil,parent)
-            i += 1
-
-def addAllFilesExt(location,name,ext,parent):
-    #print 'Include files from',os.path.abspath(location);
-    sfiles = os.listdir(location);
-    i = 0
-    for fil in sfiles:
-        fn = fil.replace('-','_')
-        fn = fn.replace('+','_')
-        if (fil.find('.svn') < 0 and fil.endswith('.'+ext) > 0):
-            #print fil
-            addFileV(name+'_'+fn+'_file',name+str(i),fil,location+'/'+fil,parent)
-            i += 1
-
-def addSingleFile(location,fil,name,parent):
-    #print 'Include single file'
-    location = os.path.abspath(location);
-    fn = name.replace('-','_')
-    fn = fn.replace('+','_')
-    addFileV(fn+'_file',name,fil,location+'/'+fil,parent)
-
-def addFeature(Id,title,description,level,parent,absent='allow',allowAdvertise='yes'):
-    e = doc.createElement('Feature')
-    e.setAttribute('Id',Id)
-    e.setAttribute('Title',title)
-    e.setAttribute('Description',description)
-    e.setAttribute('Level',level)
-    e.setAttribute('Absent',absent)
-    e.setAttribute('AllowAdvertise',allowAdvertise)
-    parent.appendChild(e)
-    return e
-
-def addHiddenFeature(Id,parent):
-    e = doc.createElement('Feature')
-    e.setAttribute('Id',Id)
-    e.setAttribute('Level','1')
-    e.setAttribute('Display','hidden')
-    e.setAttribute('Absent','allow')
-    e.setAttribute('AllowAdvertise','no')
-    parent.appendChild(e)
-    return e
-
-def addRootFeature(Id,title,description,level,parent):
-    e = doc.createElement('Feature')
-    e.setAttribute('Id',Id)
-    e.setAttribute('Title',title)
-    e.setAttribute('Description',description)
-    e.setAttribute('Level',level)
-    e.setAttribute('Display','expand')
-    e.setAttribute('ConfigurableDirectory','INSTALLDIR')
-    parent.appendChild(e)
-    return e
-
-def addCRef(Id,parent):
-    e = doc.createElement('ComponentRef')
-    e.setAttribute('Id',Id)
-    parent.appendChild(e)
-
-# adds to parent an element tag with dictionary of attributes attr
-def addTo(parent,tag,attr):
-    e = doc.createElement(tag)
-    for name,value in attr.iteritems():
-        e.setAttribute(name,value)
-    parent.appendChild(e)
-    return e
-
-def fileSearch(Id,name,parent):
-    p = addTo(parent,'Property',{'Id':Id})
-    e = addTo(p,'FileSearch',{'Id':Id+'_search','LongName':name})
-    return e
-    
-def addText(text,parent):
-    e = doc.createTextNode(text)
-    parent.appendChild(e)
-    return e
-
-# Copies files in nested folders from location to parent directory
-# Returns a list of component names to be used in addCRefs
-def addCompList(Id,location,name,parent, include_suffix=[],exclude_suffix=[]):
-    global globalFileCount
-    directory = addDirectory(Id+'_dir','dir',name,parent)
-    lst = []
-    idir = 0
-#    ifil = 0
-    if ARCH == '32':
-        m = md5.new(location)
-    else:
-        m = md5.new(location + ARCH)
-    u = m.hexdigest()
-    uuid = '{'+u[0:8]+'-'+u[8:12]+'-'+u[12:16]+'-'+u[16:20]+'-'+u[20:]+'}'
-    comp = addComponent(Id,uuid,directory)
-    lst.append(Id)
-    files = os.listdir(location)
-    for fil in files:
-        if (fil.find('.svn') < 0 and fil.find('UNIT_TESTING') < 0):
-            if ( os.path.isdir(location+'/'+fil) ):
-                idir += 1
-                lst = lst + addCompList(Id+'_'+str(idir), location+'/'+fil, fil, directory)[0]
-            else:
-                keep = False
-                if len(include_suffix) > 0: 
-                    for sfx in include_suffix:
-                        if fil.endswith(sfx):
-                            keep = True
-                            break
-                else:
-                    keep = True
-                if len(exclude_suffix) > 0: 
-                    for sfx in exclude_suffix:
-                        if fil.endswith(sfx):
-                            keep = False
-                            break
-                if keep == False:
-                    continue
-                globalFileCount += 1
-                ifil = globalFileCount
-                fn = fil.replace(' ','_')
-                fn = fil.replace('-','_')
-                fn = fn.replace('+','_')
-                fileId = 'd'+fn+'_file'+str(ifil)
-                fileName = 'file'+str(ifil)
-                fileLongName = fil
-                addFileV(fileId,fileName,fileLongName,location+'/'+fil,comp)
-    return lst,comp
-		
-def addCRefs(lstId,parent):
-    for Id in lstId:
-        e = doc.createElement('ComponentRef')
-        e.setAttribute('Id',Id)
-        parent.appendChild(e)
- 
-def createPropertiesFile(filename):
-    # Field replacements
-    replacements = {
-    "plugins.directory":"plugins.directory = ../plugins",
-    "mantidqt.plugins.directory" : "mantidqt.plugins.directory = ../plugins/qtplugins/mantid",
-    "instrumentDefinition.directory":"instrumentDefinition.directory = ../instrument",
-    "parameterDefinition.directory":"parameterDefinition.directory = ../instrument",    
-    "requiredpythonscript.directories":"""requiredpythonscript.directories = ../scripts/Crystallography;../scripts/Disordered Materials;../scripts/Engineering;\\
-../scripts/Inelastic;../scripts/Large Scale Structures;../scripts/Molecular Spectroscopy;\\
-../scripts/Muons;../scripts/Neutrinos;../scripts/SANS;../scripts/""",
-    "pythonscripts.directory":"pythonscripts.directory = ../scripts",
-    "mantidqt.python_interfaces_directory":"mantidqt.python_interfaces_directory = ../scripts",
-    "pythonscripts.directories":"pythonscripts.directories = ../scripts",
-    "pythonalgorithms.directories":"pythonalgorithms.directories=../plugins/PythonAlgs",
-    "icatDownload.directory":"icatDownload.directory = ../data"
-    }
-
-    template = open(filename,'r')
-    original = template.readlines()
-    prop_file = open('Mantid.properties','w')
-    continuation = False
-    nlines = len(original)
-    index = 0
-    while( index < nlines ):
-        line = original[index]
-        key = ""
-        for rep in replacements.iterkeys():
-            if line.startswith(rep):
-                key = rep
-                break
-        if key != "":
-            prop_file.write(replacements[key] + "\n")
-            # Skip any backslashed lines
-            while line.rstrip().endswith("\\") and index < nlines:
-                index += 1
-                line = original[index]
-        else:
-            prop_file.write(line)
-        index += 1
-    
-    template.close()
-    prop_file.close()
-
-    
-doc = xml.dom.minidom.Document()
-#doc.encoding('Windows-1252')
-wix = doc.createElement('Wix')
-wix.setAttribute('xmlns','http://schemas.microsoft.com/wix/2003/01/wi')
-doc.appendChild(wix)
-
-Product = doc.createElement('Product')
-Product.setAttribute('Id',product_uuid)
-Product.setAttribute('Codepage','1252')
-Product.setAttribute('UpgradeCode',upgrade_uuid)
-Product.setAttribute('Version',MantidVersion)
-Product.setAttribute('Manufacturer','STFC Rutherford Appleton Laboratories')
-Product.setAttribute('Language','1033')
-wix.appendChild(Product)
-
-Package = doc.createElement('Package')
-Package.setAttribute('Id',package_uuid)
-Package.setAttribute('Keywords','Installer')
-Package.setAttribute('Description','Mantid Installer')
-#Package.setAttribute('Comments','')
-Package.setAttribute('Manufacturer','STFC Rutherford Appleton Laboratories')
-Package.setAttribute('Languages','1033')
-Package.setAttribute('Compressed','yes')
-Package.setAttribute('SummaryCodepage','1252')
-Product.appendChild(Package)
-
-# Architecture specific stuff
-if ARCH == '64':
-    Product.setAttribute('Name','Mantid ' + MantidVersion + ' (64-bit)')
-    Package.setAttribute('InstallerVersion','200')
-    Package.setAttribute('Platforms','x64')
-else:
-    Product.setAttribute('Name','Mantid ' + MantidVersion)
-    Package.setAttribute('InstallerVersion','100')
-    Package.setAttribute('Platforms','Intel')
-
-Upgrade = addTo(Product,'Upgrade',{'Id':upgrade_uuid})
-addTo(Upgrade,'UpgradeVersion',{'OnlyDetect':'no','Property':'PREVIOUSFOUND','Minimum': '1.0.0','IncludeMinimum':'yes','Maximum':MantidVersion,'IncludeMaximum':'no'})
-addTo(Upgrade,'UpgradeVersion',{'OnlyDetect':'yes','Property':'NEWERFOUND','Minimum':MantidVersion,'IncludeMinimum':'no'})
-
-addTo(Product,'CustomAction',{'Id':'NoDowngrade','Error':'A later version of [ProductName] is already installed.'})
-
-exeSec = addTo(Product,'InstallExecuteSequence',{})
-NoDowngrade = addTo(exeSec,'Custom',{'Action':'NoDowngrade','After':'FindRelatedProducts'})
-addText('NEWERFOUND',NoDowngrade)
-addTo(exeSec,'RemoveExistingProducts',{'After':'InstallInitialize'})
-
-Media = doc.createElement('Media')
-Media.setAttribute('Id','1')
-Media.setAttribute('Cabinet','Mantid.cab')
-Media.setAttribute('EmbedCab','yes')
-Media.setAttribute('DiskPrompt','CD-ROM #1')
-Product.appendChild(Media)
-
-Prop = doc.createElement('Property')
-Prop.setAttribute('Id','DiskPrompt')
-Prop.setAttribute('Value','Mantid Installation')
-Product.appendChild(Prop)
-
-# Python versioning
-py_dir_prop = 'PYTHONINSTALL'
-py_reg_key = 'Software\\Python\\PythonCore\\%d.%d\\InstallPath' % (sys.version_info.major,sys.version_info.minor)
-PyProp = addTo(Product,'Property',{'Id':py_dir_prop})
-py_lookup = {'Id':'PythonRegistry1','Type':'raw','Root':'HKLM','Key':py_reg_key}
-if ARCH == '64':
-    py_lookup['Win64'] = 'yes'
-# All user search
-addTo(PyProp,'RegistrySearch',py_lookup)
-# Current user search
-py_lookup['Id'] = 'PythonRegistry2'
-py_lookup['Root'] = 'HKCU'
-addTo(PyProp,'RegistrySearch',py_lookup)
-
-# Add a condition element that halts installtion if Python is not installed. Note: If the condition evaluates to false, the dialog pops up.
-Cond = doc.createElement('Condition')
-error_msg = 'Unable to find {0}-bit version of Python {1}.{2}, cannot continue. Please download and install a {0}-bit '\
-            'version from http://www.python.org/download/releases/{1}.{2}.{3}/'.format(ARCH, sys.version_info.major,sys.version_info.minor,sys.version_info.micro)
-Cond.setAttribute('Message', error_msg)
-# Installed is set to TRUE byt the MSI if the product is *already* installed, i.e. the check only gets run on installation and not removal
-Cond.appendChild(doc.createTextNode('Installed OR PYTHONINSTALL'))
-Product.appendChild(Cond)
-
-TargetDir = addDirectory('TARGETDIR','SourceDir','SourceDir',Product)
-InstallDir = addDirectory('INSTALLDIR','MInstall',MantidInstallDir,TargetDir)
-binDir = addDirectory('MantidBin','bin','bin',InstallDir)
-
-MantidDlls = addComponent('MantidDLLs',comp_guid['MantidDLLs'],binDir)
-addTo(MantidDlls,'Registry',{'Id':'RegInstallDir','Root':'HKLM','Key':'Software\Mantid','Name':'InstallDir','Action':'write','Type':'string','Value':'[INSTALLDIR]'})
-addTo(MantidDlls,'Registry',{'Id':'RegMantidVersion','Root':'HKLM','Key':'Software\Mantid','Name':'Version','Action':'write','Type':'string','Value':MantidVersion})
-addTo(MantidDlls,'Registry',{'Id':'RegMantidGUID','Root':'HKLM','Key':'Software\Mantid','Name':'GUID','Action':'write','Type':'string','Value':product_uuid})
-
-# Need to create Mantid.properties file. A template exists but some entries point to the incorrect locations so those need modifying
-createPropertiesFile('../../Framework/Properties/Mantid.properties')
-addFileV('MantidProperties','Mantid.pro','Mantid.properties','Mantid.properties',MantidDlls)
-
-MantidScript = addFileV('MantidScript','MScr.bat','MantidScript.bat','../../Framework/PythonAPI/MantidScript.bat',MantidDlls)
-addTo(MantidScript,'Shortcut',{'Id':'startmenuMantidScript','Directory':'ProgramMenuDir','Name':'Script','LongName':'Mantid Script','WorkingDirectory':'MantidBin'})
-addFileV('MantidStartup','MStart.py','MantidStartup.py','../../Framework/PythonAPI/MantidStartup.py',MantidDlls)
-addFileV('MantidPythonAPI_pyd','MPAPI.pyd','MantidPythonAPI.pyd',MANTIDRELEASE + 'MantidPythonAPI.pyd',MantidDlls)
-addFileV('MantidAPI','MAPI.dll','MantidAPI.dll',MANTIDRELEASE + 'MantidAPI.dll',MantidDlls)
-addFileV('MantidGeometry','MGeo.dll','MantidGeometry.dll',MANTIDRELEASE + 'MantidGeometry.dll',MantidDlls)
-addFileV('MantidKernel','MKern.dll','MantidKernel.dll',MANTIDRELEASE + 'MantidKernel.dll',MantidDlls)
-
-# Add qt API  library
-addFileV('MantidQtAPI','MQTAPI.dll','MantidQtAPI.dll',MANTIDRELEASE + 'MantidQtAPI.dll',MantidDlls)
-addFileV('MantidWidgets','MWid.dll','MantidWidgets.dll',MANTIDRELEASE + 'MantidWidgets.dll',MantidDlls)
-
-# Add Qt Property Browser
-addFileV('QtPropertyBrowser','QTPB.dll','QtPropertyBrowser.dll',MANTIDRELEASE + 'QtPropertyBrowser.dll',MantidDlls)
-
-# NeXus dlls for the main path
-addDlls('../../../Third_Party/lib/win' + ARCH,'3dDll',MantidDlls,['hd425m.dll','hdf5dll.dll','hm425m.dll','libNeXus-0.dll'])
-
-#------------- Environment settings ---------------------- 
-addTo(MantidDlls,'Environment',{'Id':'UpdatePath','Name':'PATH','Action':'set','Part':'last','Value':'[PYTHONINSTALL]'})
-# MantidPATH to point to the bin directory
-mantidbin = '[INSTALLDIR]\\bin'
-addTo(MantidDlls,'Environment',{'Id':'SetMtdPath','Name':'MANTIDPATH','Action':'set','Part':'all','Value':mantidbin})
-# Also add binary directory to the path
-addTo(MantidDlls,'Environment',{'Id':'AddMtdPath','Name':'PATH','Action':'set','Part':'last','Value':'%MANTIDPATH%'})
-
-# ---------------------- Matlab bindings -------------------------
-# Only on 32bit windows for the moment
-if ARCH == '32':
-    addFileV('MantidMatlabAPI','MMAPI.dll','MantidMatlabAPI.dll',MANTIDRELEASE + 'MantidMatlabAPI.dll',MantidDlls)
-    Matlab=addCompList('MatlabMFiles','../../Framework/MatlabAPI/mfiles','Matlab',binDir)[0]
-
-    #Add mantid_setup file
-    setupfile = open('mantid_setup.m','w')
-    setupfile.write('mantid=\'./\';\n')
-    setupfile.write('addpath(strcat(mantid,\'Matlab\'),strcat(mantid,\'Matlab/MantidGlobal\'));\n')
-    setupfile.write('MantidMatlabAPI(\'SimpleAPI\',\'Create\',\'Matlab\');\n')
-    setupfile.write('addpath(strcat(mantid,\'Matlab/MantidSimpleAPI\'));\n')
-    setupfile.close()
-    addFileV('Matlabsetup','mtd_set','mantid_setup.m','mantid_setup.m',MantidDlls)
-else:
-    Matlab = []
-#---------------------------------------------------------------
-
-QTIPlot = addComponent('QTIPlot',comp_guid['QTIPlot'],binDir)
-addDlls(QTLIBDIR,'qt',QTIPlot)
-QTIPlotEXE = addFileV('QTIPlotEXE','MPlot.exe','MantidPlot.exe',MANTIDRELEASE + 'MantidPlot.exe',QTIPlot)
-# TODO: Currently the MantidLauncher only works for the 32-bit system since the registry access seems more of a pain on a 64 bit system
-if ARCH== '32':
-    MantidLauncher = addFileV('MantidLauncher','SMPlot.exe','StartMantidPlot.exe','MantidLauncher/Release/MantidLauncher.exe',QTIPlot)
-    startmenuQTIPlot = addTo(MantidLauncher,'Shortcut',{'Id':'startmenuQTIPlot','Directory':'ProgramMenuDir','Name':'MPlot','LongName':'MantidPlot','WorkingDirectory':'MantidBin','Icon':'MantidPlot.exe'})
-    desktopQTIPlot = addTo(MantidLauncher,'Shortcut',{'Id':'desktopQTIPlot','Directory':'DesktopFolder','Name':'MPlot','LongName':'MantidPlot','WorkingDirectory':'MantidBin','Icon':'MantidPlot.exe','IconIndex':'0'})
-else:
-    startmenuQTIPlot = addTo(QTIPlotEXE,'Shortcut',{'Id':'startmenuQTIPlot','Directory':'ProgramMenuDir','Name':'MPlot','LongName':'MantidPlot','WorkingDirectory':'MantidBin','Icon':'MantidPlot.exe'})
-    desktopQTIPlot = addTo(QTIPlotEXE,'Shortcut',{'Id':'desktopQTIPlot','Directory':'DesktopFolder','Name':'MPlot','LongName':'MantidPlot','WorkingDirectory':'MantidBin','Icon':'MantidPlot.exe','IconIndex':'0'})
-    
-addFileV('qtiplotrc', 'qtirc.py', 'qtiplotrc.py', '../../MantidPlot/qtiplotrc.py', MantidDlls)
-addFileV('qtiplotutil', 'qtiUtil.py', 'qtiUtil.py', '../../MantidPlot/qtiUtil.py', MantidDlls)
-addFileV('mantidplotrc', 'mtdrc.py', 'mantidplotrc.py', '../../MantidPlot/mantidplotrc.py', MantidDlls)
-addFileV('mantidplot', 'mtdplot.py', 'mantidplot.py', '../../MantidPlot/mantidplot.py', MantidDlls)
-
-# Remove files that may have been created
-files_to_remove = ['qtiplotrc.pyc','qtiUtil.pyc','mantidplotrc.pyc','mantidplot.pyc','MantidFramework.pyc','MantidHeader.pyc',\
-                   'mantidsimple.py', 'mantidsimple.pyc','mtdpyalgorithm_keywords.txt']
-for index, name in enumerate(files_to_remove):
-    addTo(MantidDlls,'RemoveFile',{'Id':'RemFile_' + str(index),'On':'uninstall','LongName': name, 'Name':name[:8]})
-
-if (QTLIBDIR == 'C:/Qt/4_4_0/bin'): 	 
-	     manifestFile = addFileV('qtiplot_manifest','qtiexe.man','MantidPlot.exe.manifest',MANTIDRELEASE + 'MantidPlot.exe.manifest',QTIPlot)
-
-addTo(MantidDlls,'RemoveFile',{'Id':'LogFile','On':'uninstall','Name':'mantid.log'})
-addTo(Product,'Icon',{'Id':'MantidPlot.exe','SourceFile':MANTIDRELEASE + 'MantidPlot.exe'})
-
-#plugins
-pluginsDir = addDirectory('PluginsDir','plugins','plugins',InstallDir)
-Plugins = addComponent('Plugins',comp_guid['Plugins'],pluginsDir)
-addFileV('MantidAlgorithms','MAlg.dll','MantidAlgorithms.dll',MANTIDRELEASE + 'MantidAlgorithms.dll',Plugins)
-addFileV('MantidDataHandling','MDH.dll','MantidDataHandling.dll',MANTIDRELEASE + 'MantidDataHandling.dll',Plugins)
-addFileV('MantidDataObjects','MDO.dll','MantidDataObjects.dll',MANTIDRELEASE + 'MantidDataObjects.dll',Plugins)
-addFileV('MantidCurveFitting','MCF.dll','MantidCurveFitting.dll',MANTIDRELEASE + 'MantidCurveFitting.dll',Plugins)
-addFileV('MantidICat','MIC.dll','MantidICat.dll',MANTIDRELEASE + 'MantidICat.dll',Plugins)
-addFileV('MantidNexus','MNex.dll','MantidNexus.dll',MANTIDRELEASE + 'MantidNexus.dll',Plugins)
-# NeXus dlls for the plugins path
-addFileV('hdf5dlldll','hdf5dll.dll','hdf5dll.dll','../../../Third_Party/lib/win' + ARCH + '/hdf5dll.dll',Plugins)
-addFileV('hd425mdll','hd425m.dll','hd425m.dll','../../../Third_Party/lib/win' + ARCH + '/hd425m.dll',Plugins)
-addFileV('hm425mdll','hm425m.dll','hm425m.dll','../../../Third_Party/lib/win'+ ARCH +'/hm425m.dll',Plugins)
-addFileV('libNeXus0dll','lNeXus-0.dll','libNeXus-0.dll','../../../Third_Party/lib/win' + ARCH + '/libNeXus-0.dll',Plugins)
-
-# Python algorithms
-pyalgsList = addCompList("PyAlgsDir","../../Framework/PythonAPI/PythonAlgorithms","PythonAlgs",pluginsDir,exclude_suffix=['.pyc'])[0]
-
-##
-# Qt plugins
-#
-# Qt requires several image plugins to be able to load icons such as gif, jpeg and these need to live in
-# a directory QTPLUGINSDIR/imageformats
-#
-# We will have the structure
-# --[MantidInstall]/plugins/
-#         --qtplugins
-#               --imageformats/
-#               --MantidQtCustom*.dll
-##
-qtpluginsDir = addDirectory('QtPlugInsDir','qplugdir','qtplugins',pluginsDir)
-qtimageformatsDir = addDirectory('QtImageDllsDir','imgdldir','imageformats',qtpluginsDir)
-qtimagedlls = addComponent('QtImagePlugins',comp_guid['QtImagePlugins'],qtimageformatsDir)
-addDlls(QTPLUGINDIR + '/imageformats', 'imgdll',qtimagedlls)
-
-# Now we need a file in the main Qt library to tell Qt where the plugins are using the qt.conf file
-addSingleFile('./','qt.conf','qtcfile', MantidDlls)
-
-# Qt plugins
-mtdqtdllDir = addDirectory('MantidQtPluginsDir','mqtdir','mantid',qtpluginsDir)
-mtdqtdlls = addComponent('MantidQtPlugins', comp_guid['MantidQtPlugins'], mtdqtdllDir)
-addFileV('MantidQtCustomDialogs','MQTCD.dll','MantidQtCustomDialogs.dll',MANTIDRELEASE + 'MantidQtCustomDialogs.dll',mtdqtdlls)
-addFileV('MantidQtCustomInterfaces','MQTCInt.dll','MantidQtCustomInterfaces.dll',MANTIDRELEASE + 'MantidQtCustomInterfaces.dll',mtdqtdlls)
-
-documentsDir = addDirectory('DocumentsDir','docs','docs',InstallDir)
-Documents = addComponent('Documents',comp_guid['Documents'],documentsDir)
-addTo(Documents,'CreateFolder',{})
-
-logsDir = addDirectory('LogsDir','logs','logs',InstallDir)
-Logs = addComponent('Logs',comp_guid['Logs'],logsDir)
-addTo(Logs,'CreateFolder',{})
-
-#-------------------  Includes  -------------------------------------
-includeDir = addDirectory('IncludeDir','include','include',InstallDir)
-includeMantidAlgorithmsDir = addDirectory('IncludeMantidAlgorithmsDir','MAlgs','MantidAlgorithms',includeDir)
-IncludeMantidAlgorithms = addComponent('IncludeMantidAlgorithms',comp_guid['IncludeMantidAlgorithms'],includeMantidAlgorithmsDir)
-addAllFiles('../../Framework/includes/MantidAlgorithms','alg',IncludeMantidAlgorithms)
-
-includeMantidAPIDir = addDirectory('IncludeMantidAPIDir','MAPI','MantidAPI',includeDir)
-IncludeMantidAPI = addComponent('IncludeMantidAPI',comp_guid['IncludeMantidAPI'],includeMantidAPIDir)
-addAllFiles('../../Framework/includes/MantidAPI','api',IncludeMantidAPI)
-
-includeMantidCurveFittingDir = addDirectory('IncludeMantidCurveFittingDir','MAlgs','MantidCurveFitting',includeDir)
-IncludeMantidCurveFitting = addComponent('IncludeMantidCurveFitting',comp_guid['IncludeMantidCurveFitting'],includeMantidCurveFittingDir)
-addAllFiles('../../Framework/includes/MantidCurveFitting','cur',IncludeMantidCurveFitting)
-
-includeMantidDataHandlingDir = addDirectory('IncludeMantidDataHandlingDir','MDH','MantidDataHandling',includeDir)
-IncludeMantidDataHandling = addComponent('IncludeMantidDataHandling',comp_guid['IncludeMantidDataHandling'],includeMantidDataHandlingDir)
-addAllFiles('../../Framework/includes/MantidDataHandling','dh',IncludeMantidDataHandling)
-
-includeMantidDataObjectsDir = addDirectory('IncludeMantidDataObjectsDir','MDO','MantidDataObjects',includeDir)
-IncludeMantidDataObjects = addComponent('IncludeMantidDataObjects',comp_guid['IncludeMantidDataObjects'],includeMantidDataObjectsDir)
-addAllFiles('../../Framework/includes/MantidDataObjects','do',IncludeMantidDataObjects)
-
-includeMantidGeometryDirList = addCompList('IncludeMantidGeometryDirList','../../Framework/includes/MantidGeometry','MantidGeometry',includeDir)[0]
-
-includeMantidKernelDir = addDirectory('IncludeMantidKernelDir','KER','MantidKernel',includeDir)
-IncludeMantidKernel = addComponent('IncludeMantidKernel',comp_guid['IncludeMantidKernel'],includeMantidKernelDir)
-addAllFiles('../../Framework/includes/MantidKernel','ker',IncludeMantidKernel)
-
-includeMantidNexusDir = addDirectory('IncludeMantidNexusDir','NEX','MantidNexus',includeDir)
-IncludeMantidNexus = addComponent('IncludeMantidNexus',comp_guid['IncludeMantidNexus'],includeMantidNexusDir)
-addAllFiles('../../Framework/includes/MantidNexus','nex',IncludeMantidNexus)
-
-includeMantidPythonAPIDir = addDirectory('IncludeMantidPythonAPIDir','PAPI','MantidPythonAPI',includeDir)
-IncludeMantidPythonAPI = addComponent('IncludeMantidPythonAPI',comp_guid['IncludeMantidPythonAPI'],includeMantidPythonAPIDir)
-addAllFiles('../../Framework/includes/MantidPythonAPI','papi',IncludeMantidPythonAPI)
-
-boostList = addCompList('boost','../../../Third_Party/include/boost','boost',includeDir)[0]
-pocoList = addCompList('poco','../../../Third_Party/include/Poco','Poco',includeDir)[0]
-#-------------------  end of Includes ---------------------------------------
-
-sconsList = addCompList('scons','../../../Third_Party/src/scons-local','scons-local',InstallDir)[0]
-
-ins_def_dir = '../../Instrument'
-ins_suffix = '.xml'
-instrument_ids, instr_comp = addCompList('instrument',ins_def_dir,'instrument',InstallDir, include_suffix=[ins_suffix])
-# At r4214 instrument cache files were moved to be written to managed workspace temp directory
-# so here we'll check if old files exist next to the instrument definitions and remove them
-idf_files = os.listdir(ins_def_dir)
-for index, file in enumerate(idf_files):
-    if not file.endswith(ins_suffix): 
-        continue
-    file = file.rstrip(ins_suffix)
-    file += ".vtp"
-    addTo(instr_comp,'RemoveFile',{'Id':'RmVTP_' + str(index),'On':'both','LongName': file, 'Name':file[:8]})
-
-tempDir = addDirectory('TempDir','temp','temp',InstallDir)
-Temp = addComponent('Temp',comp_guid['Temp'],tempDir)
-addTo(Temp,'CreateFolder',{})
-
-dataDir = addDirectory('DataDir','data','data',InstallDir)
-Data = addComponent('Data',comp_guid['Data'],dataDir)
-addTo(Data,'CreateFolder',{})
-
-#-------------------  Source  ------------------------------------------
-#sourceDir = addDirectory('SourceDir','source','source',InstallDir)
-
-#sourceMantidAlgorithmsDir = addDirectory('SourceMantidAlgorithmsDir','MAlgs','MantidAlgorithms',sourceDir)
-#SourceMantidAlgorithms = addComponent('SourceMantidAlgorithms','{C96FA514-351A-4e60-AC4F-EF07216BBDC3}',sourceMantidAlgorithmsDir)
-#addAllFilesExt('../../Framework/Algorithms/src','alg','cpp',SourceMantidAlgorithms)
-
-#sourceMantidAPIDir = addDirectory('SourceMantidAPIDir','MAPI','MantidAPI',sourceDir)
-#SourceMantidAPI = addComponent('SourceMantidAPI','{3186462A-E033-4682-B992-DA80BAF457F2}',sourceMantidAPIDir)
-#addAllFilesExt('../../Framework/API/src','api','cpp',SourceMantidAPI)
-
-# sourceMantidDataHandlingDir = addDirectory('SourceMantidDataHandlingDir','Mdh','MantidDataHandling',sourceDir)
-# SourceMantidDataHandling = addComponent('SourceMantidDataHandling','{3DE8C8E7-86F1-457f-8933-149AD79EA9D7}',sourceMantidDataHandlingDir)
-# addAllFilesExt('../../Framework/DataHandling/src','dh','cpp',SourceMantidDataHandling)
-
-# sourceMantidDataObjectsDir = addDirectory('SourceMantidDataObjectsDir','Mdo','MantidDataObjects',sourceDir)
-# SourceMantidDataObjects = addComponent('SourceMantidDataObjects','{0C071065-8E0C-4e9c-996E-454692803E7F}',sourceMantidDataObjectsDir)
-# addAllFilesExt('../../Framework/DataObjects/src','dh','cpp',SourceMantidDataObjects)
-
-# sourceMantidGeometryDir = addDirectory('SourceMantidGeometryDir','MGeo','MantidGeometry',sourceDir)
-# SourceMantidGeometry = addComponent('SourceMantidGeometry','{949C5B12-7D4B-4a8a-B132-718F6AEA9E69}',sourceMantidGeometryDir)
-# addAllFilesExt('../../Framework/Geometry/src','geo','cpp',SourceMantidGeometry)
-
-# sourceMantidKernelDir = addDirectory('SourceMantidKernelDir','MKer','MantidKernel',sourceDir)
-# SourceMantidKernel = addComponent('SourceMantidKernel','{B7126F68-544C-4e50-9438-E0D6F6155D82}',sourceMantidKernelDir)
-# addAllFilesExt('../../Framework/Kernel/src','ker','cpp',SourceMantidKernel)
-
-# sourceMantidNexusDir = addDirectory('SourceMantidNexusDir','MNex','MantidNexus',sourceDir)
-# SourceMantidNexus = addComponent('SourceMantidNexus','{35AABB59-CDE3-49bf-9F96-7A1AFB72FD2F}',sourceMantidNexusDir)
-# addAllFilesExt('../../Framework/Nexus/src','nex','cpp',SourceMantidNexus)
-
-# sourceMantidPythonAPIDir = addDirectory('SourceMantidPythonAPIDir','MPAPI','MantidPythonAPI',sourceDir)
-# SourceMantidPythonAPI = addComponent('SourceMantidPythonAPI','{CACED707-92D7-47b9-8ABC-378275D99082}',sourceMantidPythonAPIDir)
-# addAllFilesExt('../../Framework/PythonAPI/src','papi','cpp',SourceMantidPythonAPI)
-
-#----------------- end of Source ---------------------------------------
-
-#----------------- User Algorithms -------------------------------------
-UserAlgorithmsDir = addDirectory('UserAlgorithmsDir','UAlgs','UserAlgorithms',InstallDir)
-UserAlgorithms = addComponent('UserAlgorithms',comp_guid['UserAlgorithms'],UserAlgorithmsDir)
-#all cpp, h and three specific files
-addAllFilesExt(USERALGORITHMSDIR,'ualg','cpp',UserAlgorithms)
-addAllFilesExt(USERALGORITHMSDIR,'ualg','h',UserAlgorithms)
-addSingleFile(USERALGORITHMSDIR,'build.bat','UA_build.bat',UserAlgorithms)
-addSingleFile(USERALGORITHMSDIR,'createAlg.py','UA_ca.py',UserAlgorithms)
-addSingleFile(USERALGORITHMSDIR,'SConstruct','UA_Scon',UserAlgorithms)
-addFileV('MantidKernel_lib','MKernel.lib','MantidKernel.lib','../../Framework/Kernel/lib/MantidKernel.lib',UserAlgorithms)
-addFileV('MantidAPI_lib','MAPI.lib','MantidAPI.lib','../../Framework/API/lib/MantidAPI.lib',UserAlgorithms)
-addFileV('MantidDataObjects_lib','MDObject.lib','MantidDataObjects.lib','../../Framework/DataObjects/lib/MantidDataObjects.lib',UserAlgorithms)
-addFileV('MantidGeometry_lib','MGeo.lib','MantidGeometry.lib','../../Framework/Geometry/lib/MantidGeometry.lib',UserAlgorithms)
-addFileV('MantidCurveFitting_lib','MFit.lib','MantidCurveFitting.lib','../../Framework/CurveFitting/lib/MantidCurveFitting.lib',UserAlgorithms)
-addFileV('poco_foundation_lib','poco_f.lib','PocoFoundation.lib','../../../Third_Party/lib/win' + ARCH + '/PocoFoundation.lib',UserAlgorithms)
-addFileV('boost_date_time_lib','boost_dt.lib','boost_date_time-vc100-mt-1_43.lib','../../../Third_Party/lib/win' + ARCH + '/boost_date_time-vc100-mt-1_43.lib',UserAlgorithms)
-
-#--------------- Python ---------------------------------------------------------------------------------
-Sip = addComponent('Sip',comp_guid['Sip'],binDir)
-addSingleFile(SIPDIR,'sip.pyd','sip',Sip)
-PyQtList = addCompList('PyQtDir', PYQTDIR,'PyQt4',binDir, exclude_suffix=['_d.pyd','.pyc'])[0]
-addFileV('MtdFramework_py', 'MFWork.py', 'MantidFramework.py', '../../Framework/PythonAPI/MantidFramework.py', MantidDlls)
-
-#-------------------------- Scripts directory and all sub-directories ------------------------------------
-scriptsList = addCompList("ScriptsDir","../../Scripts","scripts",InstallDir)[0]
-
-# M. Gigg 2010-11-19: The Excitations directory was renamed. Unfortunately this causes the directory for the new installer to get left around
-# on certain setups that have used the scripts.  I could force a delete of the folder but if a user has added their own scripts then that would remove them too.
-# Here we just remove the pyc files so should be left with an empty directory
-# TODO: Put in a custom command to remove it if it is empty after install. This sounds simply but alas is not...
-addTo(exeSec,'Custom',{'Action':'cleanup','After':'InstallInitialize'})
-addTo(Product,'Property',{'Id':'QtExecCmdLine','Value':'"[SystemFolder]\\cmd.exe" /c del /q "[INSTALLDIR]\\scripts\\Excitations\\*.pyc"'})
-addTo(Product,'CustomAction',{'Id':'cleanup','BinaryKey':'WixCA','DllEntry':'CAQuietExec','Impersonate':'yes', 'Return':'ignore'})
-addTo(Product, 'Binary', {'Id':'wixca', 'src':'wixca.dll'})
-
-#-----------------------------------------------------------------------
-
-#-------------------------- Colormaps ------------------------------------
-ColormapsDir = addDirectory('ColormapsDir','colors','colormaps',InstallDir)
-Colormaps = addComponent('Colormaps',comp_guid['Colormaps'],ColormapsDir)
-addAllFiles('../colormaps','col',Colormaps)
-#-----------------------------------------------------------------------
-
-ProgramMenuFolder = addDirectory('ProgramMenuFolder','PMenu','Programs',TargetDir)
-ProgramMenuDir = addDirectory('ProgramMenuDir','Mantid','Mantid',ProgramMenuFolder)
-
-DesktopFolder = addDirectory('DesktopFolder','Desktop','Desktop',TargetDir)
-
-#-----------------------------------------------------------------------
-
-Complete = addRootFeature('Complete','Mantid','The complete package','1',Product)
-MantidExec = addFeature('MantidExecAndDlls','Mantid binaries','The main executable.','1',Complete)
-addCRef('MantidDLLs',MantidExec)
-addCRef('Plugins',MantidExec)
-addCRef('UserAlgorithms',MantidExec)
-addCRef('Documents',MantidExec)
-addCRef('Logs',MantidExec)
-addCRefs(scriptsList,MantidExec)
-addCRef('Colormaps',MantidExec)
-addCRef('Temp',MantidExec)
-addCRef('Data',MantidExec)
-addCRefs(Matlab,MantidExec)
-addCRefs(instrument_ids,MantidExec)
-addCRefs(sconsList,MantidExec)
-addCRef('Sip',MantidExec)
-addCRefs(PyQtList,MantidExec)
-addCRefs(pyalgsList,MantidExec)
-addCRef('QtImagePlugins', MantidExec)
-addCRef('MantidQtPlugins', MantidExec)
-
-# C/C++ runtime. The msm files are essentially themseleves installers  and merging them in this manner causes their contents to be installed during the Mantid install
-# procedure. Some dependencies still require the VC80 runtime so include these as well
-Redist = addHiddenFeature('Redist',Complete)
-if ARCH == '32':
-    msm_files = ['Microsoft_VC80_CRT_x86.msm', 'Microsoft_VC80_OpenMP_x86.msm',\
-                 'policy_8_0_Microsoft_VC80_CRT_x86.msm', 'policy_8_0_Microsoft_VC80_OpenMP_x86.msm',\
-                 'Microsoft_VC100_CRT_x86.msm','Microsoft_VC100_OpenMP_x86.msm'\
-                ]
-    msm_dir = r'C:\Program Files\Common Files\Merge Modules'
-else:
-    msm_files = ['Microsoft_VC80_CRT_x86_x64.msm', 'Microsoft_VC80_OpenMP_x86_x64.msm',\
-                 'policy_8_0_Microsoft_VC80_CRT_x86_x64.msm', 'policy_8_0_Microsoft_VC80_OpenMP_x86_x64.msm',\
-                 'Microsoft_VC100_CRT_x64.msm','Microsoft_VC100_OpenMP_x64.msm'\
-                ]
-    msm_dir = r'C:\Program Files (x86)\Common Files\Merge Modules'
-for index, mod in enumerate(msm_files):
-    id = 'VCRed_' + str(index)
-    addTo(TargetDir,'Merge',{'Id':id, 'SourceFile': os.path.join(msm_dir,mod), 'DiskId':'1','Language':'1033'})
-    addTo(Redist,'MergeRef',{'Id':id})
-
-# Header files
-Includes = addFeature('Includes','Includes','Mantid and third party header files.','2',Complete)
-addCRef('IncludeMantidAlgorithms',Includes)
-addCRef('IncludeMantidAPI',Includes)
-addCRef('IncludeMantidCurveFitting',Includes)
-addCRef('IncludeMantidDataHandling',Includes)
-addCRef('IncludeMantidDataObjects',Includes)
-addCRefs(includeMantidGeometryDirList,Includes)
-addCRef('IncludeMantidKernel',Includes)
-addCRef('IncludeMantidNexus',Includes)
-addCRef('IncludeMantidPythonAPI',Includes)
-addCRefs(boostList,Includes)
-addCRefs(pocoList,Includes)
-
-QTIPlotExec = addFeature('QTIPlotExec','MantidPlot','MantidPlot','1',MantidExec)
-addCRef('QTIPlot',QTIPlotExec)
-addTo(Product,'UIRef',{'Id':'WixUI_FeatureTree'})
-addTo(Product,'UIRef',{'Id':'WixUI_ErrorProgressText'})
-
-# Output the file so that the next step in the chain can process it
-f = open('tmp.wxs','w')
-doc.writexml(f,newl="\r\n")
-f.close()
+# Automatic creation of installer source file (.wxs)
+import os
+import xml
+import xml.dom.minidom
+import msilib
+import md5
+import uuid
+import string
+import platform
+# Use the release_date module in MantidPlot
+import sys
+sys.path.append('../../MantidPlot')
+import release_date
+
+QTDIR = 'c:/qt' #hardcoded to c:/qt location - this is true for build servers and most developers
+QTLIBDIR = QTDIR + '/lib'
+QTPLUGINDIR = QTDIR + '/plugins'
+PYTHONDIR = sys.prefix.replace('\\','/')
+SIPDIR = PYTHONDIR + '/Lib/site-packages'
+PYQTDIR = SIPDIR + '/PyQt4'
+USERALGORITHMSDIR = '../../Framework/UserAlgorithms'
+MANTIDRELEASE = '../../Framework/release/'
+
+MantidVersion = release_date.getMantidPlotVersion()
+print('Mantid version '+ MantidVersion)
+
+# Architecture
+if platform.architecture()[0] == '64bit':
+    ARCH = '64'
+    toget = 'toget64'
+    upgrade_uuid = '{ae4bb5c4-6b5f-4703-be9a-b5ce662b81ce}'
+else:
+    ARCH = '32'
+    toget = 'toget'
+    upgrade_uuid = '{E9B6F1A9-8CB7-4441-B783-4E7A921B37F0}'
+    
+
+# To perform a major upgrade, i.e. uninstall the old version if an old one exists, 
+# the product and package GUIDs need to change everytime
+product_uuid = '{' + str(uuid.uuid1()) + '}'
+package_uuid = '{' + str(uuid.uuid1()) + '}'
+
+# Setup a GUID lookup table for each of the components
+# These are different for each architecture to ensure removal of the correct one when uninstalling
+comp_guid = {}
+if ARCH == '32':
+    comp_guid['MantidDLLs'] = '{FABC0481-C18D-415e-A0B1-CCB76C35FBE8}'
+    comp_guid['QTIPlot'] = '{03ABDE5C-9084-4ebd-9CF8-31648BEFDEB7}'
+    comp_guid['Plugins'] = '{EEF0B4C9-DE52-4f99-A8D0-9D3C3941FA73}'
+    comp_guid['Documents'] = '{C16B2B59-17C8-4cc9-8A7F-16254EB8B2F4}'
+    comp_guid['Logs'] = '{0918C9A4-3481-4f21-B941-983BE21F9674}'
+    comp_guid['IncludeMantidAlgorithms'] = '{EDB85D81-1CED-459a-BF87-E148CEE6F9F6}'
+    comp_guid['IncludeMantidAPI'] = '{4761DDF6-813C-4470-8852-98CB9A69EBC9}'    
+    comp_guid['IncludeMantidCurveFitting'] = '{44d0bdf5-e13a-4a27-8609-e273965ee860}'
+    comp_guid['IncludeMantidDataHandling'] = '{DDD2DD4A-9A6A-4181-AF66-891B99DF8FFE}'
+    comp_guid['IncludeMantidDataObjects'] = '{06445843-7E74-4457-B02E-4850B4911438}'
+    comp_guid['IncludeMantidKernel'] = '{AF40472B-5822-4ff6-8E05-B4DA5224AA87}'
+    comp_guid['IncludeMantidNexus'] = '{BAC18721-6DF1-4870-82FD-2FB37260AE35}'
+    comp_guid['IncludeMantidPythonAPI'] = '{052A15D4-97A0-4ce5-A872-E6871485E734}'
+    comp_guid['Temp'] = '{02D25B60-A114-4f2a-A211-DE88CF648C61}'
+    comp_guid['Data'] = '{6D9A0A53-42D5-46a5-8E88-6BB4FB7A5FE1}'
+    comp_guid['UserAlgorithms'] = '{A82B4540-3CDB-45fa-A7B3-42F392378D3F}'
+    comp_guid['Sip'] = '{A051F48C-CA96-4cd5-B936-D446CBF67588}'
+    comp_guid['Colormaps'] = '{902DBDE3-42AE-49d3-819D-1C83C18D280A}'
+    comp_guid['QtImagePlugins'] = '{6e3c6f03-5933-40b1-9733-1bd71132404c}'
+    comp_guid['MantidQtPlugins'] = '{d035e5aa-2815-4869-836d-8fc4b8e7a418}'
+else:
+    comp_guid['MantidDLLs'] = '{c9748bae-5934-44ab-b144-420589db1623}'
+    comp_guid['QTIPlot'] = '{bfe90c00-9f39-4fde-8dbc-17f419210e12}'
+    comp_guid['Plugins'] = '{8ef1c4db-c54d-4bb1-8b66-a9421db24faf}'
+    comp_guid['Documents'] = '{bb774537-d0c6-4541-93f2-7aa5f5132d21}'
+    comp_guid['Logs'] = '{0cdce87e-976a-40a5-a3d5-73dd8bce9e2e}'
+    comp_guid['IncludeMantidAlgorithms'] = '{e21ee699-be01-419c-8e9a-2678c4da1e6a}'
+    comp_guid['IncludeMantidAPI'] = '{878ff1f2-7d09-4817-972b-3590c45ea0c9}'    
+    comp_guid['IncludeMantidCurveFitting'] = '{a766e379-deb0-4ca3-8578-0036f4722b0a}'
+    comp_guid['IncludeMantidDataHandling'] = '{c937a21a-8fb9-4111-9886-d59d705e2fd8}'
+    comp_guid['IncludeMantidDataObjects'] = '{955f31fd-ac47-475c-911b-55d0cd006fa0}'
+    comp_guid['IncludeMantidKernel'] = '{187317c0-cc23-4a21-bf19-0e347866620c}'
+    comp_guid['IncludeMantidNexus'] = '{7c60491a-36b2-402e-b989-5b8f13667cee}'
+    comp_guid['IncludeMantidPythonAPI'] = '{71c4df47-5564-49ca-8c7c-5ed4d8ceb1e1}'
+    comp_guid['Temp'] = '{212cc3fe-95fb-40d9-a3a7-8421791ac19f}'
+    comp_guid['Data'] = '{c9577b5b-75e5-4a4a-b2d5-f4905174627c}'
+    comp_guid['UserAlgorithms'] = '{496555f0-f719-4db7-bd8e-5bbcd9fe837d}'
+    comp_guid['Sip'] = '{e057fcf0-47ba-4a32-a1af-d6c70e1ff8e4}'
+    comp_guid['Colormaps'] = '{9e4a6fc4-39ea-4b8f-ba49-265d6dcfbb4c}'
+    comp_guid['QtImagePlugins'] = '{7c1ec169-d331-4b9c-b0e4-3214bcf2cbf4}'
+    comp_guid['MantidQtPlugins'] = '{22fa661e-17d5-4e33-8f2c-654c473268c3}'
+    
+MantidInstallDir = 'MantidInstall'
+
+pfile = open('mantid_version.txt','w')
+pfile.write(MantidVersion+'\n')
+pfile.write(product_uuid)
+pfile.close()
+
+globalFileCount = 0
+
+# Adds directory longName to parent.
+# parent is a python variable (not string) representing an xml element
+# Id, name, and longName are strings
+def addDirectory(Id,name,longName,parent):
+    e = doc.createElement('Directory')
+    e.setAttribute('Id',Id)
+    e.setAttribute('Name',name)
+    if name != longName:
+        e.setAttribute('LongName',longName)
+    parent.appendChild(e)
+    return e
+
+def addFile(Id,name,longName,source,vital,parent):
+    e = doc.createElement('File')
+    e.setAttribute('Id',Id)
+    e.setAttribute('Name',name)
+    e.setAttribute('LongName',longName)
+    e.setAttribute('DiskId','1')
+    e.setAttribute('Source',source)
+    e.setAttribute('Vital',vital)
+    parent.appendChild(e)
+    return e
+
+def addFileV(Id,name,longName,source,parent):
+    return addFile(Id,name,longName,source,'yes',parent)
+
+def addFileN(Id,name,longName,source,parent):
+    return addFile(Id,name,longName,source,'no',parent)
+
+def addComponent(Id,guid,parent):
+    e = doc.createElement('Component')
+    e.setAttribute('Id',Id)
+    e.setAttribute('Guid',guid)
+    if ARCH == '64':
+        e.setAttribute('Win64','yes')
+    parent.appendChild(e)
+    return e
+
+# adds all dlls from location to parent.
+# rules are applied to exclude debug libraries
+# name is a short name to which a number will be added
+def addDlls(location,name,parent, exclude_files = []):
+    #print 'Include dlls from',os.path.abspath(location);
+    sdlls = os.listdir(location);
+    i = 0
+    for fil in sdlls:
+        if fil in exclude_files:
+            continue
+        lst = fil.split('.')
+        l = len(lst)
+        if l < 2 or lst[l-1] != 'dll':
+            continue
+        del lst[l-1]
+        fn0 = string.join(lst,'_')
+        fn = fn0.replace('-','_')
+        if not ((fil.find('-gd-') >= 0) or (fil.find('-gyd-') >= 0) or
+                (fil.find('d.dll')>=0 and fil.replace('d.dll','.dll') in sdlls) or
+                (fil.find('d4.dll')>=0 and fil.replace('d4.dll','4.dll') in sdlls) or
+                (fil.find('_d.dll')>=0 and fil.replace('_d.dll','.dll') in sdlls)):
+            #print fil
+            addFileV(fn+'DLL',name+str(i),fil,location+'/'+fil,parent)
+        i += 1
+
+def addAllFiles(location,name,parent):
+    #print 'Include files from',os.path.abspath(location);
+    sfiles = os.listdir(location);
+    i = 0
+    for fil in sfiles:
+        #print fil
+        fn = fil.replace('-','_')
+        fn = fn.replace('+','_')
+        fn = fn.replace(' ','_')
+        if (fil.find('.svn') < 0 and os.path.isfile(location+'/'+fil)):
+            addFileV(name+'_'+fn+'_file',name+str(i),fil,location+'/'+fil,parent)
+            i += 1
+
+def addAllFilesExt(location,name,ext,parent):
+    #print 'Include files from',os.path.abspath(location);
+    sfiles = os.listdir(location);
+    i = 0
+    for fil in sfiles:
+        fn = fil.replace('-','_')
+        fn = fn.replace('+','_')
+        if (fil.find('.svn') < 0 and fil.endswith('.'+ext) > 0):
+            #print fil
+            addFileV(name+'_'+fn+'_file',name+str(i),fil,location+'/'+fil,parent)
+            i += 1
+
+def addSingleFile(location,fil,name,parent):
+    #print 'Include single file'
+    location = os.path.abspath(location);
+    fn = name.replace('-','_')
+    fn = fn.replace('+','_')
+    addFileV(fn+'_file',name,fil,location+'/'+fil,parent)
+
+def addFeature(Id,title,description,level,parent,absent='allow',allowAdvertise='yes'):
+    e = doc.createElement('Feature')
+    e.setAttribute('Id',Id)
+    e.setAttribute('Title',title)
+    e.setAttribute('Description',description)
+    e.setAttribute('Level',level)
+    e.setAttribute('Absent',absent)
+    e.setAttribute('AllowAdvertise',allowAdvertise)
+    parent.appendChild(e)
+    return e
+
+def addHiddenFeature(Id,parent):
+    e = doc.createElement('Feature')
+    e.setAttribute('Id',Id)
+    e.setAttribute('Level','1')
+    e.setAttribute('Display','hidden')
+    e.setAttribute('Absent','allow')
+    e.setAttribute('AllowAdvertise','no')
+    parent.appendChild(e)
+    return e
+
+def addRootFeature(Id,title,description,level,parent):
+    e = doc.createElement('Feature')
+    e.setAttribute('Id',Id)
+    e.setAttribute('Title',title)
+    e.setAttribute('Description',description)
+    e.setAttribute('Level',level)
+    e.setAttribute('Display','expand')
+    e.setAttribute('ConfigurableDirectory','INSTALLDIR')
+    parent.appendChild(e)
+    return e
+
+def addCRef(Id,parent):
+    e = doc.createElement('ComponentRef')
+    e.setAttribute('Id',Id)
+    parent.appendChild(e)
+
+# adds to parent an element tag with dictionary of attributes attr
+def addTo(parent,tag,attr):
+    e = doc.createElement(tag)
+    for name,value in attr.iteritems():
+        e.setAttribute(name,value)
+    parent.appendChild(e)
+    return e
+
+def fileSearch(Id,name,parent):
+    p = addTo(parent,'Property',{'Id':Id})
+    e = addTo(p,'FileSearch',{'Id':Id+'_search','LongName':name})
+    return e
+    
+def addText(text,parent):
+    e = doc.createTextNode(text)
+    parent.appendChild(e)
+    return e
+
+# Copies files in nested folders from location to parent directory
+# Returns a list of component names to be used in addCRefs
+def addCompList(Id,location,name,parent, include_suffix=[],exclude_suffix=[]):
+    global globalFileCount
+    directory = addDirectory(Id+'_dir','dir',name,parent)
+    lst = []
+    idir = 0
+#    ifil = 0
+    if ARCH == '32':
+        m = md5.new(location)
+    else:
+        m = md5.new(location + ARCH)
+    u = m.hexdigest()
+    uuid = '{'+u[0:8]+'-'+u[8:12]+'-'+u[12:16]+'-'+u[16:20]+'-'+u[20:]+'}'
+    comp = addComponent(Id,uuid,directory)
+    lst.append(Id)
+    files = os.listdir(location)
+    for fil in files:
+        if (fil.find('.svn') < 0 and fil.find('UNIT_TESTING') < 0):
+            if ( os.path.isdir(location+'/'+fil) ):
+                idir += 1
+                lst = lst + addCompList(Id+'_'+str(idir), location+'/'+fil, fil, directory)[0]
+            else:
+                keep = False
+                if len(include_suffix) > 0: 
+                    for sfx in include_suffix:
+                        if fil.endswith(sfx):
+                            keep = True
+                            break
+                else:
+                    keep = True
+                if len(exclude_suffix) > 0: 
+                    for sfx in exclude_suffix:
+                        if fil.endswith(sfx):
+                            keep = False
+                            break
+                if keep == False:
+                    continue
+                globalFileCount += 1
+                ifil = globalFileCount
+                fn = fil.replace(' ','_')
+                fn = fil.replace('-','_')
+                fn = fn.replace('+','_')
+                fileId = 'd'+fn+'_file'+str(ifil)
+                fileName = 'file'+str(ifil)
+                fileLongName = fil
+                addFileV(fileId,fileName,fileLongName,location+'/'+fil,comp)
+    return lst,comp
+		
+def addCRefs(lstId,parent):
+    for Id in lstId:
+        e = doc.createElement('ComponentRef')
+        e.setAttribute('Id',Id)
+        parent.appendChild(e)
+ 
+def createPropertiesFile(filename):
+    # Field replacements
+    replacements = {
+    "plugins.directory":"plugins.directory = ../plugins",
+    "mantidqt.plugins.directory" : "mantidqt.plugins.directory = ../plugins/qtplugins/mantid",
+    "instrumentDefinition.directory":"instrumentDefinition.directory = ../instrument",
+    "parameterDefinition.directory":"parameterDefinition.directory = ../instrument",    
+    "requiredpythonscript.directories":"""requiredpythonscript.directories = ../scripts/Crystallography;../scripts/Disordered Materials;../scripts/Engineering;\\
+../scripts/Inelastic;../scripts/Large Scale Structures;../scripts/Molecular Spectroscopy;\\
+../scripts/Muons;../scripts/Neutrinos;../scripts/SANS;../scripts/""",
+    "pythonscripts.directory":"pythonscripts.directory = ../scripts",
+    "mantidqt.python_interfaces_directory":"mantidqt.python_interfaces_directory = ../scripts",
+    "pythonscripts.directories":"pythonscripts.directories = ../scripts",
+    "pythonalgorithms.directories":"pythonalgorithms.directories=../plugins/PythonAlgs",
+    "icatDownload.directory":"icatDownload.directory = ../data"
+    }
+
+    template = open(filename,'r')
+    original = template.readlines()
+    prop_file = open('Mantid.properties','w')
+    continuation = False
+    nlines = len(original)
+    index = 0
+    while( index < nlines ):
+        line = original[index]
+        key = ""
+        for rep in replacements.iterkeys():
+            if line.startswith(rep):
+                key = rep
+                break
+        if key != "":
+            prop_file.write(replacements[key] + "\n")
+            # Skip any backslashed lines
+            while line.rstrip().endswith("\\") and index < nlines:
+                index += 1
+                line = original[index]
+        else:
+            prop_file.write(line)
+        index += 1
+    
+    template.close()
+    prop_file.close()
+
+    
+doc = xml.dom.minidom.Document()
+#doc.encoding('Windows-1252')
+wix = doc.createElement('Wix')
+wix.setAttribute('xmlns','http://schemas.microsoft.com/wix/2003/01/wi')
+doc.appendChild(wix)
+
+Product = doc.createElement('Product')
+Product.setAttribute('Id',product_uuid)
+Product.setAttribute('Codepage','1252')
+Product.setAttribute('UpgradeCode',upgrade_uuid)
+Product.setAttribute('Version',MantidVersion)
+Product.setAttribute('Manufacturer','STFC Rutherford Appleton Laboratories')
+Product.setAttribute('Language','1033')
+wix.appendChild(Product)
+
+Package = doc.createElement('Package')
+Package.setAttribute('Id',package_uuid)
+Package.setAttribute('Keywords','Installer')
+Package.setAttribute('Description','Mantid Installer')
+#Package.setAttribute('Comments','')
+Package.setAttribute('Manufacturer','STFC Rutherford Appleton Laboratories')
+Package.setAttribute('Languages','1033')
+Package.setAttribute('Compressed','yes')
+Package.setAttribute('SummaryCodepage','1252')
+Product.appendChild(Package)
+
+# Architecture specific stuff
+if ARCH == '64':
+    Product.setAttribute('Name','Mantid ' + MantidVersion + ' (64-bit)')
+    Package.setAttribute('InstallerVersion','200')
+    Package.setAttribute('Platforms','x64')
+else:
+    Product.setAttribute('Name','Mantid ' + MantidVersion)
+    Package.setAttribute('InstallerVersion','100')
+    Package.setAttribute('Platforms','Intel')
+
+Upgrade = addTo(Product,'Upgrade',{'Id':upgrade_uuid})
+addTo(Upgrade,'UpgradeVersion',{'OnlyDetect':'no','Property':'PREVIOUSFOUND','Minimum': '1.0.0','IncludeMinimum':'yes','Maximum':MantidVersion,'IncludeMaximum':'no'})
+addTo(Upgrade,'UpgradeVersion',{'OnlyDetect':'yes','Property':'NEWERFOUND','Minimum':MantidVersion,'IncludeMinimum':'no'})
+
+addTo(Product,'CustomAction',{'Id':'NoDowngrade','Error':'A later version of [ProductName] is already installed.'})
+
+exeSec = addTo(Product,'InstallExecuteSequence',{})
+NoDowngrade = addTo(exeSec,'Custom',{'Action':'NoDowngrade','After':'FindRelatedProducts'})
+addText('NEWERFOUND',NoDowngrade)
+addTo(exeSec,'RemoveExistingProducts',{'After':'InstallInitialize'})
+
+Media = doc.createElement('Media')
+Media.setAttribute('Id','1')
+Media.setAttribute('Cabinet','Mantid.cab')
+Media.setAttribute('EmbedCab','yes')
+Media.setAttribute('DiskPrompt','CD-ROM #1')
+Product.appendChild(Media)
+
+Prop = doc.createElement('Property')
+Prop.setAttribute('Id','DiskPrompt')
+Prop.setAttribute('Value','Mantid Installation')
+Product.appendChild(Prop)
+
+# Python versioning
+py_dir_prop = 'PYTHONINSTALL'
+py_reg_key = 'Software\\Python\\PythonCore\\%d.%d\\InstallPath' % (sys.version_info.major,sys.version_info.minor)
+PyProp = addTo(Product,'Property',{'Id':py_dir_prop})
+py_lookup = {'Id':'PythonRegistry1','Type':'raw','Root':'HKLM','Key':py_reg_key}
+if ARCH == '64':
+    py_lookup['Win64'] = 'yes'
+# All user search
+addTo(PyProp,'RegistrySearch',py_lookup)
+# Current user search
+py_lookup['Id'] = 'PythonRegistry2'
+py_lookup['Root'] = 'HKCU'
+addTo(PyProp,'RegistrySearch',py_lookup)
+
+# Add a condition element that halts installtion if Python is not installed. Note: If the condition evaluates to false, the dialog pops up.
+Cond = doc.createElement('Condition')
+error_msg = 'Unable to find {0}-bit version of Python {1}.{2}, cannot continue. Please download and install a {0}-bit '\
+            'version from http://www.python.org/download/releases/{1}.{2}.{3}/'.format(ARCH, sys.version_info.major,sys.version_info.minor,sys.version_info.micro)
+Cond.setAttribute('Message', error_msg)
+# Installed is set to TRUE byt the MSI if the product is *already* installed, i.e. the check only gets run on installation and not removal
+Cond.appendChild(doc.createTextNode('Installed OR PYTHONINSTALL'))
+Product.appendChild(Cond)
+
+TargetDir = addDirectory('TARGETDIR','SourceDir','SourceDir',Product)
+InstallDir = addDirectory('INSTALLDIR','MInstall',MantidInstallDir,TargetDir)
+binDir = addDirectory('MantidBin','bin','bin',InstallDir)
+
+MantidDlls = addComponent('MantidDLLs',comp_guid['MantidDLLs'],binDir)
+addTo(MantidDlls,'Registry',{'Id':'RegInstallDir','Root':'HKLM','Key':'Software\Mantid','Name':'InstallDir','Action':'write','Type':'string','Value':'[INSTALLDIR]'})
+addTo(MantidDlls,'Registry',{'Id':'RegMantidVersion','Root':'HKLM','Key':'Software\Mantid','Name':'Version','Action':'write','Type':'string','Value':MantidVersion})
+addTo(MantidDlls,'Registry',{'Id':'RegMantidGUID','Root':'HKLM','Key':'Software\Mantid','Name':'GUID','Action':'write','Type':'string','Value':product_uuid})
+
+# Need to create Mantid.properties file. A template exists but some entries point to the incorrect locations so those need modifying
+createPropertiesFile('../../Framework/Properties/Mantid.properties')
+addFileV('MantidProperties','Mantid.pro','Mantid.properties','Mantid.properties',MantidDlls)
+
+MantidScript = addFileV('MantidScript','MScr.bat','MantidScript.bat','../../Framework/PythonAPI/MantidScript.bat',MantidDlls)
+addTo(MantidScript,'Shortcut',{'Id':'startmenuMantidScript','Directory':'ProgramMenuDir','Name':'Script','LongName':'Mantid Script','WorkingDirectory':'MantidBin'})
+addFileV('MantidStartup','MStart.py','MantidStartup.py','../../Framework/PythonAPI/MantidStartup.py',MantidDlls)
+addFileV('MantidPythonAPI_pyd','MPAPI.pyd','MantidPythonAPI.pyd',MANTIDRELEASE + 'MantidPythonAPI.pyd',MantidDlls)
+addFileV('MantidAPI','MAPI.dll','MantidAPI.dll',MANTIDRELEASE + 'MantidAPI.dll',MantidDlls)
+addFileV('MantidGeometry','MGeo.dll','MantidGeometry.dll',MANTIDRELEASE + 'MantidGeometry.dll',MantidDlls)
+addFileV('MantidKernel','MKern.dll','MantidKernel.dll',MANTIDRELEASE + 'MantidKernel.dll',MantidDlls)
+
+# Add qt API  library
+addFileV('MantidQtAPI','MQTAPI.dll','MantidQtAPI.dll',MANTIDRELEASE + 'MantidQtAPI.dll',MantidDlls)
+addFileV('MantidWidgets','MWid.dll','MantidWidgets.dll',MANTIDRELEASE + 'MantidWidgets.dll',MantidDlls)
+
+# Add Qt Property Browser
+addFileV('QtPropertyBrowser','QTPB.dll','QtPropertyBrowser.dll',MANTIDRELEASE + 'QtPropertyBrowser.dll',MantidDlls)
+
+# NeXus dlls for the main path
+addDlls('../../../Third_Party/lib/win' + ARCH,'3dDll',MantidDlls,['hd425m.dll','hdf5dll.dll','hm425m.dll','libNeXus-0.dll'])
+
+#------------- Environment settings ---------------------- 
+addTo(MantidDlls,'Environment',{'Id':'UpdatePath','Name':'PATH','Action':'set','Part':'last','Value':'[PYTHONINSTALL]'})
+# MantidPATH to point to the bin directory
+mantidbin = '[INSTALLDIR]\\bin'
+addTo(MantidDlls,'Environment',{'Id':'SetMtdPath','Name':'MANTIDPATH','Action':'set','Part':'all','Value':mantidbin})
+# Also add binary directory to the path
+addTo(MantidDlls,'Environment',{'Id':'AddMtdPath','Name':'PATH','Action':'set','Part':'last','Value':'%MANTIDPATH%'})
+
+# ---------------------- Matlab bindings -------------------------
+# Only on 32bit windows for the moment
+if ARCH == '32':
+    addFileV('MantidMatlabAPI','MMAPI.dll','MantidMatlabAPI.dll',MANTIDRELEASE + 'MantidMatlabAPI.dll',MantidDlls)
+    Matlab=addCompList('MatlabMFiles','../../Framework/MatlabAPI/mfiles','Matlab',binDir)[0]
+
+    #Add mantid_setup file
+    setupfile = open('mantid_setup.m','w')
+    setupfile.write('mantid=\'./\';\n')
+    setupfile.write('addpath(strcat(mantid,\'Matlab\'),strcat(mantid,\'Matlab/MantidGlobal\'));\n')
+    setupfile.write('MantidMatlabAPI(\'SimpleAPI\',\'Create\',\'Matlab\');\n')
+    setupfile.write('addpath(strcat(mantid,\'Matlab/MantidSimpleAPI\'));\n')
+    setupfile.close()
+    addFileV('Matlabsetup','mtd_set','mantid_setup.m','mantid_setup.m',MantidDlls)
+else:
+    Matlab = []
+#---------------------------------------------------------------
+
+QTIPlot = addComponent('QTIPlot',comp_guid['QTIPlot'],binDir)
+addDlls(QTLIBDIR,'qt',QTIPlot)
+QTIPlotEXE = addFileV('QTIPlotEXE','MPlot.exe','MantidPlot.exe',MANTIDRELEASE + 'MantidPlot.exe',QTIPlot)
+# TODO: Currently the MantidLauncher only works for the 32-bit system since the registry access seems more of a pain on a 64 bit system
+if ARCH== '32':
+    MantidLauncher = addFileV('MantidLauncher','SMPlot.exe','StartMantidPlot.exe','MantidLauncher/Release/MantidLauncher.exe',QTIPlot)
+    startmenuQTIPlot = addTo(MantidLauncher,'Shortcut',{'Id':'startmenuQTIPlot','Directory':'ProgramMenuDir','Name':'MPlot','LongName':'MantidPlot','WorkingDirectory':'MantidBin','Icon':'MantidPlot.exe'})
+    desktopQTIPlot = addTo(MantidLauncher,'Shortcut',{'Id':'desktopQTIPlot','Directory':'DesktopFolder','Name':'MPlot','LongName':'MantidPlot','WorkingDirectory':'MantidBin','Icon':'MantidPlot.exe','IconIndex':'0'})
+else:
+    startmenuQTIPlot = addTo(QTIPlotEXE,'Shortcut',{'Id':'startmenuQTIPlot','Directory':'ProgramMenuDir','Name':'MPlot','LongName':'MantidPlot','WorkingDirectory':'MantidBin','Icon':'MantidPlot.exe'})
+    desktopQTIPlot = addTo(QTIPlotEXE,'Shortcut',{'Id':'desktopQTIPlot','Directory':'DesktopFolder','Name':'MPlot','LongName':'MantidPlot','WorkingDirectory':'MantidBin','Icon':'MantidPlot.exe','IconIndex':'0'})
+    
+addFileV('qtiplotrc', 'qtirc.py', 'qtiplotrc.py', '../../MantidPlot/qtiplotrc.py', MantidDlls)
+addFileV('qtiplotutil', 'qtiUtil.py', 'qtiUtil.py', '../../MantidPlot/qtiUtil.py', MantidDlls)
+addFileV('mantidplotrc', 'mtdrc.py', 'mantidplotrc.py', '../../MantidPlot/mantidplotrc.py', MantidDlls)
+addFileV('mantidplot', 'mtdplot.py', 'mantidplot.py', '../../MantidPlot/mantidplot.py', MantidDlls)
+
+# Remove files that may have been created
+files_to_remove = ['qtiplotrc.pyc','qtiUtil.pyc','mantidplotrc.pyc','mantidplot.pyc','MantidFramework.pyc','MantidHeader.pyc',\
+                   'mantidsimple.py', 'mantidsimple.pyc','mtdpyalgorithm_keywords.txt']
+for index, name in enumerate(files_to_remove):
+    addTo(MantidDlls,'RemoveFile',{'Id':'RemFile_' + str(index),'On':'uninstall','LongName': name, 'Name':name[:8]})
+
+if (QTLIBDIR == 'C:/Qt/4_4_0/bin'): 	 
+	     manifestFile = addFileV('qtiplot_manifest','qtiexe.man','MantidPlot.exe.manifest',MANTIDRELEASE + 'MantidPlot.exe.manifest',QTIPlot)
+
+addTo(MantidDlls,'RemoveFile',{'Id':'LogFile','On':'uninstall','Name':'mantid.log'})
+addTo(Product,'Icon',{'Id':'MantidPlot.exe','SourceFile':MANTIDRELEASE + 'MantidPlot.exe'})
+
+#plugins
+pluginsDir = addDirectory('PluginsDir','plugins','plugins',InstallDir)
+Plugins = addComponent('Plugins',comp_guid['Plugins'],pluginsDir)
+addFileV('MantidAlgorithms','MAlg.dll','MantidAlgorithms.dll',MANTIDRELEASE + 'MantidAlgorithms.dll',Plugins)
+addFileV('MantidDataHandling','MDH.dll','MantidDataHandling.dll',MANTIDRELEASE + 'MantidDataHandling.dll',Plugins)
+addFileV('MantidDataObjects','MDO.dll','MantidDataObjects.dll',MANTIDRELEASE + 'MantidDataObjects.dll',Plugins)
+addFileV('MantidCurveFitting','MCF.dll','MantidCurveFitting.dll',MANTIDRELEASE + 'MantidCurveFitting.dll',Plugins)
+addFileV('MantidICat','MIC.dll','MantidICat.dll',MANTIDRELEASE + 'MantidICat.dll',Plugins)
+addFileV('MantidNexus','MNex.dll','MantidNexus.dll',MANTIDRELEASE + 'MantidNexus.dll',Plugins)
+# NeXus dlls for the plugins path
+addFileV('hdf5dlldll','hdf5dll.dll','hdf5dll.dll','../../../Third_Party/lib/win' + ARCH + '/hdf5dll.dll',Plugins)
+addFileV('hd425mdll','hd425m.dll','hd425m.dll','../../../Third_Party/lib/win' + ARCH + '/hd425m.dll',Plugins)
+addFileV('hm425mdll','hm425m.dll','hm425m.dll','../../../Third_Party/lib/win'+ ARCH +'/hm425m.dll',Plugins)
+addFileV('libNeXus0dll','lNeXus-0.dll','libNeXus-0.dll','../../../Third_Party/lib/win' + ARCH + '/libNeXus-0.dll',Plugins)
+
+# Python algorithms
+pyalgsList = addCompList("PyAlgsDir","../../Framework/PythonAPI/PythonAlgorithms","PythonAlgs",pluginsDir,exclude_suffix=['.pyc'])[0]
+
+##
+# Qt plugins
+#
+# Qt requires several image plugins to be able to load icons such as gif, jpeg and these need to live in
+# a directory QTPLUGINSDIR/imageformats
+#
+# We will have the structure
+# --[MantidInstall]/plugins/
+#         --qtplugins
+#               --imageformats/
+#               --MantidQtCustom*.dll
+##
+qtpluginsDir = addDirectory('QtPlugInsDir','qplugdir','qtplugins',pluginsDir)
+qtimageformatsDir = addDirectory('QtImageDllsDir','imgdldir','imageformats',qtpluginsDir)
+qtimagedlls = addComponent('QtImagePlugins',comp_guid['QtImagePlugins'],qtimageformatsDir)
+addDlls(QTPLUGINDIR + '/imageformats', 'imgdll',qtimagedlls)
+
+# Now we need a file in the main Qt library to tell Qt where the plugins are using the qt.conf file
+addSingleFile('./','qt.conf','qtcfile', MantidDlls)
+
+# Qt plugins
+mtdqtdllDir = addDirectory('MantidQtPluginsDir','mqtdir','mantid',qtpluginsDir)
+mtdqtdlls = addComponent('MantidQtPlugins', comp_guid['MantidQtPlugins'], mtdqtdllDir)
+addFileV('MantidQtCustomDialogs','MQTCD.dll','MantidQtCustomDialogs.dll',MANTIDRELEASE + 'MantidQtCustomDialogs.dll',mtdqtdlls)
+addFileV('MantidQtCustomInterfaces','MQTCInt.dll','MantidQtCustomInterfaces.dll',MANTIDRELEASE + 'MantidQtCustomInterfaces.dll',mtdqtdlls)
+
+documentsDir = addDirectory('DocumentsDir','docs','docs',InstallDir)
+Documents = addComponent('Documents',comp_guid['Documents'],documentsDir)
+addTo(Documents,'CreateFolder',{})
+
+logsDir = addDirectory('LogsDir','logs','logs',InstallDir)
+Logs = addComponent('Logs',comp_guid['Logs'],logsDir)
+addTo(Logs,'CreateFolder',{})
+
+#-------------------  Includes  -------------------------------------
+includeDir = addDirectory('IncludeDir','include','include',InstallDir)
+includeMantidAlgorithmsDir = addDirectory('IncludeMantidAlgorithmsDir','MAlgs','MantidAlgorithms',includeDir)
+IncludeMantidAlgorithms = addComponent('IncludeMantidAlgorithms',comp_guid['IncludeMantidAlgorithms'],includeMantidAlgorithmsDir)
+addAllFiles('../../Framework/includes/MantidAlgorithms','alg',IncludeMantidAlgorithms)
+
+includeMantidAPIDir = addDirectory('IncludeMantidAPIDir','MAPI','MantidAPI',includeDir)
+IncludeMantidAPI = addComponent('IncludeMantidAPI',comp_guid['IncludeMantidAPI'],includeMantidAPIDir)
+addAllFiles('../../Framework/includes/MantidAPI','api',IncludeMantidAPI)
+
+includeMantidCurveFittingDir = addDirectory('IncludeMantidCurveFittingDir','MAlgs','MantidCurveFitting',includeDir)
+IncludeMantidCurveFitting = addComponent('IncludeMantidCurveFitting',comp_guid['IncludeMantidCurveFitting'],includeMantidCurveFittingDir)
+addAllFiles('../../Framework/includes/MantidCurveFitting','cur',IncludeMantidCurveFitting)
+
+includeMantidDataHandlingDir = addDirectory('IncludeMantidDataHandlingDir','MDH','MantidDataHandling',includeDir)
+IncludeMantidDataHandling = addComponent('IncludeMantidDataHandling',comp_guid['IncludeMantidDataHandling'],includeMantidDataHandlingDir)
+addAllFiles('../../Framework/includes/MantidDataHandling','dh',IncludeMantidDataHandling)
+
+includeMantidDataObjectsDir = addDirectory('IncludeMantidDataObjectsDir','MDO','MantidDataObjects',includeDir)
+IncludeMantidDataObjects = addComponent('IncludeMantidDataObjects',comp_guid['IncludeMantidDataObjects'],includeMantidDataObjectsDir)
+addAllFiles('../../Framework/includes/MantidDataObjects','do',IncludeMantidDataObjects)
+
+includeMantidGeometryDirList = addCompList('IncludeMantidGeometryDirList','../../Framework/includes/MantidGeometry','MantidGeometry',includeDir)[0]
+
+includeMantidKernelDir = addDirectory('IncludeMantidKernelDir','KER','MantidKernel',includeDir)
+IncludeMantidKernel = addComponent('IncludeMantidKernel',comp_guid['IncludeMantidKernel'],includeMantidKernelDir)
+addAllFiles('../../Framework/includes/MantidKernel','ker',IncludeMantidKernel)
+
+includeMantidNexusDir = addDirectory('IncludeMantidNexusDir','NEX','MantidNexus',includeDir)
+IncludeMantidNexus = addComponent('IncludeMantidNexus',comp_guid['IncludeMantidNexus'],includeMantidNexusDir)
+addAllFiles('../../Framework/includes/MantidNexus','nex',IncludeMantidNexus)
+
+includeMantidPythonAPIDir = addDirectory('IncludeMantidPythonAPIDir','PAPI','MantidPythonAPI',includeDir)
+IncludeMantidPythonAPI = addComponent('IncludeMantidPythonAPI',comp_guid['IncludeMantidPythonAPI'],includeMantidPythonAPIDir)
+addAllFiles('../../Framework/includes/MantidPythonAPI','papi',IncludeMantidPythonAPI)
+
+boostList = addCompList('boost','../../../Third_Party/include/boost','boost',includeDir)[0]
+pocoList = addCompList('poco','../../../Third_Party/include/Poco','Poco',includeDir)[0]
+#-------------------  end of Includes ---------------------------------------
+
+sconsList = addCompList('scons','../../../Third_Party/src/scons-local','scons-local',InstallDir)[0]
+
+ins_def_dir = '../../Instrument'
+ins_suffix = '.xml'
+instrument_ids, instr_comp = addCompList('instrument',ins_def_dir,'instrument',InstallDir, include_suffix=[ins_suffix])
+# At r4214 instrument cache files were moved to be written to managed workspace temp directory
+# so here we'll check if old files exist next to the instrument definitions and remove them
+idf_files = os.listdir(ins_def_dir)
+for index, file in enumerate(idf_files):
+    if not file.endswith(ins_suffix): 
+        continue
+    file = file.rstrip(ins_suffix)
+    file += ".vtp"
+    addTo(instr_comp,'RemoveFile',{'Id':'RmVTP_' + str(index),'On':'both','LongName': file, 'Name':file[:8]})
+
+tempDir = addDirectory('TempDir','temp','temp',InstallDir)
+Temp = addComponent('Temp',comp_guid['Temp'],tempDir)
+addTo(Temp,'CreateFolder',{})
+
+dataDir = addDirectory('DataDir','data','data',InstallDir)
+Data = addComponent('Data',comp_guid['Data'],dataDir)
+addTo(Data,'CreateFolder',{})
+
+#-------------------  Source  ------------------------------------------
+#sourceDir = addDirectory('SourceDir','source','source',InstallDir)
+
+#sourceMantidAlgorithmsDir = addDirectory('SourceMantidAlgorithmsDir','MAlgs','MantidAlgorithms',sourceDir)
+#SourceMantidAlgorithms = addComponent('SourceMantidAlgorithms','{C96FA514-351A-4e60-AC4F-EF07216BBDC3}',sourceMantidAlgorithmsDir)
+#addAllFilesExt('../../Framework/Algorithms/src','alg','cpp',SourceMantidAlgorithms)
+
+#sourceMantidAPIDir = addDirectory('SourceMantidAPIDir','MAPI','MantidAPI',sourceDir)
+#SourceMantidAPI = addComponent('SourceMantidAPI','{3186462A-E033-4682-B992-DA80BAF457F2}',sourceMantidAPIDir)
+#addAllFilesExt('../../Framework/API/src','api','cpp',SourceMantidAPI)
+
+# sourceMantidDataHandlingDir = addDirectory('SourceMantidDataHandlingDir','Mdh','MantidDataHandling',sourceDir)
+# SourceMantidDataHandling = addComponent('SourceMantidDataHandling','{3DE8C8E7-86F1-457f-8933-149AD79EA9D7}',sourceMantidDataHandlingDir)
+# addAllFilesExt('../../Framework/DataHandling/src','dh','cpp',SourceMantidDataHandling)
+
+# sourceMantidDataObjectsDir = addDirectory('SourceMantidDataObjectsDir','Mdo','MantidDataObjects',sourceDir)
+# SourceMantidDataObjects = addComponent('SourceMantidDataObjects','{0C071065-8E0C-4e9c-996E-454692803E7F}',sourceMantidDataObjectsDir)
+# addAllFilesExt('../../Framework/DataObjects/src','dh','cpp',SourceMantidDataObjects)
+
+# sourceMantidGeometryDir = addDirectory('SourceMantidGeometryDir','MGeo','MantidGeometry',sourceDir)
+# SourceMantidGeometry = addComponent('SourceMantidGeometry','{949C5B12-7D4B-4a8a-B132-718F6AEA9E69}',sourceMantidGeometryDir)
+# addAllFilesExt('../../Framework/Geometry/src','geo','cpp',SourceMantidGeometry)
+
+# sourceMantidKernelDir = addDirectory('SourceMantidKernelDir','MKer','MantidKernel',sourceDir)
+# SourceMantidKernel = addComponent('SourceMantidKernel','{B7126F68-544C-4e50-9438-E0D6F6155D82}',sourceMantidKernelDir)
+# addAllFilesExt('../../Framework/Kernel/src','ker','cpp',SourceMantidKernel)
+
+# sourceMantidNexusDir = addDirectory('SourceMantidNexusDir','MNex','MantidNexus',sourceDir)
+# SourceMantidNexus = addComponent('SourceMantidNexus','{35AABB59-CDE3-49bf-9F96-7A1AFB72FD2F}',sourceMantidNexusDir)
+# addAllFilesExt('../../Framework/Nexus/src','nex','cpp',SourceMantidNexus)
+
+# sourceMantidPythonAPIDir = addDirectory('SourceMantidPythonAPIDir','MPAPI','MantidPythonAPI',sourceDir)
+# SourceMantidPythonAPI = addComponent('SourceMantidPythonAPI','{CACED707-92D7-47b9-8ABC-378275D99082}',sourceMantidPythonAPIDir)
+# addAllFilesExt('../../Framework/PythonAPI/src','papi','cpp',SourceMantidPythonAPI)
+
+#----------------- end of Source ---------------------------------------
+
+#----------------- User Algorithms -------------------------------------
+UserAlgorithmsDir = addDirectory('UserAlgorithmsDir','UAlgs','UserAlgorithms',InstallDir)
+UserAlgorithms = addComponent('UserAlgorithms',comp_guid['UserAlgorithms'],UserAlgorithmsDir)
+#all cpp, h and three specific files
+addAllFilesExt(USERALGORITHMSDIR,'ualg','cpp',UserAlgorithms)
+addAllFilesExt(USERALGORITHMSDIR,'ualg','h',UserAlgorithms)
+addSingleFile(USERALGORITHMSDIR,'build.bat','UA_build.bat',UserAlgorithms)
+addSingleFile(USERALGORITHMSDIR,'createAlg.py','UA_ca.py',UserAlgorithms)
+addSingleFile(USERALGORITHMSDIR,'SConstruct','UA_Scon',UserAlgorithms)
+addFileV('MantidKernel_lib','MKernel.lib','MantidKernel.lib','../../Framework/Kernel/lib/MantidKernel.lib',UserAlgorithms)
+addFileV('MantidAPI_lib','MAPI.lib','MantidAPI.lib','../../Framework/API/lib/MantidAPI.lib',UserAlgorithms)
+addFileV('MantidDataObjects_lib','MDObject.lib','MantidDataObjects.lib','../../Framework/DataObjects/lib/MantidDataObjects.lib',UserAlgorithms)
+addFileV('MantidGeometry_lib','MGeo.lib','MantidGeometry.lib','../../Framework/Geometry/lib/MantidGeometry.lib',UserAlgorithms)
+addFileV('MantidCurveFitting_lib','MFit.lib','MantidCurveFitting.lib','../../Framework/CurveFitting/lib/MantidCurveFitting.lib',UserAlgorithms)
+addFileV('poco_foundation_lib','poco_f.lib','PocoFoundation.lib','../../../Third_Party/lib/win' + ARCH + '/PocoFoundation.lib',UserAlgorithms)
+addFileV('boost_date_time_lib','boost_dt.lib','boost_date_time-vc100-mt-1_43.lib','../../../Third_Party/lib/win' + ARCH + '/boost_date_time-vc100-mt-1_43.lib',UserAlgorithms)
+
+#--------------- Python ---------------------------------------------------------------------------------
+Sip = addComponent('Sip',comp_guid['Sip'],binDir)
+addSingleFile(SIPDIR,'sip.pyd','sip',Sip)
+PyQtList = addCompList('PyQtDir', PYQTDIR,'PyQt4',binDir, exclude_suffix=['_d.pyd','.pyc'])[0]
+addFileV('MtdFramework_py', 'MFWork.py', 'MantidFramework.py', '../../Framework/PythonAPI/MantidFramework.py', MantidDlls)
+
+#-------------------------- Scripts directory and all sub-directories ------------------------------------
+scriptsList = addCompList("ScriptsDir","../../Scripts","scripts",InstallDir)[0]
+
+# M. Gigg 2010-11-19: The Excitations directory was renamed. Unfortunately this causes the directory for the new installer to get left around
+# on certain setups that have used the scripts.  I could force a delete of the folder but if a user has added their own scripts then that would remove them too.
+# Here we just remove the pyc files so should be left with an empty directory
+# TODO: Put in a custom command to remove it if it is empty after install. This sounds simply but alas is not...
+addTo(exeSec,'Custom',{'Action':'cleanup','After':'InstallInitialize'})
+addTo(Product,'Property',{'Id':'QtExecCmdLine','Value':'"[SystemFolder]\\cmd.exe" /c del /q "[INSTALLDIR]\\scripts\\Excitations\\*.pyc"'})
+addTo(Product,'CustomAction',{'Id':'cleanup','BinaryKey':'WixCA','DllEntry':'CAQuietExec','Impersonate':'yes', 'Return':'ignore'})
+addTo(Product, 'Binary', {'Id':'wixca', 'src':'wixca.dll'})
+
+#-----------------------------------------------------------------------
+
+#-------------------------- Colormaps ------------------------------------
+ColormapsDir = addDirectory('ColormapsDir','colors','colormaps',InstallDir)
+Colormaps = addComponent('Colormaps',comp_guid['Colormaps'],ColormapsDir)
+addAllFiles('../colormaps','col',Colormaps)
+#-----------------------------------------------------------------------
+
+ProgramMenuFolder = addDirectory('ProgramMenuFolder','PMenu','Programs',TargetDir)
+ProgramMenuDir = addDirectory('ProgramMenuDir','Mantid','Mantid',ProgramMenuFolder)
+
+DesktopFolder = addDirectory('DesktopFolder','Desktop','Desktop',TargetDir)
+
+#-----------------------------------------------------------------------
+
+Complete = addRootFeature('Complete','Mantid','The complete package','1',Product)
+MantidExec = addFeature('MantidExecAndDlls','Mantid binaries','The main executable.','1',Complete)
+addCRef('MantidDLLs',MantidExec)
+addCRef('Plugins',MantidExec)
+addCRef('UserAlgorithms',MantidExec)
+addCRef('Documents',MantidExec)
+addCRef('Logs',MantidExec)
+addCRefs(scriptsList,MantidExec)
+addCRef('Colormaps',MantidExec)
+addCRef('Temp',MantidExec)
+addCRef('Data',MantidExec)
+addCRefs(Matlab,MantidExec)
+addCRefs(instrument_ids,MantidExec)
+addCRefs(sconsList,MantidExec)
+addCRef('Sip',MantidExec)
+addCRefs(PyQtList,MantidExec)
+addCRefs(pyalgsList,MantidExec)
+addCRef('QtImagePlugins', MantidExec)
+addCRef('MantidQtPlugins', MantidExec)
+
+# C/C++ runtime. The msm files are essentially themseleves installers  and merging them in this manner causes their contents to be installed during the Mantid install
+# procedure. Some dependencies still require the VC80 runtime so include these as well
+Redist = addHiddenFeature('Redist',Complete)
+if ARCH == '32':
+    msm_files = ['Microsoft_VC80_CRT_x86.msm', 'Microsoft_VC80_OpenMP_x86.msm',\
+                 'policy_8_0_Microsoft_VC80_CRT_x86.msm', 'policy_8_0_Microsoft_VC80_OpenMP_x86.msm',\
+                 'Microsoft_VC100_CRT_x86.msm','Microsoft_VC100_OpenMP_x86.msm'\
+                ]
+    msm_dir = r'C:\Program Files\Common Files\Merge Modules'
+else:
+    msm_files = ['Microsoft_VC80_CRT_x86_x64.msm', 'Microsoft_VC80_OpenMP_x86_x64.msm',\
+                 'policy_8_0_Microsoft_VC80_CRT_x86_x64.msm', 'policy_8_0_Microsoft_VC80_OpenMP_x86_x64.msm',\
+                 'Microsoft_VC100_CRT_x64.msm','Microsoft_VC100_OpenMP_x64.msm'\
+                ]
+    msm_dir = r'C:\Program Files (x86)\Common Files\Merge Modules'
+for index, mod in enumerate(msm_files):
+    id = 'VCRed_' + str(index)
+    addTo(TargetDir,'Merge',{'Id':id, 'SourceFile': os.path.join(msm_dir,mod), 'DiskId':'1','Language':'1033'})
+    addTo(Redist,'MergeRef',{'Id':id})
+
+# Header files
+Includes = addFeature('Includes','Includes','Mantid and third party header files.','2',Complete)
+addCRef('IncludeMantidAlgorithms',Includes)
+addCRef('IncludeMantidAPI',Includes)
+addCRef('IncludeMantidCurveFitting',Includes)
+addCRef('IncludeMantidDataHandling',Includes)
+addCRef('IncludeMantidDataObjects',Includes)
+addCRefs(includeMantidGeometryDirList,Includes)
+addCRef('IncludeMantidKernel',Includes)
+addCRef('IncludeMantidNexus',Includes)
+addCRef('IncludeMantidPythonAPI',Includes)
+addCRefs(boostList,Includes)
+addCRefs(pocoList,Includes)
+
+QTIPlotExec = addFeature('QTIPlotExec','MantidPlot','MantidPlot','1',MantidExec)
+addCRef('QTIPlot',QTIPlotExec)
+addTo(Product,'UIRef',{'Id':'WixUI_FeatureTree'})
+addTo(Product,'UIRef',{'Id':'WixUI_ErrorProgressText'})
+
+# Output the file so that the next step in the chain can process it
+f = open('tmp.wxs','w')
+doc.writexml(f,newl="\r\n")
+f.close()
diff --git a/Code/Mantid/Installers/WinInstaller/msiSize.py b/Code/Mantid/Installers/WinInstaller/msiSize.py
index ce75a742157e7894edac81b2fee78da3f53b9e30..d05816775ddac42680bbb3ab750681679a8da076 100644
--- a/Code/Mantid/Installers/WinInstaller/msiSize.py
+++ b/Code/Mantid/Installers/WinInstaller/msiSize.py
@@ -1,14 +1,14 @@
-# Determines upper limit of Mantid.msi file size in MB
-import os
-import math
-import sys
-
-if len(sys.argv) != 2:
-    exit(1)
-msiname = sys.argv[1]
-
-sz = int(math.ceil(float(os.stat(msiname)[6])/1000000))
-pfile = open('mantid_version.txt','a')
-pfile.write('\n'+str(sz)+'\n')
-pfile.close()
-
+# Determines upper limit of Mantid.msi file size in MB
+import os
+import math
+import sys
+
+if len(sys.argv) != 2:
+    exit(1)
+msiname = sys.argv[1]
+
+sz = int(math.ceil(float(os.stat(msiname)[6])/1000000))
+pfile = open('mantid_version.txt','a')
+pfile.write('\n'+str(sz)+'\n')
+pfile.close()
+
diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp
index 342be319c1b7d6a42993559c631dc748100c15b2..ff46433409f6ed9d7a5bcb5a32cf8b33263f2274 100644
--- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp
+++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp
@@ -4162,12593 +4162,12593 @@ ApplicationWindow* ApplicationWindow::openProject(const QString& fn, bool factor
 
       app->current_folder = f;
     } else if  (s.contains("<open>")) {
-      app->current_folder->folderListItem()->setOpen(s.remove("<open>").remove("</open>").toInt());
-    } else if  (s == "<table>") {
-      title = titleBase + QString::number(++aux)+"/"+QString::number(widgets);
-      progress.setLabelText(title);
-      QStringList lst;
-      while ( s!="</table>" ){
-        s=t.readLine();
-        lst<<s;
-      }
-      lst.pop_back();
-      openTable(app,lst);
-      progress.setValue(aux);
-    } else if (s.left(17)=="<TableStatistics>") {
-      QStringList lst;
-      while ( s!="</TableStatistics>" ){
-        s=t.readLine();
-        lst<<s;
-      }
-      lst.pop_back();
-      app->openTableStatistics(lst);
-    } else if  (s == "<matrix>") {
-      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
-      progress.setLabelText(title);
-      QStringList lst;
-      while ( s != "</matrix>" ) {
-        s=t.readLine();
-        lst<<s;
-      }
-      lst.pop_back();
-      openMatrix(app, lst);
-      progress.setValue(aux);
-    } else if  (s == "<note>") {
-      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
-      progress.setLabelText(title);
-      for (int i=0; i<3; i++){
-        s = t.readLine();
-        list << s;
-      }
-      Note* m = openNote(app,list);
-      QStringList cont;
-      while ( s != "</note>" ){
-        s=t.readLine();
-        cont << s;
-      }
-      cont.pop_back();
-      m->restore(cont);
-      progress.setValue(aux);
-    } else if  (s == "</folder>") {
-      Folder *parent = (Folder *)app->current_folder->parent();
-      if (!parent)
-        app->current_folder = app->projectFolder();
-      else
-        app->current_folder = parent;
-    }else if(s=="<mantidmatrix>"){
-      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
-      progress.setLabelText(title);
-      QStringList lst;
-      while ( s != "</mantidmatrix>" ){
-        s=t.readLine();
-        lst<<s;
-      }
-      lst.pop_back();
-      openMantidMatrix(lst);
-      progress.setValue(aux);
-    }
-    else if(s=="<mantidworkspaces>"){
-      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
-      progress.setLabelText(title);
-      QStringList lst;
-      while ( s != "</mantidworkspaces>" ) {
-        s=t.readLine();
-        lst<<s;
-      }
-      lst.pop_back();
-      s=lst[0];
-      populateMantidTreeWdiget(s);
-      progress.setValue(aux);
-    }
-    else if (s=="<scriptwindow>"){
-      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
-      progress.setLabelText(title);
-      QStringList lst;
-      while ( s != "</scriptwindow>" ) {
-        s=t.readLine();
-        lst<<s;
-      }
-      openScriptWindow(lst);
-      progress.setValue(aux);
-    }
-    else if (s=="<instrumentwindow>"){
-      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
-      progress.setLabelText(title);
-      QStringList lst;
-      while ( s != "</instrumentwindow>" ) {
-        s=t.readLine();
-        lst<<s;
-      }
-      openInstrumentWindow(lst);
-      progress.setValue(aux);
-    }
-  }
-  f.close();
-
-  if (progress.wasCanceled()){
-    app->saved = true;
-    app->close();
-    return 0;
-  }
-
-  //process the rest
-  f.open(QIODevice::ReadOnly);
-  MultiLayer *plot=0;
-  while ( !t.atEnd() && !progress.wasCanceled()){
-    s=t.readLine();
-    if  (s.left(8) == "<folder>"){
-      list = s.split("\t");
-      app->current_folder = app->current_folder->findSubfolder(list[1]);
-    } else if  (s == "<multiLayer>"){//process multilayers information
-      title = titleBase + QString::number(++aux)+"/"+QString::number(widgets);
-      progress.setLabelText(title);
-
-      s=t.readLine();
-      QStringList graph=s.split("\t");
-      QString caption=graph[0];
-      plot =multilayerPlot(caption, 0,  graph[2].toInt(), graph[1].toInt());
-      app->setListViewDate(caption, graph[3]);
-      plot->setBirthDate(graph[3]);
-
-      restoreWindowGeometry(app, plot, t.readLine());
-      plot->blockSignals(true);
-
-      if (d_file_version > 71)
-      {
-        QStringList lst=t.readLine().split("\t");
-        plot->setWindowLabel(lst[1]);
-        plot->setCaptionPolicy((MdiSubWindow::CaptionPolicy)lst[2].toInt());
-      }
-      if (d_file_version > 83)
-      {
-        QStringList lst=t.readLine().split("\t", QString::SkipEmptyParts);
-        plot->setMargins(lst[1].toInt(),lst[2].toInt(),lst[3].toInt(),lst[4].toInt());
-        lst=t.readLine().split("\t", QString::SkipEmptyParts);
-        plot->setSpacing(lst[1].toInt(),lst[2].toInt());
-        lst=t.readLine().split("\t", QString::SkipEmptyParts);
-        plot->setLayerCanvasSize(lst[1].toInt(),lst[2].toInt());
-        lst=t.readLine().split("\t", QString::SkipEmptyParts);
-        plot->setAlignement(lst[1].toInt(),lst[2].toInt());
-      }
-
-      while ( s!="</multiLayer>" )
-      {//open layers
-        s = t.readLine();
-        if (s.left(7)=="<graph>")
-        {	list.clear();
-        while ( s!="</graph>" )
-        {
-          s=t.readLine();
-          list<<s;
-        }
-        openGraph(app, plot, list);
-        }
-      }
-      if(plot) plot->blockSignals(false);
-      progress.setValue(aux);
-    }
-    else if  (s == "<SurfacePlot>")
-    {//process 3D plots information
-      list.clear();
-      title = titleBase + QString::number(++aux)+"/"+QString::number(widgets);
-      progress.setLabelText(title);
-      while ( s!="</SurfacePlot>" )
-      {
-        s=t.readLine();
-        list<<s;
-      }
-      openSurfacePlot(app,list);
-      progress.setValue(aux);
-    }
-    else if (s == "</folder>")
-    {
-      Folder *parent = (Folder *)app->current_folder->parent();
-      if (!parent)
-        app->current_folder = projectFolder();
-      else
-        app->current_folder = parent;
-    }
-    else if (s == "<log>")
-    {//process analysis information
-      s = t.readLine();
-      QString log = s + "\n";
-      while(s != "</log>"){
-        s = t.readLine();
-        log += s + "\n";
-      }
-      app->current_folder->appendLogInfo(log.remove("</log>"));
-    }
-  }
-  f.close();
-
-  if (progress.wasCanceled())
-  {
-    app->saved = true;
-    app->close();
-    return 0;
-  }
-
-  QFileInfo fi2(f);
-  QString fileName = fi2.absFilePath();
-  app->recentProjects.remove(fileName);
-  app->recentProjects.push_front(fileName);
-  app->updateRecentProjectsList();
-
-  app->folders->setCurrentItem(cf->folderListItem());
-  app->folders->blockSignals (false);
-  //change folder to user defined current folder
-  app->changeFolder(cf, true);
-
-  app->blockSignals (false);
-  app->renamedTables.clear();
-
-  app->restoreApplicationGeometry();
-
-  app->executeNotes();
-  app->savedProject();
-  app->d_opening_file = false;
-  app->d_workspace->blockSignals(false);
-  return app;
-}
-
-void ApplicationWindow::executeNotes()
-{
-  QList<MdiSubWindow *> lst = projectFolder()->windowsList();
-  foreach(MdiSubWindow *widget, lst)
-  if (widget->isA("Note") && ((Note*)widget)->autoexec())
-    ((Note*)widget)->executeAll();
-}
-
-void ApplicationWindow::scriptPrint(const QString &msg, bool error, bool timestamp)
-{
-  if( error || msg.contains("error",Qt::CaseInsensitive) )
-  {
-    console->setTextColor(Qt::red);
-    consoleWindow->show();
-  }
-  else
-  {
-    console->setTextColor(Qt::black);
-  }
-  QString msg_to_print = msg;
-
-  if( error || timestamp )
-  {
-    if( timestamp )
-    {
-      QString separator(100, '-'); 
-      msg_to_print  = separator + "\n" + QDateTime::currentDateTime().toString() 
-	    + ": " + msg.trimmed() + "\n" + separator + '\n';
-    }
-
-    // Check for last character being a new line character unless we are at the start of the 
-    // scroll area
-    if( !console->text().endsWith('\n') && console->textCursor().position() != 0 )
-    {
-      console->textCursor().insertText("\n");    
-    }
-  }
-
-  console->textCursor().insertText(msg_to_print);
-  console->moveCursor(QTextCursor::End);
-}
-
-bool ApplicationWindow::setScriptingLanguage(const QString &lang)
-{
-  if ( lang.isEmpty() ) return false;
-  if( scriptingEnv() && lang == scriptingEnv()->name() ) return true;
-
-  if( m_bad_script_envs.contains(lang) ) 
-  {
-    QMessageBox::information(this, "MantidPlot", QString("Previous initialization of ") + lang + QString(" failed, cannot retry."));
-    return false;
-  }
-
-  ScriptingEnv* newEnv(NULL);
-  if( m_script_envs.contains(lang) )
-  {
-    newEnv = m_script_envs.value(lang);
-  }
-  else
-  {
-    newEnv = ScriptingLangManager::newEnv(lang, this);
-    connect(newEnv, SIGNAL(print(const QString&)), this, SLOT(scriptPrint(const QString&)));
+      app->current_folder->folderListItem()->setOpen(s.remove("<open>").remove("</open>").toInt());
+    } else if  (s == "<table>") {
+      title = titleBase + QString::number(++aux)+"/"+QString::number(widgets);
+      progress.setLabelText(title);
+      QStringList lst;
+      while ( s!="</table>" ){
+        s=t.readLine();
+        lst<<s;
+      }
+      lst.pop_back();
+      openTable(app,lst);
+      progress.setValue(aux);
+    } else if (s.left(17)=="<TableStatistics>") {
+      QStringList lst;
+      while ( s!="</TableStatistics>" ){
+        s=t.readLine();
+        lst<<s;
+      }
+      lst.pop_back();
+      app->openTableStatistics(lst);
+    } else if  (s == "<matrix>") {
+      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
+      progress.setLabelText(title);
+      QStringList lst;
+      while ( s != "</matrix>" ) {
+        s=t.readLine();
+        lst<<s;
+      }
+      lst.pop_back();
+      openMatrix(app, lst);
+      progress.setValue(aux);
+    } else if  (s == "<note>") {
+      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
+      progress.setLabelText(title);
+      for (int i=0; i<3; i++){
+        s = t.readLine();
+        list << s;
+      }
+      Note* m = openNote(app,list);
+      QStringList cont;
+      while ( s != "</note>" ){
+        s=t.readLine();
+        cont << s;
+      }
+      cont.pop_back();
+      m->restore(cont);
+      progress.setValue(aux);
+    } else if  (s == "</folder>") {
+      Folder *parent = (Folder *)app->current_folder->parent();
+      if (!parent)
+        app->current_folder = app->projectFolder();
+      else
+        app->current_folder = parent;
+    }else if(s=="<mantidmatrix>"){
+      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
+      progress.setLabelText(title);
+      QStringList lst;
+      while ( s != "</mantidmatrix>" ){
+        s=t.readLine();
+        lst<<s;
+      }
+      lst.pop_back();
+      openMantidMatrix(lst);
+      progress.setValue(aux);
+    }
+    else if(s=="<mantidworkspaces>"){
+      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
+      progress.setLabelText(title);
+      QStringList lst;
+      while ( s != "</mantidworkspaces>" ) {
+        s=t.readLine();
+        lst<<s;
+      }
+      lst.pop_back();
+      s=lst[0];
+      populateMantidTreeWdiget(s);
+      progress.setValue(aux);
+    }
+    else if (s=="<scriptwindow>"){
+      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
+      progress.setLabelText(title);
+      QStringList lst;
+      while ( s != "</scriptwindow>" ) {
+        s=t.readLine();
+        lst<<s;
+      }
+      openScriptWindow(lst);
+      progress.setValue(aux);
+    }
+    else if (s=="<instrumentwindow>"){
+      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
+      progress.setLabelText(title);
+      QStringList lst;
+      while ( s != "</instrumentwindow>" ) {
+        s=t.readLine();
+        lst<<s;
+      }
+      openInstrumentWindow(lst);
+      progress.setValue(aux);
+    }
+  }
+  f.close();
+
+  if (progress.wasCanceled()){
+    app->saved = true;
+    app->close();
+    return 0;
+  }
+
+  //process the rest
+  f.open(QIODevice::ReadOnly);
+  MultiLayer *plot=0;
+  while ( !t.atEnd() && !progress.wasCanceled()){
+    s=t.readLine();
+    if  (s.left(8) == "<folder>"){
+      list = s.split("\t");
+      app->current_folder = app->current_folder->findSubfolder(list[1]);
+    } else if  (s == "<multiLayer>"){//process multilayers information
+      title = titleBase + QString::number(++aux)+"/"+QString::number(widgets);
+      progress.setLabelText(title);
+
+      s=t.readLine();
+      QStringList graph=s.split("\t");
+      QString caption=graph[0];
+      plot =multilayerPlot(caption, 0,  graph[2].toInt(), graph[1].toInt());
+      app->setListViewDate(caption, graph[3]);
+      plot->setBirthDate(graph[3]);
+
+      restoreWindowGeometry(app, plot, t.readLine());
+      plot->blockSignals(true);
+
+      if (d_file_version > 71)
+      {
+        QStringList lst=t.readLine().split("\t");
+        plot->setWindowLabel(lst[1]);
+        plot->setCaptionPolicy((MdiSubWindow::CaptionPolicy)lst[2].toInt());
+      }
+      if (d_file_version > 83)
+      {
+        QStringList lst=t.readLine().split("\t", QString::SkipEmptyParts);
+        plot->setMargins(lst[1].toInt(),lst[2].toInt(),lst[3].toInt(),lst[4].toInt());
+        lst=t.readLine().split("\t", QString::SkipEmptyParts);
+        plot->setSpacing(lst[1].toInt(),lst[2].toInt());
+        lst=t.readLine().split("\t", QString::SkipEmptyParts);
+        plot->setLayerCanvasSize(lst[1].toInt(),lst[2].toInt());
+        lst=t.readLine().split("\t", QString::SkipEmptyParts);
+        plot->setAlignement(lst[1].toInt(),lst[2].toInt());
+      }
+
+      while ( s!="</multiLayer>" )
+      {//open layers
+        s = t.readLine();
+        if (s.left(7)=="<graph>")
+        {	list.clear();
+        while ( s!="</graph>" )
+        {
+          s=t.readLine();
+          list<<s;
+        }
+        openGraph(app, plot, list);
+        }
+      }
+      if(plot) plot->blockSignals(false);
+      progress.setValue(aux);
+    }
+    else if  (s == "<SurfacePlot>")
+    {//process 3D plots information
+      list.clear();
+      title = titleBase + QString::number(++aux)+"/"+QString::number(widgets);
+      progress.setLabelText(title);
+      while ( s!="</SurfacePlot>" )
+      {
+        s=t.readLine();
+        list<<s;
+      }
+      openSurfacePlot(app,list);
+      progress.setValue(aux);
+    }
+    else if (s == "</folder>")
+    {
+      Folder *parent = (Folder *)app->current_folder->parent();
+      if (!parent)
+        app->current_folder = projectFolder();
+      else
+        app->current_folder = parent;
+    }
+    else if (s == "<log>")
+    {//process analysis information
+      s = t.readLine();
+      QString log = s + "\n";
+      while(s != "</log>"){
+        s = t.readLine();
+        log += s + "\n";
+      }
+      app->current_folder->appendLogInfo(log.remove("</log>"));
+    }
+  }
+  f.close();
+
+  if (progress.wasCanceled())
+  {
+    app->saved = true;
+    app->close();
+    return 0;
+  }
+
+  QFileInfo fi2(f);
+  QString fileName = fi2.absFilePath();
+  app->recentProjects.remove(fileName);
+  app->recentProjects.push_front(fileName);
+  app->updateRecentProjectsList();
+
+  app->folders->setCurrentItem(cf->folderListItem());
+  app->folders->blockSignals (false);
+  //change folder to user defined current folder
+  app->changeFolder(cf, true);
+
+  app->blockSignals (false);
+  app->renamedTables.clear();
+
+  app->restoreApplicationGeometry();
+
+  app->executeNotes();
+  app->savedProject();
+  app->d_opening_file = false;
+  app->d_workspace->blockSignals(false);
+  return app;
+}
+
+void ApplicationWindow::executeNotes()
+{
+  QList<MdiSubWindow *> lst = projectFolder()->windowsList();
+  foreach(MdiSubWindow *widget, lst)
+  if (widget->isA("Note") && ((Note*)widget)->autoexec())
+    ((Note*)widget)->executeAll();
+}
+
+void ApplicationWindow::scriptPrint(const QString &msg, bool error, bool timestamp)
+{
+  if( error || msg.contains("error",Qt::CaseInsensitive) )
+  {
+    console->setTextColor(Qt::red);
+    consoleWindow->show();
+  }
+  else
+  {
+    console->setTextColor(Qt::black);
+  }
+  QString msg_to_print = msg;
+
+  if( error || timestamp )
+  {
+    if( timestamp )
+    {
+      QString separator(100, '-'); 
+      msg_to_print  = separator + "\n" + QDateTime::currentDateTime().toString() 
+	    + ": " + msg.trimmed() + "\n" + separator + '\n';
+    }
+
+    // Check for last character being a new line character unless we are at the start of the 
+    // scroll area
+    if( !console->text().endsWith('\n') && console->textCursor().position() != 0 )
+    {
+      console->textCursor().insertText("\n");    
+    }
+  }
+
+  console->textCursor().insertText(msg_to_print);
+  console->moveCursor(QTextCursor::End);
+}
+
+bool ApplicationWindow::setScriptingLanguage(const QString &lang)
+{
+  if ( lang.isEmpty() ) return false;
+  if( scriptingEnv() && lang == scriptingEnv()->name() ) return true;
+
+  if( m_bad_script_envs.contains(lang) ) 
+  {
+    QMessageBox::information(this, "MantidPlot", QString("Previous initialization of ") + lang + QString(" failed, cannot retry."));
+    return false;
+  }
+
+  ScriptingEnv* newEnv(NULL);
+  if( m_script_envs.contains(lang) )
+  {
+    newEnv = m_script_envs.value(lang);
+  }
+  else
+  {
+    newEnv = ScriptingLangManager::newEnv(lang, this);
+    connect(newEnv, SIGNAL(print(const QString&)), this, SLOT(scriptPrint(const QString&)));
 
     // The following is already part of executeScript
     // This call could be uncommented if mantidsimple is folded into Mantid such that the
-    // algorithm call signature could also be updated.
-    //connect(mantidUI, SIGNAL(algorithmAboutToBeCreated()), newEnv, SLOT(refreshAlgorithms()));
-
-    if( newEnv->initialize() )
-    {   
-      m_script_envs.insert(lang, newEnv);
-    }
-    else
-    {
-      delete newEnv;
-      m_bad_script_envs.insert(lang);
-      QMessageBox::information(this, "MantidPlot", QString("Failed to initialize ") + lang);
-      return false;
-    }
-  }
-
-  // notify everyone who might be interested
-  ScriptingChangeEvent *sce = new ScriptingChangeEvent(newEnv);
-  QApplication::sendEvent(this, sce);
-  delete sce;
-
-  foreach(QObject *i, findChildren<QObject*>())
-  QApplication::postEvent(i, new ScriptingChangeEvent(newEnv));
-
-  if (scriptingWindow)
-  {
-    //Mantid - This is so that the title of the script window reflects the current scripting language
-    QApplication::postEvent(scriptingWindow, new ScriptingChangeEvent(newEnv));
-
-    foreach(QObject *i, scriptingWindow->findChildren<QObject*>())
-    QApplication::postEvent(i, new ScriptingChangeEvent(newEnv));
-  }
-
-  return true;
-}
-
-void ApplicationWindow::showScriptingLangDialog()
-{
-  // If a script is currently active, don't let a new one be selected
-  if( scriptingEnv()->isRunning() )
-  {
-    QMessageBox msg_box;
-    msg_box.setText("Cannot change scripting language, a script is still running.");
-    msg_box.exec();
-    return;
-  }
-  ScriptingLangDialog* d = new ScriptingLangDialog(scriptingEnv(), this);
-  d->exec();
-}
-
-void ApplicationWindow::openTemplate()
-{
-  QString filter = "MantidPlot 2D Graph Template (*.qpt);;";
-  filter += "MantidPlot 3D Surface Template (*.qst);;";
-  filter += "MantidPlot Table Template (*.qtt);;";
-  filter += "MantidPlot Matrix Template (*.qmt);;";
-
-  QString fn = QFileDialog::getOpenFileName(this, tr("MantidPlot - Open Template File"), templatesDir, filter);//Mantid
-  if (!fn.isEmpty()){
-    QFileInfo fi(fn);
-    templatesDir = fi.dirPath(true);
-    if (fn.contains(".qmt") || fn.contains(".qpt") || fn.contains(".qtt") || fn.contains(".qst"))
-      openTemplate(fn);
-    else {
-      QMessageBox::critical(this,tr("MantidPlot - File opening error"),//Mantid
-          tr("The file: <b>%1</b> is not a MantidPlot template file!").arg(fn));
-      return;
-    }
-  }
-}
-
-MdiSubWindow* ApplicationWindow::openTemplate(const QString& fn)
-{
-  if (fn.isEmpty() || !QFile::exists(fn)){
-    QMessageBox::critical(this, tr("MantidPlot - File opening error"),//Mantid
-        tr("The file: <b>%1</b> doesn't exist!").arg(fn));
-    return 0;
-  }
-
-  QFile f(fn);
-  QTextStream t(&f);
-  t.setEncoding(QTextStream::UnicodeUTF8);
-  f.open(QIODevice::ReadOnly);
-  QStringList l=t.readLine().split(QRegExp("\\s"), QString::SkipEmptyParts);
-  QString fileType=l[0];
-  if (fileType != "MantidPlot"){
-    QMessageBox::critical(this,tr("MantidPlot - File opening error"),//Mantid
-        tr("The file: <b> %1 </b> was not created using MantidPlot!").arg(fn));
-    return 0;
-  }
-
-  QStringList vl = l[1].split(".", QString::SkipEmptyParts);
-  d_file_version = 100*(vl[0]).toInt()+10*(vl[1]).toInt()+(vl[2]).toInt();
-
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-  MdiSubWindow *w = 0;
-  QString templateType;
-  t>>templateType;
-
-  if (templateType == "<SurfacePlot>") {
-    t.skipWhiteSpace();
-    QStringList lst;
-    while (!t.atEnd())
-      lst << t.readLine();
-    w = openSurfacePlot(this,lst);
-    if (w)
-      ((Graph3D *)w)->clearData();
-  } else {
-    int rows, cols;
-    t>>rows; t>>cols;
-    t.skipWhiteSpace();
-    QString geometry = t.readLine();
-
-    if (templateType == "<multiLayer>"){
-      w = multilayerPlot(generateUniqueName(tr("Graph")));
-      if (w){
-        ((MultiLayer*)w)->setCols(cols);
-        ((MultiLayer*)w)->setRows(rows);
-        restoreWindowGeometry(this, w, geometry);
-        if (d_file_version > 83){
-          QStringList lst=t.readLine().split("\t", QString::SkipEmptyParts);
-          ((MultiLayer*)w)->setMargins(lst[1].toInt(),lst[2].toInt(),lst[3].toInt(),lst[4].toInt());
-          lst=t.readLine().split("\t", QString::SkipEmptyParts);
-          ((MultiLayer*)w)->setSpacing(lst[1].toInt(),lst[2].toInt());
-          lst=t.readLine().split("\t", QString::SkipEmptyParts);
-          ((MultiLayer*)w)->setLayerCanvasSize(lst[1].toInt(),lst[2].toInt());
-          lst=t.readLine().split("\t", QString::SkipEmptyParts);
-          ((MultiLayer*)w)->setAlignement(lst[1].toInt(),lst[2].toInt());
-        }
-        while (!t.atEnd()){//open layers
-          QString s=t.readLine();
-          if (s.left(7)=="<graph>"){
-            QStringList lst;
-            while ( s!="</graph>" ){
-              s = t.readLine();
-              lst << s;
-            }
-            openGraph(this, (MultiLayer*)w, lst);
-          }
-        }
-      }
-    } else {
-      if (templateType == "<table>")
-        w = newTable(tr("Table1"), rows, cols);
-      else if (templateType == "<matrix>")
-        w = newMatrix(rows, cols);
-      if (w){
-        QStringList lst;
-        while (!t.atEnd())
-          lst << t.readLine();
-        w->restore(lst);
-        restoreWindowGeometry(this, w, geometry);
-      }
-    }
-  }
-
-  f.close();
-  if (w){
-    customMenu(w);
-    customToolBars(w);
-  }
-
-  QApplication::restoreOverrideCursor();
-  return w;
-}
-
-void ApplicationWindow::readSettings()
-{
-#ifdef Q_OS_MAC // Mac
-  QSettings settings(QSettings::IniFormat,QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName());
-#else
-  QSettings settings;
-#endif
-
-  /* ---------------- group General --------------- */
-  settings.beginGroup("/General");
-  settings.beginGroup("/ApplicationGeometry");//main window geometry
-  d_app_rect = QRect(settings.value("/x", 0).toInt(), settings.value("/y", 0).toInt(),
-      settings.value("/width", 0).toInt(), settings.value("/height", 0).toInt());
-  settings.endGroup();
-
-  autoSearchUpdates = settings.value("/AutoSearchUpdates", false).toBool();
-  appLanguage = settings.value("/Language", QLocale::system().name().section('_',0,0)).toString();
-  show_windows_policy = (ShowWindowsPolicy)settings.value("/ShowWindowsPolicy", ApplicationWindow::ActiveFolder).toInt();
-
-  recentProjects = settings.value("/RecentProjects").toStringList();
-  //Follows an ugly hack added by Ion in order to fix Qt4 porting issues
-  //(only needed on Windows due to a Qt bug?)
-#ifdef Q_OS_WIN
-  if (!recentProjects.isEmpty() && recentProjects[0].contains("^e"))
-    recentProjects = recentProjects[0].split("^e", QString::SkipEmptyParts);
-  else if (recentProjects.count() == 1){
-    QString s = recentProjects[0];
-    if (s.remove(QRegExp("\\s")).isEmpty())
-      recentProjects = QStringList();
-  }
-#endif
-
-  updateRecentProjectsList();
-
-  changeAppStyle(settings.value("/Style", appStyle).toString());
-  autoSave = settings.value("/AutoSave",true).toBool();
-  autoSaveTime = settings.value("/AutoSaveTime",15).toInt();
-  d_backup_files = settings.value("/BackupProjects", true).toBool();
-  d_init_window_type = (WindowType)settings.value("/InitWindow", NoWindow).toInt();
-  defaultScriptingLang = settings.value("/ScriptingLang","Python").toString();    //Mantid M. Gigg
-  d_thousands_sep = settings.value("/ThousandsSeparator", true).toBool();
-  d_locale = QLocale(settings.value("/Locale", QLocale::system().name()).toString());
-  if (!d_thousands_sep)
-    d_locale.setNumberOptions(QLocale::OmitGroupSeparator);
-
-  d_decimal_digits = settings.value("/DecimalDigits", 13).toInt();
-  d_matrix_undo_stack_size = settings.value("/MatrixUndoStackSize", 10).toInt();
-  d_eol = (EndLineChar)settings.value("/EndOfLine", d_eol).toInt();
-
-  //restore dock windows and tool bars
-  restoreState(settings.value("/DockWindows").toByteArray());
-  explorerSplitter->restoreState(settings.value("/ExplorerSplitter").toByteArray());
-  QList<int> lst = explorerSplitter->sizes();
-  for (int i=0; i< lst.count(); i++){
-    if (lst[i] == 0){
-      lst[i] = 45;
-      explorerSplitter->setSizes(lst);
-    }
-  }
-
-  QStringList applicationFont = settings.value("/Font").toStringList();
-  if (applicationFont.size() == 4)
-    appFont=QFont (applicationFont[0],applicationFont[1].toInt(),applicationFont[2].toInt(),applicationFont[3].toInt());
-
-  settings.beginGroup("/Dialogs");
-  d_extended_open_dialog = settings.value("/ExtendedOpenDialog", true).toBool();
-  d_extended_export_dialog = settings.value("/ExtendedExportDialog", true).toBool();
-  d_extended_import_ASCII_dialog = settings.value("/ExtendedImportAsciiDialog", true).toBool();
-  d_extended_plot_dialog = settings.value("/ExtendedPlotDialog", true).toBool();//used by PlotDialog
-
-  settings.beginGroup("/AddRemoveCurves");
-  d_add_curves_dialog_size = QSize(settings.value("/Width", 700).toInt(),
-      settings.value("/Height", 400).toInt());
-  d_show_current_folder = settings.value("/ShowCurrentFolder", false).toBool();
-  settings.endGroup(); // AddRemoveCurves Dialog
-  settings.endGroup(); // Dialogs
-
-  settings.beginGroup("/Colors");
-  workspaceColor = QColor(settings.value("/Workspace","darkGray").value<QColor>());
-  // see http://doc.trolltech.com/4.2/qvariant.html for instructions on qcolor <-> qvariant conversion
-  panelsColor = QColor(settings.value("/Panels","#ffffff").value<QColor>());
-  panelsTextColor = QColor(settings.value("/PanelsText","#000000").value<QColor>());
-  settings.endGroup(); // Colors
-
-  settings.beginGroup("/Paths");
-  QString appPath = qApp->applicationDirPath();
-  workingDir = settings.value("/WorkingDir", appPath).toString();
-#ifdef Q_OS_WIN
-  fitPluginsPath = settings.value("/FitPlugins", "fitPlugins").toString();
-  templatesDir = settings.value("/TemplatesDir", appPath).toString();
-  asciiDirPath = settings.value("/ASCII", appPath).toString();
-  imagesDirPath = settings.value("/Images", appPath).toString();
-#else
-  fitPluginsPath = settings.value("/FitPlugins", "/usr/lib/MantidPlot/plugins").toString();
-  templatesDir = settings.value("/TemplatesDir", QDir::homePath()).toString();
-  asciiDirPath = settings.value("/ASCII", QDir::homePath()).toString();
-  imagesDirPath = settings.value("/Images", QDir::homePath()).toString();
-  workingDir = settings.value("/WorkingDir", QDir::homePath()).toString();
-#endif
-  scriptsDirPath = settings.value("/ScriptsDir", appPath).toString();
-  fitModelsPath = settings.value("/FitModelsDir", "").toString();
-  customActionsDirPath = settings.value("/CustomActionsDir", "").toString();
-  helpFilePath = settings.value("/HelpFile", helpFilePath).toString();
-  d_translations_folder = settings.value("/Translations", d_translations_folder).toString();
-  d_python_config_folder = settings.value("/PythonConfigDir", d_python_config_folder).toString();
-  settings.endGroup(); // Paths
-  settings.endGroup();
-  /* ------------- end group General ------------------- */
-
-  settings.beginGroup("/UserFunctions");
-  if (100*maj_version + 10*min_version + patch_version == 91 &&
-      settings.contains("/FitFunctions")){
-    saveFitFunctions(settings.value("/FitFunctions").toStringList());
-    settings.remove("/FitFunctions");
-  }
-  surfaceFunc = settings.value("/SurfaceFunctions").toStringList();
-  xFunctions = settings.value("/xFunctions").toStringList();
-  yFunctions = settings.value("/yFunctions").toStringList();
-  rFunctions = settings.value("/rFunctions").toStringList();
-  thetaFunctions = settings.value("/thetaFunctions").toStringList();
-  d_param_surface_func = settings.value("/ParametricSurfaces").toStringList();
-  settings.endGroup(); // UserFunctions
-
-  settings.beginGroup("/Confirmations");
-  confirmCloseFolder = settings.value("/Folder", true).toBool();
-  confirmCloseTable = settings.value("/Table", true).toBool();
-  confirmCloseMatrix = settings.value("/Matrix", true).toBool();
-  confirmClosePlot2D = settings.value("/Plot2D", true).toBool();
-  confirmClosePlot3D = settings.value("/Plot3D", true).toBool();
-  confirmCloseNotes = settings.value("/Note", true).toBool();
-  d_inform_rename_table = settings.value("/RenameTable", true).toBool();
-  confirmCloseInstrWindow=settings.value("/InstrumentWindow", false).toBool();
-  settings.endGroup(); // Confirmations
-
-
-  /* ---------------- group Tables --------------- */
-  settings.beginGroup("/Tables");
-  d_show_table_comments = settings.value("/DisplayComments", false).toBool();
-  d_auto_update_table_values = settings.value("/AutoUpdateValues", true).toBool();
-
-  QStringList tableFonts = settings.value("/Fonts").toStringList();
-  if (tableFonts.size() == 8)
-  {
-    tableTextFont=QFont (tableFonts[0],tableFonts[1].toInt(),tableFonts[2].toInt(),tableFonts[3].toInt());
-    tableHeaderFont=QFont (tableFonts[4],tableFonts[5].toInt(),tableFonts[6].toInt(),tableFonts[7].toInt());
-  }
-
-  settings.beginGroup("/Colors");
-  tableBkgdColor = QColor(settings.value("/Background","#ffffff").value<QColor>());
-  tableTextColor = QColor(settings.value("/Text","#000000").value<QColor>());
-  tableHeaderColor = QColor(settings.value("/Header","#000000").value<QColor>());
-  settings.endGroup(); // Colors
-  settings.endGroup();
-  /* --------------- end group Tables ------------------------ */
-
-  /* --------------- group 2D Plots ----------------------------- */
-  settings.beginGroup("/2DPlots");
-  settings.beginGroup("/General");
-  titleOn = settings.value("/Title", true).toBool();
-  allAxesOn = settings.value("/AllAxes", false).toBool();
-  canvasFrameWidth = settings.value("/CanvasFrameWidth", 0).toInt();
-  defaultPlotMargin = settings.value("/Margin", 0).toInt();
-  drawBackbones = settings.value("/AxesBackbones", true).toBool();
-  xaxisScale = settings.value("/AxisXScale", "linear").toString();
-  yaxisScale = settings.value("/AxisYScale", "linear").toString();
-  zaxisScale = settings.value("/AxisZScale", "linear").toString();
-  axesLineWidth = settings.value("/AxesLineWidth", 1).toInt();
-  autoscale2DPlots = settings.value("/Autoscale", true).toBool();
-  autoScaleFonts = settings.value("/AutoScaleFonts", true).toBool();
-  autoResizeLayers = settings.value("/AutoResizeLayers", true).toBool();
-  antialiasing2DPlots = settings.value("/Antialiasing", false).toBool(); //Mantid
-  d_scale_plots_on_print = settings.value("/ScaleLayersOnPrint", false).toBool();
-  d_print_cropmarks = settings.value("/PrintCropmarks", false).toBool();
-
-  QStringList graphFonts = settings.value("/Fonts").toStringList();
-  if (graphFonts.size() == 16) {
-    plotAxesFont=QFont (graphFonts[0],graphFonts[1].toInt(),graphFonts[2].toInt(),graphFonts[3].toInt());
-    plotNumbersFont=QFont (graphFonts[4],graphFonts[5].toInt(),graphFonts[6].toInt(),graphFonts[7].toInt());
-    plotLegendFont=QFont (graphFonts[8],graphFonts[9].toInt(),graphFonts[10].toInt(),graphFonts[11].toInt());
-    plotTitleFont=QFont (graphFonts[12],graphFonts[13].toInt(),graphFonts[14].toInt(),graphFonts[15].toInt());
-  }
-  d_in_place_editing = settings.value("/InPlaceEditing", true).toBool();
-  settings.endGroup(); // General
-
-  settings.beginGroup("/Curves");
-  defaultCurveStyle = settings.value("/Style", Graph::LineSymbols).toInt();
-  defaultCurveLineWidth = settings.value("/LineWidth", 1).toDouble();
-  defaultSymbolSize = settings.value("/SymbolSize", 7).toInt();
+    // algorithm call signature could also be updated.
+    //connect(mantidUI, SIGNAL(algorithmAboutToBeCreated()), newEnv, SLOT(refreshAlgorithms()));
+
+    if( newEnv->initialize() )
+    {   
+      m_script_envs.insert(lang, newEnv);
+    }
+    else
+    {
+      delete newEnv;
+      m_bad_script_envs.insert(lang);
+      QMessageBox::information(this, "MantidPlot", QString("Failed to initialize ") + lang);
+      return false;
+    }
+  }
+
+  // notify everyone who might be interested
+  ScriptingChangeEvent *sce = new ScriptingChangeEvent(newEnv);
+  QApplication::sendEvent(this, sce);
+  delete sce;
+
+  foreach(QObject *i, findChildren<QObject*>())
+  QApplication::postEvent(i, new ScriptingChangeEvent(newEnv));
+
+  if (scriptingWindow)
+  {
+    //Mantid - This is so that the title of the script window reflects the current scripting language
+    QApplication::postEvent(scriptingWindow, new ScriptingChangeEvent(newEnv));
+
+    foreach(QObject *i, scriptingWindow->findChildren<QObject*>())
+    QApplication::postEvent(i, new ScriptingChangeEvent(newEnv));
+  }
+
+  return true;
+}
+
+void ApplicationWindow::showScriptingLangDialog()
+{
+  // If a script is currently active, don't let a new one be selected
+  if( scriptingEnv()->isRunning() )
+  {
+    QMessageBox msg_box;
+    msg_box.setText("Cannot change scripting language, a script is still running.");
+    msg_box.exec();
+    return;
+  }
+  ScriptingLangDialog* d = new ScriptingLangDialog(scriptingEnv(), this);
+  d->exec();
+}
+
+void ApplicationWindow::openTemplate()
+{
+  QString filter = "MantidPlot 2D Graph Template (*.qpt);;";
+  filter += "MantidPlot 3D Surface Template (*.qst);;";
+  filter += "MantidPlot Table Template (*.qtt);;";
+  filter += "MantidPlot Matrix Template (*.qmt);;";
+
+  QString fn = QFileDialog::getOpenFileName(this, tr("MantidPlot - Open Template File"), templatesDir, filter);//Mantid
+  if (!fn.isEmpty()){
+    QFileInfo fi(fn);
+    templatesDir = fi.dirPath(true);
+    if (fn.contains(".qmt") || fn.contains(".qpt") || fn.contains(".qtt") || fn.contains(".qst"))
+      openTemplate(fn);
+    else {
+      QMessageBox::critical(this,tr("MantidPlot - File opening error"),//Mantid
+          tr("The file: <b>%1</b> is not a MantidPlot template file!").arg(fn));
+      return;
+    }
+  }
+}
+
+MdiSubWindow* ApplicationWindow::openTemplate(const QString& fn)
+{
+  if (fn.isEmpty() || !QFile::exists(fn)){
+    QMessageBox::critical(this, tr("MantidPlot - File opening error"),//Mantid
+        tr("The file: <b>%1</b> doesn't exist!").arg(fn));
+    return 0;
+  }
+
+  QFile f(fn);
+  QTextStream t(&f);
+  t.setEncoding(QTextStream::UnicodeUTF8);
+  f.open(QIODevice::ReadOnly);
+  QStringList l=t.readLine().split(QRegExp("\\s"), QString::SkipEmptyParts);
+  QString fileType=l[0];
+  if (fileType != "MantidPlot"){
+    QMessageBox::critical(this,tr("MantidPlot - File opening error"),//Mantid
+        tr("The file: <b> %1 </b> was not created using MantidPlot!").arg(fn));
+    return 0;
+  }
+
+  QStringList vl = l[1].split(".", QString::SkipEmptyParts);
+  d_file_version = 100*(vl[0]).toInt()+10*(vl[1]).toInt()+(vl[2]).toInt();
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  MdiSubWindow *w = 0;
+  QString templateType;
+  t>>templateType;
+
+  if (templateType == "<SurfacePlot>") {
+    t.skipWhiteSpace();
+    QStringList lst;
+    while (!t.atEnd())
+      lst << t.readLine();
+    w = openSurfacePlot(this,lst);
+    if (w)
+      ((Graph3D *)w)->clearData();
+  } else {
+    int rows, cols;
+    t>>rows; t>>cols;
+    t.skipWhiteSpace();
+    QString geometry = t.readLine();
+
+    if (templateType == "<multiLayer>"){
+      w = multilayerPlot(generateUniqueName(tr("Graph")));
+      if (w){
+        ((MultiLayer*)w)->setCols(cols);
+        ((MultiLayer*)w)->setRows(rows);
+        restoreWindowGeometry(this, w, geometry);
+        if (d_file_version > 83){
+          QStringList lst=t.readLine().split("\t", QString::SkipEmptyParts);
+          ((MultiLayer*)w)->setMargins(lst[1].toInt(),lst[2].toInt(),lst[3].toInt(),lst[4].toInt());
+          lst=t.readLine().split("\t", QString::SkipEmptyParts);
+          ((MultiLayer*)w)->setSpacing(lst[1].toInt(),lst[2].toInt());
+          lst=t.readLine().split("\t", QString::SkipEmptyParts);
+          ((MultiLayer*)w)->setLayerCanvasSize(lst[1].toInt(),lst[2].toInt());
+          lst=t.readLine().split("\t", QString::SkipEmptyParts);
+          ((MultiLayer*)w)->setAlignement(lst[1].toInt(),lst[2].toInt());
+        }
+        while (!t.atEnd()){//open layers
+          QString s=t.readLine();
+          if (s.left(7)=="<graph>"){
+            QStringList lst;
+            while ( s!="</graph>" ){
+              s = t.readLine();
+              lst << s;
+            }
+            openGraph(this, (MultiLayer*)w, lst);
+          }
+        }
+      }
+    } else {
+      if (templateType == "<table>")
+        w = newTable(tr("Table1"), rows, cols);
+      else if (templateType == "<matrix>")
+        w = newMatrix(rows, cols);
+      if (w){
+        QStringList lst;
+        while (!t.atEnd())
+          lst << t.readLine();
+        w->restore(lst);
+        restoreWindowGeometry(this, w, geometry);
+      }
+    }
+  }
+
+  f.close();
+  if (w){
+    customMenu(w);
+    customToolBars(w);
+  }
+
+  QApplication::restoreOverrideCursor();
+  return w;
+}
+
+void ApplicationWindow::readSettings()
+{
+#ifdef Q_OS_MAC // Mac
+  QSettings settings(QSettings::IniFormat,QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName());
+#else
+  QSettings settings;
+#endif
+
+  /* ---------------- group General --------------- */
+  settings.beginGroup("/General");
+  settings.beginGroup("/ApplicationGeometry");//main window geometry
+  d_app_rect = QRect(settings.value("/x", 0).toInt(), settings.value("/y", 0).toInt(),
+      settings.value("/width", 0).toInt(), settings.value("/height", 0).toInt());
+  settings.endGroup();
+
+  autoSearchUpdates = settings.value("/AutoSearchUpdates", false).toBool();
+  appLanguage = settings.value("/Language", QLocale::system().name().section('_',0,0)).toString();
+  show_windows_policy = (ShowWindowsPolicy)settings.value("/ShowWindowsPolicy", ApplicationWindow::ActiveFolder).toInt();
+
+  recentProjects = settings.value("/RecentProjects").toStringList();
+  //Follows an ugly hack added by Ion in order to fix Qt4 porting issues
+  //(only needed on Windows due to a Qt bug?)
+#ifdef Q_OS_WIN
+  if (!recentProjects.isEmpty() && recentProjects[0].contains("^e"))
+    recentProjects = recentProjects[0].split("^e", QString::SkipEmptyParts);
+  else if (recentProjects.count() == 1){
+    QString s = recentProjects[0];
+    if (s.remove(QRegExp("\\s")).isEmpty())
+      recentProjects = QStringList();
+  }
+#endif
+
+  updateRecentProjectsList();
+
+  changeAppStyle(settings.value("/Style", appStyle).toString());
+  autoSave = settings.value("/AutoSave",true).toBool();
+  autoSaveTime = settings.value("/AutoSaveTime",15).toInt();
+  d_backup_files = settings.value("/BackupProjects", true).toBool();
+  d_init_window_type = (WindowType)settings.value("/InitWindow", NoWindow).toInt();
+  defaultScriptingLang = settings.value("/ScriptingLang","Python").toString();    //Mantid M. Gigg
+  d_thousands_sep = settings.value("/ThousandsSeparator", true).toBool();
+  d_locale = QLocale(settings.value("/Locale", QLocale::system().name()).toString());
+  if (!d_thousands_sep)
+    d_locale.setNumberOptions(QLocale::OmitGroupSeparator);
+
+  d_decimal_digits = settings.value("/DecimalDigits", 13).toInt();
+  d_matrix_undo_stack_size = settings.value("/MatrixUndoStackSize", 10).toInt();
+  d_eol = (EndLineChar)settings.value("/EndOfLine", d_eol).toInt();
+
+  //restore dock windows and tool bars
+  restoreState(settings.value("/DockWindows").toByteArray());
+  explorerSplitter->restoreState(settings.value("/ExplorerSplitter").toByteArray());
+  QList<int> lst = explorerSplitter->sizes();
+  for (int i=0; i< lst.count(); i++){
+    if (lst[i] == 0){
+      lst[i] = 45;
+      explorerSplitter->setSizes(lst);
+    }
+  }
+
+  QStringList applicationFont = settings.value("/Font").toStringList();
+  if (applicationFont.size() == 4)
+    appFont=QFont (applicationFont[0],applicationFont[1].toInt(),applicationFont[2].toInt(),applicationFont[3].toInt());
+
+  settings.beginGroup("/Dialogs");
+  d_extended_open_dialog = settings.value("/ExtendedOpenDialog", true).toBool();
+  d_extended_export_dialog = settings.value("/ExtendedExportDialog", true).toBool();
+  d_extended_import_ASCII_dialog = settings.value("/ExtendedImportAsciiDialog", true).toBool();
+  d_extended_plot_dialog = settings.value("/ExtendedPlotDialog", true).toBool();//used by PlotDialog
+
+  settings.beginGroup("/AddRemoveCurves");
+  d_add_curves_dialog_size = QSize(settings.value("/Width", 700).toInt(),
+      settings.value("/Height", 400).toInt());
+  d_show_current_folder = settings.value("/ShowCurrentFolder", false).toBool();
+  settings.endGroup(); // AddRemoveCurves Dialog
+  settings.endGroup(); // Dialogs
+
+  settings.beginGroup("/Colors");
+  workspaceColor = QColor(settings.value("/Workspace","darkGray").value<QColor>());
+  // see http://doc.trolltech.com/4.2/qvariant.html for instructions on qcolor <-> qvariant conversion
+  panelsColor = QColor(settings.value("/Panels","#ffffff").value<QColor>());
+  panelsTextColor = QColor(settings.value("/PanelsText","#000000").value<QColor>());
+  settings.endGroup(); // Colors
+
+  settings.beginGroup("/Paths");
+  QString appPath = qApp->applicationDirPath();
+  workingDir = settings.value("/WorkingDir", appPath).toString();
+#ifdef Q_OS_WIN
+  fitPluginsPath = settings.value("/FitPlugins", "fitPlugins").toString();
+  templatesDir = settings.value("/TemplatesDir", appPath).toString();
+  asciiDirPath = settings.value("/ASCII", appPath).toString();
+  imagesDirPath = settings.value("/Images", appPath).toString();
+#else
+  fitPluginsPath = settings.value("/FitPlugins", "/usr/lib/MantidPlot/plugins").toString();
+  templatesDir = settings.value("/TemplatesDir", QDir::homePath()).toString();
+  asciiDirPath = settings.value("/ASCII", QDir::homePath()).toString();
+  imagesDirPath = settings.value("/Images", QDir::homePath()).toString();
+  workingDir = settings.value("/WorkingDir", QDir::homePath()).toString();
+#endif
+  scriptsDirPath = settings.value("/ScriptsDir", appPath).toString();
+  fitModelsPath = settings.value("/FitModelsDir", "").toString();
+  customActionsDirPath = settings.value("/CustomActionsDir", "").toString();
+  helpFilePath = settings.value("/HelpFile", helpFilePath).toString();
+  d_translations_folder = settings.value("/Translations", d_translations_folder).toString();
+  d_python_config_folder = settings.value("/PythonConfigDir", d_python_config_folder).toString();
+  settings.endGroup(); // Paths
+  settings.endGroup();
+  /* ------------- end group General ------------------- */
+
+  settings.beginGroup("/UserFunctions");
+  if (100*maj_version + 10*min_version + patch_version == 91 &&
+      settings.contains("/FitFunctions")){
+    saveFitFunctions(settings.value("/FitFunctions").toStringList());
+    settings.remove("/FitFunctions");
+  }
+  surfaceFunc = settings.value("/SurfaceFunctions").toStringList();
+  xFunctions = settings.value("/xFunctions").toStringList();
+  yFunctions = settings.value("/yFunctions").toStringList();
+  rFunctions = settings.value("/rFunctions").toStringList();
+  thetaFunctions = settings.value("/thetaFunctions").toStringList();
+  d_param_surface_func = settings.value("/ParametricSurfaces").toStringList();
+  settings.endGroup(); // UserFunctions
+
+  settings.beginGroup("/Confirmations");
+  confirmCloseFolder = settings.value("/Folder", true).toBool();
+  confirmCloseTable = settings.value("/Table", true).toBool();
+  confirmCloseMatrix = settings.value("/Matrix", true).toBool();
+  confirmClosePlot2D = settings.value("/Plot2D", true).toBool();
+  confirmClosePlot3D = settings.value("/Plot3D", true).toBool();
+  confirmCloseNotes = settings.value("/Note", true).toBool();
+  d_inform_rename_table = settings.value("/RenameTable", true).toBool();
+  confirmCloseInstrWindow=settings.value("/InstrumentWindow", false).toBool();
+  settings.endGroup(); // Confirmations
+
+
+  /* ---------------- group Tables --------------- */
+  settings.beginGroup("/Tables");
+  d_show_table_comments = settings.value("/DisplayComments", false).toBool();
+  d_auto_update_table_values = settings.value("/AutoUpdateValues", true).toBool();
+
+  QStringList tableFonts = settings.value("/Fonts").toStringList();
+  if (tableFonts.size() == 8)
+  {
+    tableTextFont=QFont (tableFonts[0],tableFonts[1].toInt(),tableFonts[2].toInt(),tableFonts[3].toInt());
+    tableHeaderFont=QFont (tableFonts[4],tableFonts[5].toInt(),tableFonts[6].toInt(),tableFonts[7].toInt());
+  }
+
+  settings.beginGroup("/Colors");
+  tableBkgdColor = QColor(settings.value("/Background","#ffffff").value<QColor>());
+  tableTextColor = QColor(settings.value("/Text","#000000").value<QColor>());
+  tableHeaderColor = QColor(settings.value("/Header","#000000").value<QColor>());
+  settings.endGroup(); // Colors
+  settings.endGroup();
+  /* --------------- end group Tables ------------------------ */
+
+  /* --------------- group 2D Plots ----------------------------- */
+  settings.beginGroup("/2DPlots");
+  settings.beginGroup("/General");
+  titleOn = settings.value("/Title", true).toBool();
+  allAxesOn = settings.value("/AllAxes", false).toBool();
+  canvasFrameWidth = settings.value("/CanvasFrameWidth", 0).toInt();
+  defaultPlotMargin = settings.value("/Margin", 0).toInt();
+  drawBackbones = settings.value("/AxesBackbones", true).toBool();
+  xaxisScale = settings.value("/AxisXScale", "linear").toString();
+  yaxisScale = settings.value("/AxisYScale", "linear").toString();
+  zaxisScale = settings.value("/AxisZScale", "linear").toString();
+  axesLineWidth = settings.value("/AxesLineWidth", 1).toInt();
+  autoscale2DPlots = settings.value("/Autoscale", true).toBool();
+  autoScaleFonts = settings.value("/AutoScaleFonts", true).toBool();
+  autoResizeLayers = settings.value("/AutoResizeLayers", true).toBool();
+  antialiasing2DPlots = settings.value("/Antialiasing", false).toBool(); //Mantid
+  d_scale_plots_on_print = settings.value("/ScaleLayersOnPrint", false).toBool();
+  d_print_cropmarks = settings.value("/PrintCropmarks", false).toBool();
+
+  QStringList graphFonts = settings.value("/Fonts").toStringList();
+  if (graphFonts.size() == 16) {
+    plotAxesFont=QFont (graphFonts[0],graphFonts[1].toInt(),graphFonts[2].toInt(),graphFonts[3].toInt());
+    plotNumbersFont=QFont (graphFonts[4],graphFonts[5].toInt(),graphFonts[6].toInt(),graphFonts[7].toInt());
+    plotLegendFont=QFont (graphFonts[8],graphFonts[9].toInt(),graphFonts[10].toInt(),graphFonts[11].toInt());
+    plotTitleFont=QFont (graphFonts[12],graphFonts[13].toInt(),graphFonts[14].toInt(),graphFonts[15].toInt());
+  }
+  d_in_place_editing = settings.value("/InPlaceEditing", true).toBool();
+  settings.endGroup(); // General
+
+  settings.beginGroup("/Curves");
+  defaultCurveStyle = settings.value("/Style", Graph::LineSymbols).toInt();
+  defaultCurveLineWidth = settings.value("/LineWidth", 1).toDouble();
+  defaultSymbolSize = settings.value("/SymbolSize", 7).toInt();
   applyCurveStyleToMantid = settings.value("/ApplyMantid", true).toBool();
-  settings.endGroup(); // Curves
-
-  settings.beginGroup("/Ticks");
-  majTicksStyle = settings.value("/MajTicksStyle", ScaleDraw::Out).toInt();
-  minTicksStyle = settings.value("/MinTicksStyle", ScaleDraw::Out).toInt();
-  minTicksLength = settings.value("/MinTicksLength", 5).toInt();
-  majTicksLength = settings.value("/MajTicksLength", 9).toInt();
-  settings.endGroup(); // Ticks
-
-  settings.beginGroup("/Legend");
-  legendFrameStyle = settings.value("/FrameStyle", LegendWidget::Line).toInt();
-  legendTextColor = QColor(settings.value("/TextColor", "#000000").value<QColor>()); //default color Qt::black
-  legendBackground = QColor(settings.value("/BackgroundColor", "#ffffff").value<QColor>()); //default color Qt::white
-  legendBackground.setAlpha(settings.value("/Transparency", 0).toInt()); // transparent by default;
-  settings.endGroup(); // Legend
-
-  settings.beginGroup("/Arrows");
-  defaultArrowLineWidth = settings.value("/Width", 1).toDouble();
-  defaultArrowColor = QColor(settings.value("/Color", "#000000").value<QColor>());//default color Qt::black
-  defaultArrowHeadLength = settings.value("/HeadLength", 4).toInt();
-  defaultArrowHeadAngle = settings.value("/HeadAngle", 45).toInt();
-  defaultArrowHeadFill = settings.value("/HeadFill", true).toBool();
-  defaultArrowLineStyle = Graph::getPenStyle(settings.value("/LineStyle", "SolidLine").toString());
-  settings.endGroup(); // Arrows
-  settings.endGroup();
-  /* ----------------- end group 2D Plots --------------------------- */
-
-  /* ----------------- group 3D Plots --------------------------- */
-  settings.beginGroup("/3DPlots");
-  showPlot3DLegend = settings.value("/Legend",true).toBool();
-  showPlot3DProjection = settings.value("/Projection", false).toBool();
-  smooth3DMesh = settings.value("/Antialiasing", false).toBool(); //Mantid
-  plot3DResolution = settings.value ("/Resolution", 1).toInt();
-  orthogonal3DPlots = settings.value("/Orthogonal", false).toBool();
-  autoscale3DPlots = settings.value ("/Autoscale", true).toBool();
-
-  QStringList plot3DFonts = settings.value("/Fonts").toStringList();
-  if (plot3DFonts.size() == 12){
-    plot3DTitleFont=QFont (plot3DFonts[0],plot3DFonts[1].toInt(),plot3DFonts[2].toInt(),plot3DFonts[3].toInt());
-    plot3DNumbersFont=QFont (plot3DFonts[4],plot3DFonts[5].toInt(),plot3DFonts[6].toInt(),plot3DFonts[7].toInt());
-    plot3DAxesFont=QFont (plot3DFonts[8],plot3DFonts[9].toInt(),plot3DFonts[10].toInt(),plot3DFonts[11].toInt());
-  }
-
-  settings.beginGroup("/Colors");
-  plot3DColors = QStringList();
-  plot3DColors << QColor(settings.value("/MaxData", "blue").value<QColor>()).name();
-  plot3DColors << QColor(settings.value("/Labels", "#000000").value<QColor>()).name();
-  plot3DColors << QColor(settings.value("/Mesh", "#000000").value<QColor>()).name();
-  plot3DColors << QColor(settings.value("/Grid", "#000000").value<QColor>()).name();
-  plot3DColors << QColor(settings.value("/MinData", "red").value<QColor>()).name();
-  plot3DColors << QColor(settings.value("/Numbers", "#000000").value<QColor>()).name();
-  plot3DColors << QColor(settings.value("/Axes", "#000000").value<QColor>()).name();
-  plot3DColors << QColor(settings.value("/Background", "#ffffff").value<QColor>()).name();
-  settings.endGroup(); // Colors
-  settings.endGroup();
-  /* ----------------- end group 3D Plots --------------------------- */
-
-  settings.beginGroup("/Fitting");
-  fit_output_precision = settings.value("/OutputPrecision", 15).toInt();
-  pasteFitResultsToPlot = settings.value("/PasteResultsToPlot", false).toBool();
-  writeFitResultsToLog = settings.value("/WriteResultsToLog", true).toBool();
-  generateUniformFitPoints = settings.value("/GenerateFunction", true).toBool();
-  fitPoints = settings.value("/Points", 100).toInt();
-  generatePeakCurves = settings.value("/GeneratePeakCurves", true).toBool();
-  peakCurvesColor = settings.value("/PeaksColor", 2).toInt();//green color
-  fit_scale_errors = settings.value("/ScaleErrors", true).toBool();
-  d_2_linear_fit_points = settings.value("/TwoPointsLinearFit", true).toBool();
-  settings.endGroup(); // Fitting
-
-  settings.beginGroup("/ImportASCII");
-  columnSeparator = settings.value("/ColumnSeparator", "\\t").toString();
-  columnSeparator.replace("\\t", "\t").replace("\\s", " ");
-  ignoredLines = settings.value("/IgnoreLines", 0).toInt();
-  renameColumns = settings.value("/RenameColumns", true).toBool();
-  strip_spaces = settings.value("/StripSpaces", false).toBool();
-  simplify_spaces = settings.value("/SimplifySpaces", false).toBool();
-  d_ASCII_file_filter = settings.value("/AsciiFileTypeFilter", "*").toString();
-  d_ASCII_import_locale = settings.value("/AsciiImportLocale", QLocale::system().name()).toString();
-  d_import_dec_separators = settings.value("/UpdateDecSeparators", true).toBool();
-  d_ASCII_import_mode = settings.value("/ImportMode", ImportASCIIDialog::NewTables).toInt();
-  d_ASCII_comment_string = settings.value("/CommentString", "#").toString();
-  d_ASCII_import_comments = settings.value("/ImportComments", false).toBool();
-  d_ASCII_import_read_only = settings.value("/ImportReadOnly", false).toBool();
-  d_ASCII_import_preview = settings.value("/Preview", true).toBool();
-  d_preview_lines = settings.value("/PreviewLines", 100).toInt();
-  d_ASCII_end_line = (EndLineChar)settings.value("/EndLineCharacter", d_ASCII_end_line).toInt();
-  settings.endGroup(); // Import ASCII
-
-  settings.beginGroup("/ExportASCII");
-  d_export_col_separator = settings.value("/ColumnSeparator", "\\t").toString();
-  d_export_col_separator.replace("\\t", "\t").replace("\\s", " ");
-  d_export_col_names = settings.value("/ExportLabels", false).toBool();
-  d_export_col_comment = settings.value("/ExportComments", false).toBool();
-
-  d_export_table_selection = settings.value("/ExportSelection", false).toBool();
-  settings.endGroup(); // ExportASCII
-
-  settings.beginGroup("/ExportImage");
-  d_image_export_filter = settings.value("/ImageFileTypeFilter", ".png").toString();
-  d_export_transparency = settings.value("/ExportTransparency", false).toBool();
-  d_export_quality = settings.value("/ImageQuality", 100).toInt();
-  //	d_export_resolution = settings.value("/Resolution", QPrinter().resolution()).toInt();
-  d_export_color = settings.value("/ExportColor", true).toBool();
-  d_export_vector_size = settings.value("/ExportPageSize", QPrinter::Custom).toInt();
-  d_keep_plot_aspect = settings.value("/KeepAspect", true).toBool();
-  settings.endGroup(); // ExportImage
-
-  settings.beginGroup("/ScriptWindow");
+  settings.endGroup(); // Curves
+
+  settings.beginGroup("/Ticks");
+  majTicksStyle = settings.value("/MajTicksStyle", ScaleDraw::Out).toInt();
+  minTicksStyle = settings.value("/MinTicksStyle", ScaleDraw::Out).toInt();
+  minTicksLength = settings.value("/MinTicksLength", 5).toInt();
+  majTicksLength = settings.value("/MajTicksLength", 9).toInt();
+  settings.endGroup(); // Ticks
+
+  settings.beginGroup("/Legend");
+  legendFrameStyle = settings.value("/FrameStyle", LegendWidget::Line).toInt();
+  legendTextColor = QColor(settings.value("/TextColor", "#000000").value<QColor>()); //default color Qt::black
+  legendBackground = QColor(settings.value("/BackgroundColor", "#ffffff").value<QColor>()); //default color Qt::white
+  legendBackground.setAlpha(settings.value("/Transparency", 0).toInt()); // transparent by default;
+  settings.endGroup(); // Legend
+
+  settings.beginGroup("/Arrows");
+  defaultArrowLineWidth = settings.value("/Width", 1).toDouble();
+  defaultArrowColor = QColor(settings.value("/Color", "#000000").value<QColor>());//default color Qt::black
+  defaultArrowHeadLength = settings.value("/HeadLength", 4).toInt();
+  defaultArrowHeadAngle = settings.value("/HeadAngle", 45).toInt();
+  defaultArrowHeadFill = settings.value("/HeadFill", true).toBool();
+  defaultArrowLineStyle = Graph::getPenStyle(settings.value("/LineStyle", "SolidLine").toString());
+  settings.endGroup(); // Arrows
+  settings.endGroup();
+  /* ----------------- end group 2D Plots --------------------------- */
+
+  /* ----------------- group 3D Plots --------------------------- */
+  settings.beginGroup("/3DPlots");
+  showPlot3DLegend = settings.value("/Legend",true).toBool();
+  showPlot3DProjection = settings.value("/Projection", false).toBool();
+  smooth3DMesh = settings.value("/Antialiasing", false).toBool(); //Mantid
+  plot3DResolution = settings.value ("/Resolution", 1).toInt();
+  orthogonal3DPlots = settings.value("/Orthogonal", false).toBool();
+  autoscale3DPlots = settings.value ("/Autoscale", true).toBool();
+
+  QStringList plot3DFonts = settings.value("/Fonts").toStringList();
+  if (plot3DFonts.size() == 12){
+    plot3DTitleFont=QFont (plot3DFonts[0],plot3DFonts[1].toInt(),plot3DFonts[2].toInt(),plot3DFonts[3].toInt());
+    plot3DNumbersFont=QFont (plot3DFonts[4],plot3DFonts[5].toInt(),plot3DFonts[6].toInt(),plot3DFonts[7].toInt());
+    plot3DAxesFont=QFont (plot3DFonts[8],plot3DFonts[9].toInt(),plot3DFonts[10].toInt(),plot3DFonts[11].toInt());
+  }
+
+  settings.beginGroup("/Colors");
+  plot3DColors = QStringList();
+  plot3DColors << QColor(settings.value("/MaxData", "blue").value<QColor>()).name();
+  plot3DColors << QColor(settings.value("/Labels", "#000000").value<QColor>()).name();
+  plot3DColors << QColor(settings.value("/Mesh", "#000000").value<QColor>()).name();
+  plot3DColors << QColor(settings.value("/Grid", "#000000").value<QColor>()).name();
+  plot3DColors << QColor(settings.value("/MinData", "red").value<QColor>()).name();
+  plot3DColors << QColor(settings.value("/Numbers", "#000000").value<QColor>()).name();
+  plot3DColors << QColor(settings.value("/Axes", "#000000").value<QColor>()).name();
+  plot3DColors << QColor(settings.value("/Background", "#ffffff").value<QColor>()).name();
+  settings.endGroup(); // Colors
+  settings.endGroup();
+  /* ----------------- end group 3D Plots --------------------------- */
+
+  settings.beginGroup("/Fitting");
+  fit_output_precision = settings.value("/OutputPrecision", 15).toInt();
+  pasteFitResultsToPlot = settings.value("/PasteResultsToPlot", false).toBool();
+  writeFitResultsToLog = settings.value("/WriteResultsToLog", true).toBool();
+  generateUniformFitPoints = settings.value("/GenerateFunction", true).toBool();
+  fitPoints = settings.value("/Points", 100).toInt();
+  generatePeakCurves = settings.value("/GeneratePeakCurves", true).toBool();
+  peakCurvesColor = settings.value("/PeaksColor", 2).toInt();//green color
+  fit_scale_errors = settings.value("/ScaleErrors", true).toBool();
+  d_2_linear_fit_points = settings.value("/TwoPointsLinearFit", true).toBool();
+  settings.endGroup(); // Fitting
+
+  settings.beginGroup("/ImportASCII");
+  columnSeparator = settings.value("/ColumnSeparator", "\\t").toString();
+  columnSeparator.replace("\\t", "\t").replace("\\s", " ");
+  ignoredLines = settings.value("/IgnoreLines", 0).toInt();
+  renameColumns = settings.value("/RenameColumns", true).toBool();
+  strip_spaces = settings.value("/StripSpaces", false).toBool();
+  simplify_spaces = settings.value("/SimplifySpaces", false).toBool();
+  d_ASCII_file_filter = settings.value("/AsciiFileTypeFilter", "*").toString();
+  d_ASCII_import_locale = settings.value("/AsciiImportLocale", QLocale::system().name()).toString();
+  d_import_dec_separators = settings.value("/UpdateDecSeparators", true).toBool();
+  d_ASCII_import_mode = settings.value("/ImportMode", ImportASCIIDialog::NewTables).toInt();
+  d_ASCII_comment_string = settings.value("/CommentString", "#").toString();
+  d_ASCII_import_comments = settings.value("/ImportComments", false).toBool();
+  d_ASCII_import_read_only = settings.value("/ImportReadOnly", false).toBool();
+  d_ASCII_import_preview = settings.value("/Preview", true).toBool();
+  d_preview_lines = settings.value("/PreviewLines", 100).toInt();
+  d_ASCII_end_line = (EndLineChar)settings.value("/EndLineCharacter", d_ASCII_end_line).toInt();
+  settings.endGroup(); // Import ASCII
+
+  settings.beginGroup("/ExportASCII");
+  d_export_col_separator = settings.value("/ColumnSeparator", "\\t").toString();
+  d_export_col_separator.replace("\\t", "\t").replace("\\s", " ");
+  d_export_col_names = settings.value("/ExportLabels", false).toBool();
+  d_export_col_comment = settings.value("/ExportComments", false).toBool();
+
+  d_export_table_selection = settings.value("/ExportSelection", false).toBool();
+  settings.endGroup(); // ExportASCII
+
+  settings.beginGroup("/ExportImage");
+  d_image_export_filter = settings.value("/ImageFileTypeFilter", ".png").toString();
+  d_export_transparency = settings.value("/ExportTransparency", false).toBool();
+  d_export_quality = settings.value("/ImageQuality", 100).toInt();
+  //	d_export_resolution = settings.value("/Resolution", QPrinter().resolution()).toInt();
+  d_export_color = settings.value("/ExportColor", true).toBool();
+  d_export_vector_size = settings.value("/ExportPageSize", QPrinter::Custom).toInt();
+  d_keep_plot_aspect = settings.value("/KeepAspect", true).toBool();
+  settings.endGroup(); // ExportImage
+
+  settings.beginGroup("/ScriptWindow");
   d_script_win_pos = settings.value("/pos", QPoint(250,200)).toPoint();
   d_script_win_size = settings.value("/size", QSize(600,660)).toSize();
-  settings.endGroup();
-
-  settings.beginGroup("/ToolBars");
-  d_file_tool_bar = settings.value("/FileToolBar", true).toBool();
-  d_edit_tool_bar = settings.value("/EditToolBar", true).toBool();
-  d_table_tool_bar = settings.value("/TableToolBar", true).toBool();
-  d_column_tool_bar = settings.value("/ColumnToolBar", true).toBool();
-  d_matrix_tool_bar = settings.value("/MatrixToolBar", true).toBool();
-  d_plot_tool_bar = settings.value("/PlotToolBar", true).toBool();
-  d_plot3D_tool_bar = settings.value("/Plot3DToolBar", true).toBool();
-  d_display_tool_bar = settings.value("/DisplayToolBar", false).toBool();
-  d_format_tool_bar = settings.value("/FormatToolBar", true).toBool();
-  settings.endGroup();
-
-  //---------------------------------
-  // Mantid
-
-  bool warning_shown = settings.value("/DuplicationDialogShown", false).toBool();
-
-  //Check for user defined scripts in settings and create menus for them
-  //Top level scripts group
-  settings.beginGroup("CustomScripts");
-
-  // Reference list of custom Interfaces that will be added to the Interfaces menu
-  QStringList user_windows = MantidQt::API::InterfaceManager::Instance().getUserSubWindowKeys();
-  // List it user items that will be moved to the Interfaces menu
-  QStringList duplicated_custom_menu = QStringList();
-
-  foreach(QString menu, settings.childGroups())
-  {
-    addUserMenu(menu);
-    settings.beginGroup(menu);
-    foreach(QString keyName, settings.childKeys())
-    {
-      if ( menu.contains("Interfaces")==0 &&
-          (user_windows.grep(keyName).size() > 0 || pyqt_interfaces.grep(keyName).size() > 0) )
-      {
-        duplicated_custom_menu.append(menu+"/"+keyName);
+  settings.endGroup();
+
+  settings.beginGroup("/ToolBars");
+  d_file_tool_bar = settings.value("/FileToolBar", true).toBool();
+  d_edit_tool_bar = settings.value("/EditToolBar", true).toBool();
+  d_table_tool_bar = settings.value("/TableToolBar", true).toBool();
+  d_column_tool_bar = settings.value("/ColumnToolBar", true).toBool();
+  d_matrix_tool_bar = settings.value("/MatrixToolBar", true).toBool();
+  d_plot_tool_bar = settings.value("/PlotToolBar", true).toBool();
+  d_plot3D_tool_bar = settings.value("/Plot3DToolBar", true).toBool();
+  d_display_tool_bar = settings.value("/DisplayToolBar", false).toBool();
+  d_format_tool_bar = settings.value("/FormatToolBar", true).toBool();
+  settings.endGroup();
+
+  //---------------------------------
+  // Mantid
+
+  bool warning_shown = settings.value("/DuplicationDialogShown", false).toBool();
+
+  //Check for user defined scripts in settings and create menus for them
+  //Top level scripts group
+  settings.beginGroup("CustomScripts");
+
+  // Reference list of custom Interfaces that will be added to the Interfaces menu
+  QStringList user_windows = MantidQt::API::InterfaceManager::Instance().getUserSubWindowKeys();
+  // List it user items that will be moved to the Interfaces menu
+  QStringList duplicated_custom_menu = QStringList();
+
+  foreach(QString menu, settings.childGroups())
+  {
+    addUserMenu(menu);
+    settings.beginGroup(menu);
+    foreach(QString keyName, settings.childKeys())
+    {
+      if ( menu.contains("Interfaces")==0 &&
+          (user_windows.grep(keyName).size() > 0 || pyqt_interfaces.grep(keyName).size() > 0) )
+      {
+        duplicated_custom_menu.append(menu+"/"+keyName);
       }
-      if ( QFileInfo(settings.value(keyName).toString()).exists() )
-        addUserMenuAction(menu, keyName, settings.value(keyName).toString());
-    }
-    settings.endGroup();
-  }
-
-  // Mantid - Remember which interfaces the user explicitely removed
-  // from the Interfaces menu
-  removed_interfaces = settings.value("RemovedInterfaces").toStringList();
-
-  settings.endGroup();
-
-  if (duplicated_custom_menu.size() > 0 && !warning_shown)
-  {
-    QString mess = "The following menus are now part of the Interfaces menu:\n\n";
-    mess += duplicated_custom_menu.join("\n");
-    mess += "\n\nYou may consider removing them from your custom menus.";
-    //FIXME: A nice alternative to showing a message in the log window would
-    // be to pop up a message box. This should be done AFTER MantidPlot has started.
-    //QMessageBox::warning(this, tr("MantidPlot - Menu Warning"), tr(mess.ascii()));
-    Mantid::Kernel::Logger& g_log = Mantid::Kernel::Logger::get("ConfigService");
-    g_log.warning() << mess.ascii() << "\n";
-    settings.setValue("/DuplicationDialogShown", true);
-  }
-
-}
-
-void ApplicationWindow::saveSettings()
-{
-
-#ifdef Q_OS_MAC // Mac
-  QSettings settings(QSettings::IniFormat,QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName());
-#else
-  QSettings settings;//(QSettings::NativeFormat,QSettings::UserScope, "ProIndependent", "MantidPlot");
-#endif
-
-  /* ---------------- group General --------------- */
-  settings.beginGroup("/General");
-
-  settings.beginGroup("/ApplicationGeometry");
-  d_app_rect = QRect(this->pos(), this->size());
-  if (this->isMaximized())
-    d_app_rect = QRect();
-
-  settings.setValue("/x", d_app_rect.x());
-  settings.setValue("/y", d_app_rect.y());
-  settings.setValue("/width", d_app_rect.width());
-  settings.setValue("/height", d_app_rect.height());
-  settings.endGroup();
-
-  settings.setValue("/AutoSearchUpdates", autoSearchUpdates);
-  settings.setValue("/Language", appLanguage);
-  settings.setValue("/ShowWindowsPolicy", show_windows_policy);
-  settings.setValue("/RecentProjects", recentProjects);
-  settings.setValue("/Style", appStyle);
-  settings.setValue("/AutoSave", autoSave);
-  settings.setValue("/AutoSaveTime", autoSaveTime);
-  settings.setValue("/BackupProjects", d_backup_files);
-  settings.setValue("/InitWindow", int(d_init_window_type));
-
-  settings.setValue("/ScriptingLang", defaultScriptingLang);
-  settings.setValue("/ThousandsSeparator", d_thousands_sep);
-  settings.setValue("/Locale", d_locale.name());
-  settings.setValue("/DecimalDigits", d_decimal_digits);
-  settings.setValue("/MatrixUndoStackSize", d_matrix_undo_stack_size);
-  settings.setValue("/EndOfLine", (int)d_eol);
-  settings.setValue("/DockWindows", saveState());
-  settings.setValue("/ExplorerSplitter", explorerSplitter->saveState());
-
-  QStringList applicationFont;
-  applicationFont<<appFont.family();
-  applicationFont<<QString::number(appFont.pointSize());
-  applicationFont<<QString::number(appFont.weight());
-  applicationFont<<QString::number(appFont.italic());
-  settings.setValue("/Font", applicationFont);
-
-  settings.beginGroup("/Dialogs");
-  settings.setValue("/ExtendedOpenDialog", d_extended_open_dialog);
-  settings.setValue("/ExtendedExportDialog", d_extended_export_dialog);
-  settings.setValue("/ExtendedImportAsciiDialog", d_extended_import_ASCII_dialog);
-  settings.setValue("/ExtendedPlotDialog", d_extended_plot_dialog);
-  settings.beginGroup("/AddRemoveCurves");
-  settings.setValue("/Width", d_add_curves_dialog_size.width());
-  settings.setValue("/Height", d_add_curves_dialog_size.height());
-  settings.setValue("/ShowCurrentFolder", d_show_current_folder);
-  settings.endGroup(); // AddRemoveCurves Dialog
-  settings.endGroup(); // Dialogs
-
-  settings.beginGroup("/Colors");
-  settings.setValue("/Workspace", workspaceColor.name());
-  settings.setValue("/Panels", panelsColor.name());
-  settings.setValue("/PanelsText", panelsTextColor.name());
-  settings.endGroup(); // Colors
-
-  settings.beginGroup("/Paths");
-  settings.setValue("/WorkingDir", workingDir);
-  settings.setValue("/TemplatesDir", templatesDir);
-  settings.setValue("/HelpFile", helpFilePath);
-  settings.setValue("/FitPlugins", fitPluginsPath);
-  settings.setValue("/ASCII", asciiDirPath);
-  settings.setValue("/Images", imagesDirPath);
-  settings.setValue("/ScriptsDir", scriptsDirPath);
-  settings.setValue("/FitModelsDir", fitModelsPath);
-  settings.setValue("/CustomActionsDir", customActionsDirPath);
-  settings.setValue("/Translations", d_translations_folder);
-  settings.setValue("/PythonConfigDir", d_python_config_folder);
-  settings.endGroup(); // Paths
-  settings.endGroup();
-  /* ---------------- end group General --------------- */
-
-  settings.beginGroup("/UserFunctions");
-  settings.setValue("/SurfaceFunctions", surfaceFunc);
-  settings.setValue("/xFunctions", xFunctions);
-  settings.setValue("/yFunctions", yFunctions);
-  settings.setValue("/rFunctions", rFunctions);
-  settings.setValue("/thetaFunctions", thetaFunctions);
-  settings.setValue("/ParametricSurfaces", d_param_surface_func);
-  settings.endGroup(); // UserFunctions
-
-  settings.beginGroup("/Confirmations");
-  settings.setValue("/Folder", confirmCloseFolder);
-  settings.setValue("/Table", confirmCloseTable);
-  settings.setValue("/Matrix", confirmCloseMatrix);
-  settings.setValue("/Plot2D", confirmClosePlot2D);
-  settings.setValue("/Plot3D", confirmClosePlot3D);
-  settings.setValue("/Note", confirmCloseNotes);
-  settings.setValue("/RenameTable", d_inform_rename_table);
-  settings.value("/InstrumentWindow", confirmCloseInstrWindow).toBool();
-  settings.endGroup(); // Confirmations
-
-  /* ----------------- group Tables -------------- */
-  settings.beginGroup("/Tables");
-  settings.setValue("/DisplayComments", d_show_table_comments);
-  settings.setValue("/AutoUpdateValues", d_auto_update_table_values);
-  QStringList tableFonts;
-  tableFonts<<tableTextFont.family();
-  tableFonts<<QString::number(tableTextFont.pointSize());
-  tableFonts<<QString::number(tableTextFont.weight());
-  tableFonts<<QString::number(tableTextFont.italic());
-  tableFonts<<tableHeaderFont.family();
-  tableFonts<<QString::number(tableHeaderFont.pointSize());
-  tableFonts<<QString::number(tableHeaderFont.weight());
-  tableFonts<<QString::number(tableHeaderFont.italic());
-  settings.setValue("/Fonts", tableFonts);
-
-  settings.beginGroup("/Colors");
-  settings.setValue("/Background", tableBkgdColor.name());
-  settings.setValue("/Text", tableTextColor.name());
-  settings.setValue("/Header", tableHeaderColor.name());
-  settings.endGroup(); // Colors
-  settings.endGroup();
-  /* ----------------- end group Tables ---------- */
-
-  /* ----------------- group 2D Plots ------------ */
-  settings.beginGroup("/2DPlots");
-  settings.beginGroup("/General");
-  settings.setValue("/Title", titleOn);
-  settings.setValue("/AllAxes", allAxesOn);
-  settings.setValue("/CanvasFrameWidth", canvasFrameWidth);
-  settings.setValue("/Margin", defaultPlotMargin);
-  settings.setValue("/AxesBackbones", drawBackbones);
-  settings.setValue("/AxisXScale", xaxisScale);
-  settings.setValue("/AxisYScale", yaxisScale);
-  settings.setValue("/AxisZScale", zaxisScale);
-  settings.setValue("/AxesLineWidth", axesLineWidth);
-  settings.setValue("/Autoscale", autoscale2DPlots);
-  settings.setValue("/AutoScaleFonts", autoScaleFonts);
-  settings.setValue("/AutoResizeLayers", autoResizeLayers);
-  settings.setValue("/Antialiasing", antialiasing2DPlots);
-  settings.setValue("/ScaleLayersOnPrint", d_scale_plots_on_print);
-  settings.setValue("/PrintCropmarks", d_print_cropmarks);
-
-  QStringList graphFonts;
-  graphFonts<<plotAxesFont.family();
-  graphFonts<<QString::number(plotAxesFont.pointSize());
-  graphFonts<<QString::number(plotAxesFont.weight());
-  graphFonts<<QString::number(plotAxesFont.italic());
-  graphFonts<<plotNumbersFont.family();
-  graphFonts<<QString::number(plotNumbersFont.pointSize());
-  graphFonts<<QString::number(plotNumbersFont.weight());
-  graphFonts<<QString::number(plotNumbersFont.italic());
-  graphFonts<<plotLegendFont.family();
-  graphFonts<<QString::number(plotLegendFont.pointSize());
-  graphFonts<<QString::number(plotLegendFont.weight());
-  graphFonts<<QString::number(plotLegendFont.italic());
-  graphFonts<<plotTitleFont.family();
-  graphFonts<<QString::number(plotTitleFont.pointSize());
-  graphFonts<<QString::number(plotTitleFont.weight());
-  graphFonts<<QString::number(plotTitleFont.italic());
-  settings.setValue("/Fonts", graphFonts);
-
-
-  settings.setValue("/InPlaceEditing", d_in_place_editing);
-  settings.endGroup(); // General
-
-  settings.beginGroup("/Curves");
-  settings.setValue("/Style", defaultCurveStyle);
-  settings.setValue("/LineWidth", defaultCurveLineWidth);
-  settings.setValue("/SymbolSize", defaultSymbolSize);
+      if ( QFileInfo(settings.value(keyName).toString()).exists() )
+        addUserMenuAction(menu, keyName, settings.value(keyName).toString());
+    }
+    settings.endGroup();
+  }
+
+  // Mantid - Remember which interfaces the user explicitely removed
+  // from the Interfaces menu
+  removed_interfaces = settings.value("RemovedInterfaces").toStringList();
+
+  settings.endGroup();
+
+  if (duplicated_custom_menu.size() > 0 && !warning_shown)
+  {
+    QString mess = "The following menus are now part of the Interfaces menu:\n\n";
+    mess += duplicated_custom_menu.join("\n");
+    mess += "\n\nYou may consider removing them from your custom menus.";
+    //FIXME: A nice alternative to showing a message in the log window would
+    // be to pop up a message box. This should be done AFTER MantidPlot has started.
+    //QMessageBox::warning(this, tr("MantidPlot - Menu Warning"), tr(mess.ascii()));
+    Mantid::Kernel::Logger& g_log = Mantid::Kernel::Logger::get("ConfigService");
+    g_log.warning() << mess.ascii() << "\n";
+    settings.setValue("/DuplicationDialogShown", true);
+  }
+
+}
+
+void ApplicationWindow::saveSettings()
+{
+
+#ifdef Q_OS_MAC // Mac
+  QSettings settings(QSettings::IniFormat,QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName());
+#else
+  QSettings settings;//(QSettings::NativeFormat,QSettings::UserScope, "ProIndependent", "MantidPlot");
+#endif
+
+  /* ---------------- group General --------------- */
+  settings.beginGroup("/General");
+
+  settings.beginGroup("/ApplicationGeometry");
+  d_app_rect = QRect(this->pos(), this->size());
+  if (this->isMaximized())
+    d_app_rect = QRect();
+
+  settings.setValue("/x", d_app_rect.x());
+  settings.setValue("/y", d_app_rect.y());
+  settings.setValue("/width", d_app_rect.width());
+  settings.setValue("/height", d_app_rect.height());
+  settings.endGroup();
+
+  settings.setValue("/AutoSearchUpdates", autoSearchUpdates);
+  settings.setValue("/Language", appLanguage);
+  settings.setValue("/ShowWindowsPolicy", show_windows_policy);
+  settings.setValue("/RecentProjects", recentProjects);
+  settings.setValue("/Style", appStyle);
+  settings.setValue("/AutoSave", autoSave);
+  settings.setValue("/AutoSaveTime", autoSaveTime);
+  settings.setValue("/BackupProjects", d_backup_files);
+  settings.setValue("/InitWindow", int(d_init_window_type));
+
+  settings.setValue("/ScriptingLang", defaultScriptingLang);
+  settings.setValue("/ThousandsSeparator", d_thousands_sep);
+  settings.setValue("/Locale", d_locale.name());
+  settings.setValue("/DecimalDigits", d_decimal_digits);
+  settings.setValue("/MatrixUndoStackSize", d_matrix_undo_stack_size);
+  settings.setValue("/EndOfLine", (int)d_eol);
+  settings.setValue("/DockWindows", saveState());
+  settings.setValue("/ExplorerSplitter", explorerSplitter->saveState());
+
+  QStringList applicationFont;
+  applicationFont<<appFont.family();
+  applicationFont<<QString::number(appFont.pointSize());
+  applicationFont<<QString::number(appFont.weight());
+  applicationFont<<QString::number(appFont.italic());
+  settings.setValue("/Font", applicationFont);
+
+  settings.beginGroup("/Dialogs");
+  settings.setValue("/ExtendedOpenDialog", d_extended_open_dialog);
+  settings.setValue("/ExtendedExportDialog", d_extended_export_dialog);
+  settings.setValue("/ExtendedImportAsciiDialog", d_extended_import_ASCII_dialog);
+  settings.setValue("/ExtendedPlotDialog", d_extended_plot_dialog);
+  settings.beginGroup("/AddRemoveCurves");
+  settings.setValue("/Width", d_add_curves_dialog_size.width());
+  settings.setValue("/Height", d_add_curves_dialog_size.height());
+  settings.setValue("/ShowCurrentFolder", d_show_current_folder);
+  settings.endGroup(); // AddRemoveCurves Dialog
+  settings.endGroup(); // Dialogs
+
+  settings.beginGroup("/Colors");
+  settings.setValue("/Workspace", workspaceColor.name());
+  settings.setValue("/Panels", panelsColor.name());
+  settings.setValue("/PanelsText", panelsTextColor.name());
+  settings.endGroup(); // Colors
+
+  settings.beginGroup("/Paths");
+  settings.setValue("/WorkingDir", workingDir);
+  settings.setValue("/TemplatesDir", templatesDir);
+  settings.setValue("/HelpFile", helpFilePath);
+  settings.setValue("/FitPlugins", fitPluginsPath);
+  settings.setValue("/ASCII", asciiDirPath);
+  settings.setValue("/Images", imagesDirPath);
+  settings.setValue("/ScriptsDir", scriptsDirPath);
+  settings.setValue("/FitModelsDir", fitModelsPath);
+  settings.setValue("/CustomActionsDir", customActionsDirPath);
+  settings.setValue("/Translations", d_translations_folder);
+  settings.setValue("/PythonConfigDir", d_python_config_folder);
+  settings.endGroup(); // Paths
+  settings.endGroup();
+  /* ---------------- end group General --------------- */
+
+  settings.beginGroup("/UserFunctions");
+  settings.setValue("/SurfaceFunctions", surfaceFunc);
+  settings.setValue("/xFunctions", xFunctions);
+  settings.setValue("/yFunctions", yFunctions);
+  settings.setValue("/rFunctions", rFunctions);
+  settings.setValue("/thetaFunctions", thetaFunctions);
+  settings.setValue("/ParametricSurfaces", d_param_surface_func);
+  settings.endGroup(); // UserFunctions
+
+  settings.beginGroup("/Confirmations");
+  settings.setValue("/Folder", confirmCloseFolder);
+  settings.setValue("/Table", confirmCloseTable);
+  settings.setValue("/Matrix", confirmCloseMatrix);
+  settings.setValue("/Plot2D", confirmClosePlot2D);
+  settings.setValue("/Plot3D", confirmClosePlot3D);
+  settings.setValue("/Note", confirmCloseNotes);
+  settings.setValue("/RenameTable", d_inform_rename_table);
+  settings.value("/InstrumentWindow", confirmCloseInstrWindow).toBool();
+  settings.endGroup(); // Confirmations
+
+  /* ----------------- group Tables -------------- */
+  settings.beginGroup("/Tables");
+  settings.setValue("/DisplayComments", d_show_table_comments);
+  settings.setValue("/AutoUpdateValues", d_auto_update_table_values);
+  QStringList tableFonts;
+  tableFonts<<tableTextFont.family();
+  tableFonts<<QString::number(tableTextFont.pointSize());
+  tableFonts<<QString::number(tableTextFont.weight());
+  tableFonts<<QString::number(tableTextFont.italic());
+  tableFonts<<tableHeaderFont.family();
+  tableFonts<<QString::number(tableHeaderFont.pointSize());
+  tableFonts<<QString::number(tableHeaderFont.weight());
+  tableFonts<<QString::number(tableHeaderFont.italic());
+  settings.setValue("/Fonts", tableFonts);
+
+  settings.beginGroup("/Colors");
+  settings.setValue("/Background", tableBkgdColor.name());
+  settings.setValue("/Text", tableTextColor.name());
+  settings.setValue("/Header", tableHeaderColor.name());
+  settings.endGroup(); // Colors
+  settings.endGroup();
+  /* ----------------- end group Tables ---------- */
+
+  /* ----------------- group 2D Plots ------------ */
+  settings.beginGroup("/2DPlots");
+  settings.beginGroup("/General");
+  settings.setValue("/Title", titleOn);
+  settings.setValue("/AllAxes", allAxesOn);
+  settings.setValue("/CanvasFrameWidth", canvasFrameWidth);
+  settings.setValue("/Margin", defaultPlotMargin);
+  settings.setValue("/AxesBackbones", drawBackbones);
+  settings.setValue("/AxisXScale", xaxisScale);
+  settings.setValue("/AxisYScale", yaxisScale);
+  settings.setValue("/AxisZScale", zaxisScale);
+  settings.setValue("/AxesLineWidth", axesLineWidth);
+  settings.setValue("/Autoscale", autoscale2DPlots);
+  settings.setValue("/AutoScaleFonts", autoScaleFonts);
+  settings.setValue("/AutoResizeLayers", autoResizeLayers);
+  settings.setValue("/Antialiasing", antialiasing2DPlots);
+  settings.setValue("/ScaleLayersOnPrint", d_scale_plots_on_print);
+  settings.setValue("/PrintCropmarks", d_print_cropmarks);
+
+  QStringList graphFonts;
+  graphFonts<<plotAxesFont.family();
+  graphFonts<<QString::number(plotAxesFont.pointSize());
+  graphFonts<<QString::number(plotAxesFont.weight());
+  graphFonts<<QString::number(plotAxesFont.italic());
+  graphFonts<<plotNumbersFont.family();
+  graphFonts<<QString::number(plotNumbersFont.pointSize());
+  graphFonts<<QString::number(plotNumbersFont.weight());
+  graphFonts<<QString::number(plotNumbersFont.italic());
+  graphFonts<<plotLegendFont.family();
+  graphFonts<<QString::number(plotLegendFont.pointSize());
+  graphFonts<<QString::number(plotLegendFont.weight());
+  graphFonts<<QString::number(plotLegendFont.italic());
+  graphFonts<<plotTitleFont.family();
+  graphFonts<<QString::number(plotTitleFont.pointSize());
+  graphFonts<<QString::number(plotTitleFont.weight());
+  graphFonts<<QString::number(plotTitleFont.italic());
+  settings.setValue("/Fonts", graphFonts);
+
+
+  settings.setValue("/InPlaceEditing", d_in_place_editing);
+  settings.endGroup(); // General
+
+  settings.beginGroup("/Curves");
+  settings.setValue("/Style", defaultCurveStyle);
+  settings.setValue("/LineWidth", defaultCurveLineWidth);
+  settings.setValue("/SymbolSize", defaultSymbolSize);
   settings.setValue("/ApplyMantid", applyCurveStyleToMantid);
-  settings.endGroup(); // Curves
-
-  settings.beginGroup("/Ticks");
-  settings.setValue ("/MajTicksStyle", majTicksStyle);
-  settings.setValue ("/MinTicksStyle", minTicksStyle);
-  settings.setValue("/MinTicksLength", minTicksLength);
-  settings.setValue("/MajTicksLength", majTicksLength);
-  settings.endGroup(); // Ticks
-
-  settings.beginGroup("/Legend");
-  settings.setValue("/FrameStyle", legendFrameStyle);
-  settings.setValue("/TextColor", legendTextColor.name());
-  settings.setValue("/BackgroundColor", legendBackground.name());
-  settings.setValue("/Transparency", legendBackground.alpha());
-  settings.endGroup(); // Legend
-
-  settings.beginGroup("/Arrows");
-  settings.setValue("/Width", defaultArrowLineWidth);
-  settings.setValue("/Color", defaultArrowColor.name());
-  settings.setValue("/HeadLength", defaultArrowHeadLength);
-  settings.setValue("/HeadAngle", defaultArrowHeadAngle);
-  settings.setValue("/HeadFill", defaultArrowHeadFill);
-  settings.setValue("/LineStyle", Graph::penStyleName(defaultArrowLineStyle));
-  settings.endGroup(); // Arrows
-  settings.endGroup();
-  /* ----------------- end group 2D Plots -------- */
-
-  /* ----------------- group 3D Plots ------------ */
-  settings.beginGroup("/3DPlots");
-  settings.setValue("/Legend", showPlot3DLegend);
-  settings.setValue("/Projection", showPlot3DProjection);
-  settings.setValue("/Antialiasing", smooth3DMesh);
-  settings.setValue("/Resolution", plot3DResolution);
-  settings.setValue("/Orthogonal", orthogonal3DPlots);
-  settings.setValue("/Autoscale", autoscale3DPlots);
-
-  QStringList plot3DFonts;
-  plot3DFonts<<plot3DTitleFont.family();
-  plot3DFonts<<QString::number(plot3DTitleFont.pointSize());
-  plot3DFonts<<QString::number(plot3DTitleFont.weight());
-  plot3DFonts<<QString::number(plot3DTitleFont.italic());
-  plot3DFonts<<plot3DNumbersFont.family();
-  plot3DFonts<<QString::number(plot3DNumbersFont.pointSize());
-  plot3DFonts<<QString::number(plot3DNumbersFont.weight());
-  plot3DFonts<<QString::number(plot3DNumbersFont.italic());
-  plot3DFonts<<plot3DAxesFont.family();
-  plot3DFonts<<QString::number(plot3DAxesFont.pointSize());
-  plot3DFonts<<QString::number(plot3DAxesFont.weight());
-  plot3DFonts<<QString::number(plot3DAxesFont.italic());
-  settings.setValue("/Fonts", plot3DFonts);
-
-  settings.beginGroup("/Colors");
-  settings.setValue("/MaxData", plot3DColors[0]);
-  settings.setValue("/Labels", plot3DColors[1]);
-  settings.setValue("/Mesh", plot3DColors[2]);
-  settings.setValue("/Grid", plot3DColors[3]);
-  settings.setValue("/MinData", plot3DColors[4]);
-  settings.setValue("/Numbers", plot3DColors[5]);
-  settings.setValue("/Axes", plot3DColors[6]);
-  settings.setValue("/Background", plot3DColors[7]);
-  settings.endGroup(); // Colors
-  settings.endGroup();
-  /* ----------------- end group 2D Plots -------- */
-
-  settings.beginGroup("/Fitting");
-  settings.setValue("/OutputPrecision", fit_output_precision);
-  settings.setValue("/PasteResultsToPlot", pasteFitResultsToPlot);
-  settings.setValue("/WriteResultsToLog", writeFitResultsToLog);
-  settings.setValue("/GenerateFunction", generateUniformFitPoints);
-  settings.setValue("/Points", fitPoints);
-  settings.setValue("/GeneratePeakCurves", generatePeakCurves);
-  settings.setValue("/PeaksColor", peakCurvesColor);
-  settings.setValue("/ScaleErrors", fit_scale_errors);
-  settings.setValue("/TwoPointsLinearFit", d_2_linear_fit_points);
-  settings.endGroup(); // Fitting
-
-  settings.beginGroup("/ImportASCII");
-  QString sep = columnSeparator;
-  settings.setValue("/ColumnSeparator", sep.replace("\t", "\\t").replace(" ", "\\s"));
-  settings.setValue("/IgnoreLines", ignoredLines);
-  settings.setValue("/RenameColumns", renameColumns);
-  settings.setValue("/StripSpaces", strip_spaces);
-  settings.setValue("/SimplifySpaces", simplify_spaces);
-  settings.setValue("/AsciiFileTypeFilter", d_ASCII_file_filter);
-  settings.setValue("/AsciiImportLocale", d_ASCII_import_locale.name());
-  settings.setValue("/UpdateDecSeparators", d_import_dec_separators);
-  settings.setValue("/ImportMode", d_ASCII_import_mode);
-  settings.setValue("/CommentString", d_ASCII_comment_string);
-  settings.setValue("/ImportComments", d_ASCII_import_comments);
-  settings.setValue("/ImportReadOnly", d_ASCII_import_read_only);
-  settings.setValue("/Preview", d_ASCII_import_preview);
-  settings.setValue("/PreviewLines", d_preview_lines);
-  settings.setValue("/EndLineCharacter", (int)d_ASCII_end_line);
-  settings.endGroup(); // ImportASCII
-
-  settings.beginGroup("/ExportASCII");
-  sep = d_export_col_separator;
-  settings.setValue("/ColumnSeparator", sep.replace("\t", "\\t").replace(" ", "\\s"));
-  settings.setValue("/ExportLabels", d_export_col_names);
-  settings.setValue("/ExportComments", d_export_col_comment);
-  settings.setValue("/ExportSelection", d_export_table_selection);
-  settings.endGroup(); // ExportASCII
-
-  settings.beginGroup("/ExportImage");
-  settings.setValue("/ImageFileTypeFilter", d_image_export_filter);
-  settings.setValue("/ExportTransparency", d_export_transparency);
-  settings.setValue("/ImageQuality", d_export_quality);
-  settings.setValue("/Resolution", d_export_resolution);
-  settings.setValue("/ExportColor", d_export_color);
-  settings.setValue("/ExportPageSize", d_export_vector_size);
-  settings.setValue("/KeepAspect", d_keep_plot_aspect);
-  settings.endGroup(); // ExportImage
-
+  settings.endGroup(); // Curves
+
+  settings.beginGroup("/Ticks");
+  settings.setValue ("/MajTicksStyle", majTicksStyle);
+  settings.setValue ("/MinTicksStyle", minTicksStyle);
+  settings.setValue("/MinTicksLength", minTicksLength);
+  settings.setValue("/MajTicksLength", majTicksLength);
+  settings.endGroup(); // Ticks
+
+  settings.beginGroup("/Legend");
+  settings.setValue("/FrameStyle", legendFrameStyle);
+  settings.setValue("/TextColor", legendTextColor.name());
+  settings.setValue("/BackgroundColor", legendBackground.name());
+  settings.setValue("/Transparency", legendBackground.alpha());
+  settings.endGroup(); // Legend
+
+  settings.beginGroup("/Arrows");
+  settings.setValue("/Width", defaultArrowLineWidth);
+  settings.setValue("/Color", defaultArrowColor.name());
+  settings.setValue("/HeadLength", defaultArrowHeadLength);
+  settings.setValue("/HeadAngle", defaultArrowHeadAngle);
+  settings.setValue("/HeadFill", defaultArrowHeadFill);
+  settings.setValue("/LineStyle", Graph::penStyleName(defaultArrowLineStyle));
+  settings.endGroup(); // Arrows
+  settings.endGroup();
+  /* ----------------- end group 2D Plots -------- */
+
+  /* ----------------- group 3D Plots ------------ */
+  settings.beginGroup("/3DPlots");
+  settings.setValue("/Legend", showPlot3DLegend);
+  settings.setValue("/Projection", showPlot3DProjection);
+  settings.setValue("/Antialiasing", smooth3DMesh);
+  settings.setValue("/Resolution", plot3DResolution);
+  settings.setValue("/Orthogonal", orthogonal3DPlots);
+  settings.setValue("/Autoscale", autoscale3DPlots);
+
+  QStringList plot3DFonts;
+  plot3DFonts<<plot3DTitleFont.family();
+  plot3DFonts<<QString::number(plot3DTitleFont.pointSize());
+  plot3DFonts<<QString::number(plot3DTitleFont.weight());
+  plot3DFonts<<QString::number(plot3DTitleFont.italic());
+  plot3DFonts<<plot3DNumbersFont.family();
+  plot3DFonts<<QString::number(plot3DNumbersFont.pointSize());
+  plot3DFonts<<QString::number(plot3DNumbersFont.weight());
+  plot3DFonts<<QString::number(plot3DNumbersFont.italic());
+  plot3DFonts<<plot3DAxesFont.family();
+  plot3DFonts<<QString::number(plot3DAxesFont.pointSize());
+  plot3DFonts<<QString::number(plot3DAxesFont.weight());
+  plot3DFonts<<QString::number(plot3DAxesFont.italic());
+  settings.setValue("/Fonts", plot3DFonts);
+
+  settings.beginGroup("/Colors");
+  settings.setValue("/MaxData", plot3DColors[0]);
+  settings.setValue("/Labels", plot3DColors[1]);
+  settings.setValue("/Mesh", plot3DColors[2]);
+  settings.setValue("/Grid", plot3DColors[3]);
+  settings.setValue("/MinData", plot3DColors[4]);
+  settings.setValue("/Numbers", plot3DColors[5]);
+  settings.setValue("/Axes", plot3DColors[6]);
+  settings.setValue("/Background", plot3DColors[7]);
+  settings.endGroup(); // Colors
+  settings.endGroup();
+  /* ----------------- end group 2D Plots -------- */
+
+  settings.beginGroup("/Fitting");
+  settings.setValue("/OutputPrecision", fit_output_precision);
+  settings.setValue("/PasteResultsToPlot", pasteFitResultsToPlot);
+  settings.setValue("/WriteResultsToLog", writeFitResultsToLog);
+  settings.setValue("/GenerateFunction", generateUniformFitPoints);
+  settings.setValue("/Points", fitPoints);
+  settings.setValue("/GeneratePeakCurves", generatePeakCurves);
+  settings.setValue("/PeaksColor", peakCurvesColor);
+  settings.setValue("/ScaleErrors", fit_scale_errors);
+  settings.setValue("/TwoPointsLinearFit", d_2_linear_fit_points);
+  settings.endGroup(); // Fitting
+
+  settings.beginGroup("/ImportASCII");
+  QString sep = columnSeparator;
+  settings.setValue("/ColumnSeparator", sep.replace("\t", "\\t").replace(" ", "\\s"));
+  settings.setValue("/IgnoreLines", ignoredLines);
+  settings.setValue("/RenameColumns", renameColumns);
+  settings.setValue("/StripSpaces", strip_spaces);
+  settings.setValue("/SimplifySpaces", simplify_spaces);
+  settings.setValue("/AsciiFileTypeFilter", d_ASCII_file_filter);
+  settings.setValue("/AsciiImportLocale", d_ASCII_import_locale.name());
+  settings.setValue("/UpdateDecSeparators", d_import_dec_separators);
+  settings.setValue("/ImportMode", d_ASCII_import_mode);
+  settings.setValue("/CommentString", d_ASCII_comment_string);
+  settings.setValue("/ImportComments", d_ASCII_import_comments);
+  settings.setValue("/ImportReadOnly", d_ASCII_import_read_only);
+  settings.setValue("/Preview", d_ASCII_import_preview);
+  settings.setValue("/PreviewLines", d_preview_lines);
+  settings.setValue("/EndLineCharacter", (int)d_ASCII_end_line);
+  settings.endGroup(); // ImportASCII
+
+  settings.beginGroup("/ExportASCII");
+  sep = d_export_col_separator;
+  settings.setValue("/ColumnSeparator", sep.replace("\t", "\\t").replace(" ", "\\s"));
+  settings.setValue("/ExportLabels", d_export_col_names);
+  settings.setValue("/ExportComments", d_export_col_comment);
+  settings.setValue("/ExportSelection", d_export_table_selection);
+  settings.endGroup(); // ExportASCII
+
+  settings.beginGroup("/ExportImage");
+  settings.setValue("/ImageFileTypeFilter", d_image_export_filter);
+  settings.setValue("/ExportTransparency", d_export_transparency);
+  settings.setValue("/ImageQuality", d_export_quality);
+  settings.setValue("/Resolution", d_export_resolution);
+  settings.setValue("/ExportColor", d_export_color);
+  settings.setValue("/ExportPageSize", d_export_vector_size);
+  settings.setValue("/KeepAspect", d_keep_plot_aspect);
+  settings.endGroup(); // ExportImage
+
+
+  if(m_scriptInterpreter ) m_scriptInterpreter->saveSettings();
+  if( scriptingWindow ) 
+  {
+    settings.beginGroup("/ScriptWindow");
+    // Geometry is applied by the app window
+    settings.setValue("/size", d_script_win_size);
+    settings.setValue("/pos", d_script_win_pos);
+    settings.endGroup();
+    // Other specific settings
+    scriptingWindow->saveSettings();
+  }
+
+  settings.beginGroup("/ToolBars");
+  settings.setValue("/FileToolBar", d_file_tool_bar);
+  settings.setValue("/EditToolBar", d_edit_tool_bar);
+  settings.setValue("/TableToolBar", d_table_tool_bar);
+  settings.setValue("/ColumnToolBar", d_column_tool_bar);
+  settings.setValue("/MatrixToolBar", d_matrix_tool_bar);
+  settings.setValue("/PlotToolBar", d_plot_tool_bar);
+  settings.setValue("/Plot3DToolBar", d_plot3D_tool_bar);
+  settings.setValue("/DisplayToolBar", d_display_tool_bar);
+  settings.setValue("/FormatToolBar", d_format_tool_bar);
+  settings.endGroup();
+
+  //Save mantid settings
+  mantidUI->saveSettings();
+
+  //--------------------------------------
+  // Mantid - Save custom scripts
+  settings.beginGroup("CustomScripts");
+  settings.remove("");
+  foreach( QMenu* menu, d_user_menus )
+  {
+    settings.beginGroup(menu->title());
+    foreach( QAction* action, menu->actions() )
+    {
+      settings.setValue(action->text(), action->data().toString());
+    }
+    settings.endGroup();
+  }
+
+  // Mantid - Remember which interfaces the user explicitely removed
+  // from the Interfaces menu
+  settings.setValue("RemovedInterfaces", removed_interfaces);
+
+  settings.endGroup();
+  //-----------------------------------
+}
+
+void ApplicationWindow::exportGraph()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return;
+
+  MultiLayer *plot2D = 0;
+  Graph3D *plot3D = 0;
+  if(w->isA("MultiLayer")){
+    plot2D = (MultiLayer*)w;
+    if (plot2D->isEmpty()){
+      QMessageBox::critical(this, tr("MantidPlot - Export Error"),//Mantid
+          tr("<h4>There are no plot layers available in this window!</h4>"));
+      return;
+    }
+  } else if (w->isA("Graph3D"))
+    plot3D = (Graph3D*)w;
+  else
+    return;
+
+  ImageExportDialog *ied = new ImageExportDialog(this, plot2D!=NULL, d_extended_export_dialog);
+  ied->setDir(workingDir);
+  ied->selectFilter(d_image_export_filter);
+  if ( ied->exec() != QDialog::Accepted )
+    return;
+  workingDir = ied->directory().path();
+  if (ied->selectedFiles().isEmpty())
+    return;
+
+  QString selected_filter = ied->selectedFilter();
+  QString file_name = ied->selectedFiles()[0];
+  QFileInfo file_info(file_name);
+  if (!file_info.fileName().contains("."))
+    file_name.append(selected_filter.remove("*"));
+
+  QFile file(file_name);
+  if (!file.open( QIODevice::WriteOnly )){
+    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));
+    return;
+  }
+  file.close();
+
+  if (selected_filter.contains(".eps") || selected_filter.contains(".pdf") ||
+      selected_filter.contains(".ps") || selected_filter.contains(".svg")) {
+    if (plot3D)
+      plot3D->exportVector(file_name);
+    else if (plot2D){
+      if (selected_filter.contains(".svg"))
+        plot2D->exportSVG(file_name);
+      else
+        plot2D->exportVector(file_name, ied->resolution(), ied->color(), ied->keepAspect(), ied->pageSize());
+    }
+  } else {
+    QList<QByteArray> list = QImageWriter::supportedImageFormats();
+    for (int i=0; i<(int)list.count(); i++){
+      if (selected_filter.contains("." + (list[i]).lower())) {
+        if (plot2D)
+          plot2D->exportImage(file_name, ied->quality(), ied->transparency());
+        else if (plot3D)
+          plot3D->exportImage(file_name, ied->quality(), ied->transparency());
+      }
+    }
+  }
+}
+
+void ApplicationWindow::exportLayer()
+{
+  MdiSubWindow *w = activeWindow(MultiLayerWindow);
+  if (!w)
+    return;
+
+  Graph* g = ((MultiLayer*)w)->activeGraph();
+  if (!g)
+    return;
+
+  ImageExportDialog *ied = new ImageExportDialog(this, g!=NULL, d_extended_export_dialog);
+  ied->setDir(workingDir);
+  ied->selectFilter(d_image_export_filter);
+  if ( ied->exec() != QDialog::Accepted )
+    return;
+  workingDir = ied->directory().path();
+  if (ied->selectedFiles().isEmpty())
+    return;
+
+  QString selected_filter = ied->selectedFilter();
+  QString file_name = ied->selectedFiles()[0];
+  QFileInfo file_info(file_name);
+  if (!file_info.fileName().contains("."))
+    file_name.append(selected_filter.remove("*"));
+
+  QFile file(file_name);
+  if ( !file.open( QIODevice::WriteOnly ) ){
+    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));
+    return;
+  }
+  file.close();
+
+  if (selected_filter.contains(".eps") || selected_filter.contains(".pdf") || selected_filter.contains(".ps"))
+    g->exportVector(file_name, ied->resolution(), ied->color(), ied->keepAspect(), ied->pageSize());
+  else if (selected_filter.contains(".svg"))
+    g->exportSVG(file_name);
+  /*else if (selected_filter.contains(".emf"))
+		g->exportEMF(file_name);*/
+  else {
+    QList<QByteArray> list = QImageWriter::supportedImageFormats();
+    for (int i=0; i<(int)list.count(); i++)
+      if (selected_filter.contains("."+(list[i]).lower()))
+        g->exportImage(file_name, ied->quality(), ied->transparency());
+  }
+}
+
+void ApplicationWindow::exportAllGraphs()
+{
+  ImageExportDialog *ied = new ImageExportDialog(this, true, d_extended_export_dialog);
+  ied->setWindowTitle(tr("Choose a directory to export the graphs to"));
+  QStringList tmp = ied->filters();
+  ied->setFileMode(QFileDialog::Directory);
+  ied->setFilters(tmp);
+  ied->setLabelText(QFileDialog::FileType, tr("Output format:"));
+  ied->setLabelText(QFileDialog::FileName, tr("Directory:"));
+
+  ied->setDir(workingDir);
+  ied->selectFilter(d_image_export_filter);
+
+  if ( ied->exec() != QDialog::Accepted )
+    return;
+  workingDir = ied->directory().path();
+  if (ied->selectedFiles().isEmpty())
+    return;
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  QString output_dir = ied->selectedFiles()[0];
+  QString file_suffix = ied->selectedFilter();
+  file_suffix.lower();
+  file_suffix.remove("*");
+
+  bool confirm_overwrite = true;
+  MultiLayer *plot2D;
+  Graph3D *plot3D;
+
+  QList<MdiSubWindow *> windows = windowsList();
+  foreach(MdiSubWindow *w, windows){
+    if (w->isA("MultiLayer")) {
+      plot3D = 0;
+      plot2D = (MultiLayer *)w;
+      if (plot2D->isEmpty()) {
+        QApplication::restoreOverrideCursor();
+        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()));
+        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+        continue;
+      }
+    } else if (w->isA("Graph3D")) {
+      plot2D = 0;
+      plot3D = (Graph3D *)w;
+    } else
+      continue;
+
+    QString file_name = output_dir + "/" + w->objectName() + file_suffix;
+    QFile f(file_name);
+    if (f.exists() && confirm_overwrite) {
+      QApplication::restoreOverrideCursor();
+
+      QString msg = tr("A file called: <p><b>%1</b><p>already exists. ""Do you want to overwrite it?").arg(file_name);
+      QMessageBox msgBox(QMessageBox::Question, tr("MantidPlot - Overwrite file?"), msg,//Mantid
+          QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::Cancel,
+          (ApplicationWindow *)this);
+      msgBox.exec();
+      switch(msgBox.standardButton(msgBox.clickedButton())){
+      case QMessageBox::Yes:
+        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+        break;
+      case QMessageBox::YesToAll:
+        confirm_overwrite = false;
+        break;
+      case QMessageBox::No:
+        confirm_overwrite = true;
+        continue;
+        break;
+      case QMessageBox::Cancel:
+        return;
+        break;
+      default:
+        break;
+      }
+    }
+    if ( !f.open( QIODevice::WriteOnly ) ) {
+      QApplication::restoreOverrideCursor();
+      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));
+      return;
+    }
+    f.close();
+
+    if (file_suffix.contains(".eps") || file_suffix.contains(".pdf") ||
+        file_suffix.contains(".ps") || file_suffix.contains(".svg")) {
+      if (plot3D)
+        plot3D->exportVector(file_name);
+      else if (plot2D){
+        if (file_suffix.contains(".svg"))
+          plot2D->exportSVG(file_name);
+        else
+          plot2D->exportVector(file_name, ied->resolution(), ied->color(), ied->keepAspect(), ied->pageSize());
+      }
+    } else {
+      QList<QByteArray> list = QImageWriter::supportedImageFormats();
+      for (int i=0; i<(int)list.count(); i++){
+        if (file_suffix.contains("." + (list[i]).lower())) {
+          if (plot2D)
+            plot2D->exportImage(file_name, ied->quality(), ied->transparency());
+          else if (plot3D)
+            plot3D->exportImage(file_name, ied->quality(), ied->transparency());
+        }
+      }
+    }
+  }
+  QApplication::restoreOverrideCursor();
+}
+
+QString ApplicationWindow::windowGeometryInfo(MdiSubWindow *w)
+{
+  QString s = "geometry\t";
+  if (w->status() == MdiSubWindow::Maximized){
+    if (w == w->folder()->activeWindow())
+      return s + "maximized\tactive\n";
+    else
+      return s + "maximized\n";
+  }
+
+  s += QString::number(w->x()) + "\t";
+  s += QString::number(w->y()) + "\t";
+  if (w->status() != MdiSubWindow::Minimized){
+    s += QString::number(w->width()) + "\t";
+    s += QString::number(w->height()) + "\t";
+  } else {
+    s += QString::number(w->minRestoreSize().width()) + "\t";
+    s += QString::number(w->minRestoreSize().height()) + "\t";
+    s += "minimized\t";
+  }
+
+  bool hide = hidden(w);
+  if (w == w->folder()->activeWindow() && !hide)
+    s+="active\n";
+  else if(hide)
+    s+="hidden\n";
+  else
+    s+="\n";
+  return s;
+}
+
+void ApplicationWindow::restoreWindowGeometry(ApplicationWindow *app, MdiSubWindow *w, const QString s)
+{
+  if(!w) return ;
+  w->hide();
+
+  QString caption = w->objectName();
+  if (s.contains ("minimized")) {
+    QStringList lst = s.split("\t");
+    if (lst.count() > 4){
+      int width = lst[3].toInt();
+      int height = lst[4].toInt();
+      if(width > 0 && height > 0)
+        w->resize(width, height);
+    }
+    w->setStatus(MdiSubWindow::Minimized);
+    app->setListView(caption, tr("Minimized"));
+  } else if (s.contains ("maximized")){
+    w->setStatus(MdiSubWindow::Maximized);
+    app->setListView(caption, tr("Maximized"));
+  } else {
+    QStringList lst = s.split("\t");
+    if (lst.count() > 4){
+      w->resize(lst[3].toInt(), lst[4].toInt());
+      w->move(lst[1].toInt(), lst[2].toInt());
+    }
+    w->setStatus(MdiSubWindow::Normal);
+    if (lst.count() > 5) {
+      if (lst[5] == "hidden")
+        app->hideWindow(w);
+    }
+  }
+
+  if (s.contains ("active")) {
+    Folder *f = w->folder();
+    if (f)
+      f->setActiveWindow(w);
+  }
+}
+
+Folder* ApplicationWindow::projectFolder()
+{
+  return ((FolderListItem *)folders->firstChild())->folder();
+}
+
+bool ApplicationWindow::saveProject(bool compress)
+{
+  if (projectname == "untitled" || projectname.endsWith(".opj", Qt::CaseInsensitive) ||
+      projectname.endsWith(".ogm", Qt::CaseInsensitive) || projectname.endsWith(".ogw", Qt::CaseInsensitive)
+      || projectname.endsWith(".ogg", Qt::CaseInsensitive))
+  {
+    saveProjectAs();
+    return true;;
+  }
+
+#ifdef QTIPLOT_DEMO
+  showDemoVersionMessage();
+  return false;
+#endif
+
+  saveFolder(projectFolder(), projectname, compress);
+
+  setWindowTitle("MantidPlot - " + projectname);
+  savedProject();
+
+  if (autoSave){
+    if (savingTimerId)
+      killTimer(savingTimerId);
+    savingTimerId=startTimer(autoSaveTime*60000);
+  } else
+    savingTimerId=0;
+
+  QApplication::restoreOverrideCursor();
+  return true;
+}
+void ApplicationWindow::savetoNexusFile()
+{
+  QString filter = tr("Mantid Files")+" (*.nxs *.nx5 *.xml);;";
+  QString selectedFilter;
+  QString fileDir=MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory();
+  if(fileDir.isEmpty())
+  {fileDir="C\\Mantid\\Test\\Nexus";
+  }
+  QString fileName = QFileDialog::getSaveFileName(this, tr("Save File As"), fileDir, filter, &selectedFilter);
+  if ( !fileName.isEmpty() ){
+    std::string wsName;
+    MdiSubWindow *w = activeWindow();
+    if(w)
+    {
+      if(w->isA("MantidMatrix"))
+      {
+        wsName=((MantidMatrix*)w)->getWorkspaceName();
+      }
+    }
+    else
+    {
+      wsName=m_nexusInputWSName.toStdString();
+    }
+    if(!Mantid::API::AnalysisDataService::Instance().doesExist(wsName))
+    {
+      throw std::runtime_error("Invalid input workspace for SaveNexus");
+    }
+
+    savedatainNexusFormat(wsName,fileName.toStdString());
+
+    MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(QFileInfo(fileName).absoluteDir().path());
+
+  }
+}
+
+void ApplicationWindow::loadDataFile()
+{
+  if(mantidUI)
+  {
+    mantidUI->executeAlgorithm("Load",-1);
+  }
+}
+void ApplicationWindow::saveProjectAs(const QString& fileName, bool compress)
+{
+#ifdef QTIPLOT_DEMO
+  showDemoVersionMessage();
+  return;
+#endif
+
+  QString fn = fileName;
+  if (fileName.isEmpty()){
+    QString filter = tr("MantidPlot project")+" (*.mantid);;"; //tr("QtiPlot project")+" (*.qti);;";
+    filter += tr("Compressed MantidPlot project")+" (*.mantid.gz)";
+
+    QString selectedFilter;
+    fn = QFileDialog::getSaveFileName(this, tr("Save Project As"), workingDir, filter, &selectedFilter);
+    if (selectedFilter.contains(".gz"))
+      compress = true;
+  }
+
+  if ( !fn.isEmpty() ){
+    QFileInfo fi(fn);
+    workingDir = fi.dirPath(true);
+    QString baseName = fi.fileName();
+    if (!baseName.contains("."))
+      //fn.append(".qti");
+      fn.append(".mantid");
+
+    projectname = fn;
+    if (saveProject(compress)){
+      recentProjects.remove(projectname);
+      recentProjects.push_front(projectname);
+      updateRecentProjectsList();
+
+      QFileInfo fi(fn);
+      QString baseName = fi.baseName();
+      FolderListItem *item = (FolderListItem *)folders->firstChild();
+      item->setText(0, baseName);
+      item->folder()->setObjectName(baseName);
+    }
+  }
+}
+
+void ApplicationWindow::saveNoteAs()
+{
+  Note* w = (Note*)activeWindow(NoteWindow);
+  if (!w)
+    return;
+  w->exportASCII();
+}
+
+void ApplicationWindow::saveAsTemplate(MdiSubWindow* w, const QString& fileName)
+{
+  if (!w) {
+    w = activeWindow();
+    if (!w)
+      return;
+  }
+
+  QString fn = fileName;
+  if (fn.isEmpty()){
+    QString filter;
+    if (w->isA("Matrix"))
+      filter = tr("MantidPlot Matrix Template")+" (*.qmt)";
+    else if (w->isA("MultiLayer"))
+      filter = tr("MantidPlot 2D Graph Template")+" (*.qpt)";
+    else if (w->inherits("Table"))
+      filter = tr("MantidPlot Table Template")+" (*.qtt)";
+    else if (w->isA("Graph3D"))
+      filter = tr("MantidPlot 3D Surface Template")+" (*.qst)";
+
+    QString selectedFilter;
+    fn = QFileDialog::getSaveFileName(this, tr("Save Window As Template"), templatesDir + "/" + w->objectName(), filter, &selectedFilter);
+
+    if (!fn.isEmpty()){
+      QFileInfo fi(fn);
+      workingDir = fi.dirPath(true);
+      QString baseName = fi.fileName();
+      if (!baseName.contains(".")){
+        selectedFilter = selectedFilter.right(5).left(4);
+        fn.append(selectedFilter);
+      }
+    } else
+      return;
+  }
+
+  QFile f(fn);
+  if ( !f.open( QIODevice::WriteOnly ) ){
+    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(fn));
+    return;
+  }
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  QString text = "MantidPlot " + QString::number(maj_version)+"."+ QString::number(min_version)+"."+
+      QString::number(patch_version) + " template file\n";
+  text += w->saveAsTemplate(windowGeometryInfo(w));
+  QTextStream t( &f );
+  t.setEncoding(QTextStream::UnicodeUTF8);
+  t << text;
+  f.close();
+  QApplication::restoreOverrideCursor();
+}
+
+void ApplicationWindow::rename()
+{
+  MdiSubWindow* m = activeWindow();
+  if (!m)
+    return;
+
+  RenameWindowDialog *rwd = new RenameWindowDialog(this);
+  rwd->setAttribute(Qt::WA_DeleteOnClose);
+  rwd->setWidget(m);
+  rwd->exec();
+}
+
+void ApplicationWindow::renameWindow()
+{
+  WindowListItem *it = (WindowListItem *)lv->currentItem();
+  MdiSubWindow *w = it->window();
+  if (!w)
+    return;
+
+  RenameWindowDialog *rwd = new RenameWindowDialog(this);
+  rwd->setAttribute(Qt::WA_DeleteOnClose);
+  rwd->setWidget(w);
+  rwd->exec();
+}
+
+void ApplicationWindow::renameWindow(Q3ListViewItem *item, int, const QString &text)
+{
+  if (!item)
+    return;
+
+  MdiSubWindow *w = ((WindowListItem *)item)->window();
+  if (!w || text == w->objectName())
+    return;
+
+  if(!setWindowName(w, text))
+    item->setText(0, w->objectName());
+}
+
+bool ApplicationWindow::setWindowName(MdiSubWindow *w, const QString &text)
+{
+  if (!w)
+    return false;
+
+  QString name = w->objectName();
+  if (name == text)
+    return true;
+
+  QString newName = text;
+  newName.replace("-", "_");
+  if (newName.isEmpty()){
+    QMessageBox::critical(this, tr("MantidPlot - Error"), tr("Please enter a valid name!"));//Mantid
+    return false;
+  } else if (newName.contains(QRegExp("\\W"))){
+    QMessageBox::critical(this, tr("MantidPlot - Error"),//Mantid
+        tr("The name you chose is not valid: only letters and digits are allowed!")+
+        "<p>" + tr("Please choose another name!"));
+    return false;
+  }
+
+  newName.replace("_", "-");
+
+  while(alreadyUsedName(newName)){
+    QMessageBox::critical(this, tr("MantidPlot - Error"), tr("Name <b>%1</b> already exists!").arg(newName)+//Mantid
+        "<p>"+tr("Please choose another name!")+
+        "<p>"+tr("Warning: for internal consistency reasons the underscore character is replaced with a minus sign."));
+    return false;
+  }
+
+  if (w->inherits("Table"))
+    updateTableNames(name, newName);
+  else if (w->isA("Matrix"))
+    changeMatrixName(name, newName);
+
+  w->setCaptionPolicy(w->captionPolicy());
+  w->setName(newName);
+  renameListViewItem(name, newName);
+  return true;
+}
+
+QStringList ApplicationWindow::columnsList(Table::PlotDesignation plotType)
+{
+  QStringList list;
+  QList<MdiSubWindow *> windows = windowsList();
+  foreach(MdiSubWindow *w, windows){
+    if (!w->inherits("Table"))
+      continue;
+
+    Table *t = (Table *)w;
+    for (int i=0; i < t->numCols(); i++)
+    {
+      if (t->colPlotDesignation(i) == plotType || plotType == Table::All)
+        list << QString(t->objectName()) + "_" + t->colLabel(i);
+    }
+  }
+  return list;
+}
+
+void ApplicationWindow::showCurvesDialog()
+{
+  MdiSubWindow *w = activeWindow(MultiLayerWindow);
+  if (!w)
+    return;
+
+  if (((MultiLayer*)w)->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Error"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    return;
+  }
+
+  Graph* g = ((MultiLayer*)w)->activeGraph();
+  if (!g)
+    return;
+
+  if (g->isPiePlot()){
+    QMessageBox::warning(this,tr("MantidPlot - Error"),//Mantid
+        tr("This functionality is not available for pie plots!"));
+  } else {
+    CurvesDialog* crvDialog = new CurvesDialog(this);
+    crvDialog->setAttribute(Qt::WA_DeleteOnClose);
+    crvDialog->setGraph(g);
+    crvDialog->resize(d_add_curves_dialog_size);
+    crvDialog->setModal(true);
+    crvDialog->show();
+  }
+}
+
+bool ApplicationWindow::hasTable()
+{
+  Folder *f = projectFolder();
+  while (f){
+    QList<MdiSubWindow *> folderWindows = f->windowsList();
+    foreach(MdiSubWindow *w, folderWindows){
+      if (w->inherits("Table"))
+        return true;
+    }
+    f = f->folderBelow();
+  }
+  return false;
+}
+
+QStringList ApplicationWindow::tableNames()
+{
+  QStringList lst = QStringList();
+  Folder *f = projectFolder();
+  while (f){
+    QList<MdiSubWindow *> folderWindows = f->windowsList();
+    foreach(MdiSubWindow *w, folderWindows){
+      if (w->inherits("Table"))
+        lst << w->objectName();
+    }
+    f = f->folderBelow();
+  }
+  return lst;
+}
+
+QList<MdiSubWindow*> ApplicationWindow::tableList()
+{
+  QList<MdiSubWindow*> lst;
+  Folder *f = projectFolder();
+  while (f){
+    QList<MdiSubWindow *> folderWindows = f->windowsList();
+    foreach(MdiSubWindow *w, folderWindows){
+      if (w->inherits("Table"))
+        lst << w;
+    }
+    f = f->folderBelow();
+  }
+  return lst;
+}
+
+AssociationsDialog* ApplicationWindow::showPlotAssociations(int curve)
+{
+  MdiSubWindow* w = activeWindow(MultiLayerWindow);
+  if (!w)
+    return 0;
+
+  Graph *g = ((MultiLayer*)w)->activeGraph();
+  if (!g)
+    return 0;
+
+  AssociationsDialog* ad = new AssociationsDialog(this);
+  ad->setAttribute(Qt::WA_DeleteOnClose);
+  ad->setGraph(g);
+  ad->initTablesList(tableList(), curve);
+  ad->show();
+  return ad;
+}
+
+void ApplicationWindow::showTitleDialog()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return;
+
+  if (w->isA("MultiLayer")){
+    Graph* g = ((MultiLayer*)w)->activeGraph();
+    if (g){
+      TextDialog* td= new TextDialog(TextDialog::LayerTitle, this,0);
+      td->setGraph(g);
+      td->exec();
+    }
+  } else if (w->isA("Graph3D")) {
+    Plot3DDialog* pd = (Plot3DDialog*)showPlot3dDialog();
+    if (pd)
+      pd->showTitleTab();
+  }
+}
+
+void ApplicationWindow::showAxisTitleDialog()
+{
+  MdiSubWindow* w = activeWindow(MultiLayerWindow);
+  if (!w)
+    return;
+
+  Graph* g = ((MultiLayer*)w)->activeGraph();
+  if (!g)
+    return;
+
+  TextDialog* td = new TextDialog(TextDialog::AxisTitle, this, 0);
+  td->setGraph(g);
+  td->exec();
+}
+
+void ApplicationWindow::showExportASCIIDialog()
+{
+  QString tableName = QString::null;
+  MdiSubWindow* t = activeWindow();
+  if (t && (t->isA("Matrix") || t->inherits("Table") || t->isA("MantidMatrix")))
+  {
+    tableName = t->objectName();
+
+    ExportDialog* ed = new ExportDialog(tableName, this, Qt::WindowContextHelpButtonHint);
+    ed->setAttribute(Qt::WA_DeleteOnClose);
+    ed->exec();
+  }
+}
+
+void ApplicationWindow::exportAllTables(const QString& sep, bool colNames, bool colComments, bool expSelection)
+{
+  QString dir = QFileDialog::getExistingDirectory(this, tr("Choose a directory to export the tables to"), workingDir, QFileDialog::ShowDirsOnly);
+  if (!dir.isEmpty()){
+    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+    workingDir = dir;
+
+    bool confirmOverwrite = true;
+    bool success = true;
+    QList<MdiSubWindow *> windows = windowsList();
+    foreach(MdiSubWindow *w, windows){
+      if (w->inherits("Table") || w->isA("Matrix")){
+        QString fileName = dir + "/" + w->objectName() + ".txt";
+        QFile f(fileName);
+        if (f.exists(fileName) && confirmOverwrite){
+          QApplication::restoreOverrideCursor();
+          switch(QMessageBox::question(this, tr("MantidPlot - Overwrite file?"),//Mantid
+              tr("A file called: <p><b>%1</b><p>already exists. "
+                  "Do you want to overwrite it?").arg(fileName), tr("&Yes"), tr("&All"), tr("&Cancel"), 0, 1))
+          {
+          case 0:
+            if (w->inherits("Table"))
+              success = ((Table*)w)->exportASCII(fileName, sep, colNames, colComments, expSelection);
+            else if (w->isA("Matrix"))
+              success = ((Matrix*)w)->exportASCII(fileName, sep, expSelection);
+            break;
+
+          case 1:
+            confirmOverwrite = false;
+            if (w->inherits("Table"))
+              success = ((Table*)w)->exportASCII(fileName, sep, colNames, colComments, expSelection);
+            else if (w->isA("Matrix"))
+              success = ((Matrix*)w)->exportASCII(fileName, sep, expSelection);
+            break;
+
+          case 2:
+            return;
+            break;
+          }
+        } else if (w->inherits("Table"))
+          success = ((Table*)w)->exportASCII(fileName, sep, colNames, colComments, expSelection);
+        else if (w->isA("Matrix"))
+          success = ((Matrix*)w)->exportASCII(fileName, sep, expSelection);
+
+        if (!success)
+          break;
+      }
+    }
+    QApplication::restoreOverrideCursor();
+  }
+}
+
+void ApplicationWindow::exportASCII(const QString& tableName, const QString& sep,
+    bool colNames, bool colComments, bool expSelection)
+{
+  MdiSubWindow* w = window(tableName);
+  if (!w || !(w->isA("Matrix") || w->inherits("Table") || w->isA("MantidMatrix")))
+    return;
+
+  QString selectedFilter;
+  QString fname = QFileDialog::getSaveFileName(this, tr("Choose a filename to save under"),
+      asciiDirPath + "/" + w->objectName(), "*.txt;;*.dat;;*.DAT", &selectedFilter);
+  if (!fname.isEmpty() ){
+    QFileInfo fi(fname);
+    QString baseName = fi.fileName();
+    if (baseName.contains(".")==0)
+      fname.append(selectedFilter.remove("*"));
+
+    asciiDirPath = fi.dirPath(true);
+
+    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+    if (w->inherits("Table"))
+      ((Table *)w)->exportASCII(fname, sep, colNames, colComments, expSelection);
+    else if (w->isA("Matrix"))
+      ((Matrix *)w)->exportASCII(fname, sep, expSelection);
+    else if (w->isA("MantidMatrix"))
+    {
+      //call save ascii
+      try
+      {
+        Mantid::API::IAlgorithm_sptr alg =mantidUI->CreateAlgorithm("SaveAscii");
+        alg->setPropertyValue("Filename",fname.toStdString());
+        alg->setPropertyValue("Workspace",tableName.toStdString());
+        alg->execute();
+      }
+      catch(...)
+      {
+      }
+    }
+
+    QApplication::restoreOverrideCursor();
+  }
+}
+
+void ApplicationWindow::showRowsDialog()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  bool ok;
+  int rows = QInputDialog::getInteger(this, tr("MantidPlot - Enter rows number"), tr("Rows"),//Mantid
+      t->numRows(), 0, 1000000, 1, &ok);
+  if ( ok )
+    t->resizeRows(rows);
+}
+
+void ApplicationWindow::showDeleteRowsDialog()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  bool ok;
+  int start_row = QInputDialog::getInteger(this, tr("MantidPlot - Delete rows"), tr("Start row"),//Mantid
+      1, 1, t->numRows(), 1, &ok);
+  if (ok){
+    int end_row = QInputDialog::getInteger(this, tr("MantidPlot - Delete rows"), tr("End row"),//Mantid
+        t->numRows(), 1, t->numRows(), 1, &ok);
+    if (ok)
+      t->deleteRows(start_row, end_row);
+  }
+}
+
+void ApplicationWindow::showColsDialog()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  bool ok;
+  int cols = QInputDialog::getInteger(this, tr("MantidPlot - Enter columns number"), tr("Columns"),//Mantid
+      t->numCols(), 0, 1000000, 1, &ok);
+  if ( ok )
+    t->resizeCols(cols);
+}
+
+void ApplicationWindow::showColumnValuesDialog()
+{
+  Table *w = (Table*)activeWindow(TableWindow);
+  if (!w)
+    return;
+
+  if (w->selectedColumns().count()>0 || w->table()->currentSelection() >= 0){
+    SetColValuesDialog* vd = new SetColValuesDialog(scriptingEnv(), this);
+    vd->setAttribute(Qt::WA_DeleteOnClose);
+    vd->setTable(w);
+    vd->exec();
+  } else
+    QMessageBox::warning(this, tr("MantidPlot - Column selection error"), tr("Please select a column first!"));//Mantid
+}
+
+void ApplicationWindow::recalculateTable()
+{
+  MdiSubWindow* w = activeWindow();
+  if (!w)
+    return;
+
+  if (w->inherits("Table"))
+    ((Table*)w)->calculate();
+  else if (w->isA("Matrix"))
+    ((Matrix*)w)->calculate();
+}
+
+void ApplicationWindow::sortActiveTable()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  if ((int)t->selectedColumns().count()>0)
+    t->sortTableDialog();
+  else
+    QMessageBox::warning(this, "MantidPlot - Column selection error","Please select a column first!");//Mantid
+}
+
+void ApplicationWindow::sortSelection()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  t->sortColumnsDialog();
+}
+
+void ApplicationWindow::normalizeActiveTable()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  if (int(t->selectedColumns().count())>0)
+    t->normalize();
+  else
+    QMessageBox::warning(this, tr("MantidPlot - Column selection error"), tr("Please select a column first!"));//Mantid
+}
+
+void ApplicationWindow::normalizeSelection()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  if (int(t->selectedColumns().count())>0)
+    t->normalizeSelection();
+  else
+    QMessageBox::warning(this, tr("MantidPlot - Column selection error"), tr("Please select a column first!"));//Mantid
+}
+
+void ApplicationWindow::correlate()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  QStringList s = t->selectedColumns();
+  if ((int)s.count() != 2){
+    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select two columns for this operation!"));//Mantid
+    return;
+  }
+
+  Correlation *cor = new Correlation(this, t, s[0], s[1]);
+  cor->run();
+  delete cor;
+}
+
+void ApplicationWindow::autoCorrelate()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  QStringList s = t->selectedColumns();
+  if ((int)s.count() != 1)
+  {
+    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select exactly one columns for this operation!"));//Mantid
+    return;
+  }
+
+  Correlation *cor = new Correlation(this, t, s[0], s[0]);
+  cor->run();
+  delete cor;
+}
+
+void ApplicationWindow::convolute()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  QStringList s = t->selectedColumns();
+  if ((int)s.count() != 2)
+  {
+    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select two columns for this operation:\n the first represents the signal and the second the response function!"));//Mantid
+    return;
+  }
+
+  Convolution *cv = new Convolution(this, t, s[0], s[1]);
+  cv->run();
+  delete cv;
+}
+
+void ApplicationWindow::deconvolute()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  QStringList s = t->selectedColumns();
+  if ((int)s.count() != 2)
+  {
+    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select two columns for this operation:\n the first represents the signal and the second the response function!"));//Mantid
+    return;
+  }
+
+  Deconvolution *dcv = new Deconvolution(this, t, s[0], s[1]);
+  dcv->run();
+  delete dcv;
+}
+
+void ApplicationWindow::showColStatistics()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  if (int(t->selectedColumns().count()) > 0)
+  {
+    QList<int> targets;
+    for (int i=0; i < t->numCols(); i++)
+      if (t->isColumnSelected(i, true))
+        targets << i;
+    newTableStatistics(t, TableStatistics::column, targets)->showNormal();
+  }
+  else
+    QMessageBox::warning(this, tr("MantidPlot - Column selection error"),//Mantid
+        tr("Please select a column first!"));
+}
+
+void ApplicationWindow::showRowStatistics()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  if (t->numSelectedRows() > 0){
+    QList<int> targets;
+    for (int i=0; i < t->numRows(); i++)
+      if (t->isRowSelected(i, true))
+        targets << i;
+    newTableStatistics(t, TableStatistics::row, targets)->showNormal();
+  } else
+    QMessageBox::warning(this, tr("MantidPlot - Row selection error"),//Mantid
+        tr("Please select a row first!"));
+}
+
+void ApplicationWindow::showColMenu(int c)
+{
+  Table *w = (Table*)activeWindow(TableWindow);
+  if (!w)
+    return;
+
+  QMenu contextMenu(this);
+  QMenu plot(this);
+  QMenu specialPlot(this);
+  QMenu fill(this);
+  QMenu sorting(this);
+  QMenu colType(this);
+  colType.setCheckable(true);
+  QMenu panels(this);
+  QMenu stat(this);
+  QMenu norm(this);
+
+  if ((int)w->selectedColumns().count()==1)
+  {
+    w->setSelectedCol(c);
+    plot.addAction(QIcon(getQPixmap("lPlot_xpm")),tr("&Line"), this, SLOT(plotL()));
+    plot.addAction(QIcon(getQPixmap("pPlot_xpm")),tr("&Scatter"), this, SLOT(plotP()));
+    plot.addAction(QIcon(getQPixmap("lpPlot_xpm")),tr("Line + S&ymbol"), this, SLOT(plotLP()));
+
+    specialPlot.addAction(QIcon(getQPixmap("dropLines_xpm")),tr("Vertical &Drop Lines"), this, SLOT(plotVerticalDropLines()));
+    specialPlot.addAction(QIcon(getQPixmap("spline_xpm")),tr("&Spline"), this,SLOT(plotSpline()));
+    specialPlot.addAction(QIcon(getQPixmap("vert_steps_xpm")),tr("&Vertical Steps"), this, SLOT(plotVertSteps()));
+    specialPlot.addAction(QIcon(getQPixmap("hor_steps_xpm")),tr("&Horizontal Steps"), this, SLOT(plotHorSteps()));
+    specialPlot.setTitle(tr("Special Line/Symb&ol"));
+    plot.addMenu(&specialPlot);
+    plot.insertSeparator();
+
+    plot.addAction(QIcon(getQPixmap("vertBars_xpm")),tr("&Columns"), this, SLOT(plotVerticalBars()));
+    plot.addAction(QIcon(getQPixmap("hBars_xpm")),tr("&Rows"), this, SLOT(plotHorizontalBars()));
+    plot.addAction(QIcon(getQPixmap("area_xpm")),tr("&Area"), this, SLOT(plotArea()));
+
+    plot.addAction(QIcon(getQPixmap("pie_xpm")),tr("&Pie"), this, SLOT(plotPie()));
+    plot.insertSeparator();
+
+    plot.addAction(QIcon(getQPixmap("ribbon_xpm")),tr("3D Ribbo&n"), this, SLOT(plot3DRibbon()));
+    plot.addAction(QIcon(getQPixmap("bars_xpm")),tr("3D &Bars"), this, SLOT(plot3DBars()));
+    plot.addAction(QIcon(getQPixmap("scatter_xpm")),tr("3&D Scatter"), this, SLOT(plot3DScatter()));
+    plot.addAction(QIcon(getQPixmap("trajectory_xpm")),tr("3D &Trajectory"), this, SLOT(plot3DTrajectory()));
+
+    plot.insertSeparator();
+
+    stat.addAction(actionBoxPlot);
+    stat.addAction(QIcon(getQPixmap("histogram_xpm")),tr("&Histogram"), this, SLOT(plotHistogram()));
+    stat.addAction(QIcon(getQPixmap("stacked_hist_xpm")),tr("&Stacked Histograms"), this, SLOT(plotStackedHistograms()));
+    stat.setTitle(tr("Statistical &Graphs"));
+    plot.addMenu(&stat);
+
+    plot.setTitle(tr("&Plot"));
+    contextMenu.addMenu(&plot);
+    contextMenu.insertSeparator();
+
+    contextMenu.addAction(QIcon(getQPixmap("cut_xpm")),tr("Cu&t"), w, SLOT(cutSelection()));
+    contextMenu.addAction(QIcon(getQPixmap("copy_xpm")),tr("&Copy"), w, SLOT(copySelection()));
+    contextMenu.addAction(QIcon(getQPixmap("paste_xpm")),tr("Past&e"), w, SLOT(pasteSelection()));
+    contextMenu.insertSeparator();
+
+    QAction * xColID=colType.addAction(QIcon(getQPixmap("x_col_xpm")), tr("&X"), this, SLOT(setXCol()));
+    xColID->setCheckable(true);
+    QAction * yColID=colType.addAction(QIcon(getQPixmap("y_col_xpm")), tr("&Y"), this, SLOT(setYCol()));
+    yColID->setCheckable(true);
+    QAction * zColID=colType.addAction(QIcon(getQPixmap("z_col_xpm")), tr("&Z"), this, SLOT(setZCol()));
+    zColID->setCheckable(true);
+    colType.insertSeparator();
+    QAction * labelID = colType.addAction(QIcon(getQPixmap("set_label_col_xpm")), tr("&Label"), this, SLOT(setLabelCol()));
+    labelID->setCheckable(true);
+    QAction * noneID=colType.addAction(QIcon(getQPixmap("disregard_col_xpm")), tr("&None"), this, SLOT(disregardCol()));
+    noneID->setCheckable(true);
+    colType.insertSeparator();
+    QAction * xErrColID =colType.addAction(tr("X E&rror"), this, SLOT(setXErrCol()));
+    xErrColID->setCheckable(true);
+    QAction * yErrColID = colType.addAction(QIcon(getQPixmap("errors_xpm")), tr("Y &Error"), this, SLOT(setYErrCol()));
+    yErrColID->setCheckable(true);
+    colType.insertSeparator();
+
+
+    if (w->colPlotDesignation(c) == Table::X)
+      xColID->setChecked(true);
+    else if (w->colPlotDesignation(c) == Table::Y)
+      yColID->setChecked(true);
+    else if (w->colPlotDesignation(c) == Table::Z)
+      zColID->setChecked(true);
+    else if (w->colPlotDesignation(c) == Table::xErr)
+      xErrColID->setChecked(true);
+    else if (w->colPlotDesignation(c) == Table::yErr)
+      yErrColID->setChecked(true);
+    else if (w->colPlotDesignation(c) == Table::Label)
+      labelID->setChecked(true);
+    else
+      noneID->setChecked(true);
+
+    actionReadOnlyCol->addTo(&colType);
+    actionReadOnlyCol->setCheckable(true);
+    actionReadOnlyCol->setChecked(w->isReadOnlyColumn(c));
+
+    colType.setTitle(tr("Set As"));
+    contextMenu.addMenu(&colType);
+
+    if (w){
+      contextMenu.insertSeparator();
+
+      contextMenu.addAction(actionShowColumnValuesDialog);
+      contextMenu.addAction(actionTableRecalculate);
+      fill.addAction(actionSetAscValues);
+      fill.addAction(actionSetRandomValues);
+      fill.setTitle(tr("&Fill Column With"));
+      contextMenu.addMenu(&fill);
+
+      norm.addAction(tr("&Column"), w, SLOT(normalizeSelection()));
+      norm.addAction(actionNormalizeTable);
+      norm.setTitle(tr("&Normalize"));
+      contextMenu.addMenu(& norm);
+
+      contextMenu.insertSeparator();
+      contextMenu.addAction(actionShowColStatistics);
+
+      contextMenu.insertSeparator();
+
+      contextMenu.addAction(QIcon(getQPixmap("erase_xpm")), tr("Clea&r"), w, SLOT(clearSelection()));
+      contextMenu.addAction(QIcon(getQPixmap("delete_column_xpm")), tr("&Delete"), w, SLOT(removeCol()));
+      contextMenu.addAction(actionHideSelectedColumns);
+      contextMenu.addAction(actionShowAllColumns);
+      contextMenu.insertSeparator();
+      contextMenu.addAction(getQPixmap("insert_column_xpm"), tr("&Insert"), w, SLOT(insertCol()));
+      contextMenu.addAction(actionAddColToTable);
+      contextMenu.insertSeparator();
+
+      sorting.addAction(QIcon(getQPixmap("sort_ascending_xpm")), tr("&Ascending"), w, SLOT(sortColAsc()));
+      sorting.addAction(QIcon(getQPixmap("sort_descending_xpm")), tr("&Descending"), w, SLOT(sortColDesc()));
+
+      sorting.setTitle(tr("Sort Colu&mn"));
+      contextMenu.addMenu(&sorting);
+
+      contextMenu.addAction(actionSortTable);
+    }
+
+    contextMenu.insertSeparator();
+    contextMenu.addAction(actionShowColumnOptionsDialog);
+  }
+  else if ((int)w->selectedColumns().count()>1)
+  {
+    plot.addAction(QIcon(getQPixmap("lPlot_xpm")),tr("&Line"), this, SLOT(plotL()));
+    plot.addAction(QIcon(getQPixmap("pPlot_xpm")),tr("&Scatter"), this, SLOT(plotP()));
+    plot.addAction(QIcon(getQPixmap("lpPlot_xpm")),tr("Line + S&ymbol"), this,SLOT(plotLP()));
+
+    specialPlot.addAction(QIcon(getQPixmap("dropLines_xpm")),tr("Vertical &Drop Lines"), this, SLOT(plotVerticalDropLines()));
+    specialPlot.addAction(QIcon(getQPixmap("spline_xpm")),tr("&Spline"), this, SLOT(plotSpline()));
+    specialPlot.addAction(QIcon(getQPixmap("vert_steps_xpm")),tr("&Vertical Steps"), this, SLOT(plotVertSteps()));
+    specialPlot.addAction(QIcon(getQPixmap("hor_steps_xpm")),tr("&Vertical Steps"), this, SLOT(plotHorSteps()));
+    specialPlot.setTitle(tr("Special Line/Symb&ol"));
+    plot.addMenu(&specialPlot);
+    plot.insertSeparator();
+
+    plot.addAction(QIcon(getQPixmap("vertBars_xpm")),tr("&Columns"), this, SLOT(plotVerticalBars()));
+    plot.addAction(QIcon(getQPixmap("hBars_xpm")),tr("&Rows"), this, SLOT(plotHorizontalBars()));
+    plot.addAction(QIcon(getQPixmap("area_xpm")),tr("&Area"), this, SLOT(plotArea()));
+    plot.addAction(QIcon(getQPixmap("vectXYXY_xpm")),tr("Vectors &XYXY"), this, SLOT(plotVectXYXY()));
+    plot.insertSeparator();
+
+    stat.addAction(actionBoxPlot);
+    stat.addAction(QIcon(getQPixmap("histogram_xpm")),tr("&Histogram"), this, SLOT(plotHistogram()));
+    stat.addAction(QIcon(getQPixmap("stacked_hist_xpm")),tr("&Stacked Histograms"), this, SLOT(plotStackedHistograms()));
+    stat.setTitle(tr("Statistical &Graphs"));
+    plot.addMenu(&stat);
+
+    panels.addAction(QIcon(getQPixmap("panel_v2_xpm")),tr("&Vertical 2 Layers"), this, SLOT(plot2VerticalLayers()));
+    panels.addAction(QIcon(getQPixmap("panel_h2_xpm")),tr("&Horizontal 2 Layers"), this, SLOT(plot2HorizontalLayers()));
+    panels.addAction(QIcon(getQPixmap("panel_4_xpm")),tr("&4 Layers"), this, SLOT(plot4Layers()));
+    panels.addAction(QIcon(getQPixmap("stacked_xpm")),tr("&Stacked Layers"), this, SLOT(plotStackedLayers()));
+    panels.setTitle(tr("Pa&nel"));
+    plot.addMenu(&panels);
+
+    plot.setTitle(tr("&Plot"));
+    contextMenu.addMenu(&plot);
+    contextMenu.insertSeparator();
+    contextMenu.addAction(QIcon(getQPixmap("cut_xpm")),tr("Cu&t"), w, SLOT(cutSelection()));
+    contextMenu.addAction(QIcon(getQPixmap("copy_xpm")),tr("&Copy"), w, SLOT(copySelection()));
+    contextMenu.addAction(QIcon(getQPixmap("paste_xpm")),tr("Past&e"), w, SLOT(pasteSelection()));
+    contextMenu.insertSeparator();
+
+    if (w){
+      contextMenu.addAction(QIcon(getQPixmap("erase_xpm")),tr("Clea&r"), w, SLOT(clearSelection()));
+      contextMenu.addAction(QIcon(getQPixmap("close_xpm")),tr("&Delete"), w, SLOT(removeCol()));
+      contextMenu.addAction(actionHideSelectedColumns);
+      contextMenu.addAction(actionShowAllColumns);
+      contextMenu.insertSeparator();
+      contextMenu.addAction(tr("&Insert"), w, SLOT(insertCol()));
+      contextMenu.addAction(actionAddColToTable);
+      contextMenu.insertSeparator();
+    }
+
+    colType.addAction(actionSetXCol);
+    colType.addAction(actionSetYCol);
+    colType.addAction(actionSetZCol);
+    colType.insertSeparator();
+    colType.addAction(actionSetLabelCol);
+    colType.addAction(actionDisregardCol);
+    colType.insertSeparator();
+    colType.addAction(actionSetXErrCol);
+    colType.addAction(actionSetYErrCol);
+    colType.insertSeparator();
+    colType.addAction(tr("&Read-only"), this, SLOT(setReadOnlyColumns()));
+    colType.addAction(tr("Read/&Write"), this, SLOT(setReadWriteColumns()));
+    colType.setTitle(tr("Set As"));
+    contextMenu.addMenu(&colType);
+
+    if (w)
+    {
+      contextMenu.insertSeparator();
+
+      fill.addAction(actionSetAscValues);
+      fill.addAction(actionSetRandomValues);
+      fill.setTitle(tr("&Fill Columns With"));
+      contextMenu.addMenu(&fill);
+
+      norm.addAction(actionNormalizeSelection);
+      norm.addAction(actionNormalizeTable);
+      norm.setTitle(tr("&Normalize"));
+      contextMenu.addMenu(&norm);
+
+      contextMenu.insertSeparator();
+      contextMenu.addAction(actionSortSelection);
+      contextMenu.addAction(actionSortTable);
+      contextMenu.insertSeparator();
+      contextMenu.addAction(actionShowColStatistics);
+    }
+  }
+
+  QPoint posMouse=QCursor::pos();
+  contextMenu.exec(posMouse);
+}
+
+void ApplicationWindow::plot2VerticalLayers()
+{
+  multilayerPlot(1, 2, defaultCurveStyle);
+}
+
+void ApplicationWindow::plot2HorizontalLayers()
+{
+  multilayerPlot(2, 1, defaultCurveStyle);
+}
+
+void ApplicationWindow::plot4Layers()
+{
+  multilayerPlot(2, 2, defaultCurveStyle);
+}
+
+void ApplicationWindow::plotStackedLayers()
+{
+  multilayerPlot(1, -1, defaultCurveStyle);
+}
+
+void ApplicationWindow::plotStackedHistograms()
+{
+  multilayerPlot(1, -1, Graph::Histogram);
+}
+
+void ApplicationWindow::showMatrixDialog()
+{
+  Matrix *m = (Matrix*)activeWindow(MatrixWindow);
+  if (!m)
+    return;
+
+  MatrixDialog* md = new MatrixDialog(this);
+  md->setAttribute(Qt::WA_DeleteOnClose);
+  md->setMatrix (m);
+  md->exec();
+}
+
+void ApplicationWindow::showMatrixSizeDialog()
+{
+  Matrix *m = (Matrix*)activeWindow(MatrixWindow);
+  if (!m)
+    return;
+
+  MatrixSizeDialog* md = new MatrixSizeDialog(m, this);
+  md->setAttribute(Qt::WA_DeleteOnClose);
+  md->exec();
+}
+
+void ApplicationWindow::showMatrixValuesDialog()
+{
+  Matrix *m = (Matrix*)activeWindow(MatrixWindow);
+  if (!m)
+    return;
+
+  MatrixValuesDialog* md = new MatrixValuesDialog(scriptingEnv(), this);
+  md->setAttribute(Qt::WA_DeleteOnClose);
+  md->setMatrix(m);
+  md->exec();
+}
+
+void ApplicationWindow::showColumnOptionsDialog()
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  if(t->selectedColumns().count()>0) {
+    TableDialog* td = new TableDialog(t, this);
+    td->setAttribute(Qt::WA_DeleteOnClose);
+    td->exec();
+  } else
+    QMessageBox::warning(this, tr("MantidPlot"), tr("Please select a column first!"));//Mantid
+}
+
+void ApplicationWindow::showGeneralPlotDialog()
+{
+  MdiSubWindow* plot = activeWindow();
+  if (!plot)
+    return;
+
+  if (plot->isA("MultiLayer") && ((MultiLayer*)plot)->layers())
+    showPlotDialog();
+  else if (plot->isA("Graph3D")){
+    QDialog* gd = showScaleDialog();
+    ((Plot3DDialog*)gd)->showGeneralTab();
+  }
+}
+
+void ApplicationWindow::showAxisDialog()
+{
+  MdiSubWindow* plot = activeWindow();
+  if (!plot)
+    return;
+
+  QDialog* gd = showScaleDialog();
+  if (gd && plot->isA("MultiLayer") && ((MultiLayer*)plot)->layers())
+    ((AxesDialog*)gd)->showAxesPage();
+  else if (gd && plot->isA("Graph3D"))
+    ((Plot3DDialog*)gd)->showAxisTab();
+}
+
+void ApplicationWindow::showGridDialog()
+{
+  AxesDialog* gd = (AxesDialog*)showScaleDialog();
+  if (gd)
+    gd->showGridPage();
+}
+
+QDialog* ApplicationWindow::showScaleDialog()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return 0;
+
+  if (w->isA("MultiLayer")){
+    if (((MultiLayer*)w)->isEmpty())
+      return 0;
+
+    Graph* g = ((MultiLayer*)w)->activeGraph();
+    if (g->isPiePlot()){
+      QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("This functionality is not available for pie plots!"));//Mantid
+      return 0;
+    }
+
+    AxesDialog* ad = new AxesDialog(this);
+    ad->setGraph(g);
+    ad->exec();
+    return ad;
+  } else if (w->isA("Graph3D"))
+    return showPlot3dDialog();
+
+  return 0;
+}
+
+AxesDialog* ApplicationWindow::showScalePageFromAxisDialog(int axisPos)
+{
+  AxesDialog* gd = (AxesDialog*)showScaleDialog();
+  if (gd)
+    gd->setCurrentScale(axisPos);
+
+  return gd;
+}
+
+AxesDialog* ApplicationWindow::showAxisPageFromAxisDialog(int axisPos)
+{
+  AxesDialog* gd = (AxesDialog*)showScaleDialog();
+  if (gd){
+    gd->showAxesPage();
+    gd->setCurrentScale(axisPos);
+  }
+  return gd;
+}
+
+QDialog* ApplicationWindow::showPlot3dDialog()
+{
+  Graph3D *g = (Graph3D*)activeWindow(Plot3DWindow);
+  if (!g)
+    return 0;
+
+  if (!g->hasData()){
+    QApplication::restoreOverrideCursor();
+    QMessageBox::warning(this, tr("MantidPlot - Warning"),//Mantid
+        tr("Not available for empty 3D surface plots!"));
+    return 0;
+  }
+
+  Plot3DDialog* pd = new Plot3DDialog(this);
+  pd->setPlot(g);
+  pd->show();
+  return pd;
+}
+
+void ApplicationWindow::showPlotDialog(int curveKey)
+{
+  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!w)
+    return;
+
+  PlotDialog* pd = new PlotDialog(d_extended_plot_dialog, this);
+  pd->setAttribute(Qt::WA_DeleteOnClose);
+  pd->insertColumnsList(columnsList(Table::All));
+  pd->setMultiLayer(w);
+  if (curveKey >= 0){
+    Graph *g = w->activeGraph();
+    if (g)
+      pd->selectCurve(g->curveIndex(curveKey));
+  }
+  pd->initFonts(plotTitleFont, plotAxesFont, plotNumbersFont, plotLegendFont);
+  pd->showAll(d_extended_plot_dialog);
+  pd->show();
+}
+
+void ApplicationWindow::showCurvePlotDialog()
+{
+  showPlotDialog(actionShowCurvePlotDialog->data().toInt());
+}
+
+void ApplicationWindow::showCurveContextMenu(int curveKey)
+{
+  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!w)
+    return;
+
+  Graph *g = w->activeGraph();
+  DataCurve *c = (DataCurve *)g->curve(g->curveIndex(curveKey));
+  if (!c || !c->isVisible())
+    return;
+
+  QMenu curveMenu(this);
+  curveMenu.addAction(c->title().text(), this, SLOT(showCurvePlotDialog()));
+  curveMenu.insertSeparator();
+
+  curveMenu.addAction(actionHideCurve);
+  actionHideCurve->setData(curveKey);
+
+  if (g->visibleCurves() > 1 && c->type() == Graph::Function){
+    curveMenu.addAction(actionHideOtherCurves);
+    actionHideOtherCurves->setData(curveKey);
+  } else if (c->type() != Graph::Function) {
+    if ((g->visibleCurves() - c->errorBarsList().count()) > 1) {
+      curveMenu.addAction(actionHideOtherCurves);
+      actionHideOtherCurves->setData(curveKey);
+    }
+  }
+
+  if (g->visibleCurves() != g->curves())
+    curveMenu.addAction(actionShowAllCurves);
+  curveMenu.insertSeparator();
+
+  if (g->activeTool()){
+    if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector ||
+        g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker)
+      curveMenu.addAction(actionCopySelection);
+  }
+
+  if (c->type() == Graph::Function){
+    curveMenu.insertSeparator();
+    curveMenu.addAction(actionEditFunction);
+    actionEditFunction->setData(curveKey);
+  } else if (c->type() != Graph::ErrorBars){
+    if (g->activeTool()){
+      if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector ||
+          g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker){
+        curveMenu.addAction(actionCutSelection);
+        curveMenu.addAction(actionPasteSelection);
+        curveMenu.addAction(actionClearSelection);
+        curveMenu.insertSeparator();
+        if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector){
+          QAction *act = new QAction(tr("Set Display Range"), this);
+          connect(act, SIGNAL(activated()), (RangeSelectorTool *)g->activeTool(), SLOT(setCurveRange()));
+          curveMenu.addAction(act);
+        }
+      }
+    }
+
+    curveMenu.addAction(actionEditCurveRange);
+    actionEditCurveRange->setData(curveKey);
+
+    curveMenu.addAction(actionCurveFullRange);
+    if (c->isFullRange())
+      actionCurveFullRange->setDisabled(true);
+    else
+      actionCurveFullRange->setEnabled(true);
+    actionCurveFullRange->setData(curveKey);
+
+    curveMenu.insertSeparator();
+  }
+
+  curveMenu.addAction(actionShowCurveWorksheet);
+  actionShowCurveWorksheet->setData(curveKey);
+
+  curveMenu.addAction(actionShowCurvePlotDialog);
+  actionShowCurvePlotDialog->setData(curveKey);
+
+  curveMenu.insertSeparator();
+
+  curveMenu.addAction(actionRemoveCurve);
+  actionRemoveCurve->setData(curveKey);
+  curveMenu.exec(QCursor::pos());
+}
+
+void ApplicationWindow::showAllCurves()
+{
+  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!w)
+    return;
+
+  Graph* g = w->activeGraph();
+  if (!g)
+    return;
+
+  for(int i=0; i< g->curves(); i++)
+    g->showCurve(i);
+  g->replot();
+}
+
+void ApplicationWindow::hideOtherCurves()
+{
+  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!w)
+    return;
+
+  Graph* g = w->activeGraph();
+  if (!g)
+    return;
+
+  int curveKey = actionHideOtherCurves->data().toInt();
+  for(int i=0; i< g->curves(); i++)
+    g->showCurve(i, false);
+
+  g->showCurve(g->curveIndex(curveKey));
+  g->replot();
+}
+
+void ApplicationWindow::hideCurve()
+{
+  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!w)
+    return;
+
+  Graph* g = w->activeGraph();
+  if (!g)
+    return;
+
+  int curveKey = actionHideCurve->data().toInt();
+  g->showCurve(g->curveIndex(curveKey), false);
+}
+
+void ApplicationWindow::removeCurve()
+{
+  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!w)
+    return;
+
+  Graph* g = w->activeGraph();
+  if (!g)
+    return;
+
+  int curveKey = actionRemoveCurve->data().toInt();
+  g->removeCurve(g->curveIndex(curveKey));
+  g->updatePlot();
+}
+
+void ApplicationWindow::showCurveWorksheet(Graph *g, int curveIndex)
+{
+  if (!g)
+    return;
+
+  const QwtPlotItem *it = g->plotItem(curveIndex);
+  if (!it)
+    return;
+
+  if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram){
+    Spectrogram *sp = (Spectrogram *)it;
+    if (sp->matrix())
+      sp->matrix()->showMaximized();
+  } else if (((PlotCurve *)it)->type() == Graph::Function)
+    g->createTable((PlotCurve *)it);
+  else {
+    showTable(it->title().text());
+    if (g->activeTool() && g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker)
+      ((DataPickerTool *)g->activeTool())->selectTableRow();
+  }
+}
+
+void ApplicationWindow::showCurveWorksheet()
+{
+  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!w)
+    return;
+
+  Graph* g = w->activeGraph();
+  if (!g)
+    return;
+
+  int curveKey = actionShowCurveWorksheet->data().toInt();
+  showCurveWorksheet(g, g->curveIndex(curveKey));
+}
+
+void ApplicationWindow::zoomIn()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  if (plot->isEmpty())
+  {
+    QMessageBox::warning(this, tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    btnPointer->setOn(true);
+    return;
+  }
+
+  if ((Graph*)plot->activeGraph()->isPiePlot())
+  {
+    if (btnZoomIn->isOn())
+      QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+          tr("This functionality is not available for pie plots!"));
+    btnPointer->setOn(true);
+    return;
+  }
+
+  QList<Graph *> layers = plot->layersList();
+  foreach(Graph *g, layers){
+    if (!g->isPiePlot())
+      g->zoom(true);
+  }
+}
+
+void ApplicationWindow::zoomOut()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  if (plot->isEmpty() || (Graph*)plot->activeGraph()->isPiePlot())
+    return;
+
+  ((Graph*)plot->activeGraph())->zoomOut();
+  btnPointer->setOn(true);
+}
+
+void ApplicationWindow::setAutoScale()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"));
+    return;
+  }
+
+  Graph *g = (Graph*)plot->activeGraph();
+  if (g)
+    g->setAutoScale();
+}
+
+void ApplicationWindow::removePoints()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty())
+  {
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  Graph* g = (Graph*)plot->activeGraph();
+  if (!g || !g->validCurvesDataSize())
+  {
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  if (g->isPiePlot())
+  {
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("This functionality is not available for pie plots!"));
+    btnPointer->setChecked(true);
+    return;
+  }
+  else
+  {
+    switch(QMessageBox::warning (this,tr("MantidPlot"),//Mantid
+        tr("This will modify the data in the worksheets!\nAre you sure you want to continue?"),
+        tr("Continue"),tr("Cancel"),0,1))
+    {
+    case 0:
+      g->setActiveTool(new DataPickerTool(g, this, DataPickerTool::Remove, info, SLOT(setText(const QString&))));
+      displayBar->show();
+      break;
+
+    case 1:
+      btnPointer->setChecked(true);
+      break;
+    }
+  }
+}
+
+void ApplicationWindow::movePoints()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  Graph* g = (Graph*)plot->activeGraph();
+  if (!g || !g->validCurvesDataSize()){
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  if (g->isPiePlot()){
+    QMessageBox::warning(this, tr("MantidPlot - Warning"),//Mantid
+        tr("This functionality is not available for pie plots!"));
+
+    btnPointer->setChecked(true);
+    return;
+  } else {
+    switch(QMessageBox::warning (this, tr("MantidPlot"),//Mantid
+        tr("This will modify the data in the worksheets!\nAre you sure you want to continue?"),
+        tr("Continue"), tr("Cancel"), 0, 1))
+    {
+    case 0:
+      if (g){
+        g->setActiveTool(new DataPickerTool(g, this, DataPickerTool::Move, info, SLOT(setText(const QString&))));
+        displayBar->show();
+      }
+      break;
+
+    case 1:
+      btnPointer->setChecked(true);
+      break;
+    }
+  }
+}
+
+void ApplicationWindow::exportPDF()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return;
+
+  if (w->isA("MultiLayer") && ((MultiLayer *)w)->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"));
+    return;
+  }
+
+  QString fname = QFileDialog::getSaveFileName(this, tr("Choose a filename to save under"), workingDir, "*.pdf");
+  if (!fname.isEmpty() ){
+    QFileInfo fi(fname);
+    QString baseName = fi.fileName();
+    if (!baseName.contains("."))
+      fname.append(".pdf");
+
+    workingDir = fi.dirPath(true);
+
+    QFile f(fname);
+    if (!f.open(QIODevice::WriteOnly)){
+      QMessageBox::critical(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));
+      return;
+    }
+
+    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+    w->exportPDF(fname);
+    QApplication::restoreOverrideCursor();
+  }
+}
+
+//print active window
+void ApplicationWindow::print()
+{
+  MdiSubWindow* w = activeWindow();
+  if (!w)
+    return;
+
+  if (w->isA("MultiLayer") && ((MultiLayer *)w)->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"));
+    return;
+  }
+  w->print();
+}
+
+void ApplicationWindow::printAllPlots()
+{
+  QPrinter printer;
+  printer.setOrientation(QPrinter::Landscape);
+  printer.setColorMode (QPrinter::Color);
+  printer.setFullPage(true);
+
+  if (printer.setup())
+  {
+    QPainter *paint = new QPainter (&printer);
+
+    int plots = 0;
+    QList<MdiSubWindow *> windows = windowsList();
+    foreach(MdiSubWindow *w, windows){
+      if (w->isA("MultiLayer"))
+        plots++;
+    }
+
+    printer.setMinMax (0, plots);
+    printer.setFromTo (0, plots);
+
+    foreach(MdiSubWindow *w, windows){
+      if (w->isA("MultiLayer") && printer.newPage())
+        ((MultiLayer*)w)->printAllLayers(paint);
+    }
+    paint->end();
+    delete paint;
+  }
+}
+
+void ApplicationWindow::showExpGrowthDialog()
+{
+  showExpDecayDialog(-1);
+}
+
+void ApplicationWindow::showExpDecayDialog()
+{
+  showExpDecayDialog(1);
+}
+
+void ApplicationWindow::showExpDecayDialog(int type)
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g || !g->validCurvesDataSize())
+    return;
+
+  ExpDecayDialog *edd = new ExpDecayDialog(type, this);
+  edd->setAttribute(Qt::WA_DeleteOnClose);
+  connect (g, SIGNAL(destroyed()), edd, SLOT(close()));
+
+  edd->setGraph(g);
+  edd->show();
+}
+
+void ApplicationWindow::showTwoExpDecayDialog()
+{
+  showExpDecayDialog(2);
+}
+
+void ApplicationWindow::showExpDecay3Dialog()
+{
+  showExpDecayDialog(3);
+}
+
+void ApplicationWindow::showFitDialog()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return;
+
+  MultiLayer* plot = 0;
+  if(w->isA("MultiLayer"))
+    plot = (MultiLayer*)w;
+  else if(w->inherits("Table"))
+    plot = multilayerPlot((Table *)w, ((Table *)w)->drawableColumnSelection(), Graph::LineSymbols);
+
+  if (!plot)
+    return;
+
+  Graph* g = (Graph*)plot->activeGraph();
+  if (!g || !g->validCurvesDataSize())
+    return;
+
+  FitDialog *fd = new FitDialog(g, this);
+  fd->setAttribute(Qt::WA_DeleteOnClose);
+  connect (plot, SIGNAL(destroyed()), fd, SLOT(close()));
+
+  fd->setSrcTables(tableList());
+  fd->show();
+  fd->resize(fd->minimumSize());
+}
+
+void ApplicationWindow::showFilterDialog(int filter)
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if ( g && g->validCurvesDataSize())
+  {
+    FilterDialog *fd = new FilterDialog(filter, this);
+    fd->setAttribute(Qt::WA_DeleteOnClose);
+    fd->setGraph(g);
+    fd->exec();
+  }
+}
+
+void ApplicationWindow::lowPassFilterDialog()
+{
+  showFilterDialog(FFTFilter::LowPass);
+}
+
+void ApplicationWindow::highPassFilterDialog()
+{
+  showFilterDialog(FFTFilter::HighPass);
+}
+
+void ApplicationWindow::bandPassFilterDialog()
+{
+  showFilterDialog(FFTFilter::BandPass);
+}
+
+void ApplicationWindow::bandBlockFilterDialog()
+{
+  showFilterDialog(FFTFilter::BandBlock);
+}
+
+void ApplicationWindow::showFFTDialog()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return;
+
+  FFTDialog *sd = 0;
+  if (w->isA("MultiLayer")) {
+    Graph* g = ((MultiLayer*)w)->activeGraph();
+    if ( g && g->validCurvesDataSize() ){
+      sd = new FFTDialog(FFTDialog::onGraph, this);
+      sd->setAttribute(Qt::WA_DeleteOnClose);
+      sd->setGraph(g);
+    }
+  } else if (w->inherits("Table")) {
+    sd = new FFTDialog(FFTDialog::onTable, this);
+    sd->setAttribute(Qt::WA_DeleteOnClose);
+    sd->setTable((Table*)w);
+  } else if (w->inherits("Matrix")) {
+    sd = new FFTDialog(FFTDialog::onMatrix, this);
+    sd->setAttribute(Qt::WA_DeleteOnClose);
+    sd->setMatrix((Matrix*)w);
+  }
+
+  if (sd)
+    sd->exec();
+}
+
+void ApplicationWindow::showSmoothDialog(int m)
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g || !g->validCurvesDataSize())
+    return;
+
+  SmoothCurveDialog *sd = new SmoothCurveDialog(m, this);
+  sd->setAttribute(Qt::WA_DeleteOnClose);
+  sd->setGraph(g);
+  sd->exec();
+}
+
+void ApplicationWindow::showSmoothSavGolDialog()
+{
+  showSmoothDialog(SmoothFilter::SavitzkyGolay);
+}
+
+void ApplicationWindow::showSmoothFFTDialog()
+{
+  showSmoothDialog(SmoothFilter::FFT);
+}
+
+void ApplicationWindow::showSmoothAverageDialog()
+{
+  showSmoothDialog(SmoothFilter::Average);
+}
+
+void ApplicationWindow::showInterpolationDialog()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g || !g->validCurvesDataSize())
+    return;
+
+  InterpolationDialog *id = new InterpolationDialog(this);
+  id->setAttribute(Qt::WA_DeleteOnClose);
+  connect (g, SIGNAL(destroyed()), id, SLOT(close()));
+  id->setGraph(g);
+  id->show();
+}
+
+void ApplicationWindow::showFitPolynomDialog()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g || !g->validCurvesDataSize())
+    return;
+
+  PolynomFitDialog *pfd = new PolynomFitDialog(this);
+  pfd->setAttribute(Qt::WA_DeleteOnClose);
+  connect(g, SIGNAL(destroyed()), pfd, SLOT(close()));
+  pfd->setGraph(g);
+  pfd->show();
+}
+
+void ApplicationWindow::updateLog(const QString& result)
+{	
+  if ( !result.isEmpty() ){
+    current_folder->appendLogInfo(result);
+    showResults(true);
+    emit modified();
+  }
+}
+
+void ApplicationWindow::showIntegrationDialog()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g)
+    return;
+
+  IntDialog *id = new IntDialog(this, g);
+  id->exec();
+}
+
+/**
+ * Sets the visibilty of the log window. If it is shown then
+ * the results are scrolled to the bottom
+ */
+void ApplicationWindow::showLogWindow(bool show)
+{
+  logWindow->setVisible(show);
+  if( show )
+  {
+    QTextCursor cur = results->textCursor();
+    cur.movePosition(QTextCursor::End);
+    results->setTextCursor(cur);
+  }
+}
+
+void ApplicationWindow::showResults(bool ok)
+{
+  if (ok)
+  {
+    if (!current_folder->logInfo().isEmpty())
+      results->setText(current_folder->logInfo());
+    else
+      results->setText(tr("Sorry, there are no results to display!"));
+  }
+  showLogWindow(ok);
+}
+
+void ApplicationWindow::showResults(const QString& s, bool ok)
+{
+  current_folder->appendLogInfo(s);
+
+  QString logInfo = current_folder->logInfo();
+  if (!logInfo.isEmpty())
+    results->setText(logInfo);
+  showResults(ok);
+}
+
+void ApplicationWindow::showScreenReader()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  QList<Graph *> layers = plot->layersList();
+  foreach(Graph *g, layers)
+  g->setActiveTool(new ScreenPickerTool(g, info, SLOT(setText(const QString&))));
+
+  displayBar->show();
+}
+
+void ApplicationWindow::drawPoints()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  QList<Graph *> layers = plot->layersList();
+  foreach(Graph *g, layers)
+  g->setActiveTool(new DrawPointTool(this, g, info, SLOT(setText(const QString&))));
+
+  displayBar->show();
+}
+
+void ApplicationWindow::showRangeSelectors()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty()){
+    QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("There are no plot layers available in this window!"));//Mantid
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  Graph* g = (Graph*)plot->activeGraph();
+  if (!g)
+    return;
+
+  if (!g->curves()){
+    QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("There are no curves available on this plot!"));//Mantid
+    btnPointer->setChecked(true);
+    return;
+  } else if (g->isPiePlot()) {
+    QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("This functionality is not available for pie plots!"));//Mantid
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  displayBar->show();
+  g->enableRangeSelectors(info, SLOT(setText(const QString&)));
+}
+
+void ApplicationWindow::showCursor()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  if ((Graph*)plot->activeGraph()->isPiePlot()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("This functionality is not available for pie plots!"));
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  QList<Graph *> layers = plot->layersList();
+  foreach(Graph *g, layers){
+    if (g->isPiePlot() || !g->curves())
+      continue;
+    if (g->validCurvesDataSize())
+      g->setActiveTool(new DataPickerTool(g, this, DataPickerTool::Display, info, SLOT(setText(const QString&))));
+  }
+  displayBar->show();
+}
+
+/**  Switch on the multi-peak selecting tool for fitting
+ * with the Fit algorithm of multiple peaks on a single background
+ */
+void ApplicationWindow::selectMultiPeak()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  if ((Graph*)plot->activeGraph()->isPiePlot()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("This functionality is not available for pie plots!"));
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  QList<Graph *> layers = plot->layersList();
+  foreach(Graph *g, layers){
+    if (g->isPiePlot() || !g->curves())
+    {
+      continue;
+    }
+    if (g->validCurvesDataSize())
+    {
+      PeakPickerTool* ppicker = new PeakPickerTool(g, mantidUI);
+      g->setActiveTool(ppicker);
+      connect(plot,SIGNAL(windowStateChanged(Qt::WindowStates, Qt::WindowStates)),ppicker,SLOT(windowStateChanged(Qt::WindowStates, Qt::WindowStates)));
+    }
+  }
+
+}
+
+void ApplicationWindow::newLegend()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    return;
+  }
+
+  Graph* g = (Graph*)plot->activeGraph();
+  if ( g )
+    g->newLegend();
+}
+
+void ApplicationWindow::addTimeStamp()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty())
+  {
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    return;
+  }
+
+  Graph* g = (Graph*)plot->activeGraph();
+  if ( g )
+    g->addTimeStamp();
+}
+
+void ApplicationWindow::disableAddText()
+{
+  actionAddText->setChecked(false);
+  showTextDialog();
+}
+
+void ApplicationWindow::addText()
+{
+  if (!btnPointer->isOn())
+    btnPointer->setOn(TRUE);
+
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  Graph *g = (Graph*)plot->activeGraph();
+  if (g)
+    g->drawText(true);
+}
+
+void ApplicationWindow::addImage()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    return;
+  }
+
+  Graph* g = (Graph*)plot->activeGraph();
+  if (!g)
+    return;
+
+  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 - Insert image from file"), imagesDirPath, filter);//Mantid
+  if ( !fn.isEmpty() ){
+    QFileInfo fi(fn);
+    imagesDirPath = fi.dirPath(true);
+
+    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+    g->addImage(fn);
+    QApplication::restoreOverrideCursor();
+  }
+}
+
+void ApplicationWindow::drawLine()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty())
+  {
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  Graph* g = (Graph*)plot->activeGraph();
+  if (g)
+  {
+    g->drawLine(true);
+    emit modified();
+  }
+}
+
+void ApplicationWindow::drawArrow()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty())
+  {
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+
+    btnPointer->setOn(true);
+    return;
+  }
+
+  Graph* g = (Graph*)plot->activeGraph();
+  if (g)
+  {
+    g->drawLine(true, 1);
+    emit modified();
+  }
+}
+
+void ApplicationWindow::showImageDialog()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (g)
+  {
+    ImageMarker *im = (ImageMarker *) g->selectedMarkerPtr();
+    if (!im)
+      return;
+
+    ImageDialog *id = new ImageDialog(this);
+    id->setAttribute(Qt::WA_DeleteOnClose);
+    connect (id, SIGNAL(setGeometry(int, int, int, int)),
+        g, SLOT(updateImageMarker(int, int, int, int)));
+    //		id->setIcon(getQPixmap("logo_xpm"));
+    id->setOrigin(im->origin());
+    id->setSize(im->size());
+    id->exec();
+  }
+}
+
+void ApplicationWindow::showLayerDialog()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if(plot->isEmpty())
+  {
+    QMessageBox::warning(this, tr("MantidPlot - Warning"),//Mantid
+        tr("There are no plot layers available in this window."));
+    return;
+  }
+
+  LayerDialog *id=new LayerDialog(this);
+  id->setAttribute(Qt::WA_DeleteOnClose);
+  id->setMultiLayer(plot);
+  id->exec();
+}
+
+void ApplicationWindow::showTextDialog()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if ( g ){
+    LegendWidget *l = (LegendWidget *) g->selectedText();
+    if (!l)
+      return;
+
+    TextDialog *td = new TextDialog(TextDialog::TextMarker, this, 0);
+    td->setLegendWidget(l);
+    td->exec();
+  }
+}
+
+void ApplicationWindow::showLineDialog()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (g){
+    ArrowMarker *lm = (ArrowMarker *) g->selectedMarkerPtr();
+    if (!lm)
+      return;
+
+    LineDialog *ld = new LineDialog(lm, this);
+    ld->exec();
+  }
+}
+
+void ApplicationWindow::addColToTable()
+{
+  Table* m = (Table*)activeWindow(TableWindow);
+  if ( m )
+    m->addCol();
+}
+
+void ApplicationWindow::clearSelection()
+{
+  if(lv->hasFocus()){
+    deleteSelectedItems();
+    return;
+  }
+
+  MdiSubWindow* m = activeWindow();
+  if (!m)
+    return;
+
+  if (m->inherits("Table"))
+    ((Table*)m)->clearSelection();
+  else if (m->isA("Matrix"))
+    ((Matrix*)m)->clearSelection();
+  else if (m->isA("MultiLayer")){
+    Graph* g = ((MultiLayer*)m)->activeGraph();
+    if (!g)
+      return;
+
+    if (g->activeTool()){
+      if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector)
+        ((RangeSelectorTool *)g->activeTool())->clearSelection();
+      else if (g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker)
+        ((DataPickerTool *)g->activeTool())->removePoint();
+    } else if (g->titleSelected())
+      g->removeTitle();
+    else if (g->markerSelected())
+      g->removeMarker();
+  }
+  else if (m->isA("Note"))
+    ((Note*)m)->editor()->clear();
+  emit modified();
+}
+
+void ApplicationWindow::copySelection()
+{
+  if(results->hasFocus()){
+    results->copy();
+    return;
+  } else if(info->hasFocus()) {
+    info->copy();
+    return;
+  }
+  else if (m_interpreterDock->hasFocus())
+  {
+    m_scriptInterpreter->copy();
+    return;
+  }
+  MdiSubWindow* m = activeWindow();
+  if (!m)
+    return;
+
+    if (m->inherits("Table"))
+    ((Table*)m)->copySelection();
+  else if (m->isA("Matrix"))
+    ((Matrix*)m)->copySelection();
+  else if (m->isA("MultiLayer")){
+    MultiLayer* plot = (MultiLayer*)m;
+    if (!plot || plot->layers() == 0)
+      return;
+
+    Graph* g = (Graph*)plot->activeGraph();
+    if (!g)
+      return;
+
+    if (g->activeTool()){
+      if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector)
+      {
+        ((RangeSelectorTool *)g->activeTool())->copySelection();
+      }
+      else if (g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker)
+      {
+        ((DataPickerTool *)g->activeTool())->copySelection();
+      }
+    } else if (g->markerSelected()){
+      copyMarker();
+    } else
+    {
+      copyActiveLayer();
+    }
+
+    plot->copyAllLayers();
+  }
+  else if (m->isA("Note"))
+    ((Note*)m)->editor()->copy();
+  else
+    mantidUI->copyValues();//Mantid
+}
+
+void ApplicationWindow::cutSelection()
+{
+  
+  MdiSubWindow* m = activeWindow();
+  if (!m)
+    return;
+
+  if (m->inherits("Table"))
+    ((Table*)m)->cutSelection();
+  else if (m->isA("Matrix"))
+    ((Matrix*)m)->cutSelection();
+  else if(m->isA("MultiLayer")){
+    MultiLayer* plot = (MultiLayer*)m;
+    if (!plot || plot->layers() == 0)
+      return;
+
+    Graph* g = (Graph*)plot->activeGraph();
+    if (!g)
+      return;
+
+    if (g->activeTool()){
+      if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector)
+        ((RangeSelectorTool *)g->activeTool())->cutSelection();
+      else if (g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker)
+        ((DataPickerTool *)g->activeTool())->cutSelection();
+    } else {
+      copyMarker();
+      g->removeMarker();
+    }
+  }
+  else if (m->isA("Note"))
+    ((Note*)m)->editor()->cut();
+
+  emit modified();
+}
+
+void ApplicationWindow::copyMarker()
+{
+  lastCopiedLayer = NULL;
+
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (g && g->markerSelected()){
+    if (g->selectedText()){
+      d_text_copy = g->selectedText();
+      d_image_copy = NULL;
+      d_arrow_copy = NULL;
+    } else if (g->arrowMarkerSelected()){
+      d_arrow_copy = (ArrowMarker *) g->selectedMarkerPtr();
+      d_image_copy = NULL;
+      d_text_copy = NULL;
+    } else if (g->imageMarkerSelected()){
+      d_image_copy = (ImageMarker *) g->selectedMarkerPtr();
+      d_text_copy = NULL;
+      d_arrow_copy = NULL;
+    }
+  }
+}
+
+void ApplicationWindow::pasteSelection()
+{  
+  if (m_interpreterDock->hasFocus())
+  {
+    
+    m_scriptInterpreter->paste();
+    return;
+  }
+
+  MdiSubWindow* m = activeWindow();
+  if (!m)
+    return;
+
+  if (m->inherits("Table"))
+    ((Table*)m)->pasteSelection();
+  else if (m->isA("Matrix"))
+    ((Matrix*)m)->pasteSelection();
+  else if (m->isA("Note"))
+    ((Note*)m)->editor()->paste();
+  else if (m->isA("MultiLayer")){
+    MultiLayer* plot = (MultiLayer*)m;
+    if (!plot)
+      return;
+
+    if (lastCopiedLayer){
+      QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+      Graph* g = plot->addLayer();
+      g->copy(lastCopiedLayer);
+      QPoint pos = plot->mapFromGlobal(QCursor::pos());
+      plot->setGraphGeometry(pos.x(), pos.y()-20, lastCopiedLayer->width(), lastCopiedLayer->height());
+
+      QApplication::restoreOverrideCursor();
+    } else {
+      if (plot->layers() == 0)
+        return;
+
+      Graph* g = (Graph*)plot->activeGraph();
+      if (!g)
+        return;
+
+      if (g->activeTool()){
+        if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector)
+          ((RangeSelectorTool *)g->activeTool())->pasteSelection();
+        else if (g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker)
+          ((DataPickerTool *)g->activeTool())->pasteSelection();
+      } else if (d_text_copy){
+        LegendWidget *t = g->insertText(d_text_copy);
+        t->move(g->mapFromGlobal(QCursor::pos()));
+      } else if (d_arrow_copy){
+        ArrowMarker *a = g->addArrow(d_arrow_copy);
+        a->setStartPoint(QPoint(d_arrow_copy->startPoint().x() + 10,
+            d_arrow_copy->startPoint().y() + 10));
+        a->setEndPoint(QPoint(d_arrow_copy->endPoint().x() + 10,
+            d_arrow_copy->endPoint().y() + 10));
+        g->replot();
+        g->deselectMarker();
+      } else if (d_image_copy){
+        ImageMarker *i = g->addImage(d_image_copy);
+        QPoint pos = g->plotWidget()->canvas()->mapFromGlobal(QCursor::pos());
+        QSize size = d_image_copy->size();
+        i->setRect(pos.x(), pos.y(), size.width(), size.height());
+        g->replot();
+        g->deselectMarker();
+      }
+    }
+  }
+  emit modified();
+}
+
+MdiSubWindow* ApplicationWindow::clone(MdiSubWindow* w)
+{
+  if (!w) {
+    w = activeWindow();
+    if (!w){
+      QMessageBox::critical(this,tr("MantidPlot - Duplicate window error"),//Mantid
+          tr("There are no windows available in this project!"));
+      return 0;
+    }
+  }
+
+  MdiSubWindow* nw = 0;
+  MdiSubWindow::Status status = w->status();
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  if (w->isA("MultiLayer")){
+    MultiLayer *g = (MultiLayer *)w;
+    nw = multilayerPlot(generateUniqueName(tr("Graph")), 0, g->getRows(), g->getCols());
+    ((MultiLayer *)nw)->copy(g);
+  } else if (w->inherits("Table")){
+    Table *t = (Table *)w;
+    QString caption = generateUniqueName(tr("Table"));
+    nw = newTable(caption, t->numRows(), t->numCols());
+    ((Table *)nw)->copy(t);
+    QString spec = t->saveToString("geometry\n");
+    ((Table *)nw)->setSpecifications(spec.replace(t->objectName(), caption));
+  } else if (w->isA("Graph3D")){
+    Graph3D *g = (Graph3D *)w;
+    if (!g->hasData()){
+      QApplication::restoreOverrideCursor();
+      QMessageBox::warning(this, tr("MantidPlot - Duplicate error"), tr("Empty 3D surface plots cannot be duplicated!"));//Mantid
+      return 0;
+    }
+
+    QString caption = generateUniqueName(tr("Graph"));
+    QString s = g->formula();
+    if (g->userFunction()){
+      UserFunction *f = g->userFunction();
+      nw = plotSurface(f->function(), g->xStart(), g->xStop(), g->yStart(), g->yStop(),
+          g->zStart(), g->zStop(), f->columns(), f->rows());
+    } else if (g->parametricSurface()){
+      UserParametricSurface *s = g->parametricSurface();
+      nw = plotParametricSurface(s->xFormula(), s->yFormula(), s->zFormula(), s->uStart(), s->uEnd(),
+          s->vStart(), s->vEnd(), s->columns(), s->rows(), s->uPeriodic(), s->vPeriodic());
+    } else if (s.endsWith("(Z)"))
+      nw = openPlotXYZ(caption, s, g->xStart(),g->xStop(), g->yStart(),g->yStop(),g->zStart(),g->zStop());
+    else if (s.endsWith("(Y)"))//Ribbon plot
+      nw = dataPlot3D(caption, s, g->xStart(),g->xStop(), g->yStart(),g->yStop(),g->zStart(),g->zStop());
+    else
+      nw = openMatrixPlot3D(caption, s, g->xStart(), g->xStop(), g->yStart(), g->yStop(),g->zStart(),g->zStop());
+
+    if (!nw)
+      return 0;
+
+    if (status == MdiSubWindow::Maximized)
+      nw->hide();
+    ((Graph3D *)nw)->copy(g);
+    customToolBars(nw);
+  } else if (w->isA("Matrix")){
+    nw = newMatrix(((Matrix *)w)->numRows(), ((Matrix *)w)->numCols());
+    ((Matrix *)nw)->copy((Matrix *)w);
+  } else if (w->isA("Note")){
+    nw = newNote();
+    if (nw)
+      ((Note*)nw)->setText(((Note*)w)->text());
+  }
+
+  if (nw){
+    if (w->isA("MultiLayer")){
+      if (status == MdiSubWindow::Maximized)
+        nw->showMaximized();
+    } else if (w->isA("Graph3D")){
+      ((Graph3D*)nw)->setIgnoreFonts(true);
+      if (status != MdiSubWindow::Maximized){
+        nw->resize(w->size());
+        nw->showNormal();
+      } else
+        nw->showMaximized();
+      ((Graph3D*)nw)->setIgnoreFonts(false);
+    } else {
+      nw->resize(w->size());
+      nw->showNormal();
+    }
+
+    nw->setWindowLabel(w->windowLabel());
+    nw->setCaptionPolicy(w->captionPolicy());
+    setListViewSize(nw->objectName(), w->sizeToString());
+  }
+  QApplication::restoreOverrideCursor();
+  customMenu(nw);
+  return nw;
+}
+
+void ApplicationWindow::undo()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return;
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  if (qobject_cast<Note*>(w))
+    ((Note*)w)->editor()->undo();
+  else if (qobject_cast<Matrix*>(w)){
+    QUndoStack *stack = ((Matrix *)w)->undoStack();
+    if (stack && stack->canUndo())
+      stack->undo();
+  }
+  QApplication::restoreOverrideCursor();
+}
+
+void ApplicationWindow::redo()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return;
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  if (qobject_cast<Note*>(w))
+    ((Note*)w)->editor()->redo();
+  else if (qobject_cast<Matrix*>(w)){
+    QUndoStack *stack = ((Matrix *)w)->undoStack();
+    if (stack && stack->canRedo())
+      stack->redo();
+  }
+
+  QApplication::restoreOverrideCursor();
+}
+
+bool ApplicationWindow::hidden(QWidget* window)
+{
+  if (hiddenWindows->contains(window))
+    return true;
+
+  return false;
+}
+
+void ApplicationWindow::updateWindowStatus(MdiSubWindow* w)
+{
+  setListView(w->objectName(), w->aspect());
+  if (w->status() == MdiSubWindow::Maximized){
+    QList<MdiSubWindow *> windows = current_folder->windowsList();
+    foreach(MdiSubWindow *oldMaxWindow, windows){
+      if (oldMaxWindow != w && oldMaxWindow->status() == MdiSubWindow::Maximized)
+        oldMaxWindow->setStatus(MdiSubWindow::Normal);
+    }
+  }
+  modifiedProject();
+}
+
+void ApplicationWindow::hideActiveWindow()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return;
+
+  hideWindow(w);
+}
+
+void ApplicationWindow::hideWindow(MdiSubWindow* w)
+{
+  hiddenWindows->append(w);
+  w->setHidden();
+  emit modified();
+}
+
+void ApplicationWindow::hideWindow()
+{
+  WindowListItem *it = (WindowListItem *)lv->currentItem();
+  MdiSubWindow *w = it->window();
+  if (!w)
+    return;
+
+  hideWindow(w);
+}
+
+void ApplicationWindow::resizeActiveWindow()
+{
+  MdiSubWindow* w = activeWindow();
+  if (!w)
+    return;
+
+  ImageDialog *id = new ImageDialog(this);
+  id->setAttribute(Qt::WA_DeleteOnClose);
+  connect (id, SIGNAL(setGeometry(int,int,int,int)), this, SLOT(setWindowGeometry(int,int,int,int)));
+
+  id->setWindowTitle(tr("MantidPlot - Window Geometry"));//Mantid
+  id->setOrigin(w->pos());
+  id->setSize(w->size());
+  id->exec();
+}
+
+void ApplicationWindow::resizeWindow()
+{
+  WindowListItem *it = (WindowListItem *)lv->currentItem();
+  MdiSubWindow *w = it->window();
+  if (!w)
+    return;
+
+  d_workspace->setActiveSubWindow(w);
+
+  ImageDialog *id = new ImageDialog(this);
+  id->setAttribute(Qt::WA_DeleteOnClose);
+  connect (id, SIGNAL(setGeometry(int,int,int,int)), this, SLOT(setWindowGeometry(int,int,int,int)));
+
+  id->setWindowTitle(tr("MantidPlot - Window Geometry"));//Mantid
+  id->setOrigin(w->pos());
+  id->setSize(w->size());
+  id->exec();
+}
+
+void ApplicationWindow::setWindowGeometry(int x, int y, int w, int h)
+{
+  activeWindow()->setGeometry(x, y, w, h);
+}
+
+void ApplicationWindow::activateWindow()
+{
+  WindowListItem *it = (WindowListItem *)lv->currentItem();
+  activateWindow(it->window());
+}
+
+void ApplicationWindow::activateWindow(MdiSubWindow *w)
+{
+  if (!w)
+    return;
+
+  w->setNormal();
+  d_workspace->setActiveSubWindow(w);
+
+  updateWindowLists(w);
+  emit modified();
+}
+
+void ApplicationWindow::maximizeWindow(Q3ListViewItem * lbi)
+{
+  if (!lbi)
+    lbi = lv->currentItem();
+
+  if (!lbi || lbi->rtti() == FolderListItem::RTTI)
+    return;
+
+  maximizeWindow(((WindowListItem*)lbi)->window());
+}
+
+void ApplicationWindow::maximizeWindow(MdiSubWindow *w)
+{
+  if (!w || w->status() == MdiSubWindow::Maximized)
+    return;
+
+  QList<MdiSubWindow *> windows = current_folder->windowsList();
+  foreach(MdiSubWindow *ow, windows){
+    if (ow != w && ow->status() == MdiSubWindow::Maximized){
+      ow->setNormal();
+      break;
+    }
+  }
+
+  w->setMaximized();
+  updateWindowLists(w);
+  emit modified();
+}
+
+void ApplicationWindow::minimizeWindow(MdiSubWindow *w)
+{
+  if (!w)
+    w = ((WindowListItem *)lv->currentItem())->window();
+
+  if (!w)
+    return;
+
+  updateWindowLists(w);
+  w->setMinimized();
+  emit modified();
+}
+
+void ApplicationWindow::updateWindowLists(MdiSubWindow *w)
+{
+  if (!w)
+    return;
+
+  if (hiddenWindows->contains(w))
+    hiddenWindows->takeAt(hiddenWindows->indexOf(w));
+}
+
+void ApplicationWindow::closeActiveWindow()
+{
+  MdiSubWindow *w = activeWindow();
+  if (w)
+    w->close();
+}
+
+void ApplicationWindow::removeWindowFromLists(MdiSubWindow* w)
+{
+  if (!w)
+    return;
+
+  QString caption = w->objectName();
+  if (w->inherits("Table")){
+    Table* m=(Table*)w;
+    for (int i=0; i<m->numCols(); i++){
+      QString name=m->colName(i);
+      removeCurves(name);
+    }
+  } else if (w->isA("MultiLayer")){
+    MultiLayer *ml =  (MultiLayer*)w;
+    Graph *g = ml->activeGraph();
+    if (g)
+      btnPointer->setChecked(true);
+  } else if (w->isA("Matrix"))
+  {
+    remove3DMatrixPlots((Matrix*)w);
+  }
+
+  else
+  {   mantidUI->removeWindowFromLists(w);
+  }
+
+  if (hiddenWindows->contains(w))
+  {
+    hiddenWindows->takeAt(hiddenWindows->indexOf(w));
+  }
+}
+
+void ApplicationWindow::closeWindow(MdiSubWindow* window)
+{
+  if (!window)
+    return;
+
+  if (d_active_window == window)
+    d_active_window = NULL;
+  removeWindowFromLists(window);
+
+  Folder *f = window->folder();
+  f->removeWindow(window);
+
+  //update list view in project explorer
+  Q3ListViewItem *it=lv->findItem (window->objectName(), 0, Q3ListView::ExactMatch|Q3ListView::CaseSensitive);
+  if (it)
+    lv->takeItem(it);
+
+  if (show_windows_policy == ActiveFolder && !f->windowsList().count()){
+    customMenu(0);
+    customToolBars(0);
+  } else if (show_windows_policy == SubFolders && !(current_folder->children()).isEmpty()){
+    FolderListItem *fi = current_folder->folderListItem();
+    FolderListItem *item = (FolderListItem *)fi->firstChild();
+    int initial_depth = item->depth();
+    bool emptyFolder = true;
+    while (item && item->depth() >= initial_depth){
+      QList<MdiSubWindow *> lst = item->folder()->windowsList();
+      if (lst.count() > 0){
+        emptyFolder = false;
+        break;
+      }
+      item = (FolderListItem *)item->itemBelow();
+    }
+    if (emptyFolder){
+      customMenu(0);
+      customToolBars(0);
+    }
+  }
+  emit modified();
+}
+
+void ApplicationWindow::about()
+{
+  /*
+QString text = "<h2>"+ versionString() + "</h2>";
+text +=	"<h3>" + QString(copyright_string).replace("\n", "<br>") + "</h3>";
+text += "<h3>" + tr("Released") + ": " + QString(release_date) + "</h3>";
+
+text += "<h3> MantidPlot released: " + QString(MANTIDPLOT_RELEASE_DATE) + QString("</h3>");//Mantid
+
+QMessageBox *mb = new QMessageBox();
+mb->setWindowTitle (tr("About QtiPlot"));
+mb->setWindowIcon (getQPixmap("logo_xpm"));
+mb->setIconPixmap(getQPixmap("logo_xpm"));
+mb->setText(text);
+mb->exec();
+   */
+  //Mantid
+  MantidAbout *ma = new MantidAbout();
+  ma->exec();
+  delete ma;
+}
+
+void ApplicationWindow::analysisMenuAboutToShow()
+{
+  analysisMenu->clear();
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return;
+
+  if (w->isA("MultiLayer")){
+    QMenu *translateMenu = analysisMenu->addMenu (tr("&Translate"));
+    translateMenu->addAction(actionTranslateVert);
+    translateMenu->addAction(actionTranslateHor);
+    analysisMenu->insertSeparator();
+    analysisMenu->addAction(actionDifferentiate);
+    analysisMenu->addAction(actionIntegrate);
+    analysisMenu->addAction(actionShowIntDialog);
+    analysisMenu->insertSeparator();
+
+    smoothMenu->clear();
+    smoothMenu = analysisMenu->addMenu (tr("&Smooth"));
+    smoothMenu->addAction(actionSmoothSavGol);
+    smoothMenu->addAction(actionSmoothAverage);
+    smoothMenu->addAction(actionSmoothFFT);
+
+    filterMenu->clear();
+    filterMenu = analysisMenu->addMenu (tr("&FFT filter"));
+    filterMenu->addAction(actionLowPassFilter);
+    filterMenu->addAction(actionHighPassFilter);
+    filterMenu->addAction(actionBandPassFilter);
+    filterMenu->addAction(actionBandBlockFilter);
+
+    analysisMenu->insertSeparator();
+    analysisMenu->addAction(actionInterpolate);
+    analysisMenu->addAction(actionFFT);
+    analysisMenu->insertSeparator();
+    analysisMenu->addAction(actionFitLinear);
+    analysisMenu->addAction(actionShowFitPolynomDialog);
+    analysisMenu->insertSeparator();
+
+    decayMenu->clear();
+    decayMenu = analysisMenu->addMenu (tr("Fit E&xponential Decay"));
+    decayMenu->addAction(actionShowExpDecayDialog);
+    decayMenu->addAction(actionShowTwoExpDecayDialog);
+    decayMenu->addAction(actionShowExpDecay3Dialog);
+
+    analysisMenu->addAction(actionFitExpGrowth);
+    analysisMenu->addAction(actionFitSigmoidal);
+    analysisMenu->addAction(actionFitGauss);
+    analysisMenu->addAction(actionFitLorentz);
+
+    multiPeakMenu->clear();
+    multiPeakMenu = analysisMenu->addMenu (tr("Fit &Multi-peak"));
+    multiPeakMenu->addAction(actionMultiPeakGauss);
+    multiPeakMenu->addAction(actionMultiPeakLorentz);
+    analysisMenu->insertSeparator();
+    analysisMenu->addAction(actionShowFitDialog);
+  } else if (w->isA("Matrix")){
+    analysisMenu->addAction(actionIntegrate);
+    analysisMenu->insertSeparator();
+    analysisMenu->addAction(actionFFT);
+    analysisMenu->addAction(actionMatrixFFTDirect);
+    analysisMenu->addAction(actionMatrixFFTInverse);
+  } else if (w->inherits("Table")){
+    analysisMenu->addAction(actionShowColStatistics);
+    analysisMenu->addAction(actionShowRowStatistics);
+    analysisMenu->insertSeparator();
+    analysisMenu->addAction(actionSortSelection);
+    analysisMenu->addAction(actionSortTable);
+
+    normMenu->clear();
+    normMenu = analysisMenu->addMenu (tr("&Normalize"));
+    normMenu->addAction(actionNormalizeSelection);
+    normMenu->addAction(actionNormalizeTable);
+
+    analysisMenu->insertSeparator();
+    analysisMenu->addAction(actionFFT);
+    analysisMenu->insertSeparator();
+    analysisMenu->addAction(actionCorrelate);
+    analysisMenu->addAction(actionAutoCorrelate);
+    analysisMenu->insertSeparator();
+    analysisMenu->addAction(actionConvolute);
+    analysisMenu->addAction(actionDeconvolute);
+    analysisMenu->insertSeparator();
+    analysisMenu->addAction(actionShowFitDialog);
+  }
+  reloadCustomActions();
+}
+
+void ApplicationWindow::matrixMenuAboutToShow()
+{
+  matrixMenu->clear();
+  matrixMenu->addAction(actionSetMatrixProperties);
+  matrixMenu->addAction(actionSetMatrixDimensions);
+  matrixMenu->insertSeparator();
+  matrixMenu->addAction(actionSetMatrixValues);
+  matrixMenu->addAction(actionTableRecalculate);
+  matrixMenu->insertSeparator();
+  matrixMenu->addAction(actionRotateMatrix);
+  matrixMenu->addAction(actionRotateMatrixMinus);
+  matrixMenu->addAction(actionFlipMatrixVertically);
+  matrixMenu->addAction(actionFlipMatrixHorizontally);
+  matrixMenu->insertSeparator();
+  matrixMenu->addAction(actionTransposeMatrix);
+  matrixMenu->addAction(actionInvertMatrix);
+  matrixMenu->addAction(actionMatrixDeterminant);
+  matrixMenu->insertSeparator();
+  matrixMenu->addAction(actionGoToRow);
+  matrixMenu->addAction(actionGoToColumn);
+  matrixMenu->insertSeparator();
+  QMenu *matrixViewMenu = matrixMenu->addMenu (tr("Vie&w"));
+  matrixViewMenu->addAction(actionViewMatrixImage);
+  matrixViewMenu->addAction(actionViewMatrix);
+  QMenu *matrixPaletteMenu = matrixMenu->addMenu (tr("&Palette"));
+  matrixPaletteMenu->addAction(actionMatrixGrayScale);
+  matrixPaletteMenu->addAction(actionMatrixRainbowScale);
+  matrixPaletteMenu->addAction(actionMatrixCustomScale);
+  matrixMenu->insertSeparator();
+  matrixMenu->addAction(actionMatrixColumnRow);
+  matrixMenu->addAction(actionMatrixXY);
+  matrixMenu->insertSeparator();
+  QMenu *convertToTableMenu = matrixMenu->addMenu (tr("&Convert to Spreadsheet"));
+  convertToTableMenu->addAction(actionConvertMatrixDirect);
+  convertToTableMenu->addAction(actionConvertMatrixXYZ);
+  convertToTableMenu->addAction(actionConvertMatrixYXZ);
+
+  Matrix* m = (Matrix*)activeWindow(MatrixWindow);
+  if (!m)
+    return;
+
+  actionViewMatrixImage->setChecked(m->viewType() == Matrix::ImageView);
+  actionViewMatrix->setChecked(m->viewType() == Matrix::TableView);
+  actionMatrixColumnRow->setChecked(m->headerViewType() == Matrix::ColumnRow);
+  actionMatrixColumnRow->setEnabled(m->viewType() == Matrix::TableView);
+  actionMatrixXY->setChecked(m->headerViewType() == Matrix::XY);
+  actionMatrixXY->setEnabled(m->viewType() == Matrix::TableView);
+
+  actionMatrixGrayScale->setChecked(m->colorMapType() == Matrix::GrayScale);
+  actionMatrixRainbowScale->setChecked(m->colorMapType() == Matrix::Rainbow);
+  actionMatrixCustomScale->setChecked(m->colorMapType() == Matrix::Custom);
+
+  reloadCustomActions();
+}
+
+void ApplicationWindow::fileMenuAboutToShow()
+{
+  fileMenu->clear();
+  newMenu->clear();
+  exportPlotMenu->clear();
+
+  newMenu = fileMenu->addMenu(tr("&New"));
+  newMenu->addAction(actionNewProject);
+  newMenu->addAction(actionNewFolder);
+  newMenu->addAction(actionNewTable);
+  newMenu->addAction(actionNewMatrix);
+  newMenu->addAction(actionNewNote);
+  newMenu->addAction(actionNewGraph);
+  newMenu->addAction(actionNewFunctionPlot);
+  newMenu->addAction(actionNewSurfacePlot);
+
+
+  openMenu=fileMenu->addMenu(tr("&Load"));
+  openMenu->addAction(actionOpenProj);
+  openMenu->addAction(actionLoadFile);
+
+  recentMenuID = fileMenu->insertItem(tr("&Recent Projects"), recent);
+
+  fileMenu->insertSeparator();
+  fileMenu->addAction(actionManageDirs);
+  fileMenu->insertSeparator();
+  fileMenu->addAction(actionLoadImage);
+
+  MdiSubWindow *w = activeWindow();
+  if (w && w->isA("Matrix"))
+    fileMenu->addAction(actionExportMatrix);
+
+  fileMenu->insertSeparator();
+  fileMenu->addAction(actionSaveProjectAs);
+  //fileMenu->insertSeparator();
+  saveMenu=fileMenu->addMenu(tr("&Save"));
+  saveMenu->addAction(actionSaveFile);
+  saveMenu->addAction(actionSaveProject);
+
+  fileMenu->insertSeparator();
+
+  fileMenu->addAction(actionPrint);
+  fileMenu->addAction(actionPrintAllPlots);
+  fileMenu->insertSeparator();
+  MdiSubWindow* t = activeWindow();
+  if (t && (t->isA("Matrix") || t->inherits("Table") || t->isA("MantidMatrix")))
+  {
+    actionShowExportASCIIDialog->setEnabled(true);
+  }
+  else
+  {
+    actionShowExportASCIIDialog->setEnabled(false);
+  }
+
+  fileMenu->addAction(actionShowExportASCIIDialog);
+  fileMenu->addAction(actionLoad);
+  fileMenu->insertSeparator();
+  fileMenu->addAction(actionclearAllMemory);
+#ifdef USE_TCMALLOC
+  fileMenu->addAction(actionreleaseFreeMemory);
+#endif
+
+  fileMenu->insertSeparator();
+  fileMenu->addAction(actionCloseAllWindows);
+
+  reloadCustomActions();
+}
+
+void ApplicationWindow::editMenuAboutToShow()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w){
+    actionUndo->setEnabled(false);
+    actionRedo->setEnabled(false);
+    return;
+  }
+
+  if (qobject_cast<Note *>(w)){
+    ScriptEdit* doc = ((Note *)w)->editor();
+    actionUndo->setEnabled(doc->isUndoAvailable());
+    actionRedo->setEnabled(doc->isRedoAvailable());
+  } else if (qobject_cast<Matrix *>(w)){
+    QUndoStack *stack = ((Matrix *)w)->undoStack();
+    actionUndo->setEnabled(stack->canUndo());
+    actionRedo->setEnabled(stack->canRedo());
+  } else {
+    actionUndo->setEnabled(false);
+    actionRedo->setEnabled(false);
+  }
+
+  reloadCustomActions();
+}
+
+void ApplicationWindow::windowsMenuAboutToShow()
+{
+  windowsMenu->clear();
+  foldersMenu->clear();
+
+  int folder_param = 0;
+  Folder *f = projectFolder();
+  while (f){
+    int id;
+    if (folder_param < 9)
+      id = foldersMenu->insertItem("&" + QString::number(folder_param+1) + " " + f->path(), this, SLOT(foldersMenuActivated(int)));
+    else
+      id = foldersMenu->insertItem(f->path(), this, SLOT(foldersMenuActivated(int)));
+
+    foldersMenu->setItemParameter(id, folder_param);
+    folder_param++;
+    foldersMenu->setItemChecked(id, f == current_folder);
+
+    f = f->folderBelow();
+  }
+
+  windowsMenu->insertItem(tr("&Folders"), foldersMenu);
+  windowsMenu->insertSeparator();
+
+  QList<MdiSubWindow *> windows = current_folder->windowsList();
+  int n = int(windows.count());
+  if (!n ){
+    /*#ifdef SCRIPTING_PYTHON
+			windowsMenu->addAction(actionShowScriptWindow);
+		#endif*/
+    return;
+  }
+
+  windowsMenu->insertItem(tr("&Cascade"), this, SLOT(cascade()));
+  windowsMenu->insertItem(tr("&Tile"), d_workspace, SLOT(tileSubWindows()));
+  windowsMenu->insertSeparator();
+  windowsMenu->addAction(actionNextWindow);
+  windowsMenu->addAction(actionPrevWindow);
+  windowsMenu->insertSeparator();
+  windowsMenu->addAction(actionRename);
+
+  windowsMenu->addAction(actionCopyWindow);
+  MdiSubWindow* activeWin=activeWindow();
+  if(!activeWin) return;
+  if(activeWin->isA("MantidMatrix") || activeWin->isA("InstrumentWindow") )
+  {
+    actionCopyWindow->setEnabled(false);
+  }
+  else
+  {
+    actionCopyWindow->setEnabled(true);
+  }
+
+  windowsMenu->insertSeparator();
+
+
+  windowsMenu->addAction(actionResizeActiveWindow);
+  windowsMenu->insertItem(tr("&Hide Window"),
+      this, SLOT(hideActiveWindow()));
+
+  // Having the shorcut set here is neccessary on Windows, but
+  // leads to an error message elsewhere. Don't know why and don't 
+  // have a better solution than this right now.
+#ifdef _WIN32
+  windowsMenu->insertItem(getQPixmap("close_xpm"), tr("Close &Window"),  
+                   this, SLOT(closeActiveWindow()), Qt::CTRL+Qt::Key_W );  
+#else
+  windowsMenu->insertItem(getQPixmap("close_xpm"), tr("Close &Window"),
+			  this, SLOT(closeActiveWindow()) );
+#endif
+
+  if (n>0 && n<10){
+    windowsMenu->insertSeparator();
+    for (int i = 0; i<n; ++i ){
+      int id = windowsMenu->insertItem(windows.at(i)->objectName(),
+          this, SLOT( windowsMenuActivated( int ) ) );
+      windowsMenu->setItemParameter( id, i );
+      windowsMenu->setItemChecked( id, current_folder->activeWindow() == windows.at(i));
+    }
+  } else if (n>=10) {
+    windowsMenu->insertSeparator();
+    for ( int i = 0; i<9; ++i ){
+      int id = windowsMenu->insertItem(windows.at(i)->objectName(),
+          this, SLOT( windowsMenuActivated( int ) ) );
+      windowsMenu->setItemParameter( id, i );
+      windowsMenu->setItemChecked( id, activeWindow() == windows.at(i) );
+    }
+    windowsMenu->insertSeparator();
+    windowsMenu->insertItem(tr("More windows..."),this, SLOT(showMoreWindows()));
+  }
+  reloadCustomActions();
+}
+
+void ApplicationWindow::showMarkerPopupMenu()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  QMenu markerMenu(this);
+
+  if (g->imageMarkerSelected()){
+    markerMenu.insertItem(getQPixmap("pixelProfile_xpm"),tr("&View Pixel Line profile"),this, SLOT(pixelLineProfile()));
+    markerMenu.insertItem(tr("&Intensity Matrix"),this, SLOT(intensityTable()));
+    markerMenu.insertSeparator();
+  }
+
+  markerMenu.insertItem(getQPixmap("cut_xpm"),tr("&Cut"),this, SLOT(cutSelection()));
+  markerMenu.insertItem(getQPixmap("copy_xpm"), tr("&Copy"),this, SLOT(copySelection()));
+  markerMenu.insertItem(getQPixmap("erase_xpm"), tr("&Delete"),this, SLOT(clearSelection()));
+  markerMenu.insertSeparator();
+  if (g->arrowMarkerSelected())
+    markerMenu.insertItem(tr("&Properties..."),this, SLOT(showLineDialog()));
+  else if (g->imageMarkerSelected())
+    markerMenu.insertItem(tr("&Properties..."),this, SLOT(showImageDialog()));
+  else
+    markerMenu.insertItem(tr("&Properties..."),this, SLOT(showTextDialog()));
+
+  markerMenu.exec(QCursor::pos());
+}
+
+void ApplicationWindow::showMoreWindows()
+{
+  if (explorerWindow->isVisible())
+    QMessageBox::information(this, "MantidPlot",tr("Please use the project explorer to select a window!"));//Mantid
+  else
+    explorerWindow->show();
+}
+
+void ApplicationWindow::windowsMenuActivated( int id )
+{
+  QList<MdiSubWindow *> windows = current_folder->windowsList();
+  MdiSubWindow* w = windows.at( id );
+  if ( w ){
+    w->showNormal();
+    w->setFocus();
+    if(hidden(w)){
+      hiddenWindows->takeAt(hiddenWindows->indexOf(w));
+      setListView(w->objectName(), tr("Normal"));
+    }
+    d_workspace->setActiveSubWindow(w);
+  }
+}
+
+void ApplicationWindow::foldersMenuActivated( int id )
+{
+  int folder_param = 0;
+  Folder *f = projectFolder();
+  while (f){
+    if (folder_param == id){
+      changeFolder (f);
+      return;
+    }
+
+    folder_param++;
+    f = f->folderBelow();
+  }
+}
+
+void ApplicationWindow::newProject()
+{
+  saveSettings();//the recent projects must be saved
+  mantidUI->saveProject(saved);
+  clearLogInfo();
+  setWindowTitle(tr("MantidPlot - untitled"));//Mantid
+}
+
+void ApplicationWindow::savedProject()
+{	QCoreApplication::processEvents();
+if(actionSaveFile) actionSaveFile->setEnabled(false);
+if(actionSaveProject)actionSaveProject->setEnabled(false);
+saved = true;
+
+Folder *f = projectFolder();
+while (f){
+  QList<MdiSubWindow *> folderWindows = f->windowsList();
+  foreach(MdiSubWindow *w, folderWindows){
+    if (w->isA("Matrix"))
+      ((Matrix *)w)->undoStack()->setClean();
+  }
+  f = f->folderBelow();
+}
+}
+
+void ApplicationWindow::modifiedProject()
+{
+  if (saved == false)
+    return;
+  if(actionSaveFile) actionSaveFile->setEnabled(true);
+  if(actionSaveProject)actionSaveProject->setEnabled(true);
+  saved = false;
+}
+
+void ApplicationWindow::modifiedProject(MdiSubWindow *)
+{
+  modifiedProject();
+}
+
+void ApplicationWindow::timerEvent ( QTimerEvent *e)
+{
+  if (e->timerId() == savingTimerId)
+    saveProject();
+  else
+    QWidget::timerEvent(e);
+}
+
+void ApplicationWindow::dropEvent( QDropEvent* e )
+{
+  if (mantidUI->drop(e)) return;//Mantid
+
+  QStringList fileNames;
+  if (Q3UriDrag::decodeLocalFiles(e, fileNames)){
+    QList<QByteArray> lst = QImageReader::supportedImageFormats() << "JPG";
+    QStringList asciiFiles;
+
+    for(int i = 0; i<(int)fileNames.count(); i++){
+      QString fn = fileNames[i];
+      QFileInfo fi (fn);
+      QString ext = fi.extension().lower();
+      QStringList tempList;
+      QByteArray temp;
+      // convert QList<QByteArray> to QStringList to be able to 'filter'
+      foreach(temp,lst)
+      tempList.append(QString(temp));
+      QStringList l = tempList.filter(ext, Qt::CaseInsensitive);
+      if (l.count()>0)
+        loadImage(fn);
+      else if ( ext == "opj" || ext == "qti")
+        open(fn);
+      else
+        asciiFiles << fn;
+    }
+
+    importASCII(asciiFiles, ImportASCIIDialog::NewTables, columnSeparator, ignoredLines,
+        renameColumns, strip_spaces, simplify_spaces, d_ASCII_import_comments,
+        d_import_dec_separators, d_ASCII_import_locale, d_ASCII_comment_string,
+        d_ASCII_import_read_only, d_ASCII_end_line,"");
+  }
+}
+
+void ApplicationWindow::dragEnterEvent( QDragEnterEvent* e )
+{
+  if (e->source()){
+    //e->ignore();//Mantid
+    e->accept();//Mantid
+    return;
+  }
+  else//Mantid
+    e->accept(Q3UriDrag::canDecode(e));
+}
+
+//Mantid
+void ApplicationWindow::dragMoveEvent( QDragMoveEvent* e )
+{
+  if (centralWidget()->geometry().contains(e->pos())) e->accept();
+  else
+    e->ignore();
+}
+
+void ApplicationWindow::closeEvent( QCloseEvent* ce )
+{
+#ifdef QTIPLOT_DEMO
+  showDemoVersionMessage();
+#endif
+
+  // Mantid changes here
+
+  if( scriptingEnv()->isRunning() )
+  {
+    if( QMessageBox::question(this, tr("MantidPlot"), "A script is still running, abort and quit application?", tr("Yes"), tr("No")) == 0 )
+    {
+      mantidUI->cancelAllRunningAlgorithms();
+    }
+    else
+    {
+      ce->ignore();
+      return;
+    }	  
+  }
+
+  if( !saved )
+  {
+    QString savemsg = tr("Save changes to project: <p><b> %1 </b> ?").arg(projectname);
+    int result = QMessageBox::information(this, tr("MantidPlot"), savemsg, tr("Yes"), tr("No"), tr("Cancel"), 0, 2);
+    if( result == 2 || (result == 0 && !saveProject()) )
+    {
+      ce->ignore();
+      return;
+    }
+  }
+  
+
+  if( scriptingWindow )
+  {
+    this->showScriptWindow(true);
+    scriptingWindow->saveSettings();
+    scriptingWindow->acceptCloseEvent(true);
+    scriptingWindow->close();
+  }
+
+  //Save the settings and exit
+  saveSettings();
+  mantidUI->shutdown();
+  ce->accept();
+
+}
+
+void ApplicationWindow::customEvent(QEvent *e)
+{
+  if (e->type() == SCRIPTING_CHANGE_EVENT)
+    scriptingChangeEvent((ScriptingChangeEvent*)e);
+}
+
+void ApplicationWindow::deleteSelectedItems()
+{
+  if (folders->hasFocus() && folders->currentItem() != folders->firstChild())
+  {//we never allow the user to delete the project folder item
+    deleteFolder();
+    return;
+  }
+
+  Q3ListViewItem *item;
+  QList<Q3ListViewItem *> lst;
+  for (item = lv->firstChild(); item; item = item->nextSibling()){
+    if (item->isSelected())
+      lst.append(item);
+  }
+
+  folders->blockSignals(true);
+  foreach(item, lst){
+    if (item->rtti() == FolderListItem::RTTI){
+      Folder *f = ((FolderListItem *)item)->folder();
+      if (deleteFolder(f))
+        delete item;
+    } else
+      ((WindowListItem *)item)->window()->close();
+  }
+  folders->blockSignals(false);
+}
+
+void ApplicationWindow::showListViewSelectionMenu(const QPoint &p)
+{
+  QMenu cm(this);
+  cm.insertItem(tr("&Show All Windows"), this, SLOT(showSelectedWindows()));
+  cm.insertItem(tr("&Hide All Windows"), this, SLOT(hideSelectedWindows()));
+  cm.insertSeparator();
+  cm.insertItem(tr("&Delete Selection"), this, SLOT(deleteSelectedItems()), Qt::Key_F8);
+  cm.exec(p);
+}
+
+void ApplicationWindow::showListViewPopupMenu(const QPoint &p)
+{
+  QMenu cm(this);
+  QMenu window(this);
+
+  window.addAction(actionNewTable);
+  window.addAction(actionNewMatrix);
+  window.addAction(actionNewNote);
+  window.addAction(actionNewGraph);
+  window.addAction(actionNewFunctionPlot);
+  window.addAction(actionNewSurfacePlot);
+  cm.insertItem(tr("New &Window"), &window);
+
+  cm.insertItem(getQPixmap("newfolder_xpm"), tr("New F&older"), this, SLOT(addFolder()), Qt::Key_F7);
+  cm.insertSeparator();
+  cm.insertItem(tr("Auto &Column Width"), lv, SLOT(adjustColumns()));
+  cm.exec(p);
+}
+
+void ApplicationWindow::showWindowPopupMenu(Q3ListViewItem *it, const QPoint &p, int)
+{
+  if (folders->isRenaming())
+    return;
+
+  if (!it){
+    showListViewPopupMenu(p);
+    return;
+  }
+
+  Q3ListViewItem *item;
+  int selected = 0;
+  for (item = lv->firstChild(); item; item = item->nextSibling()){
+    if (item->isSelected())
+      selected++;
+
+    if (selected>1){
+      showListViewSelectionMenu(p);
+      return;
+    }
+  }
+
+  if (it->rtti() == FolderListItem::RTTI){
+    current_folder = ((FolderListItem *)it)->folder();
+    showFolderPopupMenu(it, p, false);
+    return;
+  }
+
+  MdiSubWindow *w= ((WindowListItem *)it)->window();
+  if (w){
+    QMenu cm(this);
+    QMenu plots(this);
+
+    cm.addAction(actionActivateWindow);
+    cm.addAction(actionMinimizeWindow);
+    cm.addAction(actionMaximizeWindow);
+    cm.insertSeparator();
+    if (!hidden(w))
+      cm.addAction(actionHideWindow);
+    cm.insertItem(getQPixmap("close_xpm"), tr("&Delete Window"), w, SLOT(close()), Qt::Key_F8);
+    cm.insertSeparator();
+    cm.insertItem(tr("&Rename Window"), this, SLOT(renameWindow()), Qt::Key_F2);
+    cm.addAction(actionResizeWindow);
+    cm.insertSeparator();
+    cm.insertItem(getQPixmap("fileprint_xpm"), tr("&Print Window"), w, SLOT(print()));
+    cm.insertSeparator();
+    cm.insertItem(tr("&Properties..."), this, SLOT(windowProperties()));
+
+    if (w->inherits("Table")){
+      QStringList graphs = dependingPlots(w->objectName());
+      if (int(graphs.count())>0){
+        cm.insertSeparator();
+        for (int i=0;i<int(graphs.count());i++)
+          plots.insertItem(graphs[i], window(graphs[i]), SLOT(showMaximized()));
+
+        cm.insertItem(tr("D&epending Graphs"),&plots);
+      }
+    } else if (w->isA("Matrix")){
+      QStringList graphs = depending3DPlots((Matrix*)w);
+      if (int(graphs.count())>0){
+        cm.insertSeparator();
+        for (int i=0;i<int(graphs.count());i++)
+          plots.insertItem(graphs[i], window(graphs[i]), SLOT(showMaximized()));
+
+        cm.insertItem(tr("D&epending 3D Graphs"),&plots);
+      }
+    } else if (w->isA("MultiLayer")) {
+      tablesDepend->clear();
+      QStringList tbls=multilayerDependencies(w);
+      int n = int(tbls.count());
+      if (n > 0){
+        cm.insertSeparator();
+        for (int i=0; i<n; i++)
+          tablesDepend->insertItem(tbls[i], i, -1);
+
+        cm.insertItem(tr("D&epends on"), tablesDepend);
+      }
+    } else if (w->isA("Graph3D")) {
+      Graph3D *sp=(Graph3D*)w;
+      Matrix *m = sp->matrix();
+      QString formula = sp->formula();
+      if (!formula.isEmpty()){
+        cm.insertSeparator();
+        if (formula.contains("_")){
+          QStringList tl = formula.split("_", QString::SkipEmptyParts);
+          tablesDepend->clear();
+          tablesDepend->insertItem(tl[0], 0, -1);
+          cm.insertItem(tr("D&epends on"), tablesDepend);
+        } else if (m) {
+          plots.insertItem(m->objectName(), m, SLOT(showNormal()));
+          cm.insertItem(tr("D&epends on"),&plots);
+        } else {
+          plots.insertItem(formula, w, SLOT(showNormal()));
+          cm.insertItem(tr("Function"), &plots);
+        }
+      }
+    }
+    cm.exec(p);
+  }
+}
+
+void ApplicationWindow::showTable(int i)
+{
+  Table *t = table(tablesDepend->text(i));
+  if (!t)
+    return;
+
+  updateWindowLists(t);
+
+  t->showMaximized();
+  Q3ListViewItem *it=lv->findItem (t->objectName(), 0, Q3ListView::ExactMatch | Qt::CaseSensitive );
+  if (it)
+    it->setText(2,tr("Maximized"));
+}
+
+void ApplicationWindow::showTable(const QString& curve)
+{
+  Table* w=table(curve);
+  if (!w)
+    return;
+
+  updateWindowLists(w);
+  int colIndex = w->colIndex(curve);
+  w->setSelectedCol(colIndex);
+  w->table()->clearSelection();
+  w->table()->selectColumn(colIndex);
+  w->showMaximized();
+  Q3ListViewItem *it=lv->findItem (w->objectName(), 0, Q3ListView::ExactMatch | Qt::CaseSensitive );
+  if (it)
+    it->setText(2,tr("Maximized"));
+  emit modified();
+}
+
+QStringList ApplicationWindow::depending3DPlots(Matrix *m)
+{
+  QStringList plots;
+  QList<MdiSubWindow *> windows = windowsList();
+  foreach(MdiSubWindow *w, windows){
+    if (w->isA("Graph3D") && ((Graph3D *)w)->matrix() == m)
+      plots << w->objectName();
+  }
+  return plots;
+}
+
+QStringList ApplicationWindow::dependingPlots(const QString& name)
+{
+  QStringList onPlot, plots;
+
+  QList<MdiSubWindow *> windows = windowsList();
+  foreach(MdiSubWindow *w, windows){
+    if (w->isA("MultiLayer")){
+      QList<Graph *> layers = ((MultiLayer*)w)->layersList();
+      foreach(Graph *g, layers){
+        onPlot = g->curvesList();
+        onPlot = onPlot.grep (name,TRUE);
+        if (int(onPlot.count()) && plots.contains(w->objectName())<=0)
+          plots << w->objectName();
+      }
+    }else if (w->isA("Graph3D")){
+      if ((((Graph3D*)w)->formula()).contains(name,TRUE) && plots.contains(w->objectName())<=0)
+        plots << w->objectName();
+    }
+  }
+  return plots;
+}
+
+QStringList ApplicationWindow::multilayerDependencies(QWidget *w)
+{
+  QStringList tables;
+  MultiLayer *g=(MultiLayer*)w;
+  QList<Graph *> layers = g->layersList();
+  foreach(Graph *ag, layers){
+    QStringList onPlot=ag->curvesList();
+    for (int j=0; j<onPlot.count(); j++)
+    {
+      QStringList tl = onPlot[j].split("_", QString::SkipEmptyParts);
+      if (tables.contains(tl[0])<=0)
+        tables << tl[0];
+    }
+  }
+  return tables;
+}
+
+void ApplicationWindow::showGraphContextMenu()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  QMenu cm(this);
+  Graph* ag = (Graph*)plot->activeGraph();
+  PlotToolInterface* tool = ag->activeTool();
+  if (dynamic_cast<PeakPickerTool*>(tool))
+  {
+    dynamic_cast<PeakPickerTool*>(tool)->prepareContextMenu(cm);
+    cm.exec(QCursor::pos());
+    return;
+  }
+
+  QMenu axes(this);
+  QMenu colour(this);
+  QMenu exports(this);
+  QMenu copy(this);
+  QMenu prints(this);
+
+  if (ag->isPiePlot())
+    cm.insertItem(tr("Re&move Pie Curve"),ag, SLOT(removePie()));
+  else {
+    if (ag->visibleCurves() != ag->curves()){
+      cm.addAction(actionShowAllCurves);
+      cm.insertSeparator();
+    }
+    cm.addAction(actionShowCurvesDialog);
+    cm.addAction(actionAddFunctionCurve);
+    //cm.insertItem(tr("Anal&yze"), analysisMenu);
+  }
+
+  if (lastCopiedLayer){
+    cm.insertSeparator();
+    cm.insertItem(getQPixmap("paste_xpm"), tr("&Paste Layer"), this, SLOT(pasteSelection()));
+  } else if (d_text_copy){
+    cm.insertSeparator();
+    cm.insertItem(getQPixmap("paste_xpm"), tr("&Paste Text"), plot, SIGNAL(pasteMarker()));
+  } else if (d_arrow_copy){
+    cm.insertSeparator();
+    cm.insertItem(getQPixmap("paste_xpm"), tr("&Paste Line/Arrow"), plot, SIGNAL(pasteMarker()));
+  } else if (d_image_copy){
+    cm.insertSeparator();
+    cm.insertItem(getQPixmap("paste_xpm"), tr("&Paste Image"), plot, SIGNAL(pasteMarker()));
+  }
+  cm.insertSeparator();
+  axes.insertItem(tr("Lo&g(x),Log(y)"), ag, SLOT(logLogAxes()));
+  axes.insertItem(tr("Log(&x),Linear(y)"), ag, SLOT(logXLinY()));
+  axes.insertItem(tr("Linear(x),Log(&y)"), ag, SLOT(logYlinX()));
+  axes.insertItem(tr("&Linear(x),Linear(y)"), ag, SLOT(linearAxes()));
+  cm.insertItem(tr("&Axes"), &axes);
+
+  colour.insertItem(tr("Lo&g Scale"), ag, SLOT(logColor()));
+  colour.insertItem(tr("&Linear"), ag, SLOT(linColor()));
+  cm.insertItem(tr("&Color Bar"), &colour);
+
+  cm.insertSeparator();
+  copy.insertItem(tr("&Layer"), this, SLOT(copyActiveLayer()));
+  copy.insertItem(tr("&Window"), plot, SLOT(copyAllLayers()));
+  cm.insertItem(getQPixmap("copy_xpm"), tr("&Copy"), &copy);
+
+  exports.insertItem(tr("&Layer"), this, SLOT(exportLayer()));
+  exports.insertItem(tr("&Window"), this, SLOT(exportGraph()));
+  cm.insertItem(tr("E&xport"),&exports);
+
+  prints.insertItem(tr("&Layer"), plot, SLOT(printActiveLayer()));
+  prints.insertItem(tr("&Window"), plot, SLOT(print()));
+  cm.insertItem(getQPixmap("fileprint_xpm"), tr("&Print"),&prints);
+  cm.insertSeparator();
+  cm.insertItem(tr("P&roperties..."), this, SLOT(showGeneralPlotDialog()));
+  cm.insertSeparator();
+  cm.insertItem(getQPixmap("close_xpm"), tr("&Delete Layer"), plot, SLOT(confirmRemoveLayer()));
+  cm.exec(QCursor::pos());
+}
+
+void ApplicationWindow::showWindowContextMenu()
+{
+  MdiSubWindow* w = activeWindow();
+  if (!w)
+    return;
+
+
+  QMenu cm(this);
+  QMenu plot3D(this);
+  if (w->isA("MultiLayer")){
+    MultiLayer *g = (MultiLayer*)w;
+    if (lastCopiedLayer){
+      cm.insertItem(getQPixmap("paste_xpm"), tr("&Paste Layer"), this, SLOT(pasteSelection()));
+      cm.insertSeparator();
+    }
+
+    cm.addAction(actionAddLayer);
+    if (g->layers() != 0)
+      cm.addAction(actionDeleteLayer);
+
+    cm.addAction(actionShowLayerDialog);
+    cm.insertSeparator();
+    cm.addAction(actionRename);
+    cm.addAction(actionCopyWindow);
+    cm.insertSeparator();
+    cm.insertItem(getQPixmap("copy_xpm"),tr("&Copy Page"), g, SLOT(copyAllLayers()));
+    cm.insertItem(tr("E&xport Page"), this, SLOT(exportGraph()));
+    cm.addAction(actionPrint);
+    cm.insertSeparator();
+    cm.addAction(actionCloseWindow);
+  } else if (w->isA("Graph3D")){
+    Graph3D *g=(Graph3D*)w;
+    if (!g->hasData()){
+      cm.insertItem(tr("3D &Plot"), &plot3D);
+      plot3D.addAction(actionAdd3DData);
+      plot3D.insertItem(tr("&Matrix..."), this, SLOT(add3DMatrixPlot()));
+      plot3D.addAction(actionEditSurfacePlot);
+    } else {
+      if (g->table())
+        cm.insertItem(tr("Choose &Data Set..."), this, SLOT(change3DData()));
+      else if (g->matrix())
+        cm.insertItem(tr("Choose &Matrix..."), this, SLOT(change3DMatrix()));
+      else if (g->userFunction() || g->parametricSurface())
+        cm.addAction(actionEditSurfacePlot);
+      cm.insertItem(getQPixmap("erase_xpm"), tr("C&lear"), g, SLOT(clearData()));
+    }
+
+    cm.insertSeparator();
+    cm.addAction(actionRename);
+    cm.addAction(actionCopyWindow);
+    cm.insertSeparator();
+    cm.insertItem(tr("&Copy Graph"), g, SLOT(copyImage()));
+    cm.insertItem(tr("&Export"), this, SLOT(exportGraph()));
+    cm.addAction(actionPrint);
+    cm.insertSeparator();
+    cm.addAction(actionCloseWindow);
+  } else if (w->isA("Matrix")) {
+    Matrix *t = (Matrix *)w;
+    if (t->viewType() == Matrix::TableView){
+      cm.insertItem(getQPixmap("cut_xpm"),tr("Cu&t"), t, SLOT(cutSelection()));
+      cm.insertItem(getQPixmap("copy_xpm"),tr("&Copy"), t, SLOT(copySelection()));
+      cm.insertItem(getQPixmap("paste_xpm"),tr("&Paste"), t, SLOT(pasteSelection()));
+      cm.insertSeparator();
+      cm.insertItem(getQPixmap("insert_row_xpm"), tr("&Insert Row"), t, SLOT(insertRow()));
+      cm.insertItem(getQPixmap("insert_column_xpm"), tr("&Insert Column"), t, SLOT(insertColumn()));
+      if (t->numSelectedRows() > 0)
+        cm.insertItem(getQPixmap("delete_row_xpm"), tr("&Delete Rows"), t, SLOT(deleteSelectedRows()));
+      else if (t->numSelectedColumns() > 0)
+        cm.insertItem(getQPixmap("delete_column_xpm"), tr("&Delete Columns"), t, SLOT(deleteSelectedColumns()));
+
+      cm.insertItem(getQPixmap("erase_xpm"),tr("Clea&r"), t, SLOT(clearSelection()));
+    } else if (t->viewType() == Matrix::ImageView){
+      cm.addAction(actionImportImage);
+      cm.addAction(actionExportMatrix);
+      cm.insertSeparator();
+      cm.addAction(actionSetMatrixProperties);
+      cm.addAction(actionSetMatrixDimensions);
+      cm.insertSeparator();
+      cm.addAction(actionSetMatrixValues);
+      cm.addAction(actionTableRecalculate);
+      cm.insertSeparator();
+      cm.addAction(actionRotateMatrix);
+      cm.addAction(actionRotateMatrixMinus);
+      cm.insertSeparator();
+      cm.addAction(actionFlipMatrixVertically);
+      cm.addAction(actionFlipMatrixHorizontally);
+      cm.insertSeparator();
+      cm.addAction(actionTransposeMatrix);
+      cm.addAction(actionInvertMatrix);
+    }
+  } else
+    mantidUI->showContextMenu(cm,w);//Mantid
+  cm.exec(QCursor::pos());
+}
+
+void ApplicationWindow::customWindowTitleBarMenu(MdiSubWindow *w, QMenu *menu)
+{
+  menu->addAction(actionHideActiveWindow);
+  menu->addSeparator();
+  if (w->inherits("Table")){
+    menu->addAction(actionShowExportASCIIDialog);
+    menu->addSeparator();
+  }
+
+  if (w->isA("Note"))
+    menu->addAction(actionSaveNote);
+  else
+    menu->addAction(actionSaveTemplate);
+  menu->addAction(actionPrint);
+  menu->addSeparator();
+  menu->addAction(actionRename);
+  menu->addAction(actionCopyWindow);
+  menu->addSeparator();
+}
+
+void ApplicationWindow::showTableContextMenu(bool selection)
+{
+  Table *t = (Table*)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  QMenu cm(this);
+  if (selection){
+    if ((int)t->selectedColumns().count() > 0){
+      showColMenu(t->firstSelectedColumn());
+      return;
+    } else if (t->numSelectedRows() == 1) {
+      cm.addAction(actionShowColumnValuesDialog);
+      cm.insertItem(getQPixmap("cut_xpm"),tr("Cu&t"), t, SLOT(cutSelection()));
+      cm.insertItem(getQPixmap("copy_xpm"),tr("&Copy"), t, SLOT(copySelection()));
+      cm.insertItem(getQPixmap("paste_xpm"),tr("&Paste"), t, SLOT(pasteSelection()));
+      cm.insertSeparator();
+      cm.addAction(actionTableRecalculate);
+      cm.insertItem(getQPixmap("insert_row_xpm"), tr("&Insert Row"), t, SLOT(insertRow()));
+      cm.insertItem(getQPixmap("delete_row_xpm"), tr("&Delete Row"), t, SLOT(deleteSelectedRows()));
+      cm.insertItem(getQPixmap("erase_xpm"), tr("Clea&r Row"), t, SLOT(clearSelection()));
+      cm.insertSeparator();
+      cm.addAction(actionShowRowStatistics);
+    } else if (t->numSelectedRows() > 1) {
+      cm.addAction(actionShowColumnValuesDialog);
+      cm.insertItem(getQPixmap("cut_xpm"),tr("Cu&t"), t, SLOT(cutSelection()));
+      cm.insertItem(getQPixmap("copy_xpm"),tr("&Copy"), t, SLOT(copySelection()));
+      cm.insertItem(getQPixmap("paste_xpm"),tr("&Paste"), t, SLOT(pasteSelection()));
+      cm.insertSeparator();
+      cm.addAction(actionTableRecalculate);
+      cm.insertItem(getQPixmap("delete_row_xpm"), tr("&Delete Rows"), t, SLOT(deleteSelectedRows()));
+      cm.insertItem(getQPixmap("erase_xpm"),tr("Clea&r Rows"), t, SLOT(clearSelection()));
+      cm.insertSeparator();
+      cm.addAction(actionShowRowStatistics);
+    } else if (t->numRows() > 0 && t->numCols() > 0){
+      cm.addAction(actionShowColumnValuesDialog);
+      cm.insertItem(getQPixmap("cut_xpm"),tr("Cu&t"), t, SLOT(cutSelection()));
+      cm.insertItem(getQPixmap("copy_xpm"),tr("&Copy"), t, SLOT(copySelection()));
+      cm.insertItem(getQPixmap("paste_xpm"),tr("&Paste"), t, SLOT(pasteSelection()));
+      cm.insertSeparator();
+      cm.addAction(actionTableRecalculate);
+      cm.insertItem(getQPixmap("erase_xpm"),tr("Clea&r"), t, SLOT(clearSelection()));
+    }
+  } else {
+    cm.addAction(actionShowExportASCIIDialog);
+    cm.insertSeparator();
+    cm.addAction(actionAddColToTable);
+    cm.addAction(actionClearTable);
+    cm.insertSeparator();
+    cm.addAction(actionGoToRow);
+    cm.addAction(actionGoToColumn);
+  }
+  cm.exec(QCursor::pos());
+}
+
+void ApplicationWindow::chooseHelpFolder()
+{
+  QFileInfo hfi(helpFilePath);
+  QString dir = QFileDialog::getExistingDirectory(this, tr("Choose the location of the MantidPlot help folder!"),
+      hfi.dir().absolutePath(), 0 /**QFileDialog::ShowDirsOnly*/);
+
+  if (!dir.isEmpty()){
+    helpFilePath = dir + "index.html";
+
+    QFile helpFile(helpFilePath);
+    if (!helpFile.exists()){
+      QMessageBox::critical(this, tr("MantidPlot - index.html File Not Found!"),//Mantid
+          tr("There is no file called <b>index.html</b> in this folder.<br>Please choose another folder!"));
+    }
+  }
+}
+
+void ApplicationWindow::showStandAloneHelp()
+{
+#ifdef Q_OS_MAC // Mac
+  QSettings settings(QSettings::IniFormat,QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName());
+#else
+  QSettings settings;//(QSettings::NativeFormat,QSettings::UserScope, "ProIndependent", "QtiPlot");
+#endif
+
+  settings.beginGroup("/General");
+  settings.beginGroup("/Paths");
+  QString helpPath = settings.value("/HelpFile", qApp->applicationDirPath()+"/manual/index.html").toString();
+  settings.endGroup();
+  settings.endGroup();
+
+  QFile helpFile(helpPath);
+  if (!helpPath.isEmpty() && !helpFile.exists())
+  {
+    QMessageBox::critical(0, tr("MantidPlot - Help Files Not Found!"),//Mantid
+        tr("The manual can be downloaded from the following internet address:")+
+        "<p><a href = http://soft.proindependent.com/manuals.html>http://soft.proindependent.com/manuals.html</a></p>");
+    exit(0);
+  }
+
+  QFileInfo fi(helpPath);
+  QString profilePath = QString(fi.dirPath(true)+"/qtiplot.adp");
+  if (!QFile(profilePath).exists())
+  {
+    QMessageBox::critical(0, 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")+"<br>"+
+        tr("This file is provided with the MantidPlot manual which can be downloaded from the following internet address:")+
+        "<p><a href = http://soft.proindependent.com/manuals.html>http://soft.proindependent.com/manuals.html</a></p>");
+    exit(0);
+  }
+
+  QStringList cmdLst = QStringList() << "-profile" << profilePath;
+//  QAssistantClient *assist = new QAssistantClient( QString(), 0);
+//  assist->setArguments( cmdLst );
+//  assist->showPage(helpPath);
+//  connect(assist, SIGNAL(assistantClosed()), qApp, SLOT(quit()) );
+}
+
+void ApplicationWindow::showHelp()
+{
+  QFile helpFile(helpFilePath);
+  if (!helpFile.exists())
+  {
+    QMessageBox::critical(this,tr("MantidPlot - Help Files Not Found!"),//Mantid
+        tr("Please indicate the location of the help file!")+"<br>"+
+        tr("The manual can be downloaded from the following internet address:")+
+        "<p><a href = http://soft.proindependent.com/manuals.html>http://soft.proindependent.com/manuals.html</a></p>");
+    QString fn = QFileDialog::getOpenFileName(QDir::currentDirPath(), "*.html", this );
+    if (!fn.isEmpty())
+    {
+      QFileInfo fi(fn);
+      helpFilePath=fi.absFilePath();
+      saveSettings();
+    }
+  }
+
+  QFileInfo fi(helpFilePath);
+  QString profilePath = QString(fi.dirPath(true)+"/qtiplot.adp");
+  if (!QFile(profilePath).exists())
+  {
+    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")+"<br>"+
+        tr("This file is provided with the MantidPlot manual which can be downloaded from the following internet address:")+
+        "<p><a href = http://soft.proindependent.com/manuals.html>http://soft.proindependent.com/manuals.html</a></p>");
+    return;
+  }
+
+  QStringList cmdLst = QStringList() << "-profile" << profilePath;
+//  assistant->setArguments( cmdLst );
+//  assistant->showPage(helpFilePath);
+}
+
+void ApplicationWindow::showPlotWizard()
+{
+  QStringList lst = tableNames();
+  if (lst.count() > 0){
+    PlotWizard* pw = new PlotWizard(this, 0);
+    pw->setAttribute(Qt::WA_DeleteOnClose);
+    connect (pw,SIGNAL(plot(const QStringList&)),this,SLOT(multilayerPlot(const QStringList&)));
+
+    pw->insertTablesList(lst);
+    pw->setColumnsList(columnsList(Table::All));
+    pw->changeColumnsList(lst[0]);
+    pw->exec();
+  } else
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no tables available in this project.</h4>"
+            "<p><h4>Please create a table and try again!</h4>"));
+}
+
+void ApplicationWindow::setCurveFullRange()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g)
+    return;
+
+  int curveKey = actionCurveFullRange->data().toInt();
+  g->setCurveFullRange(g->curveIndex(curveKey));
+}
+
+void ApplicationWindow::showCurveRangeDialog()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g)
+    return;
+
+  int curveKey = actionEditCurveRange->data().toInt();
+  showCurveRangeDialog(g, g->curveIndex(curveKey));
+}
+
+CurveRangeDialog* ApplicationWindow::showCurveRangeDialog(Graph *g, int curve)
+{
+  if (!g)
+    return 0;
+
+  CurveRangeDialog* crd = new CurveRangeDialog(this);
+  crd->setAttribute(Qt::WA_DeleteOnClose);
+  crd->setCurveToModify(g, curve);
+  crd->exec();
+  return crd;
+}
+
+FunctionDialog* ApplicationWindow::showFunctionDialog()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return 0;
+
+  Graph* g = plot->activeGraph();
+  if (!g)
+    return 0;
+
+  int curveKey = actionEditFunction->data().toInt();
+  return showFunctionDialog(g, g->curveIndex(curveKey));
+}
+
+FunctionDialog* ApplicationWindow::showFunctionDialog(Graph *g, int curve)
+{
+  if ( !g )
+    return 0;
+
+  FunctionDialog* fd = functionDialog();
+  fd->setWindowTitle(tr("MantidPlot - Edit function"));//Mantid
+  fd->setCurveToModify(g, curve);
+  return fd;
+}
+
+FunctionDialog* ApplicationWindow::functionDialog()
+{
+  FunctionDialog* fd = new FunctionDialog(this);
+  fd->setAttribute(Qt::WA_DeleteOnClose);
+  connect (fd,SIGNAL(clearParamFunctionsList()),this,SLOT(clearParamFunctionsList()));
+  connect (fd,SIGNAL(clearPolarFunctionsList()),this,SLOT(clearPolarFunctionsList()));
+
+  fd->insertParamFunctionsList(xFunctions, yFunctions);
+  fd->insertPolarFunctionsList(rFunctions, thetaFunctions);
+  fd->show();
+  fd->setActiveWindow();
+  return fd;
+}
+
+void ApplicationWindow::addFunctionCurve()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  if (plot->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    return;
+  }
+
+  Graph* g = plot->activeGraph();
+  if ( g ) {
+    FunctionDialog* fd = functionDialog();
+    if (fd)
+      fd->setGraph(g);
+  }
+}
+
+void ApplicationWindow::updateFunctionLists(int type, QStringList &formulas)
+{
+  int maxListSize = 10;
+  if (type == 2)
+  {
+    rFunctions.remove(formulas[0]);
+    rFunctions.push_front(formulas[0]);
+
+    thetaFunctions.remove(formulas[1]);
+    thetaFunctions.push_front(formulas[1]);
+
+    while ((int)rFunctions.size() > maxListSize)
+      rFunctions.pop_back();
+    while ((int)thetaFunctions.size() > maxListSize)
+      thetaFunctions.pop_back();
+  }
+  else if (type == 1)
+  {
+    xFunctions.remove(formulas[0]);
+    xFunctions.push_front(formulas[0]);
+
+    yFunctions.remove(formulas[1]);
+    yFunctions.push_front(formulas[1]);
+
+    while ((int)xFunctions.size() > maxListSize)
+      xFunctions.pop_back();
+    while ((int)yFunctions.size() > maxListSize)
+      yFunctions.pop_back();
+  }
+}
+
+MultiLayer * ApplicationWindow::newFunctionPlot(QStringList &formulas, double start, double end, int points, const QString& var, int type)
+{
+  MultiLayer *ml = newGraph();
+  if (ml)
+    ml->activeGraph()->addFunction(formulas, start, end, points, var, type);
+
+  updateFunctionLists(type, formulas);
+  return ml;
+}
+
+void ApplicationWindow::clearLogInfo()
+{
+  //if (!current_folder->logInfo().isEmpty()){
+  current_folder->clearLogInfo();
+  results->setText("");
+  emit modified();
+  //}
+}
+
+void ApplicationWindow::clearParamFunctionsList()
+{
+  xFunctions.clear();
+  yFunctions.clear();
+}
+
+void ApplicationWindow::clearPolarFunctionsList()
+{
+  rFunctions.clear();
+  thetaFunctions.clear();
+}
+
+void ApplicationWindow::clearSurfaceFunctionsList()
+{
+  surfaceFunc.clear();
+}
+
+void ApplicationWindow::setFramed3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setFramed();
+  actionShowAxisDialog->setEnabled(TRUE);
+}
+
+void ApplicationWindow::setBoxed3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setBoxed();
+  actionShowAxisDialog->setEnabled(TRUE);
+}
+
+void ApplicationWindow::removeAxes3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setNoAxes();
+  actionShowAxisDialog->setEnabled(false);
+}
+
+void ApplicationWindow::removeGrid3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setPolygonStyle();
+}
+
+void ApplicationWindow::setHiddenLineGrid3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setHiddenLineStyle();
+}
+
+void ApplicationWindow::setPoints3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setDotStyle();
+}
+
+void ApplicationWindow::setCones3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setConeStyle();
+}
+
+void ApplicationWindow::setCrosses3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setCrossStyle();
+}
+
+void ApplicationWindow::setBars3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setBarStyle();
+}
+
+void ApplicationWindow::setLineGrid3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setWireframeStyle();
+}
+
+void ApplicationWindow::setFilledMesh3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setFilledMeshStyle();
+}
+
+void ApplicationWindow::setFloorData3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setFloorData();
+}
+
+void ApplicationWindow::setFloorIso3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setFloorIsolines();
+}
+
+void ApplicationWindow::setEmptyFloor3DPlot()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setEmptyFloor();
+}
+
+void ApplicationWindow::setFrontGrid3DPlot(bool on)
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setFrontGrid(on);
+}
+
+void ApplicationWindow::setBackGrid3DPlot(bool on)
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setBackGrid(on);
+}
+
+void ApplicationWindow::setFloorGrid3DPlot(bool on)
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setFloorGrid(on);
+}
+
+void ApplicationWindow::setCeilGrid3DPlot(bool on)
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setCeilGrid(on);
+}
+
+void ApplicationWindow::setRightGrid3DPlot(bool on)
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setRightGrid(on);
+}
+
+void ApplicationWindow::setLeftGrid3DPlot(bool on)
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setLeftGrid(on);
+}
+
+void ApplicationWindow::pickPlotStyle( QAction* action )
+{
+  if (!action )
+    return;
+
+  if (action == polygon)
+    removeGrid3DPlot();
+  else if (action == filledmesh)
+    setFilledMesh3DPlot();
+  else if (action == wireframe)
+    setLineGrid3DPlot();
+  else if (action == hiddenline)
+    setHiddenLineGrid3DPlot();
+  else if (action == pointstyle)
+    setPoints3DPlot();
+  else if (action == conestyle)
+    setCones3DPlot();
+  else if (action == crossHairStyle)
+    setCrosses3DPlot();
+  else if (action == barstyle)
+    setBars3DPlot();
+
+  emit modified();
+}
+
+
+void ApplicationWindow::pickCoordSystem( QAction* action)
+{
+  if (!action)
+    return;
+
+  if (action == Box || action == Frame)
+  {
+    if (action == Box)
+      setBoxed3DPlot();
+    if (action == Frame)
+      setFramed3DPlot();
+    grids->setEnabled(true);
+  }
+  else if (action == None)
+  {
+    removeAxes3DPlot();
+    grids->setEnabled(false);
+  }
+
+  emit modified();
+}
+
+void ApplicationWindow::pickFloorStyle( QAction* action )
+{
+  if (!action)
+    return;
+
+  if (action == floordata)
+    setFloorData3DPlot();
+  else if (action == flooriso)
+    setFloorIso3DPlot();
+  else
+    setEmptyFloor3DPlot();
+
+  emit modified();
+}
+
+void ApplicationWindow::custom3DActions(QMdiSubWindow *w)
+{
+  if (w && w->isA("Graph3D"))
+  {
+    Graph3D* plot = (Graph3D*)w;
+    actionAnimate->setOn(plot->isAnimated());
+    actionPerspective->setOn(!plot->isOrthogonal());
+    switch(plot->plotStyle())
+    {
+    case FILLEDMESH:
+      wireframe->setChecked( false );
+      hiddenline->setChecked( false );
+      polygon->setChecked( false );
+      filledmesh->setChecked( true );
+      pointstyle->setChecked( false );
+      barstyle->setChecked( false );
+      conestyle->setChecked( false );
+      crossHairStyle->setChecked( false );
+      break;
+
+    case FILLED:
+      wireframe->setChecked( false );
+      hiddenline->setChecked( false );
+      polygon->setChecked( true );
+      filledmesh->setChecked( false );
+      pointstyle->setChecked( false );
+      barstyle->setChecked( false );
+      conestyle->setChecked( false );
+      crossHairStyle->setChecked( false );
+      break;
+
+    case Qwt3D::USER:
+      wireframe->setChecked( false );
+      hiddenline->setChecked( false );
+      polygon->setChecked( false );
+      filledmesh->setChecked( false );
+
+      if (plot->pointType() == Graph3D::VerticalBars)
+      {
+        pointstyle->setChecked( false );
+        conestyle->setChecked( false );
+        crossHairStyle->setChecked( false );
+        barstyle->setChecked( true );
+      }
+      else if (plot->pointType() == Graph3D::Dots)
+      {
+        pointstyle->setChecked( true );
+        barstyle->setChecked( false );
+        conestyle->setChecked( false );
+        crossHairStyle->setChecked( false );
+      }
+      else if (plot->pointType() == Graph3D::HairCross)
+      {
+        pointstyle->setChecked( false );
+        barstyle->setChecked( false );
+        conestyle->setChecked( false );
+        crossHairStyle->setChecked( true );
+      }
+      else if (plot->pointType() == Graph3D::Cones)
+      {
+        pointstyle->setChecked( false );
+        barstyle->setChecked( false );
+        conestyle->setChecked( true );
+        crossHairStyle->setChecked( false );
+      }
+      break;
+
+    case WIREFRAME:
+      wireframe->setChecked( true );
+      hiddenline->setChecked( false );
+      polygon->setChecked( false );
+      filledmesh->setChecked( false );
+      pointstyle->setChecked( false );
+      barstyle->setChecked( false );
+      conestyle->setChecked( false );
+      crossHairStyle->setChecked( false );
+      break;
+
+    case HIDDENLINE:
+      wireframe->setChecked( false );
+      hiddenline->setChecked( true );
+      polygon->setChecked( false );
+      filledmesh->setChecked( false );
+      pointstyle->setChecked( false );
+      barstyle->setChecked( false );
+      conestyle->setChecked( false );
+      crossHairStyle->setChecked( false );
+      break;
+
+    default:
+      break;
+    }
+
+    switch(plot->coordStyle())
+    {
+    case Qwt3D::NOCOORD:
+      None->setChecked( true );
+      Box->setChecked( false );
+      Frame->setChecked( false );
+      break;
+
+    case Qwt3D::BOX:
+      None->setChecked( false );
+      Box->setChecked( true );
+      Frame->setChecked( false );
+      break;
+
+    case Qwt3D::FRAME:
+      None->setChecked(false );
+      Box->setChecked( false );
+      Frame->setChecked(true );
+      break;
+    }
+
+    switch(plot->floorStyle())
+    {
+    case NOFLOOR:
+      floornone->setChecked( true );
+      flooriso->setChecked( false );
+      floordata->setChecked( false );
+      break;
+
+    case FLOORISO:
+      floornone->setChecked( false );
+      flooriso->setChecked( true );
+      floordata->setChecked( false );
+      break;
+
+    case FLOORDATA:
+      floornone->setChecked(false );
+      flooriso->setChecked( false );
+      floordata->setChecked(true );
+      break;
+    }
+    custom3DGrids(plot->grids());
+  }
+}
+
+void ApplicationWindow::custom3DGrids(int grids)
+{
+  if (Qwt3D::BACK & grids)
+    back->setChecked(true);
+  else
+    back->setChecked(false);
+
+  if (Qwt3D::FRONT & grids)
+    front->setChecked(true);
+  else
+    front->setChecked(false);
+
+  if (Qwt3D::CEIL & grids)
+    ceil->setChecked(true);
+  else
+    ceil->setChecked(false);
+
+  if (Qwt3D::FLOOR & grids)
+    floor->setChecked(true);
+  else
+    floor->setChecked(false);
+
+  if (Qwt3D::RIGHT & grids)
+    right->setChecked(true);
+  else
+    right->setChecked(false);
+
+  if (Qwt3D::LEFT & grids)
+    left->setChecked(true);
+  else
+    left->setChecked(false);
+}
+
+void ApplicationWindow::initPlot3DToolBar()
+{
+  plot3DTools = new QToolBar( tr( "3D Surface" ), this );
+  plot3DTools->setObjectName("plot3DTools"); // this is needed for QMainWindow::restoreState()
+  plot3DTools->setIconSize( QSize(20,20) );
+  addToolBarBreak( Qt::TopToolBarArea );
+  addToolBar( Qt::TopToolBarArea, plot3DTools );
+
+  coord = new QActionGroup( this );
+  Box = new QAction( coord );
+  Box->setIcon(QIcon(getQPixmap("box_xpm")));
+  Box->setCheckable(true);
+
+  Frame = new QAction( coord );
+  Frame->setIcon(QIcon(getQPixmap("free_axes_xpm")) );
+  Frame->setCheckable(true);
+
+  None = new QAction( coord );
+  None->setIcon(QIcon(getQPixmap("no_axes_xpm")) );
+  None->setCheckable(true);
+
+  plot3DTools->addAction(Frame);
+  plot3DTools->addAction(Box);
+  plot3DTools->addAction(None);
+  Box->setChecked( true );
+
+  plot3DTools->addSeparator();
+
+  // grid actions
+  grids = new QActionGroup( this );
+  grids->setEnabled( true );
+  grids->setExclusive( false );
+  front = new QAction( grids );
+  front->setCheckable( true );
+  front->setIcon(QIcon(getQPixmap("frontGrid_xpm")) );
+  back = new QAction( grids );
+  back->setCheckable( true );
+  back->setIcon(QIcon(getQPixmap("backGrid_xpm")));
+  right = new QAction( grids );
+  right->setCheckable( true );
+  right->setIcon(QIcon(getQPixmap("leftGrid_xpm")) );
+  left = new QAction( grids );
+  left->setCheckable( true );
+  left->setIcon(QIcon(getQPixmap("rightGrid_xpm")));
+  ceil = new QAction( grids );
+  ceil->setCheckable( true );
+  ceil->setIcon(QIcon(getQPixmap("ceilGrid_xpm")) );
+  floor = new QAction( grids );
+  floor->setCheckable( true );
+  floor->setIcon(QIcon(getQPixmap("floorGrid_xpm")) );
+
+  plot3DTools->addAction(front);
+  plot3DTools->addAction(back);
+  plot3DTools->addAction(right);
+  plot3DTools->addAction(left);
+  plot3DTools->addAction(ceil);
+  plot3DTools->addAction(floor);
+
+  plot3DTools->addSeparator();
+
+  actionPerspective = new QAction( this );
+  actionPerspective->setToggleAction( TRUE );
+  actionPerspective->setIconSet(getQPixmap("perspective_xpm") );
+  actionPerspective->addTo( plot3DTools );
+  actionPerspective->setOn(!orthogonal3DPlots);
+  connect(actionPerspective, SIGNAL(toggled(bool)), this, SLOT(togglePerspective(bool)));
+
+  actionResetRotation = new QAction( this );
+  actionResetRotation->setToggleAction( false );
+  actionResetRotation->setIconSet(getQPixmap("reset_rotation_xpm"));
+  actionResetRotation->addTo( plot3DTools );
+  connect(actionResetRotation, SIGNAL(activated()), this, SLOT(resetRotation()));
+
+  actionFitFrame = new QAction( this );
+  actionFitFrame->setToggleAction( false );
+  actionFitFrame->setIconSet(getQPixmap("fit_frame_xpm"));
+  actionFitFrame->addTo( plot3DTools );
+  connect(actionFitFrame, SIGNAL(activated()), this, SLOT(fitFrameToLayer()));
+
+  plot3DTools->addSeparator();
+
+  //plot style actions
+  plotstyle = new QActionGroup( this );
+  wireframe = new QAction( plotstyle );
+  wireframe->setCheckable( true );
+  wireframe->setEnabled( true );
+  wireframe->setIcon(QIcon(getQPixmap("lineMesh_xpm")) );
+  hiddenline = new QAction( plotstyle );
+  hiddenline->setCheckable( true );
+  hiddenline->setEnabled( true );
+  hiddenline->setIcon(QIcon(getQPixmap("grid_only_xpm")) );
+  polygon = new QAction( plotstyle );
+  polygon->setCheckable( true );
+  polygon->setEnabled( true );
+  polygon->setIcon(QIcon(getQPixmap("no_grid_xpm")));
+  filledmesh = new QAction( plotstyle );
+  filledmesh->setCheckable( true );
+  filledmesh->setIcon(QIcon(getQPixmap("grid_poly_xpm")) );
+  pointstyle = new QAction( plotstyle );
+  pointstyle->setCheckable( true );
+  pointstyle->setIcon(QIcon(getQPixmap("pointsMesh_xpm")) );
+
+  conestyle = new QAction( plotstyle );
+  conestyle->setCheckable( true );
+  conestyle->setIcon(QIcon(getQPixmap("cones_xpm")) );
+
+  crossHairStyle = new QAction( plotstyle );
+  crossHairStyle->setCheckable( true );
+  crossHairStyle->setIcon(QIcon(getQPixmap("crosses_xpm")) );
+
+  barstyle = new QAction( plotstyle );
+  barstyle->setCheckable( true );
+  barstyle->setIcon(QIcon(getQPixmap("plot_bars_xpm")) );
+
+  plot3DTools->addAction(barstyle);
+  plot3DTools->addAction(pointstyle);
+
+  plot3DTools->addAction(conestyle);
+  plot3DTools->addAction(crossHairStyle);
+  plot3DTools->addSeparator();
+
+  plot3DTools->addAction(wireframe);
+  plot3DTools->addAction(hiddenline);
+  plot3DTools->addAction(polygon);
+  plot3DTools->addAction(filledmesh);
+  filledmesh->setChecked( true );
+
+  plot3DTools->addSeparator();
+
+  //floor actions
+  floorstyle = new QActionGroup( this );
+  floordata = new QAction( floorstyle );
+  floordata->setCheckable( true );
+  floordata->setIcon(QIcon(getQPixmap("floor_xpm")) );
+  flooriso = new QAction( floorstyle );
+  flooriso->setCheckable( true );
+  flooriso->setIcon(QIcon(getQPixmap("isolines_xpm")) );
+  floornone = new QAction( floorstyle );
+  floornone->setCheckable( true );
+  floornone->setIcon(QIcon(getQPixmap("no_floor_xpm")));
+
+  plot3DTools->addAction(floordata);
+  plot3DTools->addAction(flooriso);
+  plot3DTools->addAction(floornone);
+  floornone->setChecked( true );
+
+  plot3DTools->addSeparator();
+
+  actionAnimate = new QAction( this );
+  actionAnimate->setToggleAction( true );
+  actionAnimate->setIconSet(getQPixmap("movie_xpm"));
+  plot3DTools->addAction(actionAnimate);
+
+  plot3DTools->hide();
+
+  connect(actionAnimate, SIGNAL(toggled(bool)), this, SLOT(toggle3DAnimation(bool)));
+  connect( coord, SIGNAL( triggered( QAction* ) ), this, SLOT( pickCoordSystem( QAction* ) ) );
+  connect( floorstyle, SIGNAL( triggered( QAction* ) ), this, SLOT( pickFloorStyle( QAction* ) ) );
+  connect( plotstyle, SIGNAL( triggered( QAction* ) ), this, SLOT( pickPlotStyle( QAction* ) ) );
+
+  connect( left, SIGNAL( triggered( bool ) ), this, SLOT( setLeftGrid3DPlot(bool) ));
+  connect( right, SIGNAL( triggered( bool ) ), this, SLOT( setRightGrid3DPlot( bool ) ) );
+  connect( ceil, SIGNAL( triggered( bool ) ), this, SLOT( setCeilGrid3DPlot( bool ) ) );
+  connect( floor, SIGNAL( triggered( bool ) ), this, SLOT(setFloorGrid3DPlot( bool ) ) );
+  connect( back, SIGNAL( triggered( bool ) ), this, SLOT(setBackGrid3DPlot( bool ) ) );
+  connect( front, SIGNAL( triggered( bool ) ), this, SLOT( setFrontGrid3DPlot( bool ) ) );
+}
+
+void ApplicationWindow::pixelLineProfile()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g)
+    return;
+
+  bool ok;
+  int res = QInputDialog::getInteger(
+      tr("MantidPlot - Set the number of pixels to average"), tr("Number of averaged pixels"),1, 1, 2000, 2,//Mantid
+      &ok, this );
+  if ( !ok )
+    return;
+
+  LineProfileTool *lpt = new LineProfileTool(g, this, res);
+  g->setActiveTool(lpt);
+}
+
+void ApplicationWindow::intensityTable()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (g){
+    ImageMarker *im = (ImageMarker *) g->selectedMarkerPtr();
+    if (im){
+      QString fn = im->fileName();
+      if (!fn.isEmpty())
+        importImage(fn);
+    }
+  }
+}
+
+void ApplicationWindow::autoArrangeLayers()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  plot->setMargins(5, 5, 5, 5);
+  plot->setSpacing(5, 5);
+  plot->arrangeLayers(true, false);
+}
+
+void ApplicationWindow::addLayer()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  switch(QMessageBox::information(this,
+      tr("MantidPlot - Guess best origin for the new layer?"),//Mantid
+      tr("Do you want MantidPlot to guess the best position for the new layer?\n Warning: this will rearrange existing layers!"),//Mantid
+      tr("&Guess"), tr("&Top-left corner"), tr("&Cancel"), 0, 2 ) )
+  {
+  case 0:
+  {
+    setPreferences(plot->addLayer());
+    plot->arrangeLayers(true, false);
+  }
+  break;
+
+  case 1:
+    setPreferences(plot->addLayer(0, 0, plot->size().width(), plot->size().height()));
+    break;
+
+  case 2:
+    return;
+    break;
+  }
+}
+
+void ApplicationWindow::deleteLayer()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  plot->confirmRemoveLayer();
+}
+
+Note* ApplicationWindow::openNote(ApplicationWindow* app, const QStringList &flist)
+{
+  QStringList lst = flist[0].split("\t", QString::SkipEmptyParts);
+  QString caption = lst[0];
+  Note* w = app->newNote(caption);
+  if (lst.count() == 2){
+    app->setListViewDate(caption, lst[1]);
+    w->setBirthDate(lst[1]);
+  }
+  restoreWindowGeometry(app, w, flist[1]);
+
+  lst=flist[2].split("\t");
+  w->setWindowLabel(lst[1]);
+  w->setCaptionPolicy((MdiSubWindow::CaptionPolicy)lst[2].toInt());
+  return w;
+}
+
+Matrix* ApplicationWindow::openMatrix(ApplicationWindow* app, const QStringList &flist)
+{
+  QStringList::const_iterator line = flist.begin();
+
+  QStringList list=(*line).split("\t");
+  QString caption=list[0];
+  int rows = list[1].toInt();
+  int cols = list[2].toInt();
+
+  Matrix* w = app->newMatrix(caption, rows, cols);
+  app->setListViewDate(caption,list[3]);
+  w->setBirthDate(list[3]);
+
+  for (line++; line!=flist.end(); line++)
+  {
+    QStringList fields = (*line).split("\t");
+    if (fields[0] == "geometry") {
+      restoreWindowGeometry(app, w, *line);
+    } else if (fields[0] == "ColWidth") {
+      w->setColumnsWidth(fields[1].toInt());
+    } else if (fields[0] == "Formula") {
+      w->setFormula(fields[1]);
+    } else if (fields[0] == "<formula>") {
+      QString formula;
+      for (line++; line!=flist.end() && *line != "</formula>"; line++)
+        formula += *line + "\n";
+      formula.truncate(formula.length()-1);
+      w->setFormula(formula);
+    } else if (fields[0] == "TextFormat") {
+      if (fields[1] == "f")
+        w->setTextFormat('f', fields[2].toInt());
+      else
+        w->setTextFormat('e', fields[2].toInt());
+    } else if (fields[0] == "WindowLabel") { // d_file_version > 71
+      w->setWindowLabel(fields[1]);
+      w->setCaptionPolicy((MdiSubWindow::CaptionPolicy)fields[2].toInt());
+    } else if (fields[0] == "Coordinates") { // d_file_version > 81
+      w->setCoordinates(fields[1].toDouble(), fields[2].toDouble(), fields[3].toDouble(), fields[4].toDouble());
+    } else if (fields[0] == "ViewType") { // d_file_version > 90
+      w->setViewType((Matrix::ViewType)fields[1].toInt());
+    } else if (fields[0] == "HeaderViewType") { // d_file_version > 90
+      w->setHeaderViewType((Matrix::HeaderViewType)fields[1].toInt());
+    } else if (fields[0] == "ColorPolicy"){// d_file_version > 90
+      w->setColorMapType((Matrix::ColorMapType)fields[1].toInt());
+    } else if (fields[0] == "<ColorMap>"){// d_file_version > 90
+      QStringList lst;
+      while ( *line != "</ColorMap>" ){
+        line++;
+        lst << *line;
+      }
+      lst.pop_back();
+      w->setColorMap(lst);
+    } else // <data> or values
+      break;
+  }
+  if (*line == "<data>") line++;
+
+  //read and set table values
+  for (; line!=flist.end() && *line != "</data>"; line++){
+    QStringList fields = (*line).split("\t");
+    int row = fields[0].toInt();
+    for (int col=0; col<cols; col++){
+      QString cell = fields[col+1];
+      if (cell.isEmpty())
+        continue;
+
+      if (d_file_version < 90)
+        w->setCell(row, col, QLocale::c().toDouble(cell));
+      else if (d_file_version == 90)
+        w->setText(row, col, cell);
+      else
+        w->setCell(row, col, cell.toDouble());
+    }
+    qApp->processEvents(QEventLoop::ExcludeUserInput);
+  }
+  w->resetView();
+  return w;
+}
+void ApplicationWindow::openMantidMatrix(const QStringList &list)
+{ 	
+  QString s=list[0];
+  QStringList qlist=s.split("\t");
+  QString wsName=qlist[1];
+  MantidMatrix *m=newMantidMatrix(wsName,-1,-1);//mantidUI->importMatrixWorkspace(wsName,-1,-1,false,false);
+  //if(!m)throw std::runtime_error("Error on opening matrixworkspace ");
+  if(!m) return;
+  //adding the mantid matrix windows opened to a list.
+  //this list is used for find the MantidMatrix window pointer to open a 3D/2DGraph
+  m_mantidmatrixWindows<<m;
+  QStringList::const_iterator line = list.begin();
+  for (line++; line!=list.end(); line++)
+  {	QStringList fields = (*line).split("\t");
+  if (fields[0] == "geometry" || fields[0] == "tgeometry") {
+    restoreWindowGeometry(this, m, *line);
+  }
+  }
+}
+void ApplicationWindow::openInstrumentWindow(const QStringList &list)
+{
+  QString s=list[0];
+  QStringList qlist=s.split("\t");
+  QString wsName=qlist[1];
+  InstrumentWindow *insWin = mantidUI->getInstrumentView(wsName);
+  if(!insWin) return;
+  insWin->show();
+  QStringList::const_iterator line = list.begin();
+  for (line++; line!=list.end(); line++)
+  {	QStringList fields = (*line).split("\t");
+  if (fields[0] == "geometry" || fields[0] == "tgeometry") {
+    restoreWindowGeometry(this, insWin, *line);
+  }
+  }
+}
+/** This method opens script window when  project file is loaded
+ */
+void ApplicationWindow::openScriptWindow(const QStringList &list)
+{	showScriptWindow();
+if(!scriptingWindow) return;
+scriptingWindow->setWindowTitle("MantidPlot: " + scriptingEnv()->scriptingLanguage() + " Window");
+QString s=list[0];
+QStringList scriptnames=s.split("\t");
+int count=scriptnames.size();
+if(count==0) return;
+// don't create a new tab when the first script file from theproject file  opened
+if(!scriptnames[1].isEmpty()) scriptingWindow->open(scriptnames[1],false);
+// create a new tab  and open the script for all otehr filenames
+for(int i=2;i<count;++i)
+{   if(!scriptnames[i].isEmpty())scriptingWindow->open(scriptnames[i],true);
+}
+}
+/** This method populates the mantid workspace tree when  project file is loaded 
+ */
+void ApplicationWindow::populateMantidTreeWdiget(const QString &s)
+{	
+  QStringList list = s.split("\t");
+  QStringList::const_iterator line = list.begin();
+  for (++line; line!=list.end(); ++line)
+  {	std::string wsName=(*line).toStdString();
+  if(wsName.empty())throw std::runtime_error("Workspace Name not found in project file ");
+  std::string fileName(workingDir.toStdString()+"/"+wsName);
+  fileName.append(".nxs");
+  try
+  {
+    mantidUI->loaddataFromNexusFile(wsName,fileName,true);
+  }
+  catch(...)
+  {
+  }
+  }
+}
+/** This method opens mantid matrix window when  project file is loaded 
+ */
+MantidMatrix* ApplicationWindow::newMantidMatrix(const QString& wsName,int lower,int upper)
+{	
+  MantidMatrix* m=mantidUI->openMatrixWorkspace(this,wsName,lower,upper);
+  return m;
+}
+Table* ApplicationWindow::openTable(ApplicationWindow* app, const QStringList &flist)
+{
+  QStringList::const_iterator line = flist.begin();
+
+  QStringList list=(*line).split("\t");
+  QString caption=list[0];
+  int rows = list[1].toInt();
+  int cols = list[2].toInt();
+
+  Table* w = app->newTable(caption, rows, cols);
+  app->setListViewDate(caption, list[3]);
+  w->setBirthDate(list[3]);
+
+  for (line++; line!=flist.end(); line++)
+  {
+    QStringList fields = (*line).split("\t");
+    if (fields[0] == "geometry" || fields[0] == "tgeometry") {
+      restoreWindowGeometry(app, w, *line);
+    } else if (fields[0] == "header") {
+      fields.pop_front();
+      if (d_file_version >= 78)
+        w->loadHeader(fields);
+      else
+      {
+        w->setColPlotDesignation(list[4].toInt(), Table::X);
+        w->setColPlotDesignation(list[6].toInt(), Table::Y);
+        w->setHeader(fields);
+      }
+    } else if (fields[0] == "ColWidth") {
+      fields.pop_front();
+      w->setColWidths(fields);
+    } else if (fields[0] == "com") { // legacy code
+      w->setCommands(*line);
+    } else if (fields[0] == "<com>") {
+      for (line++; line!=flist.end() && *line != "</com>"; line++)
+      {
+        int col = (*line).mid(9,(*line).length()-11).toInt();
+        QString formula;
+        for (line++; line!=flist.end() && *line != "</col>"; line++)
+          formula += *line + "\n";
+        formula.truncate(formula.length()-1);
+        w->setCommand(col,formula);
+      }
+    } else if (fields[0] == "ColType") { // d_file_version > 65
+      fields.pop_front();
+      w->setColumnTypes(fields);
+    } else if (fields[0] == "Comments") { // d_file_version > 71
+      fields.pop_front();
+      w->setColComments(fields);
+      w->setHeaderColType();
+    } else if (fields[0] == "WindowLabel") { // d_file_version > 71
+      w->setWindowLabel(fields[1]);
+      w->setCaptionPolicy((MdiSubWindow::CaptionPolicy)fields[2].toInt());
+    } else if (fields[0] == "ReadOnlyColumn") { // d_file_version > 91
+      fields.pop_front();
+      for (int i=0; i < w->numCols(); i++)
+        w->setReadOnlyColumn(i, fields[i] == "1");
+    } else if (fields[0] == "HiddenColumn") { // d_file_version >= 93
+      fields.pop_front();
+      for (int i=0; i < w->numCols(); i++)
+        w->hideColumn(i, fields[i] == "1");
+    } else // <data> or values
+      break;
+  }
+
+  QApplication::setOverrideCursor(Qt::WaitCursor);
+  w->table()->blockSignals(true);
+  for (line++; line!=flist.end() && *line != "</data>"; line++)
+  {//read and set table values
+    QStringList fields = (*line).split("\t");
+    int row = fields[0].toInt();
+    for (int col=0; col<cols; col++){
+      if (fields.count() >= col+2){
+        QString cell = fields[col+1];
+        if (cell.isEmpty())
+          continue;
+
+        if (w->columnType(col) == Table::Numeric){
+          if (d_file_version < 90)
+            w->setCell(row, col, QLocale::c().toDouble(cell.replace(",", ".")));
+          else if (d_file_version == 90)
+            w->setText(row, col, cell);
+          else if (d_file_version >= 91)
+            w->setCell(row, col, cell.toDouble());
+        } else
+          w->setText(row, col, cell);
+      }
+    }
+    QApplication::processEvents(QEventLoop::ExcludeUserInput);
+  }
+  QApplication::restoreOverrideCursor();
+
+  w->setSpecifications(w->saveToString("geometry\n"));
+  w->table()->blockSignals(false);
+  return w;
+}
+
+TableStatistics* ApplicationWindow::openTableStatistics(const QStringList &flist)
+{
+  QStringList::const_iterator line = flist.begin();
+
+  QStringList list=(*line++).split("\t");
+  QString caption=list[0];
+
+  QList<int> targets;
+  for (int i=1; i <= (*line).count('\t'); i++)
+    targets << (*line).section('\t',i,i).toInt();
+
+  TableStatistics* w = newTableStatistics(table(list[1]),
+      list[2]=="row" ? TableStatistics::row : TableStatistics::column, targets, caption);
+
+  setListViewDate(caption,list[3]);
+  w->setBirthDate(list[3]);
+
+  for (line++; line!=flist.end(); line++)
+  {
+    QStringList fields = (*line).split("\t");
+    if (fields[0] == "geometry"){
+      restoreWindowGeometry(this, w, *line);}
+    else if (fields[0] == "header") {
+      fields.pop_front();
+      if (d_file_version >= 78)
+        w->loadHeader(fields);
+      else
+      {
+        w->setColPlotDesignation(list[4].toInt(), Table::X);
+        w->setColPlotDesignation(list[6].toInt(), Table::Y);
+        w->setHeader(fields);
+      }
+    } else if (fields[0] == "ColWidth") {
+      fields.pop_front();
+      w->setColWidths(fields);
+    } else if (fields[0] == "com") { // legacy code
+      w->setCommands(*line);
+    } else if (fields[0] == "<com>") {
+      for (line++; line!=flist.end() && *line != "</com>"; line++)
+      {
+        int col = (*line).mid(9,(*line).length()-11).toInt();
+        QString formula;
+        for (line++; line!=flist.end() && *line != "</col>"; line++)
+          formula += *line + "\n";
+        formula.truncate(formula.length()-1);
+        w->setCommand(col,formula);
+      }
+    } else if (fields[0] == "ColType") { // d_file_version > 65
+      fields.pop_front();
+      w->setColumnTypes(fields);
+    } else if (fields[0] == "Comments") { // d_file_version > 71
+      fields.pop_front();
+      w->setColComments(fields);
+    } else if (fields[0] == "WindowLabel") { // d_file_version > 71
+      w->setWindowLabel(fields[1]);
+      w->setCaptionPolicy((MdiSubWindow::CaptionPolicy)fields[2].toInt());
+    }
+  }
+  return w;
+}
+
+Graph* ApplicationWindow::openGraph(ApplicationWindow* app, MultiLayer *plot,
+    const QStringList &list)
+{
+  Graph* ag = 0;
+  int curveID = 0;
+  QString wsName;
+  for (int j=0;j<(int)list.count()-1;j++){
+    QString s=list[j];
+    if (s.contains ("ggeometry")){
+      QStringList fList=s.split("\t");
+      ag =(Graph*)plot->addLayer(fList[1].toInt(), fList[2].toInt(),
+          fList[3].toInt(), fList[4].toInt());
+
+      ag->blockSignals(true);
+      ag->enableAutoscaling(autoscale2DPlots);
+
+    }
+    else if( s.contains("MantidCurve")) //1D plot curves
+    {
+      QStringList curvelst=s.split("\t");
+      if( !curvelst[1].isEmpty()&& !curvelst[2].isEmpty())
+      {
+        try {
+          new MantidCurve(curvelst[1],ag,curvelst[2],curvelst[3].toInt(),curvelst[4].toInt());
+        } catch (Mantid::Kernel::Exception::NotFoundError &) {
+          // Get here if workspace name is invalid - shouldn't be possible, but just in case
+          closeWindow(plot);
+          return 0;
+
+        } catch (std::invalid_argument&) {
+          // Get here if invalid spectrum number given - shouldn't be possible, but just in case
+          // plot->askOnCloseEvent(false);
+          //plot->close();
+          closeWindow(plot);
+          return 0;
+        }
+      }
+    }
+    else if (s.left(10) == "Background"){
+      QStringList fList = s.split("\t");
+      QColor c = QColor(fList[1]);
+      if (fList.count() == 3)
+        c.setAlpha(fList[2].toInt());
+      ag->setBackgroundColor(c);
+    }
+    else if (s.contains ("Margin")){
+      QStringList fList=s.split("\t");
+      ag->plotWidget()->setMargin(fList[1].toInt());
+    }
+    else if (s.contains ("Border")){
+      QStringList fList=s.split("\t");
+      ag->setFrame(fList[1].toInt(), QColor(fList[2]));
+    }
+    else if (s.contains ("EnabledAxes")){
+      QStringList fList=s.split("\t");
+      fList.pop_front();
+      for (int i=0; i<(int)fList.count(); i++)
+        ag->enableAxis(i, fList[i].toInt());
+    }
+    else if (s.contains ("AxesBaseline")){
+      QStringList fList = s.split("\t", QString::SkipEmptyParts);
+      fList.pop_front();
+      for (int i=0; i<(int)fList.count(); i++)
+        ag->setAxisMargin(i, fList[i].toInt());
+    }
+    else if (s.contains ("EnabledTicks"))
+    {//version < 0.8.6
+      QStringList fList=s.split("\t");
+      fList.pop_front();
+      fList.replaceInStrings("-1", "3");
+      ag->setMajorTicksType(fList);
+      ag->setMinorTicksType(fList);
+    }
+    else if (s.contains ("MajorTicks"))
+    {//version >= 0.8.6
+      QStringList fList=s.split("\t");
+      fList.pop_front();
+      ag->setMajorTicksType(fList);
+    }
+    else if (s.contains ("MinorTicks"))
+    {//version >= 0.8.6
+      QStringList fList=s.split("\t");
+      fList.pop_front();
+      ag->setMinorTicksType(fList);
+    }
+    else if (s.contains ("TicksLength")){
+      QStringList fList=s.split("\t");
+      ag->setTicksLength(fList[1].toInt(), fList[2].toInt());
+    }
+    else if (s.contains ("EnabledTickLabels")){
+      QStringList fList=s.split("\t");
+      fList.pop_front();
+      for (int i=0; i<int(fList.count()); i++)
+        ag->enableAxisLabels(i, fList[i].toInt());
+    }
+    else if (s.contains ("AxesColors")){
+      QStringList fList = s.split("\t");
+      fList.pop_front();
+      for (int i=0; i<int(fList.count()); i++)
+        ag->setAxisColor(i, QColor(fList[i]));
+    }
+    else if (s.contains ("AxesNumberColors")){
+      QStringList fList=QStringList::split ("\t",s,TRUE);
+      fList.pop_front();
+      for (int i=0; i<int(fList.count()); i++)
+        ag->setAxisLabelsColor(i, QColor(fList[i]));
+    }
+    else if (s.left(5)=="grid\t"){
+      ag->plotWidget()->grid()->load(s.split("\t"));
+    }
+    else if (s.startsWith ("<Antialiasing>") && s.endsWith ("</Antialiasing>")){
+      bool antialiasing = s.remove("<Antialiasing>").remove("</Antialiasing>").toInt();
+      ag->setAntialiasing(antialiasing);
+    }
+    else if (s.contains ("PieCurve")){
+      QStringList curve=s.split("\t");
+      if (!app->renamedTables.isEmpty()){
+        QString caption = (curve[1]).left((curve[1]).find("_",0));
+        if (app->renamedTables.contains(caption))
+        {//modify the name of the curve according to the new table name
+          int index = app->renamedTables.findIndex(caption);
+          QString newCaption = app->renamedTables[++index];
+          curve.replaceInStrings(caption+"_", newCaption+"_");
+        }
+      }
+      QPen pen = QPen(QColor(curve[3]), curve[2].toDouble(),Graph::getPenStyle(curve[4]));
+
+      Table *table = app->table(curve[1]);
+      if (table){
+        int startRow = 0;
+        int endRow = table->numRows() - 1;
+        int first_color = curve[7].toInt();
+        bool visible = true;
+        if (d_file_version >= 90)
+        {
+          startRow = curve[8].toInt();
+          endRow = curve[9].toInt();
+          visible = curve[10].toInt();
+        }
+
+        if (d_file_version <= 89)
+          first_color = convertOldToNewColorIndex(first_color);
+
+        if (curve.size() >= 22){//version 0.9.3-rc3
+          ag->plotPie(table, curve[1], pen, curve[5].toInt(),
+              curve[6].toInt(), first_color, startRow, endRow, visible,
+              curve[11].toDouble(), curve[12].toDouble(), curve[13].toDouble(),
+              curve[14].toDouble(), curve[15].toDouble(), curve[16].toInt(),
+              curve[17].toInt(), curve[18].toInt(), curve[19].toInt(),
+              curve[20].toInt(), curve[21].toInt());
+        } else
+          ag->plotPie(table, curve[1], pen, curve[5].toInt(),
+              curve[6].toInt(), first_color, startRow, endRow, visible);
+      }
+    }else if (s.left(6)=="curve\t"){
+      QStringList curve = s.split("\t", QString::SkipEmptyParts);
+      if (!app->renamedTables.isEmpty()){
+        QString caption = (curve[2]).left((curve[2]).find("_",0));
+        if (app->renamedTables.contains(caption))
+        {//modify the name of the curve according to the new table name
+          int index = app->renamedTables.findIndex (caption);
+          QString newCaption = app->renamedTables[++index];
+          curve.replaceInStrings(caption+"_", newCaption+"_");
+        }
+      }
+
+      CurveLayout cl;
+      cl.connectType=curve[4].toInt();
+      cl.lCol=curve[5].toInt();
+      if (d_file_version <= 89)
+        cl.lCol = convertOldToNewColorIndex(cl.lCol);
+      cl.lStyle=curve[6].toInt();
+      cl.lWidth=curve[7].toDouble();
+      cl.sSize=curve[8].toInt();
+      if (d_file_version <= 78)
+        cl.sType=Graph::obsoleteSymbolStyle(curve[9].toInt());
+      else
+        cl.sType=curve[9].toInt();
+
+      cl.symCol=curve[10].toInt();
+      if (d_file_version <= 89)
+        cl.symCol = convertOldToNewColorIndex(cl.symCol);
+      cl.fillCol=curve[11].toInt();
+      if (d_file_version <= 89)
+        cl.fillCol = convertOldToNewColorIndex(cl.fillCol);
+      cl.filledArea=curve[12].toInt();
+      cl.aCol=curve[13].toInt();
+      if (d_file_version <= 89)
+        cl.aCol = convertOldToNewColorIndex(cl.aCol);
+      cl.aStyle=curve[14].toInt();
+      if(curve.count() < 16)
+        cl.penWidth = cl.lWidth;
+      else if ((d_file_version >= 79) && (curve[3].toInt() == Graph::Box))
+        cl.penWidth = curve[15].toDouble();
+      else if ((d_file_version >= 78) && (curve[3].toInt() <= Graph::LineSymbols))
+        cl.penWidth = curve[15].toDouble();
+      else
+        cl.penWidth = cl.lWidth;
+
+      int plotType = curve[3].toInt();
+      Table *w = app->table(curve[2]);
+      PlotCurve *c = NULL;
+      if (w){
+        if(plotType == Graph::VectXYXY || plotType == Graph::VectXYAM){
+          QStringList colsList;
+          colsList<<curve[2]; colsList<<curve[20]; colsList<<curve[21];
+          if (d_file_version < 72)
+            colsList.prepend(w->colName(curve[1].toInt()));
+          else
+            colsList.prepend(curve[1]);
+
+          int startRow = 0;
+          int endRow = -1;
+          if (d_file_version >= 90){
+            startRow = curve[curve.count()-3].toInt();
+            endRow = curve[curve.count()-2].toInt();
+          }
+
+          c = (PlotCurve *)ag->plotVectorCurve(w, colsList, plotType, startRow, endRow);
+
+          if (d_file_version <= 77){
+            int temp_index = convertOldToNewColorIndex(curve[15].toInt());
+            ag->updateVectorsLayout(curveID, ColorBox::color(temp_index), curve[16].toDouble(), curve[17].toInt(),
+                curve[18].toInt(), curve[19].toInt(), 0, curve[20], curve[21]);
+          } else {
+            if(plotType == Graph::VectXYXY)
+              ag->updateVectorsLayout(curveID, curve[15], curve[16].toDouble(),
+                  curve[17].toInt(), curve[18].toInt(), curve[19].toInt(), 0);
+            else
+              ag->updateVectorsLayout(curveID, curve[15], curve[16].toDouble(), curve[17].toInt(),
+                  curve[18].toInt(), curve[19].toInt(), curve[22].toInt());
+          }
+        } else if (plotType == Graph::Box)
+          c = (PlotCurve *)ag->openBoxDiagram(w, curve, d_file_version);
+        else {
+          if (d_file_version < 72)
+            c = (PlotCurve *)ag->insertCurve(w, curve[1].toInt(), curve[2], plotType);
+          else if (d_file_version < 90)
+            c = (PlotCurve *)ag->insertCurve(w, curve[1], curve[2], plotType);
+          else{
+            int startRow = curve[curve.count()-3].toInt();
+            int endRow = curve[curve.count()-2].toInt();
+            c = (PlotCurve *)ag->insertCurve(w, curve[1], curve[2], plotType, startRow, endRow);
+          }
+        }
+
+        if(plotType == Graph::Histogram){
+          QwtHistogram *h = (QwtHistogram *)ag->curve(curveID);
+          if (d_file_version <= 76)
+            h->setBinning(curve[16].toInt(),curve[17].toDouble(),curve[18].toDouble(),curve[19].toDouble());
+          else
+            h->setBinning(curve[17].toInt(),curve[18].toDouble(),curve[19].toDouble(),curve[20].toDouble());
+          h->loadData();
+        }
+
+        if(plotType == Graph::VerticalBars || plotType == Graph::HorizontalBars ||
+            plotType == Graph::Histogram){
+          if (d_file_version <= 76)
+            ag->setBarsGap(curveID, curve[15].toInt(), 0);
+          else
+            ag->setBarsGap(curveID, curve[15].toInt(), curve[16].toInt());
+        }
+        ag->updateCurveLayout(c, &cl);
+        if (d_file_version >= 88){
+          if (c && c->rtti() == QwtPlotItem::Rtti_PlotCurve){
+            if (d_file_version < 90)
+              c->setAxis(curve[curve.count()-2].toInt(), curve[curve.count()-1].toInt());
+            else {
+              c->setAxis(curve[curve.count()-5].toInt(), curve[curve.count()-4].toInt());
+              c->setVisible(curve.last().toInt());
+            }
+          }
+        }
+      } else if(plotType == Graph::Histogram){//histograms from matrices
+        Matrix *m = app->matrix(curve[2]);
+        QwtHistogram *h = ag->restoreHistogram(m, curve);
+        ag->updateCurveLayout(h, &cl);
+      }
+      curveID++;
+    } else if (s == "<CurveLabels>"){
+      QStringList lst;
+      while ( s!="</CurveLabels>" ){
+        s = list[++j];
+        lst << s;
+      }
+      lst.pop_back();
+      ag->restoreCurveLabels(curveID - 1, lst);
+    } else if (s == "<Function>"){//version 0.9.5
+      curveID++;
+      QStringList lst;
+      while ( s != "</Function>" ){
+        s = list[++j];
+        lst << s;
+      }
+      lst.pop_back();
+      ag->restoreFunction(lst);
+    } else if (s.contains ("FunctionCurve")){
+      QStringList curve = s.split("\t");
+      CurveLayout cl;
+      cl.connectType=curve[6].toInt();
+      cl.lCol=curve[7].toInt();
+      cl.lStyle=curve[8].toInt();
+      cl.lWidth=curve[9].toDouble();
+      cl.sSize=curve[10].toInt();
+      cl.sType=curve[11].toInt();
+      cl.symCol=curve[12].toInt();
+      cl.fillCol=curve[13].toInt();
+      cl.filledArea=curve[14].toInt();
+      cl.aCol=curve[15].toInt();
+      cl.aStyle=curve[16].toInt();
+      int current_index = 17;
+      if(curve.count() < 16)
+        cl.penWidth = cl.lWidth;
+      else if ((d_file_version >= 79) && (curve[5].toInt() == Graph::Box))
+      {
+        cl.penWidth = curve[17].toDouble();
+        current_index++;
+      }
+      else if ((d_file_version >= 78) && (curve[5].toInt() <= Graph::LineSymbols))
+      {
+        cl.penWidth = curve[17].toDouble();
+        current_index++;
+      }
+      else
+        cl.penWidth = cl.lWidth;
+
+      PlotCurve *c = (PlotCurve *)ag->insertFunctionCurve(curve[1], curve[2].toInt(), d_file_version);
+      ag->setCurveType(curveID, curve[5].toInt());
+      ag->updateCurveLayout(c, &cl);
+      if (d_file_version >= 88){
+        QwtPlotCurve *c = ag->curve(curveID);
+        if (c){
+          if(current_index + 1 < curve.size())
+            c->setAxis(curve[current_index].toInt(), curve[current_index+1].toInt());
+          if (d_file_version >= 90 && current_index+2 < curve.size())
+            c->setVisible(curve.last().toInt());
+          else
+            c->setVisible(true);
+        }
+
+      }
+      curveID++;
+    }
+    else if (s.contains ("ErrorBars")){
+      QStringList curve = s.split("\t", QString::SkipEmptyParts);
+      if (!app->renamedTables.isEmpty()){
+        QString caption = (curve[4]).left((curve[4]).find("_",0));
+        if (app->renamedTables.contains(caption))
+        {//modify the name of the curve according to the new table name
+          int index = app->renamedTables.findIndex (caption);
+          QString newCaption = app->renamedTables[++index];
+          curve.replaceInStrings(caption+"_", newCaption+"_");
+        }
+      }
+      Table *w = app->table(curve[3]);
+      Table *errTable = app->table(curve[4]);
+      if (w && errTable){
+        ag->addErrorBars(curve[2], curve[3], errTable, curve[4], curve[1].toInt(),
+            curve[5].toDouble(), curve[6].toInt(), QColor(curve[7]),
+            curve[8].toInt(), curve[10].toInt(), curve[9].toInt());
+      }
+      curveID++;
+    }
+    else if (s == "<spectrogram>"){
+      QStringList lst;
+      lst<<list[0];
+      lst<<list[1];
+      QString lineone=lst[1];
+      QStringList lineonelst=lineone.split("\t");
+      QString name=lineonelst[1];
+      QStringList qlist=name.split(" ");
+      std::string specgramwsName =qlist[1].toStdString();
+
+      lst.clear();
+      while ( s!="</spectrogram>" ){
+        s = list[++j];
+        lst << s;
+      }
+      lst.pop_back();
+      Spectrogram* sp=openSpectrogram(ag,specgramwsName,lst);
+      if(!sp)
+      {	  closeWindow(plot);
+      return 0;
+      }
+      curveID++;
+    }
+    else if (s.left(6) == "scale\t"){
+      QStringList scl = s.split("\t");
+      scl.pop_front();
+      int size = scl.count();
+      if (d_file_version < 88){
+        double step = scl[2].toDouble();
+        if (scl[5] == "0")
+          step = 0.0;
+        ag->setScale(QwtPlot::xBottom, scl[0].toDouble(), scl[1].toDouble(), step,
+            scl[3].toInt(), scl[4].toInt(), scl[6].toInt(), bool(scl[7].toInt()));
+        ag->setScale(QwtPlot::xTop, scl[0].toDouble(), scl[1].toDouble(), step,
+            scl[3].toInt(), scl[4].toInt(), scl[6].toInt(), bool(scl[7].toInt()));
+
+        step = scl[10].toDouble();
+        if (scl[13] == "0")
+          step = 0.0;
+        ag->setScale(QwtPlot::yLeft, scl[8].toDouble(), scl[9].toDouble(), step, scl[11].toInt(),
+            scl[12].toInt(), scl[14].toInt(), bool(scl[15].toInt()));
+        ag->setScale(QwtPlot::yRight, scl[8].toDouble(), scl[9].toDouble(), step, scl[11].toInt(),
+            scl[12].toInt(), scl[14].toInt(), bool(scl[15].toInt()));
+      }
+      else if (size == 8){
+        ag->setScale(scl[0].toInt(), scl[1].toDouble(), scl[2].toDouble(), scl[3].toDouble(),
+            scl[4].toInt(), scl[5].toInt(),  scl[6].toInt(), bool(scl[7].toInt()));
+      }
+      else if (size == 9){
+
+        if(scl[8].toInt()==1)
+        {	//if axis details like scale,majortick,minor tick changed
+          ag->setScale(scl[0].toInt(), scl[1].toDouble(), scl[2].toDouble(), scl[3].toDouble(),
+              scl[4].toInt(), scl[5].toInt(),  scl[6].toInt(), bool(scl[7].toInt()));
+        }
+      }
+      else if (size == 18){
+        ag->setScale(scl[0].toInt(), scl[1].toDouble(), scl[2].toDouble(), scl[3].toDouble(),
+            scl[4].toInt(), scl[5].toInt(), scl[6].toInt(), bool(scl[7].toInt()), scl[8].toDouble(),
+            scl[9].toDouble(), scl[10].toInt(), scl[11].toDouble(), scl[12].toDouble(), scl[13].toInt(),
+            scl[14].toInt(), bool(scl[15].toInt()), scl[16].toInt(), bool(scl[17].toInt()));
+      }
+      else if (size == 19){
+        //if axis details scale,majortick,minor tick changed
+        if(scl[8].toInt()==1)
+          ag->setScale(scl[0].toInt(), scl[1].toDouble(), scl[2].toDouble(), scl[3].toDouble(),
+              scl[4].toInt(), scl[5].toInt(), scl[6].toInt(), bool(scl[7].toInt()), scl[8].toDouble(),
+              scl[9].toDouble(), scl[10].toInt(), scl[11].toDouble(), scl[12].toDouble(), scl[13].toInt(),
+              scl[14].toInt(), bool(scl[15].toInt()), scl[16].toInt(), bool(scl[17].toInt()));
+      }
+    }
+    else if (s.contains ("PlotTitle")){
+      QStringList fList=s.split("\t");
+      wsName=fList[1].split(" ")[1];
+      ag->setTitle(fList[1]);
+      ag->setTitleColor(QColor(fList[2]));
+      ag->setTitleAlignment(fList[3].toInt());
+    }
+    else if (s.contains ("TitleFont")){
+      QStringList fList=s.split("\t");
+      QFont fnt=QFont (fList[1],fList[2].toInt(),fList[3].toInt(),fList[4].toInt());
+      fnt.setUnderline(fList[5].toInt());
+      fnt.setStrikeOut(fList[6].toInt());
+      ag->setTitleFont(fnt);
+    }
+    else if (s.contains ("AxesTitles")){
+      QStringList lst=s.split("\t");
+      lst.pop_front();
+      for (int i=0; i<4; i++){
+        if (lst.count() > i)
+          ag->setScaleTitle(i, lst[i]);
+      }
+    }
+    else if (s.contains ("AxesTitleColors")){
+      QStringList colors = s.split("\t", QString::SkipEmptyParts);
+      colors.pop_front();
+      for (int i=0; i<int(colors.count()); i++)
+        ag->setAxisTitleColor(i, colors[i]);
+    }else if (s.contains ("AxesTitleAlignment")){
+      QStringList align=s.split("\t", QString::SkipEmptyParts);
+      align.pop_front();
+      for (int i=0; i<(int)align.count(); i++)
+        ag->setAxisTitleAlignment(i, align[i].toInt());
+    }else if (s.contains ("ScaleFont")){
+      QStringList fList=s.split("\t");
+      QFont fnt=QFont (fList[1],fList[2].toInt(),fList[3].toInt(),fList[4].toInt());
+      fnt.setUnderline(fList[5].toInt());
+      fnt.setStrikeOut(fList[6].toInt());
+
+      int axis=(fList[0].right(1)).toInt();
+      ag->setAxisTitleFont(axis,fnt);
+    }else if (s.contains ("AxisFont")){
+      QStringList fList=s.split("\t");
+      QFont fnt=QFont (fList[1],fList[2].toInt(),fList[3].toInt(),fList[4].toInt());
+      fnt.setUnderline(fList[5].toInt());
+      fnt.setStrikeOut(fList[6].toInt());
+
+      int axis=(fList[0].right(1)).toInt();
+      ag->setAxisFont(axis,fnt);
+    }
+    else if (s.contains ("AxesFormulas"))
+    {	QStringList fList=s.split("\t");
+    fList.remove(fList.first());
+    for (int i=0; i<(int)fList.count(); i++)
+      ag->setAxisFormula(i, fList[i]);
+    }
+    else if (s.startsWith("<AxisFormula "))
+    {
+      int axis = s.mid(18,s.length()-20).toInt();
+      QString formula;
+      for (j++; j<(int)list.count() && list[j] != "</AxisFormula>"; j++)
+        formula += list[j] + "\n";
+      formula.truncate(formula.length()-1);
+      ag->setAxisFormula(axis, formula);
+    }
+    else if (s.contains ("LabelsFormat"))
+    {
+      QStringList fList=s.split("\t");
+      fList.pop_front();
+      ag->setLabelsNumericFormat(fList);
+    }
+    else if (s.contains ("LabelsRotation"))
+    {
+      QStringList fList=s.split("\t");
+      ag->setAxisLabelRotation(QwtPlot::xBottom, fList[1].toInt());
+      ag->setAxisLabelRotation(QwtPlot::xTop, fList[2].toInt());
+    }
+    else if (s.contains ("DrawAxesBackbone"))
+    {
+      QStringList fList=s.split("\t");
+      ag->loadAxesOptions(fList[1]);
+    }
+    else if (s.contains ("AxesLineWidth"))
+    {
+      QStringList fList=s.split("\t");
+      ag->loadAxesLinewidth(fList[1].toInt());
+    }
+    else if (s.contains ("CanvasFrame")){
+      QStringList lst = s.split("\t");
+      ag->setCanvasFrame(lst[1].toInt(), QColor(lst[2]));
+    }
+    else if (s.contains ("CanvasBackground"))
+    {
+      QStringList list = s.split("\t");
+      QColor c = QColor(list[1]);
+      if (list.count() == 3)
+        c.setAlpha(list[2].toInt());
+      ag->setCanvasBackground(c);
+    }
+    else if (s.contains ("Legend"))
+    {// version <= 0.8.9
+      QStringList fList = QStringList::split ("\t",s, true);
+      ag->insertLegend(fList, d_file_version);
+    }
+    else if (s.startsWith ("<legend>") && s.endsWith ("</legend>"))
+    {
+      QStringList fList = QStringList::split ("\t", s.remove("</legend>"), true);
+      ag->insertLegend(fList, d_file_version);
+    }
+    else if (s.contains ("textMarker"))
+    {// version <= 0.8.9
+      QStringList fList = QStringList::split ("\t",s, true);
+      ag->insertText(fList, d_file_version);
+    }
+    else if (s.startsWith ("<text>") && s.endsWith ("</text>"))
+    {
+      QStringList fList = QStringList::split ("\t", s.remove("</text>"), true);
+      ag->insertText(fList, d_file_version);
+    }
+    else if (s.startsWith ("<PieLabel>") && s.endsWith ("</PieLabel>"))
+    {
+      QStringList fList = QStringList::split ("\t", s.remove("</PieLabel>"), true);
+      ag->insertText(fList, d_file_version);
+    }
+    else if (s.contains ("lineMarker"))
+    {// version <= 0.8.9
+      QStringList fList=s.split("\t");
+      ag->addArrow(fList, d_file_version);
+    }
+    else if (s.startsWith ("<line>") && s.endsWith ("</line>"))
+    {
+      QStringList fList=s.remove("</line>").split("\t");
+      ag->addArrow(fList, d_file_version);
+    }
+    else if (s.contains ("ImageMarker") || (s.startsWith ("<image>") && s.endsWith ("</image>")))
+    {
+      QStringList fList=s.remove("</image>").split("\t");
+      ag->insertImageMarker(fList, d_file_version);
+    }
+    else if (s.contains("AxisType"))
+    {
+      QStringList fList = s.split("\t");
+      for (int i=0; i<4; i++){
+        QStringList lst = fList[i+1].split(";", QString::SkipEmptyParts);
+        int format = lst[0].toInt();
+        if (format == ScaleDraw::Numeric)
+          continue;
+        if (format == ScaleDraw::Day)
+          ag->setLabelsDayFormat(i, lst[1].toInt());
+        else if (format == ScaleDraw::Month)
+          ag->setLabelsMonthFormat(i, lst[1].toInt());
+        else if (format == ScaleDraw::Time || format == ScaleDraw::Date)
+          ag->setLabelsDateTimeFormat(i, format, lst[1]+";"+lst[2]);
+        else if (lst.size() > 1)
+          ag->setLabelsTextFormat(i, format, lst[1], app->table(lst[1]));
+      }
+    }
+    else if (d_file_version < 69 && s.contains ("AxesTickLabelsCol"))
+    {
+      QStringList fList = s.split("\t");
+      for (int i=0; i<4; i++){
+        QString colName = fList[i+1];
+        Table *nw = app->table(colName);
+        ag->setLabelsTextFormat(i, ag->axisType(i), colName, nw);
+      }
+    }
+  }
+  ag->replot();
+
+  ag->blockSignals(false);
+  ag->setIgnoreResizeEvents(!app->autoResizeLayers);
+  ag->setAutoscaleFonts(app->autoScaleFonts);
+  return ag;
+}
+
+Graph3D* ApplicationWindow::openSurfacePlot(ApplicationWindow* app, const QStringList &lst)
+{
+  QStringList fList=lst[0].split("\t");
+  QString caption=fList[0];
+  QString date=fList[1];
+  if (date.isEmpty())
+    date = QDateTime::currentDateTime().toString(Qt::LocalDate);
+
+  fList=lst[2].split("\t", QString::SkipEmptyParts);
+  Graph3D *plot=0;
+
+  if (fList[1].endsWith("(Y)",true))
+    plot=app->dataPlot3D(caption, fList[1],fList[2].toDouble(),fList[3].toDouble(),
+        fList[4].toDouble(),fList[5].toDouble(),fList[6].toDouble(),fList[7].toDouble());
+  else if (fList[1].contains("(Z)",true) > 0)
+    plot=app->openPlotXYZ(caption, fList[1], fList[2].toDouble(),fList[3].toDouble(),
+        fList[4].toDouble(),fList[5].toDouble(),fList[6].toDouble(),fList[7].toDouble());
+  else if (fList[1].startsWith("matrix<",true) && fList[1].endsWith(">",false))
+    plot=app->openMatrixPlot3D(caption, fList[1], fList[2].toDouble(),fList[3].toDouble(),
+        fList[4].toDouble(),fList[5].toDouble(),fList[6].toDouble(),fList[7].toDouble());
+
+  else if (fList[1].contains("mantidMatrix3D"))
+  {
+    QString linefive=lst[5];
+    QStringList linefivelst=linefive.split("\t");
+    QString name=linefivelst[1];
+    QStringList qlist=name.split(" ");
+    std::string graph3DwsName=qlist[1].toStdString();
+    MantidMatrix *m=0;
+    QList<MantidMatrix*>::const_iterator matrixItr;;
+    for( matrixItr=m_mantidmatrixWindows.begin();matrixItr!=m_mantidmatrixWindows.end();++matrixItr)
+    {
+      if(graph3DwsName==(*matrixItr)->getWorkspaceName()) m=*matrixItr;
+    }
+    QString linethree=lst[3];
+    qlist.clear();
+    qlist=linethree.split("\t");
+    int style=qlist[1].toInt();
+    if(m)plot=m->plotGraph3D(style);
+    if(!plot)
+    {
+      closeWindow(plot);
+      return 0;
+    }
+  }
+  else if (fList[1].contains(",")){
+    QStringList l = fList[1].split(",", QString::SkipEmptyParts);
+    plot = app->plotParametricSurface(l[0], l[1], l[2], l[3].toDouble(), l[4].toDouble(),
+        l[5].toDouble(), l[6].toDouble(), l[7].toInt(), l[8].toInt(), l[9].toInt(), l[10].toInt());
+    app->setWindowName(plot, caption);
+  } else {
+    QStringList l = fList[1].split(";", QString::SkipEmptyParts);
+    if (l.count() == 1)
+      plot = app->plotSurface(fList[1], fList[2].toDouble(), fList[3].toDouble(),
+          fList[4].toDouble(), fList[5].toDouble(), fList[6].toDouble(), fList[7].toDouble());
+    else if (l.count() == 3)
+      plot = app->plotSurface(l[0], fList[2].toDouble(), fList[3].toDouble(), fList[4].toDouble(),
+          fList[5].toDouble(), fList[6].toDouble(), fList[7].toDouble(), l[1].toInt(), l[2].toInt());
+    app->setWindowName(plot, caption);
+  }
+
+  if (!plot)
+    return 0;
+
+  app->setListViewDate(caption, date);
+  plot->setBirthDate(date);
+  plot->setIgnoreFonts(true);
+  restoreWindowGeometry(app, plot, lst[1]);
+
+  fList=lst[4].split("\t", QString::SkipEmptyParts);
+  plot->setGrid(fList[1].toInt());
+
+  plot->setTitle(lst[5].split("\t"));
+  plot->setColors(lst[6].split("\t", QString::SkipEmptyParts));
+
+  fList=lst[7].split("\t", QString::SkipEmptyParts);
+  fList.pop_front();
+  plot->setAxesLabels(fList);
+
+  plot->setTicks(lst[8].split("\t", QString::SkipEmptyParts));
+  plot->setTickLengths(lst[9].split("\t", QString::SkipEmptyParts));
+  plot->setOptions(lst[10].split("\t", QString::SkipEmptyParts));
+  plot->setNumbersFont(lst[11].split("\t", QString::SkipEmptyParts));
+  plot->setXAxisLabelFont(lst[12].split("\t", QString::SkipEmptyParts));
+  plot->setYAxisLabelFont(lst[13].split("\t", QString::SkipEmptyParts));
+  plot->setZAxisLabelFont(lst[14].split("\t", QString::SkipEmptyParts));
+
+  fList=lst[15].split("\t", QString::SkipEmptyParts);
+  plot->setRotation(fList[1].toDouble(),fList[2].toDouble(),fList[3].toDouble());
+
+  fList=lst[16].split("\t", QString::SkipEmptyParts);
+  plot->setZoom(fList[1].toDouble());
+
+  fList=lst[17].split("\t", QString::SkipEmptyParts);
+  plot->setScale(fList[1].toDouble(),fList[2].toDouble(),fList[3].toDouble());
+
+  fList=lst[18].split("\t", QString::SkipEmptyParts);
+  plot->setShift(fList[1].toDouble(),fList[2].toDouble(),fList[3].toDouble());
+
+  fList=lst[19].split("\t", QString::SkipEmptyParts);
+  plot->setMeshLineWidth(fList[1].toDouble());
+
+  if (d_file_version > 71){
+    fList=lst[20].split("\t"); // using QString::SkipEmptyParts here causes a crash for empty window labels
+    plot->setWindowLabel(fList[1]);
+    plot->setCaptionPolicy((MdiSubWindow::CaptionPolicy)fList[2].toInt());
+  }
+
+  if (d_file_version >= 88){
+    fList=lst[21].split("\t", QString::SkipEmptyParts);
+    plot->setOrthogonal(fList[1].toInt());
+  }
+
+  plot->setStyle(lst[3].split("\t", QString::SkipEmptyParts));
+  plot->setIgnoreFonts(true);
+  plot->update();
+  return plot;
+}
+Spectrogram*  ApplicationWindow::openSpectrogram(Graph*ag,const std::string &specgramwsName,const QStringList &lst)
+{
+  ProjectData *prjData=new ProjectData;
+  if(!prjData)return 0;
+
+  foreach (QString str, lst) {
+    if(str.contains("<ColorMap>"))
+    {	int index=lst.indexOf(str);
+    //read the colormap file name from project file
+    QString colormapLine=lst[index+1];
+    QStringList list=colormapLine.split("\t");
+    QString colormapFile=list[2];
+    prjData->setColormapFile(colormapFile);
+    }
+    if(str.contains("<ColorPolicy>"))
+    { 	//read the colormap policy to set gray scale
+      int index=lst.indexOf(str);
+      QString colormapPolicy=lst[index];
+      int index1=colormapPolicy.indexOf(">");
+      int index2=colormapPolicy.lastIndexOf("<");
+      bool gray=colormapPolicy.mid(index1+1,index2-index1-1).toInt();
+      prjData->setGrayScale(gray);
+
+    }
+    if (str.contains("\t<ContourLines>"))
+    { //setting contour mode
+      int index=lst.indexOf(str);
+      QString contourlines=lst[index];
+      int index1=contourlines.indexOf(">");
+      int index2=contourlines.lastIndexOf("<");
+      int bcontour=contourlines.mid(index1+1,index2-index1-1).toInt();
+      if(bcontour)prjData->setContourMode(true);
+
+      //setting contour levels
+      QString contourlevels=lst[index+1];
+      index1=contourlevels.indexOf(">");
+      index2=contourlevels.lastIndexOf("<");
+      int levels=contourlevels.mid(index1+1,index2-index1-1).toInt();
+      prjData->setContourLevels(levels);
+
+      //setting contour default pen
+      QString pen=lst[index+2];
+      if(pen.contains("<DefaultPen>"))
+      {
+        QString colorstring=lst[index+3];
+        int index1=colorstring.indexOf(">");
+        int index2=colorstring.lastIndexOf("<");
+        QString pencolor=colorstring.mid(index1+1,index2-index1-1);
+
+        QString widthstring=lst[index+4];
+        index1=widthstring.indexOf(">");
+        index2=widthstring.lastIndexOf("<");
+        QString penwidth=widthstring.mid(index1+1,index2-index1-1);
+
+        QString stylestring=lst[index+4];
+        index1=stylestring.indexOf(">");
+        index2=stylestring.lastIndexOf("<");
+        QString penstyle=stylestring.mid(index1+1,index2-index1-1);
+        QColor qcolor(pencolor);
+        QPen pen = QPen(qcolor, penwidth.toDouble(),Graph::getPenStyle(penstyle.toInt()));
+        prjData->setDefaultContourPen(pen);
+        prjData->setColorMapPen(false);
+      }
+      else if (pen.contains("<CustomPen>"))
+      {	ContourLinesEditor* contourLinesEditor = new ContourLinesEditor(this->locale());
+      prjData->setCotntourLinesEditor(contourLinesEditor);
+      prjData->setCustomPen(true);
+      }
+      else prjData->setColorMapPen(true);
+    }
+    if(str.contains("<IntensityChanged>"))
+    {	 //read the intensity changed line from file and setting the spectrogram flag for intenisity
+
+      int index=lst.indexOf(str);
+      QString intensity=lst[index];
+      int index1=intensity.indexOf(">");
+      int index2=intensity.lastIndexOf("<");
+      bool bIntensity=intensity.mid(index1+1,index2-index1-1).toInt();
+      prjData->setIntensity(bIntensity);
+    }
+
+  }
+  MantidMatrix *m=0;
+  //getting the mantidmatrix object  for the saved spectrogram  inthe project file
+  QList<MantidMatrix*>::const_iterator matrixItr;;
+  for( matrixItr=m_mantidmatrixWindows.begin();matrixItr!=m_mantidmatrixWindows.end();++matrixItr)
+  {
+    if(specgramwsName==(*matrixItr)->getWorkspaceName())
+      m=*matrixItr;
+  }
+  if(!m) return 0 ;
+  Spectrogram* sp=m->plotSpectrogram(ag,this,Graph::ColorMap,true,prjData);
+  return sp;
+}
+
+void ApplicationWindow::copyActiveLayer()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph *g = plot->activeGraph();
+
+  lastCopiedLayer = g;
+  connect (g, SIGNAL(destroyed()), this, SLOT(closedLastCopiedLayer()));
+  g->copyImage();
+}
+
+void ApplicationWindow::showDataSetDialog(Analysis operation)
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph *g = plot->activeGraph();
+  if (!g)
+    return;
+
+  DataSetDialog *ad = new DataSetDialog(tr("Curve") + ": ", this);
+  ad->setGraph(g);
+  ad->setOperationType(operation);
+  ad->exec();
+}
+
+void ApplicationWindow::analyzeCurve(Graph *g, Analysis operation, const QString& curveTitle)
+{
+  if (!g)
+    return;
+
+  Fit *fitter = 0;
+  switch(operation){
+  case NoAnalysis:
+    break;
+  case Integrate:
+  {
+    Integration *i = new Integration(this, g, curveTitle);
+    i->run();
+    delete i;
+  }
+  break;
+  case Diff:
+  {
+    Differentiation *diff = new Differentiation(this, g, curveTitle);
+    diff->enableGraphicsDisplay(true);
+    diff->run();
+    delete diff;
+  }
+  break;
+  case FitLinear:
+    fitter = new LinearFit (this, g);
+    break;
+  case FitLorentz:
+    fitter = new LorentzFit(this, g);
+    break;
+  case FitGauss:
+    fitter = new GaussFit(this, g);
+    break;
+  case FitSigmoidal:
+  {
+    QwtPlotCurve* c = g->curve(curveTitle);
+    if (c){
+      ScaleEngine *se = (ScaleEngine *)g->plotWidget()->axisScaleEngine(c->xAxis());
+      if(se->type() == QwtScaleTransformation::Log10)
+        fitter = new LogisticFit (this, g);
+      else
+        fitter = new SigmoidalFit (this, g);
+    }
+  }
+  break;
+  }
+
+  if (!fitter)
+    return;
+
+  if (fitter->setDataFromCurve(curveTitle)){
+    if (operation != FitLinear){
+      fitter->guessInitialValues();
+      fitter->scaleErrors(fit_scale_errors);
+      fitter->generateFunction(generateUniformFitPoints, fitPoints);
+    } else if (d_2_linear_fit_points)
+      fitter->generateFunction(generateUniformFitPoints, 2);
+    fitter->setOutputPrecision(fit_output_precision);
+    fitter->fit();
+    if (pasteFitResultsToPlot)
+      fitter->showLegend();
+    delete fitter;
+  }
+}
+
+void ApplicationWindow::analysis(Analysis operation)
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g || !g->validCurvesDataSize())
+    return;
+
+  QString curve_title = g->selectedCurveTitle();
+  if (!curve_title.isNull()) {
+    analyzeCurve(g, operation, curve_title);
+    return;
+  }
+
+  QStringList lst = g->analysableCurvesList();
+  if (lst.count() == 1){
+    const QwtPlotCurve *c = g->curve(lst[0]);
+    if (c)
+      analyzeCurve(g, operation, lst[0]);
+  } else
+    showDataSetDialog(operation);
+}
+
+void ApplicationWindow::integrate()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return;
+
+  if (w->isA("MultiLayer"))
+    analysis(Integrate);
+  else if (w->isA("Matrix")){
+    QDateTime dt = QDateTime::currentDateTime ();
+    QString info = dt.toString(Qt::LocalDate);
+    info += "\n" + tr("Integration of %1 from zero is").arg(QString(w->objectName())) + ":\t";
+    info += QString::number(((Matrix *)w)->integrate()) + "\n";
+    info += "-------------------------------------------------------------\n";
+    current_folder->appendLogInfo(info);
+    showResults(true);
+  }
+}
+
+void ApplicationWindow::differentiate()
+{
+  analysis(Diff);
+}
+
+void ApplicationWindow::fitLinear()
+{
+  analysis(FitLinear);
+}
+
+void ApplicationWindow::fitSigmoidal()
+{
+  analysis(FitSigmoidal);
+}
+
+void ApplicationWindow::fitGauss()
+{
+  analysis(FitGauss);
+}
+
+void ApplicationWindow::fitLorentz()
+
+{
+  analysis(FitLorentz);
+}
+
+void ApplicationWindow::pickPointerCursor()
+{
+  btnPointer->setChecked(true);
+}
+
+void ApplicationWindow::disableTools()
+{
+  if (displayBar->isVisible())
+    displayBar->hide();
+
+  QList<MdiSubWindow *> windows = windowsList();
+  foreach(MdiSubWindow *w, windows){
+    if (w->isA("MultiLayer")){
+      QList<Graph *> layers = ((MultiLayer*)w)->layersList();
+      foreach(Graph *g, layers)
+      g->disableTools();
+    }
+  }
+}
+
+void ApplicationWindow::pickDataTool( QAction* action )
+{
+  if (!action)
+    return;
+
+  disableTools();
+
+  if (action == btnCursor)
+    showCursor();
+  else if (action == btnSelect)
+    showRangeSelectors();
+  else if (action == btnPicker)
+    showScreenReader();
+  else if (action == btnMovePoints)
+    movePoints();
+  else if (action == btnRemovePoints)
+    removePoints();
+  else if (action == actionDrawPoints)
+    drawPoints();
+  else if (action == btnZoomIn)
+    zoomIn();
+  else if (action == btnZoomOut)
+    zoomOut();
+  else if (action == btnArrow)
+    drawArrow();
+  else if (action == btnLine)
+    drawLine();
+  else if (action == btnMultiPeakPick)
+    selectMultiPeak();
+  else if (action == actionMagnify)
+    magnify();
+}
+
+void ApplicationWindow::connectSurfacePlot(Graph3D *plot)
+{
+  connect (plot, SIGNAL(showContextMenu()), this,SLOT(showWindowContextMenu()));
+  connect (plot, SIGNAL(showOptionsDialog()), this,SLOT(showPlot3dDialog()));
+  connect (plot, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(closeWindow(MdiSubWindow*)));
+  connect (plot, SIGNAL(hiddenWindow(MdiSubWindow*)), this, SLOT(hideWindow(MdiSubWindow*)));
+  connect (plot, SIGNAL(statusChanged(MdiSubWindow*)), this, SLOT(updateWindowStatus(MdiSubWindow*)));
+  connect (plot, SIGNAL(modified()), this, SIGNAL(modified()));
+
+  plot->askOnCloseEvent(confirmClosePlot3D);
+}
+
+void ApplicationWindow::connectMultilayerPlot(MultiLayer *g)
+{
+  connect (g,SIGNAL(showTextDialog()),this,SLOT(showTextDialog()));
+  connect (g,SIGNAL(showPlotDialog(int)),this,SLOT(showPlotDialog(int)));
+  connect (g,SIGNAL(showScaleDialog(int)), this, SLOT(showScalePageFromAxisDialog(int)));
+  connect (g,SIGNAL(showAxisDialog(int)), this, SLOT(showAxisPageFromAxisDialog(int)));
+  connect (g,SIGNAL(showCurveContextMenu(int)), this, SLOT(showCurveContextMenu(int)));
+  connect (g,SIGNAL(showContextMenu()),this,SLOT(showWindowContextMenu()));
+  connect (g,SIGNAL(showCurvesDialog()),this,SLOT(showCurvesDialog()));
+  connect (g,SIGNAL(drawLineEnded(bool)), btnPointer, SLOT(setOn(bool)));
+  connect (g,SIGNAL(drawTextOff()),this, SLOT(disableAddText()));
+  connect (g, SIGNAL(showAxisTitleDialog()), this, SLOT(showAxisTitleDialog()));
+
+  connect (g,SIGNAL(showMarkerPopupMenu()),this,SLOT(showMarkerPopupMenu()));
+  connect (g,SIGNAL(closedWindow(MdiSubWindow*)),this, SLOT(closeWindow(MdiSubWindow*)));
+  connect (g,SIGNAL(hiddenWindow(MdiSubWindow*)),this, SLOT(hideWindow(MdiSubWindow*)));
+  connect (g,SIGNAL(statusChanged(MdiSubWindow*)),this, SLOT(updateWindowStatus(MdiSubWindow*)));
+  connect (g,SIGNAL(cursorInfo(const QString&)),info,SLOT(setText(const QString&)));
+  connect (g,SIGNAL(showImageDialog()),this,SLOT(showImageDialog()));
+  connect (g,SIGNAL(createTable(const QString&,int,int,const QString&)),
+      this,SLOT(newTable(const QString&,int,int,const QString&)));
+  connect (g,SIGNAL(viewTitleDialog()),this,SLOT(showTitleDialog()));
+  connect (g,SIGNAL(modifiedWindow(MdiSubWindow*)),this,SLOT(modifiedProject(MdiSubWindow*)));
+  connect (g,SIGNAL(resizedWindow(MdiSubWindow*)), this, SLOT(repaintWindows()));
+  connect (g,SIGNAL(modifiedPlot()), this, SLOT(modifiedProject()));
+  connect (g,SIGNAL(showLineDialog()),this, SLOT(showLineDialog()));
+  connect (g,SIGNAL(pasteMarker()),this,SLOT(pasteSelection()));
+  connect (g,SIGNAL(showGraphContextMenu()),this,SLOT(showGraphContextMenu()));
+  connect (g,SIGNAL(setPointerCursor()),this, SLOT(pickPointerCursor()));
+  connect (g,SIGNAL(currentFontChanged(const QFont&)), this, SLOT(setFormatBarFont(const QFont&)));
+  connect (g,SIGNAL(enableTextEditor(Graph *)), this, SLOT(enableTextEditor(Graph *)));
+
+  g->askOnCloseEvent(confirmClosePlot2D);
+}
+
+void ApplicationWindow::connectTable(Table* w)
+{
+  connect (w->table(), SIGNAL(selectionChanged()), this, SLOT(customColumnActions()));
+  connect (w,SIGNAL(statusChanged(MdiSubWindow*)),this, SLOT(updateWindowStatus(MdiSubWindow*)));
+  connect (w,SIGNAL(hiddenWindow(MdiSubWindow*)),this, SLOT(hideWindow(MdiSubWindow*)));
+  connect (w,SIGNAL(closedWindow(MdiSubWindow*)),this, SLOT(closeWindow(MdiSubWindow*)));
+  connect (w,SIGNAL(removedCol(const QString&)),this,SLOT(removeCurves(const QString&)));
+  connect (w,SIGNAL(modifiedData(Table *, const QString&)),
+      this, SLOT(updateCurves(Table *, const QString&)));
+  connect (w,SIGNAL(resizedWindow(MdiSubWindow*)),this,SLOT(modifiedProject(MdiSubWindow*)));
+  connect (w,SIGNAL(modifiedWindow(MdiSubWindow*)),this,SLOT(modifiedProject(MdiSubWindow*)));
+  connect (w,SIGNAL(optionsDialog()),this,SLOT(showColumnOptionsDialog()));
+  connect (w,SIGNAL(colValuesDialog()),this,SLOT(showColumnValuesDialog()));
+  connect (w,SIGNAL(showContextMenu(bool)),this,SLOT(showTableContextMenu(bool)));
+  connect (w,SIGNAL(changedColHeader(const QString&,const QString&)),this,SLOT(updateColNames(const QString&,const QString&)));
+  connect (w,SIGNAL(createTable(const QString&,int,int,const QString&)),this,SLOT(newTable(const QString&,int,int,const QString&)));
+
+  w->askOnCloseEvent(confirmCloseTable);
+}
+
+void ApplicationWindow::setAppColors(const QColor& wc, const QColor& pc, const QColor& tpc, bool force)
+{
+  if (force || workspaceColor != wc){
+    workspaceColor = wc;
+    d_workspace->setBackground(wc);
+  }
+
+  if (!force && panelsColor == pc && panelsTextColor == tpc)
+    return;
+
+  panelsColor = pc;
+  panelsTextColor = tpc;
+
+  QPalette palette;
+  palette.setColor(QPalette::Base, QColor(panelsColor));
+  qApp->setPalette(palette);
+
+  palette.setColor(QPalette::Text, QColor(panelsTextColor));
+  palette.setColor(QPalette::WindowText, QColor(panelsTextColor));
+
+  lv->setPalette(palette);
+  results->setPalette(palette);
+  folders->setPalette(palette);
+}
+
+void ApplicationWindow::setPlot3DOptions()
+{
+  QList<MdiSubWindow *> windows = windowsList();
+  foreach(MdiSubWindow *w, windows){
+    if (w->isA("Graph3D")){
+      Graph3D *g = (Graph3D*)w;
+      g->setOrthogonal(orthogonal3DPlots);
+      g->setAutoscale(autoscale3DPlots);
+      g->setAntialiasing(smooth3DMesh);
+    }
+  }
+}
+
+void ApplicationWindow::createActions()
+{
+  actionCustomActionDialog = new QAction(tr("Manage Custom Menus..."), this);
+  connect(actionCustomActionDialog, SIGNAL(activated()), this, SLOT(showCustomActionDialog()));
+  
+  actionManageDirs = new QAction(QIcon(getQPixmap("managefolders_xpm")), tr("Manage User Directories"), this);
+  connect(actionManageDirs, SIGNAL(activated()), this, SLOT(showUserDirectoryDialog()));
+
+  actionNewProject = new QAction(QIcon(getQPixmap("new_xpm")), tr("New &Project"), this);
+  actionNewProject->setShortcut( tr("Ctrl+N") );
+  connect(actionNewProject, SIGNAL(activated()), this, SLOT(newProject()));
+
+  actionSaveProject=new QAction(QIcon(getQPixmap("filesave_xpm")), tr("Save &Project"), this);
+  actionSaveProject->setShortcut( tr("Ctrl+Shift+S") );
+  connect(actionSaveProject, SIGNAL(activated()), this, SLOT(saveProject()));
+
+  actionSaveFile=new QAction(QIcon(getQPixmap("filesave_nexus_xpm")), tr("Save Nexus &File"), this);
+  actionSaveFile->setShortcut( tr("Ctrl+S") );
+  connect(actionSaveFile, SIGNAL(activated()), this, SLOT(savetoNexusFile()));
+
+  actionNewFolder = new QAction(QIcon(getQPixmap("newFolder_xpm")), tr("New &Project"), this);
+  actionNewProject->setShortcut(Qt::Key_F7);
+  connect(actionNewFolder, SIGNAL(activated()), this, SLOT(addFolder()));
+
+  actionNewGraph = new QAction(QIcon(getQPixmap("new_graph_xpm")), tr("New &Graph"), this);
+  actionNewGraph->setShortcut( tr("Ctrl+G") );
+  connect(actionNewGraph, SIGNAL(activated()), this, SLOT(newGraph()));
+
+  actionNewNote = new QAction(QIcon(getQPixmap("new_note_xpm")), tr("New &Note"), this);
+  connect(actionNewNote, SIGNAL(activated()), this, SLOT(newNote()));
+
+  actionNewTable = new QAction(QIcon(getQPixmap("table_xpm")), tr("New &Table"), this);
+  actionNewTable->setShortcut( tr("Ctrl+T") );
+  connect(actionNewTable, SIGNAL(activated()), this, SLOT(newTable()));
+
+  actionNewMatrix = new QAction(QIcon(getQPixmap("new_matrix_xpm")), tr("New &Matrix"), this);
+  actionNewMatrix->setShortcut( tr("Ctrl+M") );
+  connect(actionNewMatrix, SIGNAL(activated()), this, SLOT(newMatrix()));
+
+  actionNewFunctionPlot = new QAction(QIcon(getQPixmap("newF_xpm")), tr("New &Function Plot"), this);
+  actionNewFunctionPlot->setShortcut( tr("Ctrl+F") );
+  connect(actionNewFunctionPlot, SIGNAL(activated()), this, SLOT(functionDialog()));
+
+  actionNewSurfacePlot = new QAction(QIcon(getQPixmap("newFxy_xpm")), tr("New 3D &Surface Plot"), this);
+  actionNewSurfacePlot->setShortcut( tr("Ctrl+ALT+Z") );
+  connect(actionNewSurfacePlot, SIGNAL(activated()), this, SLOT(newSurfacePlot()));
+
+  actionOpenProj=new QAction(QIcon(getQPixmap("folder_open_xpm")), tr("&Project"), this);
+  actionOpenProj->setShortcut( tr("Ctrl+Shift+O") );
+  connect(actionOpenProj, SIGNAL(activated()), this, SLOT(open()));
+
+  actionLoadFile=new QAction(QIcon(getQPixmap("fileopen_raw_xpm")), tr("Data File"), this);
+  actionLoadFile->setShortcut( tr("Ctrl+Shift+F") );
+  connect(actionLoadFile, SIGNAL(activated()), this, SLOT(loadDataFile()));
+
+  actionLoadImage = new QAction(tr("Open Image &File"), this);
+  actionLoadImage->setShortcut( tr("Ctrl+I") );
+  connect(actionLoadImage, SIGNAL(activated()), this, SLOT(loadImage()));
+
+  actionImportImage = new QAction(tr("Import I&mage..."), this);
+  connect(actionImportImage, SIGNAL(activated()), this, SLOT(importImage()));
+
+  actionSaveProjectAs = new QAction(tr("Save Project &As..."), this);
+  connect(actionSaveProjectAs, SIGNAL(activated()), this, SLOT(saveProjectAs()));
+
+  actionOpenTemplate = new QAction(QIcon(getQPixmap("open_template_xpm")),tr("Open Temp&late..."), this);
+  connect(actionOpenTemplate, SIGNAL(activated()), this, SLOT(openTemplate()));
+
+  actionSaveTemplate = new QAction(QIcon(getQPixmap("save_template_xpm")), tr("Save As &Template..."), this);
+  connect(actionSaveTemplate, SIGNAL(activated()), this, SLOT(saveAsTemplate()));
+
+  actionSaveNote = new QAction(tr("Save Note As..."), this);
+  connect(actionSaveNote, SIGNAL(activated()), this, SLOT(saveNoteAs()));
+
+  actionLoad = new QAction(QIcon(getQPixmap("import_xpm")), tr("&Import ASCII..."), this);
+  connect(actionLoad, SIGNAL(activated()), this, SLOT(importASCII()));
+
+  actionUndo = new QAction(QIcon(getQPixmap("undo_xpm")), tr("&Undo"), this);
+  actionUndo->setShortcut( tr("Ctrl+Z") );
+  connect(actionUndo, SIGNAL(activated()), this, SLOT(undo()));
+
+  actionRedo = new QAction(QIcon(getQPixmap("redo_xpm")), tr("&Redo"), this);
+  actionRedo->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_Z));
+  connect(actionRedo, SIGNAL(activated()), this, SLOT(redo()));
+
+  actionCopyWindow = new QAction(QIcon(getQPixmap("duplicate_xpm")), tr("&Duplicate"), this);
+  connect(actionCopyWindow, SIGNAL(activated()), this, SLOT(clone()));
+
+  actionCutSelection = new QAction(QIcon(getQPixmap("cut_xpm")), tr("Cu&t Selection"), this);
+  actionCutSelection->setShortcut( tr("Ctrl+X") );
+  connect(actionCutSelection, SIGNAL(activated()), this, SLOT(cutSelection()));
+
+  actionCopySelection = new QAction(QIcon(getQPixmap("copy_xpm")), tr("&Copy Selection"), this);
+  actionCopySelection->setShortcut( tr("Ctrl+C") );
+  connect(actionCopySelection, SIGNAL(activated()), this, SLOT(copySelection()));
+
+  actionPasteSelection = new QAction(QIcon(getQPixmap("paste_xpm")), tr("&Paste Selection"), this);
+  actionPasteSelection->setShortcut( tr("Ctrl+V") );
+  connect(actionPasteSelection, SIGNAL(activated()), this, SLOT(pasteSelection()));
+
+  actionClearSelection = new QAction(QIcon(getQPixmap("erase_xpm")), tr("&Delete Selection"), this);
+  actionClearSelection->setShortcut( tr("Del","delete key") );
+  connect(actionClearSelection, SIGNAL(activated()), this, SLOT(clearSelection()));
+
+  actionShowExplorer = explorerWindow->toggleViewAction();
+  actionShowExplorer->setIcon(getQPixmap("folder_xpm"));
+  actionShowExplorer->setShortcut( tr("Ctrl+E") );
+
+  actionShowLog = logWindow->toggleViewAction();
+  actionShowLog->setIcon(getQPixmap("log_xpm"));
+
+  actionShowUndoStack = undoStackWindow->toggleViewAction();
+
+    //#ifdef SCRIPTING_CONSOLE
+  actionShowConsole = consoleWindow->toggleViewAction();
+    //#endif
+
+  actionAddLayer = new QAction(QIcon(getQPixmap("newLayer_xpm")), tr("Add La&yer"), this);
+  actionAddLayer->setShortcut( tr("Alt+L") );
+  connect(actionAddLayer, SIGNAL(activated()), this, SLOT(addLayer()));
+
+  actionShowLayerDialog = new QAction(QIcon(getQPixmap("arrangeLayers_xpm")), tr("Arran&ge Layers"), this);
+  actionShowLayerDialog->setShortcut( tr("Alt+A") );
+  connect(actionShowLayerDialog, SIGNAL(activated()), this, SLOT(showLayerDialog()));
+
+  actionAutomaticLayout = new QAction(QIcon(getQPixmap("auto_layout_xpm")), tr("Automatic Layout"), this);
+  connect(actionAutomaticLayout, SIGNAL(activated()), this, SLOT(autoArrangeLayers()));
+
+  actionExportGraph = new QAction(tr("&Current"), this);
+  actionExportGraph->setShortcut( tr("Alt+G") );
+  connect(actionExportGraph, SIGNAL(activated()), this, SLOT(exportGraph()));
+
+  actionExportAllGraphs = new QAction(tr("&All"), this);
+  actionExportAllGraphs->setShortcut( tr("Alt+X") );
+  connect(actionExportAllGraphs, SIGNAL(activated()), this, SLOT(exportAllGraphs()));
+
+  actionExportPDF = new QAction(QIcon(getQPixmap("pdf_xpm")), tr("&Export PDF"), this);
+  actionExportPDF->setShortcut( tr("Ctrl+Alt+P") );
+  connect(actionExportPDF, SIGNAL(activated()), this, SLOT(exportPDF()));
+
+  actionPrint = new QAction(QIcon(getQPixmap("fileprint_xpm")), tr("&Print"), this);
+  actionPrint->setShortcut( tr("Ctrl+P") );
+  connect(actionPrint, SIGNAL(activated()), this, SLOT(print()));
+
+  actionPrintAllPlots = new QAction(tr("Print All Plo&ts"), this);
+  connect(actionPrintAllPlots, SIGNAL(activated()), this, SLOT(printAllPlots()));
+
+  actionShowExportASCIIDialog = new QAction(tr("E&xport ASCII"), this);
+  connect(actionShowExportASCIIDialog, SIGNAL(activated()), this, SLOT(showExportASCIIDialog()));
+
+  actionCloseAllWindows = new QAction(QIcon(getQPixmap("quit_xpm")), tr("&Quit"), this);
+  actionCloseAllWindows->setShortcut( tr("Ctrl+Q") );
+  connect(actionCloseAllWindows, SIGNAL(activated()), qApp, SLOT(closeAllWindows()));
+
+  actionClearLogInfo = new QAction(tr("Clear &Log Information"), this);
+  connect(actionClearLogInfo, SIGNAL(activated()), this, SLOT(clearLogInfo()));
+
+  actionClearConsole = new QAction(tr("Clear &Console"), this);
+  connect(actionClearConsole, SIGNAL(activated()), console, SLOT(clear()));
+
+  actionDeleteFitTables = new QAction(QIcon(getQPixmap("close_xpm")), tr("Delete &Fit Tables"), this);
+  connect(actionDeleteFitTables, SIGNAL(activated()), this, SLOT(deleteFitTables()));
+
+  actionShowPlotWizard = new QAction(QIcon(getQPixmap("wizard_xpm")), tr("Plot &Wizard"), this);
+  actionShowPlotWizard->setShortcut( tr("Ctrl+Alt+W") );
+  connect(actionShowPlotWizard, SIGNAL(activated()), this, SLOT(showPlotWizard()));
+
+  actionShowConfigureDialog = new QAction(tr("&Preferences..."), this);
+  connect(actionShowConfigureDialog, SIGNAL(activated()), this, SLOT(showPreferencesDialog()));
+
+  actionShowCurvesDialog = new QAction(QIcon(getQPixmap("curves_xpm")), tr("Add/Remove &Curve..."), this);
+  actionShowCurvesDialog->setShortcut( tr("ALT+C") );
+  connect(actionShowCurvesDialog, SIGNAL(activated()), this, SLOT(showCurvesDialog()));
+
+  actionAddErrorBars = new QAction(QIcon(getQPixmap("errors_xpm")), tr("Add &Error Bars..."), this);
+  actionAddErrorBars->setShortcut( tr("Ctrl+B") );
+  connect(actionAddErrorBars, SIGNAL(activated()), this, SLOT(addErrorBars()));
+
+  actionRemoveErrorBars = new QAction(QIcon(getQPixmap("errors_xpm")), tr("Remove Error Bars..."), this);
+  //actionRemoveErrorBars->setShortcut( tr("Ctrl+B") );
+  connect(actionRemoveErrorBars, SIGNAL(activated()), this, SLOT(removeErrorBars()));
+
+  actionAddFunctionCurve = new QAction(QIcon(getQPixmap("fx_xpm")), tr("Add &Function..."), this);
+  actionAddFunctionCurve->setShortcut( tr("Ctrl+Alt+F") );
+  connect(actionAddFunctionCurve, SIGNAL(activated()), this, SLOT(addFunctionCurve()));
+
+  actionUnzoom = new QAction(QIcon(getQPixmap("unzoom_xpm")), tr("&Rescale to Show All"), this);
+  actionUnzoom->setShortcut( tr("Ctrl+Shift+R") );
+  connect(actionUnzoom, SIGNAL(activated()), this, SLOT(setAutoScale()));
+
+  actionNewLegend = new QAction(QIcon(getQPixmap("legend_xpm")), tr("New &Legend"), this);
+  actionNewLegend->setShortcut( tr("Ctrl+L") );
+  connect(actionNewLegend, SIGNAL(activated()), this, SLOT(newLegend()));
+
+  actionTimeStamp = new QAction(QIcon(getQPixmap("clock_xpm")), tr("Add Time Stamp"), this);
+  actionTimeStamp->setShortcut( tr("Ctrl+ALT+T") );
+  connect(actionTimeStamp, SIGNAL(activated()), this, SLOT(addTimeStamp()));
+
+  actionAddImage = new QAction(QIcon(getQPixmap("monalisa_xpm")), tr("Add &Image"), this);
+  actionAddImage->setShortcut( tr("ALT+I") );
+  connect(actionAddImage, SIGNAL(activated()), this, SLOT(addImage()));
+
+  actionPlotL = new QAction(QIcon(getQPixmap("lPlot_xpm")), tr("&Line"), this);
+  connect(actionPlotL, SIGNAL(activated()), this, SLOT(plotL()));
+
+  actionPlotP = new QAction(QIcon(getQPixmap("pPlot_xpm")), tr("&Scatter"), this);
+  connect(actionPlotP, SIGNAL(activated()), this, SLOT(plotP()));
+
+  actionPlotLP = new QAction(QIcon(getQPixmap("lpPlot_xpm")), tr("Line + S&ymbol"), this);
+  connect(actionPlotLP, SIGNAL(activated()), this, SLOT(plotLP()));
+
+  actionPlotVerticalDropLines = new QAction(QIcon(getQPixmap("dropLines_xpm")), tr("Vertical &Drop Lines"), this);
+  connect(actionPlotVerticalDropLines, SIGNAL(activated()), this, SLOT(plotVerticalDropLines()));
+
+  actionPlotSpline = new QAction(QIcon(getQPixmap("spline_xpm")), tr("&Spline"), this);
+  connect(actionPlotSpline, SIGNAL(activated()), this, SLOT(plotSpline()));
+
+  actionPlotHorSteps = new QAction(getQPixmap("hor_steps_xpm"), tr("&Horizontal Steps"), this);
+  connect(actionPlotHorSteps, SIGNAL(activated()), this, SLOT(plotHorSteps()));
+
+  actionPlotVertSteps = new QAction(QIcon(getQPixmap("vert_steps_xpm")), tr("&Vertical Steps"), this);
+  connect(actionPlotVertSteps, SIGNAL(activated()), this, SLOT(plotVertSteps()));
+
+  actionPlotVerticalBars = new QAction(QIcon(getQPixmap("vertBars_xpm")), tr("&Columns"), this);
+  connect(actionPlotVerticalBars, SIGNAL(activated()), this, SLOT(plotVerticalBars()));
+
+  actionPlotHorizontalBars = new QAction(QIcon(getQPixmap("hBars_xpm")), tr("&Rows"), this);
+  connect(actionPlotHorizontalBars, SIGNAL(activated()), this, SLOT(plotHorizontalBars()));
+
+  actionPlotArea = new QAction(QIcon(getQPixmap("area_xpm")), tr("&Area"), this);
+  connect(actionPlotArea, SIGNAL(activated()), this, SLOT(plotArea()));
+
+  actionPlotPie = new QAction(QIcon(getQPixmap("pie_xpm")), tr("&Pie"), this);
+  connect(actionPlotPie, SIGNAL(activated()), this, SLOT(plotPie()));
+
+  actionPlotVectXYAM = new QAction(QIcon(getQPixmap("vectXYAM_xpm")), tr("Vectors XY&AM"), this);
+  connect(actionPlotVectXYAM, SIGNAL(activated()), this, SLOT(plotVectXYAM()));
+
+  actionPlotVectXYXY = new QAction(QIcon(getQPixmap("vectXYXY_xpm")), tr("&Vectors &XYXY"), this);
+  connect(actionPlotVectXYXY, SIGNAL(activated()), this, SLOT(plotVectXYXY()));
+
+  actionPlotHistogram = new QAction(QIcon(getQPixmap("histogram_xpm")), tr("&Histogram"), this);
+  connect(actionPlotHistogram, SIGNAL(activated()), this, SLOT(plotHistogram()));
+
+  actionPlotStackedHistograms = new QAction(QIcon(getQPixmap("stacked_hist_xpm")), tr("&Stacked Histogram"), this);
+  connect(actionPlotStackedHistograms, SIGNAL(activated()), this, SLOT(plotStackedHistograms()));
+
+  actionPlot2VerticalLayers = new QAction(QIcon(getQPixmap("panel_v2_xpm")), tr("&Vertical 2 Layers"), this);
+  connect(actionPlot2VerticalLayers, SIGNAL(activated()), this, SLOT(plot2VerticalLayers()));
+
+  actionPlot2HorizontalLayers = new QAction(QIcon(getQPixmap("panel_h2_xpm")), tr("&Horizontal 2 Layers"), this);
+  connect(actionPlot2HorizontalLayers, SIGNAL(activated()), this, SLOT(plot2HorizontalLayers()));
+
+  actionPlot4Layers = new QAction(QIcon(getQPixmap("panel_4_xpm")), tr("&4 Layers"), this);
+  connect(actionPlot4Layers, SIGNAL(activated()), this, SLOT(plot4Layers()));
+
+  actionPlotStackedLayers = new QAction(QIcon(getQPixmap("stacked_xpm")), tr("&Stacked Layers"), this);
+  connect(actionPlotStackedLayers, SIGNAL(activated()), this, SLOT(plotStackedLayers()));
+
+  actionPlot3DRibbon = new QAction(QIcon(getQPixmap("ribbon_xpm")), tr("&Ribbon"), this);
+  connect(actionPlot3DRibbon, SIGNAL(activated()), this, SLOT(plot3DRibbon()));
+
+  actionPlot3DBars = new QAction(QIcon(getQPixmap("bars_xpm")), tr("&Bars"), this);
+  connect(actionPlot3DBars, SIGNAL(activated()), this, SLOT(plot3DBars()));
+
+  actionPlot3DScatter = new QAction(QIcon(getQPixmap("scatter_xpm")), tr("&Scatter"), this);
+  connect(actionPlot3DScatter, SIGNAL(activated()), this, SLOT(plot3DScatter()));
+
+  actionPlot3DTrajectory = new QAction(QIcon(getQPixmap("trajectory_xpm")), tr("&Trajectory"), this);
+  connect(actionPlot3DTrajectory, SIGNAL(activated()), this, SLOT(plot3DTrajectory()));
+
+  actionShowColStatistics = new QAction(QIcon(getQPixmap("col_stat_xpm")), tr("Statistics on &Columns"), this);
+  connect(actionShowColStatistics, SIGNAL(activated()), this, SLOT(showColStatistics()));
+
+  actionShowRowStatistics = new QAction(QIcon(getQPixmap("stat_rows_xpm")), tr("Statistics on &Rows"), this);
+  connect(actionShowRowStatistics, SIGNAL(activated()), this, SLOT(showRowStatistics()));
+
+  actionIntegrate = new QAction(tr("&Integrate"), this);
+  connect(actionIntegrate, SIGNAL(activated()), this, SLOT(integrate()));
+
+  actionShowIntDialog = new QAction(tr("Integr&ate Function..."), this);
+  connect(actionShowIntDialog, SIGNAL(activated()), this, SLOT(showIntegrationDialog()));
+
+  actionInterpolate = new QAction(tr("Inte&rpolate ..."), this);
+  connect(actionInterpolate, SIGNAL(activated()), this, SLOT(showInterpolationDialog()));
+
+  actionLowPassFilter = new QAction(tr("&Low Pass..."), this);
+  connect(actionLowPassFilter, SIGNAL(activated()), this, SLOT(lowPassFilterDialog()));
+
+  actionHighPassFilter = new QAction(tr("&High Pass..."), this);
+  connect(actionHighPassFilter, SIGNAL(activated()), this, SLOT(highPassFilterDialog()));
+
+  actionBandPassFilter = new QAction(tr("&Band Pass..."), this);
+  connect(actionBandPassFilter, SIGNAL(activated()), this, SLOT(bandPassFilterDialog()));
+
+  actionBandBlockFilter = new QAction(tr("&Band Block..."), this);
+  connect(actionBandBlockFilter, SIGNAL(activated()), this, SLOT(bandBlockFilterDialog()));
+
+  actionFFT = new QAction(tr("&FFT..."), this);
+  connect(actionFFT, SIGNAL(activated()), this, SLOT(showFFTDialog()));
+
+  actionSmoothSavGol = new QAction(tr("&Savitzky-Golay..."), this);
+  connect(actionSmoothSavGol, SIGNAL(activated()), this, SLOT(showSmoothSavGolDialog()));
+
+  actionSmoothFFT = new QAction(tr("&FFT Filter..."), this);
+  connect(actionSmoothFFT, SIGNAL(activated()), this, SLOT(showSmoothFFTDialog()));
+
+  actionSmoothAverage = new QAction(tr("Moving Window &Average..."), this);
+  connect(actionSmoothAverage, SIGNAL(activated()), this, SLOT(showSmoothAverageDialog()));
+
+  actionDifferentiate = new QAction(tr("&Differentiate"), this);
+  connect(actionDifferentiate, SIGNAL(activated()), this, SLOT(differentiate()));
+
+  actionFitLinear = new QAction(tr("Fit &Linear"), this);
+  connect(actionFitLinear, SIGNAL(activated()), this, SLOT(fitLinear()));
+
+  actionShowFitPolynomDialog = new QAction(tr("Fit &Polynomial ..."), this);
+  connect(actionShowFitPolynomDialog, SIGNAL(activated()), this, SLOT(showFitPolynomDialog()));
+
+  actionShowExpDecayDialog = new QAction(tr("&First Order ..."), this);
+  connect(actionShowExpDecayDialog, SIGNAL(activated()), this, SLOT(showExpDecayDialog()));
+
+  actionShowTwoExpDecayDialog = new QAction(tr("&Second Order ..."), this);
+  connect(actionShowTwoExpDecayDialog, SIGNAL(activated()), this, SLOT(showTwoExpDecayDialog()));
+
+  actionShowExpDecay3Dialog = new QAction(tr("&Third Order ..."), this);
+  connect(actionShowExpDecay3Dialog, SIGNAL(activated()), this, SLOT(showExpDecay3Dialog()));
+
+  actionFitExpGrowth = new QAction(tr("Fit Exponential Gro&wth ..."), this);
+  connect(actionFitExpGrowth, SIGNAL(activated()), this, SLOT(showExpGrowthDialog()));
+
+  actionFitSigmoidal = new QAction(tr("Fit &Boltzmann (Sigmoidal)"), this);
+  connect(actionFitSigmoidal, SIGNAL(activated()), this, SLOT(fitSigmoidal()));
+
+  actionFitGauss = new QAction(tr("Fit &Gaussian"), this);
+  connect(actionFitGauss, SIGNAL(activated()), this, SLOT(fitGauss()));
+
+  actionFitLorentz = new QAction(tr("Fit Lorent&zian"), this);
+  connect(actionFitLorentz, SIGNAL(activated()), this, SLOT(fitLorentz()));
+
+  actionShowFitDialog = new QAction(tr("Fit &Wizard..."), this);
+  actionShowFitDialog->setShortcut( tr("Ctrl+Y") );
+  connect(actionShowFitDialog, SIGNAL(activated()), this, SLOT(showFitDialog()));
+
+  actionShowPlotDialog = new QAction(tr("&Plot ..."), this);
+  connect(actionShowPlotDialog, SIGNAL(activated()), this, SLOT(showGeneralPlotDialog()));
+
+  actionShowScaleDialog = new QAction(tr("&Scales..."), this);
+  connect(actionShowScaleDialog, SIGNAL(activated()), this, SLOT(showScaleDialog()));
+
+  actionShowAxisDialog = new QAction(tr("&Axes..."), this);
+  connect(actionShowAxisDialog, SIGNAL(activated()), this, SLOT(showAxisDialog()));
+
+  actionShowGridDialog = new QAction(tr("&Grid ..."), this);
+  connect(actionShowGridDialog, SIGNAL(activated()), this, SLOT(showGridDialog()));
+
+  actionShowTitleDialog = new QAction(tr("&Title ..."), this);
+  connect(actionShowTitleDialog, SIGNAL(activated()), this, SLOT(showTitleDialog()));
+
+  actionShowColumnOptionsDialog = new QAction(tr("Column &Options ..."), this);
+  actionShowColumnOptionsDialog->setShortcut(tr("Ctrl+Alt+O"));
+  connect(actionShowColumnOptionsDialog, SIGNAL(activated()), this, SLOT(showColumnOptionsDialog()));
+
+  actionShowColumnValuesDialog = new QAction(QIcon(getQPixmap("formula_xpm")), tr("Set Column &Values ..."), this);
+  connect(actionShowColumnValuesDialog, SIGNAL(activated()), this, SLOT(showColumnValuesDialog()));
+  actionShowColumnValuesDialog->setShortcut(tr("Alt+Q"));
+
+  actionTableRecalculate = new QAction(tr("Recalculate"), this);
+  actionTableRecalculate->setShortcut(tr("Ctrl+Return"));
+  connect(actionTableRecalculate, SIGNAL(activated()), this, SLOT(recalculateTable()));
+
+  actionHideSelectedColumns = new QAction(tr("&Hide Selected"), this);
+  connect(actionHideSelectedColumns, SIGNAL(activated()), this, SLOT(hideSelectedColumns()));
+
+  actionShowAllColumns = new QAction(tr("Sho&w All Columns"), this);
+  connect(actionShowAllColumns, SIGNAL(activated()), this, SLOT(showAllColumns()));
+
+  actionSwapColumns = new QAction(QIcon(getQPixmap("swap_columns_xpm")), tr("&Swap columns"), this);
+  connect(actionSwapColumns, SIGNAL(activated()), this, SLOT(swapColumns()));
+
+  actionMoveColRight = new QAction(QIcon(getQPixmap("move_col_right_xpm")), tr("Move &Right"), this);
+  connect(actionMoveColRight, SIGNAL(activated()), this, SLOT(moveColumnRight()));
+
+  actionMoveColLeft = new QAction(QIcon(getQPixmap("move_col_left_xpm")), tr("Move &Left"), this);
+  connect(actionMoveColLeft, SIGNAL(activated()), this, SLOT(moveColumnLeft()));
+
+  actionMoveColFirst = new QAction(QIcon(getQPixmap("move_col_first_xpm")), tr("Move to F&irst"), this);
+  connect(actionMoveColFirst, SIGNAL(activated()), this, SLOT(moveColumnFirst()));
+
+  actionMoveColLast = new QAction(QIcon(getQPixmap("move_col_last_xpm")), tr("Move to Las&t"), this);
+  connect(actionMoveColLast, SIGNAL(activated()), this, SLOT(moveColumnLast()));
+
+  actionShowColsDialog = new QAction(tr("&Columns..."), this);
+  connect(actionShowColsDialog, SIGNAL(activated()), this, SLOT(showColsDialog()));
+
+  actionShowRowsDialog = new QAction(tr("&Rows..."), this);
+  connect(actionShowRowsDialog, SIGNAL(activated()), this, SLOT(showRowsDialog()));
+
+  actionDeleteRows = new QAction(tr("&Delete Rows Interval..."), this);
+  connect(actionDeleteRows, SIGNAL(activated()), this, SLOT(showDeleteRowsDialog()));
+
+  actionAbout = new QAction(tr("&About MantidPlot"), this);//Mantid
+  actionAbout->setShortcut( tr("F1") );
+  connect(actionAbout, SIGNAL(activated()), this, SLOT(about()));
+
+  actionShowHelp = new QAction(tr("&Help"), this);
+  actionShowHelp->setShortcut( tr("Ctrl+H") );
+  connect(actionShowHelp, SIGNAL(activated()), this, SLOT(showHelp()));
+
+  actionMantidConcepts=new QAction(tr("&Mantid Concepts"), this);
+  connect(actionMantidConcepts, SIGNAL(activated()), this, SLOT(showMantidConcepts()));
+
+  actionMantidAlgorithms=new QAction(tr("&Algorithm Descriptions"), this);
+  connect(actionMantidAlgorithms, SIGNAL(activated()), this, SLOT(showalgorithmDescriptions()));
+
+  actionmantidplotHelp=new QAction(tr("&MantidPlot Help"), this);
+  connect(actionmantidplotHelp, SIGNAL(activated()), this, SLOT(showmantidplotHelp()));
+
+
+  actionChooseHelpFolder = new QAction(tr("&Choose Help Folder..."), this);
+  connect(actionChooseHelpFolder, SIGNAL(activated()), this, SLOT(chooseHelpFolder()));
+
+  actionRename = new QAction(tr("&Rename Window"), this);
+  connect(actionRename, SIGNAL(activated()), this, SLOT(rename()));
+
+  actionCloseWindow = new QAction(QIcon(getQPixmap("close_xpm")), tr("Close &Window"), this);
+  actionCloseWindow->setShortcut( tr("Ctrl+W") );
+  connect(actionCloseWindow, SIGNAL(activated()), this, SLOT(closeActiveWindow()));
+
+  actionAddColToTable = new QAction(QIcon(getQPixmap("addCol_xpm")), tr("Add Column"), this);
+  connect(actionAddColToTable, SIGNAL(activated()), this, SLOT(addColToTable()));
+
+  actionGoToRow = new QAction(tr("&Go to Row..."), this);
+  actionGoToRow->setShortcut(tr("Ctrl+Alt+G"));
+  connect(actionGoToRow, SIGNAL(activated()), this, SLOT(goToRow()));
+
+  actionGoToColumn = new QAction(tr("Go to Colum&n..."), this);
+  actionGoToColumn->setShortcut(tr("Ctrl+Alt+C"));
+  connect(actionGoToColumn, SIGNAL(activated()), this, SLOT(goToColumn()));
+
+  actionClearTable = new QAction(getQPixmap("erase_xpm"), tr("Clear"), this);
+  connect(actionClearTable, SIGNAL(activated()), this, SLOT(clearTable()));
+
+  actionDeleteLayer = new QAction(QIcon(getQPixmap("erase_xpm")), tr("&Remove Layer"), this);
+  actionDeleteLayer->setShortcut( tr("Alt+R") );
+  connect(actionDeleteLayer, SIGNAL(activated()), this, SLOT(deleteLayer()));
+
+  actionResizeActiveWindow = new QAction(QIcon(getQPixmap("resize_xpm")), tr("Window &Geometry..."), this);
+  connect(actionResizeActiveWindow, SIGNAL(activated()), this, SLOT(resizeActiveWindow()));
+
+  actionHideActiveWindow = new QAction(tr("&Hide Window"), this);
+  connect(actionHideActiveWindow, SIGNAL(activated()), this, SLOT(hideActiveWindow()));
+
+  actionShowMoreWindows = new QAction(tr("More windows..."), this);
+  connect(actionShowMoreWindows, SIGNAL(activated()), this, SLOT(showMoreWindows()));
+
+  actionPixelLineProfile = new QAction(QIcon(getQPixmap("pixelProfile_xpm")), tr("&View Pixel Line Profile"), this);
+  connect(actionPixelLineProfile, SIGNAL(activated()), this, SLOT(pixelLineProfile()));
+
+  actionIntensityTable = new QAction(tr("&Intensity Table"), this);
+  connect(actionIntensityTable, SIGNAL(activated()), this, SLOT(intensityTable()));
+
+  actionShowLineDialog = new QAction(tr("&Properties"), this);
+  connect(actionShowLineDialog, SIGNAL(activated()), this, SLOT(showLineDialog()));
+
+  actionShowImageDialog = new QAction(tr("&Properties"), this);
+  connect(actionShowImageDialog, SIGNAL(activated()), this, SLOT(showImageDialog()));
+
+  actionShowTextDialog = new QAction(tr("&Properties"), this);
+  connect(actionShowTextDialog, SIGNAL(activated()), this, SLOT(showTextDialog()));
+
+  actionActivateWindow = new QAction(tr("&Activate Window"), this);
+  connect(actionActivateWindow, SIGNAL(activated()), this, SLOT(activateWindow()));
+
+  actionMinimizeWindow = new QAction(tr("Mi&nimize Window"), this);
+  connect(actionMinimizeWindow, SIGNAL(activated()), this, SLOT(minimizeWindow()));
+
+  actionMaximizeWindow = new QAction(tr("Ma&ximize Window"), this);
+  connect(actionMaximizeWindow, SIGNAL(activated()), this, SLOT(maximizeWindow()));
+
+  actionHideWindow = new QAction(tr("&Hide Window"), this);
+  connect(actionHideWindow, SIGNAL(activated()), this, SLOT(hideWindow()));
+
+  actionResizeWindow = new QAction(QIcon(getQPixmap("resize_xpm")), tr("Re&size Window..."), this);
+  connect(actionResizeWindow, SIGNAL(activated()), this, SLOT(resizeWindow()));
+
+  actionEditSurfacePlot = new QAction(tr("&Surface..."), this);
+  connect(actionEditSurfacePlot, SIGNAL(activated()), this, SLOT(editSurfacePlot()));
+
+  actionAdd3DData = new QAction(tr("&Data Set..."), this);
+  connect(actionAdd3DData, SIGNAL(activated()), this, SLOT(add3DData()));
+
+  actionSetMatrixProperties = new QAction(tr("Set &Properties..."), this);
+  connect(actionSetMatrixProperties, SIGNAL(activated()), this, SLOT(showMatrixDialog()));
+
+  actionSetMatrixDimensions = new QAction(tr("Set &Dimensions..."), this);
+  connect(actionSetMatrixDimensions, SIGNAL(activated()), this, SLOT(showMatrixSizeDialog()));
+  actionSetMatrixDimensions->setShortcut(tr("Ctrl+D"));
+
+  actionSetMatrixValues = new QAction(QIcon(getQPixmap("formula_xpm")), tr("Set &Values..."), this);
+  connect(actionSetMatrixValues, SIGNAL(activated()), this, SLOT(showMatrixValuesDialog()));
+  actionSetMatrixValues->setShortcut(tr("Alt+Q"));
+
+  actionImagePlot =  new QAction(QIcon(getQPixmap("image_plot_xpm")), tr("&Image Plot"), this);
+  connect(actionImagePlot, SIGNAL(activated()), this, SLOT(plotImage()));
+
+  actionTransposeMatrix = new QAction(tr("&Transpose"), this);
+  connect(actionTransposeMatrix, SIGNAL(activated()), this, SLOT(transposeMatrix()));
+
+  actionFlipMatrixVertically = new QAction(QIcon(getQPixmap("flip_vertical_xpm")), tr("Flip &V"), this);
+  actionFlipMatrixVertically->setShortcut(tr("Ctrl+Shift+V"));
+  connect(actionFlipMatrixVertically, SIGNAL(activated()), this, SLOT(flipMatrixVertically()));
+
+  actionFlipMatrixHorizontally = new QAction(QIcon(getQPixmap("flip_horizontal_xpm")), tr("Flip &H"), this);
+  actionFlipMatrixHorizontally->setShortcut(tr("Ctrl+Shift+H"));
+  connect(actionFlipMatrixHorizontally, SIGNAL(activated()), this, SLOT(flipMatrixHorizontally()));
+
+  actionRotateMatrix = new QAction(QIcon(getQPixmap("rotate_clockwise_xpm")), tr("R&otate 90"), this);
+  actionRotateMatrix->setShortcut(tr("Ctrl+Shift+R"));
+  connect(actionRotateMatrix, SIGNAL(activated()), this, SLOT(rotateMatrix90()));
+
+  actionRotateMatrixMinus = new QAction(QIcon(getQPixmap("rotate_counterclockwise_xpm")), tr("Rotate &-90"), this);
+  actionRotateMatrixMinus->setShortcut(tr("Ctrl+Alt+R"));
+  connect(actionRotateMatrixMinus, SIGNAL(activated()), this, SLOT(rotateMatrixMinus90()));
+
+  actionInvertMatrix = new QAction(tr("&Invert"), this);
+  connect(actionInvertMatrix, SIGNAL(activated()), this, SLOT(invertMatrix()));
+
+  actionMatrixDeterminant = new QAction(tr("&Determinant"), this);
+  connect(actionMatrixDeterminant, SIGNAL(activated()), this, SLOT(matrixDeterminant()));
+
+  actionViewMatrixImage = new QAction(tr("&Image mode"), this);
+  actionViewMatrixImage->setShortcut(tr("Ctrl+Shift+I"));
+  connect(actionViewMatrixImage, SIGNAL(activated()), this, SLOT(viewMatrixImage()));
+  actionViewMatrixImage->setCheckable(true);
+
+  actionViewMatrix = new QAction(tr("&Data mode"), this);
+  actionViewMatrix->setShortcut(tr("Ctrl+Shift+D"));
+  connect(actionViewMatrix, SIGNAL(activated()), this, SLOT(viewMatrixTable()));
+  actionViewMatrix->setCheckable(true);
+
+  actionMatrixXY = new QAction(tr("Show &X/Y"), this);
+  actionMatrixXY->setShortcut(tr("Ctrl+Shift+X"));
+  connect(actionMatrixXY, SIGNAL(activated()), this, SLOT(viewMatrixXY()));
+  actionMatrixXY->setCheckable(true);
+
+  actionMatrixColumnRow = new QAction(tr("Show &Column/Row"), this);
+  actionMatrixColumnRow->setShortcut(tr("Ctrl+Shift+C"));
+  connect(actionMatrixColumnRow, SIGNAL(activated()), this, SLOT(viewMatrixColumnRow()));
+  actionMatrixColumnRow->setCheckable(true);
+
+  actionMatrixGrayScale = new QAction(tr("&Gray Scale"), this);
+  connect(actionMatrixGrayScale, SIGNAL(activated()), this, SLOT(setMatrixGrayScale()));
+  actionMatrixGrayScale->setCheckable(true);
+
+  actionMatrixRainbowScale = new QAction(tr("&Rainbow"), this);
+  connect(actionMatrixRainbowScale, SIGNAL(activated()), this, SLOT(setMatrixRainbowScale()));
+  actionMatrixRainbowScale->setCheckable(true);
+
+  actionMatrixCustomScale = new QAction(tr("&Custom"), this);
+  connect(actionMatrixCustomScale, SIGNAL(activated()), this, SLOT(showColorMapDialog()));
+  actionMatrixCustomScale->setCheckable(true);
+
+  actionExportMatrix = new QAction(tr("&Export Image ..."), this);
+  connect(actionExportMatrix, SIGNAL(activated()), this, SLOT(exportMatrix()));
+
+  actionConvertMatrixDirect = new QAction(tr("&Direct"), this);
+  connect(actionConvertMatrixDirect, SIGNAL(activated()), this, SLOT(convertMatrixToTableDirect()));
+
+  actionConvertMatrixXYZ = new QAction(tr("&XYZ Columns"), this);
+  connect(actionConvertMatrixXYZ, SIGNAL(activated()), this, SLOT(convertMatrixToTableXYZ()));
+
+  actionConvertMatrixYXZ = new QAction(tr("&YXZ Columns"), this);
+  connect(actionConvertMatrixYXZ, SIGNAL(activated()), this, SLOT(convertMatrixToTableYXZ()));
+
+  actionMatrixFFTDirect = new QAction(tr("&Forward FFT"), this);
+  connect(actionMatrixFFTDirect, SIGNAL(activated()), this, SLOT(matrixDirectFFT()));
+
+  actionMatrixFFTInverse = new QAction(tr("&Inverse FFT"), this);
+  connect(actionMatrixFFTInverse, SIGNAL(activated()), this, SLOT(matrixInverseFFT()));
+
+  actionConvertTable= new QAction(tr("Convert to &Matrix"), this);
+  connect(actionConvertTable, SIGNAL(activated()), this, SLOT(convertTableToMatrix()));
+
+  actionPlot3DWireFrame = new QAction(QIcon(getQPixmap("lineMesh_xpm")), tr("3D &Wire Frame"), this);
+  connect(actionPlot3DWireFrame, SIGNAL(activated()), this, SLOT(plot3DWireframe()));
+
+  actionPlot3DHiddenLine = new QAction(QIcon(getQPixmap("grid_only_xpm")), tr("3D &Hidden Line"), this);
+  connect(actionPlot3DHiddenLine, SIGNAL(activated()), this, SLOT(plot3DHiddenLine()));
+
+  actionPlot3DPolygons = new QAction(QIcon(getQPixmap("no_grid_xpm")), tr("3D &Polygons"), this);
+  connect(actionPlot3DPolygons, SIGNAL(activated()), this, SLOT(plot3DPolygons()));
+
+  actionPlot3DWireSurface = new QAction(QIcon(getQPixmap("grid_poly_xpm")), tr("3D Wire &Surface"), this);
+  connect(actionPlot3DWireSurface, SIGNAL(activated()), this, SLOT(plot3DWireSurface()));
+
+  actionColorMap = new QAction(QIcon(getQPixmap("color_map_xpm")), tr("Contour - &Color Fill"), this);
+  connect(actionColorMap, SIGNAL(activated()), this, SLOT(plotColorMap()));
+
+  actionContourMap = new QAction(QIcon(getQPixmap("contour_map_xpm")), tr("Contour &Lines"), this);
+  connect(actionContourMap, SIGNAL(activated()), this, SLOT(plotContour()));
+
+  actionGrayMap = new QAction(QIcon(getQPixmap("gray_map_xpm")), tr("&Gray Scale Map"), this);
+  connect(actionGrayMap, SIGNAL(activated()), this, SLOT(plotGrayScale()));
+
+  actionNoContourColorMap = new QAction(QIcon(getQPixmap("color_map_xpm")), tr("Color &Fill"), this);
+  connect(actionNoContourColorMap, SIGNAL(activated()), this, SLOT(plotNoContourColorMap()));
+
+  actionSortTable = new QAction(tr("Sort Ta&ble"), this);
+  connect(actionSortTable, SIGNAL(activated()), this, SLOT(sortActiveTable()));
+
+  actionSortSelection = new QAction(tr("Sort Columns"), this);
+  connect(actionSortSelection, SIGNAL(activated()), this, SLOT(sortSelection()));
+
+  actionNormalizeTable = new QAction(tr("&Table"), this);
+  connect(actionNormalizeTable, SIGNAL(activated()), this, SLOT(normalizeActiveTable()));
+
+  actionNormalizeSelection = new QAction(tr("&Columns"), this);
+  connect(actionNormalizeSelection, SIGNAL(activated()), this, SLOT(normalizeSelection()));
+
+  actionCorrelate = new QAction(tr("Co&rrelate"), this);
+  connect(actionCorrelate, SIGNAL(activated()), this, SLOT(correlate()));
+
+  actionAutoCorrelate = new QAction(tr("&Autocorrelate"), this);
+  connect(actionAutoCorrelate, SIGNAL(activated()), this, SLOT(autoCorrelate()));
+
+  actionConvolute = new QAction(tr("&Convolute"), this);
+  connect(actionConvolute, SIGNAL(activated()), this, SLOT(convolute()));
+
+  actionDeconvolute = new QAction(tr("&Deconvolute"), this);
+  connect(actionDeconvolute, SIGNAL(activated()), this, SLOT(deconvolute()));
+
+  actionTranslateHor = new QAction(tr("&Horizontal"), this);
+  connect(actionTranslateHor, SIGNAL(activated()), this, SLOT(translateCurveHor()));
+
+  actionTranslateVert = new QAction(tr("&Vertical"), this);
+  connect(actionTranslateVert, SIGNAL(activated()), this, SLOT(translateCurveVert()));
+
+  actionSetAscValues = new QAction(QIcon(getQPixmap("rowNumbers_xpm")),tr("Ro&w Numbers"), this);
+  connect(actionSetAscValues, SIGNAL(activated()), this, SLOT(setAscValues()));
+
+  actionSetRandomValues = new QAction(QIcon(getQPixmap("randomNumbers_xpm")),tr("&Random Values"), this);
+  connect(actionSetRandomValues, SIGNAL(activated()), this, SLOT(setRandomValues()));
+
+  actionReadOnlyCol = new QAction(tr("&Read Only"), this);
+  connect(actionReadOnlyCol, SIGNAL(activated()), this, SLOT(setReadOnlyCol()));
+
+  actionSetXCol = new QAction(QIcon(getQPixmap("x_col_xpm")), tr("&X"), this);
+  connect(actionSetXCol, SIGNAL(activated()), this, SLOT(setXCol()));
+
+  actionSetYCol = new QAction(QIcon(getQPixmap("y_col_xpm")), tr("&Y"), this);
+  connect(actionSetYCol, SIGNAL(activated()), this, SLOT(setYCol()));
+
+  actionSetZCol = new QAction(QIcon(getQPixmap("z_col_xpm")), tr("&Z"), this);
+  connect(actionSetZCol, SIGNAL(activated()), this, SLOT(setZCol()));
+
+  actionSetXErrCol = new QAction(tr("X E&rror"), this);
+  connect(actionSetXErrCol, SIGNAL(activated()), this, SLOT(setXErrCol()));
+
+  actionSetYErrCol = new QAction(QIcon(getQPixmap("errors_xpm")), tr("Y &Error"), this);
+  connect(actionSetYErrCol, SIGNAL(activated()), this, SLOT(setYErrCol()));
+
+  actionDisregardCol = new QAction(QIcon(getQPixmap("disregard_col_xpm")), tr("&Disregard"), this);
+  connect(actionDisregardCol, SIGNAL(activated()), this, SLOT(disregardCol()));
+
+  actionSetLabelCol = new QAction(QIcon(getQPixmap("set_label_col_xpm")), tr("&Label"), this);
+  connect(actionSetLabelCol, SIGNAL(activated()), this, SLOT(setLabelCol()));
+
+  actionBoxPlot = new QAction(QIcon(getQPixmap("boxPlot_xpm")),tr("&Box Plot"), this);
+  connect(actionBoxPlot, SIGNAL(activated()), this, SLOT(plotBoxDiagram()));
+
+  actionMultiPeakGauss = new QAction(tr("&Gaussian..."), this);
+  connect(actionMultiPeakGauss, SIGNAL(activated()), this, SLOT(fitMultiPeakGauss()));
+
+  actionMultiPeakLorentz = new QAction(tr("&Lorentzian..."), this);
+  connect(actionMultiPeakLorentz, SIGNAL(activated()), this, SLOT(fitMultiPeakLorentz()));
+
+  //actionCheckUpdates = new QAction(tr("Search for &Updates"), this);
+  //connect(actionCheckUpdates, SIGNAL(activated()), this, SLOT(searchForUpdates()));
+
+  actionHomePage = new QAction(tr("&Mantid Homepage"), this); //Mantid change
+  connect(actionHomePage, SIGNAL(activated()), this, SLOT(showHomePage()));
+
+  //actionHelpForums = new QAction(tr("QtiPlot &Forums"), this); // Mantid change
+  //	connect(actionHelpForums, SIGNAL(triggered()), this, SLOT(showForums())); // Mantid change
+
+  actionHelpBugReports = new QAction(tr("Report a &Bug"), this);
+  connect(actionHelpBugReports, SIGNAL(triggered()), this, SLOT(showBugTracker()));
+
+  //actionDownloadManual = new QAction(tr("Download &Manual"), this); // Mantid change
+  //connect(actionDownloadManual, SIGNAL(activated()), this, SLOT(downloadManual())); // Mantid change
+
+  //actionTranslations = new QAction(tr("&Translations"), this); // Mantid change
+  //connect(actionTranslations, SIGNAL(activated()), this, SLOT(downloadTranslation())); // Mantid change
+
+  //actionDonate = new QAction(tr("Make a &Donation"), this); // Mantid change
+  //connect(actionDonate, SIGNAL(activated()), this, SLOT(showDonationsPage())); // Mantid change
+
+  // 	actionTechnicalSupport = new QAction(tr("Technical &Support"), this); // Mantid change
+  // 	connect(actionTechnicalSupport, SIGNAL(activated()), this, SLOT(showSupportPage())); // Mantid change
+
+  //#ifdef SCRIPTING_DIALOG
+  //	actionScriptingLang = new QAction(tr("Scripting &language"), this);
+  //	connect(actionScriptingLang, SIGNAL(activated()), this, SLOT(showScriptingLangDialog()));
+  //#endif
+
+  actionNoteExecute = new QAction(tr("E&xecute"), this);
+  actionNoteExecute->setShortcut(tr("Ctrl+J"));
+
+  actionNoteExecuteAll = new QAction(tr("Execute &All"), this);
+  actionNoteExecuteAll->setShortcut(tr("Ctrl+Shift+J"));
+
+  actionNoteEvaluate = new QAction(tr("&Evaluate Expression"), this);
+  actionNoteEvaluate->setShortcut(tr("Ctrl+Return"));
+
+#ifdef SCRIPTING_PYTHON
+  actionShowScriptWindow = new QAction(getQPixmap("python_xpm"), tr("Toggle &Script Window"), this);
+  actionShowScriptWindow->setShortcut(tr("F3"));
+  actionShowScriptWindow->setToggleAction(true);
+  connect(actionShowScriptWindow, SIGNAL(activated()), this, SLOT(showScriptWindow()));
+  actionShowScriptInterpreter = new QAction(getQPixmap("python_xpm"), tr("Toggle Script &Interpreter"), this);
+  actionShowScriptInterpreter->setShortcut(tr("F4"));
+  actionShowScriptInterpreter->setToggleAction(true);
+  connect(actionShowScriptInterpreter, SIGNAL(activated()), this, SLOT(showScriptInterpreter()));
+#endif
+
+  actionShowCurvePlotDialog = new QAction(tr("&Plot details..."), this);
+  connect(actionShowCurvePlotDialog, SIGNAL(activated()), this, SLOT(showCurvePlotDialog()));
+
+  actionShowCurveWorksheet = new QAction(tr("&Worksheet"), this);
+  connect(actionShowCurveWorksheet, SIGNAL(activated()), this, SLOT(showCurveWorksheet()));
+
+  actionCurveFullRange = new QAction(tr("&Reset to Full Range"), this);
+  connect(actionCurveFullRange, SIGNAL(activated()), this, SLOT(setCurveFullRange()));
+
+  actionEditCurveRange = new QAction(tr("Edit &Range..."), this);
+  connect(actionEditCurveRange, SIGNAL(activated()), this, SLOT(showCurveRangeDialog()));
+
+  actionRemoveCurve = new QAction(getQPixmap("close_xpm"), tr("&Delete"), this);
+  connect(actionRemoveCurve, SIGNAL(activated()), this, SLOT(removeCurve()));
+
+  actionHideCurve = new QAction(tr("&Hide"), this);
+  connect(actionHideCurve, SIGNAL(activated()), this, SLOT(hideCurve()));
+
+  actionHideOtherCurves = new QAction(tr("Hide &Other Curves"), this);
+  connect(actionHideOtherCurves, SIGNAL(activated()), this, SLOT(hideOtherCurves()));
+
+  actionShowAllCurves = new QAction(tr("&Show All Curves"), this);
+  connect(actionShowAllCurves, SIGNAL(activated()), this, SLOT(showAllCurves()));
+
+  actionEditFunction = new QAction(tr("&Edit Function..."), this);
+  connect(actionEditFunction, SIGNAL(activated()), this, SLOT(showFunctionDialog()));
+
+  actionToolBars = new QAction(tr("&Toolbars..."), this);
+  actionToolBars->setShortcut(tr("Ctrl+Shift+T"));
+  connect(actionToolBars, SIGNAL(activated()), this, SLOT(showToolBarsMenu()));
+
+  actionFontBold = new QAction("B", this);
+  actionFontBold->setToolTip(tr("Bold"));
+  QFont font = appFont;
+  font.setBold(true);
+  actionFontBold->setFont(font);
+  actionFontBold->setCheckable(true);
+  connect(actionFontBold, SIGNAL(toggled(bool)), this, SLOT(setBoldFont(bool)));
+
+  actionFontItalic = new QAction("It", this);
+  actionFontItalic->setToolTip(tr("Italic"));
+  font = appFont;
+  font.setItalic(true);
+  actionFontItalic->setFont(font);
+  actionFontItalic->setCheckable(true);
+  connect(actionFontItalic, SIGNAL(toggled(bool)), this, SLOT(setItalicFont(bool)));
+
+  actionSuperscript = new QAction(getQPixmap("exp_xpm"), tr("Superscript"), this);
+  connect(actionSuperscript, SIGNAL(activated()), this, SLOT(insertSuperscript()));
+  actionSuperscript->setEnabled(false);
+
+  actionSubscript = new QAction(getQPixmap("index_xpm"), tr("Subscript"), this);
+  connect(actionSubscript, SIGNAL(activated()), this, SLOT(insertSubscript()));
+  actionSubscript->setEnabled(false);
+
+  actionUnderline = new QAction("U", this);
+  actionUnderline->setToolTip(tr("Underline (Ctrl+U)"));
+  actionUnderline->setShortcut(tr("Ctrl+U"));
+  font = appFont;
+  font.setUnderline(true);
+  actionUnderline->setFont(font);
+  connect(actionUnderline, SIGNAL(activated()), this, SLOT(underline()));
+  actionUnderline->setEnabled(false);
+
+  actionGreekSymbol = new QAction(QString(QChar(0x3B1)) + QString(QChar(0x3B2)), this);
+  actionGreekSymbol->setToolTip(tr("Greek"));
+  connect(actionGreekSymbol, SIGNAL(activated()), this, SLOT(insertGreekSymbol()));
+
+  actionGreekMajSymbol = new QAction(QString(QChar(0x393)), this);
+  actionGreekMajSymbol->setToolTip(tr("Greek"));
+  connect(actionGreekMajSymbol, SIGNAL(activated()), this, SLOT(insertGreekMajSymbol()));
+
+  actionMathSymbol = new QAction(QString(QChar(0x222B)), this);
+  actionMathSymbol->setToolTip(tr("Mathematical Symbols"));
+  connect(actionMathSymbol, SIGNAL(activated()), this, SLOT(insertMathSymbol()));
+
+  actionclearAllMemory = new QAction("&Clear All Memory",this);
+  actionclearAllMemory->setShortcut(QKeySequence::fromString("Ctrl+Shift+L"));
+  connect(actionclearAllMemory,SIGNAL(triggered()), mantidUI, SLOT(clearAllMemory() ));
+
+#ifdef USE_TCMALLOC
+  actionreleaseFreeMemory = new QAction("&Release Free Memory",this);
+  connect(actionreleaseFreeMemory,SIGNAL(triggered()), mantidUI, SLOT(releaseFreeMemory() ));
+#endif
+
+  actionMagnify = new QAction(QIcon(getQPixmap("magnifier_xpm")), tr("Zoom &In/Out and Drag Canvas"), this);
+  connect(actionMagnify, SIGNAL(activated()), this, SLOT(magnify()));
+
+  actionICatLogin  = new QAction("Login",this);
+  actionICatLogin->setToolTip(tr("Catalog Login"));
+  connect(actionICatLogin, SIGNAL(activated()), this, SLOT(ICatLogin()));
+
+  actionICatSearch=new QAction("Basic Search",this);
+  actionICatSearch->setToolTip(tr("Catalog Basic Search"));
+  connect(actionICatSearch, SIGNAL(activated()), this, SLOT(ICatIsisSearch()));
+
+  actionMydataSearch=new QAction("My Data Search",this);
+  actionMydataSearch->setToolTip(tr("Catalog MyData Search"));
+  connect(actionMydataSearch, SIGNAL(activated()), this, SLOT(ICatMyDataSearch()));
+
+  actionICatLogout=new QAction("Logout",this);
+  actionICatLogout->setToolTip(tr("Catalog Logout"));
+  connect(actionICatLogout, SIGNAL(activated()), this, SLOT(ICatLogout()));
+
+  actionAdvancedSearch = new QAction("Advanced Search",this);
+  actionAdvancedSearch->setToolTip(tr("Catalog Advanced Search"));
+  connect(actionAdvancedSearch, SIGNAL(activated()), this, SLOT(ICatAdvancedSearch()));
+}
+
+void ApplicationWindow::translateActionsStrings()
+{
+  actionFontBold->setToolTip(tr("Bold"));
+  actionFontItalic->setToolTip(tr("Italic"));
+  actionUnderline->setStatusTip(tr("Underline (Ctrl+U)"));
+  actionUnderline->setShortcut(tr("Ctrl+U"));
+  actionGreekSymbol->setToolTip(tr("Greek"));
+  actionGreekMajSymbol->setToolTip(tr("Greek"));
+  actionMathSymbol->setToolTip(tr("Mathematical Symbols"));
+
+  actionShowCurvePlotDialog->setMenuText(tr("&Plot details..."));
+  actionShowCurveWorksheet->setMenuText(tr("&Worksheet"));
+  actionRemoveCurve->setMenuText(tr("&Delete"));
+  actionEditFunction->setMenuText(tr("&Edit Function..."));
+
+  actionCurveFullRange->setMenuText(tr("&Reset to Full Range"));
+  actionEditCurveRange->setMenuText(tr("Edit &Range..."));
+  actionHideCurve->setMenuText(tr("&Hide"));
+  actionHideOtherCurves->setMenuText(tr("Hide &Other Curves"));
+  actionShowAllCurves->setMenuText(tr("&Show All Curves"));
+
+  actionNewProject->setMenuText(tr("New &Project"));
+  actionNewProject->setToolTip(tr("Open a new project"));
+  actionNewProject->setShortcut(tr("Ctrl+N"));
+
+  actionNewFolder->setMenuText(tr("New Fol&der"));
+  actionNewFolder->setToolTip(tr("Create a new folder"));
+  actionNewFolder->setShortcut(Qt::Key_F7);
+
+  actionNewGraph->setMenuText(tr("New &Graph"));
+  actionNewGraph->setToolTip(tr("Create an empty 2D plot"));
+  actionNewGraph->setShortcut(tr("Ctrl+G"));
+
+  actionNewNote->setMenuText(tr("New &Note"));
+  actionNewNote->setToolTip(tr("Create an empty note window"));
+
+  actionNewTable->setMenuText(tr("New &Table"));
+  actionNewTable->setShortcut(tr("Ctrl+T"));
+  actionNewTable->setToolTip(tr("New table"));
+
+  actionNewMatrix->setMenuText(tr("New &Matrix"));
+  actionNewMatrix->setShortcut(tr("Ctrl+M"));
+  actionNewMatrix->setToolTip(tr("New matrix"));
+
+  actionNewFunctionPlot->setMenuText(tr("New &Function Plot"));
+  actionNewFunctionPlot->setToolTip(tr("Create a new 2D function plot"));
+  actionNewFunctionPlot->setShortcut(tr("Ctrl+F"));
+
+  actionNewSurfacePlot->setMenuText(tr("New 3D &Surface Plot"));
+  actionNewSurfacePlot->setToolTip(tr("Create a new 3D surface plot"));
+  actionNewSurfacePlot->setShortcut(tr("Ctrl+ALT+Z"));
+
+  actionOpenProj->setMenuText(tr("&Project"));
+  actionOpenProj->setShortcut(tr("Ctrl+Shift+O"));
+  actionOpenProj->setToolTip(tr("Load Mantid project"));
+
+  actionLoadFile->setMenuText(tr("&File"));
+  actionLoadFile->setShortcut(tr("Ctrl+Shift+F"));
+  actionLoadFile->setToolTip(tr("Load Data File"));
+ 
+
+  actionLoadImage->setMenuText(tr("Open Image &File"));
+  actionLoadImage->setShortcut(tr("Ctrl+I"));
+
+  actionImportImage->setMenuText(tr("Import I&mage..."));
+
+  actionSaveFile->setMenuText(tr("&Nexus"));
+  actionSaveFile->setToolTip(tr("Save nexus file"));
+  actionSaveFile->setShortcut(tr("Ctrl+S"));
+
+  actionSaveProject->setMenuText(tr("&Project"));
+  actionSaveProject->setToolTip(tr("Save Mantid Project"));
+  actionSaveProject->setShortcut(tr("Ctrl+Shift+S"));
+
+
+  actionSaveProjectAs->setMenuText(tr("Save Project &As..."));
+
+  actionOpenTemplate->setMenuText(tr("Open Te&mplate..."));
+  actionOpenTemplate->setToolTip(tr("Open template"));
+
+  actionSaveTemplate->setMenuText(tr("Save As &Template..."));
+  actionSaveTemplate->setToolTip(tr("Save window as template"));
+
+  actionLoad->setMenuText(tr("&Import ASCII..."));
+  actionLoad->setToolTip(tr("Import data file(s)"));
+  actionLoad->setShortcut(tr("Ctrl+K"));
+
+  actionUndo->setMenuText(tr("&Undo"));
+  actionUndo->setToolTip(tr("Undo changes"));
+  actionUndo->setShortcut(tr("Ctrl+Z"));
+
+  actionRedo->setMenuText(tr("&Redo"));
+  actionRedo->setToolTip(tr("Redo changes"));
+  actionRedo->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_Z));
+
+  actionCopyWindow->setMenuText(tr("&Duplicate"));
+  actionCopyWindow->setToolTip(tr("Duplicate window"));
+
+  actionCutSelection->setMenuText(tr("Cu&t Selection"));
+  actionCutSelection->setToolTip(tr("Cut selection"));
+  actionCutSelection->setShortcut(tr("Ctrl+X"));
+  
+  actionCopySelection->setMenuText(tr("&Copy Selection"));
+  actionCopySelection->setToolTip(tr("Copy selection"));
+  actionCopySelection->setShortcut(tr("Ctrl+C"));
+  
+
+  actionPasteSelection->setMenuText(tr("&Paste Selection"));
+  actionPasteSelection->setToolTip(tr("Paste selection"));
+  actionPasteSelection->setShortcut(tr("Ctrl+V"));
+  
+
+  actionClearSelection->setMenuText(tr("&Delete Selection"));
+  actionClearSelection->setToolTip(tr("Delete selection"));
+  actionClearSelection->setShortcut(tr("Del","delete key"));
+
+  actionShowExplorer->setMenuText(tr("Project &Explorer"));
+  actionShowExplorer->setShortcut(tr("Ctrl+E"));
+  actionShowExplorer->setToolTip(tr("Show project explorer"));
+
+  actionShowLog->setMenuText(tr("Results &Log"));
+  actionShowLog->setToolTip(tr("Show analysis results"));
+
+  actionShowUndoStack->setMenuText(tr("&Undo/Redo Stack"));
+  actionShowUndoStack->setToolTip(tr("Show available undo/redo commands"));
+
+    //#ifdef SCRIPTING_CONSOLE
+  actionShowConsole->setMenuText(tr("&Console"));
+  actionShowConsole->setToolTip(tr("Show Scripting console"));
+    //#endif
+
+#ifdef SCRIPTING_PYTHON
+  actionShowScriptWindow->setMenuText(tr("&Script Window"));
+  actionShowScriptWindow->setToolTip(tr("Script Window"));
+  actionShowScriptWindow->setShortcut(tr("F3"));
+#endif
+
+  actionCustomActionDialog->setMenuText(tr("Manage Custom Menus..."));
+
+  actionAddLayer->setMenuText(tr("Add La&yer"));
+  actionAddLayer->setToolTip(tr("Add Layer"));
+  actionAddLayer->setShortcut(tr("Alt+L"));
+
+  actionShowLayerDialog->setMenuText(tr("Arran&ge Layers"));
+  actionShowLayerDialog->setToolTip(tr("Arrange Layers"));
+  actionShowLayerDialog->setShortcut(tr("Alt+A"));
+
+  actionAutomaticLayout->setMenuText(tr("Automatic Layout"));
+  actionAutomaticLayout->setToolTip(tr("Automatic Layout"));
+
+  actionExportGraph->setMenuText(tr("&Current"));
+  actionExportGraph->setShortcut(tr("Alt+G"));
+  actionExportGraph->setToolTip(tr("Export current graph"));
+
+  actionExportAllGraphs->setMenuText(tr("&All"));
+  actionExportAllGraphs->setShortcut(tr("Alt+X"));
+  actionExportAllGraphs->setToolTip(tr("Export all graphs"));
+
+  actionExportPDF->setMenuText(tr("&Export PDF"));
+  actionExportPDF->setShortcut(tr("Ctrl+Alt+P"));
+  actionExportPDF->setToolTip(tr("Export to PDF"));
+
+  actionPrint->setMenuText(tr("&Print"));
+  actionPrint->setShortcut(tr("Ctrl+P"));
+  actionPrint->setToolTip(tr("Print window"));
+
+  actionPrintAllPlots->setMenuText(tr("Print All Plo&ts"));
+  actionShowExportASCIIDialog->setMenuText(tr("E&xport ASCII"));
+
+  actionCloseAllWindows->setMenuText(tr("&Quit"));
+  actionCloseAllWindows->setShortcut(tr("Ctrl+Q"));
+
+  actionClearLogInfo->setMenuText(tr("Clear &Log Information"));
+  actionClearConsole->setMenuText(tr("Clear &Console"));
+  actionDeleteFitTables->setMenuText(tr("Delete &Fit Tables"));
+
+  actionToolBars->setMenuText(tr("&Toolbars..."));
+  actionToolBars->setShortcut(tr("Ctrl+Shift+T"));
+
+  actionShowPlotWizard->setMenuText(tr("Plot &Wizard"));
+  actionShowPlotWizard->setShortcut(tr("Ctrl+Alt+W"));
+
+  actionShowConfigureDialog->setMenuText(tr("&Preferences..."));
+
+  actionShowCurvesDialog->setMenuText(tr("Add/Remove &Curve..."));
+  actionShowCurvesDialog->setShortcut(tr("ALT+C"));
+  actionShowCurvesDialog->setToolTip(tr("Add curve to graph"));
+
+  actionAddErrorBars->setMenuText(tr("Add &Error Bars..."));
+  actionAddErrorBars->setToolTip(tr("Add Error Bars..."));
+  actionAddErrorBars->setShortcut(tr("Ctrl+B"));
+
+  actionAddFunctionCurve->setMenuText(tr("Add &Function..."));
+  actionAddFunctionCurve->setToolTip(tr("Add Function..."));
+  actionAddFunctionCurve->setShortcut(tr("Ctrl+Alt+F"));
+
+  actionUnzoom->setMenuText(tr("&Rescale to Show All"));
+  actionUnzoom->setShortcut(tr("Ctrl+Shift+R"));
+  actionUnzoom->setToolTip(tr("Best fit"));
+
+  actionNewLegend->setMenuText( tr("New &Legend"));
+  actionNewLegend->setShortcut(tr("Ctrl+L"));
+  actionNewLegend->setToolTip(tr("Add new legend"));
+
+  actionTimeStamp->setMenuText(tr("Add Time Stamp"));
+  actionTimeStamp->setShortcut(tr("Ctrl+ALT+T"));
+  actionTimeStamp->setToolTip(tr("Date & time "));
+
+  actionAddImage->setMenuText(tr("Add &Image"));
+  actionAddImage->setToolTip(tr("Add Image"));
+  actionAddImage->setShortcut(tr("ALT+I"));
+
+  actionPlotL->setMenuText(tr("&Line"));
+  actionPlotL->setToolTip(tr("Plot as line"));
+
+  actionPlotP->setMenuText(tr("&Scatter"));
+  actionPlotP->setToolTip(tr("Plot as symbols"));
+
+  actionPlotLP->setMenuText(tr("Line + S&ymbol"));
+  actionPlotLP->setToolTip(tr("Plot as line + symbols"));
+
+  actionPlotVerticalDropLines->setMenuText(tr("Vertical &Drop Lines"));
+
+  actionPlotSpline->setMenuText(tr("&Spline"));
+  actionPlotVertSteps->setMenuText(tr("&Vertical Steps"));
+  actionPlotHorSteps->setMenuText(tr("&Horizontal Steps"));
+
+  actionPlotVerticalBars->setMenuText(tr("&Columns"));
+  actionPlotVerticalBars->setToolTip(tr("Plot with vertical bars"));
+
+  actionPlotHorizontalBars->setMenuText(tr("&Rows"));
+  actionPlotHorizontalBars->setToolTip(tr("Plot with horizontal bars"));
+
+  actionPlotArea->setMenuText(tr("&Area"));
+  actionPlotArea->setToolTip(tr("Plot area"));
+
+  actionPlotPie->setMenuText(tr("&Pie"));
+  actionPlotPie->setToolTip(tr("Plot pie"));
+
+  actionPlotVectXYXY->setMenuText(tr("&Vectors XYXY"));
+  actionPlotVectXYXY->setToolTip(tr("Vectors XYXY"));
+
+  actionPlotVectXYAM->setMenuText(tr("Vectors XY&AM"));
+  actionPlotVectXYAM->setToolTip(tr("Vectors XYAM"));
+
+  actionPlotHistogram->setMenuText( tr("&Histogram"));
+  actionPlotStackedHistograms->setMenuText(tr("&Stacked Histogram"));
+  actionPlot2VerticalLayers->setMenuText(tr("&Vertical 2 Layers"));
+  actionPlot2HorizontalLayers->setMenuText(tr("&Horizontal 2 Layers"));
+  actionPlot4Layers->setMenuText(tr("&4 Layers"));
+  actionPlotStackedLayers->setMenuText(tr("&Stacked Layers"));
+
+  actionPlot3DRibbon->setMenuText(tr("&Ribbon"));
+  actionPlot3DRibbon->setToolTip(tr("Plot 3D ribbon"));
+
+  actionPlot3DBars->setMenuText(tr("&Bars"));
+  actionPlot3DBars->setToolTip(tr("Plot 3D bars"));
+
+  actionPlot3DScatter->setMenuText(tr("&Scatter"));
+  actionPlot3DScatter->setToolTip(tr("Plot 3D scatter"));
+
+  actionPlot3DTrajectory->setMenuText(tr("&Trajectory"));
+  actionPlot3DTrajectory->setToolTip(tr("Plot 3D trajectory"));
+
+  actionColorMap->setMenuText(tr("Contour + &Color Fill"));
+  actionColorMap->setToolTip(tr("Contour Lines + Color Fill"));
+
+  actionNoContourColorMap->setMenuText(tr("Color &Fill"));
+  actionNoContourColorMap->setToolTip(tr("Color Fill (No contours)"));
+
+  actionContourMap->setMenuText(tr("Contour &Lines"));
+  actionContourMap->setToolTip(tr("Contour Lines"));
+
+  actionGrayMap->setMenuText(tr("&Gray Scale Map"));
+  actionGrayMap->setToolTip(tr("Gray Scale Map"));
+
+  actionShowColStatistics->setMenuText(tr("Statistics on &Columns"));
+  actionShowColStatistics->setToolTip(tr("Selected columns statistics"));
+
+  actionShowRowStatistics->setMenuText(tr("Statistics on &Rows"));
+  actionShowRowStatistics->setToolTip(tr("Selected rows statistics"));
+  actionShowIntDialog->setMenuText(tr("Integr&ate Function..."));
+  actionIntegrate->setMenuText(tr("&Integrate"));
+  actionInterpolate->setMenuText(tr("Inte&rpolate ..."));
+  actionLowPassFilter->setMenuText(tr("&Low Pass..."));
+  actionHighPassFilter->setMenuText(tr("&High Pass..."));
+  actionBandPassFilter->setMenuText(tr("&Band Pass..."));
+  actionBandBlockFilter->setMenuText(tr("&Band Block..."));
+  actionFFT->setMenuText(tr("&FFT..."));
+  actionSmoothSavGol->setMenuText(tr("&Savitzky-Golay..."));
+  actionSmoothFFT->setMenuText(tr("&FFT Filter..."));
+  actionSmoothAverage->setMenuText(tr("Moving Window &Average..."));
+  actionDifferentiate->setMenuText(tr("&Differentiate"));
+  actionFitLinear->setMenuText(tr("Fit &Linear"));
+  actionShowFitPolynomDialog->setMenuText(tr("Fit &Polynomial ..."));
+  actionShowExpDecayDialog->setMenuText(tr("&First Order ..."));
+  actionShowTwoExpDecayDialog->setMenuText(tr("&Second Order ..."));
+  actionShowExpDecay3Dialog->setMenuText(tr("&Third Order ..."));
+  actionFitExpGrowth->setMenuText(tr("Fit Exponential Gro&wth ..."));
+  actionFitSigmoidal->setMenuText(tr("Fit &Boltzmann (Sigmoidal)"));
+  actionFitGauss->setMenuText(tr("Fit &Gaussian"));
+  actionFitLorentz->setMenuText(tr("Fit Lorent&zian"));
+
+  actionShowFitDialog->setMenuText(tr("Fit &Wizard..."));
+  actionShowFitDialog->setShortcut(tr("Ctrl+Y"));
+
+  actionShowPlotDialog->setMenuText(tr("&Plot ..."));
+  actionShowScaleDialog->setMenuText(tr("&Scales..."));
+  actionShowAxisDialog->setMenuText(tr("&Axes..."));
+  actionShowGridDialog->setMenuText(tr("&Grid ..."));
+  actionShowTitleDialog->setMenuText(tr("&Title ..."));
+  actionShowColumnOptionsDialog->setMenuText(tr("Column &Options ..."));
+  actionShowColumnOptionsDialog->setShortcut(tr("Ctrl+Alt+O"));
+  actionShowColumnValuesDialog->setMenuText(tr("Set Column &Values ..."));
+  actionShowColumnValuesDialog->setShortcut(tr("Alt+Q"));
+  actionTableRecalculate->setMenuText(tr("Recalculate"));
+  actionTableRecalculate->setShortcut(tr("Ctrl+Return"));
+  actionHideSelectedColumns->setMenuText(tr("&Hide Selected"));
+  actionHideSelectedColumns->setToolTip(tr("Hide selected columns"));
+  actionShowAllColumns->setMenuText(tr("Sho&w All Columns"));
+  actionHideSelectedColumns->setToolTip(tr("Show all table columns"));
+  actionSwapColumns->setMenuText(tr("&Swap columns"));
+  actionSwapColumns->setToolTip(tr("Swap selected columns"));
+  actionMoveColRight->setMenuText(tr("Move &Right"));
+  actionMoveColRight->setToolTip(tr("Move Right"));
+  actionMoveColLeft->setMenuText(tr("Move &Left"));
+  actionMoveColLeft->setToolTip(tr("Move Left"));
+  actionMoveColFirst->setMenuText(tr("Move to F&irst"));
+  actionMoveColFirst->setToolTip(tr("Move to First"));
+  actionMoveColLast->setMenuText(tr("Move to Las&t"));
+  actionMoveColLast->setToolTip(tr("Move to Last"));
+  actionShowColsDialog->setMenuText(tr("&Columns..."));
+  actionShowRowsDialog->setMenuText(tr("&Rows..."));
+  actionDeleteRows->setMenuText(tr("&Delete Rows Interval..."));
+
+  actionAbout->setMenuText(tr("&About MantidPlot"));//Mantid
+  actionAbout->setShortcut(tr("F1"));
+
+  //actionShowHelp->setMenuText(tr("&Help"));
+  //actionShowHelp->setShortcut(tr("Ctrl+H"));
+
+  actionMantidConcepts->setMenuText(tr("&Mantid Concepts"));
+
+  actionMantidAlgorithms->setMenuText("&Algorithm Descriptions");
+
+  actionmantidplotHelp->setMenuText("&MantidPlot Help");
+
+  //actionChooseHelpFolder->setMenuText(tr("&Choose Help Folder..."));
+  //actionRename->setMenuText(tr("&Rename Window"));
+
+  actionCloseWindow->setMenuText(tr("Close &Window"));
+  actionCloseWindow->setShortcut(tr("Ctrl+W"));
+
+  actionAddColToTable->setMenuText(tr("Add Column"));
+  actionAddColToTable->setToolTip(tr("Add Column"));
+
+  actionClearTable->setMenuText(tr("Clear"));
+  actionGoToRow->setMenuText(tr("&Go to Row..."));
+  actionGoToRow->setShortcut(tr("Ctrl+Alt+G"));
+
+  actionGoToColumn->setMenuText(tr("Go to Colum&n..."));
+  actionGoToColumn->setShortcut(tr("Ctrl+Alt+C"));
+
+  actionDeleteLayer->setMenuText(tr("&Remove Layer"));
+  actionDeleteLayer->setShortcut(tr("Alt+R"));
+
+  actionResizeActiveWindow->setMenuText(tr("Window &Geometry..."));
+  actionHideActiveWindow->setMenuText(tr("&Hide Window"));
+  actionShowMoreWindows->setMenuText(tr("More Windows..."));
+  actionPixelLineProfile->setMenuText(tr("&View Pixel Line Profile"));
+  actionIntensityTable->setMenuText(tr("&Intensity Table"));
+  actionShowLineDialog->setMenuText(tr("&Properties"));
+  actionShowImageDialog->setMenuText(tr("&Properties"));
+  actionShowTextDialog->setMenuText(tr("&Properties"));
+  actionActivateWindow->setMenuText(tr("&Activate Window"));
+  actionMinimizeWindow->setMenuText(tr("Mi&nimize Window"));
+  actionMaximizeWindow->setMenuText(tr("Ma&ximize Window"));
+  actionHideWindow->setMenuText(tr("&Hide Window"));
+  actionResizeWindow->setMenuText(tr("Re&size Window..."));
+  actionEditSurfacePlot->setMenuText(tr("&Surface..."));
+  actionAdd3DData->setMenuText(tr("&Data Set..."));
+  actionSetMatrixProperties->setMenuText(tr("Set &Properties..."));
+  actionSetMatrixDimensions->setMenuText(tr("Set &Dimensions..."));
+  actionSetMatrixDimensions->setShortcut(tr("Ctrl+D"));
+  actionSetMatrixValues->setMenuText(tr("Set &Values..."));
+  actionSetMatrixValues->setToolTip(tr("Set Matrix Values"));
+  actionSetMatrixValues->setShortcut(tr("Alt+Q"));
+  actionImagePlot->setMenuText(tr("&Image Plot"));
+  actionImagePlot->setToolTip(tr("Image Plot"));
+  actionTransposeMatrix->setMenuText(tr("&Transpose"));
+  actionRotateMatrix->setMenuText(tr("R&otate 90"));
+  actionRotateMatrix->setToolTip(tr("Rotate 90° Clockwise"));
+  actionRotateMatrixMinus->setMenuText(tr("Rotate &-90"));
+  actionRotateMatrixMinus->setToolTip(tr("Rotate 90° Counterclockwise"));
+  actionFlipMatrixVertically->setMenuText(tr("Flip &V"));
+  actionFlipMatrixVertically->setToolTip(tr("Flip Vertically"));
+  actionFlipMatrixHorizontally->setMenuText(tr("Flip &H"));
+  actionFlipMatrixHorizontally->setToolTip(tr("Flip Horizontally"));
+
+  actionMatrixXY->setMenuText(tr("Show &X/Y"));
+  actionMatrixColumnRow->setMenuText(tr("Show &Column/Row"));
+  actionViewMatrix->setMenuText(tr("&Data mode"));
+  actionViewMatrixImage->setMenuText(tr("&Image mode"));
+  actionMatrixGrayScale->setMenuText(tr("&Gray Scale"));
+  actionMatrixRainbowScale->setMenuText(tr("&Rainbow"));
+  actionMatrixCustomScale->setMenuText(tr("&Custom"));
+  actionInvertMatrix->setMenuText(tr("&Invert"));
+  actionMatrixDeterminant->setMenuText(tr("&Determinant"));
+  actionConvertMatrixDirect->setMenuText(tr("&Direct"));
+  actionConvertMatrixXYZ->setMenuText(tr("&XYZ Columns"));
+  actionConvertMatrixYXZ->setMenuText(tr("&YXZ Columns"));
+  actionExportMatrix->setMenuText(tr("&Export Image ..."));
+
+  actionConvertTable->setMenuText(tr("Convert to &Matrix"));
+  actionPlot3DWireFrame->setMenuText(tr("3D &Wire Frame"));
+  actionPlot3DHiddenLine->setMenuText(tr("3D &Hidden Line"));
+  actionPlot3DPolygons->setMenuText(tr("3D &Polygons"));
+  actionPlot3DWireSurface->setMenuText(tr("3D Wire &Surface"));
+  actionSortTable->setMenuText(tr("Sort Ta&ble"));
+  actionSortSelection->setMenuText(tr("Sort Columns"));
+  actionNormalizeTable->setMenuText(tr("&Table"));
+  actionNormalizeSelection->setMenuText(tr("&Columns"));
+  actionCorrelate->setMenuText(tr("Co&rrelate"));
+  actionAutoCorrelate->setMenuText(tr("&Autocorrelate"));
+  actionConvolute->setMenuText(tr("&Convolute"));
+  actionDeconvolute->setMenuText(tr("&Deconvolute"));
+  actionTranslateHor->setMenuText(tr("&Horizontal"));
+  actionTranslateVert->setMenuText(tr("&Vertical"));
+  actionSetAscValues->setMenuText(tr("Ro&w Numbers"));
+  actionSetAscValues->setToolTip(tr("Fill selected columns with row numbers"));
+  actionSetRandomValues->setMenuText(tr("&Random Values"));
+  actionSetRandomValues->setToolTip(tr("Fill selected columns with random numbers"));
+  actionSetXCol->setMenuText(tr("&X"));
+  actionSetXCol->setToolTip(tr("Set column as X"));
+  actionSetYCol->setMenuText(tr("&Y"));
+  actionSetYCol->setToolTip(tr("Set column as Y"));
+  actionSetZCol->setMenuText(tr("&Z"));
+  actionSetZCol->setToolTip(tr("Set column as Z"));
+  actionSetXErrCol->setMenuText(tr("X E&rror"));
+  actionSetYErrCol->setMenuText(tr("Y &Error"));
+  actionSetYErrCol->setToolTip(tr("Set as Y Error Bars"));
+  actionSetLabelCol->setMenuText(tr("&Label"));
+  actionSetLabelCol->setToolTip(tr("Set as Labels"));
+  actionDisregardCol->setMenuText(tr("&Disregard"));
+  actionDisregardCol->setToolTip(tr("Disregard Columns"));
+  actionReadOnlyCol->setMenuText(tr("&Read Only"));
+
+  actionBoxPlot->setMenuText(tr("&Box Plot"));
+  actionBoxPlot->setToolTip(tr("Box and whiskers plot"));
+
+  actionMultiPeakGauss->setMenuText(tr("&Gaussian..."));
+  actionMultiPeakLorentz->setMenuText(tr("&Lorentzian..."));
+  actionHomePage->setMenuText(tr("&Mantid Homepage")); // Mantid change
+  //actionCheckUpdates->setMenuText(tr("Search for &Updates")); //Mantid change - commented out
+  //actionHelpForums->setText(tr("Visit QtiPlot &Forums"));
+  actionHelpBugReports->setText(tr("Report a &Bug"));
+  //actionDownloadManual->setMenuText(tr("Download &Manual"));//Mantid change - commented out
+  //actionTranslations->setMenuText(tr("&Translations"));//Mantid change - commented out
+  //actionDonate->setMenuText(tr("Make a &Donation"));
+  //actionTechnicalSupport->setMenuText(tr("Technical &Support"));
+
+  //#ifdef SCRIPTING_DIALOG
+  //	actionScriptingLang->setMenuText(tr("Scripting &language"));
+  //#endif
+
+  actionNoteExecute->setMenuText(tr("E&xecute"));
+  actionNoteExecute->setShortcut(tr("Ctrl+J"));
+
+  actionNoteExecuteAll->setMenuText(tr("Execute &All"));
+  actionNoteExecuteAll->setShortcut(tr("Ctrl+Shift+J"));
+
+  actionNoteEvaluate->setMenuText(tr("&Evaluate Expression"));
+  actionNoteEvaluate->setShortcut(tr("Ctrl+Return"));
+
+  btnPointer->setMenuText(tr("Disable &tools"));
+  btnPointer->setToolTip( tr( "Pointer" ) );
+
+  btnZoomIn->setMenuText(tr("&Zoom In"));
+  btnZoomIn->setShortcut(tr("Ctrl++"));
+  btnZoomIn->setToolTip(tr("Zoom In"));
+
+  btnZoomOut->setMenuText(tr("Zoom &Out"));
+  btnZoomOut->setShortcut(tr("Ctrl+-"));
+  btnZoomOut->setToolTip(tr("Zoom Out"));
+
+  actionMagnify->setMenuText(tr("Zoom &In/Out and Drag Canvas"));
+  actionMagnify->setToolTip(tr("Zoom In (Shift++) or Out (-) and Drag Canvas"));
+
+  btnCursor->setMenuText(tr("&Data Reader"));
+  btnCursor->setShortcut(tr("CTRL+D"));
+  btnCursor->setToolTip(tr("Data reader"));
+
+  btnSelect->setMenuText(tr("&Select Data Range"));
+  btnSelect->setShortcut(tr("ALT+S"));
+  btnSelect->setToolTip(tr("Select data range"));
+
+  btnPicker->setMenuText(tr("S&creen Reader"));
+  btnPicker->setToolTip(tr("Screen reader"));
+
+  actionDrawPoints->setMenuText(tr("&Draw Data Points"));
+  actionDrawPoints->setToolTip(tr("Draw Data Points"));
+
+  btnMovePoints->setMenuText(tr("&Move Data Points..."));
+  btnMovePoints->setShortcut(tr("Ctrl+ALT+M"));
+  btnMovePoints->setToolTip(tr("Move data points"));
+
+  btnRemovePoints->setMenuText(tr("Remove &Bad Data Points..."));
+  btnRemovePoints->setShortcut(tr("Alt+B"));
+  btnRemovePoints->setToolTip(tr("Remove data points"));
+
+  actionAddText->setMenuText(tr("Add &Text"));
+  actionAddText->setToolTip(tr("Add Text"));
+  actionAddText->setShortcut(tr("ALT+T"));
+
+  btnArrow->setMenuText(tr("Draw &Arrow"));
+  btnArrow->setShortcut(tr("CTRL+ALT+A"));
+  btnArrow->setToolTip(tr("Draw arrow"));
+
+  btnLine->setMenuText(tr("Draw &Line"));
+  btnLine->setShortcut(tr("CTRL+ALT+L"));
+  btnLine->setToolTip(tr("Draw line"));
+
+  // FIXME: is setText necessary for action groups?
+  //	coord->setText( tr( "Coordinates" ) );
+  //	coord->setMenuText( tr( "&Coord" ) );
+  //  coord->setStatusTip( tr( "Coordinates" ) );
+  Box->setText( tr( "Box" ) );
+  Box->setMenuText( tr( "Box" ) );
+  Box->setToolTip( tr( "Box" ) );
+  Box->setStatusTip( tr( "Box" ) );
+  Frame->setText( tr( "Frame" ) );
+  Frame->setMenuText( tr( "&Frame" ) );
+  Frame->setToolTip( tr( "Frame" ) );
+  Frame->setStatusTip( tr( "Frame" ) );
+  None->setText( tr( "No Axes" ) );
+  None->setMenuText( tr( "No Axes" ) );
+  None->setToolTip( tr( "No axes" ) );
+  None->setStatusTip( tr( "No axes" ) );
+
+  front->setToolTip( tr( "Front grid" ) );
+  back->setToolTip( tr( "Back grid" ) );
+  right->setToolTip( tr( "Right grid" ) );
+  left->setToolTip( tr( "Left grid" ) );
+  ceil->setToolTip( tr( "Ceiling grid" ) );
+  floor->setToolTip( tr( "Floor grid" ) );
+
+  wireframe->setText( tr( "Wireframe" ) );
+  wireframe->setMenuText( tr( "Wireframe" ) );
+  wireframe->setToolTip( tr( "Wireframe" ) );
+  wireframe->setStatusTip( tr( "Wireframe" ) );
+  hiddenline->setText( tr( "Hidden Line" ) );
+  hiddenline->setMenuText( tr( "Hidden Line" ) );
+  hiddenline->setToolTip( tr( "Hidden line" ) );
+  hiddenline->setStatusTip( tr( "Hidden line" ) );
+  polygon->setText( tr( "Polygon Only" ) );
+  polygon->setMenuText( tr( "Polygon Only" ) );
+  polygon->setToolTip( tr( "Polygon only" ) );
+  polygon->setStatusTip( tr( "Polygon only" ) );
+  filledmesh->setText( tr( "Mesh & Filled Polygons" ) );
+  filledmesh->setMenuText( tr( "Mesh & Filled Polygons" ) );
+  filledmesh->setToolTip( tr( "Mesh & filled Polygons" ) );
+  filledmesh->setStatusTip( tr( "Mesh & filled Polygons" ) );
+  pointstyle->setText( tr( "Dots" ) );
+  pointstyle->setMenuText( tr( "Dots" ) );
+  pointstyle->setToolTip( tr( "Dots" ) );
+  pointstyle->setStatusTip( tr( "Dots" ) );
+  barstyle->setText( tr( "Bars" ) );
+  barstyle->setMenuText( tr( "Bars" ) );
+  barstyle->setToolTip( tr( "Bars" ) );
+  barstyle->setStatusTip( tr( "Bars" ) );
+  conestyle->setText( tr( "Cones" ) );
+  conestyle->setMenuText( tr( "Cones" ) );
+  conestyle->setToolTip( tr( "Cones" ) );
+  conestyle->setStatusTip( tr( "Cones" ) );
+  crossHairStyle->setText( tr( "Crosshairs" ) );
+  crossHairStyle->setMenuText( tr( "Crosshairs" ) );
+  crossHairStyle->setToolTip( tr( "Crosshairs" ) );
+  crossHairStyle->setStatusTip( tr( "Crosshairs" ) );
+
+  //floorstyle->setText( tr( "Floor Style" ) );
+  //floorstyle->setMenuText( tr( "Floor Style" ) );
+  //floorstyle->setStatusTip( tr( "Floor Style" ) );
+  floordata->setText( tr( "Floor Data Projection" ) );
+  floordata->setMenuText( tr( "Floor Data Projection" ) );
+  floordata->setToolTip( tr( "Floor data projection" ) );
+  floordata->setStatusTip( tr( "Floor data projection" ) );
+  flooriso->setText( tr( "Floor Isolines" ) );
+  flooriso->setMenuText( tr( "Floor Isolines" ) );
+  flooriso->setToolTip( tr( "Floor isolines" ) );
+  flooriso->setStatusTip( tr( "Floor isolines" ) );
+  floornone->setText( tr( "Empty Floor" ) );
+  floornone->setMenuText( tr( "Empty Floor" ) );
+  floornone->setToolTip( tr( "Empty floor" ) );
+  floornone->setStatusTip( tr( "Empty floor" ) );
+
+  actionAnimate->setText( tr( "Animation" ) );
+  actionAnimate->setMenuText( tr( "Animation" ) );
+  actionAnimate->setToolTip( tr( "Animation" ) );
+  actionAnimate->setStatusTip( tr( "Animation" ) );
+
+  actionPerspective->setText( tr( "Enable perspective" ) );
+  actionPerspective->setMenuText( tr( "Enable perspective" ) );
+  actionPerspective->setToolTip( tr( "Enable perspective" ) );
+  actionPerspective->setStatusTip( tr( "Enable perspective" ) );
+
+  actionResetRotation->setText( tr( "Reset rotation" ) );
+  actionResetRotation->setMenuText( tr( "Reset rotation" ) );
+  actionResetRotation->setToolTip( tr( "Reset rotation" ) );
+  actionResetRotation->setStatusTip( tr( "Reset rotation" ) );
+
+  actionFitFrame->setText( tr( "Fit frame to window" ) );
+  actionFitFrame->setMenuText( tr( "Fit frame to window" ) );
+  actionFitFrame->setToolTip( tr( "Fit frame to window" ) );
+  actionFitFrame->setStatusTip( tr( "Fit frame to window" ) );
+
+
+}
+
+Graph3D * ApplicationWindow::openMatrixPlot3D(const QString& caption, const QString& matrix_name,
+    double xl,double xr,double yl,double yr,double zl,double zr)
+{
+  QString name = matrix_name;
+  name.remove("matrix<", true);
+  name.remove(">");
+  Matrix* m = matrix(name);
+  if (!m)
+    return 0;
+
+  Graph3D *plot = new Graph3D("", this, 0, 0);
+  plot->setWindowTitle(caption);
+  plot->setName(caption);
+  plot->addMatrixData(m, xl, xr, yl, yr, zl, zr);
+  plot->update();
+
+  initPlot3D(plot);
+  return plot;
+}
+
+Graph3D * ApplicationWindow::plot3DMatrix(Matrix *m, int style)
+{
+  if (!m) {
+    //Mantid
+    Graph3D *plot = mantidUI->plot3DMatrix(style);
+    if (plot) return plot;
+    m = (Matrix*)activeWindow(MatrixWindow);
+    if (!m)
+      return 0;
+  }
+
+  QApplication::setOverrideCursor(Qt::WaitCursor);
+  QString label = generateUniqueName(tr("Graph"));
+
+  Graph3D *plot = new Graph3D("", this, 0);
+  plot->addMatrixData(m);
+  plot->customPlotStyle(style);
+  customPlot3D(plot);
+  plot->update();
+
+  plot->resize(500, 400);
+  plot->setWindowTitle(label);
+  plot->setName(label);
+  initPlot3D(plot);
+
+  emit modified();
+  QApplication::restoreOverrideCursor();
+  return plot;
+}
+
+MultiLayer* ApplicationWindow::plotGrayScale(Matrix *m)
+{
+  if (!m) {
+    //Mantid
+    MultiLayer* plot = mantidUI->plotSpectrogram(Graph::GrayScale);
+    if (plot) return plot;
+    m = (Matrix*)activeWindow(MatrixWindow);
+    if (!m)
+      return 0;
+  }
+
+  return plotSpectrogram(m, Graph::GrayScale);
+}
+
+MultiLayer* ApplicationWindow::plotContour(Matrix *m)
+{
+  if (!m) {
+    //Mantid
+    MultiLayer* plot = mantidUI->plotSpectrogram(Graph::Contour);
+    if (plot) return plot;
+    m = (Matrix*)activeWindow(MatrixWindow);
+    if (!m)
+      return 0;
+  }
+
+  return plotSpectrogram(m, Graph::Contour);
+}
+
+MultiLayer* ApplicationWindow::plotColorMap(Matrix *m)
+{
+  if (!m) {
+    //Mantid
+    MultiLayer* plot = mantidUI->plotSpectrogram(Graph::ColorMap);
+    if (plot) return plot;
+    m = (Matrix*)activeWindow(MatrixWindow);
+    if (!m)
+      return 0;
+  }
+
+  return plotSpectrogram(m, Graph::ColorMap);
+}
+
+MultiLayer* ApplicationWindow::plotNoContourColorMap(Matrix *m)
+{
+  MultiLayer* ml = NULL;
+  if( !m )
+  {
+    m = qobject_cast<Matrix*>(activeWindow(MatrixWindow));
+  }
+  if( m )
+  {
+    ml = plotSpectrogram(m, Graph::ColorMap);
+  }
+  else
+  {
+    ml =  mantidUI->plotSpectrogram(Graph::ColorMap);
+  }
+  if( !ml ) 
+  {
+    QApplication::restoreOverrideCursor();
+    return 0;
+  }
+
+  Spectrogram *spgrm = dynamic_cast<Spectrogram*>(ml->activeGraph()->plotItem(0));
+  if( spgrm )
+  {
+    //1 = ImageMode
+    spgrm->setDisplayMode(QwtPlotSpectrogram::ImageMode, true);
+    spgrm->setDisplayMode(QwtPlotSpectrogram::ContourMode, false);
+  }
+  return ml;
+}
+
+MultiLayer* ApplicationWindow::plotImage(Matrix *m)
+{
+  MultiLayer *g = NULL;
+  Graph *plot = NULL;
+  if( !m )
+  {
+    m = qobject_cast<Matrix*>(activeWindow(MatrixWindow));
+  }
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  if( m )
+  {
+    g = multilayerPlot(generateUniqueName(tr("Graph")));
+    plot = g->activeGraph();
+    setPreferences(plot);
+
+    Spectrogram *s = plot->plotSpectrogram(m, Graph::GrayScale);
+    if( !s ) 
+    {
+      QApplication::restoreOverrideCursor();
+      return 0;
+    }
+    s->setAxis(QwtPlot::xTop, QwtPlot::yLeft);
+    plot->setScale(QwtPlot::xTop, QMIN(m->xStart(), m->xEnd()), QMAX(m->xStart(), m->xEnd()));
+    plot->setScale(QwtPlot::yLeft, QMIN(m->yStart(), m->yEnd()), QMAX(m->yStart(), m->yEnd()),
+        0.0, 5, 5, GraphOptions::Linear, true);
+  }
+  else
+  {
+    g =  mantidUI->plotSpectrogram(Graph::GrayScale);
+    if( !g ) 
+    {
+      QApplication::restoreOverrideCursor();
+      return 0;
+    }
+    plot = g->activeGraph();
+    setPreferences(plot);
+    if( plot->plotItem(0) )plot->plotItem(0)->setAxis(QwtPlot::xTop, QwtPlot::yLeft);
+  }
+
+  plot->enableAxis(QwtPlot::xTop, true);
+
+  plot->enableAxis(QwtPlot::xBottom, false);
+  plot->enableAxis(QwtPlot::yRight, false);
+  plot->setAxisTitle(QwtPlot::yLeft, QString::null);
+  plot->setAxisTitle(QwtPlot::xTop, QString::null);
+  plot->setTitle(QString::null);
+
+  emit modified();
+  QApplication::restoreOverrideCursor();
+  return g;
+}
+
+MultiLayer* ApplicationWindow::plotSpectrogram(Matrix *m, Graph::CurveType type)
+{
+  if (type == Graph::ImagePlot)
+    return plotImage(m);
+  else if (type == Graph::Histogram)
+    return plotHistogram(m);
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  MultiLayer* g = multilayerPlot(generateUniqueName(tr("Graph")));
+  Graph* plot = g->activeGraph();
+  setPreferences(plot);
+
+  plot->plotSpectrogram(m, type);
+
+  plot->setAutoScale();//Mantid
+
+  QApplication::restoreOverrideCursor();
+  return g;
+}
+
+ApplicationWindow* ApplicationWindow::importOPJ(const QString& filename, bool factorySettings, bool newProject)
+{
+  if (filename.endsWith(".opj", Qt::CaseInsensitive) || filename.endsWith(".ogg", Qt::CaseInsensitive))
+  {
+    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+    ApplicationWindow *app = this;
+    if (newProject)
+      app = new ApplicationWindow(factorySettings);
+
+    app->setWindowTitle("MantidPlot - " + filename);//Mantid
+    app->restoreApplicationGeometry();
+    app->projectname = filename;
+    app->recentProjects.remove(filename);
+    app->recentProjects.push_front(filename);
+    app->updateRecentProjectsList();
+
+    ImportOPJ(app, filename);
+
+    QApplication::restoreOverrideCursor();
+    return app;
+  }
+  else if (filename.endsWith(".ogm", Qt::CaseInsensitive) || filename.endsWith(".ogw", Qt::CaseInsensitive))
+  {
+    ImportOPJ(this, filename);
+    recentProjects.remove(filename);
+    recentProjects.push_front(filename);
+    updateRecentProjectsList();
+    return this;
+  }
+  return 0;
+}
+
+void ApplicationWindow::deleteFitTables()
+{
+  QList<QWidget*>* mLst = new QList<QWidget*>();
+  QList<MdiSubWindow *> windows = windowsList();
+  foreach(MdiSubWindow *w, windows){
+    if (w->isA("MultiLayer"))
+      mLst->append(w);
+  }
+
+  foreach(QWidget *ml, *mLst){
+    if (ml->isA("MultiLayer")){
+      QList<Graph *> layers = ((MultiLayer*)ml)->layersList();
+      foreach(Graph *g, layers){
+        QList<QwtPlotCurve *> curves = g->fitCurvesList();
+        foreach(QwtPlotCurve *c, curves){
+          if (((PlotCurve *)c)->type() != Graph::Function){
+            Table *t = ((DataCurve *)c)->table();
+            if (!t)
+              continue;
+
+            t->askOnCloseEvent(false);
+            t->close();
+          }
+        }
+      }
+    }
+  }
+  delete mLst;
+}
+
+QList<MdiSubWindow *> ApplicationWindow::windowsList()
+{
+  QList<MdiSubWindow *> lst;
+
+  Folder *f = projectFolder();
+  while (f){
+    QList<MdiSubWindow *> folderWindows = f->windowsList();
+    foreach(MdiSubWindow *w, folderWindows)
+    lst << w;
+    f = f->folderBelow();
+  }
+  return lst;
+}
+
+void ApplicationWindow::updateRecentProjectsList()
+{
+  if (recentProjects.isEmpty())
+    return;
+
+  while ((int)recentProjects.size() > MaxRecentProjects)
+    recentProjects.pop_back();
+
+  recent->clear();
+
+  for (int i = 0; i<(int)recentProjects.size(); i++ )
+    recent->insertItem("&" + QString::number(i+1) + " " + recentProjects[i]);
+}
+
+void ApplicationWindow::translateCurveHor()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty())
+  {
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  Graph* g = (Graph*)plot->activeGraph();
+  if (!g)
+    return;
+
+  if (g->isPiePlot())
+  {
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("This functionality is not available for pie plots!"));
+
+    btnPointer->setChecked(true);
+    return;
+  }
+  else if (g->validCurvesDataSize())
+  {
+    btnPointer->setChecked(true);
+    g->setActiveTool(new TranslateCurveTool(g, this, TranslateCurveTool::Horizontal, info, SLOT(setText(const QString&))));
+    displayBar->show();
+  }
+}
+
+void ApplicationWindow::translateCurveVert()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  Graph* g = (Graph*)plot->activeGraph();
+  if (!g)
+    return;
+
+  if (g->isPiePlot()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("This functionality is not available for pie plots!"));
+
+    btnPointer->setChecked(true);
+    return;
+  } else if (g->validCurvesDataSize()) {
+    btnPointer->setChecked(true);
+    g->setActiveTool(new TranslateCurveTool(g, this, TranslateCurveTool::Vertical, info, SLOT(setText(const QString&))));
+    displayBar->show();
+  }
+}
+
+void ApplicationWindow::setReadOnlyCol()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+  QStringList list = t->selectedColumns();
+  for (int i=0; i<(int) list.count(); i++)
+    t->setReadOnlyColumn(t->colIndex(list[i]), actionReadOnlyCol->isChecked());
+}
+
+void ApplicationWindow::setReadOnlyColumns()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+  QStringList list = t->selectedColumns();
+  for (int i=0; i<(int) list.count(); i++)
+    t->setReadOnlyColumn(t->colIndex(list[i]));
+}
+
+void ApplicationWindow::setReadWriteColumns()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+  QStringList list = t->selectedColumns();
+  for (int i=0; i<(int) list.count(); i++)
+    t->setReadOnlyColumn(t->colIndex(list[i]), false);
+}
+
+void ApplicationWindow::setAscValues()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  t->setAscValues();
+}
+
+void ApplicationWindow::setRandomValues()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  t->setRandomValues();
+}
+
+void ApplicationWindow::setXErrCol()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  t->setPlotDesignation(Table::xErr);
+}
+
+void ApplicationWindow::setYErrCol()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  t->setPlotDesignation(Table::yErr);
+}
+
+void ApplicationWindow::setXCol()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  t->setPlotDesignation(Table::X);
+}
+
+void ApplicationWindow::setYCol()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  t->setPlotDesignation(Table::Y);
+}
+
+void ApplicationWindow::setZCol()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  t->setPlotDesignation(Table::Z);
+}
+
+void ApplicationWindow::setLabelCol()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  t->setPlotDesignation(Table::Label);
+}
+
+void ApplicationWindow::disregardCol()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  t->setPlotDesignation(Table::None);
+}
+
+void ApplicationWindow::fitMultiPeakGauss()
+{
+  fitMultiPeak((int)MultiPeakFit::Gauss);
+}
+
+void ApplicationWindow::fitMultiPeakLorentz()
+{
+  fitMultiPeak((int)MultiPeakFit::Lorentz);
+}
+
+void ApplicationWindow::fitMultiPeak(int profile)
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+  if (plot->isEmpty()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    btnPointer->setChecked(true);
+    return;
+  }
+
+  Graph* g = (Graph*)plot->activeGraph();
+  if (!g || !g->validCurvesDataSize())
+    return;
+
+  if (g->isPiePlot()){
+    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
+        tr("This functionality is not available for pie plots!"));
+    return;
+  } else {
+    bool ok;
+    int peaks = QInputDialog::getInteger(tr("MantidPlot - Enter the number of peaks"),//Mantid
+        tr("Peaks"), 2, 2, 1000000, 1, &ok, this);
+    if (ok && peaks){
+      g->setActiveTool(new MultiPeakFitTool(g, this, (MultiPeakFit::PeakProfile)profile, peaks, info, SLOT(setText(const QString&))));
+      displayBar->show();
+    }
+  }
+}
+
+//void ApplicationWindow::showSupportPage()
+//{
+//	QDesktopServices::openUrl(QUrl("http://soft.proindependent.com/contracts.html"));
+//}
+
+
+//void ApplicationWindow::showDonationsPage()
+//{
+//	QDesktopServices::openUrl(QUrl("http://soft.proindependent.com/why_donate.html"));
+//}
+
+//void ApplicationWindow::downloadManual()
+//{
+//	QDesktopServices::openUrl(QUrl("http://soft.proindependent.com/manuals.html"));
+//}
+//
+//void ApplicationWindow::downloadTranslation()
+//{
+//	QDesktopServices::openUrl(QUrl("http://soft.proindependent.com/translations.html"));
+//}
+
+void ApplicationWindow::showHomePage()
+{
+  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org"));
+}
+void ApplicationWindow::showMantidConcepts()
+{
+  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Category:Concepts"));
+}
+void ApplicationWindow::showalgorithmDescriptions()
+{
+  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Category:Algorithms"));
+}
+/*
+ Show mantidplot help page
+ */
+void ApplicationWindow::showmantidplotHelp()
+{
+  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/MantidPlot:_Help"));
+}
+
+//
+//void ApplicationWindow::showForums()
+//{
+//	QDesktopServices::openUrl(QUrl("https://developer.berlios.de/forum/?group_id=6626"));
+//}
+
+void ApplicationWindow::showBugTracker()
+{
+  QDesktopServices::openUrl(QUrl("mailto:mantid-help@mantidproject.org"));
+}
+
+void ApplicationWindow::parseCommandLineArguments(const QStringList& args)
+{
+  int num_args = args.count();
+  if(num_args == 0){
+    initWindow();
+    savedProject();
+    return;
+  }
+
+  QString str;
+  bool exec = false;
+  bool quit = false;
+  bool default_settings = false;
+  foreach(str, args){
+    if( (str == "-a" || str == "--about") ||
+        (str == "-m" || str == "--manual") )
+    {
+      QMessageBox::critical(this, tr("MantidPlot - Error"),//Mantid
+          tr("<b> %1 </b>: This command line option must be used without other arguments!").arg(str));
+    }
+    else if( (str == "-d" || str == "--default-settings"))
+    {
+      default_settings = true;
+    }
+    else if (str == "-v" || str == "--version")
+    {
+#ifdef Q_OS_WIN
+      hide();
+      about();
+#else
+      std::wcout << versionString().toStdWString();
+#endif
+      exit(0);
+    }
+    else if (str == "-r" || str == "--revision") // Print and return subversion revision number
+    {
+      hide();
+      QString version(MANTIDPLOT_RELEASE_VERSION);
+      version.remove(0,4);
+      std::cout << version.toStdString() << std::endl;
+      exit(version.toInt());
+    }
+    else if (str == "-h" || str == "--help")
+    {
+      QString s = "\n" + tr("Usage") + ": ";
+      s += "qtiplot [" + tr("options") + "] [" + tr("file") + "_" + tr("name") + "]\n\n";
+      s += tr("Valid options are") + ":\n";
+      s += "-a " + tr("or") + " --about: " + tr("show about dialog and exit") + "\n";
+      s += "-d " + tr("or") + " --default-settings: " + tr("start MantidPlot with the default settings") + "\n";//Mantid
+      s += "-h " + tr("or") + " --help: " + tr("show command line options") + "\n";
+      s += "-l=XX " + tr("or") + " --lang=XX: " + tr("start MantidPlot in language") + " XX ('en', 'fr', 'de', ...)\n";//Mantid
+      s += "-m " + tr("or") + " --manual: " + tr("show MantidPlot manual in a standalone window") + "\n";
+      s += "-v " + tr("or") + " --version: " + tr("print MantidPlot version and release date") + "\n";
+      s += "-x " + tr("or") + " --execute: " + tr("execute the script file given as argument") + "\n\n";
+      s += "'" + tr("file") + "_" + tr("name") + "' " + tr("can be any .qti, qti.gz, .opj, .ogm, .ogw, .ogg, .py or ASCII file") + "\n";
+#ifdef Q_OS_WIN
+      hide();
+      QMessageBox::information(this, tr("MantidPlot") + " - " + tr("Help"), s);//Mantid
+#else
+      std::wcout << s.toStdWString();
+#endif
+      exit(0);
+    }
+    else if (str.startsWith("--lang=") || str.startsWith("-l="))
+    {
+      QString locale = str.mid(str.find('=')+1);
+      if (locales.contains(locale))
+        switchToLanguage(locale);
+
+      if (!locales.contains(locale))
+        QMessageBox::critical(this, tr("MantidPlot - Error"),//Mantid
+            tr("<b> %1 </b>: Wrong locale option or no translation available!").arg(locale));
+    }
+    else if (str.endsWith("--execute") || str.endsWith("-x"))
+    {
+      exec = true;
+      quit = false;
+    }
+    else if (str.endsWith("--execandquit") || str.endsWith("-xq"))
+    {
+      exec = true;
+      quit = true;
+    }
+    else if (str.startsWith("-") || str.startsWith("--"))
+    {
+      QMessageBox::critical(this, tr("MantidPlot - Error"),//Mantid
+          tr("<b> %1 </b> unknown command line option!").arg(str) + "\n" + tr("Type %1 to see the list of the valid options.").arg("'MantidPlot -h'"));
+    }
+  }
+
+  QString file_name = args[num_args-1]; // last argument
+  if(file_name.startsWith("-")){// no file name given
+    initWindow();
+    savedProject();
+    return;
+  }
+
+  if (!file_name.isEmpty()){
+    QFileInfo fi(file_name);
+    if (fi.isDir()){
+      QMessageBox::critical(this, tr("MantidPlot - Error opening file"),//Mantid
+          tr("<b>%1</b> is a directory, please specify a file name!").arg(file_name));
+      return;
+    } else if (!fi.exists()) {
+      QMessageBox::critical(this, tr("MantidPlot - Error opening file"),//Mantid
+          tr("The file: <b>%1</b> doesn't exist!").arg(file_name));
+      return;
+    } else if (!fi.isReadable()) {
+      QMessageBox::critical(this, tr("MantidPlot - Error opening file"),//Mantid
+          tr("You don't have the permission to open this file: <b>%1</b>").arg(file_name));
+      return;
+    }
+
+    workingDir = fi.dirPath(true);
+    saveSettings();//the recent projects must be saved
+
+    if (exec)
+      loadScript(file_name, exec, quit);
+    else
+    {
+      saved=true;
+      open(file_name, default_settings, false);
+    }
+  }
+}
+
+void ApplicationWindow::createLanguagesList()
+{
+  locales.clear();
+
+  appTranslator = new QTranslator(this);
+  qtTranslator = new QTranslator(this);
+  qApp->installTranslator(appTranslator);
+  qApp->installTranslator(qtTranslator);
+
+  QString qmPath = d_translations_folder;
+  QDir dir(qmPath);
+  QStringList fileNames = dir.entryList("qtiplot_*.qm");
+  for (int i=0; i < (int)fileNames.size(); i++)
+  {
+    QString locale = fileNames[i];
+    locale = locale.mid(locale.find('_')+1);
+    locale.truncate(locale.find('.'));
+    locales.push_back(locale);
+  }
+  locales.push_back("en");
+  locales.sort();
+
+  if (appLanguage != "en")
+  {
+    appTranslator->load("qtiplot_" + appLanguage, qmPath);
+    qtTranslator->load("qt_" + appLanguage, qmPath+"/qt");
+  }
+}
+
+void ApplicationWindow::switchToLanguage(int param)
+{
+  if (param < (int)locales.size())
+    switchToLanguage(locales[param]);
+}
+
+void ApplicationWindow::switchToLanguage(const QString& locale)
+{
+  if (!locales.contains(locale) || appLanguage == locale)
+    return;
+
+  appLanguage = locale;
+  if (locale == "en")
+  {
+    qApp->removeTranslator(appTranslator);
+    qApp->removeTranslator(qtTranslator);
+    delete appTranslator;
+    delete qtTranslator;
+    appTranslator = new QTranslator(this);
+    qtTranslator = new QTranslator(this);
+    qApp->installTranslator(appTranslator);
+    qApp->installTranslator(qtTranslator);
+  }
+  else
+  {
+    QString qmPath = d_translations_folder;
+    appTranslator->load("qtiplot_" + locale, qmPath);
+    qtTranslator->load("qt_" + locale, qmPath+"/qt");
+  }
+  insertTranslatedStrings();
+}
+
+QStringList ApplicationWindow::matrixNames()
+{
+  QStringList names;
+  Folder *f = projectFolder();
+  while (f){
+    QList<MdiSubWindow *> folderWindows = f->windowsList();
+    foreach(MdiSubWindow *w, folderWindows){
+      if (w->isA("Matrix"))
+        names << w->objectName();
+    }
+    f = f->folderBelow();
+  }
+  return names;
+}
+QStringList ApplicationWindow::mantidmatrixNames()
+{
+  QStringList names;
+  Folder *f = projectFolder();
+  while (f){
+    QList<MdiSubWindow *> folderWindows = f->windowsList();
+    foreach(MdiSubWindow *w, folderWindows){
+      if (w->isA("MantidMatrix"))
+        names << w->objectName();
+    }
+    f = f->folderBelow();
+  }
+  return names;
+}
+
+bool ApplicationWindow::alreadyUsedName(const QString& label)
+{
+  Folder *f = projectFolder();
+  while (f){
+    QList<MdiSubWindow *> folderWindows = f->windowsList();
+    foreach(MdiSubWindow *w, folderWindows){
+      if (w->objectName() == label)
+        return true;
+    }
+    f = f->folderBelow();
+  }
+  return false;
+}
+
+bool ApplicationWindow::projectHas2DPlots()
+{
+  Folder *f = projectFolder();
+  while (f){
+    QList<MdiSubWindow *> folderWindows = f->windowsList();
+    foreach(MdiSubWindow *w, folderWindows){
+      if (w->isA("MultiLayer"))
+        return true;
+    }
+    f = f->folderBelow();
+  }
+  return false;
+}
+
+void ApplicationWindow::appendProject()
+{
+  OpenProjectDialog *open_dialog = new OpenProjectDialog(this, false);
+  open_dialog->setDirectory(workingDir);
+  open_dialog->setExtensionWidget(0);
+  if (open_dialog->exec() != QDialog::Accepted || open_dialog->selectedFiles().isEmpty())
+    return;
+  workingDir = open_dialog->directory().path();
+  appendProject(open_dialog->selectedFiles()[0]);
+}
+
+Folder* ApplicationWindow::appendProject(const QString& fn, Folder* parentFolder)
+{
+  if (fn.isEmpty())
+    return 0;
+
+  QFileInfo fi(fn);
+  workingDir = fi.dirPath(true);
+
+  if (fn.contains(".qti") || fn.contains(".opj", Qt::CaseInsensitive) ||
+      fn.contains(".ogm", Qt::CaseInsensitive) || fn.contains(".ogw", Qt::CaseInsensitive) ||
+      fn.contains(".ogg", Qt::CaseInsensitive)){
+    QFileInfo f(fn);
+    if (!f.exists ()){
+      QMessageBox::critical(this, tr("MantidPlot - File opening error"),//Mantid
+          tr("The file: <b>%1</b> doesn't exist!").arg(fn));
+      return 0;
+    }
+  }else{
+    QMessageBox::critical(this,tr("MantidPlot - File opening error"),//Mantid
+        tr("The file: <b>%1</b> is not a MantidPlot or Origin project file!").arg(fn));
+    return 0;
+  }
+
+  recentProjects.remove(fn);
+  recentProjects.push_front(fn);
+  updateRecentProjectsList();
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  QString fname = fn;
+  if (fn.contains(".qti.gz")){//decompress using zlib
+    file_uncompress((char *)fname.ascii());
+    fname.remove(".gz");
+  }
+
+  Folder *cf = current_folder;
+  if (parentFolder)
+    changeFolder(parentFolder, true);
+
+  FolderListItem *item = (FolderListItem *)current_folder->folderListItem();
+  folders->blockSignals (true);
+  blockSignals (true);
+
+  QString baseName = fi.baseName();
+  QStringList lst = current_folder->subfolders();
+  int n = lst.count(baseName);
+  if (n){//avoid identical subfolder names
+    while (lst.count(baseName + QString::number(n)))
+      n++;
+    baseName += QString::number(n);
+  }
+
+  Folder *new_folder;
+  if (parentFolder)
+    new_folder = new Folder(parentFolder, baseName);
+  else
+    new_folder = new Folder(current_folder, baseName);
+
+  current_folder = new_folder;
+  FolderListItem *fli = new FolderListItem(item, current_folder);
+  current_folder->setFolderListItem(fli);
+
+  if (fn.contains(".opj", Qt::CaseInsensitive) || fn.contains(".ogm", Qt::CaseInsensitive) ||
+      fn.contains(".ogw", Qt::CaseInsensitive) || fn.contains(".ogg", Qt::CaseInsensitive))
+    ImportOPJ(this, fn);
+  else{
+    QFile f(fname);
+    QTextStream t( &f );
+    t.setEncoding(QTextStream::UnicodeUTF8);
+    f.open(QIODevice::ReadOnly);
+
+    QString s = t.readLine();
+    lst = s.split(QRegExp("\\s"), QString::SkipEmptyParts);
+    QString version = lst[1];
+    lst = version.split(".", QString::SkipEmptyParts);
+    d_file_version =100*(lst[0]).toInt()+10*(lst[1]).toInt()+(lst[2]).toInt();
+
+    t.readLine();
+    if (d_file_version < 73)
+      t.readLine();
+
+    //process tables and matrix information
+    while ( !t.atEnd()){
+      s = t.readLine();
+      lst.clear();
+      if  (s.left(8) == "<folder>"){
+        lst = s.split("\t");
+        Folder *f = new Folder(current_folder, lst[1]);
+        f->setBirthDate(lst[2]);
+        f->setModificationDate(lst[3]);
+        if(lst.count() > 4)
+          if (lst[4] == "current")
+            cf = f;
+
+        FolderListItem *fli = new FolderListItem(current_folder->folderListItem(), f);
+        fli->setText(0, lst[1]);
+        f->setFolderListItem(fli);
+
+        current_folder = f;
+      }else if  (s == "<table>"){
+        while ( s!="</table>" ){
+          s=t.readLine();
+          lst<<s;
+        }
+        lst.pop_back();
+        openTable(this,lst);
+      }else if  (s == "<matrix>"){
+        while ( s != "</matrix>" ){
+          s=t.readLine();
+          lst<<s;
+        }
+        lst.pop_back();
+        openMatrix(this, lst);
+      }else if  (s == "<note>"){
+        for (int i=0; i<3; i++){
+          s = t.readLine();
+          lst << s;
+        }
+        Note* m = openNote(this, lst);
+        QStringList cont;
+        while ( s != "</note>" ){
+          s=t.readLine();
+          cont << s;
+        }
+        cont.pop_back();
+        m->restore(cont);
+      }else if  (s == "</folder>"){
+        Folder *parent = (Folder *)current_folder->parent();
+        if (!parent)
+          current_folder = projectFolder();
+        else
+          current_folder = parent;
+      }
+    }
+    f.close();
+
+    //process the rest
+    f.open(QIODevice::ReadOnly);
+
+    MultiLayer *plot=0;
+    while ( !t.atEnd()){
+      s=t.readLine();
+      if  (s.left(8) == "<folder>"){
+        lst = s.split("\t");
+        current_folder = current_folder->findSubfolder(lst[1]);
+      }else if  (s == "<multiLayer>"){//process multilayers information
+        s=t.readLine();
+        QStringList graph=s.split("\t");
+        QString caption=graph[0];
+        plot = multilayerPlot(caption, 0, graph[2].toInt(), graph[1].toInt());
+        setListViewDate(caption, graph[3]);
+        plot->setBirthDate(graph[3]);
+        plot->blockSignals(true);
+
+        restoreWindowGeometry(this, plot, t.readLine());
+
+        if (d_file_version > 71){
+          QStringList lst=t.readLine().split("\t");
+          plot->setWindowLabel(lst[1]);
+          plot->setCaptionPolicy((MdiSubWindow::CaptionPolicy)lst[2].toInt());
+        }
+
+        if (d_file_version > 83){
+          QStringList lst=t.readLine().split("\t", QString::SkipEmptyParts);
+          plot->setMargins(lst[1].toInt(),lst[2].toInt(),lst[3].toInt(),lst[4].toInt());
+          lst=t.readLine().split("\t", QString::SkipEmptyParts);
+          plot->setSpacing(lst[1].toInt(),lst[2].toInt());
+          lst=t.readLine().split("\t", QString::SkipEmptyParts);
+          plot->setLayerCanvasSize(lst[1].toInt(),lst[2].toInt());
+          lst=t.readLine().split("\t", QString::SkipEmptyParts);
+          plot->setAlignement(lst[1].toInt(),lst[2].toInt());
+        }
+
+        while ( s!="</multiLayer>" ){//open layers
+          s=t.readLine();
+          if (s.left(7)=="<graph>"){
+            lst.clear();
+            while ( s!="</graph>" ){
+              s=t.readLine();
+              lst<<s;
+            }
+            openGraph(this, plot, lst);
+          }
+        }
+        if(plot)
+        { plot->blockSignals(false);
+        }
+      }else if  (s == "<SurfacePlot>"){//process 3D plots information
+        lst.clear();
+        while ( s!="</SurfacePlot>" ){
+          s=t.readLine();
+          lst<<s;
+        }
+        openSurfacePlot(this,lst);
+      }else if  (s == "</folder>"){
+        Folder *parent = (Folder *)current_folder->parent();
+        if (!parent)
+          current_folder = projectFolder();
+        else
+          current_folder = parent;
+      }
+    }
+    f.close();
+  }
+
+  folders->blockSignals (false);
+  //change folder to user defined current folder
+  changeFolder(cf);
+  blockSignals (false);
+  renamedTables = QStringList();
+  QApplication::restoreOverrideCursor();
+  return new_folder;
+}
+
+#ifdef QTIPLOT_DEMO
+void ApplicationWindow::showDemoVersionMessage()
+{
+  saved = true;
+  /**
+	QMessageBox::critical(this, tr("MantidPlot - Demo Version"),//Mantid
+			tr("You are using the demonstration version of Qtiplot.\
+				It is identical with the full version, except that you can't save your work to project files and you can't use it for more than 10 minutes per session.\
+				<br><br>\
+				If you want to have ready-to-use, fully functional binaries, please subscribe for a\
+				<a href=\"http://soft.proindependent.com/individual_contract.html\">single-user binaries maintenance contract</a>.\
+				<br><br>\
+				QtiPlot is free software in the sense of free speech.\
+				If you know how to use it, you can get\
+				<a href=\"http://developer.berlios.de/project/showfiles.php?group_id=6626\">the source code</a>\
+				free of charge.\
+				Nevertheless, you are welcome to\
+				<a href=\"http://soft.proindependent.com/why_donate.html\">make a donation</a>\
+				in order to support the further development of QtiPlot."));
+   */
+}
+#endif
+
+void ApplicationWindow::saveFolder(Folder *folder, const QString& fn, bool compress)
+{
+  QFile f( fn );
+  if (d_backup_files && f.exists())
+  {// make byte-copy of current file so that there's always a copy of the data on disk
+    while (!f.open(QIODevice::ReadOnly)){
+      if (f.isOpen())
+        f.close();
+      int choice = QMessageBox::warning(this, tr("MantidPlot - File backup error"),//Mantid
+          tr("Cannot make a backup copy of <b>%1</b> (to %2).<br>If you ignore this, you run the risk of <b>data loss</b>.").arg(projectname).arg(projectname+"~"),
+          QMessageBox::Retry|QMessageBox::Default, QMessageBox::Abort|QMessageBox::Escape, QMessageBox::Ignore);
+      if (choice == QMessageBox::Abort)
+        return;
+      if (choice == QMessageBox::Ignore)
+        break;
+    }
+
+    if (f.isOpen()){
+      QFile::copy (fn, fn + "~");
+      f.close();
+    }
+  }
+
+  if ( !f.open( QIODevice::WriteOnly ) ){
+    QMessageBox::about(this, tr("MantidPlot - File save error"), tr("The file: <br><b>%1</b> is opened in read-only mode").arg(fn));//Mantid
+    return;
+  }
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  QList<MdiSubWindow *> lst = folder->windowsList();
+  int windows = 0;
+  QString text;
+  //save all loaded mantid workspace names to project file
+  // call save nexus on each workspace
+  QString aux=mantidUI->saveToString(workingDir.toStdString());
+  text+=aux;
+  //if script window is open save the currently opened script file names to project file
+  if (scriptingWindow)
+  {	//returns the files names of the all the opened script files.
+    QString aux=scriptingWindow->saveToString();
+    text+=aux;
+  }
+  foreach(MdiSubWindow *w, lst){
+    QString aux = w->saveToString(windowGeometryInfo(w));
+    if (w->inherits("Table"))
+      ((Table *)w)->setSpecifications(aux);
+    text += aux;
+    windows++;
+  }
+  int initial_depth = folder->depth();
+  Folder *dir = folder->folderBelow();
+  while (dir && dir->depth() > initial_depth){
+    text += "<folder>\t" + QString(dir->objectName()) + "\t" + dir->birthDate() + "\t" + dir->modificationDate();
+    if (dir == current_folder)
+      text += "\tcurrent\n";
+    else
+      text += "\n";  // FIXME: Having no 5th string here is not a good idea
+    text += "<open>" + QString::number(dir->folderListItem()->isOpen()) + "</open>\n";
+
+    lst = dir->windowsList();
+    foreach(MdiSubWindow *w, lst){
+      QString aux = w->saveToString(windowGeometryInfo(w));
+      if (w->inherits("Table"))
+        ((Table *)w)->setSpecifications(aux);
+      text += aux;
+      windows++;
+    }
+
+    if (!dir->logInfo().isEmpty() )
+      text += "<log>\n" + dir->logInfo() + "</log>\n" ;
+
+    if ( (dir->children()).isEmpty() )
+      text += "</folder>\n";
+
+    int depth = dir->depth();
+    dir = dir->folderBelow();
+    if (dir){
+      int next_dir_depth = dir->depth();
+      if (next_dir_depth < depth){
+        int diff = depth - next_dir_depth;
+        for (int i = 0; i < diff; i++)
+          text += "</folder>\n";
+      }
+    } else {
+      int diff = depth - initial_depth - 1;
+      for (int i = 0; i < diff; i++)
+        text += "</folder>\n";
+    }
+  }
+
+  text += "<open>" + QString::number(folder->folderListItem()->isOpen()) + "</open>\n";
+  if (!folder->logInfo().isEmpty())
+    text += "<log>\n" + folder->logInfo() + "</log>" ;
+
+  text.prepend("<windows>\t"+QString::number(windows)+"\n");
+  text.prepend("<scripting-lang>\t"+QString(scriptingEnv()->name())+"\n");
+  text.prepend("MantidPlot " + QString::number(maj_version)+"."+ QString::number(min_version)+"."+
+      QString::number(patch_version)+" project file\n");
+
+  QTextStream t( &f );
+  t.setEncoding(QTextStream::UnicodeUTF8);
+  t << text;
+  f.close();
+
+  if (compress)
+  {
+    char w9[]="w9";
+    file_compress((char *)fn.ascii(), "w9");
+  }
+
+  QApplication::restoreOverrideCursor();
+}
+
+void ApplicationWindow::saveAsProject()
+{
+  saveFolderAsProject(current_folder);
+}
+
+void ApplicationWindow::saveFolderAsProject(Folder *f)
+{
+#ifdef QTIPLOT_DEMO
+  showDemoVersionMessage();
+  return;
+#endif
+  QString filter = tr("MantidPlot project")+" (*.qti);;";//Mantid
+  filter += tr("Compressed MantidPlot project")+" (*.qti.gz)";
+
+  QString selectedFilter;
+  QString fn = QFileDialog::getSaveFileName(this, tr("Save project as"), workingDir, filter, &selectedFilter);
+  if ( !fn.isEmpty() ){
+    QFileInfo fi(fn);
+    workingDir = fi.dirPath(true);
+    QString baseName = fi.fileName();
+    if (!baseName.contains("."))
+      fn.append(".qti");
+
+    saveFolder(f, fn, selectedFilter.contains(".gz"));
+  }
+}
+
+void ApplicationWindow::showFolderPopupMenu(Q3ListViewItem *it, const QPoint &p, int)
+{
+  showFolderPopupMenu(it, p, true);
+}
+
+void ApplicationWindow::showFolderPopupMenu(Q3ListViewItem *it, const QPoint &p, bool fromFolders)
+{
+  if (!it || folders->isRenaming())
+    return;
+
+  QMenu cm(this);
+  QMenu window(this);
+  QMenu viewWindowsMenu(this);
+  viewWindowsMenu.setCheckable ( true );
+
+  cm.insertItem(tr("&Find..."), this, SLOT(showFindDialogue()));
+  cm.insertSeparator();
+  cm.insertItem(tr("App&end Project..."), this, SLOT(appendProject()));
+  if (((FolderListItem *)it)->folder()->parent())
+    cm.insertItem(tr("Save &As Project..."), this, SLOT(saveAsProject()));
+  else
+    cm.insertItem(tr("Save Project &As..."), this, SLOT(saveProjectAs()));
+  cm.insertSeparator();
+
+  if (fromFolders && show_windows_policy != HideAll)
+  {
+    cm.insertItem(tr("&Show All Windows"), this, SLOT(showAllFolderWindows()));
+    cm.insertItem(tr("&Hide All Windows"), this, SLOT(hideAllFolderWindows()));
+    cm.insertSeparator();
+  }
+
+  if (((FolderListItem *)it)->folder()->parent())
+  {
+    cm.insertItem(getQPixmap("close_xpm"), tr("&Delete Folder"), this, SLOT(deleteFolder()), Qt::Key_F8);
+    cm.insertItem(tr("&Rename"), this, SLOT(startRenameFolder()), Qt::Key_F2);
+    cm.insertSeparator();
+  }
+
+  if (fromFolders)
+  {
+    window.addAction(actionNewTable);
+    window.addAction(actionNewMatrix);
+    window.addAction(actionNewNote);
+    window.addAction(actionNewGraph);
+    window.addAction(actionNewFunctionPlot);
+    window.addAction(actionNewSurfacePlot);
+    cm.insertItem(tr("New &Window"), &window);
+  }
+
+  cm.insertItem(getQPixmap("newfolder_xpm"), tr("New F&older"), this, SLOT(addFolder()), Qt::Key_F7);
+  cm.insertSeparator();
+
+  QStringList lst;
+  lst << tr("&None") << tr("&Windows in Active Folder") << tr("Windows in &Active Folder && Subfolders");
+  for (int i = 0; i < 3; ++i)
+  {
+    int id = viewWindowsMenu.insertItem(lst[i],this, SLOT( setShowWindowsPolicy( int ) ) );
+    viewWindowsMenu.setItemParameter( id, i );
+    viewWindowsMenu.setItemChecked( id, show_windows_policy == i );
+  }
+  cm.insertItem(tr("&View Windows"), &viewWindowsMenu);
+  cm.insertSeparator();
+  cm.insertItem(tr("&Properties..."), this, SLOT(folderProperties()));
+  cm.exec(p);
+}
+
+void ApplicationWindow::setShowWindowsPolicy(int p)
+{
+  if (show_windows_policy == (ShowWindowsPolicy)p)
+    return;
+
+  show_windows_policy = (ShowWindowsPolicy)p;
+  if (show_windows_policy == HideAll){
+    QList<MdiSubWindow *> windows = windowsList();
+    foreach(MdiSubWindow *w, windows){
+      hiddenWindows->append(w);
+      w->hide();
+      setListView(w->objectName(), tr("Hidden"));
+    }
+  } else
+    showAllFolderWindows();
+}
+
+void ApplicationWindow::showFindDialogue()
+{
+  FindDialog *fd = new FindDialog(this);
+  fd->setAttribute(Qt::WA_DeleteOnClose);
+  fd->exec();
+}
+
+void ApplicationWindow::startRenameFolder()
+{
+  FolderListItem *fi = current_folder->folderListItem();
+  if (!fi)
+    return;
+
+  disconnect(folders, SIGNAL(currentChanged(Q3ListViewItem *)), this, SLOT(folderItemChanged(Q3ListViewItem *)));
+  fi->setRenameEnabled (0, true);
+  fi->startRename (0);
+}
+
+void ApplicationWindow::startRenameFolder(Q3ListViewItem *item)
+{
+  if (!item || item == folders->firstChild())
+    return;
+
+  if (item->listView() == lv && item->rtti() == FolderListItem::RTTI) {
+    disconnect(folders, SIGNAL(currentChanged(Q3ListViewItem *)), this, SLOT(folderItemChanged(Q3ListViewItem *)));
+    current_folder = ((FolderListItem *)item)->folder();
+    FolderListItem *it = current_folder->folderListItem();
+    it->setRenameEnabled (0, true);
+    it->startRename (0);
+  } else {
+    item->setRenameEnabled (0, true);
+    item->startRename (0);
+  }
+}
+
+void ApplicationWindow::renameFolder(Q3ListViewItem *it, int col, const QString &text)
+{
+  Q_UNUSED(col)
+
+		    if (!it)
+		      return;
+
+  Folder *parent = (Folder *)current_folder->parent();
+  if (!parent)//the parent folder is the project folder (it always exists)
+    parent = projectFolder();
+
+  while(text.isEmpty())
+  {
+    QMessageBox::critical(this,tr("MantidPlot - Error"), tr("Please enter a valid name!"));//Mantid
+    it->setRenameEnabled (0, true);
+    it->startRename (0);
+    return;
+  }
+
+  QStringList lst = parent->subfolders();
+  lst.remove(current_folder->objectName());
+  while(lst.contains(text)){
+    QMessageBox::critical(this,tr("MantidPlot - Error"),//Mantid
+        tr("Name already exists!")+"\n"+tr("Please choose another name!"));
+
+    it->setRenameEnabled (0, true);
+    it->startRename (0);
+    return;
+  }
+
+  current_folder->setObjectName(text);
+  it->setRenameEnabled (0, false);
+  connect(folders, SIGNAL(currentChanged(Q3ListViewItem *)),
+      this, SLOT(folderItemChanged(Q3ListViewItem *)));
+  folders->setCurrentItem(parent->folderListItem());//update the list views
+}
+
+void ApplicationWindow::showAllFolderWindows()
+{
+  QList<MdiSubWindow *> lst = current_folder->windowsList();
+  foreach(MdiSubWindow *w, lst)
+  {//force show all windows in current folder
+    if (w)
+    {
+      updateWindowLists(w);
+      switch (w->status())
+      {
+      case MdiSubWindow::Hidden:
+        w->showNormal();
+        break;
+
+      case MdiSubWindow::Normal:
+        w->showNormal();
+        break;
+
+      case MdiSubWindow::Minimized:
+        w->showMinimized();
+        break;
+
+      case MdiSubWindow::Maximized:
+        w->showMaximized();
+        break;
+      }
+    }
+  }
+
+  if ( (current_folder->children()).isEmpty() )
+    return;
+
+  FolderListItem *fi = current_folder->folderListItem();
+  FolderListItem *item = (FolderListItem *)fi->firstChild();
+  int initial_depth = item->depth();
+  while (item && item->depth() >= initial_depth)
+  {// show/hide windows in all subfolders
+    lst = ((Folder *)item->folder())->windowsList();
+    foreach(MdiSubWindow *w, lst){
+      if (w && show_windows_policy == SubFolders){
+        updateWindowLists(w);
+        switch (w->status())
+        {
+        case MdiSubWindow::Hidden:
+          w->showNormal();
+          break;
+
+        case MdiSubWindow::Normal:
+          w->showNormal();
+          break;
+
+        case MdiSubWindow::Minimized:
+          w->showMinimized();
+          break;
+
+        case MdiSubWindow::Maximized:
+          w->showMaximized();
+          break;
+        }
+      }
+      else
+        w->hide();
+    }
+
+    item = (FolderListItem *)item->itemBelow();
+  }
+}
+
+void ApplicationWindow::hideAllFolderWindows()
+{
+  QList<MdiSubWindow *> lst = current_folder->windowsList();
+  foreach(MdiSubWindow *w, lst)
+  hideWindow(w);
+
+  if ( (current_folder->children()).isEmpty() )
+    return;
+
+  if (show_windows_policy == SubFolders)
+  {
+    FolderListItem *fi = current_folder->folderListItem();
+    FolderListItem *item = (FolderListItem *)fi->firstChild();
+    int initial_depth = item->depth();
+    while (item && item->depth() >= initial_depth)
+    {
+      lst = item->folder()->windowsList();
+      foreach(MdiSubWindow *w, lst)
+      hideWindow(w);
+
+      item = (FolderListItem *)item->itemBelow();
+    }
+  }
+}
+
+void ApplicationWindow::projectProperties()
+{
+  QString s = QString(current_folder->objectName()) + "\n\n";
+  s += "\n\n\n";
+  s += tr("Type") + ": " + tr("Project")+"\n\n";
+  if (projectname != "untitled")
+  {
+    s += tr("Path") + ": " + projectname + "\n\n";
+
+    QFileInfo fi(projectname);
+    s += tr("Size") + ": " + QString::number(fi.size()) + " " + tr("bytes")+ "\n\n";
+  }
+
+  s += tr("Contents") + ": " + QString::number(windowsList().size()) + " " + tr("windows");
+  s += ", " + QString::number(current_folder->subfolders().count()) + " " + tr("folders") + "\n\n";
+  s += "\n\n\n";
+
+  if (projectname != "untitled")
+  {
+    QFileInfo fi(projectname);
+    s += tr("Created") + ": " + fi.created().toString(Qt::LocalDate) + "\n\n";
+    s += tr("Modified") + ": " + fi.lastModified().toString(Qt::LocalDate) + "\n\n";
+  }
+  else
+    s += tr("Created") + ": " + current_folder->birthDate() + "\n\n";
+
+  QMessageBox *mbox = new QMessageBox ( tr("Properties"), s, QMessageBox::NoIcon,
+      QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton, this);
+
+  //mbox->setIconPixmap(QPixmap( qtiplot_logo_xpm ));
+  mbox->show();
+}
+
+void ApplicationWindow::folderProperties()
+{
+  if (!current_folder->parent())
+  {
+    projectProperties();
+    return;
+  }
+
+  QString s = QString(current_folder->objectName()) + "\n\n";
+  s += "\n\n\n";
+  s += tr("Type") + ": " + tr("Folder")+"\n\n";
+  s += tr("Path") + ": " + current_folder->path() + "\n\n";
+  s += tr("Size") + ": " + current_folder->sizeToString() + "\n\n";
+  s += tr("Contents") + ": " + QString::number(current_folder->windowsList().count()) + " " + tr("windows");
+  s += ", " + QString::number(current_folder->subfolders().count()) + " " + tr("folders") + "\n\n";
+  //s += "\n\n\n";
+  s += tr("Created") + ": " + current_folder->birthDate() + "\n\n";
+  //s += tr("Modified") + ": " + current_folder->modificationDate() + "\n\n";
+
+  QMessageBox *mbox = new QMessageBox ( tr("Properties"), s, QMessageBox::NoIcon,
+      QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton, this);
+
+  mbox->setIconPixmap(getQPixmap("folder_open_xpm"));
+  mbox->show();
+}
+
+void ApplicationWindow::addFolder()
+{
+  if (!explorerWindow->isVisible())
+    explorerWindow->show();
+
+  QStringList lst = current_folder->subfolders();
+  QString name =  tr("New Folder");
+  lst = lst.grep( name );
+  if (!lst.isEmpty())
+    name += " ("+ QString::number(lst.size()+1)+")";
+
+  Folder *f = new Folder(current_folder, name);
+  addFolderListViewItem(f);
+
+  FolderListItem *fi = new FolderListItem(current_folder->folderListItem(), f);
+  if (fi){
+    f->setFolderListItem(fi);
+    fi->setRenameEnabled (0, true);
+    fi->startRename(0);
+  }
+}
+
+Folder* ApplicationWindow::addFolder(QString name, Folder* parent)
+{
+  if(!parent){
+    if (current_folder)
+      parent = current_folder;
+    else
+      parent = projectFolder();
+  }
+
+  QStringList lst = parent->subfolders();
+  lst = lst.grep( name );
+  if (!lst.isEmpty())
+    name += " ("+ QString::number(lst.size()+1)+")";
+
+  Folder *f = new Folder(parent, name);
+  addFolderListViewItem(f);
+
+  FolderListItem *fi = new FolderListItem(parent->folderListItem(), f);
+  if (fi)
+    f->setFolderListItem(fi);
+
+  return f;
+}
+
+bool ApplicationWindow::deleteFolder(Folder *f)
+{
+  if (!f)
+    return false;
+
+  if (confirmCloseFolder && QMessageBox::information(this, tr("MantidPlot - Delete folder?"),//Mantid
+      tr("Delete folder '%1' and all the windows it contains?").arg(f->objectName()),
+      tr("Yes"), tr("No"), 0, 0))
+    return false;
+  else {
+    Folder *parent = projectFolder();
+    if (current_folder){
+      if (current_folder->parent())
+        parent = (Folder *)current_folder->parent();
+    }
+
+    folders->blockSignals(true);
+
+    FolderListItem *fi = f->folderListItem();
+    foreach(MdiSubWindow *w, f->windowsList())
+    closeWindow(w);
+
+    if (!(f->children()).isEmpty()){
+      Folder *subFolder = f->folderBelow();
+      int initial_depth = f->depth();
+      while (subFolder && subFolder->depth() > initial_depth){
+        foreach(MdiSubWindow *w, subFolder->windowsList()){
+          removeWindowFromLists(w);
+          subFolder->removeWindow(w);
+          delete w;
+        }
+        delete subFolder->folderListItem();
+        delete subFolder;
+
+        subFolder = f->folderBelow();
+      }
+    }
+
+    delete f;
+    delete fi;
+
+    current_folder = parent;
+    folders->setCurrentItem(parent->folderListItem());
+    changeFolder(parent, true);
+    folders->blockSignals(false);
+    folders->setFocus();
+    return true;
+  }
+}
+
+void ApplicationWindow::deleteFolder()
+{
+  Folder *parent = (Folder *)current_folder->parent();
+  if (!parent)
+    parent = projectFolder();
+
+  folders->blockSignals(true);
+
+  if (deleteFolder(current_folder)){
+    current_folder = parent;
+    folders->setCurrentItem(parent->folderListItem());
+    changeFolder(parent, true);
+  }
+
+  folders->blockSignals(false);
+  folders->setFocus();
+}
+
+void ApplicationWindow::folderItemDoubleClicked(Q3ListViewItem *it)
+{
+  if (!it || it->rtti() != FolderListItem::RTTI)
+    return;
+
+  FolderListItem *item = ((FolderListItem *)it)->folder()->folderListItem();
+  folders->setCurrentItem(item);
+}
+
+void ApplicationWindow::folderItemChanged(Q3ListViewItem *it)
+{
+  if (!it)
+    return;
+
+  it->setOpen(true);
+  changeFolder (((FolderListItem *)it)->folder());
+  folders->setFocus();
+}
+
+void ApplicationWindow::hideFolderWindows(Folder *f)
+{
+  QList<MdiSubWindow *> lst = f->windowsList();
+  foreach(MdiSubWindow *w, lst)
+  w->hide();
+
+  if ((f->children()).isEmpty())
+    return;
+
+  Folder *dir = f->folderBelow();
+  int initial_depth = f->depth();
+  while (dir && dir->depth() > initial_depth){
+    lst = dir->windowsList();
+    foreach(MdiSubWindow *w, lst)
+    w->hide();
+
+    dir = dir->folderBelow();
+  }
+}
+
+bool ApplicationWindow::changeFolder(Folder *newFolder, bool force)
+{
+  if (!newFolder)
+    return false;
+
+  if (current_folder == newFolder && !force)
+    return false;
+
+  desactivateFolders();
+  newFolder->folderListItem()->setActive(true);
+
+  Folder *oldFolder = current_folder;
+  MdiSubWindow::Status old_active_window_state = MdiSubWindow::Normal;
+  MdiSubWindow *old_active_window = oldFolder->activeWindow();
+  if (old_active_window)
+    old_active_window_state = old_active_window->status();
+
+  MdiSubWindow::Status active_window_state = MdiSubWindow::Normal;
+  MdiSubWindow *active_window = newFolder->activeWindow();
+
+  if (active_window)
+    active_window_state = active_window->status();
+
+  hideFolderWindows(oldFolder);
+  current_folder = newFolder;
+
+  results->setText(current_folder->logInfo());
+
+  lv->clear();
+
+  QObjectList folderLst = newFolder->children();
+  if(!folderLst.isEmpty()){
+    foreach(QObject *f, folderLst)
+			    addFolderListViewItem(static_cast<Folder *>(f));
+  }
+
+  QList<MdiSubWindow *> lst = newFolder->windowsList();
+  foreach(MdiSubWindow *w, lst){
+    if (!hiddenWindows->contains(w) && show_windows_policy != HideAll){
+      //show only windows in the current folder which are not hidden by the user
+      if(w->status() == MdiSubWindow::Normal)
+        w->showNormal();
+      else if(w->status() == MdiSubWindow::Minimized)
+        w->showMinimized();
+      else if(w->status() == MdiSubWindow::Maximized)
+        w->showMaximized();
+    } else
+      w->setStatus(MdiSubWindow::Hidden);
+
+    addListViewItem(w);
+  }
+
+  if (!(newFolder->children()).isEmpty()){
+    Folder *f = newFolder->folderBelow();
+    int initial_depth = newFolder->depth();
+    while (f && f->depth() > initial_depth){//show/hide windows in subfolders
+      lst = f->windowsList();
+      foreach(MdiSubWindow *w, lst){
+        if (!hiddenWindows->contains(w)){
+          if (show_windows_policy == SubFolders){
+            if (w->status() == MdiSubWindow::Normal || w->status() == MdiSubWindow::Maximized)
+              w->showNormal();
+            else if (w->status() == MdiSubWindow::Minimized)
+              w->showMinimized();
+          } else
+            w->hide();
+        }
+      }
+      f = f->folderBelow();
+    }
+  }
+
+  if (active_window){
+    d_active_window = active_window;
+    d_workspace->setActiveSubWindow(active_window);
+    customMenu(active_window);
+    customToolBars(active_window);
+    if (active_window_state == MdiSubWindow::Minimized)
+      active_window->showMinimized();//ws->setActiveWindow() makes minimized windows to be shown normally
+    else if (active_window_state == MdiSubWindow::Maximized){
+      if (active_window->isA("Graph3D"))
+        ((Graph3D *)active_window)->setIgnoreFonts(true);
+      active_window->showMaximized();
+      if (active_window->isA("Graph3D"))
+        ((Graph3D *)active_window)->setIgnoreFonts(false);
+    }
+  }
+
+  if (old_active_window){
+    old_active_window->setStatus(old_active_window_state);
+    oldFolder->setActiveWindow(old_active_window);
+  }
+
+  if (d_opening_file)
+    modifiedProject();
+  return true;
+}
+
+void ApplicationWindow::desactivateFolders()
+{
+  FolderListItem *item = (FolderListItem *)folders->firstChild();
+  while (item){
+    item->setActive(false);
+    item = (FolderListItem *)item->itemBelow();
+  }
+}
+
+void ApplicationWindow::addListViewItem(MdiSubWindow *w)
+{
+  if (!w)
+    return;
+
+  WindowListItem* it = new WindowListItem(lv, w);
+  if (w->isA("Matrix")){
+    it->setPixmap(0, getQPixmap("matrix_xpm"));
+    it->setText(1, tr("Matrix"));
+  }
+  else if (w->inherits("Table")){
+    it->setPixmap(0, getQPixmap("worksheet_xpm"));
+    it->setText(1, tr("Table"));
+  }
+  else if (w->isA("Note")){
+    it->setPixmap(0, getQPixmap("note_xpm"));
+    it->setText(1, tr("Note"));
+  }
+  else if (w->isA("MultiLayer")){
+    it->setPixmap(0, getQPixmap("graph_xpm"));
+    it->setText(1, tr("Graph"));
+  }
+  else if (w->isA("Graph3D")){
+    it->setPixmap(0, getQPixmap("trajectory_xpm"));
+    it->setText(1, tr("3D Graph"));
+  }
+  else if (w->isA("MantidMatrix")){
+    it->setPixmap(0, getQPixmap("mantid_matrix_xpm"));
+    it->setText(1, tr("Workspace"));
+  }
+  else if (w->isA("InstrumentWindow")){
+    it->setText(1, tr("Instrument"));
+  }
+
+
+  it->setText(0, w->objectName());
+  it->setText(2, w->aspect());
+  it->setText(3, w->sizeToString());
+  it->setText(4, w->birthDate());
+  it->setText(5, w->windowLabel());
+}
+
+void ApplicationWindow::windowProperties()
+{
+  WindowListItem *it = (WindowListItem *)lv->currentItem();
+  MdiSubWindow *w = it->window();
+  if (!w)
+    return;
+
+  QMessageBox *mbox = new QMessageBox ( tr("Properties"), QString(), QMessageBox::NoIcon,
+      QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton, this);
+
+  QString s = QString(w->objectName()) + "\n\n";
+  s += "\n\n\n";
+
+  s += tr("Label") + ": " + ((MdiSubWindow *)w)->windowLabel() + "\n\n";
+
+  if (w->isA("Matrix")){
+    mbox->setIconPixmap(getQPixmap("matrix_xpm"));
+    s +=  tr("Type") + ": " + tr("Matrix") + "\n\n";
+  }else if (w->inherits("Table")){
+    mbox->setIconPixmap(getQPixmap("worksheet_xpm"));
+    s +=  tr("Type") + ": " + tr("Table") + "\n\n";
+  }else if (w->isA("Note")){
+    mbox->setIconPixmap(getQPixmap("note_xpm"));
+    s +=  tr("Type") + ": " + tr("Note") + "\n\n";
+  }else if (w->isA("MultiLayer")){
+    mbox->setIconPixmap(getQPixmap("graph_xpm"));
+    s +=  tr("Type") + ": " + tr("Graph") + "\n\n";
+  }else if (w->isA("Graph3D")){
+    mbox->setIconPixmap(getQPixmap("trajectory_xpm"));
+    s +=  tr("Type") + ": " + tr("3D Graph") + "\n\n";
+  }
+  s += tr("Path") + ": " + current_folder->path() + "\n\n";
+  s += tr("Size") + ": " + w->sizeToString() + "\n\n";
+  s += tr("Created") + ": " + w->birthDate() + "\n\n";
+  s += tr("Status") + ": " + it->text(2) + "\n\n";
+  mbox->setText(s);
+  mbox->show();
+}
+
+void ApplicationWindow::addFolderListViewItem(Folder *f)
+{
+  if (!f)
+    return;
+
+  FolderListItem* it = new FolderListItem(lv, f);
+  it->setActive(false);
+  it->setText(0, f->objectName());
+  it->setText(1, tr("Folder"));
+  it->setText(3, f->sizeToString());
+  it->setText(4, f->birthDate());
+}
+
+void ApplicationWindow::find(const QString& s, bool windowNames, bool labels,
+    bool folderNames, bool caseSensitive, bool partialMatch, bool subfolders)
+{
+  if (windowNames || labels){
+    MdiSubWindow *w = current_folder->findWindow(s, windowNames, labels, caseSensitive, partialMatch);
+    if (w){
+      activateWindow(w);
+      return;
+    }
+
+    if (subfolders){
+      FolderListItem *item = (FolderListItem *)folders->currentItem()->firstChild();
+      while (item){
+        Folder *f = item->folder();
+        MdiSubWindow *w = f->findWindow(s,windowNames,labels,caseSensitive,partialMatch);
+        if (w){
+          folders->setCurrentItem(f->folderListItem());
+          activateWindow(w);
+          return;
+        }
+        item = (FolderListItem *)item->itemBelow();
+      }
+    }
+  }
+
+  if (folderNames){
+    Folder *f = current_folder->findSubfolder(s, caseSensitive, partialMatch);
+    if (f){
+      folders->setCurrentItem(f->folderListItem());
+      return;
+    }
+
+    if (subfolders){
+      FolderListItem *item = (FolderListItem *)folders->currentItem()->firstChild();
+      while (item){
+        Folder *f = item->folder()->findSubfolder(s, caseSensitive, partialMatch);
+        if (f){
+          folders->setCurrentItem(f->folderListItem());
+          return;
+        }
+
+        item = (FolderListItem *)item->itemBelow();
+      }
+    }
+  }
+
+  QMessageBox::warning(this, tr("MantidPlot - No match found"),//Mantid
+      tr("Sorry, no match found for string: '%1'").arg(s));
+}
+
+void ApplicationWindow::dropFolderItems(Q3ListViewItem *dest)
+{
+  if (!dest || draggedItems.isEmpty ())
+    return;
+
+  Folder *dest_f = ((FolderListItem *)dest)->folder();
+
+  Q3ListViewItem *it;
+  QStringList subfolders = dest_f->subfolders();
+
+  foreach(it, draggedItems){
+    if (it->rtti() == FolderListItem::RTTI){
+      Folder *f = ((FolderListItem *)it)->folder();
+      FolderListItem *src = f->folderListItem();
+      if (dest_f == f){
+        QMessageBox::critical(this, "MantidPlot - Error", tr("Cannot move an object to itself!"));//Mantid
+        return;
+      }
+
+      if (((FolderListItem *)dest)->isChildOf(src)){
+        QMessageBox::critical(this,"MantidPlot - Error",tr("Cannot move a parent folder into a child folder!"));//Mantid
+        draggedItems.clear();
+        folders->setCurrentItem(current_folder->folderListItem());
+        return;
+      }
+
+      Folder *parent = (Folder *)f->parent();
+      if (!parent)
+        parent = projectFolder();
+      if (dest_f == parent)
+        return;
+
+      if (subfolders.contains(f->objectName())){
+        QMessageBox::critical(this, tr("MantidPlot") +" - " + tr("Skipped moving folder"),//Mantid
+            tr("The destination folder already contains a folder called '%1'! Folder skipped!").arg(f->objectName()));
+      } else
+        moveFolder(src, (FolderListItem *)dest);
+    } else {
+      if (dest_f == current_folder)
+        return;
+
+      MdiSubWindow *w = ((WindowListItem *)it)->window();
+      if (w){
+        current_folder->removeWindow(w);
+        w->hide();
+        dest_f->addWindow(w);
+        delete it;
+      }
+    }
+  }
+
+  draggedItems.clear();
+  current_folder = dest_f;
+  folders->setCurrentItem(dest_f->folderListItem());
+  changeFolder(dest_f, true);
+  folders->setFocus();
+}
+
+void ApplicationWindow::moveFolder(FolderListItem *src, FolderListItem *dest)
+{
+  folders->blockSignals(true);
+  if (copyFolder(src->folder(), dest->folder())){
+    delete src->folder();
+    delete src;
+  }
+  folders->blockSignals(false);
+}
+
+bool ApplicationWindow::copyFolder(Folder *src, Folder *dest)
+{
+  if (!src || !dest)
+    return false;
+
+  if (dest->subfolders().contains(src->objectName())){
+    QMessageBox::critical(this, tr("MantidPlot") + " - " + tr("Error"),//Mantid
+        tr("The destination folder already contains a folder called '%1'! Folder skipped!").arg(src->objectName()));
+    return false;
+  }
+
+  Folder *dest_f = new Folder(dest, src->objectName());
+  dest_f->setBirthDate(src->birthDate());
+  dest_f->setModificationDate(src->modificationDate());
+
+  FolderListItem *copy_item = new FolderListItem(dest->folderListItem(), dest_f);
+  copy_item->setText(0, src->objectName());
+  copy_item->setOpen(src->folderListItem()->isOpen());
+  dest_f->setFolderListItem(copy_item);
+
+  QList<MdiSubWindow *> lst = QList<MdiSubWindow *>(src->windowsList());
+  foreach(MdiSubWindow *w, lst)
+  dest_f->addWindow(w);
+
+  if (!(src->children()).isEmpty()){
+    int initial_depth = src->depth();
+    Folder *parentFolder = dest_f;
+    src = src->folderBelow();
+    while (src && parentFolder && src->depth() > initial_depth){
+      dest_f = new Folder(parentFolder, src->objectName());
+      dest_f->setBirthDate(src->birthDate());
+      dest_f->setModificationDate(src->modificationDate());
+
+      copy_item = new FolderListItem(parentFolder->folderListItem(), dest_f);
+      copy_item->setText(0, src->objectName());
+      copy_item->setOpen(src->folderListItem()->isOpen());
+      dest_f->setFolderListItem(copy_item);
+
+      lst = QList<MdiSubWindow *>(src->windowsList());
+      foreach(MdiSubWindow *w, lst)
+      dest_f->addWindow(w);
+
+      int depth = src->depth();
+      src = src->folderBelow();
+      if (src){
+        int next_folder_depth = src->depth();
+        if (next_folder_depth > depth)
+          parentFolder = dest_f;
+        else if (next_folder_depth < depth && next_folder_depth > initial_depth)
+          parentFolder = (Folder*)parentFolder->parent();
+      }
+    }
+  }
+  return true;
+}
+//Mantid commented out
+//void ApplicationWindow::searchForUpdates()
+//{
+//    int choice = QMessageBox::question(this, tr("QtiPlot"),
+//					tr("QtiPlot will try to download necessary information about the last available updates. Please modify your firewall settings in order to allow QtiPlot to connect to the internet!") + "\n" +
+//					tr("Do you wish to continue?"),
+//					QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape);
+//
+//    if (choice == QMessageBox::Yes){
+//        version_buffer.open(IO_WriteOnly);
+//        http.setHost("soft.proindependent.com");
+//        http.get("/version.txt", &version_buffer);
+//        http.closeConnection();
+//    }
+//}
+//
+//void ApplicationWindow::receivedVersionFile(bool error)
+//{
+//	if (error){
+//		QMessageBox::warning(this, tr("QtiPlot - HTTP get version file"),
+//				tr("Error while fetching version file with HTTP: %1.").arg(http.errorString()));
+//		return;
+//	}
+//
+//	version_buffer.close();
+//
+//	if (version_buffer.open(IO_ReadOnly))
+//	{
+//		QTextStream t( &version_buffer );
+//		t.setEncoding(QTextStream::UnicodeUTF8);
+//		QString version = t.readLine();
+//		version_buffer.close();
+//
+//		QString currentVersion = QString::number(maj_version) + "." + QString::number(min_version) +
+//			"." + QString::number(patch_version) + QString(extra_version);
+//
+//		if (currentVersion != version)
+//		{
+//			if(QMessageBox::question(this, tr("QtiPlot - Updates Available"),
+//						tr("There is a newer version of QtiPlot (%1) available for download. Would you like to download it?").arg(version),
+//						QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape) == QMessageBox::Yes)
+//				QDesktopServices::openUrl(QUrl("http://soft.proindependent.com/download.html"));
+//		}
+//		else if (!autoSearchUpdatesRequest)
+//		{
+//			QMessageBox::information(this, tr("QtiPlot - No Updates Available"),
+//					tr("No updates available. Your current version %1 is the last version available!").arg(version));
+//		}
+//		autoSearchUpdatesRequest = false;
+//	}
+//}
+
+/**
+  Turns 3D animation on or off
+ */
+void ApplicationWindow::toggle3DAnimation(bool on)
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->animate(on);
+}
+
+QString ApplicationWindow::generateUniqueName(const QString& name, bool increment)
+{
+  int index = 0;
+  QStringList lst;
+  Folder *f = projectFolder();
+  while (f){
+    QList<MdiSubWindow *> folderWindows = f->windowsList();
+    foreach(MdiSubWindow *w, folderWindows){
+      lst << QString(w->objectName());
+      if (QString(w->objectName()).startsWith(name))
+        index++;
+    }
+    f = f->folderBelow();
+  }
+
+  QString newName = name;
+  if (increment)//force return of a different name
+    newName += QString::number(++index);
+  else if (index>0)
+    newName += QString::number(index);
+
+  while(lst.contains(newName))
+    newName = name + QString::number(++index);
+
+  return newName;
+}
+
+void ApplicationWindow::clearTable()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+
+  if (QMessageBox::question(this, tr("MantidPlot - Warning"),//Mantid
+      tr("This will clear the contents of all the data associated with the table. Are you sure?"),
+      tr("&Yes"), tr("&No"), QString(), 0, 1 ) )
+    return;
+  else
+    t->clear();
+}
+
+void ApplicationWindow::goToRow()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return;
+
+  if (w->inherits("Table") || w->isA("Matrix")){
+    bool ok;
+    int row = QInputDialog::getInteger(this, tr("MantidPlot - Enter row number"), tr("Row"),//Mantid
+        1, 0, 1000000, 1, &ok, windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinMaxButtonsHint );
+    if ( !ok )
+      return;
+
+    if (w->inherits("Table"))
+      ((Table *)w)->goToRow(row);
+    else if (w->isA("Matrix"))
+      ((Matrix *)w)->goToRow(row);
+  }
+}
+
+void ApplicationWindow::goToColumn()
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return;
+
+  if (w->inherits("Table") || w->isA("Matrix")){
+    bool ok;
+    int col = QInputDialog::getInteger(this, tr("MantidPlot - Enter column number"), tr("Column"),//Mantid
+        1, 0, 1000000, 1, &ok, windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinMaxButtonsHint );
+    if ( !ok )
+      return;
+
+    if (w->inherits("Table"))
+      ((Table *)w)->goToColumn(col);
+    else if (w->isA("Matrix"))
+      ((Matrix *)w)->goToColumn(col);
+  }
+}
+
+void ApplicationWindow::showScriptWindow(bool forceVisible)
+{
+  if( !scriptingWindow )
+  {
+    // MG 09/02/2010 : Removed parent from scripting window. If it has one then it doesn't respect the always on top 
+    // flag, it is treated as a sub window of its parent
+    scriptingWindow = new ScriptingWindow(scriptingEnv(), NULL);
+    scriptingWindow->setObjectName("ScriptingWindow");
+    scriptingWindow->setAttribute(Qt::WA_DeleteOnClose, false);
+    connect(scriptingWindow, SIGNAL(closeMe()), this, SLOT(saveScriptWindowGeometry()));
+    connect(scriptingWindow, SIGNAL(hideMe()), this, SLOT(showScriptWindow()));
+    connect(scriptingWindow, SIGNAL(chooseScriptingLanguage()), this, SLOT(showScriptingLangDialog()));
+  }
+
+  if( forceVisible || scriptingWindow->isMinimized() || !scriptingWindow->isVisible() )
+  {
+    scriptingWindow->resize(d_script_win_size);
+    scriptingWindow->move(d_script_win_pos);
+    scriptingWindow->show();
+    scriptingWindow->setFocus();
+  }
+  else 
+  {
+    saveScriptWindowGeometry();
+    scriptingWindow->hide();
+  }
+}
+
+void ApplicationWindow::saveScriptWindowGeometry()
+{
+  d_script_win_size = scriptingWindow->size();
+  d_script_win_pos = scriptingWindow->pos();
+}
+
+void ApplicationWindow::showScriptInterpreter()
+{
+  if( !m_interpreterDock )
+  {
+    m_interpreterDock = new QDockWidget(this);
+    m_interpreterDock->setObjectName("interpreterDock");
+    m_interpreterDock->setWindowTitle("Script Interpreter");
+    addDockWidget( Qt::BottomDockWidgetArea, m_interpreterDock );
+
+    m_scriptInterpreter = new ScriptManagerWidget(scriptingEnv(), m_interpreterDock,true);
+    m_interpreterDock->setWidget(m_scriptInterpreter);
+    m_interpreterDock->setFocusPolicy(Qt::StrongFocus);
+    m_interpreterDock->setFocusProxy(m_scriptInterpreter);
+    
+  }
+  if( m_interpreterDock->isVisible() )
+  {
+    m_interpreterDock->hide();
+  }
+  else
+  { 
+    m_interpreterDock->show();
+    m_interpreterDock->setFocusPolicy(Qt::StrongFocus);
+    m_interpreterDock->setFocusProxy(m_scriptInterpreter);
+    m_scriptInterpreter->setFocus();
+    m_interpreterDock->activateWindow();
+     
+  }
+
+}
+
+/**
+  Turns perspective mode on or off
+ */
+void ApplicationWindow::togglePerspective(bool on)
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setOrthogonal(!on);
+}
+
+/**
+  Resets rotation of 3D plots to default values
+ */
+void ApplicationWindow::resetRotation()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->setRotation(30, 0, 15);
+}
+
+/**
+  Finds best layout for the 3D plot
+ */
+void ApplicationWindow::fitFrameToLayer()
+{
+  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
+  if (!g)
+    return;
+
+  g->findBestLayout();
+}
+
+ApplicationWindow::~ApplicationWindow()
+{
+  if (lastCopiedLayer)
+    delete lastCopiedLayer;
+
+  delete hiddenWindows;
+
+  if (scriptingWindow)
+  {
+    delete scriptingWindow;
+  }
+
+  if (d_text_editor)
+    delete d_text_editor;
+
+  QApplication::clipboard()->clear(QClipboard::Clipboard);
+
+  btnPointer->setChecked(true);
+
+  //Mantid
+  if (mantidUI) delete mantidUI;
+}
+
+QString ApplicationWindow::versionString()
+{
+  QString version(MANTIDPLOT_RELEASE_VERSION);
+  QString date(MANTIDPLOT_RELEASE_DATE);
+  return "This is MantidPlot version " + version + " of " + date;
+}
+
+int ApplicationWindow::convertOldToNewColorIndex(int cindex)
+{
+  if( (cindex == 13) || (cindex == 14) ) // white and light gray
+    return cindex + 4;
+
+  if(cindex == 15) // dark gray
+    return cindex + 8;
+
+  return cindex;
+}
+
+void ApplicationWindow::cascade()
+{
+  const int xoffset = 13;
+  const int yoffset = 20;
+  int x = 0;
+  int y = 0;
+  QList<QMdiSubWindow*> windows = d_workspace->subWindowList(QMdiArea::StackingOrder);
+  foreach (QMdiSubWindow *w, windows){
+    w->setActiveWindow();
+    ((MdiSubWindow *)w)->setNormal();
+    w->setGeometry(x, y, w->geometry().width(), w->geometry().height());
+    w->raise();
+    x += xoffset;
+    y += yoffset;
+  }
+  modifiedProject();
+}
+
+ApplicationWindow * ApplicationWindow::loadScript(const QString& fn, bool execute, bool quit)
+{
+#ifdef SCRIPTING_PYTHON
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  setScriptingLanguage("Python");
+  restoreApplicationGeometry();
+  showScriptWindow();
+  scriptingWindow->open(fn, false);
+  QApplication::restoreOverrideCursor();
+  if (execute)
+    scriptingWindow->executeAll();
+  if( quit )
+  {
+    saved = true;
+    this->close();
+  }
+  return this;
+#else
+  QMessageBox::critical(this, tr("MantidPlot") + " - " + tr("Error"),//Mantid
+      tr("MantidPlot was not built with Python scripting support included!"));//Mantid
+#endif
+  return 0;
+}
+
+bool ApplicationWindow::validFor2DPlot(Table *table)
+{
+  if (!table->selectedYColumns().count()){
+    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select a Y column to plot!"));//Mantid
+    return false;
+  } else if (table->numCols()<2) {
+    QMessageBox::critical(this, tr("MantidPlot - Error"),tr("You need at least two columns for this operation!"));//Mantid
+    return false;
+  } else if (table->noXColumn()) {
+    QMessageBox::critical(this, tr("MantidPlot - Error"), tr("Please set a default X column for this table, first!"));//Mantid
+    return false;
+  }
+  return true;
+}
+
+MultiLayer* ApplicationWindow::generate2DGraph(Graph::CurveType type)
+{
+  MdiSubWindow *w = activeWindow();
+  if (!w)
+    return 0;
+
+  if (w->inherits("Table")){
+    Table *table = static_cast<Table *>(w);
+    if (!validFor2DPlot(table))
+      return 0;
+
+    Q3TableSelection sel = table->getSelection();
+    return multilayerPlot(table, table->drawableColumnSelection(), type, sel.topRow(), sel.bottomRow());
+  } else if (w->isA("Matrix")){
+    Matrix *m = static_cast<Matrix *>(w);
+    return plotHistogram(m);
+  }
+  return 0;
+}
+
+bool ApplicationWindow::validFor3DPlot(Table *table)
+{
+  if (table->numCols()<2){
+    QMessageBox::critical(0,tr("MantidPlot - Error"),tr("You need at least two columns for this operation!"));//Mantid
+    return false;
+  }
+  if (table->selectedColumn() < 0 || table->colPlotDesignation(table->selectedColumn()) != Table::Z){
+    QMessageBox::critical(0,tr("MantidPlot - Error"),tr("Please select a Z column for this operation!"));//Mantid
+    return false;
+  }
+  if (table->noXColumn()){
+    QMessageBox::critical(0,tr("MantidPlot - Error"),tr("You need to define a X column first!"));//Mantid
+    return false;
+  }
+  if (table->noYColumn()){
+    QMessageBox::critical(0,tr("MantidPlot - Error"),tr("You need to define a Y column first!"));//Mantid
+    return false;
+  }
+  return true;
+}
+
+void ApplicationWindow::hideSelectedWindows()
+{
+  Q3ListViewItem *item;
+  QList<Q3ListViewItem *> lst;
+  for (item = lv->firstChild(); item; item = item->nextSibling()){
+    if (item->isSelected())
+      lst.append(item);
+  }
+
+  folders->blockSignals(true);
+  foreach(item, lst){
+    if (item->rtti() != FolderListItem::RTTI)
+      hideWindow(((WindowListItem *)item)->window());
+  }
+  folders->blockSignals(false);
+}
+
+void ApplicationWindow::showSelectedWindows()
+{
+  Q3ListViewItem *item;
+  QList<Q3ListViewItem *> lst;
+  for (item = lv->firstChild(); item; item = item->nextSibling()){
+    if (item->isSelected())
+      lst.append(item);
+  }
+
+  folders->blockSignals(true);
+  foreach(item, lst){
+    if (item->rtti() != FolderListItem::RTTI)
+      activateWindow(((WindowListItem *)item)->window());
+  }
+  folders->blockSignals(false);
+}
+
+void ApplicationWindow::swapColumns()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (!t)
+    return;
+  QStringList lst = t->selectedColumns();
+  if(lst.count() != 2)
+    return;
+
+  t->swapColumns(t->colIndex(lst[0]), t->colIndex(lst[1]));
+}
+
+void ApplicationWindow::moveColumnRight()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (t)
+    t->moveColumnBy(1);
+}
+
+void ApplicationWindow::moveColumnLeft()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (t)
+    t->moveColumnBy(-1);
+}
+
+void ApplicationWindow::moveColumnFirst()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (t)
+    t->moveColumnBy(0 - t->selectedColumn());
+}
+
+void ApplicationWindow::moveColumnLast()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (t)
+    t->moveColumnBy(t->numCols() - t->selectedColumn() - 1);
+}
+
+void ApplicationWindow::restoreApplicationGeometry()
+{
+  if (d_app_rect.isNull())
+    showMaximized();
+  else {
+    resize(d_app_rect.size());
+    move(d_app_rect.topLeft());
+    show();
+  }
+}
+
+void ApplicationWindow::scriptsDirPathChanged(const QString& path)
+{
+  scriptsDirPath = path;
+
+  QList<MdiSubWindow*> windows = windowsList();
+  foreach(MdiSubWindow *w, windows){
+    if (w->isA("Note"))
+      ((Note*)w)->setDirPath(path);
+  }
+}
+
+void ApplicationWindow::showToolBarsMenu()
+{
+  QMenu toolBarsMenu;
+
+  QAction *actionFileTools = new QAction(fileTools->windowTitle(), this);
+  actionFileTools->setCheckable(true);
+  actionFileTools->setChecked(fileTools->isVisible());
+  connect(actionFileTools, SIGNAL(toggled(bool)), fileTools, SLOT(setVisible(bool)));
+  toolBarsMenu.addAction(actionFileTools);
+
+  QAction *actionEditTools = new QAction(editTools->windowTitle(), this);
+  actionEditTools->setCheckable(true);
+  actionEditTools->setChecked(editTools->isVisible());
+  connect(actionEditTools, SIGNAL(toggled(bool)), editTools, SLOT(setVisible(bool)));
+  toolBarsMenu.addAction(actionEditTools);
+
+  QAction *actionTableTools = new QAction(tableTools->windowTitle(), this);
+  actionTableTools->setCheckable(true);
+  actionTableTools->setChecked(tableTools->isVisible());
+  connect(actionTableTools, SIGNAL(toggled(bool)), tableTools, SLOT(setVisible(bool)));
+  toolBarsMenu.addAction(actionTableTools);
+
+  QAction *actionColumnTools = new QAction(columnTools->windowTitle(), this);
+  actionColumnTools->setCheckable(true);
+  actionColumnTools->setChecked(columnTools->isVisible());
+  connect(actionColumnTools, SIGNAL(toggled(bool)), columnTools, SLOT(setVisible(bool)));
+  toolBarsMenu.addAction(actionColumnTools);
+
+  QAction *actionPlotTools = new QAction(plotTools->windowTitle(), this);
+  actionPlotTools->setCheckable(true);
+  actionPlotTools->setChecked(plotTools->isVisible());
+  connect(actionPlotTools, SIGNAL(toggled(bool)), plotTools, SLOT(setVisible(bool)));
+  toolBarsMenu.addAction(actionPlotTools);
+
+  QAction *actionMatrixTools = new QAction(plotMatrixBar->windowTitle(), this);
+  actionMatrixTools->setCheckable(true);
+  actionMatrixTools->setChecked(plotMatrixBar->isVisible());
+  connect(actionMatrixTools, SIGNAL(toggled(bool)), plotMatrixBar, SLOT(setVisible(bool)));
+  toolBarsMenu.addAction(actionMatrixTools);
+
+  QAction *actionPlot3DTools = new QAction(plot3DTools->windowTitle(), this);
+  actionPlot3DTools->setCheckable(true);
+  actionPlot3DTools->setChecked(plot3DTools->isVisible());
+  connect(actionPlot3DTools, SIGNAL(toggled(bool)), plot3DTools, SLOT(setVisible(bool)));
+  toolBarsMenu.addAction(actionPlot3DTools);
+
+  QAction *actionDisplayBar = new QAction(displayBar->windowTitle(), this);
+  actionDisplayBar->setCheckable(true);
+  actionDisplayBar->setChecked(displayBar->isVisible());
+  connect(actionDisplayBar, SIGNAL(toggled(bool)), displayBar, SLOT(setVisible(bool)));
+  toolBarsMenu.addAction(actionDisplayBar);
+
+  QAction *actionFormatToolBar = new QAction(formatToolBar->windowTitle(), this);
+  actionFormatToolBar->setCheckable(true);
+  actionFormatToolBar->setChecked(formatToolBar->isVisible());
+  connect(actionFormatToolBar, SIGNAL(toggled(bool)), formatToolBar, SLOT(setVisible(bool)));
+  toolBarsMenu.addAction(actionFormatToolBar);
+
+  QAction *action = toolBarsMenu.exec(QCursor::pos());
+  if (!action)
+    return;
+
+  MdiSubWindow *w = activeWindow();
+
+  if (action->text() == plotMatrixBar->windowTitle()){
+    d_matrix_tool_bar = action->isChecked();
+    plotMatrixBar->setEnabled(w && w->isA("Matrix"));
+  } else if (action->text() == tableTools->windowTitle()){
+    d_table_tool_bar = action->isChecked();
+    tableTools->setEnabled(w && w->inherits("Table"));
+  } else if (action->text() == columnTools->windowTitle()){
+    d_column_tool_bar = action->isChecked();
+    columnTools->setEnabled(w && w->inherits("Table"));
+  } else if (action->text() == plotTools->windowTitle()){
+    d_plot_tool_bar = action->isChecked();
+    plotTools->setEnabled(w && w->isA("MultiLayer"));
+  } else if (action->text() == plot3DTools->windowTitle()){
+    d_plot3D_tool_bar = action->isChecked();
+    plot3DTools->setEnabled(w && w->isA("Graph3D"));
+  } else if (action->text() == fileTools->windowTitle()){
+    d_file_tool_bar = action->isChecked();
+  } else if (action->text() == editTools->windowTitle()){
+    d_edit_tool_bar = action->isChecked();
+  } else if (action->text() == displayBar->windowTitle()){
+    d_display_tool_bar = action->isChecked();
+  } else if (action->text() == formatToolBar->windowTitle()){
+    d_format_tool_bar = action->isChecked();
+  }
+}
+
+void ApplicationWindow::saveFitFunctions(const QStringList& lst)
+{
+  if (!lst.count())
+    return;
+
+  QString explain = tr("Starting with version 0.9.1 MantidPlot stores the user defined fit models to a different location.");
+  explain += " " + tr("If you want to save your already defined models, please choose a destination folder.");
+  if (QMessageBox::Ok != QMessageBox::information(this, tr("MantidPlot") + " - " + tr("Import fit models"), explain,//Mantid
+      QMessageBox::Ok, QMessageBox::Cancel)) return;
+
+  QString dir = QFileDialog::getExistingDirectory(this, tr("Choose a directory to export the fit models to"), fitModelsPath, QFileDialog::ShowDirsOnly);
+  if (!dir.isEmpty()){
+    fitModelsPath = dir;
+
+    for (int i = 0; i<lst.count(); i++){
+      QString s = lst[i].simplified();
+      if (!s.isEmpty()){
+        NonLinearFit *fit = new NonLinearFit(this, 0);
+
+        int pos1 = s.find("(", 0);
+        fit->setObjectName(s.left(pos1));
+
+        int pos2 = s.find(")", pos1);
+        QString par = s.mid(pos1+4, pos2-pos1-4);
+        QStringList paramList = par.split(QRegExp("[,;]+[\\s]*"), QString::SkipEmptyParts);
+        fit->setParametersList(paramList);
+
+        QStringList l = s.split("=");
+        if (l.count() == 2)
+          fit->setFormula(l[1]);
+
+        fit->save(fitModelsPath + "/" + fit->objectName() + ".fit");
+      }
+    }
+  }
+}
+
+void ApplicationWindow::matrixDirectFFT()
+{
+  Matrix* m = (Matrix*)activeWindow(MatrixWindow);
+  if (!m)
+    return;
+
+  m->fft();
+}
+
+void ApplicationWindow::matrixInverseFFT()
+{
+  Matrix* m = (Matrix*)activeWindow(MatrixWindow);
+  if (!m)
+    return;
+
+  m->fft(true);
+}
+
+void ApplicationWindow::setFormatBarFont(const QFont& font)
+{
+  formatToolBar->setEnabled(true);
+
+  QFontComboBox *fb = (QFontComboBox *)formatToolBar->widgetForAction(actionFontBox);
+  fb->blockSignals(true);
+  fb->setCurrentFont(font);
+  fb->blockSignals(false);
+
+  QSpinBox *sb = (QSpinBox *)formatToolBar->widgetForAction(actionFontSize);
+  sb->blockSignals(true);
+  sb->setValue(font.pointSize());
+  sb->blockSignals(false);
+
+  actionFontBold->blockSignals(true);
+  actionFontBold->setChecked(font.bold());
+  actionFontBold->blockSignals(false);
+
+  actionFontItalic->blockSignals(true);
+  actionFontItalic->setChecked(font.italic());
+  actionFontItalic->blockSignals(false);
+
+  actionSubscript->setEnabled(false);
+  actionSuperscript->setEnabled(false);
+  actionUnderline->setEnabled(false);
+  actionGreekSymbol->setEnabled(false);
+  actionGreekMajSymbol->setEnabled(false);
+  actionMathSymbol->setEnabled(false);
+}
+
+void ApplicationWindow::setFontSize(int size)
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g)
+    return;
+
+  QFontComboBox *fb = (QFontComboBox *)formatToolBar->widgetForAction(actionFontBox);
+  QFont f(fb->currentFont().family(), size);
+  f.setBold(actionFontBold->isChecked());
+  f.setItalic(actionFontItalic->isChecked());
+  g->setCurrentFont(f);
+}
+
+void ApplicationWindow::setFontFamily(const QFont& font)
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g)
+    return;
+
+  QSpinBox *sb = (QSpinBox *)formatToolBar->widgetForAction(actionFontSize);
+  QFont f(font.family(), sb->value());
+  f.setBold(actionFontBold->isChecked());
+  f.setItalic(actionFontItalic->isChecked());
+  g->setCurrentFont(f);
+}
+
+void ApplicationWindow::setItalicFont(bool italic)
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g)
+    return;
+
+  QFontComboBox *fb = (QFontComboBox *)formatToolBar->widgetForAction(actionFontBox);
+  QSpinBox *sb = (QSpinBox *)formatToolBar->widgetForAction(actionFontSize);
+  QFont f(fb->currentFont().family(), sb->value());
+  f.setBold(actionFontBold->isChecked());
+  f.setItalic(italic);
+  g->setCurrentFont(f);
+}
+
+void ApplicationWindow::setBoldFont(bool bold)
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  Graph* g = plot->activeGraph();
+  if (!g)
+    return;
+
+  QFontComboBox *fb = (QFontComboBox *)formatToolBar->widgetForAction(actionFontBox);
+  QSpinBox *sb = (QSpinBox *)formatToolBar->widgetForAction(actionFontSize);
+  QFont f(fb->currentFont().family(), sb->value());
+  f.setBold(bold);
+  f.setItalic(actionFontItalic->isChecked());
+  g->setCurrentFont(f);
+}
+
+void ApplicationWindow::enableTextEditor(Graph *g)
+{
+  if (!g){
+    formatToolBar->setEnabled(false);
+    if (d_text_editor){
+      d_text_editor->close();
+      d_text_editor = NULL;
+    }
+  } else if (g) {
+    d_text_editor = new TextEditor(g);
+
+    formatToolBar->setEnabled(true);
+    actionSubscript->setEnabled(true);
+    actionSuperscript->setEnabled(true);
+    actionUnderline->setEnabled(true);
+    actionGreekSymbol->setEnabled(true);
+    actionGreekMajSymbol->setEnabled(true);
+    actionMathSymbol->setEnabled(true);
+  }
+}
+
+void ApplicationWindow::insertSuperscript()
+{
+  if (!d_text_editor)
+    return;
+
+  d_text_editor->formatText("<sup>","</sup>");
+}
+
+void ApplicationWindow::insertSubscript()
+{
+  if (!d_text_editor)
+    return;
+
+  d_text_editor->formatText("<sub>","</sub>");
+}
+
+void ApplicationWindow::underline()
+{
+  if (!d_text_editor)
+    return;
+
+  d_text_editor->formatText("<u>","</u>");
+}
+
+void ApplicationWindow::insertGreekSymbol()
+{
+  if (!d_text_editor)
+    return;
+
+  SymbolDialog *greekLetters = new SymbolDialog(SymbolDialog::lowerGreek, this);
+  connect(greekLetters, SIGNAL(addLetter(const QString&)), d_text_editor, SLOT(addSymbol(const QString&)));
+  greekLetters->exec();
+}
+
+void ApplicationWindow::insertGreekMajSymbol()
+{
+  if (!d_text_editor)
+    return;
+
+  SymbolDialog *greekLetters = new SymbolDialog(SymbolDialog::upperGreek, this);
+  connect(greekLetters, SIGNAL(addLetter(const QString&)), d_text_editor, SLOT(addSymbol(const QString&)));
+  greekLetters->exec();
+}
+
+void ApplicationWindow::insertMathSymbol()
+{
+  if (!d_text_editor)
+    return;
+
+  SymbolDialog *ms = new SymbolDialog(SymbolDialog::mathSymbols, this);
+  connect(ms, SIGNAL(addLetter(const QString&)), d_text_editor, SLOT(addSymbol(const QString&)));
+  ms->exec();
+}
+
+void ApplicationWindow::showCustomActionDialog()
+{
+  ManageCustomMenus *ad = new ManageCustomMenus(this);
+  ad->setAttribute(Qt::WA_DeleteOnClose);
+  ad->show();
+  ad->setFocus();
+}
+
+void ApplicationWindow::showUserDirectoryDialog()
+{
+  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
+  ad->show();
+  ad->setFocus();
+}
+
+void ApplicationWindow::addCustomAction(QAction *action, const QString& parentName, int index)
+{
+  if (!action)
+    return;
+
+  QList<QToolBar *> toolBars = toolBarsList();
+  foreach (QToolBar *t, toolBars){
+    if (t->objectName() == parentName){
+      t->addAction(action);
+      if (index < 0)
+        d_user_actions << action;
+      else if (index >= 0 && index < d_user_actions.size())
+        d_user_actions.replace(index, action);
+      return;
+    }
+  }
+
+  QList<QMenu *> menus = customizableMenusList();
+  foreach (QMenu *m, menus){
+    if (m->objectName() == parentName){
+      m->addAction(action);
+      if (index < 0)
+        d_user_actions << action;
+      else if (index >= 0 && index < d_user_actions.size())
+        d_user_actions.replace(index, action);
+      return;
+    }
+  }
+}
+
+void ApplicationWindow::reloadCustomActions()
+{
+  QList<QMenu *> menus = customizableMenusList();
+  foreach(QAction *a, d_user_actions){
+    if (!a->statusTip().isEmpty()){
+      foreach (QMenu *m, menus){
+        if (m->objectName() == a->statusTip()){
+          QList<QAction *> lst = m->actions();
+          if (!lst.contains(a))
+            m->addAction(a);
+        }
+      }
+    }
+  }
+}
+
+void ApplicationWindow::removeCustomAction(QAction *action)
+{
+  int index = d_user_actions.indexOf(action);
+  if (index >= 0 && index < d_user_actions.count()){
+    d_user_actions.removeAt(index);
+    delete action;
+  }
+}
+
+void ApplicationWindow::performCustomAction(QAction *action)
+{
+  if (!action || !d_user_actions.contains(action))
+    return;
+#ifdef SCRIPTING_PYTHON
+QString action_data = action->data().toString();
+if( QFileInfo(action_data).exists() )
+{
+  QFile script_file(action_data);
+  if ( !script_file.open(IO_ReadOnly) )
+  {
+    QMessageBox::information(this, "MantidPlot", "Error: There was a problem reading\n" + action_data);
+    return;
+  }
+  
+  QTextStream stream(&script_file);
+  QString scriptPath = QString("r'%1'").arg(QFileInfo(action_data).absolutePath());
+  QString code = QString("sys.path.append(%1)\n").arg(scriptPath);
+    runPythonScript(code, true);
+  code = "";
+  while( !stream.atEnd() )
+  {
+    code.append(stream.readLine() + "\n");
+  }
+  runPythonScript(code);
+  code = "";
+  code.append(QString("\nsys.path.remove(%1)").arg(scriptPath));
+    runPythonScript(code, true);
+}
+else
+{
+  //First search for an existing window
+  foreach( QMdiSubWindow* sub_win, d_workspace->subWindowList() )
+  {
+    if( sub_win->widget()->objectName() == action_data )
+    {
+      sub_win->widget()->show();
+      return;
+    }
+  }
 
-  if(m_scriptInterpreter ) m_scriptInterpreter->saveSettings();
-  if( scriptingWindow ) 
+  QMdiSubWindow* usr_win = new QMdiSubWindow;
+  usr_win->setAttribute(Qt::WA_DeleteOnClose, false);
+  MantidQt::API::UserSubWindow *user_interface = MantidQt::API::InterfaceManager::Instance().createSubWindow(action_data, usr_win);
+  if(user_interface)
   {
-    settings.beginGroup("/ScriptWindow");
-    // Geometry is applied by the app window
-    settings.setValue("/size", d_script_win_size);
-    settings.setValue("/pos", d_script_win_pos);
-    settings.endGroup();
-    // Other specific settings
-    scriptingWindow->saveSettings();
+    setGeometry(usr_win,user_interface);
+    connect(user_interface, SIGNAL(runAsPythonScript(const QString&)), this,
+        SLOT(runPythonScript(const QString&)));
+    user_interface->initializeLocalPython();
+  }
+  else
+  {
+    delete usr_win;
   }
-
-  settings.beginGroup("/ToolBars");
-  settings.setValue("/FileToolBar", d_file_tool_bar);
-  settings.setValue("/EditToolBar", d_edit_tool_bar);
-  settings.setValue("/TableToolBar", d_table_tool_bar);
-  settings.setValue("/ColumnToolBar", d_column_tool_bar);
-  settings.setValue("/MatrixToolBar", d_matrix_tool_bar);
-  settings.setValue("/PlotToolBar", d_plot_tool_bar);
-  settings.setValue("/Plot3DToolBar", d_plot3D_tool_bar);
-  settings.setValue("/DisplayToolBar", d_display_tool_bar);
-  settings.setValue("/FormatToolBar", d_format_tool_bar);
-  settings.endGroup();
-
-  //Save mantid settings
-  mantidUI->saveSettings();
-
-  //--------------------------------------
-  // Mantid - Save custom scripts
-  settings.beginGroup("CustomScripts");
-  settings.remove("");
-  foreach( QMenu* menu, d_user_menus )
-  {
-    settings.beginGroup(menu->title());
-    foreach( QAction* action, menu->actions() )
-    {
-      settings.setValue(action->text(), action->data().toString());
-    }
-    settings.endGroup();
-  }
-
-  // Mantid - Remember which interfaces the user explicitely removed
-  // from the Interfaces menu
-  settings.setValue("RemovedInterfaces", removed_interfaces);
-
-  settings.endGroup();
-  //-----------------------------------
-}
-
-void ApplicationWindow::exportGraph()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return;
-
-  MultiLayer *plot2D = 0;
-  Graph3D *plot3D = 0;
-  if(w->isA("MultiLayer")){
-    plot2D = (MultiLayer*)w;
-    if (plot2D->isEmpty()){
-      QMessageBox::critical(this, tr("MantidPlot - Export Error"),//Mantid
-          tr("<h4>There are no plot layers available in this window!</h4>"));
-      return;
-    }
-  } else if (w->isA("Graph3D"))
-    plot3D = (Graph3D*)w;
-  else
-    return;
-
-  ImageExportDialog *ied = new ImageExportDialog(this, plot2D!=NULL, d_extended_export_dialog);
-  ied->setDir(workingDir);
-  ied->selectFilter(d_image_export_filter);
-  if ( ied->exec() != QDialog::Accepted )
-    return;
-  workingDir = ied->directory().path();
-  if (ied->selectedFiles().isEmpty())
-    return;
-
-  QString selected_filter = ied->selectedFilter();
-  QString file_name = ied->selectedFiles()[0];
-  QFileInfo file_info(file_name);
-  if (!file_info.fileName().contains("."))
-    file_name.append(selected_filter.remove("*"));
-
-  QFile file(file_name);
-  if (!file.open( QIODevice::WriteOnly )){
-    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));
-    return;
-  }
-  file.close();
-
-  if (selected_filter.contains(".eps") || selected_filter.contains(".pdf") ||
-      selected_filter.contains(".ps") || selected_filter.contains(".svg")) {
-    if (plot3D)
-      plot3D->exportVector(file_name);
-    else if (plot2D){
-      if (selected_filter.contains(".svg"))
-        plot2D->exportSVG(file_name);
-      else
-        plot2D->exportVector(file_name, ied->resolution(), ied->color(), ied->keepAspect(), ied->pageSize());
-    }
-  } else {
-    QList<QByteArray> list = QImageWriter::supportedImageFormats();
-    for (int i=0; i<(int)list.count(); i++){
-      if (selected_filter.contains("." + (list[i]).lower())) {
-        if (plot2D)
-          plot2D->exportImage(file_name, ied->quality(), ied->transparency());
-        else if (plot3D)
-          plot3D->exportImage(file_name, ied->quality(), ied->transparency());
-      }
-    }
-  }
-}
-
-void ApplicationWindow::exportLayer()
-{
-  MdiSubWindow *w = activeWindow(MultiLayerWindow);
-  if (!w)
-    return;
-
-  Graph* g = ((MultiLayer*)w)->activeGraph();
-  if (!g)
-    return;
-
-  ImageExportDialog *ied = new ImageExportDialog(this, g!=NULL, d_extended_export_dialog);
-  ied->setDir(workingDir);
-  ied->selectFilter(d_image_export_filter);
-  if ( ied->exec() != QDialog::Accepted )
-    return;
-  workingDir = ied->directory().path();
-  if (ied->selectedFiles().isEmpty())
-    return;
-
-  QString selected_filter = ied->selectedFilter();
-  QString file_name = ied->selectedFiles()[0];
-  QFileInfo file_info(file_name);
-  if (!file_info.fileName().contains("."))
-    file_name.append(selected_filter.remove("*"));
-
-  QFile file(file_name);
-  if ( !file.open( QIODevice::WriteOnly ) ){
-    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));
-    return;
-  }
-  file.close();
-
-  if (selected_filter.contains(".eps") || selected_filter.contains(".pdf") || selected_filter.contains(".ps"))
-    g->exportVector(file_name, ied->resolution(), ied->color(), ied->keepAspect(), ied->pageSize());
-  else if (selected_filter.contains(".svg"))
-    g->exportSVG(file_name);
-  /*else if (selected_filter.contains(".emf"))
-		g->exportEMF(file_name);*/
-  else {
-    QList<QByteArray> list = QImageWriter::supportedImageFormats();
-    for (int i=0; i<(int)list.count(); i++)
-      if (selected_filter.contains("."+(list[i]).lower()))
-        g->exportImage(file_name, ied->quality(), ied->transparency());
-  }
-}
-
-void ApplicationWindow::exportAllGraphs()
-{
-  ImageExportDialog *ied = new ImageExportDialog(this, true, d_extended_export_dialog);
-  ied->setWindowTitle(tr("Choose a directory to export the graphs to"));
-  QStringList tmp = ied->filters();
-  ied->setFileMode(QFileDialog::Directory);
-  ied->setFilters(tmp);
-  ied->setLabelText(QFileDialog::FileType, tr("Output format:"));
-  ied->setLabelText(QFileDialog::FileName, tr("Directory:"));
-
-  ied->setDir(workingDir);
-  ied->selectFilter(d_image_export_filter);
-
-  if ( ied->exec() != QDialog::Accepted )
-    return;
-  workingDir = ied->directory().path();
-  if (ied->selectedFiles().isEmpty())
-    return;
-
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-  QString output_dir = ied->selectedFiles()[0];
-  QString file_suffix = ied->selectedFilter();
-  file_suffix.lower();
-  file_suffix.remove("*");
-
-  bool confirm_overwrite = true;
-  MultiLayer *plot2D;
-  Graph3D *plot3D;
-
-  QList<MdiSubWindow *> windows = windowsList();
-  foreach(MdiSubWindow *w, windows){
-    if (w->isA("MultiLayer")) {
-      plot3D = 0;
-      plot2D = (MultiLayer *)w;
-      if (plot2D->isEmpty()) {
-        QApplication::restoreOverrideCursor();
-        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()));
-        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-        continue;
-      }
-    } else if (w->isA("Graph3D")) {
-      plot2D = 0;
-      plot3D = (Graph3D *)w;
-    } else
-      continue;
-
-    QString file_name = output_dir + "/" + w->objectName() + file_suffix;
-    QFile f(file_name);
-    if (f.exists() && confirm_overwrite) {
-      QApplication::restoreOverrideCursor();
-
-      QString msg = tr("A file called: <p><b>%1</b><p>already exists. ""Do you want to overwrite it?").arg(file_name);
-      QMessageBox msgBox(QMessageBox::Question, tr("MantidPlot - Overwrite file?"), msg,//Mantid
-          QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::Cancel,
-          (ApplicationWindow *)this);
-      msgBox.exec();
-      switch(msgBox.standardButton(msgBox.clickedButton())){
-      case QMessageBox::Yes:
-        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-        break;
-      case QMessageBox::YesToAll:
-        confirm_overwrite = false;
-        break;
-      case QMessageBox::No:
-        confirm_overwrite = true;
-        continue;
-        break;
-      case QMessageBox::Cancel:
-        return;
-        break;
-      default:
-        break;
-      }
-    }
-    if ( !f.open( QIODevice::WriteOnly ) ) {
-      QApplication::restoreOverrideCursor();
-      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));
-      return;
-    }
-    f.close();
-
-    if (file_suffix.contains(".eps") || file_suffix.contains(".pdf") ||
-        file_suffix.contains(".ps") || file_suffix.contains(".svg")) {
-      if (plot3D)
-        plot3D->exportVector(file_name);
-      else if (plot2D){
-        if (file_suffix.contains(".svg"))
-          plot2D->exportSVG(file_name);
-        else
-          plot2D->exportVector(file_name, ied->resolution(), ied->color(), ied->keepAspect(), ied->pageSize());
-      }
-    } else {
-      QList<QByteArray> list = QImageWriter::supportedImageFormats();
-      for (int i=0; i<(int)list.count(); i++){
-        if (file_suffix.contains("." + (list[i]).lower())) {
-          if (plot2D)
-            plot2D->exportImage(file_name, ied->quality(), ied->transparency());
-          else if (plot3D)
-            plot3D->exportImage(file_name, ied->quality(), ied->transparency());
-        }
-      }
-    }
-  }
-  QApplication::restoreOverrideCursor();
-}
-
-QString ApplicationWindow::windowGeometryInfo(MdiSubWindow *w)
-{
-  QString s = "geometry\t";
-  if (w->status() == MdiSubWindow::Maximized){
-    if (w == w->folder()->activeWindow())
-      return s + "maximized\tactive\n";
-    else
-      return s + "maximized\n";
-  }
-
-  s += QString::number(w->x()) + "\t";
-  s += QString::number(w->y()) + "\t";
-  if (w->status() != MdiSubWindow::Minimized){
-    s += QString::number(w->width()) + "\t";
-    s += QString::number(w->height()) + "\t";
-  } else {
-    s += QString::number(w->minRestoreSize().width()) + "\t";
-    s += QString::number(w->minRestoreSize().height()) + "\t";
-    s += "minimized\t";
-  }
-
-  bool hide = hidden(w);
-  if (w == w->folder()->activeWindow() && !hide)
-    s+="active\n";
-  else if(hide)
-    s+="hidden\n";
-  else
-    s+="\n";
-  return s;
-}
-
-void ApplicationWindow::restoreWindowGeometry(ApplicationWindow *app, MdiSubWindow *w, const QString s)
-{
-  if(!w) return ;
-  w->hide();
-
-  QString caption = w->objectName();
-  if (s.contains ("minimized")) {
-    QStringList lst = s.split("\t");
-    if (lst.count() > 4){
-      int width = lst[3].toInt();
-      int height = lst[4].toInt();
-      if(width > 0 && height > 0)
-        w->resize(width, height);
-    }
-    w->setStatus(MdiSubWindow::Minimized);
-    app->setListView(caption, tr("Minimized"));
-  } else if (s.contains ("maximized")){
-    w->setStatus(MdiSubWindow::Maximized);
-    app->setListView(caption, tr("Maximized"));
-  } else {
-    QStringList lst = s.split("\t");
-    if (lst.count() > 4){
-      w->resize(lst[3].toInt(), lst[4].toInt());
-      w->move(lst[1].toInt(), lst[2].toInt());
-    }
-    w->setStatus(MdiSubWindow::Normal);
-    if (lst.count() > 5) {
-      if (lst[5] == "hidden")
-        app->hideWindow(w);
-    }
-  }
-
-  if (s.contains ("active")) {
-    Folder *f = w->folder();
-    if (f)
-      f->setActiveWindow(w);
-  }
-}
-
-Folder* ApplicationWindow::projectFolder()
-{
-  return ((FolderListItem *)folders->firstChild())->folder();
-}
-
-bool ApplicationWindow::saveProject(bool compress)
-{
-  if (projectname == "untitled" || projectname.endsWith(".opj", Qt::CaseInsensitive) ||
-      projectname.endsWith(".ogm", Qt::CaseInsensitive) || projectname.endsWith(".ogw", Qt::CaseInsensitive)
-      || projectname.endsWith(".ogg", Qt::CaseInsensitive))
-  {
-    saveProjectAs();
-    return true;;
-  }
-
-#ifdef QTIPLOT_DEMO
-  showDemoVersionMessage();
-  return false;
-#endif
-
-  saveFolder(projectFolder(), projectname, compress);
-
-  setWindowTitle("MantidPlot - " + projectname);
-  savedProject();
-
-  if (autoSave){
-    if (savingTimerId)
-      killTimer(savingTimerId);
-    savingTimerId=startTimer(autoSaveTime*60000);
-  } else
-    savingTimerId=0;
-
-  QApplication::restoreOverrideCursor();
-  return true;
-}
-void ApplicationWindow::savetoNexusFile()
-{
-  QString filter = tr("Mantid Files")+" (*.nxs *.nx5 *.xml);;";
-  QString selectedFilter;
-  QString fileDir=MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory();
-  if(fileDir.isEmpty())
-  {fileDir="C\\Mantid\\Test\\Nexus";
-  }
-  QString fileName = QFileDialog::getSaveFileName(this, tr("Save File As"), fileDir, filter, &selectedFilter);
-  if ( !fileName.isEmpty() ){
-    std::string wsName;
-    MdiSubWindow *w = activeWindow();
-    if(w)
-    {
-      if(w->isA("MantidMatrix"))
-      {
-        wsName=((MantidMatrix*)w)->getWorkspaceName();
-      }
-    }
-    else
-    {
-      wsName=m_nexusInputWSName.toStdString();
-    }
-    if(!Mantid::API::AnalysisDataService::Instance().doesExist(wsName))
-    {
-      throw std::runtime_error("Invalid input workspace for SaveNexus");
-    }
-
-    savedatainNexusFormat(wsName,fileName.toStdString());
-
-    MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(QFileInfo(fileName).absoluteDir().path());
-
-  }
-}
-
-void ApplicationWindow::loadDataFile()
-{
-  if(mantidUI)
-  {
-    mantidUI->executeAlgorithm("Load",-1);
-  }
-}
-void ApplicationWindow::saveProjectAs(const QString& fileName, bool compress)
-{
-#ifdef QTIPLOT_DEMO
-  showDemoVersionMessage();
-  return;
-#endif
-
-  QString fn = fileName;
-  if (fileName.isEmpty()){
-    QString filter = tr("MantidPlot project")+" (*.mantid);;"; //tr("QtiPlot project")+" (*.qti);;";
-    filter += tr("Compressed MantidPlot project")+" (*.mantid.gz)";
-
-    QString selectedFilter;
-    fn = QFileDialog::getSaveFileName(this, tr("Save Project As"), workingDir, filter, &selectedFilter);
-    if (selectedFilter.contains(".gz"))
-      compress = true;
-  }
-
-  if ( !fn.isEmpty() ){
-    QFileInfo fi(fn);
-    workingDir = fi.dirPath(true);
-    QString baseName = fi.fileName();
-    if (!baseName.contains("."))
-      //fn.append(".qti");
-      fn.append(".mantid");
-
-    projectname = fn;
-    if (saveProject(compress)){
-      recentProjects.remove(projectname);
-      recentProjects.push_front(projectname);
-      updateRecentProjectsList();
-
-      QFileInfo fi(fn);
-      QString baseName = fi.baseName();
-      FolderListItem *item = (FolderListItem *)folders->firstChild();
-      item->setText(0, baseName);
-      item->folder()->setObjectName(baseName);
-    }
-  }
-}
-
-void ApplicationWindow::saveNoteAs()
-{
-  Note* w = (Note*)activeWindow(NoteWindow);
-  if (!w)
-    return;
-  w->exportASCII();
-}
-
-void ApplicationWindow::saveAsTemplate(MdiSubWindow* w, const QString& fileName)
-{
-  if (!w) {
-    w = activeWindow();
-    if (!w)
-      return;
-  }
-
-  QString fn = fileName;
-  if (fn.isEmpty()){
-    QString filter;
-    if (w->isA("Matrix"))
-      filter = tr("MantidPlot Matrix Template")+" (*.qmt)";
-    else if (w->isA("MultiLayer"))
-      filter = tr("MantidPlot 2D Graph Template")+" (*.qpt)";
-    else if (w->inherits("Table"))
-      filter = tr("MantidPlot Table Template")+" (*.qtt)";
-    else if (w->isA("Graph3D"))
-      filter = tr("MantidPlot 3D Surface Template")+" (*.qst)";
-
-    QString selectedFilter;
-    fn = QFileDialog::getSaveFileName(this, tr("Save Window As Template"), templatesDir + "/" + w->objectName(), filter, &selectedFilter);
-
-    if (!fn.isEmpty()){
-      QFileInfo fi(fn);
-      workingDir = fi.dirPath(true);
-      QString baseName = fi.fileName();
-      if (!baseName.contains(".")){
-        selectedFilter = selectedFilter.right(5).left(4);
-        fn.append(selectedFilter);
-      }
-    } else
-      return;
-  }
-
-  QFile f(fn);
-  if ( !f.open( QIODevice::WriteOnly ) ){
-    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(fn));
-    return;
-  }
-
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-  QString text = "MantidPlot " + QString::number(maj_version)+"."+ QString::number(min_version)+"."+
-      QString::number(patch_version) + " template file\n";
-  text += w->saveAsTemplate(windowGeometryInfo(w));
-  QTextStream t( &f );
-  t.setEncoding(QTextStream::UnicodeUTF8);
-  t << text;
-  f.close();
-  QApplication::restoreOverrideCursor();
-}
-
-void ApplicationWindow::rename()
-{
-  MdiSubWindow* m = activeWindow();
-  if (!m)
-    return;
-
-  RenameWindowDialog *rwd = new RenameWindowDialog(this);
-  rwd->setAttribute(Qt::WA_DeleteOnClose);
-  rwd->setWidget(m);
-  rwd->exec();
-}
-
-void ApplicationWindow::renameWindow()
-{
-  WindowListItem *it = (WindowListItem *)lv->currentItem();
-  MdiSubWindow *w = it->window();
-  if (!w)
-    return;
-
-  RenameWindowDialog *rwd = new RenameWindowDialog(this);
-  rwd->setAttribute(Qt::WA_DeleteOnClose);
-  rwd->setWidget(w);
-  rwd->exec();
-}
-
-void ApplicationWindow::renameWindow(Q3ListViewItem *item, int, const QString &text)
-{
-  if (!item)
-    return;
-
-  MdiSubWindow *w = ((WindowListItem *)item)->window();
-  if (!w || text == w->objectName())
-    return;
-
-  if(!setWindowName(w, text))
-    item->setText(0, w->objectName());
-}
-
-bool ApplicationWindow::setWindowName(MdiSubWindow *w, const QString &text)
-{
-  if (!w)
-    return false;
-
-  QString name = w->objectName();
-  if (name == text)
-    return true;
-
-  QString newName = text;
-  newName.replace("-", "_");
-  if (newName.isEmpty()){
-    QMessageBox::critical(this, tr("MantidPlot - Error"), tr("Please enter a valid name!"));//Mantid
-    return false;
-  } else if (newName.contains(QRegExp("\\W"))){
-    QMessageBox::critical(this, tr("MantidPlot - Error"),//Mantid
-        tr("The name you chose is not valid: only letters and digits are allowed!")+
-        "<p>" + tr("Please choose another name!"));
-    return false;
-  }
-
-  newName.replace("_", "-");
-
-  while(alreadyUsedName(newName)){
-    QMessageBox::critical(this, tr("MantidPlot - Error"), tr("Name <b>%1</b> already exists!").arg(newName)+//Mantid
-        "<p>"+tr("Please choose another name!")+
-        "<p>"+tr("Warning: for internal consistency reasons the underscore character is replaced with a minus sign."));
-    return false;
-  }
-
-  if (w->inherits("Table"))
-    updateTableNames(name, newName);
-  else if (w->isA("Matrix"))
-    changeMatrixName(name, newName);
-
-  w->setCaptionPolicy(w->captionPolicy());
-  w->setName(newName);
-  renameListViewItem(name, newName);
-  return true;
-}
-
-QStringList ApplicationWindow::columnsList(Table::PlotDesignation plotType)
-{
-  QStringList list;
-  QList<MdiSubWindow *> windows = windowsList();
-  foreach(MdiSubWindow *w, windows){
-    if (!w->inherits("Table"))
-      continue;
-
-    Table *t = (Table *)w;
-    for (int i=0; i < t->numCols(); i++)
-    {
-      if (t->colPlotDesignation(i) == plotType || plotType == Table::All)
-        list << QString(t->objectName()) + "_" + t->colLabel(i);
-    }
-  }
-  return list;
-}
-
-void ApplicationWindow::showCurvesDialog()
-{
-  MdiSubWindow *w = activeWindow(MultiLayerWindow);
-  if (!w)
-    return;
-
-  if (((MultiLayer*)w)->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Error"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    return;
-  }
-
-  Graph* g = ((MultiLayer*)w)->activeGraph();
-  if (!g)
-    return;
-
-  if (g->isPiePlot()){
-    QMessageBox::warning(this,tr("MantidPlot - Error"),//Mantid
-        tr("This functionality is not available for pie plots!"));
-  } else {
-    CurvesDialog* crvDialog = new CurvesDialog(this);
-    crvDialog->setAttribute(Qt::WA_DeleteOnClose);
-    crvDialog->setGraph(g);
-    crvDialog->resize(d_add_curves_dialog_size);
-    crvDialog->setModal(true);
-    crvDialog->show();
-  }
-}
-
-bool ApplicationWindow::hasTable()
-{
-  Folder *f = projectFolder();
-  while (f){
-    QList<MdiSubWindow *> folderWindows = f->windowsList();
-    foreach(MdiSubWindow *w, folderWindows){
-      if (w->inherits("Table"))
-        return true;
-    }
-    f = f->folderBelow();
-  }
-  return false;
-}
-
-QStringList ApplicationWindow::tableNames()
-{
-  QStringList lst = QStringList();
-  Folder *f = projectFolder();
-  while (f){
-    QList<MdiSubWindow *> folderWindows = f->windowsList();
-    foreach(MdiSubWindow *w, folderWindows){
-      if (w->inherits("Table"))
-        lst << w->objectName();
-    }
-    f = f->folderBelow();
-  }
-  return lst;
-}
-
-QList<MdiSubWindow*> ApplicationWindow::tableList()
-{
-  QList<MdiSubWindow*> lst;
-  Folder *f = projectFolder();
-  while (f){
-    QList<MdiSubWindow *> folderWindows = f->windowsList();
-    foreach(MdiSubWindow *w, folderWindows){
-      if (w->inherits("Table"))
-        lst << w;
-    }
-    f = f->folderBelow();
-  }
-  return lst;
-}
-
-AssociationsDialog* ApplicationWindow::showPlotAssociations(int curve)
-{
-  MdiSubWindow* w = activeWindow(MultiLayerWindow);
-  if (!w)
-    return 0;
-
-  Graph *g = ((MultiLayer*)w)->activeGraph();
-  if (!g)
-    return 0;
-
-  AssociationsDialog* ad = new AssociationsDialog(this);
-  ad->setAttribute(Qt::WA_DeleteOnClose);
-  ad->setGraph(g);
-  ad->initTablesList(tableList(), curve);
-  ad->show();
-  return ad;
-}
-
-void ApplicationWindow::showTitleDialog()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return;
-
-  if (w->isA("MultiLayer")){
-    Graph* g = ((MultiLayer*)w)->activeGraph();
-    if (g){
-      TextDialog* td= new TextDialog(TextDialog::LayerTitle, this,0);
-      td->setGraph(g);
-      td->exec();
-    }
-  } else if (w->isA("Graph3D")) {
-    Plot3DDialog* pd = (Plot3DDialog*)showPlot3dDialog();
-    if (pd)
-      pd->showTitleTab();
-  }
-}
-
-void ApplicationWindow::showAxisTitleDialog()
-{
-  MdiSubWindow* w = activeWindow(MultiLayerWindow);
-  if (!w)
-    return;
-
-  Graph* g = ((MultiLayer*)w)->activeGraph();
-  if (!g)
-    return;
-
-  TextDialog* td = new TextDialog(TextDialog::AxisTitle, this, 0);
-  td->setGraph(g);
-  td->exec();
-}
-
-void ApplicationWindow::showExportASCIIDialog()
-{
-  QString tableName = QString::null;
-  MdiSubWindow* t = activeWindow();
-  if (t && (t->isA("Matrix") || t->inherits("Table") || t->isA("MantidMatrix")))
-  {
-    tableName = t->objectName();
-
-    ExportDialog* ed = new ExportDialog(tableName, this, Qt::WindowContextHelpButtonHint);
-    ed->setAttribute(Qt::WA_DeleteOnClose);
-    ed->exec();
-  }
-}
-
-void ApplicationWindow::exportAllTables(const QString& sep, bool colNames, bool colComments, bool expSelection)
-{
-  QString dir = QFileDialog::getExistingDirectory(this, tr("Choose a directory to export the tables to"), workingDir, QFileDialog::ShowDirsOnly);
-  if (!dir.isEmpty()){
-    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    workingDir = dir;
-
-    bool confirmOverwrite = true;
-    bool success = true;
-    QList<MdiSubWindow *> windows = windowsList();
-    foreach(MdiSubWindow *w, windows){
-      if (w->inherits("Table") || w->isA("Matrix")){
-        QString fileName = dir + "/" + w->objectName() + ".txt";
-        QFile f(fileName);
-        if (f.exists(fileName) && confirmOverwrite){
-          QApplication::restoreOverrideCursor();
-          switch(QMessageBox::question(this, tr("MantidPlot - Overwrite file?"),//Mantid
-              tr("A file called: <p><b>%1</b><p>already exists. "
-                  "Do you want to overwrite it?").arg(fileName), tr("&Yes"), tr("&All"), tr("&Cancel"), 0, 1))
-          {
-          case 0:
-            if (w->inherits("Table"))
-              success = ((Table*)w)->exportASCII(fileName, sep, colNames, colComments, expSelection);
-            else if (w->isA("Matrix"))
-              success = ((Matrix*)w)->exportASCII(fileName, sep, expSelection);
-            break;
-
-          case 1:
-            confirmOverwrite = false;
-            if (w->inherits("Table"))
-              success = ((Table*)w)->exportASCII(fileName, sep, colNames, colComments, expSelection);
-            else if (w->isA("Matrix"))
-              success = ((Matrix*)w)->exportASCII(fileName, sep, expSelection);
-            break;
-
-          case 2:
-            return;
-            break;
-          }
-        } else if (w->inherits("Table"))
-          success = ((Table*)w)->exportASCII(fileName, sep, colNames, colComments, expSelection);
-        else if (w->isA("Matrix"))
-          success = ((Matrix*)w)->exportASCII(fileName, sep, expSelection);
-
-        if (!success)
-          break;
-      }
-    }
-    QApplication::restoreOverrideCursor();
-  }
-}
-
-void ApplicationWindow::exportASCII(const QString& tableName, const QString& sep,
-    bool colNames, bool colComments, bool expSelection)
-{
-  MdiSubWindow* w = window(tableName);
-  if (!w || !(w->isA("Matrix") || w->inherits("Table") || w->isA("MantidMatrix")))
-    return;
-
-  QString selectedFilter;
-  QString fname = QFileDialog::getSaveFileName(this, tr("Choose a filename to save under"),
-      asciiDirPath + "/" + w->objectName(), "*.txt;;*.dat;;*.DAT", &selectedFilter);
-  if (!fname.isEmpty() ){
-    QFileInfo fi(fname);
-    QString baseName = fi.fileName();
-    if (baseName.contains(".")==0)
-      fname.append(selectedFilter.remove("*"));
-
-    asciiDirPath = fi.dirPath(true);
-
-    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    if (w->inherits("Table"))
-      ((Table *)w)->exportASCII(fname, sep, colNames, colComments, expSelection);
-    else if (w->isA("Matrix"))
-      ((Matrix *)w)->exportASCII(fname, sep, expSelection);
-    else if (w->isA("MantidMatrix"))
-    {
-      //call save ascii
-      try
-      {
-        Mantid::API::IAlgorithm_sptr alg =mantidUI->CreateAlgorithm("SaveAscii");
-        alg->setPropertyValue("Filename",fname.toStdString());
-        alg->setPropertyValue("Workspace",tableName.toStdString());
-        alg->execute();
-      }
-      catch(...)
-      {
-      }
-    }
-
-    QApplication::restoreOverrideCursor();
-  }
-}
-
-void ApplicationWindow::showRowsDialog()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  bool ok;
-  int rows = QInputDialog::getInteger(this, tr("MantidPlot - Enter rows number"), tr("Rows"),//Mantid
-      t->numRows(), 0, 1000000, 1, &ok);
-  if ( ok )
-    t->resizeRows(rows);
-}
-
-void ApplicationWindow::showDeleteRowsDialog()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  bool ok;
-  int start_row = QInputDialog::getInteger(this, tr("MantidPlot - Delete rows"), tr("Start row"),//Mantid
-      1, 1, t->numRows(), 1, &ok);
-  if (ok){
-    int end_row = QInputDialog::getInteger(this, tr("MantidPlot - Delete rows"), tr("End row"),//Mantid
-        t->numRows(), 1, t->numRows(), 1, &ok);
-    if (ok)
-      t->deleteRows(start_row, end_row);
-  }
-}
-
-void ApplicationWindow::showColsDialog()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  bool ok;
-  int cols = QInputDialog::getInteger(this, tr("MantidPlot - Enter columns number"), tr("Columns"),//Mantid
-      t->numCols(), 0, 1000000, 1, &ok);
-  if ( ok )
-    t->resizeCols(cols);
-}
-
-void ApplicationWindow::showColumnValuesDialog()
-{
-  Table *w = (Table*)activeWindow(TableWindow);
-  if (!w)
-    return;
-
-  if (w->selectedColumns().count()>0 || w->table()->currentSelection() >= 0){
-    SetColValuesDialog* vd = new SetColValuesDialog(scriptingEnv(), this);
-    vd->setAttribute(Qt::WA_DeleteOnClose);
-    vd->setTable(w);
-    vd->exec();
-  } else
-    QMessageBox::warning(this, tr("MantidPlot - Column selection error"), tr("Please select a column first!"));//Mantid
-}
-
-void ApplicationWindow::recalculateTable()
-{
-  MdiSubWindow* w = activeWindow();
-  if (!w)
-    return;
-
-  if (w->inherits("Table"))
-    ((Table*)w)->calculate();
-  else if (w->isA("Matrix"))
-    ((Matrix*)w)->calculate();
-}
-
-void ApplicationWindow::sortActiveTable()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  if ((int)t->selectedColumns().count()>0)
-    t->sortTableDialog();
-  else
-    QMessageBox::warning(this, "MantidPlot - Column selection error","Please select a column first!");//Mantid
-}
-
-void ApplicationWindow::sortSelection()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  t->sortColumnsDialog();
-}
-
-void ApplicationWindow::normalizeActiveTable()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  if (int(t->selectedColumns().count())>0)
-    t->normalize();
-  else
-    QMessageBox::warning(this, tr("MantidPlot - Column selection error"), tr("Please select a column first!"));//Mantid
-}
-
-void ApplicationWindow::normalizeSelection()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  if (int(t->selectedColumns().count())>0)
-    t->normalizeSelection();
-  else
-    QMessageBox::warning(this, tr("MantidPlot - Column selection error"), tr("Please select a column first!"));//Mantid
-}
-
-void ApplicationWindow::correlate()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  QStringList s = t->selectedColumns();
-  if ((int)s.count() != 2){
-    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select two columns for this operation!"));//Mantid
-    return;
-  }
-
-  Correlation *cor = new Correlation(this, t, s[0], s[1]);
-  cor->run();
-  delete cor;
-}
-
-void ApplicationWindow::autoCorrelate()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  QStringList s = t->selectedColumns();
-  if ((int)s.count() != 1)
-  {
-    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select exactly one columns for this operation!"));//Mantid
-    return;
-  }
-
-  Correlation *cor = new Correlation(this, t, s[0], s[0]);
-  cor->run();
-  delete cor;
-}
-
-void ApplicationWindow::convolute()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  QStringList s = t->selectedColumns();
-  if ((int)s.count() != 2)
-  {
-    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select two columns for this operation:\n the first represents the signal and the second the response function!"));//Mantid
-    return;
-  }
-
-  Convolution *cv = new Convolution(this, t, s[0], s[1]);
-  cv->run();
-  delete cv;
-}
-
-void ApplicationWindow::deconvolute()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  QStringList s = t->selectedColumns();
-  if ((int)s.count() != 2)
-  {
-    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select two columns for this operation:\n the first represents the signal and the second the response function!"));//Mantid
-    return;
-  }
-
-  Deconvolution *dcv = new Deconvolution(this, t, s[0], s[1]);
-  dcv->run();
-  delete dcv;
-}
-
-void ApplicationWindow::showColStatistics()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  if (int(t->selectedColumns().count()) > 0)
-  {
-    QList<int> targets;
-    for (int i=0; i < t->numCols(); i++)
-      if (t->isColumnSelected(i, true))
-        targets << i;
-    newTableStatistics(t, TableStatistics::column, targets)->showNormal();
-  }
-  else
-    QMessageBox::warning(this, tr("MantidPlot - Column selection error"),//Mantid
-        tr("Please select a column first!"));
-}
-
-void ApplicationWindow::showRowStatistics()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  if (t->numSelectedRows() > 0){
-    QList<int> targets;
-    for (int i=0; i < t->numRows(); i++)
-      if (t->isRowSelected(i, true))
-        targets << i;
-    newTableStatistics(t, TableStatistics::row, targets)->showNormal();
-  } else
-    QMessageBox::warning(this, tr("MantidPlot - Row selection error"),//Mantid
-        tr("Please select a row first!"));
-}
-
-void ApplicationWindow::showColMenu(int c)
-{
-  Table *w = (Table*)activeWindow(TableWindow);
-  if (!w)
-    return;
-
-  QMenu contextMenu(this);
-  QMenu plot(this);
-  QMenu specialPlot(this);
-  QMenu fill(this);
-  QMenu sorting(this);
-  QMenu colType(this);
-  colType.setCheckable(true);
-  QMenu panels(this);
-  QMenu stat(this);
-  QMenu norm(this);
-
-  if ((int)w->selectedColumns().count()==1)
-  {
-    w->setSelectedCol(c);
-    plot.addAction(QIcon(getQPixmap("lPlot_xpm")),tr("&Line"), this, SLOT(plotL()));
-    plot.addAction(QIcon(getQPixmap("pPlot_xpm")),tr("&Scatter"), this, SLOT(plotP()));
-    plot.addAction(QIcon(getQPixmap("lpPlot_xpm")),tr("Line + S&ymbol"), this, SLOT(plotLP()));
-
-    specialPlot.addAction(QIcon(getQPixmap("dropLines_xpm")),tr("Vertical &Drop Lines"), this, SLOT(plotVerticalDropLines()));
-    specialPlot.addAction(QIcon(getQPixmap("spline_xpm")),tr("&Spline"), this,SLOT(plotSpline()));
-    specialPlot.addAction(QIcon(getQPixmap("vert_steps_xpm")),tr("&Vertical Steps"), this, SLOT(plotVertSteps()));
-    specialPlot.addAction(QIcon(getQPixmap("hor_steps_xpm")),tr("&Horizontal Steps"), this, SLOT(plotHorSteps()));
-    specialPlot.setTitle(tr("Special Line/Symb&ol"));
-    plot.addMenu(&specialPlot);
-    plot.insertSeparator();
-
-    plot.addAction(QIcon(getQPixmap("vertBars_xpm")),tr("&Columns"), this, SLOT(plotVerticalBars()));
-    plot.addAction(QIcon(getQPixmap("hBars_xpm")),tr("&Rows"), this, SLOT(plotHorizontalBars()));
-    plot.addAction(QIcon(getQPixmap("area_xpm")),tr("&Area"), this, SLOT(plotArea()));
-
-    plot.addAction(QIcon(getQPixmap("pie_xpm")),tr("&Pie"), this, SLOT(plotPie()));
-    plot.insertSeparator();
-
-    plot.addAction(QIcon(getQPixmap("ribbon_xpm")),tr("3D Ribbo&n"), this, SLOT(plot3DRibbon()));
-    plot.addAction(QIcon(getQPixmap("bars_xpm")),tr("3D &Bars"), this, SLOT(plot3DBars()));
-    plot.addAction(QIcon(getQPixmap("scatter_xpm")),tr("3&D Scatter"), this, SLOT(plot3DScatter()));
-    plot.addAction(QIcon(getQPixmap("trajectory_xpm")),tr("3D &Trajectory"), this, SLOT(plot3DTrajectory()));
-
-    plot.insertSeparator();
-
-    stat.addAction(actionBoxPlot);
-    stat.addAction(QIcon(getQPixmap("histogram_xpm")),tr("&Histogram"), this, SLOT(plotHistogram()));
-    stat.addAction(QIcon(getQPixmap("stacked_hist_xpm")),tr("&Stacked Histograms"), this, SLOT(plotStackedHistograms()));
-    stat.setTitle(tr("Statistical &Graphs"));
-    plot.addMenu(&stat);
-
-    plot.setTitle(tr("&Plot"));
-    contextMenu.addMenu(&plot);
-    contextMenu.insertSeparator();
-
-    contextMenu.addAction(QIcon(getQPixmap("cut_xpm")),tr("Cu&t"), w, SLOT(cutSelection()));
-    contextMenu.addAction(QIcon(getQPixmap("copy_xpm")),tr("&Copy"), w, SLOT(copySelection()));
-    contextMenu.addAction(QIcon(getQPixmap("paste_xpm")),tr("Past&e"), w, SLOT(pasteSelection()));
-    contextMenu.insertSeparator();
-
-    QAction * xColID=colType.addAction(QIcon(getQPixmap("x_col_xpm")), tr("&X"), this, SLOT(setXCol()));
-    xColID->setCheckable(true);
-    QAction * yColID=colType.addAction(QIcon(getQPixmap("y_col_xpm")), tr("&Y"), this, SLOT(setYCol()));
-    yColID->setCheckable(true);
-    QAction * zColID=colType.addAction(QIcon(getQPixmap("z_col_xpm")), tr("&Z"), this, SLOT(setZCol()));
-    zColID->setCheckable(true);
-    colType.insertSeparator();
-    QAction * labelID = colType.addAction(QIcon(getQPixmap("set_label_col_xpm")), tr("&Label"), this, SLOT(setLabelCol()));
-    labelID->setCheckable(true);
-    QAction * noneID=colType.addAction(QIcon(getQPixmap("disregard_col_xpm")), tr("&None"), this, SLOT(disregardCol()));
-    noneID->setCheckable(true);
-    colType.insertSeparator();
-    QAction * xErrColID =colType.addAction(tr("X E&rror"), this, SLOT(setXErrCol()));
-    xErrColID->setCheckable(true);
-    QAction * yErrColID = colType.addAction(QIcon(getQPixmap("errors_xpm")), tr("Y &Error"), this, SLOT(setYErrCol()));
-    yErrColID->setCheckable(true);
-    colType.insertSeparator();
-
-
-    if (w->colPlotDesignation(c) == Table::X)
-      xColID->setChecked(true);
-    else if (w->colPlotDesignation(c) == Table::Y)
-      yColID->setChecked(true);
-    else if (w->colPlotDesignation(c) == Table::Z)
-      zColID->setChecked(true);
-    else if (w->colPlotDesignation(c) == Table::xErr)
-      xErrColID->setChecked(true);
-    else if (w->colPlotDesignation(c) == Table::yErr)
-      yErrColID->setChecked(true);
-    else if (w->colPlotDesignation(c) == Table::Label)
-      labelID->setChecked(true);
-    else
-      noneID->setChecked(true);
-
-    actionReadOnlyCol->addTo(&colType);
-    actionReadOnlyCol->setCheckable(true);
-    actionReadOnlyCol->setChecked(w->isReadOnlyColumn(c));
-
-    colType.setTitle(tr("Set As"));
-    contextMenu.addMenu(&colType);
-
-    if (w){
-      contextMenu.insertSeparator();
-
-      contextMenu.addAction(actionShowColumnValuesDialog);
-      contextMenu.addAction(actionTableRecalculate);
-      fill.addAction(actionSetAscValues);
-      fill.addAction(actionSetRandomValues);
-      fill.setTitle(tr("&Fill Column With"));
-      contextMenu.addMenu(&fill);
-
-      norm.addAction(tr("&Column"), w, SLOT(normalizeSelection()));
-      norm.addAction(actionNormalizeTable);
-      norm.setTitle(tr("&Normalize"));
-      contextMenu.addMenu(& norm);
-
-      contextMenu.insertSeparator();
-      contextMenu.addAction(actionShowColStatistics);
-
-      contextMenu.insertSeparator();
-
-      contextMenu.addAction(QIcon(getQPixmap("erase_xpm")), tr("Clea&r"), w, SLOT(clearSelection()));
-      contextMenu.addAction(QIcon(getQPixmap("delete_column_xpm")), tr("&Delete"), w, SLOT(removeCol()));
-      contextMenu.addAction(actionHideSelectedColumns);
-      contextMenu.addAction(actionShowAllColumns);
-      contextMenu.insertSeparator();
-      contextMenu.addAction(getQPixmap("insert_column_xpm"), tr("&Insert"), w, SLOT(insertCol()));
-      contextMenu.addAction(actionAddColToTable);
-      contextMenu.insertSeparator();
-
-      sorting.addAction(QIcon(getQPixmap("sort_ascending_xpm")), tr("&Ascending"), w, SLOT(sortColAsc()));
-      sorting.addAction(QIcon(getQPixmap("sort_descending_xpm")), tr("&Descending"), w, SLOT(sortColDesc()));
-
-      sorting.setTitle(tr("Sort Colu&mn"));
-      contextMenu.addMenu(&sorting);
-
-      contextMenu.addAction(actionSortTable);
-    }
-
-    contextMenu.insertSeparator();
-    contextMenu.addAction(actionShowColumnOptionsDialog);
-  }
-  else if ((int)w->selectedColumns().count()>1)
-  {
-    plot.addAction(QIcon(getQPixmap("lPlot_xpm")),tr("&Line"), this, SLOT(plotL()));
-    plot.addAction(QIcon(getQPixmap("pPlot_xpm")),tr("&Scatter"), this, SLOT(plotP()));
-    plot.addAction(QIcon(getQPixmap("lpPlot_xpm")),tr("Line + S&ymbol"), this,SLOT(plotLP()));
-
-    specialPlot.addAction(QIcon(getQPixmap("dropLines_xpm")),tr("Vertical &Drop Lines"), this, SLOT(plotVerticalDropLines()));
-    specialPlot.addAction(QIcon(getQPixmap("spline_xpm")),tr("&Spline"), this, SLOT(plotSpline()));
-    specialPlot.addAction(QIcon(getQPixmap("vert_steps_xpm")),tr("&Vertical Steps"), this, SLOT(plotVertSteps()));
-    specialPlot.addAction(QIcon(getQPixmap("hor_steps_xpm")),tr("&Vertical Steps"), this, SLOT(plotHorSteps()));
-    specialPlot.setTitle(tr("Special Line/Symb&ol"));
-    plot.addMenu(&specialPlot);
-    plot.insertSeparator();
-
-    plot.addAction(QIcon(getQPixmap("vertBars_xpm")),tr("&Columns"), this, SLOT(plotVerticalBars()));
-    plot.addAction(QIcon(getQPixmap("hBars_xpm")),tr("&Rows"), this, SLOT(plotHorizontalBars()));
-    plot.addAction(QIcon(getQPixmap("area_xpm")),tr("&Area"), this, SLOT(plotArea()));
-    plot.addAction(QIcon(getQPixmap("vectXYXY_xpm")),tr("Vectors &XYXY"), this, SLOT(plotVectXYXY()));
-    plot.insertSeparator();
-
-    stat.addAction(actionBoxPlot);
-    stat.addAction(QIcon(getQPixmap("histogram_xpm")),tr("&Histogram"), this, SLOT(plotHistogram()));
-    stat.addAction(QIcon(getQPixmap("stacked_hist_xpm")),tr("&Stacked Histograms"), this, SLOT(plotStackedHistograms()));
-    stat.setTitle(tr("Statistical &Graphs"));
-    plot.addMenu(&stat);
-
-    panels.addAction(QIcon(getQPixmap("panel_v2_xpm")),tr("&Vertical 2 Layers"), this, SLOT(plot2VerticalLayers()));
-    panels.addAction(QIcon(getQPixmap("panel_h2_xpm")),tr("&Horizontal 2 Layers"), this, SLOT(plot2HorizontalLayers()));
-    panels.addAction(QIcon(getQPixmap("panel_4_xpm")),tr("&4 Layers"), this, SLOT(plot4Layers()));
-    panels.addAction(QIcon(getQPixmap("stacked_xpm")),tr("&Stacked Layers"), this, SLOT(plotStackedLayers()));
-    panels.setTitle(tr("Pa&nel"));
-    plot.addMenu(&panels);
-
-    plot.setTitle(tr("&Plot"));
-    contextMenu.addMenu(&plot);
-    contextMenu.insertSeparator();
-    contextMenu.addAction(QIcon(getQPixmap("cut_xpm")),tr("Cu&t"), w, SLOT(cutSelection()));
-    contextMenu.addAction(QIcon(getQPixmap("copy_xpm")),tr("&Copy"), w, SLOT(copySelection()));
-    contextMenu.addAction(QIcon(getQPixmap("paste_xpm")),tr("Past&e"), w, SLOT(pasteSelection()));
-    contextMenu.insertSeparator();
-
-    if (w){
-      contextMenu.addAction(QIcon(getQPixmap("erase_xpm")),tr("Clea&r"), w, SLOT(clearSelection()));
-      contextMenu.addAction(QIcon(getQPixmap("close_xpm")),tr("&Delete"), w, SLOT(removeCol()));
-      contextMenu.addAction(actionHideSelectedColumns);
-      contextMenu.addAction(actionShowAllColumns);
-      contextMenu.insertSeparator();
-      contextMenu.addAction(tr("&Insert"), w, SLOT(insertCol()));
-      contextMenu.addAction(actionAddColToTable);
-      contextMenu.insertSeparator();
-    }
-
-    colType.addAction(actionSetXCol);
-    colType.addAction(actionSetYCol);
-    colType.addAction(actionSetZCol);
-    colType.insertSeparator();
-    colType.addAction(actionSetLabelCol);
-    colType.addAction(actionDisregardCol);
-    colType.insertSeparator();
-    colType.addAction(actionSetXErrCol);
-    colType.addAction(actionSetYErrCol);
-    colType.insertSeparator();
-    colType.addAction(tr("&Read-only"), this, SLOT(setReadOnlyColumns()));
-    colType.addAction(tr("Read/&Write"), this, SLOT(setReadWriteColumns()));
-    colType.setTitle(tr("Set As"));
-    contextMenu.addMenu(&colType);
-
-    if (w)
-    {
-      contextMenu.insertSeparator();
-
-      fill.addAction(actionSetAscValues);
-      fill.addAction(actionSetRandomValues);
-      fill.setTitle(tr("&Fill Columns With"));
-      contextMenu.addMenu(&fill);
-
-      norm.addAction(actionNormalizeSelection);
-      norm.addAction(actionNormalizeTable);
-      norm.setTitle(tr("&Normalize"));
-      contextMenu.addMenu(&norm);
-
-      contextMenu.insertSeparator();
-      contextMenu.addAction(actionSortSelection);
-      contextMenu.addAction(actionSortTable);
-      contextMenu.insertSeparator();
-      contextMenu.addAction(actionShowColStatistics);
-    }
-  }
-
-  QPoint posMouse=QCursor::pos();
-  contextMenu.exec(posMouse);
-}
-
-void ApplicationWindow::plot2VerticalLayers()
-{
-  multilayerPlot(1, 2, defaultCurveStyle);
-}
-
-void ApplicationWindow::plot2HorizontalLayers()
-{
-  multilayerPlot(2, 1, defaultCurveStyle);
-}
-
-void ApplicationWindow::plot4Layers()
-{
-  multilayerPlot(2, 2, defaultCurveStyle);
-}
-
-void ApplicationWindow::plotStackedLayers()
-{
-  multilayerPlot(1, -1, defaultCurveStyle);
-}
-
-void ApplicationWindow::plotStackedHistograms()
-{
-  multilayerPlot(1, -1, Graph::Histogram);
-}
-
-void ApplicationWindow::showMatrixDialog()
-{
-  Matrix *m = (Matrix*)activeWindow(MatrixWindow);
-  if (!m)
-    return;
-
-  MatrixDialog* md = new MatrixDialog(this);
-  md->setAttribute(Qt::WA_DeleteOnClose);
-  md->setMatrix (m);
-  md->exec();
-}
-
-void ApplicationWindow::showMatrixSizeDialog()
-{
-  Matrix *m = (Matrix*)activeWindow(MatrixWindow);
-  if (!m)
-    return;
-
-  MatrixSizeDialog* md = new MatrixSizeDialog(m, this);
-  md->setAttribute(Qt::WA_DeleteOnClose);
-  md->exec();
-}
-
-void ApplicationWindow::showMatrixValuesDialog()
-{
-  Matrix *m = (Matrix*)activeWindow(MatrixWindow);
-  if (!m)
-    return;
-
-  MatrixValuesDialog* md = new MatrixValuesDialog(scriptingEnv(), this);
-  md->setAttribute(Qt::WA_DeleteOnClose);
-  md->setMatrix(m);
-  md->exec();
-}
-
-void ApplicationWindow::showColumnOptionsDialog()
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  if(t->selectedColumns().count()>0) {
-    TableDialog* td = new TableDialog(t, this);
-    td->setAttribute(Qt::WA_DeleteOnClose);
-    td->exec();
-  } else
-    QMessageBox::warning(this, tr("MantidPlot"), tr("Please select a column first!"));//Mantid
-}
-
-void ApplicationWindow::showGeneralPlotDialog()
-{
-  MdiSubWindow* plot = activeWindow();
-  if (!plot)
-    return;
-
-  if (plot->isA("MultiLayer") && ((MultiLayer*)plot)->layers())
-    showPlotDialog();
-  else if (plot->isA("Graph3D")){
-    QDialog* gd = showScaleDialog();
-    ((Plot3DDialog*)gd)->showGeneralTab();
-  }
-}
-
-void ApplicationWindow::showAxisDialog()
-{
-  MdiSubWindow* plot = activeWindow();
-  if (!plot)
-    return;
-
-  QDialog* gd = showScaleDialog();
-  if (gd && plot->isA("MultiLayer") && ((MultiLayer*)plot)->layers())
-    ((AxesDialog*)gd)->showAxesPage();
-  else if (gd && plot->isA("Graph3D"))
-    ((Plot3DDialog*)gd)->showAxisTab();
-}
-
-void ApplicationWindow::showGridDialog()
-{
-  AxesDialog* gd = (AxesDialog*)showScaleDialog();
-  if (gd)
-    gd->showGridPage();
-}
-
-QDialog* ApplicationWindow::showScaleDialog()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return 0;
-
-  if (w->isA("MultiLayer")){
-    if (((MultiLayer*)w)->isEmpty())
-      return 0;
-
-    Graph* g = ((MultiLayer*)w)->activeGraph();
-    if (g->isPiePlot()){
-      QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("This functionality is not available for pie plots!"));//Mantid
-      return 0;
-    }
-
-    AxesDialog* ad = new AxesDialog(this);
-    ad->setGraph(g);
-    ad->exec();
-    return ad;
-  } else if (w->isA("Graph3D"))
-    return showPlot3dDialog();
-
-  return 0;
-}
-
-AxesDialog* ApplicationWindow::showScalePageFromAxisDialog(int axisPos)
-{
-  AxesDialog* gd = (AxesDialog*)showScaleDialog();
-  if (gd)
-    gd->setCurrentScale(axisPos);
-
-  return gd;
-}
-
-AxesDialog* ApplicationWindow::showAxisPageFromAxisDialog(int axisPos)
-{
-  AxesDialog* gd = (AxesDialog*)showScaleDialog();
-  if (gd){
-    gd->showAxesPage();
-    gd->setCurrentScale(axisPos);
-  }
-  return gd;
-}
-
-QDialog* ApplicationWindow::showPlot3dDialog()
-{
-  Graph3D *g = (Graph3D*)activeWindow(Plot3DWindow);
-  if (!g)
-    return 0;
-
-  if (!g->hasData()){
-    QApplication::restoreOverrideCursor();
-    QMessageBox::warning(this, tr("MantidPlot - Warning"),//Mantid
-        tr("Not available for empty 3D surface plots!"));
-    return 0;
-  }
-
-  Plot3DDialog* pd = new Plot3DDialog(this);
-  pd->setPlot(g);
-  pd->show();
-  return pd;
-}
-
-void ApplicationWindow::showPlotDialog(int curveKey)
-{
-  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!w)
-    return;
-
-  PlotDialog* pd = new PlotDialog(d_extended_plot_dialog, this);
-  pd->setAttribute(Qt::WA_DeleteOnClose);
-  pd->insertColumnsList(columnsList(Table::All));
-  pd->setMultiLayer(w);
-  if (curveKey >= 0){
-    Graph *g = w->activeGraph();
-    if (g)
-      pd->selectCurve(g->curveIndex(curveKey));
-  }
-  pd->initFonts(plotTitleFont, plotAxesFont, plotNumbersFont, plotLegendFont);
-  pd->showAll(d_extended_plot_dialog);
-  pd->show();
-}
-
-void ApplicationWindow::showCurvePlotDialog()
-{
-  showPlotDialog(actionShowCurvePlotDialog->data().toInt());
-}
-
-void ApplicationWindow::showCurveContextMenu(int curveKey)
-{
-  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!w)
-    return;
-
-  Graph *g = w->activeGraph();
-  DataCurve *c = (DataCurve *)g->curve(g->curveIndex(curveKey));
-  if (!c || !c->isVisible())
-    return;
-
-  QMenu curveMenu(this);
-  curveMenu.addAction(c->title().text(), this, SLOT(showCurvePlotDialog()));
-  curveMenu.insertSeparator();
-
-  curveMenu.addAction(actionHideCurve);
-  actionHideCurve->setData(curveKey);
-
-  if (g->visibleCurves() > 1 && c->type() == Graph::Function){
-    curveMenu.addAction(actionHideOtherCurves);
-    actionHideOtherCurves->setData(curveKey);
-  } else if (c->type() != Graph::Function) {
-    if ((g->visibleCurves() - c->errorBarsList().count()) > 1) {
-      curveMenu.addAction(actionHideOtherCurves);
-      actionHideOtherCurves->setData(curveKey);
-    }
-  }
-
-  if (g->visibleCurves() != g->curves())
-    curveMenu.addAction(actionShowAllCurves);
-  curveMenu.insertSeparator();
-
-  if (g->activeTool()){
-    if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector ||
-        g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker)
-      curveMenu.addAction(actionCopySelection);
-  }
-
-  if (c->type() == Graph::Function){
-    curveMenu.insertSeparator();
-    curveMenu.addAction(actionEditFunction);
-    actionEditFunction->setData(curveKey);
-  } else if (c->type() != Graph::ErrorBars){
-    if (g->activeTool()){
-      if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector ||
-          g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker){
-        curveMenu.addAction(actionCutSelection);
-        curveMenu.addAction(actionPasteSelection);
-        curveMenu.addAction(actionClearSelection);
-        curveMenu.insertSeparator();
-        if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector){
-          QAction *act = new QAction(tr("Set Display Range"), this);
-          connect(act, SIGNAL(activated()), (RangeSelectorTool *)g->activeTool(), SLOT(setCurveRange()));
-          curveMenu.addAction(act);
-        }
-      }
-    }
-
-    curveMenu.addAction(actionEditCurveRange);
-    actionEditCurveRange->setData(curveKey);
-
-    curveMenu.addAction(actionCurveFullRange);
-    if (c->isFullRange())
-      actionCurveFullRange->setDisabled(true);
-    else
-      actionCurveFullRange->setEnabled(true);
-    actionCurveFullRange->setData(curveKey);
-
-    curveMenu.insertSeparator();
-  }
-
-  curveMenu.addAction(actionShowCurveWorksheet);
-  actionShowCurveWorksheet->setData(curveKey);
-
-  curveMenu.addAction(actionShowCurvePlotDialog);
-  actionShowCurvePlotDialog->setData(curveKey);
-
-  curveMenu.insertSeparator();
-
-  curveMenu.addAction(actionRemoveCurve);
-  actionRemoveCurve->setData(curveKey);
-  curveMenu.exec(QCursor::pos());
-}
-
-void ApplicationWindow::showAllCurves()
-{
-  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!w)
-    return;
-
-  Graph* g = w->activeGraph();
-  if (!g)
-    return;
-
-  for(int i=0; i< g->curves(); i++)
-    g->showCurve(i);
-  g->replot();
-}
-
-void ApplicationWindow::hideOtherCurves()
-{
-  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!w)
-    return;
-
-  Graph* g = w->activeGraph();
-  if (!g)
-    return;
-
-  int curveKey = actionHideOtherCurves->data().toInt();
-  for(int i=0; i< g->curves(); i++)
-    g->showCurve(i, false);
-
-  g->showCurve(g->curveIndex(curveKey));
-  g->replot();
-}
-
-void ApplicationWindow::hideCurve()
-{
-  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!w)
-    return;
-
-  Graph* g = w->activeGraph();
-  if (!g)
-    return;
-
-  int curveKey = actionHideCurve->data().toInt();
-  g->showCurve(g->curveIndex(curveKey), false);
-}
-
-void ApplicationWindow::removeCurve()
-{
-  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!w)
-    return;
-
-  Graph* g = w->activeGraph();
-  if (!g)
-    return;
-
-  int curveKey = actionRemoveCurve->data().toInt();
-  g->removeCurve(g->curveIndex(curveKey));
-  g->updatePlot();
-}
-
-void ApplicationWindow::showCurveWorksheet(Graph *g, int curveIndex)
-{
-  if (!g)
-    return;
-
-  const QwtPlotItem *it = g->plotItem(curveIndex);
-  if (!it)
-    return;
-
-  if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram){
-    Spectrogram *sp = (Spectrogram *)it;
-    if (sp->matrix())
-      sp->matrix()->showMaximized();
-  } else if (((PlotCurve *)it)->type() == Graph::Function)
-    g->createTable((PlotCurve *)it);
-  else {
-    showTable(it->title().text());
-    if (g->activeTool() && g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker)
-      ((DataPickerTool *)g->activeTool())->selectTableRow();
-  }
-}
-
-void ApplicationWindow::showCurveWorksheet()
-{
-  MultiLayer *w = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!w)
-    return;
-
-  Graph* g = w->activeGraph();
-  if (!g)
-    return;
-
-  int curveKey = actionShowCurveWorksheet->data().toInt();
-  showCurveWorksheet(g, g->curveIndex(curveKey));
-}
-
-void ApplicationWindow::zoomIn()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  if (plot->isEmpty())
-  {
-    QMessageBox::warning(this, tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    btnPointer->setOn(true);
-    return;
-  }
-
-  if ((Graph*)plot->activeGraph()->isPiePlot())
-  {
-    if (btnZoomIn->isOn())
-      QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-          tr("This functionality is not available for pie plots!"));
-    btnPointer->setOn(true);
-    return;
-  }
-
-  QList<Graph *> layers = plot->layersList();
-  foreach(Graph *g, layers){
-    if (!g->isPiePlot())
-      g->zoom(true);
-  }
-}
-
-void ApplicationWindow::zoomOut()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  if (plot->isEmpty() || (Graph*)plot->activeGraph()->isPiePlot())
-    return;
-
-  ((Graph*)plot->activeGraph())->zoomOut();
-  btnPointer->setOn(true);
-}
-
-void ApplicationWindow::setAutoScale()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"));
-    return;
-  }
-
-  Graph *g = (Graph*)plot->activeGraph();
-  if (g)
-    g->setAutoScale();
-}
-
-void ApplicationWindow::removePoints()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty())
-  {
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  Graph* g = (Graph*)plot->activeGraph();
-  if (!g || !g->validCurvesDataSize())
-  {
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  if (g->isPiePlot())
-  {
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("This functionality is not available for pie plots!"));
-    btnPointer->setChecked(true);
-    return;
-  }
-  else
-  {
-    switch(QMessageBox::warning (this,tr("MantidPlot"),//Mantid
-        tr("This will modify the data in the worksheets!\nAre you sure you want to continue?"),
-        tr("Continue"),tr("Cancel"),0,1))
-    {
-    case 0:
-      g->setActiveTool(new DataPickerTool(g, this, DataPickerTool::Remove, info, SLOT(setText(const QString&))));
-      displayBar->show();
-      break;
-
-    case 1:
-      btnPointer->setChecked(true);
-      break;
-    }
-  }
-}
-
-void ApplicationWindow::movePoints()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  Graph* g = (Graph*)plot->activeGraph();
-  if (!g || !g->validCurvesDataSize()){
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  if (g->isPiePlot()){
-    QMessageBox::warning(this, tr("MantidPlot - Warning"),//Mantid
-        tr("This functionality is not available for pie plots!"));
-
-    btnPointer->setChecked(true);
-    return;
-  } else {
-    switch(QMessageBox::warning (this, tr("MantidPlot"),//Mantid
-        tr("This will modify the data in the worksheets!\nAre you sure you want to continue?"),
-        tr("Continue"), tr("Cancel"), 0, 1))
-    {
-    case 0:
-      if (g){
-        g->setActiveTool(new DataPickerTool(g, this, DataPickerTool::Move, info, SLOT(setText(const QString&))));
-        displayBar->show();
-      }
-      break;
-
-    case 1:
-      btnPointer->setChecked(true);
-      break;
-    }
-  }
-}
-
-void ApplicationWindow::exportPDF()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return;
-
-  if (w->isA("MultiLayer") && ((MultiLayer *)w)->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"));
-    return;
-  }
-
-  QString fname = QFileDialog::getSaveFileName(this, tr("Choose a filename to save under"), workingDir, "*.pdf");
-  if (!fname.isEmpty() ){
-    QFileInfo fi(fname);
-    QString baseName = fi.fileName();
-    if (!baseName.contains("."))
-      fname.append(".pdf");
-
-    workingDir = fi.dirPath(true);
-
-    QFile f(fname);
-    if (!f.open(QIODevice::WriteOnly)){
-      QMessageBox::critical(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));
-      return;
-    }
-
-    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    w->exportPDF(fname);
-    QApplication::restoreOverrideCursor();
-  }
-}
-
-//print active window
-void ApplicationWindow::print()
-{
-  MdiSubWindow* w = activeWindow();
-  if (!w)
-    return;
-
-  if (w->isA("MultiLayer") && ((MultiLayer *)w)->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"));
-    return;
-  }
-  w->print();
-}
-
-void ApplicationWindow::printAllPlots()
-{
-  QPrinter printer;
-  printer.setOrientation(QPrinter::Landscape);
-  printer.setColorMode (QPrinter::Color);
-  printer.setFullPage(true);
-
-  if (printer.setup())
-  {
-    QPainter *paint = new QPainter (&printer);
-
-    int plots = 0;
-    QList<MdiSubWindow *> windows = windowsList();
-    foreach(MdiSubWindow *w, windows){
-      if (w->isA("MultiLayer"))
-        plots++;
-    }
-
-    printer.setMinMax (0, plots);
-    printer.setFromTo (0, plots);
-
-    foreach(MdiSubWindow *w, windows){
-      if (w->isA("MultiLayer") && printer.newPage())
-        ((MultiLayer*)w)->printAllLayers(paint);
-    }
-    paint->end();
-    delete paint;
-  }
-}
-
-void ApplicationWindow::showExpGrowthDialog()
-{
-  showExpDecayDialog(-1);
-}
-
-void ApplicationWindow::showExpDecayDialog()
-{
-  showExpDecayDialog(1);
-}
-
-void ApplicationWindow::showExpDecayDialog(int type)
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g || !g->validCurvesDataSize())
-    return;
-
-  ExpDecayDialog *edd = new ExpDecayDialog(type, this);
-  edd->setAttribute(Qt::WA_DeleteOnClose);
-  connect (g, SIGNAL(destroyed()), edd, SLOT(close()));
-
-  edd->setGraph(g);
-  edd->show();
-}
-
-void ApplicationWindow::showTwoExpDecayDialog()
-{
-  showExpDecayDialog(2);
-}
-
-void ApplicationWindow::showExpDecay3Dialog()
-{
-  showExpDecayDialog(3);
-}
-
-void ApplicationWindow::showFitDialog()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return;
-
-  MultiLayer* plot = 0;
-  if(w->isA("MultiLayer"))
-    plot = (MultiLayer*)w;
-  else if(w->inherits("Table"))
-    plot = multilayerPlot((Table *)w, ((Table *)w)->drawableColumnSelection(), Graph::LineSymbols);
-
-  if (!plot)
-    return;
-
-  Graph* g = (Graph*)plot->activeGraph();
-  if (!g || !g->validCurvesDataSize())
-    return;
-
-  FitDialog *fd = new FitDialog(g, this);
-  fd->setAttribute(Qt::WA_DeleteOnClose);
-  connect (plot, SIGNAL(destroyed()), fd, SLOT(close()));
-
-  fd->setSrcTables(tableList());
-  fd->show();
-  fd->resize(fd->minimumSize());
-}
-
-void ApplicationWindow::showFilterDialog(int filter)
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if ( g && g->validCurvesDataSize())
-  {
-    FilterDialog *fd = new FilterDialog(filter, this);
-    fd->setAttribute(Qt::WA_DeleteOnClose);
-    fd->setGraph(g);
-    fd->exec();
-  }
-}
-
-void ApplicationWindow::lowPassFilterDialog()
-{
-  showFilterDialog(FFTFilter::LowPass);
-}
-
-void ApplicationWindow::highPassFilterDialog()
-{
-  showFilterDialog(FFTFilter::HighPass);
-}
-
-void ApplicationWindow::bandPassFilterDialog()
-{
-  showFilterDialog(FFTFilter::BandPass);
-}
-
-void ApplicationWindow::bandBlockFilterDialog()
-{
-  showFilterDialog(FFTFilter::BandBlock);
-}
-
-void ApplicationWindow::showFFTDialog()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return;
-
-  FFTDialog *sd = 0;
-  if (w->isA("MultiLayer")) {
-    Graph* g = ((MultiLayer*)w)->activeGraph();
-    if ( g && g->validCurvesDataSize() ){
-      sd = new FFTDialog(FFTDialog::onGraph, this);
-      sd->setAttribute(Qt::WA_DeleteOnClose);
-      sd->setGraph(g);
-    }
-  } else if (w->inherits("Table")) {
-    sd = new FFTDialog(FFTDialog::onTable, this);
-    sd->setAttribute(Qt::WA_DeleteOnClose);
-    sd->setTable((Table*)w);
-  } else if (w->inherits("Matrix")) {
-    sd = new FFTDialog(FFTDialog::onMatrix, this);
-    sd->setAttribute(Qt::WA_DeleteOnClose);
-    sd->setMatrix((Matrix*)w);
-  }
-
-  if (sd)
-    sd->exec();
-}
-
-void ApplicationWindow::showSmoothDialog(int m)
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g || !g->validCurvesDataSize())
-    return;
-
-  SmoothCurveDialog *sd = new SmoothCurveDialog(m, this);
-  sd->setAttribute(Qt::WA_DeleteOnClose);
-  sd->setGraph(g);
-  sd->exec();
-}
-
-void ApplicationWindow::showSmoothSavGolDialog()
-{
-  showSmoothDialog(SmoothFilter::SavitzkyGolay);
-}
-
-void ApplicationWindow::showSmoothFFTDialog()
-{
-  showSmoothDialog(SmoothFilter::FFT);
-}
-
-void ApplicationWindow::showSmoothAverageDialog()
-{
-  showSmoothDialog(SmoothFilter::Average);
-}
-
-void ApplicationWindow::showInterpolationDialog()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g || !g->validCurvesDataSize())
-    return;
-
-  InterpolationDialog *id = new InterpolationDialog(this);
-  id->setAttribute(Qt::WA_DeleteOnClose);
-  connect (g, SIGNAL(destroyed()), id, SLOT(close()));
-  id->setGraph(g);
-  id->show();
-}
-
-void ApplicationWindow::showFitPolynomDialog()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g || !g->validCurvesDataSize())
-    return;
-
-  PolynomFitDialog *pfd = new PolynomFitDialog(this);
-  pfd->setAttribute(Qt::WA_DeleteOnClose);
-  connect(g, SIGNAL(destroyed()), pfd, SLOT(close()));
-  pfd->setGraph(g);
-  pfd->show();
-}
-
-void ApplicationWindow::updateLog(const QString& result)
-{	
-  if ( !result.isEmpty() ){
-    current_folder->appendLogInfo(result);
-    showResults(true);
-    emit modified();
-  }
-}
-
-void ApplicationWindow::showIntegrationDialog()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g)
-    return;
-
-  IntDialog *id = new IntDialog(this, g);
-  id->exec();
-}
-
-/**
- * Sets the visibilty of the log window. If it is shown then
- * the results are scrolled to the bottom
- */
-void ApplicationWindow::showLogWindow(bool show)
-{
-  logWindow->setVisible(show);
-  if( show )
-  {
-    QTextCursor cur = results->textCursor();
-    cur.movePosition(QTextCursor::End);
-    results->setTextCursor(cur);
-  }
-}
-
-void ApplicationWindow::showResults(bool ok)
-{
-  if (ok)
-  {
-    if (!current_folder->logInfo().isEmpty())
-      results->setText(current_folder->logInfo());
-    else
-      results->setText(tr("Sorry, there are no results to display!"));
-  }
-  showLogWindow(ok);
-}
-
-void ApplicationWindow::showResults(const QString& s, bool ok)
-{
-  current_folder->appendLogInfo(s);
-
-  QString logInfo = current_folder->logInfo();
-  if (!logInfo.isEmpty())
-    results->setText(logInfo);
-  showResults(ok);
-}
-
-void ApplicationWindow::showScreenReader()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  QList<Graph *> layers = plot->layersList();
-  foreach(Graph *g, layers)
-  g->setActiveTool(new ScreenPickerTool(g, info, SLOT(setText(const QString&))));
-
-  displayBar->show();
-}
-
-void ApplicationWindow::drawPoints()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  QList<Graph *> layers = plot->layersList();
-  foreach(Graph *g, layers)
-  g->setActiveTool(new DrawPointTool(this, g, info, SLOT(setText(const QString&))));
-
-  displayBar->show();
-}
-
-void ApplicationWindow::showRangeSelectors()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty()){
-    QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("There are no plot layers available in this window!"));//Mantid
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  Graph* g = (Graph*)plot->activeGraph();
-  if (!g)
-    return;
-
-  if (!g->curves()){
-    QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("There are no curves available on this plot!"));//Mantid
-    btnPointer->setChecked(true);
-    return;
-  } else if (g->isPiePlot()) {
-    QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("This functionality is not available for pie plots!"));//Mantid
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  displayBar->show();
-  g->enableRangeSelectors(info, SLOT(setText(const QString&)));
-}
-
-void ApplicationWindow::showCursor()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  if ((Graph*)plot->activeGraph()->isPiePlot()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("This functionality is not available for pie plots!"));
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  QList<Graph *> layers = plot->layersList();
-  foreach(Graph *g, layers){
-    if (g->isPiePlot() || !g->curves())
-      continue;
-    if (g->validCurvesDataSize())
-      g->setActiveTool(new DataPickerTool(g, this, DataPickerTool::Display, info, SLOT(setText(const QString&))));
-  }
-  displayBar->show();
-}
-
-/**  Switch on the multi-peak selecting tool for fitting
- * with the Fit algorithm of multiple peaks on a single background
- */
-void ApplicationWindow::selectMultiPeak()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  if ((Graph*)plot->activeGraph()->isPiePlot()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("This functionality is not available for pie plots!"));
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  QList<Graph *> layers = plot->layersList();
-  foreach(Graph *g, layers){
-    if (g->isPiePlot() || !g->curves())
-    {
-      continue;
-    }
-    if (g->validCurvesDataSize())
-    {
-      PeakPickerTool* ppicker = new PeakPickerTool(g, mantidUI);
-      g->setActiveTool(ppicker);
-      connect(plot,SIGNAL(windowStateChanged(Qt::WindowStates, Qt::WindowStates)),ppicker,SLOT(windowStateChanged(Qt::WindowStates, Qt::WindowStates)));
-    }
-  }
-
-}
-
-void ApplicationWindow::newLegend()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    return;
-  }
-
-  Graph* g = (Graph*)plot->activeGraph();
-  if ( g )
-    g->newLegend();
-}
-
-void ApplicationWindow::addTimeStamp()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty())
-  {
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    return;
-  }
-
-  Graph* g = (Graph*)plot->activeGraph();
-  if ( g )
-    g->addTimeStamp();
-}
-
-void ApplicationWindow::disableAddText()
-{
-  actionAddText->setChecked(false);
-  showTextDialog();
-}
-
-void ApplicationWindow::addText()
-{
-  if (!btnPointer->isOn())
-    btnPointer->setOn(TRUE);
-
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  Graph *g = (Graph*)plot->activeGraph();
-  if (g)
-    g->drawText(true);
-}
-
-void ApplicationWindow::addImage()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    return;
-  }
-
-  Graph* g = (Graph*)plot->activeGraph();
-  if (!g)
-    return;
-
-  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 - Insert image from file"), imagesDirPath, filter);//Mantid
-  if ( !fn.isEmpty() ){
-    QFileInfo fi(fn);
-    imagesDirPath = fi.dirPath(true);
-
-    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    g->addImage(fn);
-    QApplication::restoreOverrideCursor();
-  }
-}
-
-void ApplicationWindow::drawLine()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty())
-  {
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  Graph* g = (Graph*)plot->activeGraph();
-  if (g)
-  {
-    g->drawLine(true);
-    emit modified();
-  }
-}
-
-void ApplicationWindow::drawArrow()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty())
-  {
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-
-    btnPointer->setOn(true);
-    return;
-  }
-
-  Graph* g = (Graph*)plot->activeGraph();
-  if (g)
-  {
-    g->drawLine(true, 1);
-    emit modified();
-  }
-}
-
-void ApplicationWindow::showImageDialog()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (g)
-  {
-    ImageMarker *im = (ImageMarker *) g->selectedMarkerPtr();
-    if (!im)
-      return;
-
-    ImageDialog *id = new ImageDialog(this);
-    id->setAttribute(Qt::WA_DeleteOnClose);
-    connect (id, SIGNAL(setGeometry(int, int, int, int)),
-        g, SLOT(updateImageMarker(int, int, int, int)));
-    //		id->setIcon(getQPixmap("logo_xpm"));
-    id->setOrigin(im->origin());
-    id->setSize(im->size());
-    id->exec();
-  }
-}
-
-void ApplicationWindow::showLayerDialog()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if(plot->isEmpty())
-  {
-    QMessageBox::warning(this, tr("MantidPlot - Warning"),//Mantid
-        tr("There are no plot layers available in this window."));
-    return;
-  }
-
-  LayerDialog *id=new LayerDialog(this);
-  id->setAttribute(Qt::WA_DeleteOnClose);
-  id->setMultiLayer(plot);
-  id->exec();
-}
-
-void ApplicationWindow::showTextDialog()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if ( g ){
-    LegendWidget *l = (LegendWidget *) g->selectedText();
-    if (!l)
-      return;
-
-    TextDialog *td = new TextDialog(TextDialog::TextMarker, this, 0);
-    td->setLegendWidget(l);
-    td->exec();
-  }
-}
-
-void ApplicationWindow::showLineDialog()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (g){
-    ArrowMarker *lm = (ArrowMarker *) g->selectedMarkerPtr();
-    if (!lm)
-      return;
-
-    LineDialog *ld = new LineDialog(lm, this);
-    ld->exec();
-  }
-}
-
-void ApplicationWindow::addColToTable()
-{
-  Table* m = (Table*)activeWindow(TableWindow);
-  if ( m )
-    m->addCol();
-}
-
-void ApplicationWindow::clearSelection()
-{
-  if(lv->hasFocus()){
-    deleteSelectedItems();
-    return;
-  }
-
-  MdiSubWindow* m = activeWindow();
-  if (!m)
-    return;
-
-  if (m->inherits("Table"))
-    ((Table*)m)->clearSelection();
-  else if (m->isA("Matrix"))
-    ((Matrix*)m)->clearSelection();
-  else if (m->isA("MultiLayer")){
-    Graph* g = ((MultiLayer*)m)->activeGraph();
-    if (!g)
-      return;
-
-    if (g->activeTool()){
-      if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector)
-        ((RangeSelectorTool *)g->activeTool())->clearSelection();
-      else if (g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker)
-        ((DataPickerTool *)g->activeTool())->removePoint();
-    } else if (g->titleSelected())
-      g->removeTitle();
-    else if (g->markerSelected())
-      g->removeMarker();
-  }
-  else if (m->isA("Note"))
-    ((Note*)m)->editor()->clear();
-  emit modified();
-}
-
-void ApplicationWindow::copySelection()
-{
-  if(results->hasFocus()){
-    results->copy();
-    return;
-  } else if(info->hasFocus()) {
-    info->copy();
-    return;
-  }
-  else if (m_interpreterDock->hasFocus())
-  {
-    m_scriptInterpreter->copy();
-    return;
-  }
-  MdiSubWindow* m = activeWindow();
-  if (!m)
-    return;
-
-    if (m->inherits("Table"))
-    ((Table*)m)->copySelection();
-  else if (m->isA("Matrix"))
-    ((Matrix*)m)->copySelection();
-  else if (m->isA("MultiLayer")){
-    MultiLayer* plot = (MultiLayer*)m;
-    if (!plot || plot->layers() == 0)
-      return;
-
-    Graph* g = (Graph*)plot->activeGraph();
-    if (!g)
-      return;
-
-    if (g->activeTool()){
-      if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector)
-      {
-        ((RangeSelectorTool *)g->activeTool())->copySelection();
-      }
-      else if (g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker)
-      {
-        ((DataPickerTool *)g->activeTool())->copySelection();
-      }
-    } else if (g->markerSelected()){
-      copyMarker();
-    } else
-    {
-      copyActiveLayer();
-    }
-
-    plot->copyAllLayers();
-  }
-  else if (m->isA("Note"))
-    ((Note*)m)->editor()->copy();
-  else
-    mantidUI->copyValues();//Mantid
-}
-
-void ApplicationWindow::cutSelection()
-{
-  
-  MdiSubWindow* m = activeWindow();
-  if (!m)
-    return;
-
-  if (m->inherits("Table"))
-    ((Table*)m)->cutSelection();
-  else if (m->isA("Matrix"))
-    ((Matrix*)m)->cutSelection();
-  else if(m->isA("MultiLayer")){
-    MultiLayer* plot = (MultiLayer*)m;
-    if (!plot || plot->layers() == 0)
-      return;
-
-    Graph* g = (Graph*)plot->activeGraph();
-    if (!g)
-      return;
-
-    if (g->activeTool()){
-      if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector)
-        ((RangeSelectorTool *)g->activeTool())->cutSelection();
-      else if (g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker)
-        ((DataPickerTool *)g->activeTool())->cutSelection();
-    } else {
-      copyMarker();
-      g->removeMarker();
-    }
-  }
-  else if (m->isA("Note"))
-    ((Note*)m)->editor()->cut();
-
-  emit modified();
-}
-
-void ApplicationWindow::copyMarker()
-{
-  lastCopiedLayer = NULL;
-
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (g && g->markerSelected()){
-    if (g->selectedText()){
-      d_text_copy = g->selectedText();
-      d_image_copy = NULL;
-      d_arrow_copy = NULL;
-    } else if (g->arrowMarkerSelected()){
-      d_arrow_copy = (ArrowMarker *) g->selectedMarkerPtr();
-      d_image_copy = NULL;
-      d_text_copy = NULL;
-    } else if (g->imageMarkerSelected()){
-      d_image_copy = (ImageMarker *) g->selectedMarkerPtr();
-      d_text_copy = NULL;
-      d_arrow_copy = NULL;
-    }
-  }
-}
-
-void ApplicationWindow::pasteSelection()
-{  
-  if (m_interpreterDock->hasFocus())
-  {
-    
-    m_scriptInterpreter->paste();
-    return;
-  }
-
-  MdiSubWindow* m = activeWindow();
-  if (!m)
-    return;
-
-  if (m->inherits("Table"))
-    ((Table*)m)->pasteSelection();
-  else if (m->isA("Matrix"))
-    ((Matrix*)m)->pasteSelection();
-  else if (m->isA("Note"))
-    ((Note*)m)->editor()->paste();
-  else if (m->isA("MultiLayer")){
-    MultiLayer* plot = (MultiLayer*)m;
-    if (!plot)
-      return;
-
-    if (lastCopiedLayer){
-      QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-      Graph* g = plot->addLayer();
-      g->copy(lastCopiedLayer);
-      QPoint pos = plot->mapFromGlobal(QCursor::pos());
-      plot->setGraphGeometry(pos.x(), pos.y()-20, lastCopiedLayer->width(), lastCopiedLayer->height());
-
-      QApplication::restoreOverrideCursor();
-    } else {
-      if (plot->layers() == 0)
-        return;
-
-      Graph* g = (Graph*)plot->activeGraph();
-      if (!g)
-        return;
-
-      if (g->activeTool()){
-        if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector)
-          ((RangeSelectorTool *)g->activeTool())->pasteSelection();
-        else if (g->activeTool()->rtti() == PlotToolInterface::Rtti_DataPicker)
-          ((DataPickerTool *)g->activeTool())->pasteSelection();
-      } else if (d_text_copy){
-        LegendWidget *t = g->insertText(d_text_copy);
-        t->move(g->mapFromGlobal(QCursor::pos()));
-      } else if (d_arrow_copy){
-        ArrowMarker *a = g->addArrow(d_arrow_copy);
-        a->setStartPoint(QPoint(d_arrow_copy->startPoint().x() + 10,
-            d_arrow_copy->startPoint().y() + 10));
-        a->setEndPoint(QPoint(d_arrow_copy->endPoint().x() + 10,
-            d_arrow_copy->endPoint().y() + 10));
-        g->replot();
-        g->deselectMarker();
-      } else if (d_image_copy){
-        ImageMarker *i = g->addImage(d_image_copy);
-        QPoint pos = g->plotWidget()->canvas()->mapFromGlobal(QCursor::pos());
-        QSize size = d_image_copy->size();
-        i->setRect(pos.x(), pos.y(), size.width(), size.height());
-        g->replot();
-        g->deselectMarker();
-      }
-    }
-  }
-  emit modified();
-}
-
-MdiSubWindow* ApplicationWindow::clone(MdiSubWindow* w)
-{
-  if (!w) {
-    w = activeWindow();
-    if (!w){
-      QMessageBox::critical(this,tr("MantidPlot - Duplicate window error"),//Mantid
-          tr("There are no windows available in this project!"));
-      return 0;
-    }
-  }
-
-  MdiSubWindow* nw = 0;
-  MdiSubWindow::Status status = w->status();
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-  if (w->isA("MultiLayer")){
-    MultiLayer *g = (MultiLayer *)w;
-    nw = multilayerPlot(generateUniqueName(tr("Graph")), 0, g->getRows(), g->getCols());
-    ((MultiLayer *)nw)->copy(g);
-  } else if (w->inherits("Table")){
-    Table *t = (Table *)w;
-    QString caption = generateUniqueName(tr("Table"));
-    nw = newTable(caption, t->numRows(), t->numCols());
-    ((Table *)nw)->copy(t);
-    QString spec = t->saveToString("geometry\n");
-    ((Table *)nw)->setSpecifications(spec.replace(t->objectName(), caption));
-  } else if (w->isA("Graph3D")){
-    Graph3D *g = (Graph3D *)w;
-    if (!g->hasData()){
-      QApplication::restoreOverrideCursor();
-      QMessageBox::warning(this, tr("MantidPlot - Duplicate error"), tr("Empty 3D surface plots cannot be duplicated!"));//Mantid
-      return 0;
-    }
-
-    QString caption = generateUniqueName(tr("Graph"));
-    QString s = g->formula();
-    if (g->userFunction()){
-      UserFunction *f = g->userFunction();
-      nw = plotSurface(f->function(), g->xStart(), g->xStop(), g->yStart(), g->yStop(),
-          g->zStart(), g->zStop(), f->columns(), f->rows());
-    } else if (g->parametricSurface()){
-      UserParametricSurface *s = g->parametricSurface();
-      nw = plotParametricSurface(s->xFormula(), s->yFormula(), s->zFormula(), s->uStart(), s->uEnd(),
-          s->vStart(), s->vEnd(), s->columns(), s->rows(), s->uPeriodic(), s->vPeriodic());
-    } else if (s.endsWith("(Z)"))
-      nw = openPlotXYZ(caption, s, g->xStart(),g->xStop(), g->yStart(),g->yStop(),g->zStart(),g->zStop());
-    else if (s.endsWith("(Y)"))//Ribbon plot
-      nw = dataPlot3D(caption, s, g->xStart(),g->xStop(), g->yStart(),g->yStop(),g->zStart(),g->zStop());
-    else
-      nw = openMatrixPlot3D(caption, s, g->xStart(), g->xStop(), g->yStart(), g->yStop(),g->zStart(),g->zStop());
-
-    if (!nw)
-      return 0;
-
-    if (status == MdiSubWindow::Maximized)
-      nw->hide();
-    ((Graph3D *)nw)->copy(g);
-    customToolBars(nw);
-  } else if (w->isA("Matrix")){
-    nw = newMatrix(((Matrix *)w)->numRows(), ((Matrix *)w)->numCols());
-    ((Matrix *)nw)->copy((Matrix *)w);
-  } else if (w->isA("Note")){
-    nw = newNote();
-    if (nw)
-      ((Note*)nw)->setText(((Note*)w)->text());
-  }
-
-  if (nw){
-    if (w->isA("MultiLayer")){
-      if (status == MdiSubWindow::Maximized)
-        nw->showMaximized();
-    } else if (w->isA("Graph3D")){
-      ((Graph3D*)nw)->setIgnoreFonts(true);
-      if (status != MdiSubWindow::Maximized){
-        nw->resize(w->size());
-        nw->showNormal();
-      } else
-        nw->showMaximized();
-      ((Graph3D*)nw)->setIgnoreFonts(false);
-    } else {
-      nw->resize(w->size());
-      nw->showNormal();
-    }
-
-    nw->setWindowLabel(w->windowLabel());
-    nw->setCaptionPolicy(w->captionPolicy());
-    setListViewSize(nw->objectName(), w->sizeToString());
-  }
-  QApplication::restoreOverrideCursor();
-  customMenu(nw);
-  return nw;
-}
-
-void ApplicationWindow::undo()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return;
-
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-  if (qobject_cast<Note*>(w))
-    ((Note*)w)->editor()->undo();
-  else if (qobject_cast<Matrix*>(w)){
-    QUndoStack *stack = ((Matrix *)w)->undoStack();
-    if (stack && stack->canUndo())
-      stack->undo();
-  }
-  QApplication::restoreOverrideCursor();
-}
-
-void ApplicationWindow::redo()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return;
-
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-  if (qobject_cast<Note*>(w))
-    ((Note*)w)->editor()->redo();
-  else if (qobject_cast<Matrix*>(w)){
-    QUndoStack *stack = ((Matrix *)w)->undoStack();
-    if (stack && stack->canRedo())
-      stack->redo();
-  }
-
-  QApplication::restoreOverrideCursor();
-}
-
-bool ApplicationWindow::hidden(QWidget* window)
-{
-  if (hiddenWindows->contains(window))
-    return true;
-
-  return false;
-}
-
-void ApplicationWindow::updateWindowStatus(MdiSubWindow* w)
-{
-  setListView(w->objectName(), w->aspect());
-  if (w->status() == MdiSubWindow::Maximized){
-    QList<MdiSubWindow *> windows = current_folder->windowsList();
-    foreach(MdiSubWindow *oldMaxWindow, windows){
-      if (oldMaxWindow != w && oldMaxWindow->status() == MdiSubWindow::Maximized)
-        oldMaxWindow->setStatus(MdiSubWindow::Normal);
-    }
-  }
-  modifiedProject();
-}
-
-void ApplicationWindow::hideActiveWindow()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return;
-
-  hideWindow(w);
-}
-
-void ApplicationWindow::hideWindow(MdiSubWindow* w)
-{
-  hiddenWindows->append(w);
-  w->setHidden();
-  emit modified();
-}
-
-void ApplicationWindow::hideWindow()
-{
-  WindowListItem *it = (WindowListItem *)lv->currentItem();
-  MdiSubWindow *w = it->window();
-  if (!w)
-    return;
-
-  hideWindow(w);
-}
-
-void ApplicationWindow::resizeActiveWindow()
-{
-  MdiSubWindow* w = activeWindow();
-  if (!w)
-    return;
-
-  ImageDialog *id = new ImageDialog(this);
-  id->setAttribute(Qt::WA_DeleteOnClose);
-  connect (id, SIGNAL(setGeometry(int,int,int,int)), this, SLOT(setWindowGeometry(int,int,int,int)));
-
-  id->setWindowTitle(tr("MantidPlot - Window Geometry"));//Mantid
-  id->setOrigin(w->pos());
-  id->setSize(w->size());
-  id->exec();
-}
-
-void ApplicationWindow::resizeWindow()
-{
-  WindowListItem *it = (WindowListItem *)lv->currentItem();
-  MdiSubWindow *w = it->window();
-  if (!w)
-    return;
-
-  d_workspace->setActiveSubWindow(w);
-
-  ImageDialog *id = new ImageDialog(this);
-  id->setAttribute(Qt::WA_DeleteOnClose);
-  connect (id, SIGNAL(setGeometry(int,int,int,int)), this, SLOT(setWindowGeometry(int,int,int,int)));
-
-  id->setWindowTitle(tr("MantidPlot - Window Geometry"));//Mantid
-  id->setOrigin(w->pos());
-  id->setSize(w->size());
-  id->exec();
-}
-
-void ApplicationWindow::setWindowGeometry(int x, int y, int w, int h)
-{
-  activeWindow()->setGeometry(x, y, w, h);
-}
-
-void ApplicationWindow::activateWindow()
-{
-  WindowListItem *it = (WindowListItem *)lv->currentItem();
-  activateWindow(it->window());
-}
-
-void ApplicationWindow::activateWindow(MdiSubWindow *w)
-{
-  if (!w)
-    return;
-
-  w->setNormal();
-  d_workspace->setActiveSubWindow(w);
-
-  updateWindowLists(w);
-  emit modified();
-}
-
-void ApplicationWindow::maximizeWindow(Q3ListViewItem * lbi)
-{
-  if (!lbi)
-    lbi = lv->currentItem();
-
-  if (!lbi || lbi->rtti() == FolderListItem::RTTI)
-    return;
-
-  maximizeWindow(((WindowListItem*)lbi)->window());
-}
-
-void ApplicationWindow::maximizeWindow(MdiSubWindow *w)
-{
-  if (!w || w->status() == MdiSubWindow::Maximized)
-    return;
-
-  QList<MdiSubWindow *> windows = current_folder->windowsList();
-  foreach(MdiSubWindow *ow, windows){
-    if (ow != w && ow->status() == MdiSubWindow::Maximized){
-      ow->setNormal();
-      break;
-    }
-  }
-
-  w->setMaximized();
-  updateWindowLists(w);
-  emit modified();
-}
-
-void ApplicationWindow::minimizeWindow(MdiSubWindow *w)
-{
-  if (!w)
-    w = ((WindowListItem *)lv->currentItem())->window();
-
-  if (!w)
-    return;
-
-  updateWindowLists(w);
-  w->setMinimized();
-  emit modified();
-}
-
-void ApplicationWindow::updateWindowLists(MdiSubWindow *w)
-{
-  if (!w)
-    return;
-
-  if (hiddenWindows->contains(w))
-    hiddenWindows->takeAt(hiddenWindows->indexOf(w));
-}
-
-void ApplicationWindow::closeActiveWindow()
-{
-  MdiSubWindow *w = activeWindow();
-  if (w)
-    w->close();
-}
-
-void ApplicationWindow::removeWindowFromLists(MdiSubWindow* w)
-{
-  if (!w)
-    return;
-
-  QString caption = w->objectName();
-  if (w->inherits("Table")){
-    Table* m=(Table*)w;
-    for (int i=0; i<m->numCols(); i++){
-      QString name=m->colName(i);
-      removeCurves(name);
-    }
-  } else if (w->isA("MultiLayer")){
-    MultiLayer *ml =  (MultiLayer*)w;
-    Graph *g = ml->activeGraph();
-    if (g)
-      btnPointer->setChecked(true);
-  } else if (w->isA("Matrix"))
-  {
-    remove3DMatrixPlots((Matrix*)w);
-  }
-
-  else
-  {   mantidUI->removeWindowFromLists(w);
-  }
-
-  if (hiddenWindows->contains(w))
-  {
-    hiddenWindows->takeAt(hiddenWindows->indexOf(w));
-  }
-}
-
-void ApplicationWindow::closeWindow(MdiSubWindow* window)
-{
-  if (!window)
-    return;
-
-  if (d_active_window == window)
-    d_active_window = NULL;
-  removeWindowFromLists(window);
-
-  Folder *f = window->folder();
-  f->removeWindow(window);
-
-  //update list view in project explorer
-  Q3ListViewItem *it=lv->findItem (window->objectName(), 0, Q3ListView::ExactMatch|Q3ListView::CaseSensitive);
-  if (it)
-    lv->takeItem(it);
-
-  if (show_windows_policy == ActiveFolder && !f->windowsList().count()){
-    customMenu(0);
-    customToolBars(0);
-  } else if (show_windows_policy == SubFolders && !(current_folder->children()).isEmpty()){
-    FolderListItem *fi = current_folder->folderListItem();
-    FolderListItem *item = (FolderListItem *)fi->firstChild();
-    int initial_depth = item->depth();
-    bool emptyFolder = true;
-    while (item && item->depth() >= initial_depth){
-      QList<MdiSubWindow *> lst = item->folder()->windowsList();
-      if (lst.count() > 0){
-        emptyFolder = false;
-        break;
-      }
-      item = (FolderListItem *)item->itemBelow();
-    }
-    if (emptyFolder){
-      customMenu(0);
-      customToolBars(0);
-    }
-  }
-  emit modified();
-}
-
-void ApplicationWindow::about()
-{
-  /*
-QString text = "<h2>"+ versionString() + "</h2>";
-text +=	"<h3>" + QString(copyright_string).replace("\n", "<br>") + "</h3>";
-text += "<h3>" + tr("Released") + ": " + QString(release_date) + "</h3>";
-
-text += "<h3> MantidPlot released: " + QString(MANTIDPLOT_RELEASE_DATE) + QString("</h3>");//Mantid
-
-QMessageBox *mb = new QMessageBox();
-mb->setWindowTitle (tr("About QtiPlot"));
-mb->setWindowIcon (getQPixmap("logo_xpm"));
-mb->setIconPixmap(getQPixmap("logo_xpm"));
-mb->setText(text);
-mb->exec();
-   */
-  //Mantid
-  MantidAbout *ma = new MantidAbout();
-  ma->exec();
-  delete ma;
-}
-
-void ApplicationWindow::analysisMenuAboutToShow()
-{
-  analysisMenu->clear();
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return;
-
-  if (w->isA("MultiLayer")){
-    QMenu *translateMenu = analysisMenu->addMenu (tr("&Translate"));
-    translateMenu->addAction(actionTranslateVert);
-    translateMenu->addAction(actionTranslateHor);
-    analysisMenu->insertSeparator();
-    analysisMenu->addAction(actionDifferentiate);
-    analysisMenu->addAction(actionIntegrate);
-    analysisMenu->addAction(actionShowIntDialog);
-    analysisMenu->insertSeparator();
-
-    smoothMenu->clear();
-    smoothMenu = analysisMenu->addMenu (tr("&Smooth"));
-    smoothMenu->addAction(actionSmoothSavGol);
-    smoothMenu->addAction(actionSmoothAverage);
-    smoothMenu->addAction(actionSmoothFFT);
-
-    filterMenu->clear();
-    filterMenu = analysisMenu->addMenu (tr("&FFT filter"));
-    filterMenu->addAction(actionLowPassFilter);
-    filterMenu->addAction(actionHighPassFilter);
-    filterMenu->addAction(actionBandPassFilter);
-    filterMenu->addAction(actionBandBlockFilter);
-
-    analysisMenu->insertSeparator();
-    analysisMenu->addAction(actionInterpolate);
-    analysisMenu->addAction(actionFFT);
-    analysisMenu->insertSeparator();
-    analysisMenu->addAction(actionFitLinear);
-    analysisMenu->addAction(actionShowFitPolynomDialog);
-    analysisMenu->insertSeparator();
-
-    decayMenu->clear();
-    decayMenu = analysisMenu->addMenu (tr("Fit E&xponential Decay"));
-    decayMenu->addAction(actionShowExpDecayDialog);
-    decayMenu->addAction(actionShowTwoExpDecayDialog);
-    decayMenu->addAction(actionShowExpDecay3Dialog);
-
-    analysisMenu->addAction(actionFitExpGrowth);
-    analysisMenu->addAction(actionFitSigmoidal);
-    analysisMenu->addAction(actionFitGauss);
-    analysisMenu->addAction(actionFitLorentz);
-
-    multiPeakMenu->clear();
-    multiPeakMenu = analysisMenu->addMenu (tr("Fit &Multi-peak"));
-    multiPeakMenu->addAction(actionMultiPeakGauss);
-    multiPeakMenu->addAction(actionMultiPeakLorentz);
-    analysisMenu->insertSeparator();
-    analysisMenu->addAction(actionShowFitDialog);
-  } else if (w->isA("Matrix")){
-    analysisMenu->addAction(actionIntegrate);
-    analysisMenu->insertSeparator();
-    analysisMenu->addAction(actionFFT);
-    analysisMenu->addAction(actionMatrixFFTDirect);
-    analysisMenu->addAction(actionMatrixFFTInverse);
-  } else if (w->inherits("Table")){
-    analysisMenu->addAction(actionShowColStatistics);
-    analysisMenu->addAction(actionShowRowStatistics);
-    analysisMenu->insertSeparator();
-    analysisMenu->addAction(actionSortSelection);
-    analysisMenu->addAction(actionSortTable);
-
-    normMenu->clear();
-    normMenu = analysisMenu->addMenu (tr("&Normalize"));
-    normMenu->addAction(actionNormalizeSelection);
-    normMenu->addAction(actionNormalizeTable);
-
-    analysisMenu->insertSeparator();
-    analysisMenu->addAction(actionFFT);
-    analysisMenu->insertSeparator();
-    analysisMenu->addAction(actionCorrelate);
-    analysisMenu->addAction(actionAutoCorrelate);
-    analysisMenu->insertSeparator();
-    analysisMenu->addAction(actionConvolute);
-    analysisMenu->addAction(actionDeconvolute);
-    analysisMenu->insertSeparator();
-    analysisMenu->addAction(actionShowFitDialog);
-  }
-  reloadCustomActions();
-}
-
-void ApplicationWindow::matrixMenuAboutToShow()
-{
-  matrixMenu->clear();
-  matrixMenu->addAction(actionSetMatrixProperties);
-  matrixMenu->addAction(actionSetMatrixDimensions);
-  matrixMenu->insertSeparator();
-  matrixMenu->addAction(actionSetMatrixValues);
-  matrixMenu->addAction(actionTableRecalculate);
-  matrixMenu->insertSeparator();
-  matrixMenu->addAction(actionRotateMatrix);
-  matrixMenu->addAction(actionRotateMatrixMinus);
-  matrixMenu->addAction(actionFlipMatrixVertically);
-  matrixMenu->addAction(actionFlipMatrixHorizontally);
-  matrixMenu->insertSeparator();
-  matrixMenu->addAction(actionTransposeMatrix);
-  matrixMenu->addAction(actionInvertMatrix);
-  matrixMenu->addAction(actionMatrixDeterminant);
-  matrixMenu->insertSeparator();
-  matrixMenu->addAction(actionGoToRow);
-  matrixMenu->addAction(actionGoToColumn);
-  matrixMenu->insertSeparator();
-  QMenu *matrixViewMenu = matrixMenu->addMenu (tr("Vie&w"));
-  matrixViewMenu->addAction(actionViewMatrixImage);
-  matrixViewMenu->addAction(actionViewMatrix);
-  QMenu *matrixPaletteMenu = matrixMenu->addMenu (tr("&Palette"));
-  matrixPaletteMenu->addAction(actionMatrixGrayScale);
-  matrixPaletteMenu->addAction(actionMatrixRainbowScale);
-  matrixPaletteMenu->addAction(actionMatrixCustomScale);
-  matrixMenu->insertSeparator();
-  matrixMenu->addAction(actionMatrixColumnRow);
-  matrixMenu->addAction(actionMatrixXY);
-  matrixMenu->insertSeparator();
-  QMenu *convertToTableMenu = matrixMenu->addMenu (tr("&Convert to Spreadsheet"));
-  convertToTableMenu->addAction(actionConvertMatrixDirect);
-  convertToTableMenu->addAction(actionConvertMatrixXYZ);
-  convertToTableMenu->addAction(actionConvertMatrixYXZ);
-
-  Matrix* m = (Matrix*)activeWindow(MatrixWindow);
-  if (!m)
-    return;
-
-  actionViewMatrixImage->setChecked(m->viewType() == Matrix::ImageView);
-  actionViewMatrix->setChecked(m->viewType() == Matrix::TableView);
-  actionMatrixColumnRow->setChecked(m->headerViewType() == Matrix::ColumnRow);
-  actionMatrixColumnRow->setEnabled(m->viewType() == Matrix::TableView);
-  actionMatrixXY->setChecked(m->headerViewType() == Matrix::XY);
-  actionMatrixXY->setEnabled(m->viewType() == Matrix::TableView);
-
-  actionMatrixGrayScale->setChecked(m->colorMapType() == Matrix::GrayScale);
-  actionMatrixRainbowScale->setChecked(m->colorMapType() == Matrix::Rainbow);
-  actionMatrixCustomScale->setChecked(m->colorMapType() == Matrix::Custom);
-
-  reloadCustomActions();
-}
-
-void ApplicationWindow::fileMenuAboutToShow()
-{
-  fileMenu->clear();
-  newMenu->clear();
-  exportPlotMenu->clear();
-
-  newMenu = fileMenu->addMenu(tr("&New"));
-  newMenu->addAction(actionNewProject);
-  newMenu->addAction(actionNewFolder);
-  newMenu->addAction(actionNewTable);
-  newMenu->addAction(actionNewMatrix);
-  newMenu->addAction(actionNewNote);
-  newMenu->addAction(actionNewGraph);
-  newMenu->addAction(actionNewFunctionPlot);
-  newMenu->addAction(actionNewSurfacePlot);
-
-
-  openMenu=fileMenu->addMenu(tr("&Load"));
-  openMenu->addAction(actionOpenProj);
-  openMenu->addAction(actionLoadFile);
-
-  recentMenuID = fileMenu->insertItem(tr("&Recent Projects"), recent);
-
-  fileMenu->insertSeparator();
-  fileMenu->addAction(actionManageDirs);
-  fileMenu->insertSeparator();
-  fileMenu->addAction(actionLoadImage);
-
-  MdiSubWindow *w = activeWindow();
-  if (w && w->isA("Matrix"))
-    fileMenu->addAction(actionExportMatrix);
-
-  fileMenu->insertSeparator();
-  fileMenu->addAction(actionSaveProjectAs);
-  //fileMenu->insertSeparator();
-  saveMenu=fileMenu->addMenu(tr("&Save"));
-  saveMenu->addAction(actionSaveFile);
-  saveMenu->addAction(actionSaveProject);
-
-  fileMenu->insertSeparator();
-
-  fileMenu->addAction(actionPrint);
-  fileMenu->addAction(actionPrintAllPlots);
-  fileMenu->insertSeparator();
-  MdiSubWindow* t = activeWindow();
-  if (t && (t->isA("Matrix") || t->inherits("Table") || t->isA("MantidMatrix")))
-  {
-    actionShowExportASCIIDialog->setEnabled(true);
-  }
-  else
-  {
-    actionShowExportASCIIDialog->setEnabled(false);
-  }
-
-  fileMenu->addAction(actionShowExportASCIIDialog);
-  fileMenu->addAction(actionLoad);
-  fileMenu->insertSeparator();
-  fileMenu->addAction(actionclearAllMemory);
-#ifdef USE_TCMALLOC
-  fileMenu->addAction(actionreleaseFreeMemory);
-#endif
-
-  fileMenu->insertSeparator();
-  fileMenu->addAction(actionCloseAllWindows);
-
-  reloadCustomActions();
-}
-
-void ApplicationWindow::editMenuAboutToShow()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w){
-    actionUndo->setEnabled(false);
-    actionRedo->setEnabled(false);
-    return;
-  }
-
-  if (qobject_cast<Note *>(w)){
-    ScriptEdit* doc = ((Note *)w)->editor();
-    actionUndo->setEnabled(doc->isUndoAvailable());
-    actionRedo->setEnabled(doc->isRedoAvailable());
-  } else if (qobject_cast<Matrix *>(w)){
-    QUndoStack *stack = ((Matrix *)w)->undoStack();
-    actionUndo->setEnabled(stack->canUndo());
-    actionRedo->setEnabled(stack->canRedo());
-  } else {
-    actionUndo->setEnabled(false);
-    actionRedo->setEnabled(false);
-  }
-
-  reloadCustomActions();
-}
-
-void ApplicationWindow::windowsMenuAboutToShow()
-{
-  windowsMenu->clear();
-  foldersMenu->clear();
-
-  int folder_param = 0;
-  Folder *f = projectFolder();
-  while (f){
-    int id;
-    if (folder_param < 9)
-      id = foldersMenu->insertItem("&" + QString::number(folder_param+1) + " " + f->path(), this, SLOT(foldersMenuActivated(int)));
-    else
-      id = foldersMenu->insertItem(f->path(), this, SLOT(foldersMenuActivated(int)));
-
-    foldersMenu->setItemParameter(id, folder_param);
-    folder_param++;
-    foldersMenu->setItemChecked(id, f == current_folder);
-
-    f = f->folderBelow();
-  }
-
-  windowsMenu->insertItem(tr("&Folders"), foldersMenu);
-  windowsMenu->insertSeparator();
-
-  QList<MdiSubWindow *> windows = current_folder->windowsList();
-  int n = int(windows.count());
-  if (!n ){
-    /*#ifdef SCRIPTING_PYTHON
-			windowsMenu->addAction(actionShowScriptWindow);
-		#endif*/
-    return;
-  }
-
-  windowsMenu->insertItem(tr("&Cascade"), this, SLOT(cascade()));
-  windowsMenu->insertItem(tr("&Tile"), d_workspace, SLOT(tileSubWindows()));
-  windowsMenu->insertSeparator();
-  windowsMenu->addAction(actionNextWindow);
-  windowsMenu->addAction(actionPrevWindow);
-  windowsMenu->insertSeparator();
-  windowsMenu->addAction(actionRename);
-
-  windowsMenu->addAction(actionCopyWindow);
-  MdiSubWindow* activeWin=activeWindow();
-  if(!activeWin) return;
-  if(activeWin->isA("MantidMatrix") || activeWin->isA("InstrumentWindow") )
-  {
-    actionCopyWindow->setEnabled(false);
-  }
-  else
-  {
-    actionCopyWindow->setEnabled(true);
-  }
-
-  windowsMenu->insertSeparator();
-
-
-  windowsMenu->addAction(actionResizeActiveWindow);
-  windowsMenu->insertItem(tr("&Hide Window"),
-      this, SLOT(hideActiveWindow()));
 
-  // Having the shorcut set here is neccessary on Windows, but
-  // leads to an error message elsewhere. Don't know why and don't 
-  // have a better solution than this right now.
-#ifdef _WIN32
-  windowsMenu->insertItem(getQPixmap("close_xpm"), tr("Close &Window"),  
-                   this, SLOT(closeActiveWindow()), Qt::CTRL+Qt::Key_W );  
+}
 #else
-  windowsMenu->insertItem(getQPixmap("close_xpm"), tr("Close &Window"),
-			  this, SLOT(closeActiveWindow()) );
+QMessageBox::critical(this, tr("MantidPlot") + " - " + tr("Error"),//Mantid
+    tr("MantidPlot was not built with Python scripting support included!"));
 #endif
-
-  if (n>0 && n<10){
-    windowsMenu->insertSeparator();
-    for (int i = 0; i<n; ++i ){
-      int id = windowsMenu->insertItem(windows.at(i)->objectName(),
-          this, SLOT( windowsMenuActivated( int ) ) );
-      windowsMenu->setItemParameter( id, i );
-      windowsMenu->setItemChecked( id, current_folder->activeWindow() == windows.at(i));
-    }
-  } else if (n>=10) {
-    windowsMenu->insertSeparator();
-    for ( int i = 0; i<9; ++i ){
-      int id = windowsMenu->insertItem(windows.at(i)->objectName(),
-          this, SLOT( windowsMenuActivated( int ) ) );
-      windowsMenu->setItemParameter( id, i );
-      windowsMenu->setItemChecked( id, activeWindow() == windows.at(i) );
-    }
-    windowsMenu->insertSeparator();
-    windowsMenu->insertItem(tr("More windows..."),this, SLOT(showMoreWindows()));
-  }
-  reloadCustomActions();
-}
-
-void ApplicationWindow::showMarkerPopupMenu()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  QMenu markerMenu(this);
-
-  if (g->imageMarkerSelected()){
-    markerMenu.insertItem(getQPixmap("pixelProfile_xpm"),tr("&View Pixel Line profile"),this, SLOT(pixelLineProfile()));
-    markerMenu.insertItem(tr("&Intensity Matrix"),this, SLOT(intensityTable()));
-    markerMenu.insertSeparator();
-  }
-
-  markerMenu.insertItem(getQPixmap("cut_xpm"),tr("&Cut"),this, SLOT(cutSelection()));
-  markerMenu.insertItem(getQPixmap("copy_xpm"), tr("&Copy"),this, SLOT(copySelection()));
-  markerMenu.insertItem(getQPixmap("erase_xpm"), tr("&Delete"),this, SLOT(clearSelection()));
-  markerMenu.insertSeparator();
-  if (g->arrowMarkerSelected())
-    markerMenu.insertItem(tr("&Properties..."),this, SLOT(showLineDialog()));
-  else if (g->imageMarkerSelected())
-    markerMenu.insertItem(tr("&Properties..."),this, SLOT(showImageDialog()));
-  else
-    markerMenu.insertItem(tr("&Properties..."),this, SLOT(showTextDialog()));
-
-  markerMenu.exec(QCursor::pos());
-}
-
-void ApplicationWindow::showMoreWindows()
-{
-  if (explorerWindow->isVisible())
-    QMessageBox::information(this, "MantidPlot",tr("Please use the project explorer to select a window!"));//Mantid
-  else
-    explorerWindow->show();
-}
-
-void ApplicationWindow::windowsMenuActivated( int id )
-{
-  QList<MdiSubWindow *> windows = current_folder->windowsList();
-  MdiSubWindow* w = windows.at( id );
-  if ( w ){
-    w->showNormal();
-    w->setFocus();
-    if(hidden(w)){
-      hiddenWindows->takeAt(hiddenWindows->indexOf(w));
-      setListView(w->objectName(), tr("Normal"));
-    }
-    d_workspace->setActiveSubWindow(w);
-  }
-}
-
-void ApplicationWindow::foldersMenuActivated( int id )
-{
-  int folder_param = 0;
-  Folder *f = projectFolder();
-  while (f){
-    if (folder_param == id){
-      changeFolder (f);
-      return;
-    }
-
-    folder_param++;
-    f = f->folderBelow();
-  }
-}
-
-void ApplicationWindow::newProject()
-{
-  saveSettings();//the recent projects must be saved
-  mantidUI->saveProject(saved);
-  clearLogInfo();
-  setWindowTitle(tr("MantidPlot - untitled"));//Mantid
-}
-
-void ApplicationWindow::savedProject()
-{	QCoreApplication::processEvents();
-if(actionSaveFile) actionSaveFile->setEnabled(false);
-if(actionSaveProject)actionSaveProject->setEnabled(false);
-saved = true;
-
-Folder *f = projectFolder();
-while (f){
-  QList<MdiSubWindow *> folderWindows = f->windowsList();
-  foreach(MdiSubWindow *w, folderWindows){
-    if (w->isA("Matrix"))
-      ((Matrix *)w)->undoStack()->setClean();
-  }
-  f = f->folderBelow();
-}
-}
-
-void ApplicationWindow::modifiedProject()
-{
-  if (saved == false)
-    return;
-  if(actionSaveFile) actionSaveFile->setEnabled(true);
-  if(actionSaveProject)actionSaveProject->setEnabled(true);
-  saved = false;
-}
-
-void ApplicationWindow::modifiedProject(MdiSubWindow *)
-{
-  modifiedProject();
-}
-
-void ApplicationWindow::timerEvent ( QTimerEvent *e)
-{
-  if (e->timerId() == savingTimerId)
-    saveProject();
-  else
-    QWidget::timerEvent(e);
-}
-
-void ApplicationWindow::dropEvent( QDropEvent* e )
-{
-  if (mantidUI->drop(e)) return;//Mantid
-
-  QStringList fileNames;
-  if (Q3UriDrag::decodeLocalFiles(e, fileNames)){
-    QList<QByteArray> lst = QImageReader::supportedImageFormats() << "JPG";
-    QStringList asciiFiles;
-
-    for(int i = 0; i<(int)fileNames.count(); i++){
-      QString fn = fileNames[i];
-      QFileInfo fi (fn);
-      QString ext = fi.extension().lower();
-      QStringList tempList;
-      QByteArray temp;
-      // convert QList<QByteArray> to QStringList to be able to 'filter'
-      foreach(temp,lst)
-      tempList.append(QString(temp));
-      QStringList l = tempList.filter(ext, Qt::CaseInsensitive);
-      if (l.count()>0)
-        loadImage(fn);
-      else if ( ext == "opj" || ext == "qti")
-        open(fn);
-      else
-        asciiFiles << fn;
-    }
-
-    importASCII(asciiFiles, ImportASCIIDialog::NewTables, columnSeparator, ignoredLines,
-        renameColumns, strip_spaces, simplify_spaces, d_ASCII_import_comments,
-        d_import_dec_separators, d_ASCII_import_locale, d_ASCII_comment_string,
-        d_ASCII_import_read_only, d_ASCII_end_line,"");
-  }
-}
-
-void ApplicationWindow::dragEnterEvent( QDragEnterEvent* e )
-{
-  if (e->source()){
-    //e->ignore();//Mantid
-    e->accept();//Mantid
-    return;
-  }
-  else//Mantid
-    e->accept(Q3UriDrag::canDecode(e));
-}
-
-//Mantid
-void ApplicationWindow::dragMoveEvent( QDragMoveEvent* e )
-{
-  if (centralWidget()->geometry().contains(e->pos())) e->accept();
-  else
-    e->ignore();
-}
-
-void ApplicationWindow::closeEvent( QCloseEvent* ce )
-{
-#ifdef QTIPLOT_DEMO
-  showDemoVersionMessage();
-#endif
-
-  // Mantid changes here
-
-  if( scriptingEnv()->isRunning() )
-  {
-    if( QMessageBox::question(this, tr("MantidPlot"), "A script is still running, abort and quit application?", tr("Yes"), tr("No")) == 0 )
-    {
-      mantidUI->cancelAllRunningAlgorithms();
-    }
-    else
-    {
-      ce->ignore();
-      return;
-    }	  
-  }
-
-  if( !saved )
-  {
-    QString savemsg = tr("Save changes to project: <p><b> %1 </b> ?").arg(projectname);
-    int result = QMessageBox::information(this, tr("MantidPlot"), savemsg, tr("Yes"), tr("No"), tr("Cancel"), 0, 2);
-    if( result == 2 || (result == 0 && !saveProject()) )
-    {
-      ce->ignore();
-      return;
-    }
-  }
-  
-
-  if( scriptingWindow )
+}
+
+void ApplicationWindow::runPythonScript(const QString & code, bool quiet)
+{
+  if( code.isEmpty() || scriptingEnv()->isRunning() ) return;
+
+  if( m_iface_script == NULL )
   {
-    this->showScriptWindow(true);
-    scriptingWindow->saveSettings();
-    scriptingWindow->acceptCloseEvent(true);
-    scriptingWindow->close();
+    setScriptingLanguage("Python");
+    m_iface_script = scriptingEnv()->newScript("",this,false, "");
+    m_iface_script->setLineOffset(0);
+    connect(m_iface_script, SIGNAL(print(const QString &)), this, SLOT(scriptPrint(const QString&)));
+    connect(m_iface_script, SIGNAL(error(const QString &, const QString&, int)), this, 
+        SLOT(scriptPrint(const QString &)));
+
   }
 
-  //Save the settings and exit
-  saveSettings();
-  mantidUI->shutdown();
-  ce->accept();
-
-}
-
-void ApplicationWindow::customEvent(QEvent *e)
-{
-  if (e->type() == SCRIPTING_CHANGE_EVENT)
-    scriptingChangeEvent((ScriptingChangeEvent*)e);
-}
-
-void ApplicationWindow::deleteSelectedItems()
-{
-  if (folders->hasFocus() && folders->currentItem() != folders->firstChild())
-  {//we never allow the user to delete the project folder item
-    deleteFolder();
-    return;
-  }
-
-  Q3ListViewItem *item;
-  QList<Q3ListViewItem *> lst;
-  for (item = lv->firstChild(); item; item = item->nextSibling()){
-    if (item->isSelected())
-      lst.append(item);
-  }
-
-  folders->blockSignals(true);
-  foreach(item, lst){
-    if (item->rtti() == FolderListItem::RTTI){
-      Folder *f = ((FolderListItem *)item)->folder();
-      if (deleteFolder(f))
-        delete item;
-    } else
-      ((WindowListItem *)item)->window()->close();
-  }
-  folders->blockSignals(false);
-}
-
-void ApplicationWindow::showListViewSelectionMenu(const QPoint &p)
-{
-  QMenu cm(this);
-  cm.insertItem(tr("&Show All Windows"), this, SLOT(showSelectedWindows()));
-  cm.insertItem(tr("&Hide All Windows"), this, SLOT(hideSelectedWindows()));
-  cm.insertSeparator();
-  cm.insertItem(tr("&Delete Selection"), this, SLOT(deleteSelectedItems()), Qt::Key_F8);
-  cm.exec(p);
-}
-
-void ApplicationWindow::showListViewPopupMenu(const QPoint &p)
-{
-  QMenu cm(this);
-  QMenu window(this);
-
-  window.addAction(actionNewTable);
-  window.addAction(actionNewMatrix);
-  window.addAction(actionNewNote);
-  window.addAction(actionNewGraph);
-  window.addAction(actionNewFunctionPlot);
-  window.addAction(actionNewSurfacePlot);
-  cm.insertItem(tr("New &Window"), &window);
-
-  cm.insertItem(getQPixmap("newfolder_xpm"), tr("New F&older"), this, SLOT(addFolder()), Qt::Key_F7);
-  cm.insertSeparator();
-  cm.insertItem(tr("Auto &Column Width"), lv, SLOT(adjustColumns()));
-  cm.exec(p);
-}
-
-void ApplicationWindow::showWindowPopupMenu(Q3ListViewItem *it, const QPoint &p, int)
-{
-  if (folders->isRenaming())
-    return;
-
-  if (!it){
-    showListViewPopupMenu(p);
-    return;
-  }
-
-  Q3ListViewItem *item;
-  int selected = 0;
-  for (item = lv->firstChild(); item; item = item->nextSibling()){
-    if (item->isSelected())
-      selected++;
-
-    if (selected>1){
-      showListViewSelectionMenu(p);
-      return;
-    }
-  }
-
-  if (it->rtti() == FolderListItem::RTTI){
-    current_folder = ((FolderListItem *)it)->folder();
-    showFolderPopupMenu(it, p, false);
-    return;
-  }
-
-  MdiSubWindow *w= ((WindowListItem *)it)->window();
-  if (w){
-    QMenu cm(this);
-    QMenu plots(this);
-
-    cm.addAction(actionActivateWindow);
-    cm.addAction(actionMinimizeWindow);
-    cm.addAction(actionMaximizeWindow);
-    cm.insertSeparator();
-    if (!hidden(w))
-      cm.addAction(actionHideWindow);
-    cm.insertItem(getQPixmap("close_xpm"), tr("&Delete Window"), w, SLOT(close()), Qt::Key_F8);
-    cm.insertSeparator();
-    cm.insertItem(tr("&Rename Window"), this, SLOT(renameWindow()), Qt::Key_F2);
-    cm.addAction(actionResizeWindow);
-    cm.insertSeparator();
-    cm.insertItem(getQPixmap("fileprint_xpm"), tr("&Print Window"), w, SLOT(print()));
-    cm.insertSeparator();
-    cm.insertItem(tr("&Properties..."), this, SLOT(windowProperties()));
-
-    if (w->inherits("Table")){
-      QStringList graphs = dependingPlots(w->objectName());
-      if (int(graphs.count())>0){
-        cm.insertSeparator();
-        for (int i=0;i<int(graphs.count());i++)
-          plots.insertItem(graphs[i], window(graphs[i]), SLOT(showMaximized()));
-
-        cm.insertItem(tr("D&epending Graphs"),&plots);
-      }
-    } else if (w->isA("Matrix")){
-      QStringList graphs = depending3DPlots((Matrix*)w);
-      if (int(graphs.count())>0){
-        cm.insertSeparator();
-        for (int i=0;i<int(graphs.count());i++)
-          plots.insertItem(graphs[i], window(graphs[i]), SLOT(showMaximized()));
-
-        cm.insertItem(tr("D&epending 3D Graphs"),&plots);
-      }
-    } else if (w->isA("MultiLayer")) {
-      tablesDepend->clear();
-      QStringList tbls=multilayerDependencies(w);
-      int n = int(tbls.count());
-      if (n > 0){
-        cm.insertSeparator();
-        for (int i=0; i<n; i++)
-          tablesDepend->insertItem(tbls[i], i, -1);
-
-        cm.insertItem(tr("D&epends on"), tablesDepend);
-      }
-    } else if (w->isA("Graph3D")) {
-      Graph3D *sp=(Graph3D*)w;
-      Matrix *m = sp->matrix();
-      QString formula = sp->formula();
-      if (!formula.isEmpty()){
-        cm.insertSeparator();
-        if (formula.contains("_")){
-          QStringList tl = formula.split("_", QString::SkipEmptyParts);
-          tablesDepend->clear();
-          tablesDepend->insertItem(tl[0], 0, -1);
-          cm.insertItem(tr("D&epends on"), tablesDepend);
-        } else if (m) {
-          plots.insertItem(m->objectName(), m, SLOT(showNormal()));
-          cm.insertItem(tr("D&epends on"),&plots);
-        } else {
-          plots.insertItem(formula, w, SLOT(showNormal()));
-          cm.insertItem(tr("Function"), &plots);
-        }
-      }
-    }
-    cm.exec(p);
-  }
-}
-
-void ApplicationWindow::showTable(int i)
-{
-  Table *t = table(tablesDepend->text(i));
-  if (!t)
-    return;
-
-  updateWindowLists(t);
-
-  t->showMaximized();
-  Q3ListViewItem *it=lv->findItem (t->objectName(), 0, Q3ListView::ExactMatch | Qt::CaseSensitive );
-  if (it)
-    it->setText(2,tr("Maximized"));
-}
-
-void ApplicationWindow::showTable(const QString& curve)
-{
-  Table* w=table(curve);
-  if (!w)
-    return;
-
-  updateWindowLists(w);
-  int colIndex = w->colIndex(curve);
-  w->setSelectedCol(colIndex);
-  w->table()->clearSelection();
-  w->table()->selectColumn(colIndex);
-  w->showMaximized();
-  Q3ListViewItem *it=lv->findItem (w->objectName(), 0, Q3ListView::ExactMatch | Qt::CaseSensitive );
-  if (it)
-    it->setText(2,tr("Maximized"));
-  emit modified();
-}
-
-QStringList ApplicationWindow::depending3DPlots(Matrix *m)
-{
-  QStringList plots;
-  QList<MdiSubWindow *> windows = windowsList();
-  foreach(MdiSubWindow *w, windows){
-    if (w->isA("Graph3D") && ((Graph3D *)w)->matrix() == m)
-      plots << w->objectName();
-  }
-  return plots;
-}
-
-QStringList ApplicationWindow::dependingPlots(const QString& name)
-{
-  QStringList onPlot, plots;
-
-  QList<MdiSubWindow *> windows = windowsList();
-  foreach(MdiSubWindow *w, windows){
-    if (w->isA("MultiLayer")){
-      QList<Graph *> layers = ((MultiLayer*)w)->layersList();
-      foreach(Graph *g, layers){
-        onPlot = g->curvesList();
-        onPlot = onPlot.grep (name,TRUE);
-        if (int(onPlot.count()) && plots.contains(w->objectName())<=0)
-          plots << w->objectName();
-      }
-    }else if (w->isA("Graph3D")){
-      if ((((Graph3D*)w)->formula()).contains(name,TRUE) && plots.contains(w->objectName())<=0)
-        plots << w->objectName();
-    }
-  }
-  return plots;
-}
-
-QStringList ApplicationWindow::multilayerDependencies(QWidget *w)
-{
-  QStringList tables;
-  MultiLayer *g=(MultiLayer*)w;
-  QList<Graph *> layers = g->layersList();
-  foreach(Graph *ag, layers){
-    QStringList onPlot=ag->curvesList();
-    for (int j=0; j<onPlot.count(); j++)
-    {
-      QStringList tl = onPlot[j].split("_", QString::SkipEmptyParts);
-      if (tables.contains(tl[0])<=0)
-        tables << tl[0];
-    }
-  }
-  return tables;
-}
-
-void ApplicationWindow::showGraphContextMenu()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  QMenu cm(this);
-  Graph* ag = (Graph*)plot->activeGraph();
-  PlotToolInterface* tool = ag->activeTool();
-  if (dynamic_cast<PeakPickerTool*>(tool))
-  {
-    dynamic_cast<PeakPickerTool*>(tool)->prepareContextMenu(cm);
-    cm.exec(QCursor::pos());
-    return;
-  }
-
-  QMenu axes(this);
-  QMenu colour(this);
-  QMenu exports(this);
-  QMenu copy(this);
-  QMenu prints(this);
-
-  if (ag->isPiePlot())
-    cm.insertItem(tr("Re&move Pie Curve"),ag, SLOT(removePie()));
-  else {
-    if (ag->visibleCurves() != ag->curves()){
-      cm.addAction(actionShowAllCurves);
-      cm.insertSeparator();
-    }
-    cm.addAction(actionShowCurvesDialog);
-    cm.addAction(actionAddFunctionCurve);
-    //cm.insertItem(tr("Anal&yze"), analysisMenu);
-  }
-
-  if (lastCopiedLayer){
-    cm.insertSeparator();
-    cm.insertItem(getQPixmap("paste_xpm"), tr("&Paste Layer"), this, SLOT(pasteSelection()));
-  } else if (d_text_copy){
-    cm.insertSeparator();
-    cm.insertItem(getQPixmap("paste_xpm"), tr("&Paste Text"), plot, SIGNAL(pasteMarker()));
-  } else if (d_arrow_copy){
-    cm.insertSeparator();
-    cm.insertItem(getQPixmap("paste_xpm"), tr("&Paste Line/Arrow"), plot, SIGNAL(pasteMarker()));
-  } else if (d_image_copy){
-    cm.insertSeparator();
-    cm.insertItem(getQPixmap("paste_xpm"), tr("&Paste Image"), plot, SIGNAL(pasteMarker()));
-  }
-  cm.insertSeparator();
-  axes.insertItem(tr("Lo&g(x),Log(y)"), ag, SLOT(logLogAxes()));
-  axes.insertItem(tr("Log(&x),Linear(y)"), ag, SLOT(logXLinY()));
-  axes.insertItem(tr("Linear(x),Log(&y)"), ag, SLOT(logYlinX()));
-  axes.insertItem(tr("&Linear(x),Linear(y)"), ag, SLOT(linearAxes()));
-  cm.insertItem(tr("&Axes"), &axes);
-
-  colour.insertItem(tr("Lo&g Scale"), ag, SLOT(logColor()));
-  colour.insertItem(tr("&Linear"), ag, SLOT(linColor()));
-  cm.insertItem(tr("&Color Bar"), &colour);
-
-  cm.insertSeparator();
-  copy.insertItem(tr("&Layer"), this, SLOT(copyActiveLayer()));
-  copy.insertItem(tr("&Window"), plot, SLOT(copyAllLayers()));
-  cm.insertItem(getQPixmap("copy_xpm"), tr("&Copy"), &copy);
-
-  exports.insertItem(tr("&Layer"), this, SLOT(exportLayer()));
-  exports.insertItem(tr("&Window"), this, SLOT(exportGraph()));
-  cm.insertItem(tr("E&xport"),&exports);
-
-  prints.insertItem(tr("&Layer"), plot, SLOT(printActiveLayer()));
-  prints.insertItem(tr("&Window"), plot, SLOT(print()));
-  cm.insertItem(getQPixmap("fileprint_xpm"), tr("&Print"),&prints);
-  cm.insertSeparator();
-  cm.insertItem(tr("P&roperties..."), this, SLOT(showGeneralPlotDialog()));
-  cm.insertSeparator();
-  cm.insertItem(getQPixmap("close_xpm"), tr("&Delete Layer"), plot, SLOT(confirmRemoveLayer()));
-  cm.exec(QCursor::pos());
-}
-
-void ApplicationWindow::showWindowContextMenu()
-{
-  MdiSubWindow* w = activeWindow();
-  if (!w)
-    return;
-
-
-  QMenu cm(this);
-  QMenu plot3D(this);
-  if (w->isA("MultiLayer")){
-    MultiLayer *g = (MultiLayer*)w;
-    if (lastCopiedLayer){
-      cm.insertItem(getQPixmap("paste_xpm"), tr("&Paste Layer"), this, SLOT(pasteSelection()));
-      cm.insertSeparator();
-    }
-
-    cm.addAction(actionAddLayer);
-    if (g->layers() != 0)
-      cm.addAction(actionDeleteLayer);
-
-    cm.addAction(actionShowLayerDialog);
-    cm.insertSeparator();
-    cm.addAction(actionRename);
-    cm.addAction(actionCopyWindow);
-    cm.insertSeparator();
-    cm.insertItem(getQPixmap("copy_xpm"),tr("&Copy Page"), g, SLOT(copyAllLayers()));
-    cm.insertItem(tr("E&xport Page"), this, SLOT(exportGraph()));
-    cm.addAction(actionPrint);
-    cm.insertSeparator();
-    cm.addAction(actionCloseWindow);
-  } else if (w->isA("Graph3D")){
-    Graph3D *g=(Graph3D*)w;
-    if (!g->hasData()){
-      cm.insertItem(tr("3D &Plot"), &plot3D);
-      plot3D.addAction(actionAdd3DData);
-      plot3D.insertItem(tr("&Matrix..."), this, SLOT(add3DMatrixPlot()));
-      plot3D.addAction(actionEditSurfacePlot);
-    } else {
-      if (g->table())
-        cm.insertItem(tr("Choose &Data Set..."), this, SLOT(change3DData()));
-      else if (g->matrix())
-        cm.insertItem(tr("Choose &Matrix..."), this, SLOT(change3DMatrix()));
-      else if (g->userFunction() || g->parametricSurface())
-        cm.addAction(actionEditSurfacePlot);
-      cm.insertItem(getQPixmap("erase_xpm"), tr("C&lear"), g, SLOT(clearData()));
-    }
-
-    cm.insertSeparator();
-    cm.addAction(actionRename);
-    cm.addAction(actionCopyWindow);
-    cm.insertSeparator();
-    cm.insertItem(tr("&Copy Graph"), g, SLOT(copyImage()));
-    cm.insertItem(tr("&Export"), this, SLOT(exportGraph()));
-    cm.addAction(actionPrint);
-    cm.insertSeparator();
-    cm.addAction(actionCloseWindow);
-  } else if (w->isA("Matrix")) {
-    Matrix *t = (Matrix *)w;
-    if (t->viewType() == Matrix::TableView){
-      cm.insertItem(getQPixmap("cut_xpm"),tr("Cu&t"), t, SLOT(cutSelection()));
-      cm.insertItem(getQPixmap("copy_xpm"),tr("&Copy"), t, SLOT(copySelection()));
-      cm.insertItem(getQPixmap("paste_xpm"),tr("&Paste"), t, SLOT(pasteSelection()));
-      cm.insertSeparator();
-      cm.insertItem(getQPixmap("insert_row_xpm"), tr("&Insert Row"), t, SLOT(insertRow()));
-      cm.insertItem(getQPixmap("insert_column_xpm"), tr("&Insert Column"), t, SLOT(insertColumn()));
-      if (t->numSelectedRows() > 0)
-        cm.insertItem(getQPixmap("delete_row_xpm"), tr("&Delete Rows"), t, SLOT(deleteSelectedRows()));
-      else if (t->numSelectedColumns() > 0)
-        cm.insertItem(getQPixmap("delete_column_xpm"), tr("&Delete Columns"), t, SLOT(deleteSelectedColumns()));
-
-      cm.insertItem(getQPixmap("erase_xpm"),tr("Clea&r"), t, SLOT(clearSelection()));
-    } else if (t->viewType() == Matrix::ImageView){
-      cm.addAction(actionImportImage);
-      cm.addAction(actionExportMatrix);
-      cm.insertSeparator();
-      cm.addAction(actionSetMatrixProperties);
-      cm.addAction(actionSetMatrixDimensions);
-      cm.insertSeparator();
-      cm.addAction(actionSetMatrixValues);
-      cm.addAction(actionTableRecalculate);
-      cm.insertSeparator();
-      cm.addAction(actionRotateMatrix);
-      cm.addAction(actionRotateMatrixMinus);
-      cm.insertSeparator();
-      cm.addAction(actionFlipMatrixVertically);
-      cm.addAction(actionFlipMatrixHorizontally);
-      cm.insertSeparator();
-      cm.addAction(actionTransposeMatrix);
-      cm.addAction(actionInvertMatrix);
-    }
-  } else
-    mantidUI->showContextMenu(cm,w);//Mantid
-  cm.exec(QCursor::pos());
-}
-
-void ApplicationWindow::customWindowTitleBarMenu(MdiSubWindow *w, QMenu *menu)
-{
-  menu->addAction(actionHideActiveWindow);
-  menu->addSeparator();
-  if (w->inherits("Table")){
-    menu->addAction(actionShowExportASCIIDialog);
-    menu->addSeparator();
-  }
-
-  if (w->isA("Note"))
-    menu->addAction(actionSaveNote);
-  else
-    menu->addAction(actionSaveTemplate);
-  menu->addAction(actionPrint);
-  menu->addSeparator();
-  menu->addAction(actionRename);
-  menu->addAction(actionCopyWindow);
-  menu->addSeparator();
-}
-
-void ApplicationWindow::showTableContextMenu(bool selection)
-{
-  Table *t = (Table*)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  QMenu cm(this);
-  if (selection){
-    if ((int)t->selectedColumns().count() > 0){
-      showColMenu(t->firstSelectedColumn());
-      return;
-    } else if (t->numSelectedRows() == 1) {
-      cm.addAction(actionShowColumnValuesDialog);
-      cm.insertItem(getQPixmap("cut_xpm"),tr("Cu&t"), t, SLOT(cutSelection()));
-      cm.insertItem(getQPixmap("copy_xpm"),tr("&Copy"), t, SLOT(copySelection()));
-      cm.insertItem(getQPixmap("paste_xpm"),tr("&Paste"), t, SLOT(pasteSelection()));
-      cm.insertSeparator();
-      cm.addAction(actionTableRecalculate);
-      cm.insertItem(getQPixmap("insert_row_xpm"), tr("&Insert Row"), t, SLOT(insertRow()));
-      cm.insertItem(getQPixmap("delete_row_xpm"), tr("&Delete Row"), t, SLOT(deleteSelectedRows()));
-      cm.insertItem(getQPixmap("erase_xpm"), tr("Clea&r Row"), t, SLOT(clearSelection()));
-      cm.insertSeparator();
-      cm.addAction(actionShowRowStatistics);
-    } else if (t->numSelectedRows() > 1) {
-      cm.addAction(actionShowColumnValuesDialog);
-      cm.insertItem(getQPixmap("cut_xpm"),tr("Cu&t"), t, SLOT(cutSelection()));
-      cm.insertItem(getQPixmap("copy_xpm"),tr("&Copy"), t, SLOT(copySelection()));
-      cm.insertItem(getQPixmap("paste_xpm"),tr("&Paste"), t, SLOT(pasteSelection()));
-      cm.insertSeparator();
-      cm.addAction(actionTableRecalculate);
-      cm.insertItem(getQPixmap("delete_row_xpm"), tr("&Delete Rows"), t, SLOT(deleteSelectedRows()));
-      cm.insertItem(getQPixmap("erase_xpm"),tr("Clea&r Rows"), t, SLOT(clearSelection()));
-      cm.insertSeparator();
-      cm.addAction(actionShowRowStatistics);
-    } else if (t->numRows() > 0 && t->numCols() > 0){
-      cm.addAction(actionShowColumnValuesDialog);
-      cm.insertItem(getQPixmap("cut_xpm"),tr("Cu&t"), t, SLOT(cutSelection()));
-      cm.insertItem(getQPixmap("copy_xpm"),tr("&Copy"), t, SLOT(copySelection()));
-      cm.insertItem(getQPixmap("paste_xpm"),tr("&Paste"), t, SLOT(pasteSelection()));
-      cm.insertSeparator();
-      cm.addAction(actionTableRecalculate);
-      cm.insertItem(getQPixmap("erase_xpm"),tr("Clea&r"), t, SLOT(clearSelection()));
-    }
-  } else {
-    cm.addAction(actionShowExportASCIIDialog);
-    cm.insertSeparator();
-    cm.addAction(actionAddColToTable);
-    cm.addAction(actionClearTable);
-    cm.insertSeparator();
-    cm.addAction(actionGoToRow);
-    cm.addAction(actionGoToColumn);
-  }
-  cm.exec(QCursor::pos());
-}
-
-void ApplicationWindow::chooseHelpFolder()
-{
-  QFileInfo hfi(helpFilePath);
-  QString dir = QFileDialog::getExistingDirectory(this, tr("Choose the location of the MantidPlot help folder!"),
-      hfi.dir().absolutePath(), 0 /**QFileDialog::ShowDirsOnly*/);
-
-  if (!dir.isEmpty()){
-    helpFilePath = dir + "index.html";
-
-    QFile helpFile(helpFilePath);
-    if (!helpFile.exists()){
-      QMessageBox::critical(this, tr("MantidPlot - index.html File Not Found!"),//Mantid
-          tr("There is no file called <b>index.html</b> in this folder.<br>Please choose another folder!"));
-    }
-  }
-}
-
-void ApplicationWindow::showStandAloneHelp()
-{
-#ifdef Q_OS_MAC // Mac
-  QSettings settings(QSettings::IniFormat,QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName());
-#else
-  QSettings settings;//(QSettings::NativeFormat,QSettings::UserScope, "ProIndependent", "QtiPlot");
-#endif
-
-  settings.beginGroup("/General");
-  settings.beginGroup("/Paths");
-  QString helpPath = settings.value("/HelpFile", qApp->applicationDirPath()+"/manual/index.html").toString();
-  settings.endGroup();
-  settings.endGroup();
-
-  QFile helpFile(helpPath);
-  if (!helpPath.isEmpty() && !helpFile.exists())
-  {
-    QMessageBox::critical(0, tr("MantidPlot - Help Files Not Found!"),//Mantid
-        tr("The manual can be downloaded from the following internet address:")+
-        "<p><a href = http://soft.proindependent.com/manuals.html>http://soft.proindependent.com/manuals.html</a></p>");
-    exit(0);
-  }
-
-  QFileInfo fi(helpPath);
-  QString profilePath = QString(fi.dirPath(true)+"/qtiplot.adp");
-  if (!QFile(profilePath).exists())
-  {
-    QMessageBox::critical(0, 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")+"<br>"+
-        tr("This file is provided with the MantidPlot manual which can be downloaded from the following internet address:")+
-        "<p><a href = http://soft.proindependent.com/manuals.html>http://soft.proindependent.com/manuals.html</a></p>");
-    exit(0);
-  }
-
-  QStringList cmdLst = QStringList() << "-profile" << profilePath;
-//  QAssistantClient *assist = new QAssistantClient( QString(), 0);
-//  assist->setArguments( cmdLst );
-//  assist->showPage(helpPath);
-//  connect(assist, SIGNAL(assistantClosed()), qApp, SLOT(quit()) );
-}
-
-void ApplicationWindow::showHelp()
-{
-  QFile helpFile(helpFilePath);
-  if (!helpFile.exists())
-  {
-    QMessageBox::critical(this,tr("MantidPlot - Help Files Not Found!"),//Mantid
-        tr("Please indicate the location of the help file!")+"<br>"+
-        tr("The manual can be downloaded from the following internet address:")+
-        "<p><a href = http://soft.proindependent.com/manuals.html>http://soft.proindependent.com/manuals.html</a></p>");
-    QString fn = QFileDialog::getOpenFileName(QDir::currentDirPath(), "*.html", this );
-    if (!fn.isEmpty())
-    {
-      QFileInfo fi(fn);
-      helpFilePath=fi.absFilePath();
-      saveSettings();
-    }
-  }
-
-  QFileInfo fi(helpFilePath);
-  QString profilePath = QString(fi.dirPath(true)+"/qtiplot.adp");
-  if (!QFile(profilePath).exists())
-  {
-    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")+"<br>"+
-        tr("This file is provided with the MantidPlot manual which can be downloaded from the following internet address:")+
-        "<p><a href = http://soft.proindependent.com/manuals.html>http://soft.proindependent.com/manuals.html</a></p>");
-    return;
-  }
-
-  QStringList cmdLst = QStringList() << "-profile" << profilePath;
-//  assistant->setArguments( cmdLst );
-//  assistant->showPage(helpFilePath);
-}
-
-void ApplicationWindow::showPlotWizard()
-{
-  QStringList lst = tableNames();
-  if (lst.count() > 0){
-    PlotWizard* pw = new PlotWizard(this, 0);
-    pw->setAttribute(Qt::WA_DeleteOnClose);
-    connect (pw,SIGNAL(plot(const QStringList&)),this,SLOT(multilayerPlot(const QStringList&)));
-
-    pw->insertTablesList(lst);
-    pw->setColumnsList(columnsList(Table::All));
-    pw->changeColumnsList(lst[0]);
-    pw->exec();
-  } else
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no tables available in this project.</h4>"
-            "<p><h4>Please create a table and try again!</h4>"));
-}
-
-void ApplicationWindow::setCurveFullRange()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g)
-    return;
-
-  int curveKey = actionCurveFullRange->data().toInt();
-  g->setCurveFullRange(g->curveIndex(curveKey));
-}
-
-void ApplicationWindow::showCurveRangeDialog()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g)
-    return;
-
-  int curveKey = actionEditCurveRange->data().toInt();
-  showCurveRangeDialog(g, g->curveIndex(curveKey));
-}
-
-CurveRangeDialog* ApplicationWindow::showCurveRangeDialog(Graph *g, int curve)
-{
-  if (!g)
-    return 0;
-
-  CurveRangeDialog* crd = new CurveRangeDialog(this);
-  crd->setAttribute(Qt::WA_DeleteOnClose);
-  crd->setCurveToModify(g, curve);
-  crd->exec();
-  return crd;
-}
-
-FunctionDialog* ApplicationWindow::showFunctionDialog()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return 0;
-
-  Graph* g = plot->activeGraph();
-  if (!g)
-    return 0;
-
-  int curveKey = actionEditFunction->data().toInt();
-  return showFunctionDialog(g, g->curveIndex(curveKey));
-}
-
-FunctionDialog* ApplicationWindow::showFunctionDialog(Graph *g, int curve)
-{
-  if ( !g )
-    return 0;
-
-  FunctionDialog* fd = functionDialog();
-  fd->setWindowTitle(tr("MantidPlot - Edit function"));//Mantid
-  fd->setCurveToModify(g, curve);
-  return fd;
-}
-
-FunctionDialog* ApplicationWindow::functionDialog()
-{
-  FunctionDialog* fd = new FunctionDialog(this);
-  fd->setAttribute(Qt::WA_DeleteOnClose);
-  connect (fd,SIGNAL(clearParamFunctionsList()),this,SLOT(clearParamFunctionsList()));
-  connect (fd,SIGNAL(clearPolarFunctionsList()),this,SLOT(clearPolarFunctionsList()));
-
-  fd->insertParamFunctionsList(xFunctions, yFunctions);
-  fd->insertPolarFunctionsList(rFunctions, thetaFunctions);
-  fd->show();
-  fd->setActiveWindow();
-  return fd;
-}
-
-void ApplicationWindow::addFunctionCurve()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  if (plot->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    return;
-  }
-
-  Graph* g = plot->activeGraph();
-  if ( g ) {
-    FunctionDialog* fd = functionDialog();
-    if (fd)
-      fd->setGraph(g);
-  }
-}
-
-void ApplicationWindow::updateFunctionLists(int type, QStringList &formulas)
-{
-  int maxListSize = 10;
-  if (type == 2)
-  {
-    rFunctions.remove(formulas[0]);
-    rFunctions.push_front(formulas[0]);
-
-    thetaFunctions.remove(formulas[1]);
-    thetaFunctions.push_front(formulas[1]);
-
-    while ((int)rFunctions.size() > maxListSize)
-      rFunctions.pop_back();
-    while ((int)thetaFunctions.size() > maxListSize)
-      thetaFunctions.pop_back();
-  }
-  else if (type == 1)
-  {
-    xFunctions.remove(formulas[0]);
-    xFunctions.push_front(formulas[0]);
-
-    yFunctions.remove(formulas[1]);
-    yFunctions.push_front(formulas[1]);
-
-    while ((int)xFunctions.size() > maxListSize)
-      xFunctions.pop_back();
-    while ((int)yFunctions.size() > maxListSize)
-      yFunctions.pop_back();
-  }
-}
-
-MultiLayer * ApplicationWindow::newFunctionPlot(QStringList &formulas, double start, double end, int points, const QString& var, int type)
-{
-  MultiLayer *ml = newGraph();
-  if (ml)
-    ml->activeGraph()->addFunction(formulas, start, end, points, var, type);
-
-  updateFunctionLists(type, formulas);
-  return ml;
-}
-
-void ApplicationWindow::clearLogInfo()
-{
-  //if (!current_folder->logInfo().isEmpty()){
-  current_folder->clearLogInfo();
-  results->setText("");
-  emit modified();
-  //}
-}
-
-void ApplicationWindow::clearParamFunctionsList()
-{
-  xFunctions.clear();
-  yFunctions.clear();
-}
-
-void ApplicationWindow::clearPolarFunctionsList()
-{
-  rFunctions.clear();
-  thetaFunctions.clear();
-}
-
-void ApplicationWindow::clearSurfaceFunctionsList()
-{
-  surfaceFunc.clear();
-}
-
-void ApplicationWindow::setFramed3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setFramed();
-  actionShowAxisDialog->setEnabled(TRUE);
-}
-
-void ApplicationWindow::setBoxed3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setBoxed();
-  actionShowAxisDialog->setEnabled(TRUE);
-}
-
-void ApplicationWindow::removeAxes3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setNoAxes();
-  actionShowAxisDialog->setEnabled(false);
-}
-
-void ApplicationWindow::removeGrid3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setPolygonStyle();
-}
-
-void ApplicationWindow::setHiddenLineGrid3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setHiddenLineStyle();
-}
-
-void ApplicationWindow::setPoints3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setDotStyle();
-}
-
-void ApplicationWindow::setCones3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setConeStyle();
-}
-
-void ApplicationWindow::setCrosses3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setCrossStyle();
-}
-
-void ApplicationWindow::setBars3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setBarStyle();
-}
-
-void ApplicationWindow::setLineGrid3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setWireframeStyle();
-}
-
-void ApplicationWindow::setFilledMesh3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setFilledMeshStyle();
-}
-
-void ApplicationWindow::setFloorData3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setFloorData();
-}
-
-void ApplicationWindow::setFloorIso3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setFloorIsolines();
-}
-
-void ApplicationWindow::setEmptyFloor3DPlot()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setEmptyFloor();
-}
-
-void ApplicationWindow::setFrontGrid3DPlot(bool on)
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setFrontGrid(on);
-}
-
-void ApplicationWindow::setBackGrid3DPlot(bool on)
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setBackGrid(on);
-}
-
-void ApplicationWindow::setFloorGrid3DPlot(bool on)
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setFloorGrid(on);
-}
-
-void ApplicationWindow::setCeilGrid3DPlot(bool on)
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setCeilGrid(on);
-}
-
-void ApplicationWindow::setRightGrid3DPlot(bool on)
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setRightGrid(on);
-}
-
-void ApplicationWindow::setLeftGrid3DPlot(bool on)
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setLeftGrid(on);
-}
-
-void ApplicationWindow::pickPlotStyle( QAction* action )
-{
-  if (!action )
-    return;
-
-  if (action == polygon)
-    removeGrid3DPlot();
-  else if (action == filledmesh)
-    setFilledMesh3DPlot();
-  else if (action == wireframe)
-    setLineGrid3DPlot();
-  else if (action == hiddenline)
-    setHiddenLineGrid3DPlot();
-  else if (action == pointstyle)
-    setPoints3DPlot();
-  else if (action == conestyle)
-    setCones3DPlot();
-  else if (action == crossHairStyle)
-    setCrosses3DPlot();
-  else if (action == barstyle)
-    setBars3DPlot();
-
-  emit modified();
-}
-
-
-void ApplicationWindow::pickCoordSystem( QAction* action)
-{
-  if (!action)
-    return;
-
-  if (action == Box || action == Frame)
-  {
-    if (action == Box)
-      setBoxed3DPlot();
-    if (action == Frame)
-      setFramed3DPlot();
-    grids->setEnabled(true);
-  }
-  else if (action == None)
-  {
-    removeAxes3DPlot();
-    grids->setEnabled(false);
-  }
-
-  emit modified();
-}
-
-void ApplicationWindow::pickFloorStyle( QAction* action )
-{
-  if (!action)
-    return;
-
-  if (action == floordata)
-    setFloorData3DPlot();
-  else if (action == flooriso)
-    setFloorIso3DPlot();
-  else
-    setEmptyFloor3DPlot();
-
-  emit modified();
-}
-
-void ApplicationWindow::custom3DActions(QMdiSubWindow *w)
-{
-  if (w && w->isA("Graph3D"))
-  {
-    Graph3D* plot = (Graph3D*)w;
-    actionAnimate->setOn(plot->isAnimated());
-    actionPerspective->setOn(!plot->isOrthogonal());
-    switch(plot->plotStyle())
-    {
-    case FILLEDMESH:
-      wireframe->setChecked( false );
-      hiddenline->setChecked( false );
-      polygon->setChecked( false );
-      filledmesh->setChecked( true );
-      pointstyle->setChecked( false );
-      barstyle->setChecked( false );
-      conestyle->setChecked( false );
-      crossHairStyle->setChecked( false );
-      break;
-
-    case FILLED:
-      wireframe->setChecked( false );
-      hiddenline->setChecked( false );
-      polygon->setChecked( true );
-      filledmesh->setChecked( false );
-      pointstyle->setChecked( false );
-      barstyle->setChecked( false );
-      conestyle->setChecked( false );
-      crossHairStyle->setChecked( false );
-      break;
-
-    case Qwt3D::USER:
-      wireframe->setChecked( false );
-      hiddenline->setChecked( false );
-      polygon->setChecked( false );
-      filledmesh->setChecked( false );
-
-      if (plot->pointType() == Graph3D::VerticalBars)
-      {
-        pointstyle->setChecked( false );
-        conestyle->setChecked( false );
-        crossHairStyle->setChecked( false );
-        barstyle->setChecked( true );
-      }
-      else if (plot->pointType() == Graph3D::Dots)
-      {
-        pointstyle->setChecked( true );
-        barstyle->setChecked( false );
-        conestyle->setChecked( false );
-        crossHairStyle->setChecked( false );
-      }
-      else if (plot->pointType() == Graph3D::HairCross)
-      {
-        pointstyle->setChecked( false );
-        barstyle->setChecked( false );
-        conestyle->setChecked( false );
-        crossHairStyle->setChecked( true );
-      }
-      else if (plot->pointType() == Graph3D::Cones)
-      {
-        pointstyle->setChecked( false );
-        barstyle->setChecked( false );
-        conestyle->setChecked( true );
-        crossHairStyle->setChecked( false );
-      }
-      break;
-
-    case WIREFRAME:
-      wireframe->setChecked( true );
-      hiddenline->setChecked( false );
-      polygon->setChecked( false );
-      filledmesh->setChecked( false );
-      pointstyle->setChecked( false );
-      barstyle->setChecked( false );
-      conestyle->setChecked( false );
-      crossHairStyle->setChecked( false );
-      break;
-
-    case HIDDENLINE:
-      wireframe->setChecked( false );
-      hiddenline->setChecked( true );
-      polygon->setChecked( false );
-      filledmesh->setChecked( false );
-      pointstyle->setChecked( false );
-      barstyle->setChecked( false );
-      conestyle->setChecked( false );
-      crossHairStyle->setChecked( false );
-      break;
-
-    default:
-      break;
-    }
-
-    switch(plot->coordStyle())
-    {
-    case Qwt3D::NOCOORD:
-      None->setChecked( true );
-      Box->setChecked( false );
-      Frame->setChecked( false );
-      break;
-
-    case Qwt3D::BOX:
-      None->setChecked( false );
-      Box->setChecked( true );
-      Frame->setChecked( false );
-      break;
-
-    case Qwt3D::FRAME:
-      None->setChecked(false );
-      Box->setChecked( false );
-      Frame->setChecked(true );
-      break;
-    }
-
-    switch(plot->floorStyle())
-    {
-    case NOFLOOR:
-      floornone->setChecked( true );
-      flooriso->setChecked( false );
-      floordata->setChecked( false );
-      break;
-
-    case FLOORISO:
-      floornone->setChecked( false );
-      flooriso->setChecked( true );
-      floordata->setChecked( false );
-      break;
-
-    case FLOORDATA:
-      floornone->setChecked(false );
-      flooriso->setChecked( false );
-      floordata->setChecked(true );
-      break;
-    }
-    custom3DGrids(plot->grids());
-  }
-}
-
-void ApplicationWindow::custom3DGrids(int grids)
-{
-  if (Qwt3D::BACK & grids)
-    back->setChecked(true);
-  else
-    back->setChecked(false);
-
-  if (Qwt3D::FRONT & grids)
-    front->setChecked(true);
-  else
-    front->setChecked(false);
-
-  if (Qwt3D::CEIL & grids)
-    ceil->setChecked(true);
-  else
-    ceil->setChecked(false);
-
-  if (Qwt3D::FLOOR & grids)
-    floor->setChecked(true);
-  else
-    floor->setChecked(false);
-
-  if (Qwt3D::RIGHT & grids)
-    right->setChecked(true);
-  else
-    right->setChecked(false);
-
-  if (Qwt3D::LEFT & grids)
-    left->setChecked(true);
-  else
-    left->setChecked(false);
-}
-
-void ApplicationWindow::initPlot3DToolBar()
-{
-  plot3DTools = new QToolBar( tr( "3D Surface" ), this );
-  plot3DTools->setObjectName("plot3DTools"); // this is needed for QMainWindow::restoreState()
-  plot3DTools->setIconSize( QSize(20,20) );
-  addToolBarBreak( Qt::TopToolBarArea );
-  addToolBar( Qt::TopToolBarArea, plot3DTools );
-
-  coord = new QActionGroup( this );
-  Box = new QAction( coord );
-  Box->setIcon(QIcon(getQPixmap("box_xpm")));
-  Box->setCheckable(true);
-
-  Frame = new QAction( coord );
-  Frame->setIcon(QIcon(getQPixmap("free_axes_xpm")) );
-  Frame->setCheckable(true);
-
-  None = new QAction( coord );
-  None->setIcon(QIcon(getQPixmap("no_axes_xpm")) );
-  None->setCheckable(true);
-
-  plot3DTools->addAction(Frame);
-  plot3DTools->addAction(Box);
-  plot3DTools->addAction(None);
-  Box->setChecked( true );
-
-  plot3DTools->addSeparator();
-
-  // grid actions
-  grids = new QActionGroup( this );
-  grids->setEnabled( true );
-  grids->setExclusive( false );
-  front = new QAction( grids );
-  front->setCheckable( true );
-  front->setIcon(QIcon(getQPixmap("frontGrid_xpm")) );
-  back = new QAction( grids );
-  back->setCheckable( true );
-  back->setIcon(QIcon(getQPixmap("backGrid_xpm")));
-  right = new QAction( grids );
-  right->setCheckable( true );
-  right->setIcon(QIcon(getQPixmap("leftGrid_xpm")) );
-  left = new QAction( grids );
-  left->setCheckable( true );
-  left->setIcon(QIcon(getQPixmap("rightGrid_xpm")));
-  ceil = new QAction( grids );
-  ceil->setCheckable( true );
-  ceil->setIcon(QIcon(getQPixmap("ceilGrid_xpm")) );
-  floor = new QAction( grids );
-  floor->setCheckable( true );
-  floor->setIcon(QIcon(getQPixmap("floorGrid_xpm")) );
-
-  plot3DTools->addAction(front);
-  plot3DTools->addAction(back);
-  plot3DTools->addAction(right);
-  plot3DTools->addAction(left);
-  plot3DTools->addAction(ceil);
-  plot3DTools->addAction(floor);
-
-  plot3DTools->addSeparator();
-
-  actionPerspective = new QAction( this );
-  actionPerspective->setToggleAction( TRUE );
-  actionPerspective->setIconSet(getQPixmap("perspective_xpm") );
-  actionPerspective->addTo( plot3DTools );
-  actionPerspective->setOn(!orthogonal3DPlots);
-  connect(actionPerspective, SIGNAL(toggled(bool)), this, SLOT(togglePerspective(bool)));
-
-  actionResetRotation = new QAction( this );
-  actionResetRotation->setToggleAction( false );
-  actionResetRotation->setIconSet(getQPixmap("reset_rotation_xpm"));
-  actionResetRotation->addTo( plot3DTools );
-  connect(actionResetRotation, SIGNAL(activated()), this, SLOT(resetRotation()));
-
-  actionFitFrame = new QAction( this );
-  actionFitFrame->setToggleAction( false );
-  actionFitFrame->setIconSet(getQPixmap("fit_frame_xpm"));
-  actionFitFrame->addTo( plot3DTools );
-  connect(actionFitFrame, SIGNAL(activated()), this, SLOT(fitFrameToLayer()));
-
-  plot3DTools->addSeparator();
-
-  //plot style actions
-  plotstyle = new QActionGroup( this );
-  wireframe = new QAction( plotstyle );
-  wireframe->setCheckable( true );
-  wireframe->setEnabled( true );
-  wireframe->setIcon(QIcon(getQPixmap("lineMesh_xpm")) );
-  hiddenline = new QAction( plotstyle );
-  hiddenline->setCheckable( true );
-  hiddenline->setEnabled( true );
-  hiddenline->setIcon(QIcon(getQPixmap("grid_only_xpm")) );
-  polygon = new QAction( plotstyle );
-  polygon->setCheckable( true );
-  polygon->setEnabled( true );
-  polygon->setIcon(QIcon(getQPixmap("no_grid_xpm")));
-  filledmesh = new QAction( plotstyle );
-  filledmesh->setCheckable( true );
-  filledmesh->setIcon(QIcon(getQPixmap("grid_poly_xpm")) );
-  pointstyle = new QAction( plotstyle );
-  pointstyle->setCheckable( true );
-  pointstyle->setIcon(QIcon(getQPixmap("pointsMesh_xpm")) );
-
-  conestyle = new QAction( plotstyle );
-  conestyle->setCheckable( true );
-  conestyle->setIcon(QIcon(getQPixmap("cones_xpm")) );
-
-  crossHairStyle = new QAction( plotstyle );
-  crossHairStyle->setCheckable( true );
-  crossHairStyle->setIcon(QIcon(getQPixmap("crosses_xpm")) );
-
-  barstyle = new QAction( plotstyle );
-  barstyle->setCheckable( true );
-  barstyle->setIcon(QIcon(getQPixmap("plot_bars_xpm")) );
-
-  plot3DTools->addAction(barstyle);
-  plot3DTools->addAction(pointstyle);
-
-  plot3DTools->addAction(conestyle);
-  plot3DTools->addAction(crossHairStyle);
-  plot3DTools->addSeparator();
-
-  plot3DTools->addAction(wireframe);
-  plot3DTools->addAction(hiddenline);
-  plot3DTools->addAction(polygon);
-  plot3DTools->addAction(filledmesh);
-  filledmesh->setChecked( true );
-
-  plot3DTools->addSeparator();
-
-  //floor actions
-  floorstyle = new QActionGroup( this );
-  floordata = new QAction( floorstyle );
-  floordata->setCheckable( true );
-  floordata->setIcon(QIcon(getQPixmap("floor_xpm")) );
-  flooriso = new QAction( floorstyle );
-  flooriso->setCheckable( true );
-  flooriso->setIcon(QIcon(getQPixmap("isolines_xpm")) );
-  floornone = new QAction( floorstyle );
-  floornone->setCheckable( true );
-  floornone->setIcon(QIcon(getQPixmap("no_floor_xpm")));
-
-  plot3DTools->addAction(floordata);
-  plot3DTools->addAction(flooriso);
-  plot3DTools->addAction(floornone);
-  floornone->setChecked( true );
-
-  plot3DTools->addSeparator();
-
-  actionAnimate = new QAction( this );
-  actionAnimate->setToggleAction( true );
-  actionAnimate->setIconSet(getQPixmap("movie_xpm"));
-  plot3DTools->addAction(actionAnimate);
-
-  plot3DTools->hide();
-
-  connect(actionAnimate, SIGNAL(toggled(bool)), this, SLOT(toggle3DAnimation(bool)));
-  connect( coord, SIGNAL( triggered( QAction* ) ), this, SLOT( pickCoordSystem( QAction* ) ) );
-  connect( floorstyle, SIGNAL( triggered( QAction* ) ), this, SLOT( pickFloorStyle( QAction* ) ) );
-  connect( plotstyle, SIGNAL( triggered( QAction* ) ), this, SLOT( pickPlotStyle( QAction* ) ) );
-
-  connect( left, SIGNAL( triggered( bool ) ), this, SLOT( setLeftGrid3DPlot(bool) ));
-  connect( right, SIGNAL( triggered( bool ) ), this, SLOT( setRightGrid3DPlot( bool ) ) );
-  connect( ceil, SIGNAL( triggered( bool ) ), this, SLOT( setCeilGrid3DPlot( bool ) ) );
-  connect( floor, SIGNAL( triggered( bool ) ), this, SLOT(setFloorGrid3DPlot( bool ) ) );
-  connect( back, SIGNAL( triggered( bool ) ), this, SLOT(setBackGrid3DPlot( bool ) ) );
-  connect( front, SIGNAL( triggered( bool ) ), this, SLOT( setFrontGrid3DPlot( bool ) ) );
-}
-
-void ApplicationWindow::pixelLineProfile()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g)
-    return;
-
-  bool ok;
-  int res = QInputDialog::getInteger(
-      tr("MantidPlot - Set the number of pixels to average"), tr("Number of averaged pixels"),1, 1, 2000, 2,//Mantid
-      &ok, this );
-  if ( !ok )
-    return;
-
-  LineProfileTool *lpt = new LineProfileTool(g, this, res);
-  g->setActiveTool(lpt);
-}
-
-void ApplicationWindow::intensityTable()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (g){
-    ImageMarker *im = (ImageMarker *) g->selectedMarkerPtr();
-    if (im){
-      QString fn = im->fileName();
-      if (!fn.isEmpty())
-        importImage(fn);
-    }
-  }
-}
-
-void ApplicationWindow::autoArrangeLayers()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  plot->setMargins(5, 5, 5, 5);
-  plot->setSpacing(5, 5);
-  plot->arrangeLayers(true, false);
-}
-
-void ApplicationWindow::addLayer()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  switch(QMessageBox::information(this,
-      tr("MantidPlot - Guess best origin for the new layer?"),//Mantid
-      tr("Do you want MantidPlot to guess the best position for the new layer?\n Warning: this will rearrange existing layers!"),//Mantid
-      tr("&Guess"), tr("&Top-left corner"), tr("&Cancel"), 0, 2 ) )
-  {
-  case 0:
-  {
-    setPreferences(plot->addLayer());
-    plot->arrangeLayers(true, false);
-  }
-  break;
-
-  case 1:
-    setPreferences(plot->addLayer(0, 0, plot->size().width(), plot->size().height()));
-    break;
-
-  case 2:
-    return;
-    break;
-  }
-}
-
-void ApplicationWindow::deleteLayer()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  plot->confirmRemoveLayer();
-}
-
-Note* ApplicationWindow::openNote(ApplicationWindow* app, const QStringList &flist)
-{
-  QStringList lst = flist[0].split("\t", QString::SkipEmptyParts);
-  QString caption = lst[0];
-  Note* w = app->newNote(caption);
-  if (lst.count() == 2){
-    app->setListViewDate(caption, lst[1]);
-    w->setBirthDate(lst[1]);
-  }
-  restoreWindowGeometry(app, w, flist[1]);
-
-  lst=flist[2].split("\t");
-  w->setWindowLabel(lst[1]);
-  w->setCaptionPolicy((MdiSubWindow::CaptionPolicy)lst[2].toInt());
-  return w;
-}
-
-Matrix* ApplicationWindow::openMatrix(ApplicationWindow* app, const QStringList &flist)
-{
-  QStringList::const_iterator line = flist.begin();
-
-  QStringList list=(*line).split("\t");
-  QString caption=list[0];
-  int rows = list[1].toInt();
-  int cols = list[2].toInt();
-
-  Matrix* w = app->newMatrix(caption, rows, cols);
-  app->setListViewDate(caption,list[3]);
-  w->setBirthDate(list[3]);
-
-  for (line++; line!=flist.end(); line++)
-  {
-    QStringList fields = (*line).split("\t");
-    if (fields[0] == "geometry") {
-      restoreWindowGeometry(app, w, *line);
-    } else if (fields[0] == "ColWidth") {
-      w->setColumnsWidth(fields[1].toInt());
-    } else if (fields[0] == "Formula") {
-      w->setFormula(fields[1]);
-    } else if (fields[0] == "<formula>") {
-      QString formula;
-      for (line++; line!=flist.end() && *line != "</formula>"; line++)
-        formula += *line + "\n";
-      formula.truncate(formula.length()-1);
-      w->setFormula(formula);
-    } else if (fields[0] == "TextFormat") {
-      if (fields[1] == "f")
-        w->setTextFormat('f', fields[2].toInt());
-      else
-        w->setTextFormat('e', fields[2].toInt());
-    } else if (fields[0] == "WindowLabel") { // d_file_version > 71
-      w->setWindowLabel(fields[1]);
-      w->setCaptionPolicy((MdiSubWindow::CaptionPolicy)fields[2].toInt());
-    } else if (fields[0] == "Coordinates") { // d_file_version > 81
-      w->setCoordinates(fields[1].toDouble(), fields[2].toDouble(), fields[3].toDouble(), fields[4].toDouble());
-    } else if (fields[0] == "ViewType") { // d_file_version > 90
-      w->setViewType((Matrix::ViewType)fields[1].toInt());
-    } else if (fields[0] == "HeaderViewType") { // d_file_version > 90
-      w->setHeaderViewType((Matrix::HeaderViewType)fields[1].toInt());
-    } else if (fields[0] == "ColorPolicy"){// d_file_version > 90
-      w->setColorMapType((Matrix::ColorMapType)fields[1].toInt());
-    } else if (fields[0] == "<ColorMap>"){// d_file_version > 90
-      QStringList lst;
-      while ( *line != "</ColorMap>" ){
-        line++;
-        lst << *line;
-      }
-      lst.pop_back();
-      w->setColorMap(lst);
-    } else // <data> or values
-      break;
-  }
-  if (*line == "<data>") line++;
-
-  //read and set table values
-  for (; line!=flist.end() && *line != "</data>"; line++){
-    QStringList fields = (*line).split("\t");
-    int row = fields[0].toInt();
-    for (int col=0; col<cols; col++){
-      QString cell = fields[col+1];
-      if (cell.isEmpty())
-        continue;
-
-      if (d_file_version < 90)
-        w->setCell(row, col, QLocale::c().toDouble(cell));
-      else if (d_file_version == 90)
-        w->setText(row, col, cell);
-      else
-        w->setCell(row, col, cell.toDouble());
-    }
-    qApp->processEvents(QEventLoop::ExcludeUserInput);
-  }
-  w->resetView();
-  return w;
-}
-void ApplicationWindow::openMantidMatrix(const QStringList &list)
-{ 	
-  QString s=list[0];
-  QStringList qlist=s.split("\t");
-  QString wsName=qlist[1];
-  MantidMatrix *m=newMantidMatrix(wsName,-1,-1);//mantidUI->importMatrixWorkspace(wsName,-1,-1,false,false);
-  //if(!m)throw std::runtime_error("Error on opening matrixworkspace ");
-  if(!m) return;
-  //adding the mantid matrix windows opened to a list.
-  //this list is used for find the MantidMatrix window pointer to open a 3D/2DGraph
-  m_mantidmatrixWindows<<m;
-  QStringList::const_iterator line = list.begin();
-  for (line++; line!=list.end(); line++)
-  {	QStringList fields = (*line).split("\t");
-  if (fields[0] == "geometry" || fields[0] == "tgeometry") {
-    restoreWindowGeometry(this, m, *line);
-  }
-  }
-}
-void ApplicationWindow::openInstrumentWindow(const QStringList &list)
-{
-  QString s=list[0];
-  QStringList qlist=s.split("\t");
-  QString wsName=qlist[1];
-  InstrumentWindow *insWin = mantidUI->getInstrumentView(wsName);
-  if(!insWin) return;
-  insWin->show();
-  QStringList::const_iterator line = list.begin();
-  for (line++; line!=list.end(); line++)
-  {	QStringList fields = (*line).split("\t");
-  if (fields[0] == "geometry" || fields[0] == "tgeometry") {
-    restoreWindowGeometry(this, insWin, *line);
-  }
-  }
-}
-/** This method opens script window when  project file is loaded
- */
-void ApplicationWindow::openScriptWindow(const QStringList &list)
-{	showScriptWindow();
-if(!scriptingWindow) return;
-scriptingWindow->setWindowTitle("MantidPlot: " + scriptingEnv()->scriptingLanguage() + " Window");
-QString s=list[0];
-QStringList scriptnames=s.split("\t");
-int count=scriptnames.size();
-if(count==0) return;
-// don't create a new tab when the first script file from theproject file  opened
-if(!scriptnames[1].isEmpty()) scriptingWindow->open(scriptnames[1],false);
-// create a new tab  and open the script for all otehr filenames
-for(int i=2;i<count;++i)
-{   if(!scriptnames[i].isEmpty())scriptingWindow->open(scriptnames[i],true);
-}
-}
-/** This method populates the mantid workspace tree when  project file is loaded 
- */
-void ApplicationWindow::populateMantidTreeWdiget(const QString &s)
-{	
-  QStringList list = s.split("\t");
-  QStringList::const_iterator line = list.begin();
-  for (++line; line!=list.end(); ++line)
-  {	std::string wsName=(*line).toStdString();
-  if(wsName.empty())throw std::runtime_error("Workspace Name not found in project file ");
-  std::string fileName(workingDir.toStdString()+"/"+wsName);
-  fileName.append(".nxs");
-  try
-  {
-    mantidUI->loaddataFromNexusFile(wsName,fileName,true);
-  }
-  catch(...)
-  {
-  }
-  }
-}
-/** This method opens mantid matrix window when  project file is loaded 
- */
-MantidMatrix* ApplicationWindow::newMantidMatrix(const QString& wsName,int lower,int upper)
-{	
-  MantidMatrix* m=mantidUI->openMatrixWorkspace(this,wsName,lower,upper);
-  return m;
-}
-Table* ApplicationWindow::openTable(ApplicationWindow* app, const QStringList &flist)
-{
-  QStringList::const_iterator line = flist.begin();
-
-  QStringList list=(*line).split("\t");
-  QString caption=list[0];
-  int rows = list[1].toInt();
-  int cols = list[2].toInt();
-
-  Table* w = app->newTable(caption, rows, cols);
-  app->setListViewDate(caption, list[3]);
-  w->setBirthDate(list[3]);
-
-  for (line++; line!=flist.end(); line++)
-  {
-    QStringList fields = (*line).split("\t");
-    if (fields[0] == "geometry" || fields[0] == "tgeometry") {
-      restoreWindowGeometry(app, w, *line);
-    } else if (fields[0] == "header") {
-      fields.pop_front();
-      if (d_file_version >= 78)
-        w->loadHeader(fields);
-      else
-      {
-        w->setColPlotDesignation(list[4].toInt(), Table::X);
-        w->setColPlotDesignation(list[6].toInt(), Table::Y);
-        w->setHeader(fields);
-      }
-    } else if (fields[0] == "ColWidth") {
-      fields.pop_front();
-      w->setColWidths(fields);
-    } else if (fields[0] == "com") { // legacy code
-      w->setCommands(*line);
-    } else if (fields[0] == "<com>") {
-      for (line++; line!=flist.end() && *line != "</com>"; line++)
-      {
-        int col = (*line).mid(9,(*line).length()-11).toInt();
-        QString formula;
-        for (line++; line!=flist.end() && *line != "</col>"; line++)
-          formula += *line + "\n";
-        formula.truncate(formula.length()-1);
-        w->setCommand(col,formula);
-      }
-    } else if (fields[0] == "ColType") { // d_file_version > 65
-      fields.pop_front();
-      w->setColumnTypes(fields);
-    } else if (fields[0] == "Comments") { // d_file_version > 71
-      fields.pop_front();
-      w->setColComments(fields);
-      w->setHeaderColType();
-    } else if (fields[0] == "WindowLabel") { // d_file_version > 71
-      w->setWindowLabel(fields[1]);
-      w->setCaptionPolicy((MdiSubWindow::CaptionPolicy)fields[2].toInt());
-    } else if (fields[0] == "ReadOnlyColumn") { // d_file_version > 91
-      fields.pop_front();
-      for (int i=0; i < w->numCols(); i++)
-        w->setReadOnlyColumn(i, fields[i] == "1");
-    } else if (fields[0] == "HiddenColumn") { // d_file_version >= 93
-      fields.pop_front();
-      for (int i=0; i < w->numCols(); i++)
-        w->hideColumn(i, fields[i] == "1");
-    } else // <data> or values
-      break;
-  }
-
-  QApplication::setOverrideCursor(Qt::WaitCursor);
-  w->table()->blockSignals(true);
-  for (line++; line!=flist.end() && *line != "</data>"; line++)
-  {//read and set table values
-    QStringList fields = (*line).split("\t");
-    int row = fields[0].toInt();
-    for (int col=0; col<cols; col++){
-      if (fields.count() >= col+2){
-        QString cell = fields[col+1];
-        if (cell.isEmpty())
-          continue;
-
-        if (w->columnType(col) == Table::Numeric){
-          if (d_file_version < 90)
-            w->setCell(row, col, QLocale::c().toDouble(cell.replace(",", ".")));
-          else if (d_file_version == 90)
-            w->setText(row, col, cell);
-          else if (d_file_version >= 91)
-            w->setCell(row, col, cell.toDouble());
-        } else
-          w->setText(row, col, cell);
-      }
-    }
-    QApplication::processEvents(QEventLoop::ExcludeUserInput);
-  }
-  QApplication::restoreOverrideCursor();
-
-  w->setSpecifications(w->saveToString("geometry\n"));
-  w->table()->blockSignals(false);
-  return w;
-}
-
-TableStatistics* ApplicationWindow::openTableStatistics(const QStringList &flist)
-{
-  QStringList::const_iterator line = flist.begin();
-
-  QStringList list=(*line++).split("\t");
-  QString caption=list[0];
-
-  QList<int> targets;
-  for (int i=1; i <= (*line).count('\t'); i++)
-    targets << (*line).section('\t',i,i).toInt();
-
-  TableStatistics* w = newTableStatistics(table(list[1]),
-      list[2]=="row" ? TableStatistics::row : TableStatistics::column, targets, caption);
-
-  setListViewDate(caption,list[3]);
-  w->setBirthDate(list[3]);
-
-  for (line++; line!=flist.end(); line++)
-  {
-    QStringList fields = (*line).split("\t");
-    if (fields[0] == "geometry"){
-      restoreWindowGeometry(this, w, *line);}
-    else if (fields[0] == "header") {
-      fields.pop_front();
-      if (d_file_version >= 78)
-        w->loadHeader(fields);
-      else
-      {
-        w->setColPlotDesignation(list[4].toInt(), Table::X);
-        w->setColPlotDesignation(list[6].toInt(), Table::Y);
-        w->setHeader(fields);
-      }
-    } else if (fields[0] == "ColWidth") {
-      fields.pop_front();
-      w->setColWidths(fields);
-    } else if (fields[0] == "com") { // legacy code
-      w->setCommands(*line);
-    } else if (fields[0] == "<com>") {
-      for (line++; line!=flist.end() && *line != "</com>"; line++)
-      {
-        int col = (*line).mid(9,(*line).length()-11).toInt();
-        QString formula;
-        for (line++; line!=flist.end() && *line != "</col>"; line++)
-          formula += *line + "\n";
-        formula.truncate(formula.length()-1);
-        w->setCommand(col,formula);
-      }
-    } else if (fields[0] == "ColType") { // d_file_version > 65
-      fields.pop_front();
-      w->setColumnTypes(fields);
-    } else if (fields[0] == "Comments") { // d_file_version > 71
-      fields.pop_front();
-      w->setColComments(fields);
-    } else if (fields[0] == "WindowLabel") { // d_file_version > 71
-      w->setWindowLabel(fields[1]);
-      w->setCaptionPolicy((MdiSubWindow::CaptionPolicy)fields[2].toInt());
-    }
-  }
-  return w;
-}
-
-Graph* ApplicationWindow::openGraph(ApplicationWindow* app, MultiLayer *plot,
-    const QStringList &list)
-{
-  Graph* ag = 0;
-  int curveID = 0;
-  QString wsName;
-  for (int j=0;j<(int)list.count()-1;j++){
-    QString s=list[j];
-    if (s.contains ("ggeometry")){
-      QStringList fList=s.split("\t");
-      ag =(Graph*)plot->addLayer(fList[1].toInt(), fList[2].toInt(),
-          fList[3].toInt(), fList[4].toInt());
-
-      ag->blockSignals(true);
-      ag->enableAutoscaling(autoscale2DPlots);
-
-    }
-    else if( s.contains("MantidCurve")) //1D plot curves
-    {
-      QStringList curvelst=s.split("\t");
-      if( !curvelst[1].isEmpty()&& !curvelst[2].isEmpty())
-      {
-        try {
-          new MantidCurve(curvelst[1],ag,curvelst[2],curvelst[3].toInt(),curvelst[4].toInt());
-        } catch (Mantid::Kernel::Exception::NotFoundError &) {
-          // Get here if workspace name is invalid - shouldn't be possible, but just in case
-          closeWindow(plot);
-          return 0;
-
-        } catch (std::invalid_argument&) {
-          // Get here if invalid spectrum number given - shouldn't be possible, but just in case
-          // plot->askOnCloseEvent(false);
-          //plot->close();
-          closeWindow(plot);
-          return 0;
-        }
-      }
-    }
-    else if (s.left(10) == "Background"){
-      QStringList fList = s.split("\t");
-      QColor c = QColor(fList[1]);
-      if (fList.count() == 3)
-        c.setAlpha(fList[2].toInt());
-      ag->setBackgroundColor(c);
-    }
-    else if (s.contains ("Margin")){
-      QStringList fList=s.split("\t");
-      ag->plotWidget()->setMargin(fList[1].toInt());
-    }
-    else if (s.contains ("Border")){
-      QStringList fList=s.split("\t");
-      ag->setFrame(fList[1].toInt(), QColor(fList[2]));
-    }
-    else if (s.contains ("EnabledAxes")){
-      QStringList fList=s.split("\t");
-      fList.pop_front();
-      for (int i=0; i<(int)fList.count(); i++)
-        ag->enableAxis(i, fList[i].toInt());
-    }
-    else if (s.contains ("AxesBaseline")){
-      QStringList fList = s.split("\t", QString::SkipEmptyParts);
-      fList.pop_front();
-      for (int i=0; i<(int)fList.count(); i++)
-        ag->setAxisMargin(i, fList[i].toInt());
-    }
-    else if (s.contains ("EnabledTicks"))
-    {//version < 0.8.6
-      QStringList fList=s.split("\t");
-      fList.pop_front();
-      fList.replaceInStrings("-1", "3");
-      ag->setMajorTicksType(fList);
-      ag->setMinorTicksType(fList);
-    }
-    else if (s.contains ("MajorTicks"))
-    {//version >= 0.8.6
-      QStringList fList=s.split("\t");
-      fList.pop_front();
-      ag->setMajorTicksType(fList);
-    }
-    else if (s.contains ("MinorTicks"))
-    {//version >= 0.8.6
-      QStringList fList=s.split("\t");
-      fList.pop_front();
-      ag->setMinorTicksType(fList);
-    }
-    else if (s.contains ("TicksLength")){
-      QStringList fList=s.split("\t");
-      ag->setTicksLength(fList[1].toInt(), fList[2].toInt());
-    }
-    else if (s.contains ("EnabledTickLabels")){
-      QStringList fList=s.split("\t");
-      fList.pop_front();
-      for (int i=0; i<int(fList.count()); i++)
-        ag->enableAxisLabels(i, fList[i].toInt());
-    }
-    else if (s.contains ("AxesColors")){
-      QStringList fList = s.split("\t");
-      fList.pop_front();
-      for (int i=0; i<int(fList.count()); i++)
-        ag->setAxisColor(i, QColor(fList[i]));
-    }
-    else if (s.contains ("AxesNumberColors")){
-      QStringList fList=QStringList::split ("\t",s,TRUE);
-      fList.pop_front();
-      for (int i=0; i<int(fList.count()); i++)
-        ag->setAxisLabelsColor(i, QColor(fList[i]));
-    }
-    else if (s.left(5)=="grid\t"){
-      ag->plotWidget()->grid()->load(s.split("\t"));
-    }
-    else if (s.startsWith ("<Antialiasing>") && s.endsWith ("</Antialiasing>")){
-      bool antialiasing = s.remove("<Antialiasing>").remove("</Antialiasing>").toInt();
-      ag->setAntialiasing(antialiasing);
-    }
-    else if (s.contains ("PieCurve")){
-      QStringList curve=s.split("\t");
-      if (!app->renamedTables.isEmpty()){
-        QString caption = (curve[1]).left((curve[1]).find("_",0));
-        if (app->renamedTables.contains(caption))
-        {//modify the name of the curve according to the new table name
-          int index = app->renamedTables.findIndex(caption);
-          QString newCaption = app->renamedTables[++index];
-          curve.replaceInStrings(caption+"_", newCaption+"_");
-        }
-      }
-      QPen pen = QPen(QColor(curve[3]), curve[2].toDouble(),Graph::getPenStyle(curve[4]));
-
-      Table *table = app->table(curve[1]);
-      if (table){
-        int startRow = 0;
-        int endRow = table->numRows() - 1;
-        int first_color = curve[7].toInt();
-        bool visible = true;
-        if (d_file_version >= 90)
-        {
-          startRow = curve[8].toInt();
-          endRow = curve[9].toInt();
-          visible = curve[10].toInt();
-        }
-
-        if (d_file_version <= 89)
-          first_color = convertOldToNewColorIndex(first_color);
-
-        if (curve.size() >= 22){//version 0.9.3-rc3
-          ag->plotPie(table, curve[1], pen, curve[5].toInt(),
-              curve[6].toInt(), first_color, startRow, endRow, visible,
-              curve[11].toDouble(), curve[12].toDouble(), curve[13].toDouble(),
-              curve[14].toDouble(), curve[15].toDouble(), curve[16].toInt(),
-              curve[17].toInt(), curve[18].toInt(), curve[19].toInt(),
-              curve[20].toInt(), curve[21].toInt());
-        } else
-          ag->plotPie(table, curve[1], pen, curve[5].toInt(),
-              curve[6].toInt(), first_color, startRow, endRow, visible);
-      }
-    }else if (s.left(6)=="curve\t"){
-      QStringList curve = s.split("\t", QString::SkipEmptyParts);
-      if (!app->renamedTables.isEmpty()){
-        QString caption = (curve[2]).left((curve[2]).find("_",0));
-        if (app->renamedTables.contains(caption))
-        {//modify the name of the curve according to the new table name
-          int index = app->renamedTables.findIndex (caption);
-          QString newCaption = app->renamedTables[++index];
-          curve.replaceInStrings(caption+"_", newCaption+"_");
-        }
-      }
-
-      CurveLayout cl;
-      cl.connectType=curve[4].toInt();
-      cl.lCol=curve[5].toInt();
-      if (d_file_version <= 89)
-        cl.lCol = convertOldToNewColorIndex(cl.lCol);
-      cl.lStyle=curve[6].toInt();
-      cl.lWidth=curve[7].toDouble();
-      cl.sSize=curve[8].toInt();
-      if (d_file_version <= 78)
-        cl.sType=Graph::obsoleteSymbolStyle(curve[9].toInt());
-      else
-        cl.sType=curve[9].toInt();
-
-      cl.symCol=curve[10].toInt();
-      if (d_file_version <= 89)
-        cl.symCol = convertOldToNewColorIndex(cl.symCol);
-      cl.fillCol=curve[11].toInt();
-      if (d_file_version <= 89)
-        cl.fillCol = convertOldToNewColorIndex(cl.fillCol);
-      cl.filledArea=curve[12].toInt();
-      cl.aCol=curve[13].toInt();
-      if (d_file_version <= 89)
-        cl.aCol = convertOldToNewColorIndex(cl.aCol);
-      cl.aStyle=curve[14].toInt();
-      if(curve.count() < 16)
-        cl.penWidth = cl.lWidth;
-      else if ((d_file_version >= 79) && (curve[3].toInt() == Graph::Box))
-        cl.penWidth = curve[15].toDouble();
-      else if ((d_file_version >= 78) && (curve[3].toInt() <= Graph::LineSymbols))
-        cl.penWidth = curve[15].toDouble();
-      else
-        cl.penWidth = cl.lWidth;
-
-      int plotType = curve[3].toInt();
-      Table *w = app->table(curve[2]);
-      PlotCurve *c = NULL;
-      if (w){
-        if(plotType == Graph::VectXYXY || plotType == Graph::VectXYAM){
-          QStringList colsList;
-          colsList<<curve[2]; colsList<<curve[20]; colsList<<curve[21];
-          if (d_file_version < 72)
-            colsList.prepend(w->colName(curve[1].toInt()));
-          else
-            colsList.prepend(curve[1]);
-
-          int startRow = 0;
-          int endRow = -1;
-          if (d_file_version >= 90){
-            startRow = curve[curve.count()-3].toInt();
-            endRow = curve[curve.count()-2].toInt();
-          }
-
-          c = (PlotCurve *)ag->plotVectorCurve(w, colsList, plotType, startRow, endRow);
-
-          if (d_file_version <= 77){
-            int temp_index = convertOldToNewColorIndex(curve[15].toInt());
-            ag->updateVectorsLayout(curveID, ColorBox::color(temp_index), curve[16].toDouble(), curve[17].toInt(),
-                curve[18].toInt(), curve[19].toInt(), 0, curve[20], curve[21]);
-          } else {
-            if(plotType == Graph::VectXYXY)
-              ag->updateVectorsLayout(curveID, curve[15], curve[16].toDouble(),
-                  curve[17].toInt(), curve[18].toInt(), curve[19].toInt(), 0);
-            else
-              ag->updateVectorsLayout(curveID, curve[15], curve[16].toDouble(), curve[17].toInt(),
-                  curve[18].toInt(), curve[19].toInt(), curve[22].toInt());
-          }
-        } else if (plotType == Graph::Box)
-          c = (PlotCurve *)ag->openBoxDiagram(w, curve, d_file_version);
-        else {
-          if (d_file_version < 72)
-            c = (PlotCurve *)ag->insertCurve(w, curve[1].toInt(), curve[2], plotType);
-          else if (d_file_version < 90)
-            c = (PlotCurve *)ag->insertCurve(w, curve[1], curve[2], plotType);
-          else{
-            int startRow = curve[curve.count()-3].toInt();
-            int endRow = curve[curve.count()-2].toInt();
-            c = (PlotCurve *)ag->insertCurve(w, curve[1], curve[2], plotType, startRow, endRow);
-          }
-        }
-
-        if(plotType == Graph::Histogram){
-          QwtHistogram *h = (QwtHistogram *)ag->curve(curveID);
-          if (d_file_version <= 76)
-            h->setBinning(curve[16].toInt(),curve[17].toDouble(),curve[18].toDouble(),curve[19].toDouble());
-          else
-            h->setBinning(curve[17].toInt(),curve[18].toDouble(),curve[19].toDouble(),curve[20].toDouble());
-          h->loadData();
-        }
-
-        if(plotType == Graph::VerticalBars || plotType == Graph::HorizontalBars ||
-            plotType == Graph::Histogram){
-          if (d_file_version <= 76)
-            ag->setBarsGap(curveID, curve[15].toInt(), 0);
-          else
-            ag->setBarsGap(curveID, curve[15].toInt(), curve[16].toInt());
-        }
-        ag->updateCurveLayout(c, &cl);
-        if (d_file_version >= 88){
-          if (c && c->rtti() == QwtPlotItem::Rtti_PlotCurve){
-            if (d_file_version < 90)
-              c->setAxis(curve[curve.count()-2].toInt(), curve[curve.count()-1].toInt());
-            else {
-              c->setAxis(curve[curve.count()-5].toInt(), curve[curve.count()-4].toInt());
-              c->setVisible(curve.last().toInt());
-            }
-          }
-        }
-      } else if(plotType == Graph::Histogram){//histograms from matrices
-        Matrix *m = app->matrix(curve[2]);
-        QwtHistogram *h = ag->restoreHistogram(m, curve);
-        ag->updateCurveLayout(h, &cl);
-      }
-      curveID++;
-    } else if (s == "<CurveLabels>"){
-      QStringList lst;
-      while ( s!="</CurveLabels>" ){
-        s = list[++j];
-        lst << s;
-      }
-      lst.pop_back();
-      ag->restoreCurveLabels(curveID - 1, lst);
-    } else if (s == "<Function>"){//version 0.9.5
-      curveID++;
-      QStringList lst;
-      while ( s != "</Function>" ){
-        s = list[++j];
-        lst << s;
-      }
-      lst.pop_back();
-      ag->restoreFunction(lst);
-    } else if (s.contains ("FunctionCurve")){
-      QStringList curve = s.split("\t");
-      CurveLayout cl;
-      cl.connectType=curve[6].toInt();
-      cl.lCol=curve[7].toInt();
-      cl.lStyle=curve[8].toInt();
-      cl.lWidth=curve[9].toDouble();
-      cl.sSize=curve[10].toInt();
-      cl.sType=curve[11].toInt();
-      cl.symCol=curve[12].toInt();
-      cl.fillCol=curve[13].toInt();
-      cl.filledArea=curve[14].toInt();
-      cl.aCol=curve[15].toInt();
-      cl.aStyle=curve[16].toInt();
-      int current_index = 17;
-      if(curve.count() < 16)
-        cl.penWidth = cl.lWidth;
-      else if ((d_file_version >= 79) && (curve[5].toInt() == Graph::Box))
-      {
-        cl.penWidth = curve[17].toDouble();
-        current_index++;
-      }
-      else if ((d_file_version >= 78) && (curve[5].toInt() <= Graph::LineSymbols))
-      {
-        cl.penWidth = curve[17].toDouble();
-        current_index++;
-      }
-      else
-        cl.penWidth = cl.lWidth;
-
-      PlotCurve *c = (PlotCurve *)ag->insertFunctionCurve(curve[1], curve[2].toInt(), d_file_version);
-      ag->setCurveType(curveID, curve[5].toInt());
-      ag->updateCurveLayout(c, &cl);
-      if (d_file_version >= 88){
-        QwtPlotCurve *c = ag->curve(curveID);
-        if (c){
-          if(current_index + 1 < curve.size())
-            c->setAxis(curve[current_index].toInt(), curve[current_index+1].toInt());
-          if (d_file_version >= 90 && current_index+2 < curve.size())
-            c->setVisible(curve.last().toInt());
-          else
-            c->setVisible(true);
-        }
-
-      }
-      curveID++;
-    }
-    else if (s.contains ("ErrorBars")){
-      QStringList curve = s.split("\t", QString::SkipEmptyParts);
-      if (!app->renamedTables.isEmpty()){
-        QString caption = (curve[4]).left((curve[4]).find("_",0));
-        if (app->renamedTables.contains(caption))
-        {//modify the name of the curve according to the new table name
-          int index = app->renamedTables.findIndex (caption);
-          QString newCaption = app->renamedTables[++index];
-          curve.replaceInStrings(caption+"_", newCaption+"_");
-        }
-      }
-      Table *w = app->table(curve[3]);
-      Table *errTable = app->table(curve[4]);
-      if (w && errTable){
-        ag->addErrorBars(curve[2], curve[3], errTable, curve[4], curve[1].toInt(),
-            curve[5].toDouble(), curve[6].toInt(), QColor(curve[7]),
-            curve[8].toInt(), curve[10].toInt(), curve[9].toInt());
-      }
-      curveID++;
-    }
-    else if (s == "<spectrogram>"){
-      QStringList lst;
-      lst<<list[0];
-      lst<<list[1];
-      QString lineone=lst[1];
-      QStringList lineonelst=lineone.split("\t");
-      QString name=lineonelst[1];
-      QStringList qlist=name.split(" ");
-      std::string specgramwsName =qlist[1].toStdString();
-
-      lst.clear();
-      while ( s!="</spectrogram>" ){
-        s = list[++j];
-        lst << s;
-      }
-      lst.pop_back();
-      Spectrogram* sp=openSpectrogram(ag,specgramwsName,lst);
-      if(!sp)
-      {	  closeWindow(plot);
-      return 0;
-      }
-      curveID++;
-    }
-    else if (s.left(6) == "scale\t"){
-      QStringList scl = s.split("\t");
-      scl.pop_front();
-      int size = scl.count();
-      if (d_file_version < 88){
-        double step = scl[2].toDouble();
-        if (scl[5] == "0")
-          step = 0.0;
-        ag->setScale(QwtPlot::xBottom, scl[0].toDouble(), scl[1].toDouble(), step,
-            scl[3].toInt(), scl[4].toInt(), scl[6].toInt(), bool(scl[7].toInt()));
-        ag->setScale(QwtPlot::xTop, scl[0].toDouble(), scl[1].toDouble(), step,
-            scl[3].toInt(), scl[4].toInt(), scl[6].toInt(), bool(scl[7].toInt()));
-
-        step = scl[10].toDouble();
-        if (scl[13] == "0")
-          step = 0.0;
-        ag->setScale(QwtPlot::yLeft, scl[8].toDouble(), scl[9].toDouble(), step, scl[11].toInt(),
-            scl[12].toInt(), scl[14].toInt(), bool(scl[15].toInt()));
-        ag->setScale(QwtPlot::yRight, scl[8].toDouble(), scl[9].toDouble(), step, scl[11].toInt(),
-            scl[12].toInt(), scl[14].toInt(), bool(scl[15].toInt()));
-      }
-      else if (size == 8){
-        ag->setScale(scl[0].toInt(), scl[1].toDouble(), scl[2].toDouble(), scl[3].toDouble(),
-            scl[4].toInt(), scl[5].toInt(),  scl[6].toInt(), bool(scl[7].toInt()));
-      }
-      else if (size == 9){
-
-        if(scl[8].toInt()==1)
-        {	//if axis details like scale,majortick,minor tick changed
-          ag->setScale(scl[0].toInt(), scl[1].toDouble(), scl[2].toDouble(), scl[3].toDouble(),
-              scl[4].toInt(), scl[5].toInt(),  scl[6].toInt(), bool(scl[7].toInt()));
-        }
-      }
-      else if (size == 18){
-        ag->setScale(scl[0].toInt(), scl[1].toDouble(), scl[2].toDouble(), scl[3].toDouble(),
-            scl[4].toInt(), scl[5].toInt(), scl[6].toInt(), bool(scl[7].toInt()), scl[8].toDouble(),
-            scl[9].toDouble(), scl[10].toInt(), scl[11].toDouble(), scl[12].toDouble(), scl[13].toInt(),
-            scl[14].toInt(), bool(scl[15].toInt()), scl[16].toInt(), bool(scl[17].toInt()));
-      }
-      else if (size == 19){
-        //if axis details scale,majortick,minor tick changed
-        if(scl[8].toInt()==1)
-          ag->setScale(scl[0].toInt(), scl[1].toDouble(), scl[2].toDouble(), scl[3].toDouble(),
-              scl[4].toInt(), scl[5].toInt(), scl[6].toInt(), bool(scl[7].toInt()), scl[8].toDouble(),
-              scl[9].toDouble(), scl[10].toInt(), scl[11].toDouble(), scl[12].toDouble(), scl[13].toInt(),
-              scl[14].toInt(), bool(scl[15].toInt()), scl[16].toInt(), bool(scl[17].toInt()));
-      }
-    }
-    else if (s.contains ("PlotTitle")){
-      QStringList fList=s.split("\t");
-      wsName=fList[1].split(" ")[1];
-      ag->setTitle(fList[1]);
-      ag->setTitleColor(QColor(fList[2]));
-      ag->setTitleAlignment(fList[3].toInt());
-    }
-    else if (s.contains ("TitleFont")){
-      QStringList fList=s.split("\t");
-      QFont fnt=QFont (fList[1],fList[2].toInt(),fList[3].toInt(),fList[4].toInt());
-      fnt.setUnderline(fList[5].toInt());
-      fnt.setStrikeOut(fList[6].toInt());
-      ag->setTitleFont(fnt);
-    }
-    else if (s.contains ("AxesTitles")){
-      QStringList lst=s.split("\t");
-      lst.pop_front();
-      for (int i=0; i<4; i++){
-        if (lst.count() > i)
-          ag->setScaleTitle(i, lst[i]);
-      }
-    }
-    else if (s.contains ("AxesTitleColors")){
-      QStringList colors = s.split("\t", QString::SkipEmptyParts);
-      colors.pop_front();
-      for (int i=0; i<int(colors.count()); i++)
-        ag->setAxisTitleColor(i, colors[i]);
-    }else if (s.contains ("AxesTitleAlignment")){
-      QStringList align=s.split("\t", QString::SkipEmptyParts);
-      align.pop_front();
-      for (int i=0; i<(int)align.count(); i++)
-        ag->setAxisTitleAlignment(i, align[i].toInt());
-    }else if (s.contains ("ScaleFont")){
-      QStringList fList=s.split("\t");
-      QFont fnt=QFont (fList[1],fList[2].toInt(),fList[3].toInt(),fList[4].toInt());
-      fnt.setUnderline(fList[5].toInt());
-      fnt.setStrikeOut(fList[6].toInt());
-
-      int axis=(fList[0].right(1)).toInt();
-      ag->setAxisTitleFont(axis,fnt);
-    }else if (s.contains ("AxisFont")){
-      QStringList fList=s.split("\t");
-      QFont fnt=QFont (fList[1],fList[2].toInt(),fList[3].toInt(),fList[4].toInt());
-      fnt.setUnderline(fList[5].toInt());
-      fnt.setStrikeOut(fList[6].toInt());
-
-      int axis=(fList[0].right(1)).toInt();
-      ag->setAxisFont(axis,fnt);
-    }
-    else if (s.contains ("AxesFormulas"))
-    {	QStringList fList=s.split("\t");
-    fList.remove(fList.first());
-    for (int i=0; i<(int)fList.count(); i++)
-      ag->setAxisFormula(i, fList[i]);
-    }
-    else if (s.startsWith("<AxisFormula "))
-    {
-      int axis = s.mid(18,s.length()-20).toInt();
-      QString formula;
-      for (j++; j<(int)list.count() && list[j] != "</AxisFormula>"; j++)
-        formula += list[j] + "\n";
-      formula.truncate(formula.length()-1);
-      ag->setAxisFormula(axis, formula);
-    }
-    else if (s.contains ("LabelsFormat"))
-    {
-      QStringList fList=s.split("\t");
-      fList.pop_front();
-      ag->setLabelsNumericFormat(fList);
-    }
-    else if (s.contains ("LabelsRotation"))
-    {
-      QStringList fList=s.split("\t");
-      ag->setAxisLabelRotation(QwtPlot::xBottom, fList[1].toInt());
-      ag->setAxisLabelRotation(QwtPlot::xTop, fList[2].toInt());
-    }
-    else if (s.contains ("DrawAxesBackbone"))
-    {
-      QStringList fList=s.split("\t");
-      ag->loadAxesOptions(fList[1]);
-    }
-    else if (s.contains ("AxesLineWidth"))
-    {
-      QStringList fList=s.split("\t");
-      ag->loadAxesLinewidth(fList[1].toInt());
-    }
-    else if (s.contains ("CanvasFrame")){
-      QStringList lst = s.split("\t");
-      ag->setCanvasFrame(lst[1].toInt(), QColor(lst[2]));
-    }
-    else if (s.contains ("CanvasBackground"))
-    {
-      QStringList list = s.split("\t");
-      QColor c = QColor(list[1]);
-      if (list.count() == 3)
-        c.setAlpha(list[2].toInt());
-      ag->setCanvasBackground(c);
-    }
-    else if (s.contains ("Legend"))
-    {// version <= 0.8.9
-      QStringList fList = QStringList::split ("\t",s, true);
-      ag->insertLegend(fList, d_file_version);
-    }
-    else if (s.startsWith ("<legend>") && s.endsWith ("</legend>"))
-    {
-      QStringList fList = QStringList::split ("\t", s.remove("</legend>"), true);
-      ag->insertLegend(fList, d_file_version);
-    }
-    else if (s.contains ("textMarker"))
-    {// version <= 0.8.9
-      QStringList fList = QStringList::split ("\t",s, true);
-      ag->insertText(fList, d_file_version);
-    }
-    else if (s.startsWith ("<text>") && s.endsWith ("</text>"))
-    {
-      QStringList fList = QStringList::split ("\t", s.remove("</text>"), true);
-      ag->insertText(fList, d_file_version);
-    }
-    else if (s.startsWith ("<PieLabel>") && s.endsWith ("</PieLabel>"))
-    {
-      QStringList fList = QStringList::split ("\t", s.remove("</PieLabel>"), true);
-      ag->insertText(fList, d_file_version);
-    }
-    else if (s.contains ("lineMarker"))
-    {// version <= 0.8.9
-      QStringList fList=s.split("\t");
-      ag->addArrow(fList, d_file_version);
-    }
-    else if (s.startsWith ("<line>") && s.endsWith ("</line>"))
-    {
-      QStringList fList=s.remove("</line>").split("\t");
-      ag->addArrow(fList, d_file_version);
-    }
-    else if (s.contains ("ImageMarker") || (s.startsWith ("<image>") && s.endsWith ("</image>")))
-    {
-      QStringList fList=s.remove("</image>").split("\t");
-      ag->insertImageMarker(fList, d_file_version);
-    }
-    else if (s.contains("AxisType"))
-    {
-      QStringList fList = s.split("\t");
-      for (int i=0; i<4; i++){
-        QStringList lst = fList[i+1].split(";", QString::SkipEmptyParts);
-        int format = lst[0].toInt();
-        if (format == ScaleDraw::Numeric)
-          continue;
-        if (format == ScaleDraw::Day)
-          ag->setLabelsDayFormat(i, lst[1].toInt());
-        else if (format == ScaleDraw::Month)
-          ag->setLabelsMonthFormat(i, lst[1].toInt());
-        else if (format == ScaleDraw::Time || format == ScaleDraw::Date)
-          ag->setLabelsDateTimeFormat(i, format, lst[1]+";"+lst[2]);
-        else if (lst.size() > 1)
-          ag->setLabelsTextFormat(i, format, lst[1], app->table(lst[1]));
-      }
-    }
-    else if (d_file_version < 69 && s.contains ("AxesTickLabelsCol"))
-    {
-      QStringList fList = s.split("\t");
-      for (int i=0; i<4; i++){
-        QString colName = fList[i+1];
-        Table *nw = app->table(colName);
-        ag->setLabelsTextFormat(i, ag->axisType(i), colName, nw);
-      }
-    }
-  }
-  ag->replot();
-
-  ag->blockSignals(false);
-  ag->setIgnoreResizeEvents(!app->autoResizeLayers);
-  ag->setAutoscaleFonts(app->autoScaleFonts);
-  return ag;
-}
-
-Graph3D* ApplicationWindow::openSurfacePlot(ApplicationWindow* app, const QStringList &lst)
-{
-  QStringList fList=lst[0].split("\t");
-  QString caption=fList[0];
-  QString date=fList[1];
-  if (date.isEmpty())
-    date = QDateTime::currentDateTime().toString(Qt::LocalDate);
-
-  fList=lst[2].split("\t", QString::SkipEmptyParts);
-  Graph3D *plot=0;
-
-  if (fList[1].endsWith("(Y)",true))
-    plot=app->dataPlot3D(caption, fList[1],fList[2].toDouble(),fList[3].toDouble(),
-        fList[4].toDouble(),fList[5].toDouble(),fList[6].toDouble(),fList[7].toDouble());
-  else if (fList[1].contains("(Z)",true) > 0)
-    plot=app->openPlotXYZ(caption, fList[1], fList[2].toDouble(),fList[3].toDouble(),
-        fList[4].toDouble(),fList[5].toDouble(),fList[6].toDouble(),fList[7].toDouble());
-  else if (fList[1].startsWith("matrix<",true) && fList[1].endsWith(">",false))
-    plot=app->openMatrixPlot3D(caption, fList[1], fList[2].toDouble(),fList[3].toDouble(),
-        fList[4].toDouble(),fList[5].toDouble(),fList[6].toDouble(),fList[7].toDouble());
-
-  else if (fList[1].contains("mantidMatrix3D"))
-  {
-    QString linefive=lst[5];
-    QStringList linefivelst=linefive.split("\t");
-    QString name=linefivelst[1];
-    QStringList qlist=name.split(" ");
-    std::string graph3DwsName=qlist[1].toStdString();
-    MantidMatrix *m=0;
-    QList<MantidMatrix*>::const_iterator matrixItr;;
-    for( matrixItr=m_mantidmatrixWindows.begin();matrixItr!=m_mantidmatrixWindows.end();++matrixItr)
-    {
-      if(graph3DwsName==(*matrixItr)->getWorkspaceName()) m=*matrixItr;
-    }
-    QString linethree=lst[3];
-    qlist.clear();
-    qlist=linethree.split("\t");
-    int style=qlist[1].toInt();
-    if(m)plot=m->plotGraph3D(style);
-    if(!plot)
-    {
-      closeWindow(plot);
-      return 0;
-    }
-  }
-  else if (fList[1].contains(",")){
-    QStringList l = fList[1].split(",", QString::SkipEmptyParts);
-    plot = app->plotParametricSurface(l[0], l[1], l[2], l[3].toDouble(), l[4].toDouble(),
-        l[5].toDouble(), l[6].toDouble(), l[7].toInt(), l[8].toInt(), l[9].toInt(), l[10].toInt());
-    app->setWindowName(plot, caption);
-  } else {
-    QStringList l = fList[1].split(";", QString::SkipEmptyParts);
-    if (l.count() == 1)
-      plot = app->plotSurface(fList[1], fList[2].toDouble(), fList[3].toDouble(),
-          fList[4].toDouble(), fList[5].toDouble(), fList[6].toDouble(), fList[7].toDouble());
-    else if (l.count() == 3)
-      plot = app->plotSurface(l[0], fList[2].toDouble(), fList[3].toDouble(), fList[4].toDouble(),
-          fList[5].toDouble(), fList[6].toDouble(), fList[7].toDouble(), l[1].toInt(), l[2].toInt());
-    app->setWindowName(plot, caption);
-  }
-
-  if (!plot)
-    return 0;
-
-  app->setListViewDate(caption, date);
-  plot->setBirthDate(date);
-  plot->setIgnoreFonts(true);
-  restoreWindowGeometry(app, plot, lst[1]);
-
-  fList=lst[4].split("\t", QString::SkipEmptyParts);
-  plot->setGrid(fList[1].toInt());
-
-  plot->setTitle(lst[5].split("\t"));
-  plot->setColors(lst[6].split("\t", QString::SkipEmptyParts));
-
-  fList=lst[7].split("\t", QString::SkipEmptyParts);
-  fList.pop_front();
-  plot->setAxesLabels(fList);
-
-  plot->setTicks(lst[8].split("\t", QString::SkipEmptyParts));
-  plot->setTickLengths(lst[9].split("\t", QString::SkipEmptyParts));
-  plot->setOptions(lst[10].split("\t", QString::SkipEmptyParts));
-  plot->setNumbersFont(lst[11].split("\t", QString::SkipEmptyParts));
-  plot->setXAxisLabelFont(lst[12].split("\t", QString::SkipEmptyParts));
-  plot->setYAxisLabelFont(lst[13].split("\t", QString::SkipEmptyParts));
-  plot->setZAxisLabelFont(lst[14].split("\t", QString::SkipEmptyParts));
-
-  fList=lst[15].split("\t", QString::SkipEmptyParts);
-  plot->setRotation(fList[1].toDouble(),fList[2].toDouble(),fList[3].toDouble());
-
-  fList=lst[16].split("\t", QString::SkipEmptyParts);
-  plot->setZoom(fList[1].toDouble());
-
-  fList=lst[17].split("\t", QString::SkipEmptyParts);
-  plot->setScale(fList[1].toDouble(),fList[2].toDouble(),fList[3].toDouble());
-
-  fList=lst[18].split("\t", QString::SkipEmptyParts);
-  plot->setShift(fList[1].toDouble(),fList[2].toDouble(),fList[3].toDouble());
-
-  fList=lst[19].split("\t", QString::SkipEmptyParts);
-  plot->setMeshLineWidth(fList[1].toDouble());
-
-  if (d_file_version > 71){
-    fList=lst[20].split("\t"); // using QString::SkipEmptyParts here causes a crash for empty window labels
-    plot->setWindowLabel(fList[1]);
-    plot->setCaptionPolicy((MdiSubWindow::CaptionPolicy)fList[2].toInt());
-  }
-
-  if (d_file_version >= 88){
-    fList=lst[21].split("\t", QString::SkipEmptyParts);
-    plot->setOrthogonal(fList[1].toInt());
-  }
-
-  plot->setStyle(lst[3].split("\t", QString::SkipEmptyParts));
-  plot->setIgnoreFonts(true);
-  plot->update();
-  return plot;
-}
-Spectrogram*  ApplicationWindow::openSpectrogram(Graph*ag,const std::string &specgramwsName,const QStringList &lst)
-{
-  ProjectData *prjData=new ProjectData;
-  if(!prjData)return 0;
-
-  foreach (QString str, lst) {
-    if(str.contains("<ColorMap>"))
-    {	int index=lst.indexOf(str);
-    //read the colormap file name from project file
-    QString colormapLine=lst[index+1];
-    QStringList list=colormapLine.split("\t");
-    QString colormapFile=list[2];
-    prjData->setColormapFile(colormapFile);
-    }
-    if(str.contains("<ColorPolicy>"))
-    { 	//read the colormap policy to set gray scale
-      int index=lst.indexOf(str);
-      QString colormapPolicy=lst[index];
-      int index1=colormapPolicy.indexOf(">");
-      int index2=colormapPolicy.lastIndexOf("<");
-      bool gray=colormapPolicy.mid(index1+1,index2-index1-1).toInt();
-      prjData->setGrayScale(gray);
-
-    }
-    if (str.contains("\t<ContourLines>"))
-    { //setting contour mode
-      int index=lst.indexOf(str);
-      QString contourlines=lst[index];
-      int index1=contourlines.indexOf(">");
-      int index2=contourlines.lastIndexOf("<");
-      int bcontour=contourlines.mid(index1+1,index2-index1-1).toInt();
-      if(bcontour)prjData->setContourMode(true);
-
-      //setting contour levels
-      QString contourlevels=lst[index+1];
-      index1=contourlevels.indexOf(">");
-      index2=contourlevels.lastIndexOf("<");
-      int levels=contourlevels.mid(index1+1,index2-index1-1).toInt();
-      prjData->setContourLevels(levels);
-
-      //setting contour default pen
-      QString pen=lst[index+2];
-      if(pen.contains("<DefaultPen>"))
-      {
-        QString colorstring=lst[index+3];
-        int index1=colorstring.indexOf(">");
-        int index2=colorstring.lastIndexOf("<");
-        QString pencolor=colorstring.mid(index1+1,index2-index1-1);
-
-        QString widthstring=lst[index+4];
-        index1=widthstring.indexOf(">");
-        index2=widthstring.lastIndexOf("<");
-        QString penwidth=widthstring.mid(index1+1,index2-index1-1);
-
-        QString stylestring=lst[index+4];
-        index1=stylestring.indexOf(">");
-        index2=stylestring.lastIndexOf("<");
-        QString penstyle=stylestring.mid(index1+1,index2-index1-1);
-        QColor qcolor(pencolor);
-        QPen pen = QPen(qcolor, penwidth.toDouble(),Graph::getPenStyle(penstyle.toInt()));
-        prjData->setDefaultContourPen(pen);
-        prjData->setColorMapPen(false);
-      }
-      else if (pen.contains("<CustomPen>"))
-      {	ContourLinesEditor* contourLinesEditor = new ContourLinesEditor(this->locale());
-      prjData->setCotntourLinesEditor(contourLinesEditor);
-      prjData->setCustomPen(true);
-      }
-      else prjData->setColorMapPen(true);
-    }
-    if(str.contains("<IntensityChanged>"))
-    {	 //read the intensity changed line from file and setting the spectrogram flag for intenisity
-
-      int index=lst.indexOf(str);
-      QString intensity=lst[index];
-      int index1=intensity.indexOf(">");
-      int index2=intensity.lastIndexOf("<");
-      bool bIntensity=intensity.mid(index1+1,index2-index1-1).toInt();
-      prjData->setIntensity(bIntensity);
-    }
-
-  }
-  MantidMatrix *m=0;
-  //getting the mantidmatrix object  for the saved spectrogram  inthe project file
-  QList<MantidMatrix*>::const_iterator matrixItr;;
-  for( matrixItr=m_mantidmatrixWindows.begin();matrixItr!=m_mantidmatrixWindows.end();++matrixItr)
-  {
-    if(specgramwsName==(*matrixItr)->getWorkspaceName())
-      m=*matrixItr;
-  }
-  if(!m) return 0 ;
-  Spectrogram* sp=m->plotSpectrogram(ag,this,Graph::ColorMap,true,prjData);
-  return sp;
-}
-
-void ApplicationWindow::copyActiveLayer()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph *g = plot->activeGraph();
-
-  lastCopiedLayer = g;
-  connect (g, SIGNAL(destroyed()), this, SLOT(closedLastCopiedLayer()));
-  g->copyImage();
-}
-
-void ApplicationWindow::showDataSetDialog(Analysis operation)
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph *g = plot->activeGraph();
-  if (!g)
-    return;
-
-  DataSetDialog *ad = new DataSetDialog(tr("Curve") + ": ", this);
-  ad->setGraph(g);
-  ad->setOperationType(operation);
-  ad->exec();
-}
-
-void ApplicationWindow::analyzeCurve(Graph *g, Analysis operation, const QString& curveTitle)
-{
-  if (!g)
-    return;
-
-  Fit *fitter = 0;
-  switch(operation){
-  case NoAnalysis:
-    break;
-  case Integrate:
-  {
-    Integration *i = new Integration(this, g, curveTitle);
-    i->run();
-    delete i;
-  }
-  break;
-  case Diff:
-  {
-    Differentiation *diff = new Differentiation(this, g, curveTitle);
-    diff->enableGraphicsDisplay(true);
-    diff->run();
-    delete diff;
-  }
-  break;
-  case FitLinear:
-    fitter = new LinearFit (this, g);
-    break;
-  case FitLorentz:
-    fitter = new LorentzFit(this, g);
-    break;
-  case FitGauss:
-    fitter = new GaussFit(this, g);
-    break;
-  case FitSigmoidal:
-  {
-    QwtPlotCurve* c = g->curve(curveTitle);
-    if (c){
-      ScaleEngine *se = (ScaleEngine *)g->plotWidget()->axisScaleEngine(c->xAxis());
-      if(se->type() == QwtScaleTransformation::Log10)
-        fitter = new LogisticFit (this, g);
-      else
-        fitter = new SigmoidalFit (this, g);
-    }
-  }
-  break;
-  }
-
-  if (!fitter)
-    return;
-
-  if (fitter->setDataFromCurve(curveTitle)){
-    if (operation != FitLinear){
-      fitter->guessInitialValues();
-      fitter->scaleErrors(fit_scale_errors);
-      fitter->generateFunction(generateUniformFitPoints, fitPoints);
-    } else if (d_2_linear_fit_points)
-      fitter->generateFunction(generateUniformFitPoints, 2);
-    fitter->setOutputPrecision(fit_output_precision);
-    fitter->fit();
-    if (pasteFitResultsToPlot)
-      fitter->showLegend();
-    delete fitter;
-  }
-}
-
-void ApplicationWindow::analysis(Analysis operation)
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g || !g->validCurvesDataSize())
-    return;
-
-  QString curve_title = g->selectedCurveTitle();
-  if (!curve_title.isNull()) {
-    analyzeCurve(g, operation, curve_title);
-    return;
-  }
-
-  QStringList lst = g->analysableCurvesList();
-  if (lst.count() == 1){
-    const QwtPlotCurve *c = g->curve(lst[0]);
-    if (c)
-      analyzeCurve(g, operation, lst[0]);
-  } else
-    showDataSetDialog(operation);
-}
-
-void ApplicationWindow::integrate()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return;
-
-  if (w->isA("MultiLayer"))
-    analysis(Integrate);
-  else if (w->isA("Matrix")){
-    QDateTime dt = QDateTime::currentDateTime ();
-    QString info = dt.toString(Qt::LocalDate);
-    info += "\n" + tr("Integration of %1 from zero is").arg(QString(w->objectName())) + ":\t";
-    info += QString::number(((Matrix *)w)->integrate()) + "\n";
-    info += "-------------------------------------------------------------\n";
-    current_folder->appendLogInfo(info);
-    showResults(true);
-  }
-}
-
-void ApplicationWindow::differentiate()
-{
-  analysis(Diff);
-}
-
-void ApplicationWindow::fitLinear()
-{
-  analysis(FitLinear);
-}
-
-void ApplicationWindow::fitSigmoidal()
-{
-  analysis(FitSigmoidal);
-}
-
-void ApplicationWindow::fitGauss()
-{
-  analysis(FitGauss);
-}
-
-void ApplicationWindow::fitLorentz()
-
-{
-  analysis(FitLorentz);
-}
-
-void ApplicationWindow::pickPointerCursor()
-{
-  btnPointer->setChecked(true);
-}
-
-void ApplicationWindow::disableTools()
-{
-  if (displayBar->isVisible())
-    displayBar->hide();
-
-  QList<MdiSubWindow *> windows = windowsList();
-  foreach(MdiSubWindow *w, windows){
-    if (w->isA("MultiLayer")){
-      QList<Graph *> layers = ((MultiLayer*)w)->layersList();
-      foreach(Graph *g, layers)
-      g->disableTools();
-    }
-  }
-}
-
-void ApplicationWindow::pickDataTool( QAction* action )
-{
-  if (!action)
-    return;
-
-  disableTools();
-
-  if (action == btnCursor)
-    showCursor();
-  else if (action == btnSelect)
-    showRangeSelectors();
-  else if (action == btnPicker)
-    showScreenReader();
-  else if (action == btnMovePoints)
-    movePoints();
-  else if (action == btnRemovePoints)
-    removePoints();
-  else if (action == actionDrawPoints)
-    drawPoints();
-  else if (action == btnZoomIn)
-    zoomIn();
-  else if (action == btnZoomOut)
-    zoomOut();
-  else if (action == btnArrow)
-    drawArrow();
-  else if (action == btnLine)
-    drawLine();
-  else if (action == btnMultiPeakPick)
-    selectMultiPeak();
-  else if (action == actionMagnify)
-    magnify();
-}
-
-void ApplicationWindow::connectSurfacePlot(Graph3D *plot)
-{
-  connect (plot, SIGNAL(showContextMenu()), this,SLOT(showWindowContextMenu()));
-  connect (plot, SIGNAL(showOptionsDialog()), this,SLOT(showPlot3dDialog()));
-  connect (plot, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(closeWindow(MdiSubWindow*)));
-  connect (plot, SIGNAL(hiddenWindow(MdiSubWindow*)), this, SLOT(hideWindow(MdiSubWindow*)));
-  connect (plot, SIGNAL(statusChanged(MdiSubWindow*)), this, SLOT(updateWindowStatus(MdiSubWindow*)));
-  connect (plot, SIGNAL(modified()), this, SIGNAL(modified()));
-
-  plot->askOnCloseEvent(confirmClosePlot3D);
-}
-
-void ApplicationWindow::connectMultilayerPlot(MultiLayer *g)
-{
-  connect (g,SIGNAL(showTextDialog()),this,SLOT(showTextDialog()));
-  connect (g,SIGNAL(showPlotDialog(int)),this,SLOT(showPlotDialog(int)));
-  connect (g,SIGNAL(showScaleDialog(int)), this, SLOT(showScalePageFromAxisDialog(int)));
-  connect (g,SIGNAL(showAxisDialog(int)), this, SLOT(showAxisPageFromAxisDialog(int)));
-  connect (g,SIGNAL(showCurveContextMenu(int)), this, SLOT(showCurveContextMenu(int)));
-  connect (g,SIGNAL(showContextMenu()),this,SLOT(showWindowContextMenu()));
-  connect (g,SIGNAL(showCurvesDialog()),this,SLOT(showCurvesDialog()));
-  connect (g,SIGNAL(drawLineEnded(bool)), btnPointer, SLOT(setOn(bool)));
-  connect (g,SIGNAL(drawTextOff()),this, SLOT(disableAddText()));
-  connect (g, SIGNAL(showAxisTitleDialog()), this, SLOT(showAxisTitleDialog()));
-
-  connect (g,SIGNAL(showMarkerPopupMenu()),this,SLOT(showMarkerPopupMenu()));
-  connect (g,SIGNAL(closedWindow(MdiSubWindow*)),this, SLOT(closeWindow(MdiSubWindow*)));
-  connect (g,SIGNAL(hiddenWindow(MdiSubWindow*)),this, SLOT(hideWindow(MdiSubWindow*)));
-  connect (g,SIGNAL(statusChanged(MdiSubWindow*)),this, SLOT(updateWindowStatus(MdiSubWindow*)));
-  connect (g,SIGNAL(cursorInfo(const QString&)),info,SLOT(setText(const QString&)));
-  connect (g,SIGNAL(showImageDialog()),this,SLOT(showImageDialog()));
-  connect (g,SIGNAL(createTable(const QString&,int,int,const QString&)),
-      this,SLOT(newTable(const QString&,int,int,const QString&)));
-  connect (g,SIGNAL(viewTitleDialog()),this,SLOT(showTitleDialog()));
-  connect (g,SIGNAL(modifiedWindow(MdiSubWindow*)),this,SLOT(modifiedProject(MdiSubWindow*)));
-  connect (g,SIGNAL(resizedWindow(MdiSubWindow*)), this, SLOT(repaintWindows()));
-  connect (g,SIGNAL(modifiedPlot()), this, SLOT(modifiedProject()));
-  connect (g,SIGNAL(showLineDialog()),this, SLOT(showLineDialog()));
-  connect (g,SIGNAL(pasteMarker()),this,SLOT(pasteSelection()));
-  connect (g,SIGNAL(showGraphContextMenu()),this,SLOT(showGraphContextMenu()));
-  connect (g,SIGNAL(setPointerCursor()),this, SLOT(pickPointerCursor()));
-  connect (g,SIGNAL(currentFontChanged(const QFont&)), this, SLOT(setFormatBarFont(const QFont&)));
-  connect (g,SIGNAL(enableTextEditor(Graph *)), this, SLOT(enableTextEditor(Graph *)));
-
-  g->askOnCloseEvent(confirmClosePlot2D);
-}
-
-void ApplicationWindow::connectTable(Table* w)
-{
-  connect (w->table(), SIGNAL(selectionChanged()), this, SLOT(customColumnActions()));
-  connect (w,SIGNAL(statusChanged(MdiSubWindow*)),this, SLOT(updateWindowStatus(MdiSubWindow*)));
-  connect (w,SIGNAL(hiddenWindow(MdiSubWindow*)),this, SLOT(hideWindow(MdiSubWindow*)));
-  connect (w,SIGNAL(closedWindow(MdiSubWindow*)),this, SLOT(closeWindow(MdiSubWindow*)));
-  connect (w,SIGNAL(removedCol(const QString&)),this,SLOT(removeCurves(const QString&)));
-  connect (w,SIGNAL(modifiedData(Table *, const QString&)),
-      this, SLOT(updateCurves(Table *, const QString&)));
-  connect (w,SIGNAL(resizedWindow(MdiSubWindow*)),this,SLOT(modifiedProject(MdiSubWindow*)));
-  connect (w,SIGNAL(modifiedWindow(MdiSubWindow*)),this,SLOT(modifiedProject(MdiSubWindow*)));
-  connect (w,SIGNAL(optionsDialog()),this,SLOT(showColumnOptionsDialog()));
-  connect (w,SIGNAL(colValuesDialog()),this,SLOT(showColumnValuesDialog()));
-  connect (w,SIGNAL(showContextMenu(bool)),this,SLOT(showTableContextMenu(bool)));
-  connect (w,SIGNAL(changedColHeader(const QString&,const QString&)),this,SLOT(updateColNames(const QString&,const QString&)));
-  connect (w,SIGNAL(createTable(const QString&,int,int,const QString&)),this,SLOT(newTable(const QString&,int,int,const QString&)));
-
-  w->askOnCloseEvent(confirmCloseTable);
-}
-
-void ApplicationWindow::setAppColors(const QColor& wc, const QColor& pc, const QColor& tpc, bool force)
-{
-  if (force || workspaceColor != wc){
-    workspaceColor = wc;
-    d_workspace->setBackground(wc);
-  }
-
-  if (!force && panelsColor == pc && panelsTextColor == tpc)
-    return;
-
-  panelsColor = pc;
-  panelsTextColor = tpc;
-
-  QPalette palette;
-  palette.setColor(QPalette::Base, QColor(panelsColor));
-  qApp->setPalette(palette);
-
-  palette.setColor(QPalette::Text, QColor(panelsTextColor));
-  palette.setColor(QPalette::WindowText, QColor(panelsTextColor));
-
-  lv->setPalette(palette);
-  results->setPalette(palette);
-  folders->setPalette(palette);
-}
-
-void ApplicationWindow::setPlot3DOptions()
-{
-  QList<MdiSubWindow *> windows = windowsList();
-  foreach(MdiSubWindow *w, windows){
-    if (w->isA("Graph3D")){
-      Graph3D *g = (Graph3D*)w;
-      g->setOrthogonal(orthogonal3DPlots);
-      g->setAutoscale(autoscale3DPlots);
-      g->setAntialiasing(smooth3DMesh);
-    }
-  }
-}
-
-void ApplicationWindow::createActions()
-{
-  actionCustomActionDialog = new QAction(tr("Manage Custom Menus..."), this);
-  connect(actionCustomActionDialog, SIGNAL(activated()), this, SLOT(showCustomActionDialog()));
-  
-  actionManageDirs = new QAction(QIcon(getQPixmap("managefolders_xpm")), tr("Manage User Directories"), this);
-  connect(actionManageDirs, SIGNAL(activated()), this, SLOT(showUserDirectoryDialog()));
-
-  actionNewProject = new QAction(QIcon(getQPixmap("new_xpm")), tr("New &Project"), this);
-  actionNewProject->setShortcut( tr("Ctrl+N") );
-  connect(actionNewProject, SIGNAL(activated()), this, SLOT(newProject()));
-
-  actionSaveProject=new QAction(QIcon(getQPixmap("filesave_xpm")), tr("Save &Project"), this);
-  actionSaveProject->setShortcut( tr("Ctrl+Shift+S") );
-  connect(actionSaveProject, SIGNAL(activated()), this, SLOT(saveProject()));
-
-  actionSaveFile=new QAction(QIcon(getQPixmap("filesave_nexus_xpm")), tr("Save Nexus &File"), this);
-  actionSaveFile->setShortcut( tr("Ctrl+S") );
-  connect(actionSaveFile, SIGNAL(activated()), this, SLOT(savetoNexusFile()));
-
-  actionNewFolder = new QAction(QIcon(getQPixmap("newFolder_xpm")), tr("New &Project"), this);
-  actionNewProject->setShortcut(Qt::Key_F7);
-  connect(actionNewFolder, SIGNAL(activated()), this, SLOT(addFolder()));
-
-  actionNewGraph = new QAction(QIcon(getQPixmap("new_graph_xpm")), tr("New &Graph"), this);
-  actionNewGraph->setShortcut( tr("Ctrl+G") );
-  connect(actionNewGraph, SIGNAL(activated()), this, SLOT(newGraph()));
-
-  actionNewNote = new QAction(QIcon(getQPixmap("new_note_xpm")), tr("New &Note"), this);
-  connect(actionNewNote, SIGNAL(activated()), this, SLOT(newNote()));
-
-  actionNewTable = new QAction(QIcon(getQPixmap("table_xpm")), tr("New &Table"), this);
-  actionNewTable->setShortcut( tr("Ctrl+T") );
-  connect(actionNewTable, SIGNAL(activated()), this, SLOT(newTable()));
-
-  actionNewMatrix = new QAction(QIcon(getQPixmap("new_matrix_xpm")), tr("New &Matrix"), this);
-  actionNewMatrix->setShortcut( tr("Ctrl+M") );
-  connect(actionNewMatrix, SIGNAL(activated()), this, SLOT(newMatrix()));
-
-  actionNewFunctionPlot = new QAction(QIcon(getQPixmap("newF_xpm")), tr("New &Function Plot"), this);
-  actionNewFunctionPlot->setShortcut( tr("Ctrl+F") );
-  connect(actionNewFunctionPlot, SIGNAL(activated()), this, SLOT(functionDialog()));
-
-  actionNewSurfacePlot = new QAction(QIcon(getQPixmap("newFxy_xpm")), tr("New 3D &Surface Plot"), this);
-  actionNewSurfacePlot->setShortcut( tr("Ctrl+ALT+Z") );
-  connect(actionNewSurfacePlot, SIGNAL(activated()), this, SLOT(newSurfacePlot()));
-
-  actionOpenProj=new QAction(QIcon(getQPixmap("folder_open_xpm")), tr("&Project"), this);
-  actionOpenProj->setShortcut( tr("Ctrl+Shift+O") );
-  connect(actionOpenProj, SIGNAL(activated()), this, SLOT(open()));
-
-  actionLoadFile=new QAction(QIcon(getQPixmap("fileopen_raw_xpm")), tr("Data File"), this);
-  actionLoadFile->setShortcut( tr("Ctrl+Shift+F") );
-  connect(actionLoadFile, SIGNAL(activated()), this, SLOT(loadDataFile()));
-
-  actionLoadImage = new QAction(tr("Open Image &File"), this);
-  actionLoadImage->setShortcut( tr("Ctrl+I") );
-  connect(actionLoadImage, SIGNAL(activated()), this, SLOT(loadImage()));
-
-  actionImportImage = new QAction(tr("Import I&mage..."), this);
-  connect(actionImportImage, SIGNAL(activated()), this, SLOT(importImage()));
-
-  actionSaveProjectAs = new QAction(tr("Save Project &As..."), this);
-  connect(actionSaveProjectAs, SIGNAL(activated()), this, SLOT(saveProjectAs()));
-
-  actionOpenTemplate = new QAction(QIcon(getQPixmap("open_template_xpm")),tr("Open Temp&late..."), this);
-  connect(actionOpenTemplate, SIGNAL(activated()), this, SLOT(openTemplate()));
-
-  actionSaveTemplate = new QAction(QIcon(getQPixmap("save_template_xpm")), tr("Save As &Template..."), this);
-  connect(actionSaveTemplate, SIGNAL(activated()), this, SLOT(saveAsTemplate()));
-
-  actionSaveNote = new QAction(tr("Save Note As..."), this);
-  connect(actionSaveNote, SIGNAL(activated()), this, SLOT(saveNoteAs()));
-
-  actionLoad = new QAction(QIcon(getQPixmap("import_xpm")), tr("&Import ASCII..."), this);
-  connect(actionLoad, SIGNAL(activated()), this, SLOT(importASCII()));
-
-  actionUndo = new QAction(QIcon(getQPixmap("undo_xpm")), tr("&Undo"), this);
-  actionUndo->setShortcut( tr("Ctrl+Z") );
-  connect(actionUndo, SIGNAL(activated()), this, SLOT(undo()));
-
-  actionRedo = new QAction(QIcon(getQPixmap("redo_xpm")), tr("&Redo"), this);
-  actionRedo->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_Z));
-  connect(actionRedo, SIGNAL(activated()), this, SLOT(redo()));
-
-  actionCopyWindow = new QAction(QIcon(getQPixmap("duplicate_xpm")), tr("&Duplicate"), this);
-  connect(actionCopyWindow, SIGNAL(activated()), this, SLOT(clone()));
-
-  actionCutSelection = new QAction(QIcon(getQPixmap("cut_xpm")), tr("Cu&t Selection"), this);
-  actionCutSelection->setShortcut( tr("Ctrl+X") );
-  connect(actionCutSelection, SIGNAL(activated()), this, SLOT(cutSelection()));
-
-  actionCopySelection = new QAction(QIcon(getQPixmap("copy_xpm")), tr("&Copy Selection"), this);
-  actionCopySelection->setShortcut( tr("Ctrl+C") );
-  connect(actionCopySelection, SIGNAL(activated()), this, SLOT(copySelection()));
-
-  actionPasteSelection = new QAction(QIcon(getQPixmap("paste_xpm")), tr("&Paste Selection"), this);
-  actionPasteSelection->setShortcut( tr("Ctrl+V") );
-  connect(actionPasteSelection, SIGNAL(activated()), this, SLOT(pasteSelection()));
-
-  actionClearSelection = new QAction(QIcon(getQPixmap("erase_xpm")), tr("&Delete Selection"), this);
-  actionClearSelection->setShortcut( tr("Del","delete key") );
-  connect(actionClearSelection, SIGNAL(activated()), this, SLOT(clearSelection()));
-
-  actionShowExplorer = explorerWindow->toggleViewAction();
-  actionShowExplorer->setIcon(getQPixmap("folder_xpm"));
-  actionShowExplorer->setShortcut( tr("Ctrl+E") );
-
-  actionShowLog = logWindow->toggleViewAction();
-  actionShowLog->setIcon(getQPixmap("log_xpm"));
-
-  actionShowUndoStack = undoStackWindow->toggleViewAction();
-
-    //#ifdef SCRIPTING_CONSOLE
-  actionShowConsole = consoleWindow->toggleViewAction();
-    //#endif
-
-  actionAddLayer = new QAction(QIcon(getQPixmap("newLayer_xpm")), tr("Add La&yer"), this);
-  actionAddLayer->setShortcut( tr("Alt+L") );
-  connect(actionAddLayer, SIGNAL(activated()), this, SLOT(addLayer()));
-
-  actionShowLayerDialog = new QAction(QIcon(getQPixmap("arrangeLayers_xpm")), tr("Arran&ge Layers"), this);
-  actionShowLayerDialog->setShortcut( tr("Alt+A") );
-  connect(actionShowLayerDialog, SIGNAL(activated()), this, SLOT(showLayerDialog()));
-
-  actionAutomaticLayout = new QAction(QIcon(getQPixmap("auto_layout_xpm")), tr("Automatic Layout"), this);
-  connect(actionAutomaticLayout, SIGNAL(activated()), this, SLOT(autoArrangeLayers()));
-
-  actionExportGraph = new QAction(tr("&Current"), this);
-  actionExportGraph->setShortcut( tr("Alt+G") );
-  connect(actionExportGraph, SIGNAL(activated()), this, SLOT(exportGraph()));
-
-  actionExportAllGraphs = new QAction(tr("&All"), this);
-  actionExportAllGraphs->setShortcut( tr("Alt+X") );
-  connect(actionExportAllGraphs, SIGNAL(activated()), this, SLOT(exportAllGraphs()));
-
-  actionExportPDF = new QAction(QIcon(getQPixmap("pdf_xpm")), tr("&Export PDF"), this);
-  actionExportPDF->setShortcut( tr("Ctrl+Alt+P") );
-  connect(actionExportPDF, SIGNAL(activated()), this, SLOT(exportPDF()));
-
-  actionPrint = new QAction(QIcon(getQPixmap("fileprint_xpm")), tr("&Print"), this);
-  actionPrint->setShortcut( tr("Ctrl+P") );
-  connect(actionPrint, SIGNAL(activated()), this, SLOT(print()));
-
-  actionPrintAllPlots = new QAction(tr("Print All Plo&ts"), this);
-  connect(actionPrintAllPlots, SIGNAL(activated()), this, SLOT(printAllPlots()));
-
-  actionShowExportASCIIDialog = new QAction(tr("E&xport ASCII"), this);
-  connect(actionShowExportASCIIDialog, SIGNAL(activated()), this, SLOT(showExportASCIIDialog()));
-
-  actionCloseAllWindows = new QAction(QIcon(getQPixmap("quit_xpm")), tr("&Quit"), this);
-  actionCloseAllWindows->setShortcut( tr("Ctrl+Q") );
-  connect(actionCloseAllWindows, SIGNAL(activated()), qApp, SLOT(closeAllWindows()));
-
-  actionClearLogInfo = new QAction(tr("Clear &Log Information"), this);
-  connect(actionClearLogInfo, SIGNAL(activated()), this, SLOT(clearLogInfo()));
-
-  actionClearConsole = new QAction(tr("Clear &Console"), this);
-  connect(actionClearConsole, SIGNAL(activated()), console, SLOT(clear()));
-
-  actionDeleteFitTables = new QAction(QIcon(getQPixmap("close_xpm")), tr("Delete &Fit Tables"), this);
-  connect(actionDeleteFitTables, SIGNAL(activated()), this, SLOT(deleteFitTables()));
-
-  actionShowPlotWizard = new QAction(QIcon(getQPixmap("wizard_xpm")), tr("Plot &Wizard"), this);
-  actionShowPlotWizard->setShortcut( tr("Ctrl+Alt+W") );
-  connect(actionShowPlotWizard, SIGNAL(activated()), this, SLOT(showPlotWizard()));
-
-  actionShowConfigureDialog = new QAction(tr("&Preferences..."), this);
-  connect(actionShowConfigureDialog, SIGNAL(activated()), this, SLOT(showPreferencesDialog()));
-
-  actionShowCurvesDialog = new QAction(QIcon(getQPixmap("curves_xpm")), tr("Add/Remove &Curve..."), this);
-  actionShowCurvesDialog->setShortcut( tr("ALT+C") );
-  connect(actionShowCurvesDialog, SIGNAL(activated()), this, SLOT(showCurvesDialog()));
-
-  actionAddErrorBars = new QAction(QIcon(getQPixmap("errors_xpm")), tr("Add &Error Bars..."), this);
-  actionAddErrorBars->setShortcut( tr("Ctrl+B") );
-  connect(actionAddErrorBars, SIGNAL(activated()), this, SLOT(addErrorBars()));
-
-  actionRemoveErrorBars = new QAction(QIcon(getQPixmap("errors_xpm")), tr("Remove Error Bars..."), this);
-  //actionRemoveErrorBars->setShortcut( tr("Ctrl+B") );
-  connect(actionRemoveErrorBars, SIGNAL(activated()), this, SLOT(removeErrorBars()));
-
-  actionAddFunctionCurve = new QAction(QIcon(getQPixmap("fx_xpm")), tr("Add &Function..."), this);
-  actionAddFunctionCurve->setShortcut( tr("Ctrl+Alt+F") );
-  connect(actionAddFunctionCurve, SIGNAL(activated()), this, SLOT(addFunctionCurve()));
-
-  actionUnzoom = new QAction(QIcon(getQPixmap("unzoom_xpm")), tr("&Rescale to Show All"), this);
-  actionUnzoom->setShortcut( tr("Ctrl+Shift+R") );
-  connect(actionUnzoom, SIGNAL(activated()), this, SLOT(setAutoScale()));
-
-  actionNewLegend = new QAction(QIcon(getQPixmap("legend_xpm")), tr("New &Legend"), this);
-  actionNewLegend->setShortcut( tr("Ctrl+L") );
-  connect(actionNewLegend, SIGNAL(activated()), this, SLOT(newLegend()));
-
-  actionTimeStamp = new QAction(QIcon(getQPixmap("clock_xpm")), tr("Add Time Stamp"), this);
-  actionTimeStamp->setShortcut( tr("Ctrl+ALT+T") );
-  connect(actionTimeStamp, SIGNAL(activated()), this, SLOT(addTimeStamp()));
-
-  actionAddImage = new QAction(QIcon(getQPixmap("monalisa_xpm")), tr("Add &Image"), this);
-  actionAddImage->setShortcut( tr("ALT+I") );
-  connect(actionAddImage, SIGNAL(activated()), this, SLOT(addImage()));
-
-  actionPlotL = new QAction(QIcon(getQPixmap("lPlot_xpm")), tr("&Line"), this);
-  connect(actionPlotL, SIGNAL(activated()), this, SLOT(plotL()));
-
-  actionPlotP = new QAction(QIcon(getQPixmap("pPlot_xpm")), tr("&Scatter"), this);
-  connect(actionPlotP, SIGNAL(activated()), this, SLOT(plotP()));
-
-  actionPlotLP = new QAction(QIcon(getQPixmap("lpPlot_xpm")), tr("Line + S&ymbol"), this);
-  connect(actionPlotLP, SIGNAL(activated()), this, SLOT(plotLP()));
-
-  actionPlotVerticalDropLines = new QAction(QIcon(getQPixmap("dropLines_xpm")), tr("Vertical &Drop Lines"), this);
-  connect(actionPlotVerticalDropLines, SIGNAL(activated()), this, SLOT(plotVerticalDropLines()));
-
-  actionPlotSpline = new QAction(QIcon(getQPixmap("spline_xpm")), tr("&Spline"), this);
-  connect(actionPlotSpline, SIGNAL(activated()), this, SLOT(plotSpline()));
-
-  actionPlotHorSteps = new QAction(getQPixmap("hor_steps_xpm"), tr("&Horizontal Steps"), this);
-  connect(actionPlotHorSteps, SIGNAL(activated()), this, SLOT(plotHorSteps()));
-
-  actionPlotVertSteps = new QAction(QIcon(getQPixmap("vert_steps_xpm")), tr("&Vertical Steps"), this);
-  connect(actionPlotVertSteps, SIGNAL(activated()), this, SLOT(plotVertSteps()));
-
-  actionPlotVerticalBars = new QAction(QIcon(getQPixmap("vertBars_xpm")), tr("&Columns"), this);
-  connect(actionPlotVerticalBars, SIGNAL(activated()), this, SLOT(plotVerticalBars()));
-
-  actionPlotHorizontalBars = new QAction(QIcon(getQPixmap("hBars_xpm")), tr("&Rows"), this);
-  connect(actionPlotHorizontalBars, SIGNAL(activated()), this, SLOT(plotHorizontalBars()));
-
-  actionPlotArea = new QAction(QIcon(getQPixmap("area_xpm")), tr("&Area"), this);
-  connect(actionPlotArea, SIGNAL(activated()), this, SLOT(plotArea()));
-
-  actionPlotPie = new QAction(QIcon(getQPixmap("pie_xpm")), tr("&Pie"), this);
-  connect(actionPlotPie, SIGNAL(activated()), this, SLOT(plotPie()));
-
-  actionPlotVectXYAM = new QAction(QIcon(getQPixmap("vectXYAM_xpm")), tr("Vectors XY&AM"), this);
-  connect(actionPlotVectXYAM, SIGNAL(activated()), this, SLOT(plotVectXYAM()));
-
-  actionPlotVectXYXY = new QAction(QIcon(getQPixmap("vectXYXY_xpm")), tr("&Vectors &XYXY"), this);
-  connect(actionPlotVectXYXY, SIGNAL(activated()), this, SLOT(plotVectXYXY()));
-
-  actionPlotHistogram = new QAction(QIcon(getQPixmap("histogram_xpm")), tr("&Histogram"), this);
-  connect(actionPlotHistogram, SIGNAL(activated()), this, SLOT(plotHistogram()));
-
-  actionPlotStackedHistograms = new QAction(QIcon(getQPixmap("stacked_hist_xpm")), tr("&Stacked Histogram"), this);
-  connect(actionPlotStackedHistograms, SIGNAL(activated()), this, SLOT(plotStackedHistograms()));
-
-  actionPlot2VerticalLayers = new QAction(QIcon(getQPixmap("panel_v2_xpm")), tr("&Vertical 2 Layers"), this);
-  connect(actionPlot2VerticalLayers, SIGNAL(activated()), this, SLOT(plot2VerticalLayers()));
-
-  actionPlot2HorizontalLayers = new QAction(QIcon(getQPixmap("panel_h2_xpm")), tr("&Horizontal 2 Layers"), this);
-  connect(actionPlot2HorizontalLayers, SIGNAL(activated()), this, SLOT(plot2HorizontalLayers()));
-
-  actionPlot4Layers = new QAction(QIcon(getQPixmap("panel_4_xpm")), tr("&4 Layers"), this);
-  connect(actionPlot4Layers, SIGNAL(activated()), this, SLOT(plot4Layers()));
-
-  actionPlotStackedLayers = new QAction(QIcon(getQPixmap("stacked_xpm")), tr("&Stacked Layers"), this);
-  connect(actionPlotStackedLayers, SIGNAL(activated()), this, SLOT(plotStackedLayers()));
-
-  actionPlot3DRibbon = new QAction(QIcon(getQPixmap("ribbon_xpm")), tr("&Ribbon"), this);
-  connect(actionPlot3DRibbon, SIGNAL(activated()), this, SLOT(plot3DRibbon()));
-
-  actionPlot3DBars = new QAction(QIcon(getQPixmap("bars_xpm")), tr("&Bars"), this);
-  connect(actionPlot3DBars, SIGNAL(activated()), this, SLOT(plot3DBars()));
-
-  actionPlot3DScatter = new QAction(QIcon(getQPixmap("scatter_xpm")), tr("&Scatter"), this);
-  connect(actionPlot3DScatter, SIGNAL(activated()), this, SLOT(plot3DScatter()));
-
-  actionPlot3DTrajectory = new QAction(QIcon(getQPixmap("trajectory_xpm")), tr("&Trajectory"), this);
-  connect(actionPlot3DTrajectory, SIGNAL(activated()), this, SLOT(plot3DTrajectory()));
-
-  actionShowColStatistics = new QAction(QIcon(getQPixmap("col_stat_xpm")), tr("Statistics on &Columns"), this);
-  connect(actionShowColStatistics, SIGNAL(activated()), this, SLOT(showColStatistics()));
-
-  actionShowRowStatistics = new QAction(QIcon(getQPixmap("stat_rows_xpm")), tr("Statistics on &Rows"), this);
-  connect(actionShowRowStatistics, SIGNAL(activated()), this, SLOT(showRowStatistics()));
-
-  actionIntegrate = new QAction(tr("&Integrate"), this);
-  connect(actionIntegrate, SIGNAL(activated()), this, SLOT(integrate()));
-
-  actionShowIntDialog = new QAction(tr("Integr&ate Function..."), this);
-  connect(actionShowIntDialog, SIGNAL(activated()), this, SLOT(showIntegrationDialog()));
-
-  actionInterpolate = new QAction(tr("Inte&rpolate ..."), this);
-  connect(actionInterpolate, SIGNAL(activated()), this, SLOT(showInterpolationDialog()));
-
-  actionLowPassFilter = new QAction(tr("&Low Pass..."), this);
-  connect(actionLowPassFilter, SIGNAL(activated()), this, SLOT(lowPassFilterDialog()));
-
-  actionHighPassFilter = new QAction(tr("&High Pass..."), this);
-  connect(actionHighPassFilter, SIGNAL(activated()), this, SLOT(highPassFilterDialog()));
-
-  actionBandPassFilter = new QAction(tr("&Band Pass..."), this);
-  connect(actionBandPassFilter, SIGNAL(activated()), this, SLOT(bandPassFilterDialog()));
-
-  actionBandBlockFilter = new QAction(tr("&Band Block..."), this);
-  connect(actionBandBlockFilter, SIGNAL(activated()), this, SLOT(bandBlockFilterDialog()));
-
-  actionFFT = new QAction(tr("&FFT..."), this);
-  connect(actionFFT, SIGNAL(activated()), this, SLOT(showFFTDialog()));
-
-  actionSmoothSavGol = new QAction(tr("&Savitzky-Golay..."), this);
-  connect(actionSmoothSavGol, SIGNAL(activated()), this, SLOT(showSmoothSavGolDialog()));
-
-  actionSmoothFFT = new QAction(tr("&FFT Filter..."), this);
-  connect(actionSmoothFFT, SIGNAL(activated()), this, SLOT(showSmoothFFTDialog()));
-
-  actionSmoothAverage = new QAction(tr("Moving Window &Average..."), this);
-  connect(actionSmoothAverage, SIGNAL(activated()), this, SLOT(showSmoothAverageDialog()));
-
-  actionDifferentiate = new QAction(tr("&Differentiate"), this);
-  connect(actionDifferentiate, SIGNAL(activated()), this, SLOT(differentiate()));
-
-  actionFitLinear = new QAction(tr("Fit &Linear"), this);
-  connect(actionFitLinear, SIGNAL(activated()), this, SLOT(fitLinear()));
-
-  actionShowFitPolynomDialog = new QAction(tr("Fit &Polynomial ..."), this);
-  connect(actionShowFitPolynomDialog, SIGNAL(activated()), this, SLOT(showFitPolynomDialog()));
-
-  actionShowExpDecayDialog = new QAction(tr("&First Order ..."), this);
-  connect(actionShowExpDecayDialog, SIGNAL(activated()), this, SLOT(showExpDecayDialog()));
-
-  actionShowTwoExpDecayDialog = new QAction(tr("&Second Order ..."), this);
-  connect(actionShowTwoExpDecayDialog, SIGNAL(activated()), this, SLOT(showTwoExpDecayDialog()));
-
-  actionShowExpDecay3Dialog = new QAction(tr("&Third Order ..."), this);
-  connect(actionShowExpDecay3Dialog, SIGNAL(activated()), this, SLOT(showExpDecay3Dialog()));
-
-  actionFitExpGrowth = new QAction(tr("Fit Exponential Gro&wth ..."), this);
-  connect(actionFitExpGrowth, SIGNAL(activated()), this, SLOT(showExpGrowthDialog()));
-
-  actionFitSigmoidal = new QAction(tr("Fit &Boltzmann (Sigmoidal)"), this);
-  connect(actionFitSigmoidal, SIGNAL(activated()), this, SLOT(fitSigmoidal()));
-
-  actionFitGauss = new QAction(tr("Fit &Gaussian"), this);
-  connect(actionFitGauss, SIGNAL(activated()), this, SLOT(fitGauss()));
-
-  actionFitLorentz = new QAction(tr("Fit Lorent&zian"), this);
-  connect(actionFitLorentz, SIGNAL(activated()), this, SLOT(fitLorentz()));
-
-  actionShowFitDialog = new QAction(tr("Fit &Wizard..."), this);
-  actionShowFitDialog->setShortcut( tr("Ctrl+Y") );
-  connect(actionShowFitDialog, SIGNAL(activated()), this, SLOT(showFitDialog()));
-
-  actionShowPlotDialog = new QAction(tr("&Plot ..."), this);
-  connect(actionShowPlotDialog, SIGNAL(activated()), this, SLOT(showGeneralPlotDialog()));
-
-  actionShowScaleDialog = new QAction(tr("&Scales..."), this);
-  connect(actionShowScaleDialog, SIGNAL(activated()), this, SLOT(showScaleDialog()));
-
-  actionShowAxisDialog = new QAction(tr("&Axes..."), this);
-  connect(actionShowAxisDialog, SIGNAL(activated()), this, SLOT(showAxisDialog()));
-
-  actionShowGridDialog = new QAction(tr("&Grid ..."), this);
-  connect(actionShowGridDialog, SIGNAL(activated()), this, SLOT(showGridDialog()));
-
-  actionShowTitleDialog = new QAction(tr("&Title ..."), this);
-  connect(actionShowTitleDialog, SIGNAL(activated()), this, SLOT(showTitleDialog()));
-
-  actionShowColumnOptionsDialog = new QAction(tr("Column &Options ..."), this);
-  actionShowColumnOptionsDialog->setShortcut(tr("Ctrl+Alt+O"));
-  connect(actionShowColumnOptionsDialog, SIGNAL(activated()), this, SLOT(showColumnOptionsDialog()));
-
-  actionShowColumnValuesDialog = new QAction(QIcon(getQPixmap("formula_xpm")), tr("Set Column &Values ..."), this);
-  connect(actionShowColumnValuesDialog, SIGNAL(activated()), this, SLOT(showColumnValuesDialog()));
-  actionShowColumnValuesDialog->setShortcut(tr("Alt+Q"));
-
-  actionTableRecalculate = new QAction(tr("Recalculate"), this);
-  actionTableRecalculate->setShortcut(tr("Ctrl+Return"));
-  connect(actionTableRecalculate, SIGNAL(activated()), this, SLOT(recalculateTable()));
-
-  actionHideSelectedColumns = new QAction(tr("&Hide Selected"), this);
-  connect(actionHideSelectedColumns, SIGNAL(activated()), this, SLOT(hideSelectedColumns()));
-
-  actionShowAllColumns = new QAction(tr("Sho&w All Columns"), this);
-  connect(actionShowAllColumns, SIGNAL(activated()), this, SLOT(showAllColumns()));
-
-  actionSwapColumns = new QAction(QIcon(getQPixmap("swap_columns_xpm")), tr("&Swap columns"), this);
-  connect(actionSwapColumns, SIGNAL(activated()), this, SLOT(swapColumns()));
-
-  actionMoveColRight = new QAction(QIcon(getQPixmap("move_col_right_xpm")), tr("Move &Right"), this);
-  connect(actionMoveColRight, SIGNAL(activated()), this, SLOT(moveColumnRight()));
-
-  actionMoveColLeft = new QAction(QIcon(getQPixmap("move_col_left_xpm")), tr("Move &Left"), this);
-  connect(actionMoveColLeft, SIGNAL(activated()), this, SLOT(moveColumnLeft()));
-
-  actionMoveColFirst = new QAction(QIcon(getQPixmap("move_col_first_xpm")), tr("Move to F&irst"), this);
-  connect(actionMoveColFirst, SIGNAL(activated()), this, SLOT(moveColumnFirst()));
-
-  actionMoveColLast = new QAction(QIcon(getQPixmap("move_col_last_xpm")), tr("Move to Las&t"), this);
-  connect(actionMoveColLast, SIGNAL(activated()), this, SLOT(moveColumnLast()));
-
-  actionShowColsDialog = new QAction(tr("&Columns..."), this);
-  connect(actionShowColsDialog, SIGNAL(activated()), this, SLOT(showColsDialog()));
-
-  actionShowRowsDialog = new QAction(tr("&Rows..."), this);
-  connect(actionShowRowsDialog, SIGNAL(activated()), this, SLOT(showRowsDialog()));
-
-  actionDeleteRows = new QAction(tr("&Delete Rows Interval..."), this);
-  connect(actionDeleteRows, SIGNAL(activated()), this, SLOT(showDeleteRowsDialog()));
-
-  actionAbout = new QAction(tr("&About MantidPlot"), this);//Mantid
-  actionAbout->setShortcut( tr("F1") );
-  connect(actionAbout, SIGNAL(activated()), this, SLOT(about()));
-
-  actionShowHelp = new QAction(tr("&Help"), this);
-  actionShowHelp->setShortcut( tr("Ctrl+H") );
-  connect(actionShowHelp, SIGNAL(activated()), this, SLOT(showHelp()));
-
-  actionMantidConcepts=new QAction(tr("&Mantid Concepts"), this);
-  connect(actionMantidConcepts, SIGNAL(activated()), this, SLOT(showMantidConcepts()));
-
-  actionMantidAlgorithms=new QAction(tr("&Algorithm Descriptions"), this);
-  connect(actionMantidAlgorithms, SIGNAL(activated()), this, SLOT(showalgorithmDescriptions()));
-
-  actionmantidplotHelp=new QAction(tr("&MantidPlot Help"), this);
-  connect(actionmantidplotHelp, SIGNAL(activated()), this, SLOT(showmantidplotHelp()));
-
-
-  actionChooseHelpFolder = new QAction(tr("&Choose Help Folder..."), this);
-  connect(actionChooseHelpFolder, SIGNAL(activated()), this, SLOT(chooseHelpFolder()));
-
-  actionRename = new QAction(tr("&Rename Window"), this);
-  connect(actionRename, SIGNAL(activated()), this, SLOT(rename()));
-
-  actionCloseWindow = new QAction(QIcon(getQPixmap("close_xpm")), tr("Close &Window"), this);
-  actionCloseWindow->setShortcut( tr("Ctrl+W") );
-  connect(actionCloseWindow, SIGNAL(activated()), this, SLOT(closeActiveWindow()));
-
-  actionAddColToTable = new QAction(QIcon(getQPixmap("addCol_xpm")), tr("Add Column"), this);
-  connect(actionAddColToTable, SIGNAL(activated()), this, SLOT(addColToTable()));
-
-  actionGoToRow = new QAction(tr("&Go to Row..."), this);
-  actionGoToRow->setShortcut(tr("Ctrl+Alt+G"));
-  connect(actionGoToRow, SIGNAL(activated()), this, SLOT(goToRow()));
-
-  actionGoToColumn = new QAction(tr("Go to Colum&n..."), this);
-  actionGoToColumn->setShortcut(tr("Ctrl+Alt+C"));
-  connect(actionGoToColumn, SIGNAL(activated()), this, SLOT(goToColumn()));
-
-  actionClearTable = new QAction(getQPixmap("erase_xpm"), tr("Clear"), this);
-  connect(actionClearTable, SIGNAL(activated()), this, SLOT(clearTable()));
-
-  actionDeleteLayer = new QAction(QIcon(getQPixmap("erase_xpm")), tr("&Remove Layer"), this);
-  actionDeleteLayer->setShortcut( tr("Alt+R") );
-  connect(actionDeleteLayer, SIGNAL(activated()), this, SLOT(deleteLayer()));
-
-  actionResizeActiveWindow = new QAction(QIcon(getQPixmap("resize_xpm")), tr("Window &Geometry..."), this);
-  connect(actionResizeActiveWindow, SIGNAL(activated()), this, SLOT(resizeActiveWindow()));
-
-  actionHideActiveWindow = new QAction(tr("&Hide Window"), this);
-  connect(actionHideActiveWindow, SIGNAL(activated()), this, SLOT(hideActiveWindow()));
-
-  actionShowMoreWindows = new QAction(tr("More windows..."), this);
-  connect(actionShowMoreWindows, SIGNAL(activated()), this, SLOT(showMoreWindows()));
-
-  actionPixelLineProfile = new QAction(QIcon(getQPixmap("pixelProfile_xpm")), tr("&View Pixel Line Profile"), this);
-  connect(actionPixelLineProfile, SIGNAL(activated()), this, SLOT(pixelLineProfile()));
-
-  actionIntensityTable = new QAction(tr("&Intensity Table"), this);
-  connect(actionIntensityTable, SIGNAL(activated()), this, SLOT(intensityTable()));
-
-  actionShowLineDialog = new QAction(tr("&Properties"), this);
-  connect(actionShowLineDialog, SIGNAL(activated()), this, SLOT(showLineDialog()));
-
-  actionShowImageDialog = new QAction(tr("&Properties"), this);
-  connect(actionShowImageDialog, SIGNAL(activated()), this, SLOT(showImageDialog()));
-
-  actionShowTextDialog = new QAction(tr("&Properties"), this);
-  connect(actionShowTextDialog, SIGNAL(activated()), this, SLOT(showTextDialog()));
-
-  actionActivateWindow = new QAction(tr("&Activate Window"), this);
-  connect(actionActivateWindow, SIGNAL(activated()), this, SLOT(activateWindow()));
-
-  actionMinimizeWindow = new QAction(tr("Mi&nimize Window"), this);
-  connect(actionMinimizeWindow, SIGNAL(activated()), this, SLOT(minimizeWindow()));
-
-  actionMaximizeWindow = new QAction(tr("Ma&ximize Window"), this);
-  connect(actionMaximizeWindow, SIGNAL(activated()), this, SLOT(maximizeWindow()));
-
-  actionHideWindow = new QAction(tr("&Hide Window"), this);
-  connect(actionHideWindow, SIGNAL(activated()), this, SLOT(hideWindow()));
-
-  actionResizeWindow = new QAction(QIcon(getQPixmap("resize_xpm")), tr("Re&size Window..."), this);
-  connect(actionResizeWindow, SIGNAL(activated()), this, SLOT(resizeWindow()));
-
-  actionEditSurfacePlot = new QAction(tr("&Surface..."), this);
-  connect(actionEditSurfacePlot, SIGNAL(activated()), this, SLOT(editSurfacePlot()));
-
-  actionAdd3DData = new QAction(tr("&Data Set..."), this);
-  connect(actionAdd3DData, SIGNAL(activated()), this, SLOT(add3DData()));
-
-  actionSetMatrixProperties = new QAction(tr("Set &Properties..."), this);
-  connect(actionSetMatrixProperties, SIGNAL(activated()), this, SLOT(showMatrixDialog()));
-
-  actionSetMatrixDimensions = new QAction(tr("Set &Dimensions..."), this);
-  connect(actionSetMatrixDimensions, SIGNAL(activated()), this, SLOT(showMatrixSizeDialog()));
-  actionSetMatrixDimensions->setShortcut(tr("Ctrl+D"));
-
-  actionSetMatrixValues = new QAction(QIcon(getQPixmap("formula_xpm")), tr("Set &Values..."), this);
-  connect(actionSetMatrixValues, SIGNAL(activated()), this, SLOT(showMatrixValuesDialog()));
-  actionSetMatrixValues->setShortcut(tr("Alt+Q"));
-
-  actionImagePlot =  new QAction(QIcon(getQPixmap("image_plot_xpm")), tr("&Image Plot"), this);
-  connect(actionImagePlot, SIGNAL(activated()), this, SLOT(plotImage()));
-
-  actionTransposeMatrix = new QAction(tr("&Transpose"), this);
-  connect(actionTransposeMatrix, SIGNAL(activated()), this, SLOT(transposeMatrix()));
-
-  actionFlipMatrixVertically = new QAction(QIcon(getQPixmap("flip_vertical_xpm")), tr("Flip &V"), this);
-  actionFlipMatrixVertically->setShortcut(tr("Ctrl+Shift+V"));
-  connect(actionFlipMatrixVertically, SIGNAL(activated()), this, SLOT(flipMatrixVertically()));
-
-  actionFlipMatrixHorizontally = new QAction(QIcon(getQPixmap("flip_horizontal_xpm")), tr("Flip &H"), this);
-  actionFlipMatrixHorizontally->setShortcut(tr("Ctrl+Shift+H"));
-  connect(actionFlipMatrixHorizontally, SIGNAL(activated()), this, SLOT(flipMatrixHorizontally()));
-
-  actionRotateMatrix = new QAction(QIcon(getQPixmap("rotate_clockwise_xpm")), tr("R&otate 90"), this);
-  actionRotateMatrix->setShortcut(tr("Ctrl+Shift+R"));
-  connect(actionRotateMatrix, SIGNAL(activated()), this, SLOT(rotateMatrix90()));
-
-  actionRotateMatrixMinus = new QAction(QIcon(getQPixmap("rotate_counterclockwise_xpm")), tr("Rotate &-90"), this);
-  actionRotateMatrixMinus->setShortcut(tr("Ctrl+Alt+R"));
-  connect(actionRotateMatrixMinus, SIGNAL(activated()), this, SLOT(rotateMatrixMinus90()));
-
-  actionInvertMatrix = new QAction(tr("&Invert"), this);
-  connect(actionInvertMatrix, SIGNAL(activated()), this, SLOT(invertMatrix()));
-
-  actionMatrixDeterminant = new QAction(tr("&Determinant"), this);
-  connect(actionMatrixDeterminant, SIGNAL(activated()), this, SLOT(matrixDeterminant()));
-
-  actionViewMatrixImage = new QAction(tr("&Image mode"), this);
-  actionViewMatrixImage->setShortcut(tr("Ctrl+Shift+I"));
-  connect(actionViewMatrixImage, SIGNAL(activated()), this, SLOT(viewMatrixImage()));
-  actionViewMatrixImage->setCheckable(true);
-
-  actionViewMatrix = new QAction(tr("&Data mode"), this);
-  actionViewMatrix->setShortcut(tr("Ctrl+Shift+D"));
-  connect(actionViewMatrix, SIGNAL(activated()), this, SLOT(viewMatrixTable()));
-  actionViewMatrix->setCheckable(true);
-
-  actionMatrixXY = new QAction(tr("Show &X/Y"), this);
-  actionMatrixXY->setShortcut(tr("Ctrl+Shift+X"));
-  connect(actionMatrixXY, SIGNAL(activated()), this, SLOT(viewMatrixXY()));
-  actionMatrixXY->setCheckable(true);
-
-  actionMatrixColumnRow = new QAction(tr("Show &Column/Row"), this);
-  actionMatrixColumnRow->setShortcut(tr("Ctrl+Shift+C"));
-  connect(actionMatrixColumnRow, SIGNAL(activated()), this, SLOT(viewMatrixColumnRow()));
-  actionMatrixColumnRow->setCheckable(true);
-
-  actionMatrixGrayScale = new QAction(tr("&Gray Scale"), this);
-  connect(actionMatrixGrayScale, SIGNAL(activated()), this, SLOT(setMatrixGrayScale()));
-  actionMatrixGrayScale->setCheckable(true);
-
-  actionMatrixRainbowScale = new QAction(tr("&Rainbow"), this);
-  connect(actionMatrixRainbowScale, SIGNAL(activated()), this, SLOT(setMatrixRainbowScale()));
-  actionMatrixRainbowScale->setCheckable(true);
-
-  actionMatrixCustomScale = new QAction(tr("&Custom"), this);
-  connect(actionMatrixCustomScale, SIGNAL(activated()), this, SLOT(showColorMapDialog()));
-  actionMatrixCustomScale->setCheckable(true);
-
-  actionExportMatrix = new QAction(tr("&Export Image ..."), this);
-  connect(actionExportMatrix, SIGNAL(activated()), this, SLOT(exportMatrix()));
-
-  actionConvertMatrixDirect = new QAction(tr("&Direct"), this);
-  connect(actionConvertMatrixDirect, SIGNAL(activated()), this, SLOT(convertMatrixToTableDirect()));
-
-  actionConvertMatrixXYZ = new QAction(tr("&XYZ Columns"), this);
-  connect(actionConvertMatrixXYZ, SIGNAL(activated()), this, SLOT(convertMatrixToTableXYZ()));
-
-  actionConvertMatrixYXZ = new QAction(tr("&YXZ Columns"), this);
-  connect(actionConvertMatrixYXZ, SIGNAL(activated()), this, SLOT(convertMatrixToTableYXZ()));
-
-  actionMatrixFFTDirect = new QAction(tr("&Forward FFT"), this);
-  connect(actionMatrixFFTDirect, SIGNAL(activated()), this, SLOT(matrixDirectFFT()));
-
-  actionMatrixFFTInverse = new QAction(tr("&Inverse FFT"), this);
-  connect(actionMatrixFFTInverse, SIGNAL(activated()), this, SLOT(matrixInverseFFT()));
-
-  actionConvertTable= new QAction(tr("Convert to &Matrix"), this);
-  connect(actionConvertTable, SIGNAL(activated()), this, SLOT(convertTableToMatrix()));
-
-  actionPlot3DWireFrame = new QAction(QIcon(getQPixmap("lineMesh_xpm")), tr("3D &Wire Frame"), this);
-  connect(actionPlot3DWireFrame, SIGNAL(activated()), this, SLOT(plot3DWireframe()));
-
-  actionPlot3DHiddenLine = new QAction(QIcon(getQPixmap("grid_only_xpm")), tr("3D &Hidden Line"), this);
-  connect(actionPlot3DHiddenLine, SIGNAL(activated()), this, SLOT(plot3DHiddenLine()));
-
-  actionPlot3DPolygons = new QAction(QIcon(getQPixmap("no_grid_xpm")), tr("3D &Polygons"), this);
-  connect(actionPlot3DPolygons, SIGNAL(activated()), this, SLOT(plot3DPolygons()));
-
-  actionPlot3DWireSurface = new QAction(QIcon(getQPixmap("grid_poly_xpm")), tr("3D Wire &Surface"), this);
-  connect(actionPlot3DWireSurface, SIGNAL(activated()), this, SLOT(plot3DWireSurface()));
-
-  actionColorMap = new QAction(QIcon(getQPixmap("color_map_xpm")), tr("Contour - &Color Fill"), this);
-  connect(actionColorMap, SIGNAL(activated()), this, SLOT(plotColorMap()));
-
-  actionContourMap = new QAction(QIcon(getQPixmap("contour_map_xpm")), tr("Contour &Lines"), this);
-  connect(actionContourMap, SIGNAL(activated()), this, SLOT(plotContour()));
-
-  actionGrayMap = new QAction(QIcon(getQPixmap("gray_map_xpm")), tr("&Gray Scale Map"), this);
-  connect(actionGrayMap, SIGNAL(activated()), this, SLOT(plotGrayScale()));
-
-  actionNoContourColorMap = new QAction(QIcon(getQPixmap("color_map_xpm")), tr("Color &Fill"), this);
-  connect(actionNoContourColorMap, SIGNAL(activated()), this, SLOT(plotNoContourColorMap()));
-
-  actionSortTable = new QAction(tr("Sort Ta&ble"), this);
-  connect(actionSortTable, SIGNAL(activated()), this, SLOT(sortActiveTable()));
-
-  actionSortSelection = new QAction(tr("Sort Columns"), this);
-  connect(actionSortSelection, SIGNAL(activated()), this, SLOT(sortSelection()));
-
-  actionNormalizeTable = new QAction(tr("&Table"), this);
-  connect(actionNormalizeTable, SIGNAL(activated()), this, SLOT(normalizeActiveTable()));
-
-  actionNormalizeSelection = new QAction(tr("&Columns"), this);
-  connect(actionNormalizeSelection, SIGNAL(activated()), this, SLOT(normalizeSelection()));
-
-  actionCorrelate = new QAction(tr("Co&rrelate"), this);
-  connect(actionCorrelate, SIGNAL(activated()), this, SLOT(correlate()));
-
-  actionAutoCorrelate = new QAction(tr("&Autocorrelate"), this);
-  connect(actionAutoCorrelate, SIGNAL(activated()), this, SLOT(autoCorrelate()));
-
-  actionConvolute = new QAction(tr("&Convolute"), this);
-  connect(actionConvolute, SIGNAL(activated()), this, SLOT(convolute()));
-
-  actionDeconvolute = new QAction(tr("&Deconvolute"), this);
-  connect(actionDeconvolute, SIGNAL(activated()), this, SLOT(deconvolute()));
-
-  actionTranslateHor = new QAction(tr("&Horizontal"), this);
-  connect(actionTranslateHor, SIGNAL(activated()), this, SLOT(translateCurveHor()));
-
-  actionTranslateVert = new QAction(tr("&Vertical"), this);
-  connect(actionTranslateVert, SIGNAL(activated()), this, SLOT(translateCurveVert()));
-
-  actionSetAscValues = new QAction(QIcon(getQPixmap("rowNumbers_xpm")),tr("Ro&w Numbers"), this);
-  connect(actionSetAscValues, SIGNAL(activated()), this, SLOT(setAscValues()));
-
-  actionSetRandomValues = new QAction(QIcon(getQPixmap("randomNumbers_xpm")),tr("&Random Values"), this);
-  connect(actionSetRandomValues, SIGNAL(activated()), this, SLOT(setRandomValues()));
-
-  actionReadOnlyCol = new QAction(tr("&Read Only"), this);
-  connect(actionReadOnlyCol, SIGNAL(activated()), this, SLOT(setReadOnlyCol()));
-
-  actionSetXCol = new QAction(QIcon(getQPixmap("x_col_xpm")), tr("&X"), this);
-  connect(actionSetXCol, SIGNAL(activated()), this, SLOT(setXCol()));
-
-  actionSetYCol = new QAction(QIcon(getQPixmap("y_col_xpm")), tr("&Y"), this);
-  connect(actionSetYCol, SIGNAL(activated()), this, SLOT(setYCol()));
-
-  actionSetZCol = new QAction(QIcon(getQPixmap("z_col_xpm")), tr("&Z"), this);
-  connect(actionSetZCol, SIGNAL(activated()), this, SLOT(setZCol()));
-
-  actionSetXErrCol = new QAction(tr("X E&rror"), this);
-  connect(actionSetXErrCol, SIGNAL(activated()), this, SLOT(setXErrCol()));
-
-  actionSetYErrCol = new QAction(QIcon(getQPixmap("errors_xpm")), tr("Y &Error"), this);
-  connect(actionSetYErrCol, SIGNAL(activated()), this, SLOT(setYErrCol()));
-
-  actionDisregardCol = new QAction(QIcon(getQPixmap("disregard_col_xpm")), tr("&Disregard"), this);
-  connect(actionDisregardCol, SIGNAL(activated()), this, SLOT(disregardCol()));
-
-  actionSetLabelCol = new QAction(QIcon(getQPixmap("set_label_col_xpm")), tr("&Label"), this);
-  connect(actionSetLabelCol, SIGNAL(activated()), this, SLOT(setLabelCol()));
-
-  actionBoxPlot = new QAction(QIcon(getQPixmap("boxPlot_xpm")),tr("&Box Plot"), this);
-  connect(actionBoxPlot, SIGNAL(activated()), this, SLOT(plotBoxDiagram()));
-
-  actionMultiPeakGauss = new QAction(tr("&Gaussian..."), this);
-  connect(actionMultiPeakGauss, SIGNAL(activated()), this, SLOT(fitMultiPeakGauss()));
-
-  actionMultiPeakLorentz = new QAction(tr("&Lorentzian..."), this);
-  connect(actionMultiPeakLorentz, SIGNAL(activated()), this, SLOT(fitMultiPeakLorentz()));
-
-  //actionCheckUpdates = new QAction(tr("Search for &Updates"), this);
-  //connect(actionCheckUpdates, SIGNAL(activated()), this, SLOT(searchForUpdates()));
-
-  actionHomePage = new QAction(tr("&Mantid Homepage"), this); //Mantid change
-  connect(actionHomePage, SIGNAL(activated()), this, SLOT(showHomePage()));
-
-  //actionHelpForums = new QAction(tr("QtiPlot &Forums"), this); // Mantid change
-  //	connect(actionHelpForums, SIGNAL(triggered()), this, SLOT(showForums())); // Mantid change
-
-  actionHelpBugReports = new QAction(tr("Report a &Bug"), this);
-  connect(actionHelpBugReports, SIGNAL(triggered()), this, SLOT(showBugTracker()));
-
-  //actionDownloadManual = new QAction(tr("Download &Manual"), this); // Mantid change
-  //connect(actionDownloadManual, SIGNAL(activated()), this, SLOT(downloadManual())); // Mantid change
-
-  //actionTranslations = new QAction(tr("&Translations"), this); // Mantid change
-  //connect(actionTranslations, SIGNAL(activated()), this, SLOT(downloadTranslation())); // Mantid change
-
-  //actionDonate = new QAction(tr("Make a &Donation"), this); // Mantid change
-  //connect(actionDonate, SIGNAL(activated()), this, SLOT(showDonationsPage())); // Mantid change
-
-  // 	actionTechnicalSupport = new QAction(tr("Technical &Support"), this); // Mantid change
-  // 	connect(actionTechnicalSupport, SIGNAL(activated()), this, SLOT(showSupportPage())); // Mantid change
-
-  //#ifdef SCRIPTING_DIALOG
-  //	actionScriptingLang = new QAction(tr("Scripting &language"), this);
-  //	connect(actionScriptingLang, SIGNAL(activated()), this, SLOT(showScriptingLangDialog()));
-  //#endif
-
-  actionNoteExecute = new QAction(tr("E&xecute"), this);
-  actionNoteExecute->setShortcut(tr("Ctrl+J"));
-
-  actionNoteExecuteAll = new QAction(tr("Execute &All"), this);
-  actionNoteExecuteAll->setShortcut(tr("Ctrl+Shift+J"));
-
-  actionNoteEvaluate = new QAction(tr("&Evaluate Expression"), this);
-  actionNoteEvaluate->setShortcut(tr("Ctrl+Return"));
-
-#ifdef SCRIPTING_PYTHON
-  actionShowScriptWindow = new QAction(getQPixmap("python_xpm"), tr("Toggle &Script Window"), this);
-  actionShowScriptWindow->setShortcut(tr("F3"));
-  actionShowScriptWindow->setToggleAction(true);
-  connect(actionShowScriptWindow, SIGNAL(activated()), this, SLOT(showScriptWindow()));
-  actionShowScriptInterpreter = new QAction(getQPixmap("python_xpm"), tr("Toggle Script &Interpreter"), this);
-  actionShowScriptInterpreter->setShortcut(tr("F4"));
-  actionShowScriptInterpreter->setToggleAction(true);
-  connect(actionShowScriptInterpreter, SIGNAL(activated()), this, SLOT(showScriptInterpreter()));
-#endif
-
-  actionShowCurvePlotDialog = new QAction(tr("&Plot details..."), this);
-  connect(actionShowCurvePlotDialog, SIGNAL(activated()), this, SLOT(showCurvePlotDialog()));
-
-  actionShowCurveWorksheet = new QAction(tr("&Worksheet"), this);
-  connect(actionShowCurveWorksheet, SIGNAL(activated()), this, SLOT(showCurveWorksheet()));
-
-  actionCurveFullRange = new QAction(tr("&Reset to Full Range"), this);
-  connect(actionCurveFullRange, SIGNAL(activated()), this, SLOT(setCurveFullRange()));
-
-  actionEditCurveRange = new QAction(tr("Edit &Range..."), this);
-  connect(actionEditCurveRange, SIGNAL(activated()), this, SLOT(showCurveRangeDialog()));
-
-  actionRemoveCurve = new QAction(getQPixmap("close_xpm"), tr("&Delete"), this);
-  connect(actionRemoveCurve, SIGNAL(activated()), this, SLOT(removeCurve()));
-
-  actionHideCurve = new QAction(tr("&Hide"), this);
-  connect(actionHideCurve, SIGNAL(activated()), this, SLOT(hideCurve()));
-
-  actionHideOtherCurves = new QAction(tr("Hide &Other Curves"), this);
-  connect(actionHideOtherCurves, SIGNAL(activated()), this, SLOT(hideOtherCurves()));
-
-  actionShowAllCurves = new QAction(tr("&Show All Curves"), this);
-  connect(actionShowAllCurves, SIGNAL(activated()), this, SLOT(showAllCurves()));
-
-  actionEditFunction = new QAction(tr("&Edit Function..."), this);
-  connect(actionEditFunction, SIGNAL(activated()), this, SLOT(showFunctionDialog()));
-
-  actionToolBars = new QAction(tr("&Toolbars..."), this);
-  actionToolBars->setShortcut(tr("Ctrl+Shift+T"));
-  connect(actionToolBars, SIGNAL(activated()), this, SLOT(showToolBarsMenu()));
-
-  actionFontBold = new QAction("B", this);
-  actionFontBold->setToolTip(tr("Bold"));
-  QFont font = appFont;
-  font.setBold(true);
-  actionFontBold->setFont(font);
-  actionFontBold->setCheckable(true);
-  connect(actionFontBold, SIGNAL(toggled(bool)), this, SLOT(setBoldFont(bool)));
-
-  actionFontItalic = new QAction("It", this);
-  actionFontItalic->setToolTip(tr("Italic"));
-  font = appFont;
-  font.setItalic(true);
-  actionFontItalic->setFont(font);
-  actionFontItalic->setCheckable(true);
-  connect(actionFontItalic, SIGNAL(toggled(bool)), this, SLOT(setItalicFont(bool)));
-
-  actionSuperscript = new QAction(getQPixmap("exp_xpm"), tr("Superscript"), this);
-  connect(actionSuperscript, SIGNAL(activated()), this, SLOT(insertSuperscript()));
-  actionSuperscript->setEnabled(false);
-
-  actionSubscript = new QAction(getQPixmap("index_xpm"), tr("Subscript"), this);
-  connect(actionSubscript, SIGNAL(activated()), this, SLOT(insertSubscript()));
-  actionSubscript->setEnabled(false);
-
-  actionUnderline = new QAction("U", this);
-  actionUnderline->setToolTip(tr("Underline (Ctrl+U)"));
-  actionUnderline->setShortcut(tr("Ctrl+U"));
-  font = appFont;
-  font.setUnderline(true);
-  actionUnderline->setFont(font);
-  connect(actionUnderline, SIGNAL(activated()), this, SLOT(underline()));
-  actionUnderline->setEnabled(false);
-
-  actionGreekSymbol = new QAction(QString(QChar(0x3B1)) + QString(QChar(0x3B2)), this);
-  actionGreekSymbol->setToolTip(tr("Greek"));
-  connect(actionGreekSymbol, SIGNAL(activated()), this, SLOT(insertGreekSymbol()));
-
-  actionGreekMajSymbol = new QAction(QString(QChar(0x393)), this);
-  actionGreekMajSymbol->setToolTip(tr("Greek"));
-  connect(actionGreekMajSymbol, SIGNAL(activated()), this, SLOT(insertGreekMajSymbol()));
-
-  actionMathSymbol = new QAction(QString(QChar(0x222B)), this);
-  actionMathSymbol->setToolTip(tr("Mathematical Symbols"));
-  connect(actionMathSymbol, SIGNAL(activated()), this, SLOT(insertMathSymbol()));
-
-  actionclearAllMemory = new QAction("&Clear All Memory",this);
-  actionclearAllMemory->setShortcut(QKeySequence::fromString("Ctrl+Shift+L"));
-  connect(actionclearAllMemory,SIGNAL(triggered()), mantidUI, SLOT(clearAllMemory() ));
+  m_iface_script->setCode(code);
+  if( !quiet )
+  {
+    // Output a message to say we've started
+    scriptPrint("Script execution started.", false, true);
+  }
+  bool success = m_iface_script->exec();
+  if(success && !quiet)
+  {
+    scriptPrint("Script execution completed successfully.", false, true);
+  }
+    
+}
 
-#ifdef USE_TCMALLOC
-  actionreleaseFreeMemory = new QAction("&Release Free Memory",this);
-  connect(actionreleaseFreeMemory,SIGNAL(triggered()), mantidUI, SLOT(releaseFreeMemory() ));
-#endif
-
-  actionMagnify = new QAction(QIcon(getQPixmap("magnifier_xpm")), tr("Zoom &In/Out and Drag Canvas"), this);
-  connect(actionMagnify, SIGNAL(activated()), this, SLOT(magnify()));
-
-  actionICatLogin  = new QAction("Login",this);
-  actionICatLogin->setToolTip(tr("Catalog Login"));
-  connect(actionICatLogin, SIGNAL(activated()), this, SLOT(ICatLogin()));
-
-  actionICatSearch=new QAction("Basic Search",this);
-  actionICatSearch->setToolTip(tr("Catalog Basic Search"));
-  connect(actionICatSearch, SIGNAL(activated()), this, SLOT(ICatIsisSearch()));
-
-  actionMydataSearch=new QAction("My Data Search",this);
-  actionMydataSearch->setToolTip(tr("Catalog MyData Search"));
-  connect(actionMydataSearch, SIGNAL(activated()), this, SLOT(ICatMyDataSearch()));
-
-  actionICatLogout=new QAction("Logout",this);
-  actionICatLogout->setToolTip(tr("Catalog Logout"));
-  connect(actionICatLogout, SIGNAL(activated()), this, SLOT(ICatLogout()));
-
-  actionAdvancedSearch = new QAction("Advanced Search",this);
-  actionAdvancedSearch->setToolTip(tr("Catalog Advanced Search"));
-  connect(actionAdvancedSearch, SIGNAL(activated()), this, SLOT(ICatAdvancedSearch()));
-}
-
-void ApplicationWindow::translateActionsStrings()
-{
-  actionFontBold->setToolTip(tr("Bold"));
-  actionFontItalic->setToolTip(tr("Italic"));
-  actionUnderline->setStatusTip(tr("Underline (Ctrl+U)"));
-  actionUnderline->setShortcut(tr("Ctrl+U"));
-  actionGreekSymbol->setToolTip(tr("Greek"));
-  actionGreekMajSymbol->setToolTip(tr("Greek"));
-  actionMathSymbol->setToolTip(tr("Mathematical Symbols"));
-
-  actionShowCurvePlotDialog->setMenuText(tr("&Plot details..."));
-  actionShowCurveWorksheet->setMenuText(tr("&Worksheet"));
-  actionRemoveCurve->setMenuText(tr("&Delete"));
-  actionEditFunction->setMenuText(tr("&Edit Function..."));
-
-  actionCurveFullRange->setMenuText(tr("&Reset to Full Range"));
-  actionEditCurveRange->setMenuText(tr("Edit &Range..."));
-  actionHideCurve->setMenuText(tr("&Hide"));
-  actionHideOtherCurves->setMenuText(tr("Hide &Other Curves"));
-  actionShowAllCurves->setMenuText(tr("&Show All Curves"));
-
-  actionNewProject->setMenuText(tr("New &Project"));
-  actionNewProject->setToolTip(tr("Open a new project"));
-  actionNewProject->setShortcut(tr("Ctrl+N"));
-
-  actionNewFolder->setMenuText(tr("New Fol&der"));
-  actionNewFolder->setToolTip(tr("Create a new folder"));
-  actionNewFolder->setShortcut(Qt::Key_F7);
-
-  actionNewGraph->setMenuText(tr("New &Graph"));
-  actionNewGraph->setToolTip(tr("Create an empty 2D plot"));
-  actionNewGraph->setShortcut(tr("Ctrl+G"));
-
-  actionNewNote->setMenuText(tr("New &Note"));
-  actionNewNote->setToolTip(tr("Create an empty note window"));
-
-  actionNewTable->setMenuText(tr("New &Table"));
-  actionNewTable->setShortcut(tr("Ctrl+T"));
-  actionNewTable->setToolTip(tr("New table"));
-
-  actionNewMatrix->setMenuText(tr("New &Matrix"));
-  actionNewMatrix->setShortcut(tr("Ctrl+M"));
-  actionNewMatrix->setToolTip(tr("New matrix"));
-
-  actionNewFunctionPlot->setMenuText(tr("New &Function Plot"));
-  actionNewFunctionPlot->setToolTip(tr("Create a new 2D function plot"));
-  actionNewFunctionPlot->setShortcut(tr("Ctrl+F"));
-
-  actionNewSurfacePlot->setMenuText(tr("New 3D &Surface Plot"));
-  actionNewSurfacePlot->setToolTip(tr("Create a new 3D surface plot"));
-  actionNewSurfacePlot->setShortcut(tr("Ctrl+ALT+Z"));
-
-  actionOpenProj->setMenuText(tr("&Project"));
-  actionOpenProj->setShortcut(tr("Ctrl+Shift+O"));
-  actionOpenProj->setToolTip(tr("Load Mantid project"));
-
-  actionLoadFile->setMenuText(tr("&File"));
-  actionLoadFile->setShortcut(tr("Ctrl+Shift+F"));
-  actionLoadFile->setToolTip(tr("Load Data File"));
- 
-
-  actionLoadImage->setMenuText(tr("Open Image &File"));
-  actionLoadImage->setShortcut(tr("Ctrl+I"));
-
-  actionImportImage->setMenuText(tr("Import I&mage..."));
-
-  actionSaveFile->setMenuText(tr("&Nexus"));
-  actionSaveFile->setToolTip(tr("Save nexus file"));
-  actionSaveFile->setShortcut(tr("Ctrl+S"));
-
-  actionSaveProject->setMenuText(tr("&Project"));
-  actionSaveProject->setToolTip(tr("Save Mantid Project"));
-  actionSaveProject->setShortcut(tr("Ctrl+Shift+S"));
-
-
-  actionSaveProjectAs->setMenuText(tr("Save Project &As..."));
-
-  actionOpenTemplate->setMenuText(tr("Open Te&mplate..."));
-  actionOpenTemplate->setToolTip(tr("Open template"));
-
-  actionSaveTemplate->setMenuText(tr("Save As &Template..."));
-  actionSaveTemplate->setToolTip(tr("Save window as template"));
-
-  actionLoad->setMenuText(tr("&Import ASCII..."));
-  actionLoad->setToolTip(tr("Import data file(s)"));
-  actionLoad->setShortcut(tr("Ctrl+K"));
-
-  actionUndo->setMenuText(tr("&Undo"));
-  actionUndo->setToolTip(tr("Undo changes"));
-  actionUndo->setShortcut(tr("Ctrl+Z"));
-
-  actionRedo->setMenuText(tr("&Redo"));
-  actionRedo->setToolTip(tr("Redo changes"));
-  actionRedo->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_Z));
-
-  actionCopyWindow->setMenuText(tr("&Duplicate"));
-  actionCopyWindow->setToolTip(tr("Duplicate window"));
-
-  actionCutSelection->setMenuText(tr("Cu&t Selection"));
-  actionCutSelection->setToolTip(tr("Cut selection"));
-  actionCutSelection->setShortcut(tr("Ctrl+X"));
-  
-  actionCopySelection->setMenuText(tr("&Copy Selection"));
-  actionCopySelection->setToolTip(tr("Copy selection"));
-  actionCopySelection->setShortcut(tr("Ctrl+C"));
-  
-
-  actionPasteSelection->setMenuText(tr("&Paste Selection"));
-  actionPasteSelection->setToolTip(tr("Paste selection"));
-  actionPasteSelection->setShortcut(tr("Ctrl+V"));
-  
-
-  actionClearSelection->setMenuText(tr("&Delete Selection"));
-  actionClearSelection->setToolTip(tr("Delete selection"));
-  actionClearSelection->setShortcut(tr("Del","delete key"));
-
-  actionShowExplorer->setMenuText(tr("Project &Explorer"));
-  actionShowExplorer->setShortcut(tr("Ctrl+E"));
-  actionShowExplorer->setToolTip(tr("Show project explorer"));
-
-  actionShowLog->setMenuText(tr("Results &Log"));
-  actionShowLog->setToolTip(tr("Show analysis results"));
-
-  actionShowUndoStack->setMenuText(tr("&Undo/Redo Stack"));
-  actionShowUndoStack->setToolTip(tr("Show available undo/redo commands"));
-
-    //#ifdef SCRIPTING_CONSOLE
-  actionShowConsole->setMenuText(tr("&Console"));
-  actionShowConsole->setToolTip(tr("Show Scripting console"));
-    //#endif
-
-#ifdef SCRIPTING_PYTHON
-  actionShowScriptWindow->setMenuText(tr("&Script Window"));
-  actionShowScriptWindow->setToolTip(tr("Script Window"));
-  actionShowScriptWindow->setShortcut(tr("F3"));
-#endif
-
-  actionCustomActionDialog->setMenuText(tr("Manage Custom Menus..."));
-
-  actionAddLayer->setMenuText(tr("Add La&yer"));
-  actionAddLayer->setToolTip(tr("Add Layer"));
-  actionAddLayer->setShortcut(tr("Alt+L"));
-
-  actionShowLayerDialog->setMenuText(tr("Arran&ge Layers"));
-  actionShowLayerDialog->setToolTip(tr("Arrange Layers"));
-  actionShowLayerDialog->setShortcut(tr("Alt+A"));
-
-  actionAutomaticLayout->setMenuText(tr("Automatic Layout"));
-  actionAutomaticLayout->setToolTip(tr("Automatic Layout"));
-
-  actionExportGraph->setMenuText(tr("&Current"));
-  actionExportGraph->setShortcut(tr("Alt+G"));
-  actionExportGraph->setToolTip(tr("Export current graph"));
-
-  actionExportAllGraphs->setMenuText(tr("&All"));
-  actionExportAllGraphs->setShortcut(tr("Alt+X"));
-  actionExportAllGraphs->setToolTip(tr("Export all graphs"));
-
-  actionExportPDF->setMenuText(tr("&Export PDF"));
-  actionExportPDF->setShortcut(tr("Ctrl+Alt+P"));
-  actionExportPDF->setToolTip(tr("Export to PDF"));
-
-  actionPrint->setMenuText(tr("&Print"));
-  actionPrint->setShortcut(tr("Ctrl+P"));
-  actionPrint->setToolTip(tr("Print window"));
-
-  actionPrintAllPlots->setMenuText(tr("Print All Plo&ts"));
-  actionShowExportASCIIDialog->setMenuText(tr("E&xport ASCII"));
-
-  actionCloseAllWindows->setMenuText(tr("&Quit"));
-  actionCloseAllWindows->setShortcut(tr("Ctrl+Q"));
-
-  actionClearLogInfo->setMenuText(tr("Clear &Log Information"));
-  actionClearConsole->setMenuText(tr("Clear &Console"));
-  actionDeleteFitTables->setMenuText(tr("Delete &Fit Tables"));
-
-  actionToolBars->setMenuText(tr("&Toolbars..."));
-  actionToolBars->setShortcut(tr("Ctrl+Shift+T"));
-
-  actionShowPlotWizard->setMenuText(tr("Plot &Wizard"));
-  actionShowPlotWizard->setShortcut(tr("Ctrl+Alt+W"));
-
-  actionShowConfigureDialog->setMenuText(tr("&Preferences..."));
-
-  actionShowCurvesDialog->setMenuText(tr("Add/Remove &Curve..."));
-  actionShowCurvesDialog->setShortcut(tr("ALT+C"));
-  actionShowCurvesDialog->setToolTip(tr("Add curve to graph"));
-
-  actionAddErrorBars->setMenuText(tr("Add &Error Bars..."));
-  actionAddErrorBars->setToolTip(tr("Add Error Bars..."));
-  actionAddErrorBars->setShortcut(tr("Ctrl+B"));
-
-  actionAddFunctionCurve->setMenuText(tr("Add &Function..."));
-  actionAddFunctionCurve->setToolTip(tr("Add Function..."));
-  actionAddFunctionCurve->setShortcut(tr("Ctrl+Alt+F"));
-
-  actionUnzoom->setMenuText(tr("&Rescale to Show All"));
-  actionUnzoom->setShortcut(tr("Ctrl+Shift+R"));
-  actionUnzoom->setToolTip(tr("Best fit"));
-
-  actionNewLegend->setMenuText( tr("New &Legend"));
-  actionNewLegend->setShortcut(tr("Ctrl+L"));
-  actionNewLegend->setToolTip(tr("Add new legend"));
-
-  actionTimeStamp->setMenuText(tr("Add Time Stamp"));
-  actionTimeStamp->setShortcut(tr("Ctrl+ALT+T"));
-  actionTimeStamp->setToolTip(tr("Date & time "));
-
-  actionAddImage->setMenuText(tr("Add &Image"));
-  actionAddImage->setToolTip(tr("Add Image"));
-  actionAddImage->setShortcut(tr("ALT+I"));
-
-  actionPlotL->setMenuText(tr("&Line"));
-  actionPlotL->setToolTip(tr("Plot as line"));
-
-  actionPlotP->setMenuText(tr("&Scatter"));
-  actionPlotP->setToolTip(tr("Plot as symbols"));
-
-  actionPlotLP->setMenuText(tr("Line + S&ymbol"));
-  actionPlotLP->setToolTip(tr("Plot as line + symbols"));
-
-  actionPlotVerticalDropLines->setMenuText(tr("Vertical &Drop Lines"));
-
-  actionPlotSpline->setMenuText(tr("&Spline"));
-  actionPlotVertSteps->setMenuText(tr("&Vertical Steps"));
-  actionPlotHorSteps->setMenuText(tr("&Horizontal Steps"));
-
-  actionPlotVerticalBars->setMenuText(tr("&Columns"));
-  actionPlotVerticalBars->setToolTip(tr("Plot with vertical bars"));
-
-  actionPlotHorizontalBars->setMenuText(tr("&Rows"));
-  actionPlotHorizontalBars->setToolTip(tr("Plot with horizontal bars"));
-
-  actionPlotArea->setMenuText(tr("&Area"));
-  actionPlotArea->setToolTip(tr("Plot area"));
-
-  actionPlotPie->setMenuText(tr("&Pie"));
-  actionPlotPie->setToolTip(tr("Plot pie"));
-
-  actionPlotVectXYXY->setMenuText(tr("&Vectors XYXY"));
-  actionPlotVectXYXY->setToolTip(tr("Vectors XYXY"));
-
-  actionPlotVectXYAM->setMenuText(tr("Vectors XY&AM"));
-  actionPlotVectXYAM->setToolTip(tr("Vectors XYAM"));
-
-  actionPlotHistogram->setMenuText( tr("&Histogram"));
-  actionPlotStackedHistograms->setMenuText(tr("&Stacked Histogram"));
-  actionPlot2VerticalLayers->setMenuText(tr("&Vertical 2 Layers"));
-  actionPlot2HorizontalLayers->setMenuText(tr("&Horizontal 2 Layers"));
-  actionPlot4Layers->setMenuText(tr("&4 Layers"));
-  actionPlotStackedLayers->setMenuText(tr("&Stacked Layers"));
-
-  actionPlot3DRibbon->setMenuText(tr("&Ribbon"));
-  actionPlot3DRibbon->setToolTip(tr("Plot 3D ribbon"));
-
-  actionPlot3DBars->setMenuText(tr("&Bars"));
-  actionPlot3DBars->setToolTip(tr("Plot 3D bars"));
-
-  actionPlot3DScatter->setMenuText(tr("&Scatter"));
-  actionPlot3DScatter->setToolTip(tr("Plot 3D scatter"));
-
-  actionPlot3DTrajectory->setMenuText(tr("&Trajectory"));
-  actionPlot3DTrajectory->setToolTip(tr("Plot 3D trajectory"));
-
-  actionColorMap->setMenuText(tr("Contour + &Color Fill"));
-  actionColorMap->setToolTip(tr("Contour Lines + Color Fill"));
-
-  actionNoContourColorMap->setMenuText(tr("Color &Fill"));
-  actionNoContourColorMap->setToolTip(tr("Color Fill (No contours)"));
-
-  actionContourMap->setMenuText(tr("Contour &Lines"));
-  actionContourMap->setToolTip(tr("Contour Lines"));
-
-  actionGrayMap->setMenuText(tr("&Gray Scale Map"));
-  actionGrayMap->setToolTip(tr("Gray Scale Map"));
-
-  actionShowColStatistics->setMenuText(tr("Statistics on &Columns"));
-  actionShowColStatistics->setToolTip(tr("Selected columns statistics"));
-
-  actionShowRowStatistics->setMenuText(tr("Statistics on &Rows"));
-  actionShowRowStatistics->setToolTip(tr("Selected rows statistics"));
-  actionShowIntDialog->setMenuText(tr("Integr&ate Function..."));
-  actionIntegrate->setMenuText(tr("&Integrate"));
-  actionInterpolate->setMenuText(tr("Inte&rpolate ..."));
-  actionLowPassFilter->setMenuText(tr("&Low Pass..."));
-  actionHighPassFilter->setMenuText(tr("&High Pass..."));
-  actionBandPassFilter->setMenuText(tr("&Band Pass..."));
-  actionBandBlockFilter->setMenuText(tr("&Band Block..."));
-  actionFFT->setMenuText(tr("&FFT..."));
-  actionSmoothSavGol->setMenuText(tr("&Savitzky-Golay..."));
-  actionSmoothFFT->setMenuText(tr("&FFT Filter..."));
-  actionSmoothAverage->setMenuText(tr("Moving Window &Average..."));
-  actionDifferentiate->setMenuText(tr("&Differentiate"));
-  actionFitLinear->setMenuText(tr("Fit &Linear"));
-  actionShowFitPolynomDialog->setMenuText(tr("Fit &Polynomial ..."));
-  actionShowExpDecayDialog->setMenuText(tr("&First Order ..."));
-  actionShowTwoExpDecayDialog->setMenuText(tr("&Second Order ..."));
-  actionShowExpDecay3Dialog->setMenuText(tr("&Third Order ..."));
-  actionFitExpGrowth->setMenuText(tr("Fit Exponential Gro&wth ..."));
-  actionFitSigmoidal->setMenuText(tr("Fit &Boltzmann (Sigmoidal)"));
-  actionFitGauss->setMenuText(tr("Fit &Gaussian"));
-  actionFitLorentz->setMenuText(tr("Fit Lorent&zian"));
-
-  actionShowFitDialog->setMenuText(tr("Fit &Wizard..."));
-  actionShowFitDialog->setShortcut(tr("Ctrl+Y"));
-
-  actionShowPlotDialog->setMenuText(tr("&Plot ..."));
-  actionShowScaleDialog->setMenuText(tr("&Scales..."));
-  actionShowAxisDialog->setMenuText(tr("&Axes..."));
-  actionShowGridDialog->setMenuText(tr("&Grid ..."));
-  actionShowTitleDialog->setMenuText(tr("&Title ..."));
-  actionShowColumnOptionsDialog->setMenuText(tr("Column &Options ..."));
-  actionShowColumnOptionsDialog->setShortcut(tr("Ctrl+Alt+O"));
-  actionShowColumnValuesDialog->setMenuText(tr("Set Column &Values ..."));
-  actionShowColumnValuesDialog->setShortcut(tr("Alt+Q"));
-  actionTableRecalculate->setMenuText(tr("Recalculate"));
-  actionTableRecalculate->setShortcut(tr("Ctrl+Return"));
-  actionHideSelectedColumns->setMenuText(tr("&Hide Selected"));
-  actionHideSelectedColumns->setToolTip(tr("Hide selected columns"));
-  actionShowAllColumns->setMenuText(tr("Sho&w All Columns"));
-  actionHideSelectedColumns->setToolTip(tr("Show all table columns"));
-  actionSwapColumns->setMenuText(tr("&Swap columns"));
-  actionSwapColumns->setToolTip(tr("Swap selected columns"));
-  actionMoveColRight->setMenuText(tr("Move &Right"));
-  actionMoveColRight->setToolTip(tr("Move Right"));
-  actionMoveColLeft->setMenuText(tr("Move &Left"));
-  actionMoveColLeft->setToolTip(tr("Move Left"));
-  actionMoveColFirst->setMenuText(tr("Move to F&irst"));
-  actionMoveColFirst->setToolTip(tr("Move to First"));
-  actionMoveColLast->setMenuText(tr("Move to Las&t"));
-  actionMoveColLast->setToolTip(tr("Move to Last"));
-  actionShowColsDialog->setMenuText(tr("&Columns..."));
-  actionShowRowsDialog->setMenuText(tr("&Rows..."));
-  actionDeleteRows->setMenuText(tr("&Delete Rows Interval..."));
-
-  actionAbout->setMenuText(tr("&About MantidPlot"));//Mantid
-  actionAbout->setShortcut(tr("F1"));
-
-  //actionShowHelp->setMenuText(tr("&Help"));
-  //actionShowHelp->setShortcut(tr("Ctrl+H"));
-
-  actionMantidConcepts->setMenuText(tr("&Mantid Concepts"));
-
-  actionMantidAlgorithms->setMenuText("&Algorithm Descriptions");
-
-  actionmantidplotHelp->setMenuText("&MantidPlot Help");
-
-  //actionChooseHelpFolder->setMenuText(tr("&Choose Help Folder..."));
-  //actionRename->setMenuText(tr("&Rename Window"));
-
-  actionCloseWindow->setMenuText(tr("Close &Window"));
-  actionCloseWindow->setShortcut(tr("Ctrl+W"));
-
-  actionAddColToTable->setMenuText(tr("Add Column"));
-  actionAddColToTable->setToolTip(tr("Add Column"));
-
-  actionClearTable->setMenuText(tr("Clear"));
-  actionGoToRow->setMenuText(tr("&Go to Row..."));
-  actionGoToRow->setShortcut(tr("Ctrl+Alt+G"));
-
-  actionGoToColumn->setMenuText(tr("Go to Colum&n..."));
-  actionGoToColumn->setShortcut(tr("Ctrl+Alt+C"));
-
-  actionDeleteLayer->setMenuText(tr("&Remove Layer"));
-  actionDeleteLayer->setShortcut(tr("Alt+R"));
-
-  actionResizeActiveWindow->setMenuText(tr("Window &Geometry..."));
-  actionHideActiveWindow->setMenuText(tr("&Hide Window"));
-  actionShowMoreWindows->setMenuText(tr("More Windows..."));
-  actionPixelLineProfile->setMenuText(tr("&View Pixel Line Profile"));
-  actionIntensityTable->setMenuText(tr("&Intensity Table"));
-  actionShowLineDialog->setMenuText(tr("&Properties"));
-  actionShowImageDialog->setMenuText(tr("&Properties"));
-  actionShowTextDialog->setMenuText(tr("&Properties"));
-  actionActivateWindow->setMenuText(tr("&Activate Window"));
-  actionMinimizeWindow->setMenuText(tr("Mi&nimize Window"));
-  actionMaximizeWindow->setMenuText(tr("Ma&ximize Window"));
-  actionHideWindow->setMenuText(tr("&Hide Window"));
-  actionResizeWindow->setMenuText(tr("Re&size Window..."));
-  actionEditSurfacePlot->setMenuText(tr("&Surface..."));
-  actionAdd3DData->setMenuText(tr("&Data Set..."));
-  actionSetMatrixProperties->setMenuText(tr("Set &Properties..."));
-  actionSetMatrixDimensions->setMenuText(tr("Set &Dimensions..."));
-  actionSetMatrixDimensions->setShortcut(tr("Ctrl+D"));
-  actionSetMatrixValues->setMenuText(tr("Set &Values..."));
-  actionSetMatrixValues->setToolTip(tr("Set Matrix Values"));
-  actionSetMatrixValues->setShortcut(tr("Alt+Q"));
-  actionImagePlot->setMenuText(tr("&Image Plot"));
-  actionImagePlot->setToolTip(tr("Image Plot"));
-  actionTransposeMatrix->setMenuText(tr("&Transpose"));
-  actionRotateMatrix->setMenuText(tr("R&otate 90"));
-  actionRotateMatrix->setToolTip(tr("Rotate 90° Clockwise"));
-  actionRotateMatrixMinus->setMenuText(tr("Rotate &-90"));
-  actionRotateMatrixMinus->setToolTip(tr("Rotate 90° Counterclockwise"));
-  actionFlipMatrixVertically->setMenuText(tr("Flip &V"));
-  actionFlipMatrixVertically->setToolTip(tr("Flip Vertically"));
-  actionFlipMatrixHorizontally->setMenuText(tr("Flip &H"));
-  actionFlipMatrixHorizontally->setToolTip(tr("Flip Horizontally"));
-
-  actionMatrixXY->setMenuText(tr("Show &X/Y"));
-  actionMatrixColumnRow->setMenuText(tr("Show &Column/Row"));
-  actionViewMatrix->setMenuText(tr("&Data mode"));
-  actionViewMatrixImage->setMenuText(tr("&Image mode"));
-  actionMatrixGrayScale->setMenuText(tr("&Gray Scale"));
-  actionMatrixRainbowScale->setMenuText(tr("&Rainbow"));
-  actionMatrixCustomScale->setMenuText(tr("&Custom"));
-  actionInvertMatrix->setMenuText(tr("&Invert"));
-  actionMatrixDeterminant->setMenuText(tr("&Determinant"));
-  actionConvertMatrixDirect->setMenuText(tr("&Direct"));
-  actionConvertMatrixXYZ->setMenuText(tr("&XYZ Columns"));
-  actionConvertMatrixYXZ->setMenuText(tr("&YXZ Columns"));
-  actionExportMatrix->setMenuText(tr("&Export Image ..."));
-
-  actionConvertTable->setMenuText(tr("Convert to &Matrix"));
-  actionPlot3DWireFrame->setMenuText(tr("3D &Wire Frame"));
-  actionPlot3DHiddenLine->setMenuText(tr("3D &Hidden Line"));
-  actionPlot3DPolygons->setMenuText(tr("3D &Polygons"));
-  actionPlot3DWireSurface->setMenuText(tr("3D Wire &Surface"));
-  actionSortTable->setMenuText(tr("Sort Ta&ble"));
-  actionSortSelection->setMenuText(tr("Sort Columns"));
-  actionNormalizeTable->setMenuText(tr("&Table"));
-  actionNormalizeSelection->setMenuText(tr("&Columns"));
-  actionCorrelate->setMenuText(tr("Co&rrelate"));
-  actionAutoCorrelate->setMenuText(tr("&Autocorrelate"));
-  actionConvolute->setMenuText(tr("&Convolute"));
-  actionDeconvolute->setMenuText(tr("&Deconvolute"));
-  actionTranslateHor->setMenuText(tr("&Horizontal"));
-  actionTranslateVert->setMenuText(tr("&Vertical"));
-  actionSetAscValues->setMenuText(tr("Ro&w Numbers"));
-  actionSetAscValues->setToolTip(tr("Fill selected columns with row numbers"));
-  actionSetRandomValues->setMenuText(tr("&Random Values"));
-  actionSetRandomValues->setToolTip(tr("Fill selected columns with random numbers"));
-  actionSetXCol->setMenuText(tr("&X"));
-  actionSetXCol->setToolTip(tr("Set column as X"));
-  actionSetYCol->setMenuText(tr("&Y"));
-  actionSetYCol->setToolTip(tr("Set column as Y"));
-  actionSetZCol->setMenuText(tr("&Z"));
-  actionSetZCol->setToolTip(tr("Set column as Z"));
-  actionSetXErrCol->setMenuText(tr("X E&rror"));
-  actionSetYErrCol->setMenuText(tr("Y &Error"));
-  actionSetYErrCol->setToolTip(tr("Set as Y Error Bars"));
-  actionSetLabelCol->setMenuText(tr("&Label"));
-  actionSetLabelCol->setToolTip(tr("Set as Labels"));
-  actionDisregardCol->setMenuText(tr("&Disregard"));
-  actionDisregardCol->setToolTip(tr("Disregard Columns"));
-  actionReadOnlyCol->setMenuText(tr("&Read Only"));
-
-  actionBoxPlot->setMenuText(tr("&Box Plot"));
-  actionBoxPlot->setToolTip(tr("Box and whiskers plot"));
-
-  actionMultiPeakGauss->setMenuText(tr("&Gaussian..."));
-  actionMultiPeakLorentz->setMenuText(tr("&Lorentzian..."));
-  actionHomePage->setMenuText(tr("&Mantid Homepage")); // Mantid change
-  //actionCheckUpdates->setMenuText(tr("Search for &Updates")); //Mantid change - commented out
-  //actionHelpForums->setText(tr("Visit QtiPlot &Forums"));
-  actionHelpBugReports->setText(tr("Report a &Bug"));
-  //actionDownloadManual->setMenuText(tr("Download &Manual"));//Mantid change - commented out
-  //actionTranslations->setMenuText(tr("&Translations"));//Mantid change - commented out
-  //actionDonate->setMenuText(tr("Make a &Donation"));
-  //actionTechnicalSupport->setMenuText(tr("Technical &Support"));
-
-  //#ifdef SCRIPTING_DIALOG
-  //	actionScriptingLang->setMenuText(tr("Scripting &language"));
-  //#endif
-
-  actionNoteExecute->setMenuText(tr("E&xecute"));
-  actionNoteExecute->setShortcut(tr("Ctrl+J"));
-
-  actionNoteExecuteAll->setMenuText(tr("Execute &All"));
-  actionNoteExecuteAll->setShortcut(tr("Ctrl+Shift+J"));
-
-  actionNoteEvaluate->setMenuText(tr("&Evaluate Expression"));
-  actionNoteEvaluate->setShortcut(tr("Ctrl+Return"));
-
-  btnPointer->setMenuText(tr("Disable &tools"));
-  btnPointer->setToolTip( tr( "Pointer" ) );
-
-  btnZoomIn->setMenuText(tr("&Zoom In"));
-  btnZoomIn->setShortcut(tr("Ctrl++"));
-  btnZoomIn->setToolTip(tr("Zoom In"));
-
-  btnZoomOut->setMenuText(tr("Zoom &Out"));
-  btnZoomOut->setShortcut(tr("Ctrl+-"));
-  btnZoomOut->setToolTip(tr("Zoom Out"));
-
-  actionMagnify->setMenuText(tr("Zoom &In/Out and Drag Canvas"));
-  actionMagnify->setToolTip(tr("Zoom In (Shift++) or Out (-) and Drag Canvas"));
-
-  btnCursor->setMenuText(tr("&Data Reader"));
-  btnCursor->setShortcut(tr("CTRL+D"));
-  btnCursor->setToolTip(tr("Data reader"));
-
-  btnSelect->setMenuText(tr("&Select Data Range"));
-  btnSelect->setShortcut(tr("ALT+S"));
-  btnSelect->setToolTip(tr("Select data range"));
-
-  btnPicker->setMenuText(tr("S&creen Reader"));
-  btnPicker->setToolTip(tr("Screen reader"));
-
-  actionDrawPoints->setMenuText(tr("&Draw Data Points"));
-  actionDrawPoints->setToolTip(tr("Draw Data Points"));
-
-  btnMovePoints->setMenuText(tr("&Move Data Points..."));
-  btnMovePoints->setShortcut(tr("Ctrl+ALT+M"));
-  btnMovePoints->setToolTip(tr("Move data points"));
-
-  btnRemovePoints->setMenuText(tr("Remove &Bad Data Points..."));
-  btnRemovePoints->setShortcut(tr("Alt+B"));
-  btnRemovePoints->setToolTip(tr("Remove data points"));
-
-  actionAddText->setMenuText(tr("Add &Text"));
-  actionAddText->setToolTip(tr("Add Text"));
-  actionAddText->setShortcut(tr("ALT+T"));
-
-  btnArrow->setMenuText(tr("Draw &Arrow"));
-  btnArrow->setShortcut(tr("CTRL+ALT+A"));
-  btnArrow->setToolTip(tr("Draw arrow"));
-
-  btnLine->setMenuText(tr("Draw &Line"));
-  btnLine->setShortcut(tr("CTRL+ALT+L"));
-  btnLine->setToolTip(tr("Draw line"));
-
-  // FIXME: is setText necessary for action groups?
-  //	coord->setText( tr( "Coordinates" ) );
-  //	coord->setMenuText( tr( "&Coord" ) );
-  //  coord->setStatusTip( tr( "Coordinates" ) );
-  Box->setText( tr( "Box" ) );
-  Box->setMenuText( tr( "Box" ) );
-  Box->setToolTip( tr( "Box" ) );
-  Box->setStatusTip( tr( "Box" ) );
-  Frame->setText( tr( "Frame" ) );
-  Frame->setMenuText( tr( "&Frame" ) );
-  Frame->setToolTip( tr( "Frame" ) );
-  Frame->setStatusTip( tr( "Frame" ) );
-  None->setText( tr( "No Axes" ) );
-  None->setMenuText( tr( "No Axes" ) );
-  None->setToolTip( tr( "No axes" ) );
-  None->setStatusTip( tr( "No axes" ) );
-
-  front->setToolTip( tr( "Front grid" ) );
-  back->setToolTip( tr( "Back grid" ) );
-  right->setToolTip( tr( "Right grid" ) );
-  left->setToolTip( tr( "Left grid" ) );
-  ceil->setToolTip( tr( "Ceiling grid" ) );
-  floor->setToolTip( tr( "Floor grid" ) );
-
-  wireframe->setText( tr( "Wireframe" ) );
-  wireframe->setMenuText( tr( "Wireframe" ) );
-  wireframe->setToolTip( tr( "Wireframe" ) );
-  wireframe->setStatusTip( tr( "Wireframe" ) );
-  hiddenline->setText( tr( "Hidden Line" ) );
-  hiddenline->setMenuText( tr( "Hidden Line" ) );
-  hiddenline->setToolTip( tr( "Hidden line" ) );
-  hiddenline->setStatusTip( tr( "Hidden line" ) );
-  polygon->setText( tr( "Polygon Only" ) );
-  polygon->setMenuText( tr( "Polygon Only" ) );
-  polygon->setToolTip( tr( "Polygon only" ) );
-  polygon->setStatusTip( tr( "Polygon only" ) );
-  filledmesh->setText( tr( "Mesh & Filled Polygons" ) );
-  filledmesh->setMenuText( tr( "Mesh & Filled Polygons" ) );
-  filledmesh->setToolTip( tr( "Mesh & filled Polygons" ) );
-  filledmesh->setStatusTip( tr( "Mesh & filled Polygons" ) );
-  pointstyle->setText( tr( "Dots" ) );
-  pointstyle->setMenuText( tr( "Dots" ) );
-  pointstyle->setToolTip( tr( "Dots" ) );
-  pointstyle->setStatusTip( tr( "Dots" ) );
-  barstyle->setText( tr( "Bars" ) );
-  barstyle->setMenuText( tr( "Bars" ) );
-  barstyle->setToolTip( tr( "Bars" ) );
-  barstyle->setStatusTip( tr( "Bars" ) );
-  conestyle->setText( tr( "Cones" ) );
-  conestyle->setMenuText( tr( "Cones" ) );
-  conestyle->setToolTip( tr( "Cones" ) );
-  conestyle->setStatusTip( tr( "Cones" ) );
-  crossHairStyle->setText( tr( "Crosshairs" ) );
-  crossHairStyle->setMenuText( tr( "Crosshairs" ) );
-  crossHairStyle->setToolTip( tr( "Crosshairs" ) );
-  crossHairStyle->setStatusTip( tr( "Crosshairs" ) );
-
-  //floorstyle->setText( tr( "Floor Style" ) );
-  //floorstyle->setMenuText( tr( "Floor Style" ) );
-  //floorstyle->setStatusTip( tr( "Floor Style" ) );
-  floordata->setText( tr( "Floor Data Projection" ) );
-  floordata->setMenuText( tr( "Floor Data Projection" ) );
-  floordata->setToolTip( tr( "Floor data projection" ) );
-  floordata->setStatusTip( tr( "Floor data projection" ) );
-  flooriso->setText( tr( "Floor Isolines" ) );
-  flooriso->setMenuText( tr( "Floor Isolines" ) );
-  flooriso->setToolTip( tr( "Floor isolines" ) );
-  flooriso->setStatusTip( tr( "Floor isolines" ) );
-  floornone->setText( tr( "Empty Floor" ) );
-  floornone->setMenuText( tr( "Empty Floor" ) );
-  floornone->setToolTip( tr( "Empty floor" ) );
-  floornone->setStatusTip( tr( "Empty floor" ) );
-
-  actionAnimate->setText( tr( "Animation" ) );
-  actionAnimate->setMenuText( tr( "Animation" ) );
-  actionAnimate->setToolTip( tr( "Animation" ) );
-  actionAnimate->setStatusTip( tr( "Animation" ) );
-
-  actionPerspective->setText( tr( "Enable perspective" ) );
-  actionPerspective->setMenuText( tr( "Enable perspective" ) );
-  actionPerspective->setToolTip( tr( "Enable perspective" ) );
-  actionPerspective->setStatusTip( tr( "Enable perspective" ) );
-
-  actionResetRotation->setText( tr( "Reset rotation" ) );
-  actionResetRotation->setMenuText( tr( "Reset rotation" ) );
-  actionResetRotation->setToolTip( tr( "Reset rotation" ) );
-  actionResetRotation->setStatusTip( tr( "Reset rotation" ) );
-
-  actionFitFrame->setText( tr( "Fit frame to window" ) );
-  actionFitFrame->setMenuText( tr( "Fit frame to window" ) );
-  actionFitFrame->setToolTip( tr( "Fit frame to window" ) );
-  actionFitFrame->setStatusTip( tr( "Fit frame to window" ) );
-
-
-}
-
-Graph3D * ApplicationWindow::openMatrixPlot3D(const QString& caption, const QString& matrix_name,
-    double xl,double xr,double yl,double yr,double zl,double zr)
-{
-  QString name = matrix_name;
-  name.remove("matrix<", true);
-  name.remove(">");
-  Matrix* m = matrix(name);
-  if (!m)
-    return 0;
-
-  Graph3D *plot = new Graph3D("", this, 0, 0);
-  plot->setWindowTitle(caption);
-  plot->setName(caption);
-  plot->addMatrixData(m, xl, xr, yl, yr, zl, zr);
-  plot->update();
-
-  initPlot3D(plot);
-  return plot;
-}
-
-Graph3D * ApplicationWindow::plot3DMatrix(Matrix *m, int style)
-{
-  if (!m) {
-    //Mantid
-    Graph3D *plot = mantidUI->plot3DMatrix(style);
-    if (plot) return plot;
-    m = (Matrix*)activeWindow(MatrixWindow);
-    if (!m)
-      return 0;
-  }
-
-  QApplication::setOverrideCursor(Qt::WaitCursor);
-  QString label = generateUniqueName(tr("Graph"));
-
-  Graph3D *plot = new Graph3D("", this, 0);
-  plot->addMatrixData(m);
-  plot->customPlotStyle(style);
-  customPlot3D(plot);
-  plot->update();
-
-  plot->resize(500, 400);
-  plot->setWindowTitle(label);
-  plot->setName(label);
-  initPlot3D(plot);
-
-  emit modified();
-  QApplication::restoreOverrideCursor();
-  return plot;
-}
-
-MultiLayer* ApplicationWindow::plotGrayScale(Matrix *m)
-{
-  if (!m) {
-    //Mantid
-    MultiLayer* plot = mantidUI->plotSpectrogram(Graph::GrayScale);
-    if (plot) return plot;
-    m = (Matrix*)activeWindow(MatrixWindow);
-    if (!m)
-      return 0;
-  }
-
-  return plotSpectrogram(m, Graph::GrayScale);
-}
-
-MultiLayer* ApplicationWindow::plotContour(Matrix *m)
-{
-  if (!m) {
-    //Mantid
-    MultiLayer* plot = mantidUI->plotSpectrogram(Graph::Contour);
-    if (plot) return plot;
-    m = (Matrix*)activeWindow(MatrixWindow);
-    if (!m)
-      return 0;
-  }
-
-  return plotSpectrogram(m, Graph::Contour);
-}
-
-MultiLayer* ApplicationWindow::plotColorMap(Matrix *m)
-{
-  if (!m) {
-    //Mantid
-    MultiLayer* plot = mantidUI->plotSpectrogram(Graph::ColorMap);
-    if (plot) return plot;
-    m = (Matrix*)activeWindow(MatrixWindow);
-    if (!m)
-      return 0;
-  }
-
-  return plotSpectrogram(m, Graph::ColorMap);
-}
-
-MultiLayer* ApplicationWindow::plotNoContourColorMap(Matrix *m)
-{
-  MultiLayer* ml = NULL;
-  if( !m )
-  {
-    m = qobject_cast<Matrix*>(activeWindow(MatrixWindow));
-  }
-  if( m )
-  {
-    ml = plotSpectrogram(m, Graph::ColorMap);
-  }
-  else
-  {
-    ml =  mantidUI->plotSpectrogram(Graph::ColorMap);
-  }
-  if( !ml ) 
-  {
-    QApplication::restoreOverrideCursor();
-    return 0;
-  }
-
-  Spectrogram *spgrm = dynamic_cast<Spectrogram*>(ml->activeGraph()->plotItem(0));
-  if( spgrm )
-  {
-    //1 = ImageMode
-    spgrm->setDisplayMode(QwtPlotSpectrogram::ImageMode, true);
-    spgrm->setDisplayMode(QwtPlotSpectrogram::ContourMode, false);
-  }
-  return ml;
-}
-
-MultiLayer* ApplicationWindow::plotImage(Matrix *m)
-{
-  MultiLayer *g = NULL;
-  Graph *plot = NULL;
-  if( !m )
-  {
-    m = qobject_cast<Matrix*>(activeWindow(MatrixWindow));
-  }
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-  if( m )
-  {
-    g = multilayerPlot(generateUniqueName(tr("Graph")));
-    plot = g->activeGraph();
-    setPreferences(plot);
-
-    Spectrogram *s = plot->plotSpectrogram(m, Graph::GrayScale);
-    if( !s ) 
-    {
-      QApplication::restoreOverrideCursor();
-      return 0;
-    }
-    s->setAxis(QwtPlot::xTop, QwtPlot::yLeft);
-    plot->setScale(QwtPlot::xTop, QMIN(m->xStart(), m->xEnd()), QMAX(m->xStart(), m->xEnd()));
-    plot->setScale(QwtPlot::yLeft, QMIN(m->yStart(), m->yEnd()), QMAX(m->yStart(), m->yEnd()),
-        0.0, 5, 5, GraphOptions::Linear, true);
-  }
-  else
-  {
-    g =  mantidUI->plotSpectrogram(Graph::GrayScale);
-    if( !g ) 
-    {
-      QApplication::restoreOverrideCursor();
-      return 0;
-    }
-    plot = g->activeGraph();
-    setPreferences(plot);
-    if( plot->plotItem(0) )plot->plotItem(0)->setAxis(QwtPlot::xTop, QwtPlot::yLeft);
-  }
-
-  plot->enableAxis(QwtPlot::xTop, true);
-
-  plot->enableAxis(QwtPlot::xBottom, false);
-  plot->enableAxis(QwtPlot::yRight, false);
-  plot->setAxisTitle(QwtPlot::yLeft, QString::null);
-  plot->setAxisTitle(QwtPlot::xTop, QString::null);
-  plot->setTitle(QString::null);
-
-  emit modified();
-  QApplication::restoreOverrideCursor();
-  return g;
-}
-
-MultiLayer* ApplicationWindow::plotSpectrogram(Matrix *m, Graph::CurveType type)
-{
-  if (type == Graph::ImagePlot)
-    return plotImage(m);
-  else if (type == Graph::Histogram)
-    return plotHistogram(m);
-
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-  MultiLayer* g = multilayerPlot(generateUniqueName(tr("Graph")));
-  Graph* plot = g->activeGraph();
-  setPreferences(plot);
-
-  plot->plotSpectrogram(m, type);
-
-  plot->setAutoScale();//Mantid
-
-  QApplication::restoreOverrideCursor();
-  return g;
-}
-
-ApplicationWindow* ApplicationWindow::importOPJ(const QString& filename, bool factorySettings, bool newProject)
-{
-  if (filename.endsWith(".opj", Qt::CaseInsensitive) || filename.endsWith(".ogg", Qt::CaseInsensitive))
-  {
-    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-    ApplicationWindow *app = this;
-    if (newProject)
-      app = new ApplicationWindow(factorySettings);
-
-    app->setWindowTitle("MantidPlot - " + filename);//Mantid
-    app->restoreApplicationGeometry();
-    app->projectname = filename;
-    app->recentProjects.remove(filename);
-    app->recentProjects.push_front(filename);
-    app->updateRecentProjectsList();
-
-    ImportOPJ(app, filename);
-
-    QApplication::restoreOverrideCursor();
-    return app;
-  }
-  else if (filename.endsWith(".ogm", Qt::CaseInsensitive) || filename.endsWith(".ogw", Qt::CaseInsensitive))
-  {
-    ImportOPJ(this, filename);
-    recentProjects.remove(filename);
-    recentProjects.push_front(filename);
-    updateRecentProjectsList();
-    return this;
-  }
-  return 0;
-}
-
-void ApplicationWindow::deleteFitTables()
-{
-  QList<QWidget*>* mLst = new QList<QWidget*>();
-  QList<MdiSubWindow *> windows = windowsList();
-  foreach(MdiSubWindow *w, windows){
-    if (w->isA("MultiLayer"))
-      mLst->append(w);
-  }
-
-  foreach(QWidget *ml, *mLst){
-    if (ml->isA("MultiLayer")){
-      QList<Graph *> layers = ((MultiLayer*)ml)->layersList();
-      foreach(Graph *g, layers){
-        QList<QwtPlotCurve *> curves = g->fitCurvesList();
-        foreach(QwtPlotCurve *c, curves){
-          if (((PlotCurve *)c)->type() != Graph::Function){
-            Table *t = ((DataCurve *)c)->table();
-            if (!t)
-              continue;
-
-            t->askOnCloseEvent(false);
-            t->close();
-          }
-        }
-      }
-    }
-  }
-  delete mLst;
-}
-
-QList<MdiSubWindow *> ApplicationWindow::windowsList()
-{
-  QList<MdiSubWindow *> lst;
-
-  Folder *f = projectFolder();
-  while (f){
-    QList<MdiSubWindow *> folderWindows = f->windowsList();
-    foreach(MdiSubWindow *w, folderWindows)
-    lst << w;
-    f = f->folderBelow();
-  }
-  return lst;
-}
-
-void ApplicationWindow::updateRecentProjectsList()
-{
-  if (recentProjects.isEmpty())
-    return;
-
-  while ((int)recentProjects.size() > MaxRecentProjects)
-    recentProjects.pop_back();
-
-  recent->clear();
-
-  for (int i = 0; i<(int)recentProjects.size(); i++ )
-    recent->insertItem("&" + QString::number(i+1) + " " + recentProjects[i]);
-}
-
-void ApplicationWindow::translateCurveHor()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty())
-  {
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  Graph* g = (Graph*)plot->activeGraph();
-  if (!g)
-    return;
-
-  if (g->isPiePlot())
-  {
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("This functionality is not available for pie plots!"));
-
-    btnPointer->setChecked(true);
-    return;
-  }
-  else if (g->validCurvesDataSize())
-  {
-    btnPointer->setChecked(true);
-    g->setActiveTool(new TranslateCurveTool(g, this, TranslateCurveTool::Horizontal, info, SLOT(setText(const QString&))));
-    displayBar->show();
-  }
-}
-
-void ApplicationWindow::translateCurveVert()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  Graph* g = (Graph*)plot->activeGraph();
-  if (!g)
-    return;
-
-  if (g->isPiePlot()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("This functionality is not available for pie plots!"));
-
-    btnPointer->setChecked(true);
-    return;
-  } else if (g->validCurvesDataSize()) {
-    btnPointer->setChecked(true);
-    g->setActiveTool(new TranslateCurveTool(g, this, TranslateCurveTool::Vertical, info, SLOT(setText(const QString&))));
-    displayBar->show();
-  }
-}
-
-void ApplicationWindow::setReadOnlyCol()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-  QStringList list = t->selectedColumns();
-  for (int i=0; i<(int) list.count(); i++)
-    t->setReadOnlyColumn(t->colIndex(list[i]), actionReadOnlyCol->isChecked());
-}
-
-void ApplicationWindow::setReadOnlyColumns()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-  QStringList list = t->selectedColumns();
-  for (int i=0; i<(int) list.count(); i++)
-    t->setReadOnlyColumn(t->colIndex(list[i]));
-}
-
-void ApplicationWindow::setReadWriteColumns()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-  QStringList list = t->selectedColumns();
-  for (int i=0; i<(int) list.count(); i++)
-    t->setReadOnlyColumn(t->colIndex(list[i]), false);
-}
-
-void ApplicationWindow::setAscValues()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  t->setAscValues();
-}
-
-void ApplicationWindow::setRandomValues()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  t->setRandomValues();
-}
-
-void ApplicationWindow::setXErrCol()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  t->setPlotDesignation(Table::xErr);
-}
-
-void ApplicationWindow::setYErrCol()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  t->setPlotDesignation(Table::yErr);
-}
-
-void ApplicationWindow::setXCol()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  t->setPlotDesignation(Table::X);
-}
-
-void ApplicationWindow::setYCol()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  t->setPlotDesignation(Table::Y);
-}
-
-void ApplicationWindow::setZCol()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  t->setPlotDesignation(Table::Z);
-}
-
-void ApplicationWindow::setLabelCol()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  t->setPlotDesignation(Table::Label);
-}
-
-void ApplicationWindow::disregardCol()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  t->setPlotDesignation(Table::None);
-}
-
-void ApplicationWindow::fitMultiPeakGauss()
-{
-  fitMultiPeak((int)MultiPeakFit::Gauss);
-}
-
-void ApplicationWindow::fitMultiPeakLorentz()
-{
-  fitMultiPeak((int)MultiPeakFit::Lorentz);
-}
-
-void ApplicationWindow::fitMultiPeak(int profile)
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-  if (plot->isEmpty()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    btnPointer->setChecked(true);
-    return;
-  }
-
-  Graph* g = (Graph*)plot->activeGraph();
-  if (!g || !g->validCurvesDataSize())
-    return;
-
-  if (g->isPiePlot()){
-    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
-        tr("This functionality is not available for pie plots!"));
-    return;
-  } else {
-    bool ok;
-    int peaks = QInputDialog::getInteger(tr("MantidPlot - Enter the number of peaks"),//Mantid
-        tr("Peaks"), 2, 2, 1000000, 1, &ok, this);
-    if (ok && peaks){
-      g->setActiveTool(new MultiPeakFitTool(g, this, (MultiPeakFit::PeakProfile)profile, peaks, info, SLOT(setText(const QString&))));
-      displayBar->show();
-    }
-  }
-}
-
-//void ApplicationWindow::showSupportPage()
-//{
-//	QDesktopServices::openUrl(QUrl("http://soft.proindependent.com/contracts.html"));
-//}
-
-
-//void ApplicationWindow::showDonationsPage()
-//{
-//	QDesktopServices::openUrl(QUrl("http://soft.proindependent.com/why_donate.html"));
-//}
-
-//void ApplicationWindow::downloadManual()
-//{
-//	QDesktopServices::openUrl(QUrl("http://soft.proindependent.com/manuals.html"));
-//}
-//
-//void ApplicationWindow::downloadTranslation()
-//{
-//	QDesktopServices::openUrl(QUrl("http://soft.proindependent.com/translations.html"));
-//}
-
-void ApplicationWindow::showHomePage()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org"));
-}
-void ApplicationWindow::showMantidConcepts()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Category:Concepts"));
-}
-void ApplicationWindow::showalgorithmDescriptions()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Category:Algorithms"));
-}
-/*
- Show mantidplot help page
- */
-void ApplicationWindow::showmantidplotHelp()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/MantidPlot:_Help"));
-}
-
-//
-//void ApplicationWindow::showForums()
-//{
-//	QDesktopServices::openUrl(QUrl("https://developer.berlios.de/forum/?group_id=6626"));
-//}
-
-void ApplicationWindow::showBugTracker()
-{
-  QDesktopServices::openUrl(QUrl("mailto:mantid-help@mantidproject.org"));
-}
-
-void ApplicationWindow::parseCommandLineArguments(const QStringList& args)
-{
-  int num_args = args.count();
-  if(num_args == 0){
-    initWindow();
-    savedProject();
-    return;
-  }
-
-  QString str;
-  bool exec = false;
-  bool quit = false;
-  bool default_settings = false;
-  foreach(str, args){
-    if( (str == "-a" || str == "--about") ||
-        (str == "-m" || str == "--manual") )
-    {
-      QMessageBox::critical(this, tr("MantidPlot - Error"),//Mantid
-          tr("<b> %1 </b>: This command line option must be used without other arguments!").arg(str));
-    }
-    else if( (str == "-d" || str == "--default-settings"))
-    {
-      default_settings = true;
-    }
-    else if (str == "-v" || str == "--version")
-    {
-#ifdef Q_OS_WIN
-      hide();
-      about();
-#else
-      std::wcout << versionString().toStdWString();
-#endif
-      exit(0);
-    }
-    else if (str == "-r" || str == "--revision") // Print and return subversion revision number
-    {
-      hide();
-      QString version(MANTIDPLOT_RELEASE_VERSION);
-      version.remove(0,4);
-      std::cout << version.toStdString() << std::endl;
-      exit(version.toInt());
-    }
-    else if (str == "-h" || str == "--help")
-    {
-      QString s = "\n" + tr("Usage") + ": ";
-      s += "qtiplot [" + tr("options") + "] [" + tr("file") + "_" + tr("name") + "]\n\n";
-      s += tr("Valid options are") + ":\n";
-      s += "-a " + tr("or") + " --about: " + tr("show about dialog and exit") + "\n";
-      s += "-d " + tr("or") + " --default-settings: " + tr("start MantidPlot with the default settings") + "\n";//Mantid
-      s += "-h " + tr("or") + " --help: " + tr("show command line options") + "\n";
-      s += "-l=XX " + tr("or") + " --lang=XX: " + tr("start MantidPlot in language") + " XX ('en', 'fr', 'de', ...)\n";//Mantid
-      s += "-m " + tr("or") + " --manual: " + tr("show MantidPlot manual in a standalone window") + "\n";
-      s += "-v " + tr("or") + " --version: " + tr("print MantidPlot version and release date") + "\n";
-      s += "-x " + tr("or") + " --execute: " + tr("execute the script file given as argument") + "\n\n";
-      s += "'" + tr("file") + "_" + tr("name") + "' " + tr("can be any .qti, qti.gz, .opj, .ogm, .ogw, .ogg, .py or ASCII file") + "\n";
-#ifdef Q_OS_WIN
-      hide();
-      QMessageBox::information(this, tr("MantidPlot") + " - " + tr("Help"), s);//Mantid
-#else
-      std::wcout << s.toStdWString();
-#endif
-      exit(0);
-    }
-    else if (str.startsWith("--lang=") || str.startsWith("-l="))
-    {
-      QString locale = str.mid(str.find('=')+1);
-      if (locales.contains(locale))
-        switchToLanguage(locale);
-
-      if (!locales.contains(locale))
-        QMessageBox::critical(this, tr("MantidPlot - Error"),//Mantid
-            tr("<b> %1 </b>: Wrong locale option or no translation available!").arg(locale));
-    }
-    else if (str.endsWith("--execute") || str.endsWith("-x"))
-    {
-      exec = true;
-      quit = false;
-    }
-    else if (str.endsWith("--execandquit") || str.endsWith("-xq"))
-    {
-      exec = true;
-      quit = true;
-    }
-    else if (str.startsWith("-") || str.startsWith("--"))
-    {
-      QMessageBox::critical(this, tr("MantidPlot - Error"),//Mantid
-          tr("<b> %1 </b> unknown command line option!").arg(str) + "\n" + tr("Type %1 to see the list of the valid options.").arg("'MantidPlot -h'"));
-    }
-  }
-
-  QString file_name = args[num_args-1]; // last argument
-  if(file_name.startsWith("-")){// no file name given
-    initWindow();
-    savedProject();
-    return;
-  }
-
-  if (!file_name.isEmpty()){
-    QFileInfo fi(file_name);
-    if (fi.isDir()){
-      QMessageBox::critical(this, tr("MantidPlot - Error opening file"),//Mantid
-          tr("<b>%1</b> is a directory, please specify a file name!").arg(file_name));
-      return;
-    } else if (!fi.exists()) {
-      QMessageBox::critical(this, tr("MantidPlot - Error opening file"),//Mantid
-          tr("The file: <b>%1</b> doesn't exist!").arg(file_name));
-      return;
-    } else if (!fi.isReadable()) {
-      QMessageBox::critical(this, tr("MantidPlot - Error opening file"),//Mantid
-          tr("You don't have the permission to open this file: <b>%1</b>").arg(file_name));
-      return;
-    }
-
-    workingDir = fi.dirPath(true);
-    saveSettings();//the recent projects must be saved
-
-    if (exec)
-      loadScript(file_name, exec, quit);
-    else
-    {
-      saved=true;
-      open(file_name, default_settings, false);
-    }
-  }
-}
-
-void ApplicationWindow::createLanguagesList()
-{
-  locales.clear();
-
-  appTranslator = new QTranslator(this);
-  qtTranslator = new QTranslator(this);
-  qApp->installTranslator(appTranslator);
-  qApp->installTranslator(qtTranslator);
-
-  QString qmPath = d_translations_folder;
-  QDir dir(qmPath);
-  QStringList fileNames = dir.entryList("qtiplot_*.qm");
-  for (int i=0; i < (int)fileNames.size(); i++)
-  {
-    QString locale = fileNames[i];
-    locale = locale.mid(locale.find('_')+1);
-    locale.truncate(locale.find('.'));
-    locales.push_back(locale);
-  }
-  locales.push_back("en");
-  locales.sort();
-
-  if (appLanguage != "en")
-  {
-    appTranslator->load("qtiplot_" + appLanguage, qmPath);
-    qtTranslator->load("qt_" + appLanguage, qmPath+"/qt");
-  }
-}
-
-void ApplicationWindow::switchToLanguage(int param)
-{
-  if (param < (int)locales.size())
-    switchToLanguage(locales[param]);
-}
-
-void ApplicationWindow::switchToLanguage(const QString& locale)
-{
-  if (!locales.contains(locale) || appLanguage == locale)
-    return;
-
-  appLanguage = locale;
-  if (locale == "en")
-  {
-    qApp->removeTranslator(appTranslator);
-    qApp->removeTranslator(qtTranslator);
-    delete appTranslator;
-    delete qtTranslator;
-    appTranslator = new QTranslator(this);
-    qtTranslator = new QTranslator(this);
-    qApp->installTranslator(appTranslator);
-    qApp->installTranslator(qtTranslator);
-  }
-  else
-  {
-    QString qmPath = d_translations_folder;
-    appTranslator->load("qtiplot_" + locale, qmPath);
-    qtTranslator->load("qt_" + locale, qmPath+"/qt");
-  }
-  insertTranslatedStrings();
-}
-
-QStringList ApplicationWindow::matrixNames()
-{
-  QStringList names;
-  Folder *f = projectFolder();
-  while (f){
-    QList<MdiSubWindow *> folderWindows = f->windowsList();
-    foreach(MdiSubWindow *w, folderWindows){
-      if (w->isA("Matrix"))
-        names << w->objectName();
-    }
-    f = f->folderBelow();
-  }
-  return names;
-}
-QStringList ApplicationWindow::mantidmatrixNames()
-{
-  QStringList names;
-  Folder *f = projectFolder();
-  while (f){
-    QList<MdiSubWindow *> folderWindows = f->windowsList();
-    foreach(MdiSubWindow *w, folderWindows){
-      if (w->isA("MantidMatrix"))
-        names << w->objectName();
-    }
-    f = f->folderBelow();
-  }
-  return names;
-}
-
-bool ApplicationWindow::alreadyUsedName(const QString& label)
-{
-  Folder *f = projectFolder();
-  while (f){
-    QList<MdiSubWindow *> folderWindows = f->windowsList();
-    foreach(MdiSubWindow *w, folderWindows){
-      if (w->objectName() == label)
-        return true;
-    }
-    f = f->folderBelow();
-  }
-  return false;
-}
-
-bool ApplicationWindow::projectHas2DPlots()
-{
-  Folder *f = projectFolder();
-  while (f){
-    QList<MdiSubWindow *> folderWindows = f->windowsList();
-    foreach(MdiSubWindow *w, folderWindows){
-      if (w->isA("MultiLayer"))
-        return true;
-    }
-    f = f->folderBelow();
-  }
-  return false;
-}
-
-void ApplicationWindow::appendProject()
-{
-  OpenProjectDialog *open_dialog = new OpenProjectDialog(this, false);
-  open_dialog->setDirectory(workingDir);
-  open_dialog->setExtensionWidget(0);
-  if (open_dialog->exec() != QDialog::Accepted || open_dialog->selectedFiles().isEmpty())
-    return;
-  workingDir = open_dialog->directory().path();
-  appendProject(open_dialog->selectedFiles()[0]);
-}
-
-Folder* ApplicationWindow::appendProject(const QString& fn, Folder* parentFolder)
-{
-  if (fn.isEmpty())
-    return 0;
-
-  QFileInfo fi(fn);
-  workingDir = fi.dirPath(true);
-
-  if (fn.contains(".qti") || fn.contains(".opj", Qt::CaseInsensitive) ||
-      fn.contains(".ogm", Qt::CaseInsensitive) || fn.contains(".ogw", Qt::CaseInsensitive) ||
-      fn.contains(".ogg", Qt::CaseInsensitive)){
-    QFileInfo f(fn);
-    if (!f.exists ()){
-      QMessageBox::critical(this, tr("MantidPlot - File opening error"),//Mantid
-          tr("The file: <b>%1</b> doesn't exist!").arg(fn));
-      return 0;
-    }
-  }else{
-    QMessageBox::critical(this,tr("MantidPlot - File opening error"),//Mantid
-        tr("The file: <b>%1</b> is not a MantidPlot or Origin project file!").arg(fn));
-    return 0;
-  }
-
-  recentProjects.remove(fn);
-  recentProjects.push_front(fn);
-  updateRecentProjectsList();
-
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-  QString fname = fn;
-  if (fn.contains(".qti.gz")){//decompress using zlib
-    file_uncompress((char *)fname.ascii());
-    fname.remove(".gz");
-  }
-
-  Folder *cf = current_folder;
-  if (parentFolder)
-    changeFolder(parentFolder, true);
-
-  FolderListItem *item = (FolderListItem *)current_folder->folderListItem();
-  folders->blockSignals (true);
-  blockSignals (true);
-
-  QString baseName = fi.baseName();
-  QStringList lst = current_folder->subfolders();
-  int n = lst.count(baseName);
-  if (n){//avoid identical subfolder names
-    while (lst.count(baseName + QString::number(n)))
-      n++;
-    baseName += QString::number(n);
-  }
-
-  Folder *new_folder;
-  if (parentFolder)
-    new_folder = new Folder(parentFolder, baseName);
-  else
-    new_folder = new Folder(current_folder, baseName);
-
-  current_folder = new_folder;
-  FolderListItem *fli = new FolderListItem(item, current_folder);
-  current_folder->setFolderListItem(fli);
-
-  if (fn.contains(".opj", Qt::CaseInsensitive) || fn.contains(".ogm", Qt::CaseInsensitive) ||
-      fn.contains(".ogw", Qt::CaseInsensitive) || fn.contains(".ogg", Qt::CaseInsensitive))
-    ImportOPJ(this, fn);
-  else{
-    QFile f(fname);
-    QTextStream t( &f );
-    t.setEncoding(QTextStream::UnicodeUTF8);
-    f.open(QIODevice::ReadOnly);
-
-    QString s = t.readLine();
-    lst = s.split(QRegExp("\\s"), QString::SkipEmptyParts);
-    QString version = lst[1];
-    lst = version.split(".", QString::SkipEmptyParts);
-    d_file_version =100*(lst[0]).toInt()+10*(lst[1]).toInt()+(lst[2]).toInt();
-
-    t.readLine();
-    if (d_file_version < 73)
-      t.readLine();
-
-    //process tables and matrix information
-    while ( !t.atEnd()){
-      s = t.readLine();
-      lst.clear();
-      if  (s.left(8) == "<folder>"){
-        lst = s.split("\t");
-        Folder *f = new Folder(current_folder, lst[1]);
-        f->setBirthDate(lst[2]);
-        f->setModificationDate(lst[3]);
-        if(lst.count() > 4)
-          if (lst[4] == "current")
-            cf = f;
-
-        FolderListItem *fli = new FolderListItem(current_folder->folderListItem(), f);
-        fli->setText(0, lst[1]);
-        f->setFolderListItem(fli);
-
-        current_folder = f;
-      }else if  (s == "<table>"){
-        while ( s!="</table>" ){
-          s=t.readLine();
-          lst<<s;
-        }
-        lst.pop_back();
-        openTable(this,lst);
-      }else if  (s == "<matrix>"){
-        while ( s != "</matrix>" ){
-          s=t.readLine();
-          lst<<s;
-        }
-        lst.pop_back();
-        openMatrix(this, lst);
-      }else if  (s == "<note>"){
-        for (int i=0; i<3; i++){
-          s = t.readLine();
-          lst << s;
-        }
-        Note* m = openNote(this, lst);
-        QStringList cont;
-        while ( s != "</note>" ){
-          s=t.readLine();
-          cont << s;
-        }
-        cont.pop_back();
-        m->restore(cont);
-      }else if  (s == "</folder>"){
-        Folder *parent = (Folder *)current_folder->parent();
-        if (!parent)
-          current_folder = projectFolder();
-        else
-          current_folder = parent;
-      }
-    }
-    f.close();
-
-    //process the rest
-    f.open(QIODevice::ReadOnly);
-
-    MultiLayer *plot=0;
-    while ( !t.atEnd()){
-      s=t.readLine();
-      if  (s.left(8) == "<folder>"){
-        lst = s.split("\t");
-        current_folder = current_folder->findSubfolder(lst[1]);
-      }else if  (s == "<multiLayer>"){//process multilayers information
-        s=t.readLine();
-        QStringList graph=s.split("\t");
-        QString caption=graph[0];
-        plot = multilayerPlot(caption, 0, graph[2].toInt(), graph[1].toInt());
-        setListViewDate(caption, graph[3]);
-        plot->setBirthDate(graph[3]);
-        plot->blockSignals(true);
-
-        restoreWindowGeometry(this, plot, t.readLine());
-
-        if (d_file_version > 71){
-          QStringList lst=t.readLine().split("\t");
-          plot->setWindowLabel(lst[1]);
-          plot->setCaptionPolicy((MdiSubWindow::CaptionPolicy)lst[2].toInt());
-        }
-
-        if (d_file_version > 83){
-          QStringList lst=t.readLine().split("\t", QString::SkipEmptyParts);
-          plot->setMargins(lst[1].toInt(),lst[2].toInt(),lst[3].toInt(),lst[4].toInt());
-          lst=t.readLine().split("\t", QString::SkipEmptyParts);
-          plot->setSpacing(lst[1].toInt(),lst[2].toInt());
-          lst=t.readLine().split("\t", QString::SkipEmptyParts);
-          plot->setLayerCanvasSize(lst[1].toInt(),lst[2].toInt());
-          lst=t.readLine().split("\t", QString::SkipEmptyParts);
-          plot->setAlignement(lst[1].toInt(),lst[2].toInt());
-        }
-
-        while ( s!="</multiLayer>" ){//open layers
-          s=t.readLine();
-          if (s.left(7)=="<graph>"){
-            lst.clear();
-            while ( s!="</graph>" ){
-              s=t.readLine();
-              lst<<s;
-            }
-            openGraph(this, plot, lst);
-          }
-        }
-        if(plot)
-        { plot->blockSignals(false);
-        }
-      }else if  (s == "<SurfacePlot>"){//process 3D plots information
-        lst.clear();
-        while ( s!="</SurfacePlot>" ){
-          s=t.readLine();
-          lst<<s;
-        }
-        openSurfacePlot(this,lst);
-      }else if  (s == "</folder>"){
-        Folder *parent = (Folder *)current_folder->parent();
-        if (!parent)
-          current_folder = projectFolder();
-        else
-          current_folder = parent;
-      }
-    }
-    f.close();
-  }
-
-  folders->blockSignals (false);
-  //change folder to user defined current folder
-  changeFolder(cf);
-  blockSignals (false);
-  renamedTables = QStringList();
-  QApplication::restoreOverrideCursor();
-  return new_folder;
-}
-
-#ifdef QTIPLOT_DEMO
-void ApplicationWindow::showDemoVersionMessage()
-{
-  saved = true;
-  /**
-	QMessageBox::critical(this, tr("MantidPlot - Demo Version"),//Mantid
-			tr("You are using the demonstration version of Qtiplot.\
-				It is identical with the full version, except that you can't save your work to project files and you can't use it for more than 10 minutes per session.\
-				<br><br>\
-				If you want to have ready-to-use, fully functional binaries, please subscribe for a\
-				<a href=\"http://soft.proindependent.com/individual_contract.html\">single-user binaries maintenance contract</a>.\
-				<br><br>\
-				QtiPlot is free software in the sense of free speech.\
-				If you know how to use it, you can get\
-				<a href=\"http://developer.berlios.de/project/showfiles.php?group_id=6626\">the source code</a>\
-				free of charge.\
-				Nevertheless, you are welcome to\
-				<a href=\"http://soft.proindependent.com/why_donate.html\">make a donation</a>\
-				in order to support the further development of QtiPlot."));
-   */
-}
-#endif
-
-void ApplicationWindow::saveFolder(Folder *folder, const QString& fn, bool compress)
-{
-  QFile f( fn );
-  if (d_backup_files && f.exists())
-  {// make byte-copy of current file so that there's always a copy of the data on disk
-    while (!f.open(QIODevice::ReadOnly)){
-      if (f.isOpen())
-        f.close();
-      int choice = QMessageBox::warning(this, tr("MantidPlot - File backup error"),//Mantid
-          tr("Cannot make a backup copy of <b>%1</b> (to %2).<br>If you ignore this, you run the risk of <b>data loss</b>.").arg(projectname).arg(projectname+"~"),
-          QMessageBox::Retry|QMessageBox::Default, QMessageBox::Abort|QMessageBox::Escape, QMessageBox::Ignore);
-      if (choice == QMessageBox::Abort)
-        return;
-      if (choice == QMessageBox::Ignore)
-        break;
-    }
-
-    if (f.isOpen()){
-      QFile::copy (fn, fn + "~");
-      f.close();
-    }
-  }
-
-  if ( !f.open( QIODevice::WriteOnly ) ){
-    QMessageBox::about(this, tr("MantidPlot - File save error"), tr("The file: <br><b>%1</b> is opened in read-only mode").arg(fn));//Mantid
-    return;
-  }
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-  QList<MdiSubWindow *> lst = folder->windowsList();
-  int windows = 0;
-  QString text;
-  //save all loaded mantid workspace names to project file
-  // call save nexus on each workspace
-  QString aux=mantidUI->saveToString(workingDir.toStdString());
-  text+=aux;
-  //if script window is open save the currently opened script file names to project file
-  if (scriptingWindow)
-  {	//returns the files names of the all the opened script files.
-    QString aux=scriptingWindow->saveToString();
-    text+=aux;
-  }
-  foreach(MdiSubWindow *w, lst){
-    QString aux = w->saveToString(windowGeometryInfo(w));
-    if (w->inherits("Table"))
-      ((Table *)w)->setSpecifications(aux);
-    text += aux;
-    windows++;
-  }
-  int initial_depth = folder->depth();
-  Folder *dir = folder->folderBelow();
-  while (dir && dir->depth() > initial_depth){
-    text += "<folder>\t" + QString(dir->objectName()) + "\t" + dir->birthDate() + "\t" + dir->modificationDate();
-    if (dir == current_folder)
-      text += "\tcurrent\n";
-    else
-      text += "\n";  // FIXME: Having no 5th string here is not a good idea
-    text += "<open>" + QString::number(dir->folderListItem()->isOpen()) + "</open>\n";
-
-    lst = dir->windowsList();
-    foreach(MdiSubWindow *w, lst){
-      QString aux = w->saveToString(windowGeometryInfo(w));
-      if (w->inherits("Table"))
-        ((Table *)w)->setSpecifications(aux);
-      text += aux;
-      windows++;
-    }
-
-    if (!dir->logInfo().isEmpty() )
-      text += "<log>\n" + dir->logInfo() + "</log>\n" ;
-
-    if ( (dir->children()).isEmpty() )
-      text += "</folder>\n";
-
-    int depth = dir->depth();
-    dir = dir->folderBelow();
-    if (dir){
-      int next_dir_depth = dir->depth();
-      if (next_dir_depth < depth){
-        int diff = depth - next_dir_depth;
-        for (int i = 0; i < diff; i++)
-          text += "</folder>\n";
-      }
-    } else {
-      int diff = depth - initial_depth - 1;
-      for (int i = 0; i < diff; i++)
-        text += "</folder>\n";
-    }
-  }
-
-  text += "<open>" + QString::number(folder->folderListItem()->isOpen()) + "</open>\n";
-  if (!folder->logInfo().isEmpty())
-    text += "<log>\n" + folder->logInfo() + "</log>" ;
-
-  text.prepend("<windows>\t"+QString::number(windows)+"\n");
-  text.prepend("<scripting-lang>\t"+QString(scriptingEnv()->name())+"\n");
-  text.prepend("MantidPlot " + QString::number(maj_version)+"."+ QString::number(min_version)+"."+
-      QString::number(patch_version)+" project file\n");
-
-  QTextStream t( &f );
-  t.setEncoding(QTextStream::UnicodeUTF8);
-  t << text;
-  f.close();
-
-  if (compress)
+void ApplicationWindow::loadCustomActions()
+{
+  QString path = customActionsDirPath + "/";
+  QDir dir(path);
+  QStringList lst = dir.entryList(QDir::Files|QDir::NoSymLinks, QDir::Name);
+  for (int i=0; i<lst.count(); i++){
+    QString fileName = path + lst[i];
+    QFile file(fileName);
+    QFileInfo fi(file);
+    if (!file.open(QFile::ReadOnly | QFile::Text))
+      continue;
+
+    QAction *action = new QAction(this);
+    CustomActionHandler handler(action);
+    QXmlSimpleReader reader;
+    reader.setContentHandler(&handler);
+    reader.setErrorHandler(&handler);
+
+    QXmlInputSource xmlInputSource(&file);
+    if (reader.parse(xmlInputSource))
+      addCustomAction(action, handler.parentName());
+  }
+}
+
+QList<QMenu *> ApplicationWindow::customizableMenusList()
+{
+  QList<QMenu *> lst;
+  lst << 	windowsMenu << view << graph << fileMenu << format << edit;
+  lst << help << plot2DMenu << analysisMenu << multiPeakMenu;
+  lst << matrixMenu << plot3DMenu << plotDataMenu ;// scriptingMenu;
+  lst << tableMenu << fillMenu << normMenu << newMenu << exportPlotMenu << smoothMenu;
+  lst << filterMenu << decayMenu;
+  return lst;
+}
+
+//-------------------------------
+// Mantid
+void ApplicationWindow::addUserMenu(const QString & topMenu)
+{
+  if( topMenu.isEmpty() ) return;
+
+  foreach(QMenu* menu, d_user_menus)
   {
-    char w9[]="w9";
-    file_compress((char *)fn.ascii(), "w9");
-  }
-
-  QApplication::restoreOverrideCursor();
-}
-
-void ApplicationWindow::saveAsProject()
-{
-  saveFolderAsProject(current_folder);
-}
-
-void ApplicationWindow::saveFolderAsProject(Folder *f)
-{
-#ifdef QTIPLOT_DEMO
-  showDemoVersionMessage();
-  return;
-#endif
-  QString filter = tr("MantidPlot project")+" (*.qti);;";//Mantid
-  filter += tr("Compressed MantidPlot project")+" (*.qti.gz)";
-
-  QString selectedFilter;
-  QString fn = QFileDialog::getSaveFileName(this, tr("Save project as"), workingDir, filter, &selectedFilter);
-  if ( !fn.isEmpty() ){
-    QFileInfo fi(fn);
-    workingDir = fi.dirPath(true);
-    QString baseName = fi.fileName();
-    if (!baseName.contains("."))
-      fn.append(".qti");
-
-    saveFolder(f, fn, selectedFilter.contains(".gz"));
-  }
-}
-
-void ApplicationWindow::showFolderPopupMenu(Q3ListViewItem *it, const QPoint &p, int)
-{
-  showFolderPopupMenu(it, p, true);
-}
-
-void ApplicationWindow::showFolderPopupMenu(Q3ListViewItem *it, const QPoint &p, bool fromFolders)
-{
-  if (!it || folders->isRenaming())
-    return;
-
-  QMenu cm(this);
-  QMenu window(this);
-  QMenu viewWindowsMenu(this);
-  viewWindowsMenu.setCheckable ( true );
-
-  cm.insertItem(tr("&Find..."), this, SLOT(showFindDialogue()));
-  cm.insertSeparator();
-  cm.insertItem(tr("App&end Project..."), this, SLOT(appendProject()));
-  if (((FolderListItem *)it)->folder()->parent())
-    cm.insertItem(tr("Save &As Project..."), this, SLOT(saveAsProject()));
-  else
-    cm.insertItem(tr("Save Project &As..."), this, SLOT(saveProjectAs()));
-  cm.insertSeparator();
-
-  if (fromFolders && show_windows_policy != HideAll)
-  {
-    cm.insertItem(tr("&Show All Windows"), this, SLOT(showAllFolderWindows()));
-    cm.insertItem(tr("&Hide All Windows"), this, SLOT(hideAllFolderWindows()));
-    cm.insertSeparator();
-  }
-
-  if (((FolderListItem *)it)->folder()->parent())
-  {
-    cm.insertItem(getQPixmap("close_xpm"), tr("&Delete Folder"), this, SLOT(deleteFolder()), Qt::Key_F8);
-    cm.insertItem(tr("&Rename"), this, SLOT(startRenameFolder()), Qt::Key_F2);
-    cm.insertSeparator();
-  }
-
-  if (fromFolders)
-  {
-    window.addAction(actionNewTable);
-    window.addAction(actionNewMatrix);
-    window.addAction(actionNewNote);
-    window.addAction(actionNewGraph);
-    window.addAction(actionNewFunctionPlot);
-    window.addAction(actionNewSurfacePlot);
-    cm.insertItem(tr("New &Window"), &window);
-  }
-
-  cm.insertItem(getQPixmap("newfolder_xpm"), tr("New F&older"), this, SLOT(addFolder()), Qt::Key_F7);
-  cm.insertSeparator();
-
-  QStringList lst;
-  lst << tr("&None") << tr("&Windows in Active Folder") << tr("Windows in &Active Folder && Subfolders");
-  for (int i = 0; i < 3; ++i)
-  {
-    int id = viewWindowsMenu.insertItem(lst[i],this, SLOT( setShowWindowsPolicy( int ) ) );
-    viewWindowsMenu.setItemParameter( id, i );
-    viewWindowsMenu.setItemChecked( id, show_windows_policy == i );
-  }
-  cm.insertItem(tr("&View Windows"), &viewWindowsMenu);
-  cm.insertSeparator();
-  cm.insertItem(tr("&Properties..."), this, SLOT(folderProperties()));
-  cm.exec(p);
-}
-
-void ApplicationWindow::setShowWindowsPolicy(int p)
-{
-  if (show_windows_policy == (ShowWindowsPolicy)p)
-    return;
-
-  show_windows_policy = (ShowWindowsPolicy)p;
-  if (show_windows_policy == HideAll){
-    QList<MdiSubWindow *> windows = windowsList();
-    foreach(MdiSubWindow *w, windows){
-      hiddenWindows->append(w);
-      w->hide();
-      setListView(w->objectName(), tr("Hidden"));
-    }
-  } else
-    showAllFolderWindows();
-}
-
-void ApplicationWindow::showFindDialogue()
-{
-  FindDialog *fd = new FindDialog(this);
-  fd->setAttribute(Qt::WA_DeleteOnClose);
-  fd->exec();
-}
-
-void ApplicationWindow::startRenameFolder()
-{
-  FolderListItem *fi = current_folder->folderListItem();
-  if (!fi)
-    return;
-
-  disconnect(folders, SIGNAL(currentChanged(Q3ListViewItem *)), this, SLOT(folderItemChanged(Q3ListViewItem *)));
-  fi->setRenameEnabled (0, true);
-  fi->startRename (0);
-}
-
-void ApplicationWindow::startRenameFolder(Q3ListViewItem *item)
-{
-  if (!item || item == folders->firstChild())
-    return;
-
-  if (item->listView() == lv && item->rtti() == FolderListItem::RTTI) {
-    disconnect(folders, SIGNAL(currentChanged(Q3ListViewItem *)), this, SLOT(folderItemChanged(Q3ListViewItem *)));
-    current_folder = ((FolderListItem *)item)->folder();
-    FolderListItem *it = current_folder->folderListItem();
-    it->setRenameEnabled (0, true);
-    it->startRename (0);
-  } else {
-    item->setRenameEnabled (0, true);
-    item->startRename (0);
-  }
-}
-
-void ApplicationWindow::renameFolder(Q3ListViewItem *it, int col, const QString &text)
-{
-  Q_UNUSED(col)
-
-		    if (!it)
-		      return;
-
-  Folder *parent = (Folder *)current_folder->parent();
-  if (!parent)//the parent folder is the project folder (it always exists)
-    parent = projectFolder();
-
-  while(text.isEmpty())
-  {
-    QMessageBox::critical(this,tr("MantidPlot - Error"), tr("Please enter a valid name!"));//Mantid
-    it->setRenameEnabled (0, true);
-    it->startRename (0);
-    return;
-  }
-
-  QStringList lst = parent->subfolders();
-  lst.remove(current_folder->objectName());
-  while(lst.contains(text)){
-    QMessageBox::critical(this,tr("MantidPlot - Error"),//Mantid
-        tr("Name already exists!")+"\n"+tr("Please choose another name!"));
-
-    it->setRenameEnabled (0, true);
-    it->startRename (0);
-    return;
-  }
-
-  current_folder->setObjectName(text);
-  it->setRenameEnabled (0, false);
-  connect(folders, SIGNAL(currentChanged(Q3ListViewItem *)),
-      this, SLOT(folderItemChanged(Q3ListViewItem *)));
-  folders->setCurrentItem(parent->folderListItem());//update the list views
-}
-
-void ApplicationWindow::showAllFolderWindows()
-{
-  QList<MdiSubWindow *> lst = current_folder->windowsList();
-  foreach(MdiSubWindow *w, lst)
-  {//force show all windows in current folder
-    if (w)
-    {
-      updateWindowLists(w);
-      switch (w->status())
-      {
-      case MdiSubWindow::Hidden:
-        w->showNormal();
-        break;
-
-      case MdiSubWindow::Normal:
-        w->showNormal();
-        break;
-
-      case MdiSubWindow::Minimized:
-        w->showMinimized();
-        break;
-
-      case MdiSubWindow::Maximized:
-        w->showMaximized();
-        break;
-      }
-    }
-  }
-
-  if ( (current_folder->children()).isEmpty() )
-    return;
-
-  FolderListItem *fi = current_folder->folderListItem();
-  FolderListItem *item = (FolderListItem *)fi->firstChild();
-  int initial_depth = item->depth();
-  while (item && item->depth() >= initial_depth)
-  {// show/hide windows in all subfolders
-    lst = ((Folder *)item->folder())->windowsList();
-    foreach(MdiSubWindow *w, lst){
-      if (w && show_windows_policy == SubFolders){
-        updateWindowLists(w);
-        switch (w->status())
-        {
-        case MdiSubWindow::Hidden:
-          w->showNormal();
-          break;
-
-        case MdiSubWindow::Normal:
-          w->showNormal();
-          break;
-
-        case MdiSubWindow::Minimized:
-          w->showMinimized();
-          break;
-
-        case MdiSubWindow::Maximized:
-          w->showMaximized();
-          break;
-        }
-      }
-      else
-        w->hide();
-    }
-
-    item = (FolderListItem *)item->itemBelow();
-  }
-}
-
-void ApplicationWindow::hideAllFolderWindows()
-{
-  QList<MdiSubWindow *> lst = current_folder->windowsList();
-  foreach(MdiSubWindow *w, lst)
-  hideWindow(w);
-
-  if ( (current_folder->children()).isEmpty() )
-    return;
-
-  if (show_windows_policy == SubFolders)
-  {
-    FolderListItem *fi = current_folder->folderListItem();
-    FolderListItem *item = (FolderListItem *)fi->firstChild();
-    int initial_depth = item->depth();
-    while (item && item->depth() >= initial_depth)
-    {
-      lst = item->folder()->windowsList();
-      foreach(MdiSubWindow *w, lst)
-      hideWindow(w);
-
-      item = (FolderListItem *)item->itemBelow();
-    }
-  }
-}
-
-void ApplicationWindow::projectProperties()
-{
-  QString s = QString(current_folder->objectName()) + "\n\n";
-  s += "\n\n\n";
-  s += tr("Type") + ": " + tr("Project")+"\n\n";
-  if (projectname != "untitled")
-  {
-    s += tr("Path") + ": " + projectname + "\n\n";
-
-    QFileInfo fi(projectname);
-    s += tr("Size") + ": " + QString::number(fi.size()) + " " + tr("bytes")+ "\n\n";
-  }
-
-  s += tr("Contents") + ": " + QString::number(windowsList().size()) + " " + tr("windows");
-  s += ", " + QString::number(current_folder->subfolders().count()) + " " + tr("folders") + "\n\n";
-  s += "\n\n\n";
-
-  if (projectname != "untitled")
-  {
-    QFileInfo fi(projectname);
-    s += tr("Created") + ": " + fi.created().toString(Qt::LocalDate) + "\n\n";
-    s += tr("Modified") + ": " + fi.lastModified().toString(Qt::LocalDate) + "\n\n";
-  }
-  else
-    s += tr("Created") + ": " + current_folder->birthDate() + "\n\n";
-
-  QMessageBox *mbox = new QMessageBox ( tr("Properties"), s, QMessageBox::NoIcon,
-      QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton, this);
-
-  //mbox->setIconPixmap(QPixmap( qtiplot_logo_xpm ));
-  mbox->show();
-}
-
-void ApplicationWindow::folderProperties()
-{
-  if (!current_folder->parent())
-  {
-    projectProperties();
-    return;
-  }
-
-  QString s = QString(current_folder->objectName()) + "\n\n";
-  s += "\n\n\n";
-  s += tr("Type") + ": " + tr("Folder")+"\n\n";
-  s += tr("Path") + ": " + current_folder->path() + "\n\n";
-  s += tr("Size") + ": " + current_folder->sizeToString() + "\n\n";
-  s += tr("Contents") + ": " + QString::number(current_folder->windowsList().count()) + " " + tr("windows");
-  s += ", " + QString::number(current_folder->subfolders().count()) + " " + tr("folders") + "\n\n";
-  //s += "\n\n\n";
-  s += tr("Created") + ": " + current_folder->birthDate() + "\n\n";
-  //s += tr("Modified") + ": " + current_folder->modificationDate() + "\n\n";
-
-  QMessageBox *mbox = new QMessageBox ( tr("Properties"), s, QMessageBox::NoIcon,
-      QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton, this);
-
-  mbox->setIconPixmap(getQPixmap("folder_open_xpm"));
-  mbox->show();
-}
-
-void ApplicationWindow::addFolder()
-{
-  if (!explorerWindow->isVisible())
-    explorerWindow->show();
-
-  QStringList lst = current_folder->subfolders();
-  QString name =  tr("New Folder");
-  lst = lst.grep( name );
-  if (!lst.isEmpty())
-    name += " ("+ QString::number(lst.size()+1)+")";
-
-  Folder *f = new Folder(current_folder, name);
-  addFolderListViewItem(f);
-
-  FolderListItem *fi = new FolderListItem(current_folder->folderListItem(), f);
-  if (fi){
-    f->setFolderListItem(fi);
-    fi->setRenameEnabled (0, true);
-    fi->startRename(0);
-  }
-}
-
-Folder* ApplicationWindow::addFolder(QString name, Folder* parent)
-{
-  if(!parent){
-    if (current_folder)
-      parent = current_folder;
-    else
-      parent = projectFolder();
-  }
-
-  QStringList lst = parent->subfolders();
-  lst = lst.grep( name );
-  if (!lst.isEmpty())
-    name += " ("+ QString::number(lst.size()+1)+")";
-
-  Folder *f = new Folder(parent, name);
-  addFolderListViewItem(f);
-
-  FolderListItem *fi = new FolderListItem(parent->folderListItem(), f);
-  if (fi)
-    f->setFolderListItem(fi);
-
-  return f;
-}
-
-bool ApplicationWindow::deleteFolder(Folder *f)
-{
-  if (!f)
-    return false;
-
-  if (confirmCloseFolder && QMessageBox::information(this, tr("MantidPlot - Delete folder?"),//Mantid
-      tr("Delete folder '%1' and all the windows it contains?").arg(f->objectName()),
-      tr("Yes"), tr("No"), 0, 0))
-    return false;
-  else {
-    Folder *parent = projectFolder();
-    if (current_folder){
-      if (current_folder->parent())
-        parent = (Folder *)current_folder->parent();
-    }
-
-    folders->blockSignals(true);
-
-    FolderListItem *fi = f->folderListItem();
-    foreach(MdiSubWindow *w, f->windowsList())
-    closeWindow(w);
-
-    if (!(f->children()).isEmpty()){
-      Folder *subFolder = f->folderBelow();
-      int initial_depth = f->depth();
-      while (subFolder && subFolder->depth() > initial_depth){
-        foreach(MdiSubWindow *w, subFolder->windowsList()){
-          removeWindowFromLists(w);
-          subFolder->removeWindow(w);
-          delete w;
-        }
-        delete subFolder->folderListItem();
-        delete subFolder;
-
-        subFolder = f->folderBelow();
-      }
-    }
-
-    delete f;
-    delete fi;
-
-    current_folder = parent;
-    folders->setCurrentItem(parent->folderListItem());
-    changeFolder(parent, true);
-    folders->blockSignals(false);
-    folders->setFocus();
-    return true;
-  }
-}
-
-void ApplicationWindow::deleteFolder()
-{
-  Folder *parent = (Folder *)current_folder->parent();
-  if (!parent)
-    parent = projectFolder();
-
-  folders->blockSignals(true);
-
-  if (deleteFolder(current_folder)){
-    current_folder = parent;
-    folders->setCurrentItem(parent->folderListItem());
-    changeFolder(parent, true);
-  }
-
-  folders->blockSignals(false);
-  folders->setFocus();
-}
-
-void ApplicationWindow::folderItemDoubleClicked(Q3ListViewItem *it)
-{
-  if (!it || it->rtti() != FolderListItem::RTTI)
-    return;
-
-  FolderListItem *item = ((FolderListItem *)it)->folder()->folderListItem();
-  folders->setCurrentItem(item);
-}
-
-void ApplicationWindow::folderItemChanged(Q3ListViewItem *it)
-{
-  if (!it)
-    return;
-
-  it->setOpen(true);
-  changeFolder (((FolderListItem *)it)->folder());
-  folders->setFocus();
-}
-
-void ApplicationWindow::hideFolderWindows(Folder *f)
-{
-  QList<MdiSubWindow *> lst = f->windowsList();
-  foreach(MdiSubWindow *w, lst)
-  w->hide();
-
-  if ((f->children()).isEmpty())
-    return;
-
-  Folder *dir = f->folderBelow();
-  int initial_depth = f->depth();
-  while (dir && dir->depth() > initial_depth){
-    lst = dir->windowsList();
-    foreach(MdiSubWindow *w, lst)
-    w->hide();
-
-    dir = dir->folderBelow();
-  }
-}
-
-bool ApplicationWindow::changeFolder(Folder *newFolder, bool force)
-{
-  if (!newFolder)
-    return false;
-
-  if (current_folder == newFolder && !force)
-    return false;
-
-  desactivateFolders();
-  newFolder->folderListItem()->setActive(true);
-
-  Folder *oldFolder = current_folder;
-  MdiSubWindow::Status old_active_window_state = MdiSubWindow::Normal;
-  MdiSubWindow *old_active_window = oldFolder->activeWindow();
-  if (old_active_window)
-    old_active_window_state = old_active_window->status();
-
-  MdiSubWindow::Status active_window_state = MdiSubWindow::Normal;
-  MdiSubWindow *active_window = newFolder->activeWindow();
-
-  if (active_window)
-    active_window_state = active_window->status();
-
-  hideFolderWindows(oldFolder);
-  current_folder = newFolder;
-
-  results->setText(current_folder->logInfo());
-
-  lv->clear();
-
-  QObjectList folderLst = newFolder->children();
-  if(!folderLst.isEmpty()){
-    foreach(QObject *f, folderLst)
-			    addFolderListViewItem(static_cast<Folder *>(f));
-  }
-
-  QList<MdiSubWindow *> lst = newFolder->windowsList();
-  foreach(MdiSubWindow *w, lst){
-    if (!hiddenWindows->contains(w) && show_windows_policy != HideAll){
-      //show only windows in the current folder which are not hidden by the user
-      if(w->status() == MdiSubWindow::Normal)
-        w->showNormal();
-      else if(w->status() == MdiSubWindow::Minimized)
-        w->showMinimized();
-      else if(w->status() == MdiSubWindow::Maximized)
-        w->showMaximized();
-    } else
-      w->setStatus(MdiSubWindow::Hidden);
-
-    addListViewItem(w);
-  }
-
-  if (!(newFolder->children()).isEmpty()){
-    Folder *f = newFolder->folderBelow();
-    int initial_depth = newFolder->depth();
-    while (f && f->depth() > initial_depth){//show/hide windows in subfolders
-      lst = f->windowsList();
-      foreach(MdiSubWindow *w, lst){
-        if (!hiddenWindows->contains(w)){
-          if (show_windows_policy == SubFolders){
-            if (w->status() == MdiSubWindow::Normal || w->status() == MdiSubWindow::Maximized)
-              w->showNormal();
-            else if (w->status() == MdiSubWindow::Minimized)
-              w->showMinimized();
-          } else
-            w->hide();
-        }
-      }
-      f = f->folderBelow();
-    }
-  }
-
-  if (active_window){
-    d_active_window = active_window;
-    d_workspace->setActiveSubWindow(active_window);
-    customMenu(active_window);
-    customToolBars(active_window);
-    if (active_window_state == MdiSubWindow::Minimized)
-      active_window->showMinimized();//ws->setActiveWindow() makes minimized windows to be shown normally
-    else if (active_window_state == MdiSubWindow::Maximized){
-      if (active_window->isA("Graph3D"))
-        ((Graph3D *)active_window)->setIgnoreFonts(true);
-      active_window->showMaximized();
-      if (active_window->isA("Graph3D"))
-        ((Graph3D *)active_window)->setIgnoreFonts(false);
-    }
-  }
-
-  if (old_active_window){
-    old_active_window->setStatus(old_active_window_state);
-    oldFolder->setActiveWindow(old_active_window);
-  }
-
-  if (d_opening_file)
-    modifiedProject();
-  return true;
-}
-
-void ApplicationWindow::desactivateFolders()
-{
-  FolderListItem *item = (FolderListItem *)folders->firstChild();
-  while (item){
-    item->setActive(false);
-    item = (FolderListItem *)item->itemBelow();
-  }
-}
-
-void ApplicationWindow::addListViewItem(MdiSubWindow *w)
-{
-  if (!w)
-    return;
-
-  WindowListItem* it = new WindowListItem(lv, w);
-  if (w->isA("Matrix")){
-    it->setPixmap(0, getQPixmap("matrix_xpm"));
-    it->setText(1, tr("Matrix"));
-  }
-  else if (w->inherits("Table")){
-    it->setPixmap(0, getQPixmap("worksheet_xpm"));
-    it->setText(1, tr("Table"));
-  }
-  else if (w->isA("Note")){
-    it->setPixmap(0, getQPixmap("note_xpm"));
-    it->setText(1, tr("Note"));
-  }
-  else if (w->isA("MultiLayer")){
-    it->setPixmap(0, getQPixmap("graph_xpm"));
-    it->setText(1, tr("Graph"));
-  }
-  else if (w->isA("Graph3D")){
-    it->setPixmap(0, getQPixmap("trajectory_xpm"));
-    it->setText(1, tr("3D Graph"));
-  }
-  else if (w->isA("MantidMatrix")){
-    it->setPixmap(0, getQPixmap("mantid_matrix_xpm"));
-    it->setText(1, tr("Workspace"));
-  }
-  else if (w->isA("InstrumentWindow")){
-    it->setText(1, tr("Instrument"));
-  }
-
-
-  it->setText(0, w->objectName());
-  it->setText(2, w->aspect());
-  it->setText(3, w->sizeToString());
-  it->setText(4, w->birthDate());
-  it->setText(5, w->windowLabel());
-}
-
-void ApplicationWindow::windowProperties()
-{
-  WindowListItem *it = (WindowListItem *)lv->currentItem();
-  MdiSubWindow *w = it->window();
-  if (!w)
-    return;
-
-  QMessageBox *mbox = new QMessageBox ( tr("Properties"), QString(), QMessageBox::NoIcon,
-      QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton, this);
-
-  QString s = QString(w->objectName()) + "\n\n";
-  s += "\n\n\n";
-
-  s += tr("Label") + ": " + ((MdiSubWindow *)w)->windowLabel() + "\n\n";
-
-  if (w->isA("Matrix")){
-    mbox->setIconPixmap(getQPixmap("matrix_xpm"));
-    s +=  tr("Type") + ": " + tr("Matrix") + "\n\n";
-  }else if (w->inherits("Table")){
-    mbox->setIconPixmap(getQPixmap("worksheet_xpm"));
-    s +=  tr("Type") + ": " + tr("Table") + "\n\n";
-  }else if (w->isA("Note")){
-    mbox->setIconPixmap(getQPixmap("note_xpm"));
-    s +=  tr("Type") + ": " + tr("Note") + "\n\n";
-  }else if (w->isA("MultiLayer")){
-    mbox->setIconPixmap(getQPixmap("graph_xpm"));
-    s +=  tr("Type") + ": " + tr("Graph") + "\n\n";
-  }else if (w->isA("Graph3D")){
-    mbox->setIconPixmap(getQPixmap("trajectory_xpm"));
-    s +=  tr("Type") + ": " + tr("3D Graph") + "\n\n";
-  }
-  s += tr("Path") + ": " + current_folder->path() + "\n\n";
-  s += tr("Size") + ": " + w->sizeToString() + "\n\n";
-  s += tr("Created") + ": " + w->birthDate() + "\n\n";
-  s += tr("Status") + ": " + it->text(2) + "\n\n";
-  mbox->setText(s);
-  mbox->show();
-}
-
-void ApplicationWindow::addFolderListViewItem(Folder *f)
-{
-  if (!f)
-    return;
-
-  FolderListItem* it = new FolderListItem(lv, f);
-  it->setActive(false);
-  it->setText(0, f->objectName());
-  it->setText(1, tr("Folder"));
-  it->setText(3, f->sizeToString());
-  it->setText(4, f->birthDate());
-}
-
-void ApplicationWindow::find(const QString& s, bool windowNames, bool labels,
-    bool folderNames, bool caseSensitive, bool partialMatch, bool subfolders)
-{
-  if (windowNames || labels){
-    MdiSubWindow *w = current_folder->findWindow(s, windowNames, labels, caseSensitive, partialMatch);
-    if (w){
-      activateWindow(w);
-      return;
-    }
-
-    if (subfolders){
-      FolderListItem *item = (FolderListItem *)folders->currentItem()->firstChild();
-      while (item){
-        Folder *f = item->folder();
-        MdiSubWindow *w = f->findWindow(s,windowNames,labels,caseSensitive,partialMatch);
-        if (w){
-          folders->setCurrentItem(f->folderListItem());
-          activateWindow(w);
-          return;
-        }
-        item = (FolderListItem *)item->itemBelow();
-      }
-    }
-  }
-
-  if (folderNames){
-    Folder *f = current_folder->findSubfolder(s, caseSensitive, partialMatch);
-    if (f){
-      folders->setCurrentItem(f->folderListItem());
-      return;
-    }
-
-    if (subfolders){
-      FolderListItem *item = (FolderListItem *)folders->currentItem()->firstChild();
-      while (item){
-        Folder *f = item->folder()->findSubfolder(s, caseSensitive, partialMatch);
-        if (f){
-          folders->setCurrentItem(f->folderListItem());
-          return;
-        }
-
-        item = (FolderListItem *)item->itemBelow();
-      }
-    }
-  }
-
-  QMessageBox::warning(this, tr("MantidPlot - No match found"),//Mantid
-      tr("Sorry, no match found for string: '%1'").arg(s));
-}
-
-void ApplicationWindow::dropFolderItems(Q3ListViewItem *dest)
-{
-  if (!dest || draggedItems.isEmpty ())
-    return;
-
-  Folder *dest_f = ((FolderListItem *)dest)->folder();
-
-  Q3ListViewItem *it;
-  QStringList subfolders = dest_f->subfolders();
-
-  foreach(it, draggedItems){
-    if (it->rtti() == FolderListItem::RTTI){
-      Folder *f = ((FolderListItem *)it)->folder();
-      FolderListItem *src = f->folderListItem();
-      if (dest_f == f){
-        QMessageBox::critical(this, "MantidPlot - Error", tr("Cannot move an object to itself!"));//Mantid
-        return;
-      }
-
-      if (((FolderListItem *)dest)->isChildOf(src)){
-        QMessageBox::critical(this,"MantidPlot - Error",tr("Cannot move a parent folder into a child folder!"));//Mantid
-        draggedItems.clear();
-        folders->setCurrentItem(current_folder->folderListItem());
-        return;
-      }
-
-      Folder *parent = (Folder *)f->parent();
-      if (!parent)
-        parent = projectFolder();
-      if (dest_f == parent)
-        return;
-
-      if (subfolders.contains(f->objectName())){
-        QMessageBox::critical(this, tr("MantidPlot") +" - " + tr("Skipped moving folder"),//Mantid
-            tr("The destination folder already contains a folder called '%1'! Folder skipped!").arg(f->objectName()));
-      } else
-        moveFolder(src, (FolderListItem *)dest);
-    } else {
-      if (dest_f == current_folder)
-        return;
-
-      MdiSubWindow *w = ((WindowListItem *)it)->window();
-      if (w){
-        current_folder->removeWindow(w);
-        w->hide();
-        dest_f->addWindow(w);
-        delete it;
-      }
-    }
-  }
-
-  draggedItems.clear();
-  current_folder = dest_f;
-  folders->setCurrentItem(dest_f->folderListItem());
-  changeFolder(dest_f, true);
-  folders->setFocus();
-}
-
-void ApplicationWindow::moveFolder(FolderListItem *src, FolderListItem *dest)
-{
-  folders->blockSignals(true);
-  if (copyFolder(src->folder(), dest->folder())){
-    delete src->folder();
-    delete src;
-  }
-  folders->blockSignals(false);
-}
-
-bool ApplicationWindow::copyFolder(Folder *src, Folder *dest)
-{
-  if (!src || !dest)
-    return false;
-
-  if (dest->subfolders().contains(src->objectName())){
-    QMessageBox::critical(this, tr("MantidPlot") + " - " + tr("Error"),//Mantid
-        tr("The destination folder already contains a folder called '%1'! Folder skipped!").arg(src->objectName()));
-    return false;
-  }
-
-  Folder *dest_f = new Folder(dest, src->objectName());
-  dest_f->setBirthDate(src->birthDate());
-  dest_f->setModificationDate(src->modificationDate());
-
-  FolderListItem *copy_item = new FolderListItem(dest->folderListItem(), dest_f);
-  copy_item->setText(0, src->objectName());
-  copy_item->setOpen(src->folderListItem()->isOpen());
-  dest_f->setFolderListItem(copy_item);
-
-  QList<MdiSubWindow *> lst = QList<MdiSubWindow *>(src->windowsList());
-  foreach(MdiSubWindow *w, lst)
-  dest_f->addWindow(w);
-
-  if (!(src->children()).isEmpty()){
-    int initial_depth = src->depth();
-    Folder *parentFolder = dest_f;
-    src = src->folderBelow();
-    while (src && parentFolder && src->depth() > initial_depth){
-      dest_f = new Folder(parentFolder, src->objectName());
-      dest_f->setBirthDate(src->birthDate());
-      dest_f->setModificationDate(src->modificationDate());
-
-      copy_item = new FolderListItem(parentFolder->folderListItem(), dest_f);
-      copy_item->setText(0, src->objectName());
-      copy_item->setOpen(src->folderListItem()->isOpen());
-      dest_f->setFolderListItem(copy_item);
-
-      lst = QList<MdiSubWindow *>(src->windowsList());
-      foreach(MdiSubWindow *w, lst)
-      dest_f->addWindow(w);
-
-      int depth = src->depth();
-      src = src->folderBelow();
-      if (src){
-        int next_folder_depth = src->depth();
-        if (next_folder_depth > depth)
-          parentFolder = dest_f;
-        else if (next_folder_depth < depth && next_folder_depth > initial_depth)
-          parentFolder = (Folder*)parentFolder->parent();
-      }
-    }
-  }
-  return true;
-}
-//Mantid commented out
-//void ApplicationWindow::searchForUpdates()
-//{
-//    int choice = QMessageBox::question(this, tr("QtiPlot"),
-//					tr("QtiPlot will try to download necessary information about the last available updates. Please modify your firewall settings in order to allow QtiPlot to connect to the internet!") + "\n" +
-//					tr("Do you wish to continue?"),
-//					QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape);
-//
-//    if (choice == QMessageBox::Yes){
-//        version_buffer.open(IO_WriteOnly);
-//        http.setHost("soft.proindependent.com");
-//        http.get("/version.txt", &version_buffer);
-//        http.closeConnection();
-//    }
-//}
-//
-//void ApplicationWindow::receivedVersionFile(bool error)
-//{
-//	if (error){
-//		QMessageBox::warning(this, tr("QtiPlot - HTTP get version file"),
-//				tr("Error while fetching version file with HTTP: %1.").arg(http.errorString()));
-//		return;
-//	}
-//
-//	version_buffer.close();
-//
-//	if (version_buffer.open(IO_ReadOnly))
-//	{
-//		QTextStream t( &version_buffer );
-//		t.setEncoding(QTextStream::UnicodeUTF8);
-//		QString version = t.readLine();
-//		version_buffer.close();
-//
-//		QString currentVersion = QString::number(maj_version) + "." + QString::number(min_version) +
-//			"." + QString::number(patch_version) + QString(extra_version);
-//
-//		if (currentVersion != version)
-//		{
-//			if(QMessageBox::question(this, tr("QtiPlot - Updates Available"),
-//						tr("There is a newer version of QtiPlot (%1) available for download. Would you like to download it?").arg(version),
-//						QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape) == QMessageBox::Yes)
-//				QDesktopServices::openUrl(QUrl("http://soft.proindependent.com/download.html"));
-//		}
-//		else if (!autoSearchUpdatesRequest)
-//		{
-//			QMessageBox::information(this, tr("QtiPlot - No Updates Available"),
-//					tr("No updates available. Your current version %1 is the last version available!").arg(version));
-//		}
-//		autoSearchUpdatesRequest = false;
-//	}
-//}
-
-/**
-  Turns 3D animation on or off
- */
-void ApplicationWindow::toggle3DAnimation(bool on)
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->animate(on);
-}
-
-QString ApplicationWindow::generateUniqueName(const QString& name, bool increment)
-{
-  int index = 0;
-  QStringList lst;
-  Folder *f = projectFolder();
-  while (f){
-    QList<MdiSubWindow *> folderWindows = f->windowsList();
-    foreach(MdiSubWindow *w, folderWindows){
-      lst << QString(w->objectName());
-      if (QString(w->objectName()).startsWith(name))
-        index++;
-    }
-    f = f->folderBelow();
-  }
-
-  QString newName = name;
-  if (increment)//force return of a different name
-    newName += QString::number(++index);
-  else if (index>0)
-    newName += QString::number(index);
-
-  while(lst.contains(newName))
-    newName = name + QString::number(++index);
-
-  return newName;
-}
-
-void ApplicationWindow::clearTable()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-
-  if (QMessageBox::question(this, tr("MantidPlot - Warning"),//Mantid
-      tr("This will clear the contents of all the data associated with the table. Are you sure?"),
-      tr("&Yes"), tr("&No"), QString(), 0, 1 ) )
-    return;
-  else
-    t->clear();
-}
-
-void ApplicationWindow::goToRow()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return;
-
-  if (w->inherits("Table") || w->isA("Matrix")){
-    bool ok;
-    int row = QInputDialog::getInteger(this, tr("MantidPlot - Enter row number"), tr("Row"),//Mantid
-        1, 0, 1000000, 1, &ok, windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinMaxButtonsHint );
-    if ( !ok )
-      return;
-
-    if (w->inherits("Table"))
-      ((Table *)w)->goToRow(row);
-    else if (w->isA("Matrix"))
-      ((Matrix *)w)->goToRow(row);
-  }
-}
-
-void ApplicationWindow::goToColumn()
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return;
-
-  if (w->inherits("Table") || w->isA("Matrix")){
-    bool ok;
-    int col = QInputDialog::getInteger(this, tr("MantidPlot - Enter column number"), tr("Column"),//Mantid
-        1, 0, 1000000, 1, &ok, windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinMaxButtonsHint );
-    if ( !ok )
-      return;
-
-    if (w->inherits("Table"))
-      ((Table *)w)->goToColumn(col);
-    else if (w->isA("Matrix"))
-      ((Matrix *)w)->goToColumn(col);
-  }
-}
-
-void ApplicationWindow::showScriptWindow(bool forceVisible)
+    if( menu->title() == topMenu ) return;
+  }
+
+  QMenu* customMenu = new QMenu(topMenu);
+  customMenu->setTitle(topMenu);
+  customMenu->setName(topMenu);
+  connect(customMenu, SIGNAL(triggered(QAction*)), this, SLOT(performCustomAction(QAction*)));
+  d_user_menus.append(customMenu);
+  menuBar()->insertItem(tr(topMenu), customMenu);
+}
+
+void ApplicationWindow::addUserMenuAction(const QString & parentMenu, const QString & itemName, const QString & itemData)
 {
-  if( !scriptingWindow )
+  QMenu* topMenu(NULL);
+  foreach(topMenu, d_user_menus)
   {
-    // MG 09/02/2010 : Removed parent from scripting window. If it has one then it doesn't respect the always on top 
-    // flag, it is treated as a sub window of its parent
-    scriptingWindow = new ScriptingWindow(scriptingEnv(), NULL);
-    scriptingWindow->setObjectName("ScriptingWindow");
-    scriptingWindow->setAttribute(Qt::WA_DeleteOnClose, false);
-    connect(scriptingWindow, SIGNAL(closeMe()), this, SLOT(saveScriptWindowGeometry()));
-    connect(scriptingWindow, SIGNAL(hideMe()), this, SLOT(showScriptWindow()));
-    connect(scriptingWindow, SIGNAL(chooseScriptingLanguage()), this, SLOT(showScriptingLangDialog()));
+    if( topMenu->title() == parentMenu ) break;
+  } 
+
+  if( !topMenu ) return;
+  foreach(QAction* userAction, topMenu->actions())
+  {
+    if( userAction->text() == itemName ) return;
   }
 
-  if( forceVisible || scriptingWindow->isMinimized() || !scriptingWindow->isVisible() )
+  QAction* scriptAction = new QAction(tr(itemName), topMenu);
+  scriptAction->setData(itemData); 
+  topMenu->addAction(scriptAction);
+  d_user_actions.append(scriptAction);
+
+  // Remove name from the list of removed interfaces if applicable
+  removed_interfaces.remove(itemName);
+}
+
+void ApplicationWindow::removeUserMenu(const QString & parentMenu)
+{
+  int i(0);
+  QMenu *menu = NULL;
+  foreach(menu, d_user_menus)
   {
-    scriptingWindow->resize(d_script_win_size);
-    scriptingWindow->move(d_script_win_pos);
-    scriptingWindow->show();
-    scriptingWindow->setFocus();
+    if( menu->title() == parentMenu ) break;
+    ++i;
   }
-  else 
+  if( !menu ) return; 
+
+  d_user_menus.removeAt(i);
+  menuBar()->removeAction(menu->menuAction());
+}
+
+void ApplicationWindow::removeUserMenuAction(const QString & parentMenu, const QString & userAction)
+{
+  QMenu *menu = NULL;
+  foreach(menu, d_user_menus)
   {
-    saveScriptWindowGeometry();
-    scriptingWindow->hide();
+    if( menu->title() == parentMenu ) break;
   }
+  if( !menu ) return;
+
+  QAction *action = NULL;
+  int menu_count(0);
+  foreach(action, d_user_actions)
+  {
+    if( action->text() == userAction ) break;
+    ++menu_count;
+  }
+  if( !action ) return;
+
+  d_user_actions.removeAt(menu_count);
+  menu->removeAction(action);
+
+  // Add interface name to the list of removed interfaces
+  removed_interfaces.append(userAction);
 }
 
-void ApplicationWindow::saveScriptWindowGeometry()
+const QList<QMenu*> & ApplicationWindow::getCustomMenus() const
 {
-  d_script_win_size = scriptingWindow->size();
-  d_script_win_pos = scriptingWindow->pos();
+  return d_user_menus;
+} 
+
+QList<QMenu *> ApplicationWindow::menusList()
+{
+  QList<QMenu *> lst;
+  QObjectList children = this->children();
+  foreach (QObject *w, children){
+    if (w->isA("QMenu"))
+      lst << (QMenu *)w;
+  }
+  return lst;
 }
 
-void ApplicationWindow::showScriptInterpreter()
-{
-  if( !m_interpreterDock )
-  {
-    m_interpreterDock = new QDockWidget(this);
-    m_interpreterDock->setObjectName("interpreterDock");
-    m_interpreterDock->setWindowTitle("Script Interpreter");
-    addDockWidget( Qt::BottomDockWidgetArea, m_interpreterDock );
-
-    m_scriptInterpreter = new ScriptManagerWidget(scriptingEnv(), m_interpreterDock,true);
-    m_interpreterDock->setWidget(m_scriptInterpreter);
-    m_interpreterDock->setFocusPolicy(Qt::StrongFocus);
-    m_interpreterDock->setFocusProxy(m_scriptInterpreter);
-    
-  }
-  if( m_interpreterDock->isVisible() )
-  {
-    m_interpreterDock->hide();
-  }
-  else
-  { 
-    m_interpreterDock->show();
-    m_interpreterDock->setFocusPolicy(Qt::StrongFocus);
-    m_interpreterDock->setFocusProxy(m_scriptInterpreter);
-    m_scriptInterpreter->setFocus();
-    m_interpreterDock->activateWindow();
-     
+// End of a section of Mantid custom functions
+//-------------------------------------------
+
+QList<QToolBar *> ApplicationWindow::toolBarsList()
+{
+  QList<QToolBar *> lst;
+  QObjectList children = this->children();
+  foreach (QObject *w, children){
+    if (w->isA("QToolBar"))
+      lst << (QToolBar *)w;
   }
-
-}
-
-/**
-  Turns perspective mode on or off
- */
-void ApplicationWindow::togglePerspective(bool on)
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setOrthogonal(!on);
-}
-
-/**
-  Resets rotation of 3D plots to default values
- */
-void ApplicationWindow::resetRotation()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->setRotation(30, 0, 15);
-}
-
-/**
-  Finds best layout for the 3D plot
- */
-void ApplicationWindow::fitFrameToLayer()
-{
-  Graph3D *g = (Graph3D *)activeWindow(Plot3DWindow);
-  if (!g)
-    return;
-
-  g->findBestLayout();
-}
-
-ApplicationWindow::~ApplicationWindow()
-{
-  if (lastCopiedLayer)
-    delete lastCopiedLayer;
-
-  delete hiddenWindows;
-
-  if (scriptingWindow)
-  {
-    delete scriptingWindow;
-  }
-
-  if (d_text_editor)
-    delete d_text_editor;
-
-  QApplication::clipboard()->clear(QClipboard::Clipboard);
-
-  btnPointer->setChecked(true);
-
-  //Mantid
-  if (mantidUI) delete mantidUI;
-}
-
-QString ApplicationWindow::versionString()
-{
-  QString version(MANTIDPLOT_RELEASE_VERSION);
-  QString date(MANTIDPLOT_RELEASE_DATE);
-  return "This is MantidPlot version " + version + " of " + date;
-}
-
-int ApplicationWindow::convertOldToNewColorIndex(int cindex)
-{
-  if( (cindex == 13) || (cindex == 14) ) // white and light gray
-    return cindex + 4;
-
-  if(cindex == 15) // dark gray
-    return cindex + 8;
-
-  return cindex;
-}
-
-void ApplicationWindow::cascade()
-{
-  const int xoffset = 13;
-  const int yoffset = 20;
-  int x = 0;
-  int y = 0;
-  QList<QMdiSubWindow*> windows = d_workspace->subWindowList(QMdiArea::StackingOrder);
-  foreach (QMdiSubWindow *w, windows){
-    w->setActiveWindow();
-    ((MdiSubWindow *)w)->setNormal();
-    w->setGeometry(x, y, w->geometry().width(), w->geometry().height());
-    w->raise();
-    x += xoffset;
-    y += yoffset;
-  }
-  modifiedProject();
-}
-
-ApplicationWindow * ApplicationWindow::loadScript(const QString& fn, bool execute, bool quit)
-{
-#ifdef SCRIPTING_PYTHON
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-  setScriptingLanguage("Python");
-  restoreApplicationGeometry();
-  showScriptWindow();
-  scriptingWindow->open(fn, false);
-  QApplication::restoreOverrideCursor();
-  if (execute)
-    scriptingWindow->executeAll();
-  if( quit )
-  {
-    saved = true;
-    this->close();
-  }
-  return this;
-#else
-  QMessageBox::critical(this, tr("MantidPlot") + " - " + tr("Error"),//Mantid
-      tr("MantidPlot was not built with Python scripting support included!"));//Mantid
-#endif
-  return 0;
-}
-
-bool ApplicationWindow::validFor2DPlot(Table *table)
-{
-  if (!table->selectedYColumns().count()){
-    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select a Y column to plot!"));//Mantid
-    return false;
-  } else if (table->numCols()<2) {
-    QMessageBox::critical(this, tr("MantidPlot - Error"),tr("You need at least two columns for this operation!"));//Mantid
-    return false;
-  } else if (table->noXColumn()) {
-    QMessageBox::critical(this, tr("MantidPlot - Error"), tr("Please set a default X column for this table, first!"));//Mantid
-    return false;
-  }
-  return true;
-}
-
-MultiLayer* ApplicationWindow::generate2DGraph(Graph::CurveType type)
-{
-  MdiSubWindow *w = activeWindow();
-  if (!w)
-    return 0;
-
-  if (w->inherits("Table")){
-    Table *table = static_cast<Table *>(w);
-    if (!validFor2DPlot(table))
-      return 0;
-
-    Q3TableSelection sel = table->getSelection();
-    return multilayerPlot(table, table->drawableColumnSelection(), type, sel.topRow(), sel.bottomRow());
-  } else if (w->isA("Matrix")){
-    Matrix *m = static_cast<Matrix *>(w);
-    return plotHistogram(m);
-  }
-  return 0;
-}
-
-bool ApplicationWindow::validFor3DPlot(Table *table)
-{
-  if (table->numCols()<2){
-    QMessageBox::critical(0,tr("MantidPlot - Error"),tr("You need at least two columns for this operation!"));//Mantid
-    return false;
-  }
-  if (table->selectedColumn() < 0 || table->colPlotDesignation(table->selectedColumn()) != Table::Z){
-    QMessageBox::critical(0,tr("MantidPlot - Error"),tr("Please select a Z column for this operation!"));//Mantid
-    return false;
-  }
-  if (table->noXColumn()){
-    QMessageBox::critical(0,tr("MantidPlot - Error"),tr("You need to define a X column first!"));//Mantid
-    return false;
-  }
-  if (table->noYColumn()){
-    QMessageBox::critical(0,tr("MantidPlot - Error"),tr("You need to define a Y column first!"));//Mantid
-    return false;
-  }
-  return true;
-}
-
-void ApplicationWindow::hideSelectedWindows()
-{
-  Q3ListViewItem *item;
-  QList<Q3ListViewItem *> lst;
-  for (item = lv->firstChild(); item; item = item->nextSibling()){
-    if (item->isSelected())
-      lst.append(item);
-  }
-
-  folders->blockSignals(true);
-  foreach(item, lst){
-    if (item->rtti() != FolderListItem::RTTI)
-      hideWindow(((WindowListItem *)item)->window());
-  }
-  folders->blockSignals(false);
-}
-
-void ApplicationWindow::showSelectedWindows()
-{
-  Q3ListViewItem *item;
-  QList<Q3ListViewItem *> lst;
-  for (item = lv->firstChild(); item; item = item->nextSibling()){
-    if (item->isSelected())
-      lst.append(item);
-  }
-
-  folders->blockSignals(true);
-  foreach(item, lst){
-    if (item->rtti() != FolderListItem::RTTI)
-      activateWindow(((WindowListItem *)item)->window());
-  }
-  folders->blockSignals(false);
-}
-
-void ApplicationWindow::swapColumns()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (!t)
-    return;
-  QStringList lst = t->selectedColumns();
-  if(lst.count() != 2)
-    return;
-
-  t->swapColumns(t->colIndex(lst[0]), t->colIndex(lst[1]));
-}
-
-void ApplicationWindow::moveColumnRight()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (t)
-    t->moveColumnBy(1);
-}
-
-void ApplicationWindow::moveColumnLeft()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (t)
-    t->moveColumnBy(-1);
-}
-
-void ApplicationWindow::moveColumnFirst()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (t)
-    t->moveColumnBy(0 - t->selectedColumn());
-}
-
-void ApplicationWindow::moveColumnLast()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (t)
-    t->moveColumnBy(t->numCols() - t->selectedColumn() - 1);
-}
-
-void ApplicationWindow::restoreApplicationGeometry()
-{
-  if (d_app_rect.isNull())
-    showMaximized();
-  else {
-    resize(d_app_rect.size());
-    move(d_app_rect.topLeft());
-    show();
-  }
-}
-
-void ApplicationWindow::scriptsDirPathChanged(const QString& path)
-{
-  scriptsDirPath = path;
-
-  QList<MdiSubWindow*> windows = windowsList();
-  foreach(MdiSubWindow *w, windows){
-    if (w->isA("Note"))
-      ((Note*)w)->setDirPath(path);
-  }
-}
-
-void ApplicationWindow::showToolBarsMenu()
-{
-  QMenu toolBarsMenu;
-
-  QAction *actionFileTools = new QAction(fileTools->windowTitle(), this);
-  actionFileTools->setCheckable(true);
-  actionFileTools->setChecked(fileTools->isVisible());
-  connect(actionFileTools, SIGNAL(toggled(bool)), fileTools, SLOT(setVisible(bool)));
-  toolBarsMenu.addAction(actionFileTools);
-
-  QAction *actionEditTools = new QAction(editTools->windowTitle(), this);
-  actionEditTools->setCheckable(true);
-  actionEditTools->setChecked(editTools->isVisible());
-  connect(actionEditTools, SIGNAL(toggled(bool)), editTools, SLOT(setVisible(bool)));
-  toolBarsMenu.addAction(actionEditTools);
-
-  QAction *actionTableTools = new QAction(tableTools->windowTitle(), this);
-  actionTableTools->setCheckable(true);
-  actionTableTools->setChecked(tableTools->isVisible());
-  connect(actionTableTools, SIGNAL(toggled(bool)), tableTools, SLOT(setVisible(bool)));
-  toolBarsMenu.addAction(actionTableTools);
-
-  QAction *actionColumnTools = new QAction(columnTools->windowTitle(), this);
-  actionColumnTools->setCheckable(true);
-  actionColumnTools->setChecked(columnTools->isVisible());
-  connect(actionColumnTools, SIGNAL(toggled(bool)), columnTools, SLOT(setVisible(bool)));
-  toolBarsMenu.addAction(actionColumnTools);
-
-  QAction *actionPlotTools = new QAction(plotTools->windowTitle(), this);
-  actionPlotTools->setCheckable(true);
-  actionPlotTools->setChecked(plotTools->isVisible());
-  connect(actionPlotTools, SIGNAL(toggled(bool)), plotTools, SLOT(setVisible(bool)));
-  toolBarsMenu.addAction(actionPlotTools);
-
-  QAction *actionMatrixTools = new QAction(plotMatrixBar->windowTitle(), this);
-  actionMatrixTools->setCheckable(true);
-  actionMatrixTools->setChecked(plotMatrixBar->isVisible());
-  connect(actionMatrixTools, SIGNAL(toggled(bool)), plotMatrixBar, SLOT(setVisible(bool)));
-  toolBarsMenu.addAction(actionMatrixTools);
-
-  QAction *actionPlot3DTools = new QAction(plot3DTools->windowTitle(), this);
-  actionPlot3DTools->setCheckable(true);
-  actionPlot3DTools->setChecked(plot3DTools->isVisible());
-  connect(actionPlot3DTools, SIGNAL(toggled(bool)), plot3DTools, SLOT(setVisible(bool)));
-  toolBarsMenu.addAction(actionPlot3DTools);
-
-  QAction *actionDisplayBar = new QAction(displayBar->windowTitle(), this);
-  actionDisplayBar->setCheckable(true);
-  actionDisplayBar->setChecked(displayBar->isVisible());
-  connect(actionDisplayBar, SIGNAL(toggled(bool)), displayBar, SLOT(setVisible(bool)));
-  toolBarsMenu.addAction(actionDisplayBar);
-
-  QAction *actionFormatToolBar = new QAction(formatToolBar->windowTitle(), this);
-  actionFormatToolBar->setCheckable(true);
-  actionFormatToolBar->setChecked(formatToolBar->isVisible());
-  connect(actionFormatToolBar, SIGNAL(toggled(bool)), formatToolBar, SLOT(setVisible(bool)));
-  toolBarsMenu.addAction(actionFormatToolBar);
-
-  QAction *action = toolBarsMenu.exec(QCursor::pos());
-  if (!action)
-    return;
-
-  MdiSubWindow *w = activeWindow();
-
-  if (action->text() == plotMatrixBar->windowTitle()){
-    d_matrix_tool_bar = action->isChecked();
-    plotMatrixBar->setEnabled(w && w->isA("Matrix"));
-  } else if (action->text() == tableTools->windowTitle()){
-    d_table_tool_bar = action->isChecked();
-    tableTools->setEnabled(w && w->inherits("Table"));
-  } else if (action->text() == columnTools->windowTitle()){
-    d_column_tool_bar = action->isChecked();
-    columnTools->setEnabled(w && w->inherits("Table"));
-  } else if (action->text() == plotTools->windowTitle()){
-    d_plot_tool_bar = action->isChecked();
-    plotTools->setEnabled(w && w->isA("MultiLayer"));
-  } else if (action->text() == plot3DTools->windowTitle()){
-    d_plot3D_tool_bar = action->isChecked();
-    plot3DTools->setEnabled(w && w->isA("Graph3D"));
-  } else if (action->text() == fileTools->windowTitle()){
-    d_file_tool_bar = action->isChecked();
-  } else if (action->text() == editTools->windowTitle()){
-    d_edit_tool_bar = action->isChecked();
-  } else if (action->text() == displayBar->windowTitle()){
-    d_display_tool_bar = action->isChecked();
-  } else if (action->text() == formatToolBar->windowTitle()){
-    d_format_tool_bar = action->isChecked();
-  }
-}
-
-void ApplicationWindow::saveFitFunctions(const QStringList& lst)
-{
-  if (!lst.count())
-    return;
-
-  QString explain = tr("Starting with version 0.9.1 MantidPlot stores the user defined fit models to a different location.");
-  explain += " " + tr("If you want to save your already defined models, please choose a destination folder.");
-  if (QMessageBox::Ok != QMessageBox::information(this, tr("MantidPlot") + " - " + tr("Import fit models"), explain,//Mantid
-      QMessageBox::Ok, QMessageBox::Cancel)) return;
-
-  QString dir = QFileDialog::getExistingDirectory(this, tr("Choose a directory to export the fit models to"), fitModelsPath, QFileDialog::ShowDirsOnly);
-  if (!dir.isEmpty()){
-    fitModelsPath = dir;
-
-    for (int i = 0; i<lst.count(); i++){
-      QString s = lst[i].simplified();
-      if (!s.isEmpty()){
-        NonLinearFit *fit = new NonLinearFit(this, 0);
-
-        int pos1 = s.find("(", 0);
-        fit->setObjectName(s.left(pos1));
-
-        int pos2 = s.find(")", pos1);
-        QString par = s.mid(pos1+4, pos2-pos1-4);
-        QStringList paramList = par.split(QRegExp("[,;]+[\\s]*"), QString::SkipEmptyParts);
-        fit->setParametersList(paramList);
-
-        QStringList l = s.split("=");
-        if (l.count() == 2)
-          fit->setFormula(l[1]);
-
-        fit->save(fitModelsPath + "/" + fit->objectName() + ".fit");
-      }
-    }
-  }
-}
-
-void ApplicationWindow::matrixDirectFFT()
-{
-  Matrix* m = (Matrix*)activeWindow(MatrixWindow);
-  if (!m)
-    return;
-
-  m->fft();
-}
-
-void ApplicationWindow::matrixInverseFFT()
-{
-  Matrix* m = (Matrix*)activeWindow(MatrixWindow);
-  if (!m)
-    return;
-
-  m->fft(true);
-}
-
-void ApplicationWindow::setFormatBarFont(const QFont& font)
-{
-  formatToolBar->setEnabled(true);
-
-  QFontComboBox *fb = (QFontComboBox *)formatToolBar->widgetForAction(actionFontBox);
-  fb->blockSignals(true);
-  fb->setCurrentFont(font);
-  fb->blockSignals(false);
-
-  QSpinBox *sb = (QSpinBox *)formatToolBar->widgetForAction(actionFontSize);
-  sb->blockSignals(true);
-  sb->setValue(font.pointSize());
-  sb->blockSignals(false);
-
-  actionFontBold->blockSignals(true);
-  actionFontBold->setChecked(font.bold());
-  actionFontBold->blockSignals(false);
-
-  actionFontItalic->blockSignals(true);
-  actionFontItalic->setChecked(font.italic());
-  actionFontItalic->blockSignals(false);
-
-  actionSubscript->setEnabled(false);
-  actionSuperscript->setEnabled(false);
-  actionUnderline->setEnabled(false);
-  actionGreekSymbol->setEnabled(false);
-  actionGreekMajSymbol->setEnabled(false);
-  actionMathSymbol->setEnabled(false);
-}
-
-void ApplicationWindow::setFontSize(int size)
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g)
-    return;
-
-  QFontComboBox *fb = (QFontComboBox *)formatToolBar->widgetForAction(actionFontBox);
-  QFont f(fb->currentFont().family(), size);
-  f.setBold(actionFontBold->isChecked());
-  f.setItalic(actionFontItalic->isChecked());
-  g->setCurrentFont(f);
-}
-
-void ApplicationWindow::setFontFamily(const QFont& font)
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g)
-    return;
-
-  QSpinBox *sb = (QSpinBox *)formatToolBar->widgetForAction(actionFontSize);
-  QFont f(font.family(), sb->value());
-  f.setBold(actionFontBold->isChecked());
-  f.setItalic(actionFontItalic->isChecked());
-  g->setCurrentFont(f);
-}
-
-void ApplicationWindow::setItalicFont(bool italic)
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g)
-    return;
-
-  QFontComboBox *fb = (QFontComboBox *)formatToolBar->widgetForAction(actionFontBox);
-  QSpinBox *sb = (QSpinBox *)formatToolBar->widgetForAction(actionFontSize);
-  QFont f(fb->currentFont().family(), sb->value());
-  f.setBold(actionFontBold->isChecked());
-  f.setItalic(italic);
-  g->setCurrentFont(f);
-}
-
-void ApplicationWindow::setBoldFont(bool bold)
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  Graph* g = plot->activeGraph();
-  if (!g)
-    return;
-
-  QFontComboBox *fb = (QFontComboBox *)formatToolBar->widgetForAction(actionFontBox);
-  QSpinBox *sb = (QSpinBox *)formatToolBar->widgetForAction(actionFontSize);
-  QFont f(fb->currentFont().family(), sb->value());
-  f.setBold(bold);
-  f.setItalic(actionFontItalic->isChecked());
-  g->setCurrentFont(f);
-}
-
-void ApplicationWindow::enableTextEditor(Graph *g)
-{
-  if (!g){
-    formatToolBar->setEnabled(false);
-    if (d_text_editor){
-      d_text_editor->close();
-      d_text_editor = NULL;
-    }
-  } else if (g) {
-    d_text_editor = new TextEditor(g);
-
-    formatToolBar->setEnabled(true);
-    actionSubscript->setEnabled(true);
-    actionSuperscript->setEnabled(true);
-    actionUnderline->setEnabled(true);
-    actionGreekSymbol->setEnabled(true);
-    actionGreekMajSymbol->setEnabled(true);
-    actionMathSymbol->setEnabled(true);
-  }
-}
-
-void ApplicationWindow::insertSuperscript()
-{
-  if (!d_text_editor)
-    return;
-
-  d_text_editor->formatText("<sup>","</sup>");
-}
-
-void ApplicationWindow::insertSubscript()
-{
-  if (!d_text_editor)
-    return;
-
-  d_text_editor->formatText("<sub>","</sub>");
-}
-
-void ApplicationWindow::underline()
-{
-  if (!d_text_editor)
-    return;
-
-  d_text_editor->formatText("<u>","</u>");
-}
-
-void ApplicationWindow::insertGreekSymbol()
-{
-  if (!d_text_editor)
-    return;
-
-  SymbolDialog *greekLetters = new SymbolDialog(SymbolDialog::lowerGreek, this);
-  connect(greekLetters, SIGNAL(addLetter(const QString&)), d_text_editor, SLOT(addSymbol(const QString&)));
-  greekLetters->exec();
-}
-
-void ApplicationWindow::insertGreekMajSymbol()
-{
-  if (!d_text_editor)
-    return;
-
-  SymbolDialog *greekLetters = new SymbolDialog(SymbolDialog::upperGreek, this);
-  connect(greekLetters, SIGNAL(addLetter(const QString&)), d_text_editor, SLOT(addSymbol(const QString&)));
-  greekLetters->exec();
-}
-
-void ApplicationWindow::insertMathSymbol()
-{
-  if (!d_text_editor)
-    return;
-
-  SymbolDialog *ms = new SymbolDialog(SymbolDialog::mathSymbols, this);
-  connect(ms, SIGNAL(addLetter(const QString&)), d_text_editor, SLOT(addSymbol(const QString&)));
-  ms->exec();
-}
-
-void ApplicationWindow::showCustomActionDialog()
-{
-  ManageCustomMenus *ad = new ManageCustomMenus(this);
-  ad->setAttribute(Qt::WA_DeleteOnClose);
-  ad->show();
-  ad->setFocus();
-}
-
-void ApplicationWindow::showUserDirectoryDialog()
-{
-  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
-  ad->show();
-  ad->setFocus();
-}
-
-void ApplicationWindow::addCustomAction(QAction *action, const QString& parentName, int index)
-{
-  if (!action)
-    return;
-
-  QList<QToolBar *> toolBars = toolBarsList();
-  foreach (QToolBar *t, toolBars){
-    if (t->objectName() == parentName){
-      t->addAction(action);
-      if (index < 0)
-        d_user_actions << action;
-      else if (index >= 0 && index < d_user_actions.size())
-        d_user_actions.replace(index, action);
-      return;
-    }
-  }
-
-  QList<QMenu *> menus = customizableMenusList();
-  foreach (QMenu *m, menus){
-    if (m->objectName() == parentName){
-      m->addAction(action);
-      if (index < 0)
-        d_user_actions << action;
-      else if (index >= 0 && index < d_user_actions.size())
-        d_user_actions.replace(index, action);
-      return;
-    }
-  }
-}
-
-void ApplicationWindow::reloadCustomActions()
-{
-  QList<QMenu *> menus = customizableMenusList();
-  foreach(QAction *a, d_user_actions){
-    if (!a->statusTip().isEmpty()){
-      foreach (QMenu *m, menus){
-        if (m->objectName() == a->statusTip()){
-          QList<QAction *> lst = m->actions();
-          if (!lst.contains(a))
-            m->addAction(a);
-        }
-      }
-    }
-  }
-}
-
-void ApplicationWindow::removeCustomAction(QAction *action)
-{
-  int index = d_user_actions.indexOf(action);
-  if (index >= 0 && index < d_user_actions.count()){
-    d_user_actions.removeAt(index);
-    delete action;
-  }
-}
-
-void ApplicationWindow::performCustomAction(QAction *action)
-{
-  if (!action || !d_user_actions.contains(action))
-    return;
-#ifdef SCRIPTING_PYTHON
-QString action_data = action->data().toString();
-if( QFileInfo(action_data).exists() )
-{
-  QFile script_file(action_data);
-  if ( !script_file.open(IO_ReadOnly) )
-  {
-    QMessageBox::information(this, "MantidPlot", "Error: There was a problem reading\n" + action_data);
-    return;
-  }
-  
-  QTextStream stream(&script_file);
-  QString scriptPath = QString("r'%1'").arg(QFileInfo(action_data).absolutePath());
-  QString code = QString("sys.path.append(%1)\n").arg(scriptPath);
-    runPythonScript(code, true);
-  code = "";
-  while( !stream.atEnd() )
-  {
-    code.append(stream.readLine() + "\n");
-  }
-  runPythonScript(code);
-  code = "";
-  code.append(QString("\nsys.path.remove(%1)").arg(scriptPath));
-    runPythonScript(code, true);
-}
-else
-{
-  //First search for an existing window
-  foreach( QMdiSubWindow* sub_win, d_workspace->subWindowList() )
-  {
-    if( sub_win->widget()->objectName() == action_data )
-    {
-      sub_win->widget()->show();
-      return;
-    }
-  }
-
-  QMdiSubWindow* usr_win = new QMdiSubWindow;
-  usr_win->setAttribute(Qt::WA_DeleteOnClose, false);
-  MantidQt::API::UserSubWindow *user_interface = MantidQt::API::InterfaceManager::Instance().createSubWindow(action_data, usr_win);
-  if(user_interface)
-  {
-    setGeometry(usr_win,user_interface);
-    connect(user_interface, SIGNAL(runAsPythonScript(const QString&)), this,
-        SLOT(runPythonScript(const QString&)));
-    user_interface->initializeLocalPython();
-  }
-  else
-  {
-    delete usr_win;
-  }
-
-}
-#else
-QMessageBox::critical(this, tr("MantidPlot") + " - " + tr("Error"),//Mantid
-    tr("MantidPlot was not built with Python scripting support included!"));
-#endif
-}
-
-void ApplicationWindow::runPythonScript(const QString & code, bool quiet)
-{
-  if( code.isEmpty() || scriptingEnv()->isRunning() ) return;
-
-  if( m_iface_script == NULL )
-  {
-    setScriptingLanguage("Python");
-    m_iface_script = scriptingEnv()->newScript("",this,false, "");
-    m_iface_script->setLineOffset(0);
-    connect(m_iface_script, SIGNAL(print(const QString &)), this, SLOT(scriptPrint(const QString&)));
-    connect(m_iface_script, SIGNAL(error(const QString &, const QString&, int)), this, 
-        SLOT(scriptPrint(const QString &)));
-
-  }
-
-  m_iface_script->setCode(code);
-  if( !quiet )
+  return lst;
+}
+
+void ApplicationWindow::hideSelectedColumns()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (t)
+    t->hideSelectedColumns();
+}
+
+void ApplicationWindow::showAllColumns()
+{
+  Table *t = (Table *)activeWindow(TableWindow);
+  if (t)
+    t->showAllColumns();
+}
+
+void ApplicationWindow::setMatrixUndoStackSize(int size)
+{
+  if (d_matrix_undo_stack_size == size)
+    return;
+
+  d_matrix_undo_stack_size = size;
+  Folder *f = projectFolder();
+  while (f){
+    QList<MdiSubWindow *> folderWindows = f->windowsList();
+    foreach(MdiSubWindow *w, folderWindows){
+      if (w->isA("Matrix")){
+        QUndoStack *stack = ((Matrix *)w)->undoStack();
+        if (!stack->count())// undo limit can only be changed for empty stacks
+          stack->setUndoLimit(size);
+      }
+    }
+    f = f->folderBelow();
+  }
+}
+
+//! This is a dirty hack: sometimes the workspace area and the windows are not redrawn properly
+// after a MultiLayer plot window is resized by the user: Qt bug?
+void ApplicationWindow::repaintWindows()
+{
+  if (d_opening_file || (d_active_window && d_active_window->status() == MdiSubWindow::Maximized))
+    return;
+
+  QWidget *viewPort = d_workspace->viewport();
+  QSize size = viewPort->size();
+  viewPort->resize(QSize(size.width() + 1, size.height() + 1));
+  viewPort->resize(size);
+}
+
+QString ApplicationWindow::endOfLine()
+{
+  switch(d_eol){
+  case LF:
+    return "\n";
+    break;
+  case CRLF:
+    return "\r\n";
+    break;
+  case CR:
+    return "\r";
+    break;
+  }
+  return "\n";
+}
+
+/**  Switch on the right tool buttons associated with a MultiLayer window
+ *   @param w :: The active MultiLayer window.
+ */
+void ApplicationWindow::customMultilayerToolButtons(MultiLayer* w)
+{
+  if (!w)
   {
-    // Output a message to say we've started
-    scriptPrint("Script execution started.", false, true);
+    btnPointer->setOn(true);
+    return;
   }
-  bool success = m_iface_script->exec();
-  if(success && !quiet)
+
+  Graph* g = w->activeGraph();
+  if (g)
   {
-    scriptPrint("Script execution completed successfully.", false, true);
+    PlotToolInterface* tool = g->activeTool();
+    if (g->zoomOn())
+      btnZoomIn->setOn(true);
+
+    else if (g->areRangeSelectorsOn())
+      btnSelect->setOn(true);
+    //else if (dynamic_cast<PeakPickerTool1D*>(tool))
+    //  btnPeakPick->setOn(true);
+    else if (dynamic_cast<PeakPickerTool*>(tool))
+      btnMultiPeakPick->setOn(true);
+    else if (dynamic_cast<DataPickerTool*>(tool))
+    {
+      switch(((DataPickerTool*)tool)->getMode())
+      {
+      case DataPickerTool::Move:
+        btnMovePoints->setOn(true);
+        break;
+      case DataPickerTool::Remove:
+        btnRemovePoints->setOn(true);
+        break;
+      case DataPickerTool::Display:
+        btnCursor->setOn(true);
+        break;
+      default:
+        btnPointer->setOn(true);
+      }
+    }
+    else if (dynamic_cast<DrawPointTool*>(tool))
+      actionDrawPoints->setOn(true);
+    else if (dynamic_cast<ScreenPickerTool*>(tool))
+      btnPicker->setOn(true);
+    else
+      btnPointer->setOn(true);
   }
-    
-}
-
-void ApplicationWindow::loadCustomActions()
-{
-  QString path = customActionsDirPath + "/";
-  QDir dir(path);
-  QStringList lst = dir.entryList(QDir::Files|QDir::NoSymLinks, QDir::Name);
-  for (int i=0; i<lst.count(); i++){
-    QString fileName = path + lst[i];
-    QFile file(fileName);
-    QFileInfo fi(file);
-    if (!file.open(QFile::ReadOnly | QFile::Text))
-      continue;
-
-    QAction *action = new QAction(this);
-    CustomActionHandler handler(action);
-    QXmlSimpleReader reader;
-    reader.setContentHandler(&handler);
-    reader.setErrorHandler(&handler);
-
-    QXmlInputSource xmlInputSource(&file);
-    if (reader.parse(xmlInputSource))
-      addCustomAction(action, handler.parentName());
-  }
-}
-
-QList<QMenu *> ApplicationWindow::customizableMenusList()
-{
-  QList<QMenu *> lst;
-  lst << 	windowsMenu << view << graph << fileMenu << format << edit;
-  lst << help << plot2DMenu << analysisMenu << multiPeakMenu;
-  lst << matrixMenu << plot3DMenu << plotDataMenu ;// scriptingMenu;
-  lst << tableMenu << fillMenu << normMenu << newMenu << exportPlotMenu << smoothMenu;
-  lst << filterMenu << decayMenu;
-  return lst;
-}
-
-//-------------------------------
-// Mantid
-void ApplicationWindow::addUserMenu(const QString & topMenu)
-{
-  if( topMenu.isEmpty() ) return;
-
-  foreach(QMenu* menu, d_user_menus)
-  {
-    if( menu->title() == topMenu ) return;
-  }
-
-  QMenu* customMenu = new QMenu(topMenu);
-  customMenu->setTitle(topMenu);
-  customMenu->setName(topMenu);
-  connect(customMenu, SIGNAL(triggered(QAction*)), this, SLOT(performCustomAction(QAction*)));
-  d_user_menus.append(customMenu);
-  menuBar()->insertItem(tr(topMenu), customMenu);
-}
-
-void ApplicationWindow::addUserMenuAction(const QString & parentMenu, const QString & itemName, const QString & itemData)
-{
-  QMenu* topMenu(NULL);
-  foreach(topMenu, d_user_menus)
-  {
-    if( topMenu->title() == parentMenu ) break;
-  } 
-
-  if( !topMenu ) return;
-  foreach(QAction* userAction, topMenu->actions())
-  {
-    if( userAction->text() == itemName ) return;
-  }
-
-  QAction* scriptAction = new QAction(tr(itemName), topMenu);
-  scriptAction->setData(itemData); 
-  topMenu->addAction(scriptAction);
-  d_user_actions.append(scriptAction);
-
-  // Remove name from the list of removed interfaces if applicable
-  removed_interfaces.remove(itemName);
-}
-
-void ApplicationWindow::removeUserMenu(const QString & parentMenu)
-{
-  int i(0);
-  QMenu *menu = NULL;
-  foreach(menu, d_user_menus)
-  {
-    if( menu->title() == parentMenu ) break;
-    ++i;
-  }
-  if( !menu ) return; 
-
-  d_user_menus.removeAt(i);
-  menuBar()->removeAction(menu->menuAction());
-}
-
-void ApplicationWindow::removeUserMenuAction(const QString & parentMenu, const QString & userAction)
-{
-  QMenu *menu = NULL;
-  foreach(menu, d_user_menus)
-  {
-    if( menu->title() == parentMenu ) break;
-  }
-  if( !menu ) return;
-
-  QAction *action = NULL;
-  int menu_count(0);
-  foreach(action, d_user_actions)
-  {
-    if( action->text() == userAction ) break;
-    ++menu_count;
-  }
-  if( !action ) return;
-
-  d_user_actions.removeAt(menu_count);
-  menu->removeAction(action);
-
-  // Add interface name to the list of removed interfaces
-  removed_interfaces.append(userAction);
-}
-
-const QList<QMenu*> & ApplicationWindow::getCustomMenus() const
-{
-  return d_user_menus;
-} 
-
-QList<QMenu *> ApplicationWindow::menusList()
-{
-  QList<QMenu *> lst;
-  QObjectList children = this->children();
-  foreach (QObject *w, children){
-    if (w->isA("QMenu"))
-      lst << (QMenu *)w;
-  }
-  return lst;
-}
-
-// End of a section of Mantid custom functions
-//-------------------------------------------
-
-QList<QToolBar *> ApplicationWindow::toolBarsList()
-{
-  QList<QToolBar *> lst;
-  QObjectList children = this->children();
-  foreach (QObject *w, children){
-    if (w->isA("QToolBar"))
-      lst << (QToolBar *)w;
-  }
-  return lst;
-}
-
-void ApplicationWindow::hideSelectedColumns()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (t)
-    t->hideSelectedColumns();
-}
-
-void ApplicationWindow::showAllColumns()
-{
-  Table *t = (Table *)activeWindow(TableWindow);
-  if (t)
-    t->showAllColumns();
-}
-
-void ApplicationWindow::setMatrixUndoStackSize(int size)
-{
-  if (d_matrix_undo_stack_size == size)
-    return;
-
-  d_matrix_undo_stack_size = size;
-  Folder *f = projectFolder();
-  while (f){
-    QList<MdiSubWindow *> folderWindows = f->windowsList();
-    foreach(MdiSubWindow *w, folderWindows){
-      if (w->isA("Matrix")){
-        QUndoStack *stack = ((Matrix *)w)->undoStack();
-        if (!stack->count())// undo limit can only be changed for empty stacks
-          stack->setUndoLimit(size);
-      }
-    }
-    f = f->folderBelow();
-  }
-}
-
-//! This is a dirty hack: sometimes the workspace area and the windows are not redrawn properly
-// after a MultiLayer plot window is resized by the user: Qt bug?
-void ApplicationWindow::repaintWindows()
-{
-  if (d_opening_file || (d_active_window && d_active_window->status() == MdiSubWindow::Maximized))
-    return;
-
-  QWidget *viewPort = d_workspace->viewport();
-  QSize size = viewPort->size();
-  viewPort->resize(QSize(size.width() + 1, size.height() + 1));
-  viewPort->resize(size);
-}
-
-QString ApplicationWindow::endOfLine()
-{
-  switch(d_eol){
-  case LF:
-    return "\n";
-    break;
-  case CRLF:
-    return "\r\n";
-    break;
-  case CR:
-    return "\r";
-    break;
-  }
-  return "\n";
-}
-
-/**  Switch on the right tool buttons associated with a MultiLayer window
- *   @param w :: The active MultiLayer window.
- */
-void ApplicationWindow::customMultilayerToolButtons(MultiLayer* w)
-{
-  if (!w)
-  {
-    btnPointer->setOn(true);
-    return;
-  }
-
-  Graph* g = w->activeGraph();
-  if (g)
-  {
-    PlotToolInterface* tool = g->activeTool();
-    if (g->zoomOn())
-      btnZoomIn->setOn(true);
-
-    else if (g->areRangeSelectorsOn())
-      btnSelect->setOn(true);
-    //else if (dynamic_cast<PeakPickerTool1D*>(tool))
-    //  btnPeakPick->setOn(true);
-    else if (dynamic_cast<PeakPickerTool*>(tool))
-      btnMultiPeakPick->setOn(true);
-    else if (dynamic_cast<DataPickerTool*>(tool))
-    {
-      switch(((DataPickerTool*)tool)->getMode())
-      {
-      case DataPickerTool::Move:
-        btnMovePoints->setOn(true);
-        break;
-      case DataPickerTool::Remove:
-        btnRemovePoints->setOn(true);
-        break;
-      case DataPickerTool::Display:
-        btnCursor->setOn(true);
-        break;
-      default:
-        btnPointer->setOn(true);
-      }
-    }
-    else if (dynamic_cast<DrawPointTool*>(tool))
-      actionDrawPoints->setOn(true);
-    else if (dynamic_cast<ScreenPickerTool*>(tool))
-      btnPicker->setOn(true);
-    else
-      btnPointer->setOn(true);
-  }
-  else
-    btnPointer->setOn(true);
-}
-/**  save workspace data in nexus format
- *   @param wsName :: name of the ouput file.
- *   @param fileName :: name of the ouput file.
- */
-void ApplicationWindow::savedatainNexusFormat(const std::string& wsName,const std::string& fileName)
-{		
-  //std::string s=workingDir.toStdString()+wsName+".nxs";
-  // std::string fileName(s);
-  if(fileName.empty()) return ;
-  try
-  {
-    if(mantidUI)mantidUI->savedatainNexusFormat(fileName,wsName);
-  }
-  catch(...)
-  {
-  }
-}
-void ApplicationWindow::enablesaveNexus(const QString &wsName)
-{
-  if(actionSaveFile) actionSaveFile->setEnabled(true);
-  m_nexusInputWSName=wsName;
-}
-/* For zooming the selected graph using the drag canvas tool and mouse drag.
- */
-void ApplicationWindow::magnify()
-{
-  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
-  if (!plot)
-    return;
-
-  if (plot->isEmpty()){
-    QMessageBox::warning(this, tr("QtiPlot - Warning"),
-        tr("<h4>There are no plot layers available in this window.</h4>"
-            "<p><h4>Please add a layer and try again!</h4>"));
-    btnPointer->setOn(true);
-    return;
-  }
-
-  QList<Graph *> layers = plot->layersList();
-  foreach(Graph *g, layers)
-  g->enablePanningMagnifier();
-}
-/// Handler for ICat Login Menu
-void ApplicationWindow::ICatLogin()
-{
-  mantidUI->executeAlgorithm("CatalogLogin",1);
-}
-
-void ApplicationWindow::ICatIsisSearch()
-{	
-  QMdiSubWindow* usr_win = new QMdiSubWindow(this);
-  usr_win->setAttribute(Qt::WA_DeleteOnClose, false);
-  QWidget* icatsearch_interface = new MantidQt::MantidWidgets::ICatSearch(usr_win);
-  if(icatsearch_interface)
-  {
-    setGeometry(usr_win,icatsearch_interface);
-  }
-  else
-  {
-    delete usr_win;
-  }
-}
-void ApplicationWindow::ICatMyDataSearch()
-{	
-  QMdiSubWindow* usr_win = new QMdiSubWindow(this);
-  usr_win->setAttribute(Qt::WA_DeleteOnClose, false);
-  QWidget* mydatsearch = new MantidQt::MantidWidgets::ICatMyDataSearch(usr_win);
-  if(mydatsearch)
-  {
-    setGeometry(usr_win,mydatsearch);
-  }
-  else
-  {
-    delete usr_win;
-  }
-}
-void ApplicationWindow ::ICatAdvancedSearch()
-{
-  QMdiSubWindow* usr_win = new QMdiSubWindow(this);
-  usr_win->setAttribute(Qt::WA_DeleteOnClose, false);
-  QWidget* advanced_search = new MantidQt::MantidWidgets::ICatAdvancedSearch(usr_win);
-  if(advanced_search)
-  {
-    setGeometry(usr_win,advanced_search);
-  }
-  else
-  {
-    delete usr_win;
-  }
-}
-void ApplicationWindow::setGeometry(QMdiSubWindow* usr_win,QWidget* user_interface)
-{   
-  QRect frame = QRect(usr_win->frameGeometry().topLeft() - usr_win->geometry().topLeft(),
-      usr_win->geometry().bottomRight() - usr_win->geometry().bottomRight());
-  usr_win->setWidget(user_interface);
-  QRect iface_geom = QRect(frame.topLeft() + user_interface->geometry().topLeft(),
-      frame.bottomRight() + user_interface->geometry().bottomRight());
-  usr_win->setGeometry(iface_geom);
-  d_workspace->addSubWindow(usr_win);
-  usr_win->show();
-
-
-
-}
-void ApplicationWindow::ICatLogout()
-{
-  mantidUI->executeICatLogout(-1);
-}
-
-/**
- * Write a message to the log window
- * @param message :: A string containing the message
- * @param error :: A boolean indicating if this is an error
- */
-void ApplicationWindow::writeToLogWindow(const QString& message,bool error)
-{		
-  if(error)
-  {
-    results->setTextColor(Qt::red);
-  }
-  else
-  {
-    results->setTextColor(Qt::black);
-  }
-  QTextCursor cursor = results->textCursor();
-  cursor.movePosition(QTextCursor::End);
-  results->setTextCursor(cursor);
-  results->insertPlainText(message + "\n");
-  cursor = results->textCursor();
-  cursor.movePosition(QTextCursor::End);
-}
-
-  /**
-  * Write an error message to the log window (convenience slot)
-  * @param message :: The string to send the log window
-  */
-  void ApplicationWindow::writeErrorToLogWindow(const QString& message)
-  {
-    writeToLogWindow(message, true);
-  }
-
-/* This method executes loadraw asynchrnously
- * @param  fileName - name of the file to load
- * @param wsName :: -name of the workspace to store data
- */
-void ApplicationWindow::executeLoadRawAsynch(const QString& fileName,const QString& wsName )
-{
-  mantidUI->loadrawfromICatInterface(fileName,wsName);
-}
-
-/* This method executes loadnexus asynchrnously
- * @param  fileName - name of the file to load
- * @param wsName :: -name of the workspace to store data
- */
-void ApplicationWindow::executeLoadNexusAsynch(const QString& fileName,const QString& wsName)
-{
-  mantidUI->loadnexusfromICatInterface(fileName,wsName);
-}
-
-/* This method executes Download data files algorithm
- * @param  filenames - list of the file names to download
- */
-void ApplicationWindow::executeDownloadDataFiles(const std::vector<std::string>& filenNames,const std::vector<long long>& fileIds)
-{
-  //getting the sender of the signal(it's ICatInvestigation object)
-  QObject* qsender= sender();
-  if(!qsender) return;
-
-  // connecting  filelocations signal to ICatInvestigation slot setfileLocations
-  // This is to send the filelocations vector  after  algorithm execution to ICatInvestigation object(which is MnatidQt) for further processing
-  connect(mantidUI,SIGNAL(fileLocations(const std::vector<std::string>&)),qsender,SLOT(setfileLocations(const std::vector<std::string>&)));
-  /// execute the algorithm
-  mantidUI->executeDownloadDataFiles(filenNames,fileIds);
-}
-
-void  ApplicationWindow::executeloadAlgorithm(const QString& algName,const QString& fileName, const QString& wsName)
-{
-  mantidUI->executeloadAlgorithm(algName,fileName,wsName);
-}
-
+  else
+    btnPointer->setOn(true);
+}
+/**  save workspace data in nexus format
+ *   @param wsName :: name of the ouput file.
+ *   @param fileName :: name of the ouput file.
+ */
+void ApplicationWindow::savedatainNexusFormat(const std::string& wsName,const std::string& fileName)
+{		
+  //std::string s=workingDir.toStdString()+wsName+".nxs";
+  // std::string fileName(s);
+  if(fileName.empty()) return ;
+  try
+  {
+    if(mantidUI)mantidUI->savedatainNexusFormat(fileName,wsName);
+  }
+  catch(...)
+  {
+  }
+}
+void ApplicationWindow::enablesaveNexus(const QString &wsName)
+{
+  if(actionSaveFile) actionSaveFile->setEnabled(true);
+  m_nexusInputWSName=wsName;
+}
+/* For zooming the selected graph using the drag canvas tool and mouse drag.
+ */
+void ApplicationWindow::magnify()
+{
+  MultiLayer *plot = (MultiLayer *)activeWindow(MultiLayerWindow);
+  if (!plot)
+    return;
+
+  if (plot->isEmpty()){
+    QMessageBox::warning(this, tr("QtiPlot - Warning"),
+        tr("<h4>There are no plot layers available in this window.</h4>"
+            "<p><h4>Please add a layer and try again!</h4>"));
+    btnPointer->setOn(true);
+    return;
+  }
+
+  QList<Graph *> layers = plot->layersList();
+  foreach(Graph *g, layers)
+  g->enablePanningMagnifier();
+}
+/// Handler for ICat Login Menu
+void ApplicationWindow::ICatLogin()
+{
+  mantidUI->executeAlgorithm("CatalogLogin",1);
+}
+
+void ApplicationWindow::ICatIsisSearch()
+{	
+  QMdiSubWindow* usr_win = new QMdiSubWindow(this);
+  usr_win->setAttribute(Qt::WA_DeleteOnClose, false);
+  QWidget* icatsearch_interface = new MantidQt::MantidWidgets::ICatSearch(usr_win);
+  if(icatsearch_interface)
+  {
+    setGeometry(usr_win,icatsearch_interface);
+  }
+  else
+  {
+    delete usr_win;
+  }
+}
+void ApplicationWindow::ICatMyDataSearch()
+{	
+  QMdiSubWindow* usr_win = new QMdiSubWindow(this);
+  usr_win->setAttribute(Qt::WA_DeleteOnClose, false);
+  QWidget* mydatsearch = new MantidQt::MantidWidgets::ICatMyDataSearch(usr_win);
+  if(mydatsearch)
+  {
+    setGeometry(usr_win,mydatsearch);
+  }
+  else
+  {
+    delete usr_win;
+  }
+}
+void ApplicationWindow ::ICatAdvancedSearch()
+{
+  QMdiSubWindow* usr_win = new QMdiSubWindow(this);
+  usr_win->setAttribute(Qt::WA_DeleteOnClose, false);
+  QWidget* advanced_search = new MantidQt::MantidWidgets::ICatAdvancedSearch(usr_win);
+  if(advanced_search)
+  {
+    setGeometry(usr_win,advanced_search);
+  }
+  else
+  {
+    delete usr_win;
+  }
+}
+void ApplicationWindow::setGeometry(QMdiSubWindow* usr_win,QWidget* user_interface)
+{   
+  QRect frame = QRect(usr_win->frameGeometry().topLeft() - usr_win->geometry().topLeft(),
+      usr_win->geometry().bottomRight() - usr_win->geometry().bottomRight());
+  usr_win->setWidget(user_interface);
+  QRect iface_geom = QRect(frame.topLeft() + user_interface->geometry().topLeft(),
+      frame.bottomRight() + user_interface->geometry().bottomRight());
+  usr_win->setGeometry(iface_geom);
+  d_workspace->addSubWindow(usr_win);
+  usr_win->show();
+
+
+
+}
+void ApplicationWindow::ICatLogout()
+{
+  mantidUI->executeICatLogout(-1);
+}
+
+/**
+ * Write a message to the log window
+ * @param message :: A string containing the message
+ * @param error :: A boolean indicating if this is an error
+ */
+void ApplicationWindow::writeToLogWindow(const QString& message,bool error)
+{		
+  if(error)
+  {
+    results->setTextColor(Qt::red);
+  }
+  else
+  {
+    results->setTextColor(Qt::black);
+  }
+  QTextCursor cursor = results->textCursor();
+  cursor.movePosition(QTextCursor::End);
+  results->setTextCursor(cursor);
+  results->insertPlainText(message + "\n");
+  cursor = results->textCursor();
+  cursor.movePosition(QTextCursor::End);
+}
+
+  /**
+  * Write an error message to the log window (convenience slot)
+  * @param message :: The string to send the log window
+  */
+  void ApplicationWindow::writeErrorToLogWindow(const QString& message)
+  {
+    writeToLogWindow(message, true);
+  }
+
+/* This method executes loadraw asynchrnously
+ * @param  fileName - name of the file to load
+ * @param wsName :: -name of the workspace to store data
+ */
+void ApplicationWindow::executeLoadRawAsynch(const QString& fileName,const QString& wsName )
+{
+  mantidUI->loadrawfromICatInterface(fileName,wsName);
+}
+
+/* This method executes loadnexus asynchrnously
+ * @param  fileName - name of the file to load
+ * @param wsName :: -name of the workspace to store data
+ */
+void ApplicationWindow::executeLoadNexusAsynch(const QString& fileName,const QString& wsName)
+{
+  mantidUI->loadnexusfromICatInterface(fileName,wsName);
+}
+
+/* This method executes Download data files algorithm
+ * @param  filenames - list of the file names to download
+ */
+void ApplicationWindow::executeDownloadDataFiles(const std::vector<std::string>& filenNames,const std::vector<long long>& fileIds)
+{
+  //getting the sender of the signal(it's ICatInvestigation object)
+  QObject* qsender= sender();
+  if(!qsender) return;
+
+  // connecting  filelocations signal to ICatInvestigation slot setfileLocations
+  // This is to send the filelocations vector  after  algorithm execution to ICatInvestigation object(which is MnatidQt) for further processing
+  connect(mantidUI,SIGNAL(fileLocations(const std::vector<std::string>&)),qsender,SLOT(setfileLocations(const std::vector<std::string>&)));
+  /// execute the algorithm
+  mantidUI->executeDownloadDataFiles(filenNames,fileIds);
+}
+
+void  ApplicationWindow::executeloadAlgorithm(const QString& algName,const QString& fileName, const QString& wsName)
+{
+  mantidUI->executeloadAlgorithm(algName,fileName,wsName);
+}
+
diff --git a/Code/Mantid/MantidPlot/src/AssociationsDialog.cpp b/Code/Mantid/MantidPlot/src/AssociationsDialog.cpp
index fea9df70a4efd586c18f8e14adf7a4c46f5a2281..99b4c7aa17b481a13942e0468a4184f1865c6347 100644
--- a/Code/Mantid/MantidPlot/src/AssociationsDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/AssociationsDialog.cpp
@@ -254,7 +254,7 @@ 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);
@@ -284,7 +284,7 @@ for (int i=0; i < table->rowCount(); i++ )
 
 bool xerr = false, yerr = false, vectors = false;
 QString errColName, xEndColName, yEndColName;
-if (n > 2){
+if (n > 2){
 	table->showColumn(3);
 	table->showColumn(4);
 
@@ -356,10 +356,10 @@ void AssociationsDialog::setGraph(Graph *g)
             continue;
 
         if (((DataCurve *)it)->type() != Graph::Function){
-            QString s = ((DataCurve *)it)->plotAssociation();
+            QString s = ((DataCurve *)it)->plotAssociation();
             if (((DataCurve *)it)->table()){
                 QString table = ((DataCurve *)it)->table()->objectName();
-                plotAssociationsList << table + ": " + s.remove(table + "_");
+                plotAssociationsList << table + ": " + s.remove(table + "_");
             }
         }
 	}
diff --git a/Code/Mantid/MantidPlot/src/AxesDialog.cpp b/Code/Mantid/MantidPlot/src/AxesDialog.cpp
index 6f6ac8d113eb83d98b71dc176016b68209608111..27abad9667159964d7e0b5cbad748a1b06ffca6d 100644
--- a/Code/Mantid/MantidPlot/src/AxesDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/AxesDialog.cpp
@@ -56,8 +56,8 @@
 #include <QListWidget>
 #include <QVector>
 #include <QGroupBox>
-#include <QDateTimeEdit>
-#include <QTimeEdit>
+#include <QDateTimeEdit>
+#include <QTimeEdit>
 
 #include <qwt_plot.h>
 #include <qwt_scale_widget.h>
@@ -1222,12 +1222,12 @@ AxesDialog::AxesDialog( QWidget* parent, Qt::WFlags fl )
     connect( buttonOk, SIGNAL( clicked() ), this, SLOT( accept() ) );
     connect( buttonCancel, SIGNAL( clicked() ), this, SLOT( reject() ) );
     connect( buttonApply, SIGNAL( clicked() ), this, SLOT(updatePlot() ) );
-    connect( generalDialog, SIGNAL( currentChanged ( QWidget * ) ),
+    connect( generalDialog, SIGNAL( currentChanged ( QWidget * ) ),
             this, SLOT(pageChanged ( QWidget * ) ) );
 }
 
 void AxesDialog::initScalesPage()
-{
+{
     ApplicationWindow *app = (ApplicationWindow *)parent();
 	scalesPage = new QWidget();
 
@@ -1235,33 +1235,33 @@ void AxesDialog::initScalesPage()
 	QGridLayout * middleLayout = new QGridLayout(middleBox);
 
 	middleLayout->addWidget(new QLabel(tr( "From" )), 0, 0);
-	boxStart = new DoubleSpinBox();
-	boxStart->setLocale(app->locale());
+	boxStart = new DoubleSpinBox();
+	boxStart->setLocale(app->locale());
     boxStart->setDecimals(app->d_decimal_digits);
-	middleLayout->addWidget( boxStart, 0, 1 );
-
-	boxStartDateTime = new QDateTimeEdit();
-	boxStartDateTime->setCalendarPopup(true);
-	middleLayout->addWidget( boxStartDateTime, 0, 1 );
-	boxStartDateTime->hide();
-
-	boxStartTime = new QTimeEdit();
-	middleLayout->addWidget(boxStartTime, 0, 1 );
-	boxStartTime->hide();
+	middleLayout->addWidget( boxStart, 0, 1 );
+
+	boxStartDateTime = new QDateTimeEdit();
+	boxStartDateTime->setCalendarPopup(true);
+	middleLayout->addWidget( boxStartDateTime, 0, 1 );
+	boxStartDateTime->hide();
+
+	boxStartTime = new QTimeEdit();
+	middleLayout->addWidget(boxStartTime, 0, 1 );
+	boxStartTime->hide();
 
 	middleLayout->addWidget(new QLabel(tr( "To" )), 1, 0);
-	boxEnd = new DoubleSpinBox();
-	boxEnd->setLocale(app->locale());
+	boxEnd = new DoubleSpinBox();
+	boxEnd->setLocale(app->locale());
     boxEnd->setDecimals(app->d_decimal_digits);
-	middleLayout->addWidget( boxEnd, 1, 1);
-
-    boxEndDateTime = new QDateTimeEdit();
-    boxEndDateTime->setCalendarPopup(true);
-    middleLayout->addWidget(boxEndDateTime, 1, 1);
-    boxEndDateTime->hide();
-
-    boxEndTime = new QTimeEdit();
-    middleLayout->addWidget(boxEndTime, 1, 1);
+	middleLayout->addWidget( boxEnd, 1, 1);
+
+    boxEndDateTime = new QDateTimeEdit();
+    boxEndDateTime->setCalendarPopup(true);
+    middleLayout->addWidget(boxEndDateTime, 1, 1);
+    boxEndDateTime->hide();
+
+    boxEndTime = new QTimeEdit();
+    middleLayout->addWidget(boxEndTime, 1, 1);
     boxEndTime->hide();
 
 	boxScaleTypeLabel = new QLabel(tr( "Type" ));
@@ -1296,53 +1296,53 @@ void AxesDialog::initScalesPage()
 	boxBreakEnd->setLocale(app->locale());
     boxBreakEnd->setDecimals(app->d_decimal_digits);
 	breaksLayout->addWidget(boxBreakEnd, 2, 1);
-
-    breaksLayout->addWidget(new QLabel(tr("Position")), 3, 0);
+
+    breaksLayout->addWidget(new QLabel(tr("Position")), 3, 0);
     boxBreakPosition = new QSpinBox();
-	boxBreakPosition->setSuffix(" (" + tr("% of Axis Length") + ")");
-    breaksLayout->addWidget(boxBreakPosition, 3, 1);
+	boxBreakPosition->setSuffix(" (" + tr("% of Axis Length") + ")");
+    breaksLayout->addWidget(boxBreakPosition, 3, 1);
 
 	breaksLayout->addWidget(new QLabel(tr("Width")), 4, 0);
 	boxBreakWidth = new QSpinBox();
 	boxBreakWidth->setSuffix(" (" + tr("pixels") + ")");
 	breaksLayout->addWidget(boxBreakWidth, 4, 1);
-
-    boxLog10AfterBreak = new QCheckBox(tr("&Log10 Scale After Break"));
-    breaksLayout->addWidget(boxLog10AfterBreak, 0, 3);
-
-    breaksLayout->addWidget(new QLabel(tr("Step Before Break")), 1, 2);
-    boxStepBeforeBreak = new DoubleSpinBox();
-    boxStepBeforeBreak->setMinimum(0.0);
-    boxStepBeforeBreak->setSpecialValueText(tr("Guess"));
-	boxStepBeforeBreak->setLocale(app->locale());
-    boxStepBeforeBreak->setDecimals(app->d_decimal_digits);
-	breaksLayout->addWidget(boxStepBeforeBreak, 1, 3);
-
-    breaksLayout->addWidget(new QLabel(tr("Step After Break")), 2, 2);
-    boxStepAfterBreak = new DoubleSpinBox();
-    boxStepAfterBreak->setMinimum(0.0);
-    boxStepAfterBreak->setSpecialValueText(tr("Guess"));
-	boxStepAfterBreak->setLocale(app->locale());
-    boxStepAfterBreak->setDecimals(app->d_decimal_digits);
-	breaksLayout->addWidget(boxStepAfterBreak, 2, 3);
-
-    breaksLayout->addWidget(new QLabel(tr("Minor Ticks Before")), 3, 2);
-    boxMinorTicksBeforeBreak = new QComboBox();
-	boxMinorTicksBeforeBreak->setEditable(true);
-	boxMinorTicksBeforeBreak->addItems(QStringList()<<"0"<<"1"<<"4"<<"9"<<"14"<<"19");
-    breaksLayout->addWidget(boxMinorTicksBeforeBreak, 3, 3);
-
-    breaksLayout->addWidget(new QLabel(tr("Minor Ticks After")), 4, 2);
-    boxMinorTicksAfterBreak  = new QComboBox();
-	boxMinorTicksAfterBreak->setEditable(true);
-	boxMinorTicksAfterBreak->addItems(QStringList()<<"0"<<"1"<<"4"<<"9"<<"14"<<"19");
-    breaksLayout->addWidget(boxMinorTicksAfterBreak, 4, 3);
+
+    boxLog10AfterBreak = new QCheckBox(tr("&Log10 Scale After Break"));
+    breaksLayout->addWidget(boxLog10AfterBreak, 0, 3);
+
+    breaksLayout->addWidget(new QLabel(tr("Step Before Break")), 1, 2);
+    boxStepBeforeBreak = new DoubleSpinBox();
+    boxStepBeforeBreak->setMinimum(0.0);
+    boxStepBeforeBreak->setSpecialValueText(tr("Guess"));
+	boxStepBeforeBreak->setLocale(app->locale());
+    boxStepBeforeBreak->setDecimals(app->d_decimal_digits);
+	breaksLayout->addWidget(boxStepBeforeBreak, 1, 3);
+
+    breaksLayout->addWidget(new QLabel(tr("Step After Break")), 2, 2);
+    boxStepAfterBreak = new DoubleSpinBox();
+    boxStepAfterBreak->setMinimum(0.0);
+    boxStepAfterBreak->setSpecialValueText(tr("Guess"));
+	boxStepAfterBreak->setLocale(app->locale());
+    boxStepAfterBreak->setDecimals(app->d_decimal_digits);
+	breaksLayout->addWidget(boxStepAfterBreak, 2, 3);
+
+    breaksLayout->addWidget(new QLabel(tr("Minor Ticks Before")), 3, 2);
+    boxMinorTicksBeforeBreak = new QComboBox();
+	boxMinorTicksBeforeBreak->setEditable(true);
+	boxMinorTicksBeforeBreak->addItems(QStringList()<<"0"<<"1"<<"4"<<"9"<<"14"<<"19");
+    breaksLayout->addWidget(boxMinorTicksBeforeBreak, 3, 3);
+
+    breaksLayout->addWidget(new QLabel(tr("Minor Ticks After")), 4, 2);
+    boxMinorTicksAfterBreak  = new QComboBox();
+	boxMinorTicksAfterBreak->setEditable(true);
+	boxMinorTicksAfterBreak->addItems(QStringList()<<"0"<<"1"<<"4"<<"9"<<"14"<<"19");
+    breaksLayout->addWidget(boxMinorTicksAfterBreak, 4, 3);
 
 	QGroupBox *rightBox = new QGroupBox(QString());
-	QGridLayout *rightLayout = new QGridLayout(rightBox);
+	QGridLayout *rightLayout = new QGridLayout(rightBox);
 
 	QWidget * stepWidget = new QWidget();
-	QHBoxLayout * stepWidgetLayout = new QHBoxLayout( stepWidget );
+	QHBoxLayout * stepWidgetLayout = new QHBoxLayout( stepWidget );
 	stepWidgetLayout->setMargin(0);
 
 	btnStep = new QCheckBox(tr("Step"));
@@ -1353,7 +1353,7 @@ void AxesDialog::initScalesPage()
 	boxStep->setMinimum(0.0);
 	boxStep->setLocale(app->locale());
     boxStep->setDecimals(app->d_decimal_digits);
-	stepWidgetLayout->addWidget(boxStep);
+	stepWidgetLayout->addWidget(boxStep);
 
 	boxUnit = new QComboBox();
 	boxUnit->hide();
@@ -1378,14 +1378,14 @@ void AxesDialog::initScalesPage()
 	rightLayout->addWidget( boxMinorValue, 2, 1);
 
 	rightLayout->setRowStretch( 3, 1 );
-
-    QHBoxLayout* hl = new QHBoxLayout();
-	hl->addWidget(middleBox);
-	hl->addWidget(rightBox);
-
-    QVBoxLayout* vl = new QVBoxLayout();
-	vl->addLayout(hl);
-	vl->addWidget(boxAxesBreaks);
+
+    QHBoxLayout* hl = new QHBoxLayout();
+	hl->addWidget(middleBox);
+	hl->addWidget(rightBox);
+
+    QVBoxLayout* vl = new QVBoxLayout();
+	vl->addLayout(hl);
+	vl->addWidget(boxAxesBreaks);
 
 	QPixmap image0( ( const char** ) bottom_scl_xpm );
 	QPixmap image1( ( const char** ) left_scl_xpm );
@@ -1396,7 +1396,7 @@ void AxesDialog::initScalesPage()
 	axesList->addItem( new QListWidgetItem(image0, tr( "Bottom" )));
 	axesList->addItem( new QListWidgetItem(image1, tr( "Left" )));
 	axesList->addItem( new QListWidgetItem(image2, tr( "Top" )));
-	axesList->addItem( new QListWidgetItem(image3,  tr( "Right" )));
+	axesList->addItem( new QListWidgetItem(image3,  tr( "Right" )));
     axesList->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding));
 	axesList->setIconSize(image0.size());
 	axesList->setCurrentRow(-1);
@@ -1509,17 +1509,17 @@ void AxesDialog::initGridPage()
     rightLayout->addWidget( boxXLine, 5, 1);
 
     boxYLine = new QCheckBox(tr( "Y=0" ));
-    rightLayout->addWidget(boxYLine, 5, 2);
-
-    rightLayout->addWidget( new QLabel(tr( "Apply To" )), 6, 0);
-    boxApplyGridFormat = new QComboBox();
-    boxApplyGridFormat->insertItem(tr("This Layer"));
+    rightLayout->addWidget(boxYLine, 5, 2);
+
+    rightLayout->addWidget( new QLabel(tr( "Apply To" )), 6, 0);
+    boxApplyGridFormat = new QComboBox();
+    boxApplyGridFormat->insertItem(tr("This Layer"));
     boxApplyGridFormat->insertItem(tr("This Window"));
-    boxApplyGridFormat->insertItem(tr("All Windows"));
-    rightLayout->addWidget(boxApplyGridFormat, 6, 1);
-
-    boxAntialiseGrid = new QCheckBox(tr("An&tialised"));
-    rightLayout->addWidget(boxAntialiseGrid, 6, 2);
+    boxApplyGridFormat->insertItem(tr("All Windows"));
+    rightLayout->addWidget(boxApplyGridFormat, 6, 1);
+
+    boxAntialiseGrid = new QCheckBox(tr("An&tialised"));
+    rightLayout->addWidget(boxAntialiseGrid, 6, 2);
 
     rightLayout->setRowStretch(7, 1);
     rightLayout->setColumnStretch(4, 1);
@@ -1555,7 +1555,7 @@ void AxesDialog::initGridPage()
     connect(axesGridList, SIGNAL(currentRowChanged(int)), this, SLOT(showGridOptions(int)));
 
 	connect(boxMajorGrid,SIGNAL(toggled(bool)), this, SLOT(majorGridEnabled(bool)));
-	connect(boxMinorGrid,SIGNAL(toggled(bool)), this, SLOT(minorGridEnabled(bool)));
+	connect(boxMinorGrid,SIGNAL(toggled(bool)), this, SLOT(minorGridEnabled(bool)));
 	connect(boxAntialiseGrid,SIGNAL(toggled(bool)), this, SLOT(updateGrid()));
 	connect(boxColorMajor,SIGNAL(activated(int)),this, SLOT(updateGrid()));
 	connect(boxColorMinor,SIGNAL(activated(int)),this, SLOT(updateGrid()));
@@ -2001,7 +2001,7 @@ void AxesDialog::showAxisFormatOptions(int format)
 
 		case 6:
         {
-            labelTable->show();
+            labelTable->show();
             QString tableName = d_graph->axisFormatInfo(axis);
             if (tablesList.contains(tableName))
                 boxTableName->setCurrentText(tableName);
@@ -2075,7 +2075,7 @@ void AxesDialog::showAxis()
 	if (!boxShowFormula->isChecked())
 	   formula = QString();
 
-    showAxis(axis, boxAxisType->currentIndex(), boxColName->currentText(),ok, boxMajorTicksType->currentIndex(),
+    showAxis(axis, boxAxisType->currentIndex(), boxColName->currentText(),ok, boxMajorTicksType->currentIndex(),
             boxMinorTicksType->currentIndex(), boxShowLabels->isChecked(), boxAxisColor->color(), boxFormat->currentIndex(),
             boxPrecision->value(), boxAngle->value(), boxBaseline->value(), formula, boxAxisNumColor->color());
 }
@@ -2201,8 +2201,8 @@ void AxesDialog::majorGridEnabled(bool on)
 	boxTypeMajor->setEnabled(on);
 	boxColorMajor->setEnabled(on);
 	boxWidthMajor->setEnabled(on);
-
-    updateGrid();
+
+    updateGrid();
 }
 
 void AxesDialog::minorGridEnabled(bool on)
@@ -2218,94 +2218,94 @@ void AxesDialog::updateGrid()
 {
 	if (generalDialog->currentWidget() != gridPage)
 		return;
-
-    switch(boxApplyGridFormat->currentIndex()){
-        case 0:
+
+    switch(boxApplyGridFormat->currentIndex()){
+        case 0:
         {
 		    applyChangesToGrid(d_graph->plotWidget()->grid());
             d_graph->replot();
-            d_graph->notifyChanges();
-        }
-        break;
-
-        case 1:
-        {
-			MultiLayer *plot = d_graph->multiLayer();
-            if (!plot)
-                return;
-
-            QList<Graph *> layers = plot->layersList();
-			foreach(Graph *g, layers){
-                if (g->isPiePlot())
-                    continue;
-
-                applyChangesToGrid(g->plotWidget()->grid());
-                g->replot();
-            }
-            plot->applicationWindow()->modifiedProject();
-        }
-        break;
-
-        case 2:
-        {
-		    ApplicationWindow *app = (ApplicationWindow *)parent();
-            if (!app)
-                return;
-
-            QList<MdiSubWindow *> windows = app->windowsList();
-            foreach(MdiSubWindow *w, windows){
-                if (w->isA("MultiLayer")){
-                    QList<Graph *> layers = ((MultiLayer*)w)->layersList();
-                    foreach(Graph *g, layers){
-                        if (g->isPiePlot())
-                            continue;
-                        applyChangesToGrid(g->plotWidget()->grid());
-                        g->replot();
-                    }
-                }
-            }
-            app->modifiedProject();
-        }
-        break;
+            d_graph->notifyChanges();
+        }
+        break;
+
+        case 1:
+        {
+			MultiLayer *plot = d_graph->multiLayer();
+            if (!plot)
+                return;
+
+            QList<Graph *> layers = plot->layersList();
+			foreach(Graph *g, layers){
+                if (g->isPiePlot())
+                    continue;
+
+                applyChangesToGrid(g->plotWidget()->grid());
+                g->replot();
+            }
+            plot->applicationWindow()->modifiedProject();
+        }
+        break;
+
+        case 2:
+        {
+		    ApplicationWindow *app = (ApplicationWindow *)parent();
+            if (!app)
+                return;
+
+            QList<MdiSubWindow *> windows = app->windowsList();
+            foreach(MdiSubWindow *w, windows){
+                if (w->isA("MultiLayer")){
+                    QList<Graph *> layers = ((MultiLayer*)w)->layersList();
+                    foreach(Graph *g, layers){
+                        if (g->isPiePlot())
+                            continue;
+                        applyChangesToGrid(g->plotWidget()->grid());
+                        g->replot();
+                    }
+                }
+            }
+            app->modifiedProject();
+        }
+        break;
     }
 }
-
-void AxesDialog::applyChangesToGrid(Grid *grid)
-{
-    if (!grid)
-        return;
-
-	if (axesGridList->currentRow() == 1){
-		grid->enableX(boxMajorGrid->isChecked());
-		grid->enableXMin(boxMinorGrid->isChecked());
-
-		grid->setMajPenX(QPen(ColorBox::color(boxColorMajor->currentIndex()), boxWidthMajor->value(),
-					 		Graph::getPenStyle(boxTypeMajor->currentIndex())));
-		grid->setMinPenX(QPen(ColorBox::color(boxColorMinor->currentIndex()), boxWidthMinor->value(),
-					 		Graph::getPenStyle(boxTypeMinor->currentIndex())));
-	} else {
-		grid->enableY(boxMajorGrid->isChecked());
-		grid->enableYMin(boxMinorGrid->isChecked());
-
-		grid->setMajPenY(QPen(ColorBox::color(boxColorMajor->currentIndex()), boxWidthMajor->value(),
-					 		Graph::getPenStyle(boxTypeMajor->currentIndex())));
-		grid->setMinPenY(QPen(ColorBox::color(boxColorMinor->currentIndex()), boxWidthMinor->value(),
-					 		Graph::getPenStyle(boxTypeMinor->currentIndex())));
-	}
-
-	grid->enableZeroLineX(boxXLine->isChecked());
-	grid->enableZeroLineY(boxYLine->isChecked());
-	grid->setAxis(boxGridXAxis->currentIndex() + 2, boxGridYAxis->currentIndex());
-	grid->setRenderHint(QwtPlotItem::RenderAntialiased, boxAntialiseGrid->isChecked());
-}
+
+void AxesDialog::applyChangesToGrid(Grid *grid)
+{
+    if (!grid)
+        return;
+
+	if (axesGridList->currentRow() == 1){
+		grid->enableX(boxMajorGrid->isChecked());
+		grid->enableXMin(boxMinorGrid->isChecked());
+
+		grid->setMajPenX(QPen(ColorBox::color(boxColorMajor->currentIndex()), boxWidthMajor->value(),
+					 		Graph::getPenStyle(boxTypeMajor->currentIndex())));
+		grid->setMinPenX(QPen(ColorBox::color(boxColorMinor->currentIndex()), boxWidthMinor->value(),
+					 		Graph::getPenStyle(boxTypeMinor->currentIndex())));
+	} else {
+		grid->enableY(boxMajorGrid->isChecked());
+		grid->enableYMin(boxMinorGrid->isChecked());
+
+		grid->setMajPenY(QPen(ColorBox::color(boxColorMajor->currentIndex()), boxWidthMajor->value(),
+					 		Graph::getPenStyle(boxTypeMajor->currentIndex())));
+		grid->setMinPenY(QPen(ColorBox::color(boxColorMinor->currentIndex()), boxWidthMinor->value(),
+					 		Graph::getPenStyle(boxTypeMinor->currentIndex())));
+	}
+
+	grid->enableZeroLineX(boxXLine->isChecked());
+	grid->enableZeroLineY(boxYLine->isChecked());
+	grid->setAxis(boxGridXAxis->currentIndex() + 2, boxGridYAxis->currentIndex());
+	grid->setRenderHint(QwtPlotItem::RenderAntialiased, boxAntialiseGrid->isChecked());
+}
 
 void AxesDialog::showGridOptions(int axis)
 {
     Grid *grd = (Grid *)d_graph->plotWidget()->grid();
     if (!grd)
         return;
-
-    boxMajorGrid->blockSignals(true);
+
+    boxMajorGrid->blockSignals(true);
 	boxMinorGrid->blockSignals(true);
 	boxWidthMajor->blockSignals(true);
 	boxWidthMinor->blockSignals(true);
@@ -2313,7 +2313,7 @@ void AxesDialog::showGridOptions(int axis)
 	boxColorMinor->blockSignals(true);
 	boxTypeMajor->blockSignals(true);
 	boxTypeMinor->blockSignals(true);
-    boxAntialiseGrid->blockSignals(true);
+    boxAntialiseGrid->blockSignals(true);
 
     if (axis == 1) {
         boxMajorGrid->setChecked(grd->xEnabled());
@@ -2354,33 +2354,33 @@ void AxesDialog::showGridOptions(int axis)
     	boxColorMinor->setColor(minPenY.color());
     	boxWidthMinor->setValue(minPenY.widthF());
 	}
-
-    bool majorOn = boxMajorGrid->isChecked();
-    boxTypeMajor->setEnabled(majorOn);
-	boxColorMajor->setEnabled(majorOn);
-	boxWidthMajor->setEnabled(majorOn);
-
-    bool minorOn = boxMinorGrid->isChecked();
-    boxTypeMinor->setEnabled(minorOn);
-    boxColorMinor->setEnabled(minorOn);
-    boxWidthMinor->setEnabled(minorOn);
+
+    bool majorOn = boxMajorGrid->isChecked();
+    boxTypeMajor->setEnabled(majorOn);
+	boxColorMajor->setEnabled(majorOn);
+	boxWidthMajor->setEnabled(majorOn);
+
+    bool minorOn = boxMinorGrid->isChecked();
+    boxTypeMinor->setEnabled(minorOn);
+    boxColorMinor->setEnabled(minorOn);
+    boxWidthMinor->setEnabled(minorOn);
 
     boxGridXAxis->setCurrentIndex(grd->xAxis() - 2);
     boxGridYAxis->setCurrentIndex(grd->yAxis());
 
     boxXLine->setChecked(grd->xZeroLineEnabled());
     boxYLine->setChecked(grd->yZeroLineEnabled());
-
-    boxAntialiseGrid->setChecked(grd->testRenderHint(QwtPlotItem::RenderAntialiased));
-
+
+    boxAntialiseGrid->setChecked(grd->testRenderHint(QwtPlotItem::RenderAntialiased));
+
     boxAntialiseGrid->blockSignals(false);
 	boxWidthMajor->blockSignals(false);
 	boxWidthMinor->blockSignals(false);
 	boxColorMajor->blockSignals(false);
 	boxColorMinor->blockSignals(false);
 	boxTypeMajor->blockSignals(false);
-	boxTypeMinor->blockSignals(false);
-	boxMajorGrid->blockSignals(false);
+	boxTypeMinor->blockSignals(false);
+	boxMajorGrid->blockSignals(false);
 	boxMinorGrid->blockSignals(false);
 }
 
@@ -2433,25 +2433,25 @@ bool AxesDialog::updatePlot()
 	if (generalDialog->currentWidget()==(QWidget*)scalesPage)
   {		
 
-    int a = mapToQwtAxis(axesList->currentRow());
-    ScaleDraw::ScaleType type = d_graph->axisType(a);
-
-    double start = 0.0, end = 0.0;
-    if (type == ScaleDraw::Date){
-      ScaleDraw *sclDraw = (ScaleDraw *)d_graph->plotWidget()->axisScaleDraw(a);
-      QDateTime origin = sclDraw->dateTimeOrigin();
-      start = (double)origin.secsTo(boxStartDateTime->dateTime());
-      end = (double)origin.secsTo(boxEndDateTime->dateTime());
-    } else if (type == ScaleDraw::Time){
-      ScaleDraw *sclDraw = (ScaleDraw *)d_graph->plotWidget()->axisScaleDraw(a);
-      QTime origin = sclDraw->dateTimeOrigin().time();
-      start = (double)origin.msecsTo(boxStartTime->time());
-      end = (double)origin.msecsTo(boxEndTime->time());
-    } else {
-      start = boxStart->value();
-      end = boxEnd->value();
+    int a = mapToQwtAxis(axesList->currentRow());
+    ScaleDraw::ScaleType type = d_graph->axisType(a);
+
+    double start = 0.0, end = 0.0;
+    if (type == ScaleDraw::Date){
+      ScaleDraw *sclDraw = (ScaleDraw *)d_graph->plotWidget()->axisScaleDraw(a);
+      QDateTime origin = sclDraw->dateTimeOrigin();
+      start = (double)origin.secsTo(boxStartDateTime->dateTime());
+      end = (double)origin.secsTo(boxEndDateTime->dateTime());
+    } else if (type == ScaleDraw::Time){
+      ScaleDraw *sclDraw = (ScaleDraw *)d_graph->plotWidget()->axisScaleDraw(a);
+      QTime origin = sclDraw->dateTimeOrigin().time();
+      start = (double)origin.msecsTo(boxStartTime->time());
+      end = (double)origin.msecsTo(boxEndTime->time());
+    } else {
+      start = boxStart->value();
+      end = boxEnd->value();
     }
-
+
     double step = 0.0;
     if (btnStep->isChecked()){
       step = boxStep->value();
@@ -2489,9 +2489,9 @@ bool AxesDialog::updatePlot()
       breakRight = qMax(boxBreakStart->value(), boxBreakEnd->value());
     }
     d_graph->setScale(a, start, end, step, boxMajorValue->value(), boxMinorValue->currentText().toInt(),
-      boxScaleType->currentIndex(), btnInvert->isChecked(), breakLeft, breakRight,
-      boxBreakPosition->value(), boxStepBeforeBreak->value(), boxStepAfterBreak->value(),
-      boxMinorTicksBeforeBreak->currentText().toInt(), boxMinorTicksAfterBreak->currentText().toInt(),
+      boxScaleType->currentIndex(), btnInvert->isChecked(), breakLeft, breakRight,
+      boxBreakPosition->value(), boxStepBeforeBreak->value(), boxStepAfterBreak->value(),
+      boxMinorTicksBeforeBreak->currentText().toInt(), boxMinorTicksAfterBreak->currentText().toInt(),
       boxLog10AfterBreak->isChecked(), boxBreakWidth->value(), boxBreakDecoration->isChecked());
     d_graph->notifyChanges();
 	}
@@ -2504,7 +2504,7 @@ bool AxesDialog::updatePlot()
 
 		int baseline = boxBaseline->value();
 		axesBaseline[axis] = baseline;
-
+
         QString formatInfo = QString::null;
 		if (format == ScaleDraw::Numeric)
 		{
@@ -2532,16 +2532,16 @@ bool AxesDialog::updatePlot()
 					//return false;
 				}
 			}
-		} else if (format == ScaleDraw::Time || format == ScaleDraw::Date){
-            QStringList lst = d_graph->axisFormatInfo(axis).split(";", QString::KeepEmptyParts);
-            if ((int)lst.count() >= 2)
-                lst[1] = boxFormat->currentText();
-            formatInfo = lst.join(";");
-        } else if (format == ScaleDraw::Day || format == ScaleDraw::Month)
-            formatInfo = QString::number(boxFormat->currentIndex());
-          else if (format == ScaleDraw::ColHeader)
-            formatInfo = boxTableName->currentText();
-          else
+		} else if (format == ScaleDraw::Time || format == ScaleDraw::Date){
+            QStringList lst = d_graph->axisFormatInfo(axis).split(";", QString::KeepEmptyParts);
+            if ((int)lst.count() >= 2)
+                lst[1] = boxFormat->currentText();
+            formatInfo = lst.join(";");
+        } else if (format == ScaleDraw::Day || format == ScaleDraw::Month)
+            formatInfo = QString::number(boxFormat->currentIndex());
+          else if (format == ScaleDraw::ColHeader)
+            formatInfo = boxTableName->currentText();
+          else
             formatInfo = boxColName->currentText();
 
 		if (d_graph->axisTitle(axis) != boxTitle->text())
@@ -2566,7 +2566,7 @@ bool AxesDialog::updatePlot()
         	d_graph->setCanvasFrame(boxFrameWidth->value(), boxFrameColor->color());
 		else
 			d_graph->setCanvasFrame(0);
-        d_graph->drawAxesBackbones(boxBackbones->isChecked());
+        d_graph->drawAxesBackbones(boxBackbones->isChecked());
         d_graph->replot();
 	}
    m_updatePlot=true;
@@ -2671,102 +2671,102 @@ void AxesDialog::updateScale()
     boxUnit->clear();
     
     Plot *d_plot = d_graph->plotWidget();
-    int a = mapToQwtAxis(axis);
-	const QwtScaleDiv *scDiv = d_plot->axisScaleDiv(a);
-    double start = QMIN(scDiv->lBound(), scDiv->hBound());
-    double end = QMAX(scDiv->lBound(), scDiv->hBound());
-	ScaleDraw::ScaleType type = d_graph->axisType(a);
-	if (type == ScaleDraw::Date){
-	    ScaleDraw *sclDraw = (ScaleDraw *)d_plot->axisScaleDraw(a);
-        QDateTime origin = sclDraw->dateTimeOrigin();
-
-	    boxStart->hide();
-	    boxStartTime->hide();
-        boxStartDateTime->show();
-        boxStartDateTime->setDisplayFormat(sclDraw->format());
-        boxStartDateTime->setDateTime(origin.addSecs((int)start));
-
-        boxEnd->hide();
-        boxEndTime->hide();
-        boxEndDateTime->show();
-        boxEndDateTime->setDisplayFormat(sclDraw->format());
-        boxEndDateTime->setDateTime(origin.addSecs((int)end));
-
-		boxUnit->show();
-		boxUnit->insertItem(tr("days"));
-		boxUnit->insertItem(tr("weeks"));
-		boxStep->setValue(d_graph->axisStep(a)/86400.0);
-		boxStep->setSingleStep(1);
-	} else if (type == ScaleDraw::Time){
-	    ScaleDraw *sclDraw = (ScaleDraw *)d_plot->axisScaleDraw(a);
-        QTime origin = sclDraw->dateTimeOrigin().time();
-
-	    boxStart->hide();
-	    boxStartDateTime->hide();
-        boxStartTime->show();
-        boxStartTime->setDisplayFormat(sclDraw->format());
-        boxStartTime->setTime(origin.addMSecs((int)start));
-
-        boxEnd->hide();
-        boxEndDateTime->hide();
-        boxEndTime->show();
-        boxEndTime->setDisplayFormat(sclDraw->format());
-        boxEndTime->setTime(origin.addMSecs((int)end));
-
-        boxUnit->show();
-        boxUnit->insertItem(tr("millisec."));
-        boxUnit->insertItem(tr("sec."));
-        boxUnit->insertItem(tr("min."));
-        boxUnit->insertItem(tr("hours"));
-        boxUnit->setCurrentIndex(1);
-        boxStep->setValue(d_graph->axisStep(a)/1e3);
-        boxStep->setSingleStep(1000);
-	} else {
-	    boxStart->show();
-        boxStart->setValue(start);
-        boxStartTime->hide();
-        boxStartDateTime->hide();
-        boxEnd->show();
-        boxEnd->setValue(end);
-	    boxEndTime->hide();
-        boxEndDateTime->hide();
-        boxStep->setValue(d_graph->axisStep(a));
-        boxStep->setSingleStep(0.1);
-	}
-
+    int a = mapToQwtAxis(axis);
+	const QwtScaleDiv *scDiv = d_plot->axisScaleDiv(a);
+    double start = QMIN(scDiv->lBound(), scDiv->hBound());
+    double end = QMAX(scDiv->lBound(), scDiv->hBound());
+	ScaleDraw::ScaleType type = d_graph->axisType(a);
+	if (type == ScaleDraw::Date){
+	    ScaleDraw *sclDraw = (ScaleDraw *)d_plot->axisScaleDraw(a);
+        QDateTime origin = sclDraw->dateTimeOrigin();
+
+	    boxStart->hide();
+	    boxStartTime->hide();
+        boxStartDateTime->show();
+        boxStartDateTime->setDisplayFormat(sclDraw->format());
+        boxStartDateTime->setDateTime(origin.addSecs((int)start));
+
+        boxEnd->hide();
+        boxEndTime->hide();
+        boxEndDateTime->show();
+        boxEndDateTime->setDisplayFormat(sclDraw->format());
+        boxEndDateTime->setDateTime(origin.addSecs((int)end));
+
+		boxUnit->show();
+		boxUnit->insertItem(tr("days"));
+		boxUnit->insertItem(tr("weeks"));
+		boxStep->setValue(d_graph->axisStep(a)/86400.0);
+		boxStep->setSingleStep(1);
+	} else if (type == ScaleDraw::Time){
+	    ScaleDraw *sclDraw = (ScaleDraw *)d_plot->axisScaleDraw(a);
+        QTime origin = sclDraw->dateTimeOrigin().time();
+
+	    boxStart->hide();
+	    boxStartDateTime->hide();
+        boxStartTime->show();
+        boxStartTime->setDisplayFormat(sclDraw->format());
+        boxStartTime->setTime(origin.addMSecs((int)start));
+
+        boxEnd->hide();
+        boxEndDateTime->hide();
+        boxEndTime->show();
+        boxEndTime->setDisplayFormat(sclDraw->format());
+        boxEndTime->setTime(origin.addMSecs((int)end));
+
+        boxUnit->show();
+        boxUnit->insertItem(tr("millisec."));
+        boxUnit->insertItem(tr("sec."));
+        boxUnit->insertItem(tr("min."));
+        boxUnit->insertItem(tr("hours"));
+        boxUnit->setCurrentIndex(1);
+        boxStep->setValue(d_graph->axisStep(a)/1e3);
+        boxStep->setSingleStep(1000);
+	} else {
+	    boxStart->show();
+        boxStart->setValue(start);
+        boxStartTime->hide();
+        boxStartDateTime->hide();
+        boxEnd->show();
+        boxEnd->setValue(end);
+	    boxEndTime->hide();
+        boxEndDateTime->hide();
+        boxStep->setValue(d_graph->axisStep(a));
+        boxStep->setSingleStep(0.1);
+	}
+
     double range = fabs(scDiv->range());
     QwtScaleEngine *qwtsc_engine = d_plot->axisScaleEngine(a);
 	ScaleEngine* sc_engine=dynamic_cast<ScaleEngine*>(qwtsc_engine);
 	if(sc_engine)
 	{		
 		if (sc_engine->axisBreakLeft() > -DBL_MAX)
-			boxBreakStart->setValue(sc_engine->axisBreakLeft());
-		else
-			boxBreakStart->setValue(start + 0.25*range);
+			boxBreakStart->setValue(sc_engine->axisBreakLeft());
+		else
+			boxBreakStart->setValue(start + 0.25*range);
 
 		if (sc_engine->axisBreakRight() < DBL_MAX)
-			boxBreakEnd->setValue(sc_engine->axisBreakRight());
-		else
-			boxBreakEnd->setValue(start + 0.75*range);
+			boxBreakEnd->setValue(sc_engine->axisBreakRight());
+		else
+			boxBreakEnd->setValue(start + 0.75*range);
+
+		boxAxesBreaks->setChecked(sc_engine->hasBreak());
 
-		boxAxesBreaks->setChecked(sc_engine->hasBreak());
-
 		boxBreakPosition->setValue(sc_engine->breakPosition());
-		boxBreakWidth->setValue(sc_engine->breakWidth());
-		boxStepBeforeBreak->setValue(sc_engine->stepBeforeBreak());
-		boxStepAfterBreak->setValue(sc_engine->stepAfterBreak());
-
-		QwtScaleTransformation::Type scale_type = sc_engine->type();
-		boxMinorTicksBeforeBreak->clear();
-		if (scale_type == QwtScaleTransformation::Log10)
-			boxMinorTicksBeforeBreak->addItems(QStringList()<<"0"<<"2"<<"4"<<"8");
-		else
-			boxMinorTicksBeforeBreak->addItems(QStringList()<<"0"<<"1"<<"4"<<"9"<<"14"<<"19");
-		boxMinorTicksBeforeBreak->setEditText(QString::number(sc_engine->minTicksBeforeBreak()));
-
-
-		boxMinorTicksAfterBreak->setEditText(QString::number(sc_engine->minTicksAfterBreak()));
-		boxLog10AfterBreak->setChecked(sc_engine->log10ScaleAfterBreak());
+		boxBreakWidth->setValue(sc_engine->breakWidth());
+		boxStepBeforeBreak->setValue(sc_engine->stepBeforeBreak());
+		boxStepAfterBreak->setValue(sc_engine->stepAfterBreak());
+
+		QwtScaleTransformation::Type scale_type = sc_engine->type();
+		boxMinorTicksBeforeBreak->clear();
+		if (scale_type == QwtScaleTransformation::Log10)
+			boxMinorTicksBeforeBreak->addItems(QStringList()<<"0"<<"2"<<"4"<<"8");
+		else
+			boxMinorTicksBeforeBreak->addItems(QStringList()<<"0"<<"1"<<"4"<<"9"<<"14"<<"19");
+		boxMinorTicksBeforeBreak->setEditText(QString::number(sc_engine->minTicksBeforeBreak()));
+
+
+		boxMinorTicksAfterBreak->setEditText(QString::number(sc_engine->minTicksAfterBreak()));
+		boxLog10AfterBreak->setChecked(sc_engine->log10ScaleAfterBreak());
 		boxBreakDecoration->setChecked(sc_engine->hasBreakDecoration());
 		btnInvert->setChecked(sc_engine->testAttribute(QwtScaleEngine::Inverted)); 
 		boxScaleType->setCurrentItem(scale_type); 
@@ -2784,7 +2784,7 @@ void AxesDialog::updateScale()
     {
       boxAxesBreaks->setChecked (false);
     }
-	
+	
 	}
 	else 
 	{	
@@ -2793,7 +2793,7 @@ void AxesDialog::updateScale()
 	}
 
  	QwtValueList lst = scDiv->ticks (QwtScaleDiv::MajorTick);
-	boxMajorValue->setValue(lst.count());
+	boxMajorValue->setValue(lst.count());
 		
 	if (d_graph->axisStep(a) != 0.0){
 		btnStep->setChecked(true);
@@ -2810,7 +2810,7 @@ void AxesDialog::updateScale()
 		boxMajorValue->setEnabled(true);
 	}
    
-	//}
+	//}
 		       
 }
 
@@ -2827,7 +2827,7 @@ void AxesDialog::pickAxisColor()
 	if (!boxShowFormula->isChecked())
 	   formula = QString();
 
-    showAxis(axis, boxAxisType->currentIndex(), d_graph->axisFormatInfo(axis), boxShowAxis->isChecked(),
+    showAxis(axis, boxAxisType->currentIndex(), d_graph->axisFormatInfo(axis), boxShowAxis->isChecked(),
             boxMajorTicksType->currentIndex(), boxMinorTicksType->currentIndex(),
             boxShowLabels->isChecked(), boxAxisColor->color(), boxFormat->currentIndex(), boxPrecision->value(),
             boxAngle->value(), boxBaseline->value(), formula, boxAxisNumColor->color());
@@ -2840,7 +2840,7 @@ void AxesDialog::pickAxisNumColor()
   	if (!boxShowFormula->isChecked())
   	     formula = QString::null;
 
-  	showAxis(axis, boxAxisType->currentIndex(), d_graph->axisFormatInfo(axis), boxShowAxis->isChecked(),
+  	showAxis(axis, boxAxisType->currentIndex(), d_graph->axisFormatInfo(axis), boxShowAxis->isChecked(),
             boxMajorTicksType->currentIndex(), boxMinorTicksType->currentIndex(),
             boxShowLabels->isChecked(), boxAxisColor->color(), boxFormat->currentIndex(), boxPrecision->value(),
             boxAngle->value(), boxBaseline->value(), formula, boxAxisNumColor->color());
@@ -2881,9 +2881,9 @@ void AxesDialog::updateMajTicksType(int)
 	if (!boxShowFormula->isChecked())
 		formula = QString();
 
-    showAxis(axis, boxAxisType->currentIndex(), d_graph->axisFormatInfo(axis), boxShowAxis->isChecked(),
-            type, boxMinorTicksType->currentIndex(), boxShowLabels->isChecked(), boxAxisColor->color(),
-            boxFormat->currentIndex(),boxPrecision->value(), boxAngle->value(), boxBaseline->value(),
+    showAxis(axis, boxAxisType->currentIndex(), d_graph->axisFormatInfo(axis), boxShowAxis->isChecked(),
+            type, boxMinorTicksType->currentIndex(), boxShowLabels->isChecked(), boxAxisColor->color(),
+            boxFormat->currentIndex(),boxPrecision->value(), boxAngle->value(), boxBaseline->value(),
             formula, boxAxisNumColor->color());
 }
 
@@ -2899,8 +2899,8 @@ void AxesDialog::updateMinTicksType(int)
     if (!boxShowFormula->isChecked())
 		formula = QString();
 
-    showAxis(axis,boxAxisType->currentIndex(), d_graph->axisFormatInfo(axis), boxShowAxis->isChecked(),
-            boxMajorTicksType->currentIndex(), type, boxShowLabels->isChecked(), boxAxisColor->color(),
+    showAxis(axis,boxAxisType->currentIndex(), d_graph->axisFormatInfo(axis), boxShowAxis->isChecked(),
+            boxMajorTicksType->currentIndex(), type, boxShowLabels->isChecked(), boxAxisColor->color(),
             boxFormat->currentIndex(),boxPrecision->value(),
             boxAngle->value(), boxBaseline->value(), formula, boxAxisNumColor->color());
 }
@@ -2919,7 +2919,7 @@ void AxesDialog::updateTickLabelsList(bool on)
 	if (tickLabelsOn[axis] == QString::number(on))
 		return;
 	tickLabelsOn[axis]=QString::number(on);
-
+
     QString formatInfo = QString::null;
 	int type = boxAxisType->currentIndex();
 	if (type == ScaleDraw::Day || type == ScaleDraw::Month)
@@ -2986,7 +2986,7 @@ void AxesDialog::setLabelsNumericFormat(int)
 	int format = boxFormat->currentIndex();
 
 	Plot *plot = d_graph->plotWidget();
-
+
     QString formatInfo = QString::null;
 	if (type == ScaleDraw::Numeric){
 		if (plot->axisLabelFormat(axis) == format &&
@@ -2999,7 +2999,7 @@ void AxesDialog::setLabelsNumericFormat(int)
 			boxPrecision->setEnabled(true);
     } else if (type == ScaleDraw::Day || type == ScaleDraw::Month)
 		formatInfo = QString::number(format);
-	  else if (type == ScaleDraw::Time || type == ScaleDraw::Date){
+	  else if (type == ScaleDraw::Time || type == ScaleDraw::Date){
 		QStringList lst = d_graph->axisFormatInfo(axis).split(";", QString::SkipEmptyParts);
 		lst[1] = boxFormat->currentText();
 		formatInfo = lst.join(";");
diff --git a/Code/Mantid/MantidPlot/src/AxesDialog.h b/Code/Mantid/MantidPlot/src/AxesDialog.h
index 6623761e6eb696d48210163b45ab0a87ba8b297c..afa51c7c261fc5059928a0bd9990928bbb53bdd9 100644
--- a/Code/Mantid/MantidPlot/src/AxesDialog.h
+++ b/Code/Mantid/MantidPlot/src/AxesDialog.h
@@ -34,8 +34,8 @@
 #include <QList>
 #include <QTextEdit>
 //#include "MantidKernel/Logger.h"
-
-class QTimeEdit;
+
+class QTimeEdit;
 class QDateTimeEdit;
 class QListWidget;
 class QListWidgetItem;
@@ -54,7 +54,7 @@ class ColorButton;
 class Graph;
 class TextFormatButtons;
 class DoubleSpinBox;
-class Grid;
+class Grid;
 
 //! General plot options dialog
 /**
@@ -142,8 +142,8 @@ protected:
 	//! generate UI for the grid page
 	void initGridPage();
 	//! generate UI for the general page
-	void initFramePage();
-	//! Modifies the grid
+	void initFramePage();
+	//! Modifies the grid
 	void applyChangesToGrid(Grid *grid);
 
     QPushButton* buttonApply;
@@ -151,7 +151,7 @@ protected:
     QPushButton* buttonCancel;
     QTabWidget* generalDialog;
     QWidget* scalesPage;
-    DoubleSpinBox* boxEnd;
+    DoubleSpinBox* boxEnd;
     DoubleSpinBox* boxStart;
     QComboBox* boxScaleType;
     QComboBox* boxMinorValue;
@@ -200,15 +200,15 @@ protected:
 	int xBottomLabelsRotation, xTopLabelsRotation;
 
 	QGroupBox *boxAxesBreaks;
-	DoubleSpinBox *boxBreakStart, *boxBreakEnd, *boxStepBeforeBreak, *boxStepAfterBreak;
-	QSpinBox *boxBreakPosition, *boxBreakWidth;
-	QComboBox *boxMinorTicksBeforeBreak, *boxMinorTicksAfterBreak;
-	QCheckBox *boxLog10AfterBreak, *boxBreakDecoration, *boxAntialiseGrid;
+	DoubleSpinBox *boxBreakStart, *boxBreakEnd, *boxStepBeforeBreak, *boxStepAfterBreak;
+	QSpinBox *boxBreakPosition, *boxBreakWidth;
+	QComboBox *boxMinorTicksBeforeBreak, *boxMinorTicksAfterBreak;
+	QCheckBox *boxLog10AfterBreak, *boxBreakDecoration, *boxAntialiseGrid;
     QComboBox *boxApplyGridFormat;
 	Graph* d_graph;
 	//! Last selected tab
-  	QWidget* lastPage;
-    QDateTimeEdit *boxStartDateTime, *boxEndDateTime;
+  	QWidget* lastPage;
+    QDateTimeEdit *boxStartDateTime, *boxEndDateTime;
     QTimeEdit *boxStartTime, *boxEndTime;
 	bool m_updatePlot;
 
diff --git a/Code/Mantid/MantidPlot/src/BoxCurve.cpp b/Code/Mantid/MantidPlot/src/BoxCurve.cpp
index d6e6f4275685ad4e617f4902459beb7c67e90a1d..a50d4aeafbc7f3fbc9dbda030462bc36fb693a60 100644
--- a/Code/Mantid/MantidPlot/src/BoxCurve.cpp
+++ b/Code/Mantid/MantidPlot/src/BoxCurve.cpp
@@ -48,7 +48,7 @@ BoxCurve::BoxCurve(Table *t, const QString& name, int startRow, int endRow):
 	w_coeff = 95.0;
 	b_width = 80;
 
-	setType(Graph::Box);
+	setType(Graph::Box);
     setStyle(QwtPlotCurve::UserCurve);
 }
 
diff --git a/Code/Mantid/MantidPlot/src/CanvasPicker.cpp b/Code/Mantid/MantidPlot/src/CanvasPicker.cpp
index ad078b17ddbc1a396b85d6139422cbe056eacc72..06b7291a8123257fb40c1cc59d32fb812630f565 100644
--- a/Code/Mantid/MantidPlot/src/CanvasPicker.cpp
+++ b/Code/Mantid/MantidPlot/src/CanvasPicker.cpp
@@ -77,9 +77,9 @@ bool CanvasPicker::eventFilter(QObject *object, QEvent *e)
 						break;
 					}
 				}
-
-                int dist, point;
-                plotWidget->closestCurve(me->pos().x(), me->pos().y(), dist, point);
+
+                int dist, point;
+                plotWidget->closestCurve(me->pos().x(), me->pos().y(), dist, point);
 
 				if (me->button() == Qt::LeftButton && (plot()->drawLineActive())){
 					startLinePoint = me->pos();
@@ -138,8 +138,8 @@ bool CanvasPicker::eventFilter(QObject *object, QEvent *e)
 
 				QPoint pos = me->pos();
 				DataCurve *c = plot()->selectedCurveLabels();
-				if (c){
-					
+				if (c){
+					
 					c->moveLabels(pos);
 					return true;
 				}
diff --git a/Code/Mantid/MantidPlot/src/ColorButton.cpp b/Code/Mantid/MantidPlot/src/ColorButton.cpp
index 2c472fd45b1d0140dc2b1c63e1f4532c44e5b981..67ca5b868e24802f558f13880d0f5eb324402a47 100644
--- a/Code/Mantid/MantidPlot/src/ColorButton.cpp
+++ b/Code/Mantid/MantidPlot/src/ColorButton.cpp
@@ -27,45 +27,45 @@
  *                                                                         *
  ***************************************************************************/
 #include "ColorButton.h"
-#include <QPainter>
-#include <QColorDialog>
+#include <QPainter>
+#include <QColorDialog>
 
-ColorButton::ColorButton(QWidget *parent) : QPushButton(parent),
+ColorButton::ColorButton(QWidget *parent) : QPushButton(parent),
 	d_color(Qt::black)
-{
-   updateColor();
-   connect(this, SIGNAL(clicked()), this, SLOT(pickColor()));
+{
+   updateColor();
+   connect(this, SIGNAL(clicked()), this, SLOT(pickColor()));
 }
 
 void ColorButton::setColor(const QColor& c)
 {
-	if (d_color == c)
-        return;
-
-    d_color = c;
-    updateColor();
+	if (d_color == c)
+        return;
+
+    d_color = c;
+    updateColor();
     emit colorChanged();
 }
-
-void ColorButton::updateColor()
-{
-	QRect r = QRect(0, 0, 27, 15);
-    QPixmap pix(QSize(28, 16));
-	pix.fill(d_color);
-
-	QPainter p;
-	p.begin(&pix);
-	p.drawRect(r);
-	p.end();
-
-	setIcon(QIcon(pix));
-}
-
-void ColorButton::pickColor()
-{
-    QColor c = QColorDialog::getColor(d_color, this);
-	if ( !c.isValid() )
-		return ;
-
-	setColor(c);
-}
+
+void ColorButton::updateColor()
+{
+	QRect r = QRect(0, 0, 27, 15);
+    QPixmap pix(QSize(28, 16));
+	pix.fill(d_color);
+
+	QPainter p;
+	p.begin(&pix);
+	p.drawRect(r);
+	p.end();
+
+	setIcon(QIcon(pix));
+}
+
+void ColorButton::pickColor()
+{
+    QColor c = QColorDialog::getColor(d_color, this);
+	if ( !c.isValid() )
+		return ;
+
+	setColor(c);
+}
diff --git a/Code/Mantid/MantidPlot/src/ColorButton.h b/Code/Mantid/MantidPlot/src/ColorButton.h
index 68d3a7cfeb5eb6213297bfc3281f9d89bef1d0c7..f37f867da4d4c7627b94a1fa3a24bb4af995c6a7 100644
--- a/Code/Mantid/MantidPlot/src/ColorButton.h
+++ b/Code/Mantid/MantidPlot/src/ColorButton.h
@@ -30,7 +30,7 @@
 #ifndef COLORBUTTON_H
 #define COLORBUTTON_H
 
-#include <QPushButton>
+#include <QPushButton>
 
 //! A button used for color selection
 class ColorButton : public QPushButton
@@ -44,14 +44,14 @@ public:
 	void setColor(const QColor& c);
 	//! Get the color of the display part
 	QColor color(){return d_color;};
-
-signals:
-    void colorChanged();
-
-private slots:
-    void pickColor();
-
-private:
+
+signals:
+    void colorChanged();
+
+private slots:
+    void pickColor();
+
+private:
     void updateColor();
 	QColor d_color;
 };
diff --git a/Code/Mantid/MantidPlot/src/ConfigDialog.cpp b/Code/Mantid/MantidPlot/src/ConfigDialog.cpp
index 9acd27c7249b1004501e6c607287871a107cbac7..eaa66fc3038683b1edff66a79a27f801e03328b2 100644
--- a/Code/Mantid/MantidPlot/src/ConfigDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ConfigDialog.cpp
@@ -73,7 +73,7 @@
 #include "MantidAPI/IBackgroundFunction.h"
 #include "MantidAPI/IPeakFunction.h"
 #include "MantidQtMantidWidgets/InstrumentSelector.h"
-
+
 
 ConfigDialog::ConfigDialog( QWidget* parent, Qt::WFlags fl )
     : QDialog( parent, fl )
@@ -233,7 +233,7 @@ void ConfigDialog::initTablesPage()
 	QVBoxLayout * tablesPageLayout = new QVBoxLayout( tables );
 	tablesPageLayout->addLayout(topLayout,1);
 	tablesPageLayout->addWidget(groupBoxTableCol);
-	tablesPageLayout->addWidget(groupBoxTableFonts);
+	tablesPageLayout->addWidget(groupBoxTableFonts);
     tablesPageLayout->addWidget(boxTableComments);
 	tablesPageLayout->addWidget(boxUpdateTableValues);
 	tablesPageLayout->addStretch();
@@ -475,12 +475,12 @@ void ConfigDialog::initAppPage()
 	boxScriptingLanguage->insertStringList(llist);
 	boxScriptingLanguage->setCurrentItem(llist.findIndex(app->defaultScriptingLang));
 	topBoxLayout->addWidget( boxScriptingLanguage, 3, 1 );
-
-    lblUndoStackSize = new QLabel();
-	topBoxLayout->addWidget( lblUndoStackSize, 4, 0 );
-    undoStackSizeBox = new QSpinBox();
-    undoStackSizeBox->setValue(app->matrixUndoStackSize());
-    topBoxLayout->addWidget( undoStackSizeBox, 4, 1 );
+
+    lblUndoStackSize = new QLabel();
+	topBoxLayout->addWidget( lblUndoStackSize, 4, 0 );
+    undoStackSizeBox = new QSpinBox();
+    undoStackSizeBox->setValue(app->matrixUndoStackSize());
+    topBoxLayout->addWidget( undoStackSizeBox, 4, 1 );
 
 	lblEndOfLine = new QLabel();
 	topBoxLayout->addWidget(lblEndOfLine, 5, 0 );
@@ -505,10 +505,10 @@ void ConfigDialog::initAppPage()
 	boxMinutes->setValue(app->autoSaveTime);
 	boxMinutes->setEnabled(app->autoSave);
 	topBoxLayout->addWidget( boxMinutes, 7, 1 );
-
-    boxBackupProject = new QCheckBox();
-	boxBackupProject->setChecked(app->d_backup_files);
-	topBoxLayout->addWidget( boxBackupProject, 8, 0, 1, 2 );
+
+    boxBackupProject = new QCheckBox();
+	boxBackupProject->setChecked(app->d_backup_files);
+	topBoxLayout->addWidget( boxBackupProject, 8, 0, 1, 2 );
 
 	boxSearchUpdates = new QCheckBox();
 	boxSearchUpdates->setChecked(app->autoSearchUpdates);
@@ -688,7 +688,7 @@ void ConfigDialog::initDirSearchTab()
   lePythonScriptsDirs->setText(QString::fromStdString(str));
 	grid->addWidget(lePythonScriptsDirs, 0, 1);
 
-	QPushButton *button = new QPushButton();
+	QPushButton *button = new QPushButton();
 	button->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
 	grid->addWidget(button, 0, 2);
 
@@ -704,7 +704,7 @@ void ConfigDialog::initDirSearchTab()
   lePythonAlgorithmsDirs->setText(QString::fromStdString(str));
 	grid->addWidget(lePythonAlgorithmsDirs, 1, 1);
 
-	button = new QPushButton();
+	button = new QPushButton();
 	button->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
 	grid->addWidget(button, 1, 2);
 
@@ -719,7 +719,7 @@ void ConfigDialog::initDirSearchTab()
   leInstrumentDir->setText(QString::fromStdString(str));
 	grid->addWidget(leInstrumentDir, 2, 1);
 
-	button = new QPushButton();
+	button = new QPushButton();
 	button->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
 	grid->addWidget(button, 2, 2);
 
@@ -733,8 +733,8 @@ void ConfigDialog::initDirSearchTab()
 	leParameterDir = new QLineEdit();
   leParameterDir->setText(QString::fromStdString(str));
 	grid->addWidget(leParameterDir, 3, 1);
-
-	button = new QPushButton();
+
+	button = new QPushButton();
 	button->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
 	grid->addWidget(button, 3, 2);
 
@@ -826,8 +826,8 @@ void ConfigDialog::initCurveFittingTab()
     index = backgroundFunctions->findText(value[0], Qt::MatchFixedString);// Case insensitive
     if( value.size() > 1 )
     {
-      value.removeFirst();
-      QString args = value.join(" ");
+      value.removeFirst();
+      QString args = value.join(" ");
       functionArguments->setText(args);
     }
   }
@@ -945,10 +945,10 @@ void ConfigDialog::initOptionsPage()
 		boxScaleFonts->setEnabled(false);
 
 	optionsTabLayout->addWidget( boxResize );
-
-  boxLabelsEditing = new QCheckBox();
-  boxLabelsEditing->setChecked(!app->d_in_place_editing);
-  optionsTabLayout->addWidget(boxLabelsEditing);
+
+  boxLabelsEditing = new QCheckBox();
+  boxLabelsEditing->setChecked(!app->d_in_place_editing);
+  optionsTabLayout->addWidget(boxLabelsEditing);
 
   plotsTabWidget->addTab( plotOptions, QString() );
 }
@@ -967,15 +967,15 @@ void ConfigDialog::initAxesPage()
   lblXLogLin = new QLabel();
 	axisBoxLayout->addWidget( lblXLogLin, 0, 0 );
 
-  cbXLog = new QComboBox();
-  cbXLog->addItem(tr("linear"));
-  cbXLog->addItem("log");
-  if ( app->xaxisScale == "log" )
-  {
+  cbXLog = new QComboBox();
+  cbXLog->addItem(tr("linear"));
+  cbXLog->addItem("log");
+  if ( app->xaxisScale == "log" )
+  {
     cbXLog->setCurrentIndex(1);
   }
   else
-  {
+  {
     cbXLog->setCurrentIndex(0);
   }
 	axisBoxLayout->addWidget(cbXLog, 0, 1);
@@ -984,14 +984,14 @@ void ConfigDialog::initAxesPage()
 	axisBoxLayout->addWidget( lblYLogLin, 1, 0 );
 
   cbYLog = new QComboBox();
-  cbYLog->addItem(tr("linear"));
-  cbYLog->addItem("log");
-  if ( app->yaxisScale == "log" )
-  {
+  cbYLog->addItem(tr("linear"));
+  cbYLog->addItem("log");
+  if ( app->yaxisScale == "log" )
+  {
     cbYLog->setCurrentIndex(1);
   }
   else
-  {
+  {
     cbYLog->setCurrentIndex(0);
   }
 	axisBoxLayout->addWidget(cbYLog, 1, 1);
@@ -1000,14 +1000,14 @@ void ConfigDialog::initAxesPage()
 	axisBoxLayout->addWidget( lblZLogLin, 2, 0 );
 
   cbZLog = new QComboBox();
-  cbZLog->addItem(tr("linear"));
-  cbZLog->addItem("log");
-  if ( app->zaxisScale == "log" )
-  {
+  cbZLog->addItem(tr("linear"));
+  cbZLog->addItem("log");
+  if ( app->zaxisScale == "log" )
+  {
     cbZLog->setCurrentIndex(1);
   }
   else
-  {
+  {
     cbZLog->setCurrentIndex(0);
   }
 	axisBoxLayout->addWidget(cbZLog, 2, 1);
@@ -1216,7 +1216,7 @@ void ConfigDialog::initFileLocationsPage()
 	translationsPathLine->setText(app->d_translations_folder);
 	gl->addWidget(translationsPathLine, 0, 1);
 
-	QPushButton *browseTranslationsBtn = new QPushButton();
+	QPushButton *browseTranslationsBtn = new QPushButton();
 	browseTranslationsBtn->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
 	gl->addWidget(browseTranslationsBtn, 0, 2);
 
@@ -1227,7 +1227,7 @@ void ConfigDialog::initFileLocationsPage()
 	helpPathLine = new QLineEdit(hfi.dir().absolutePath());
 	gl->addWidget( helpPathLine, 1, 1);
 
-	QPushButton *browseHelpBtn = new QPushButton();
+	QPushButton *browseHelpBtn = new QPushButton();
 	browseHelpBtn->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
 	gl->addWidget(browseHelpBtn, 1, 2);
 	gl->setRowStretch(2, 1);
@@ -1239,7 +1239,7 @@ void ConfigDialog::initFileLocationsPage()
 // 	pythonConfigDirLine = new QLineEdit(app->d_python_config_folder);
 // 	gl->addWidget(pythonConfigDirLine, 2, 1);
 
-// 	QPushButton *browsePythonConfigBtn = new QPushButton();
+// 	QPushButton *browsePythonConfigBtn = new QPushButton();
 // 	browsePythonConfigBtn->setIcon(QIcon(getQPixmap("choose_folder_xpm")));
 // 	connect(browsePythonConfigBtn, SIGNAL(clicked()), this, SLOT(choosePythonConfigFolder()));
 // 	gl->addWidget(browsePythonConfigBtn, 2, 2);
@@ -1298,8 +1298,8 @@ void ConfigDialog::languageChange()
     boxLabelsEditing->setText(tr("&Disable in-place editing"));
 	lblMinTicksLength->setText(tr("Length"));
 
-  lblXLogLin->setText(tr("Default X scale"));
-  lblYLogLin->setText(tr("Default Y scale"));
+  lblXLogLin->setText(tr("Default X scale"));
+  lblYLogLin->setText(tr("Default Y scale"));
   lblZLogLin->setText(tr("Default color scale"));
 
 	lblAxesLineWidth->setText(tr("Axes linewidth" ));
@@ -1374,11 +1374,11 @@ void ConfigDialog::languageChange()
 	lblWorkspace->setText(tr("Workspace"));
 	lblPanelsText->setText(tr("Panels text"));
 	lblPanels->setText(tr("Panels"));
-	boxSave->setText(tr("Save every"));
+	boxSave->setText(tr("Save every"));
 	boxBackupProject->setText(tr("&Backup project before saving"));
 	boxSearchUpdates->setText(tr("Check for new versions at startup"));
 	boxMinutes->setSuffix(tr(" minutes"));
-	lblScriptingLanguage->setText(tr("Default scripting language"));
+	lblScriptingLanguage->setText(tr("Default scripting language"));
 	lblUndoStackSize->setText(tr("Matrix Undo Stack Size"));
 	lblEndOfLine->setText(tr("Endline character"));
 	lblInitWindow->setText(tr("Start New Project"));
@@ -1543,7 +1543,7 @@ void ConfigDialog::apply()
 	app->setAutoUpdateTableValues(boxUpdateTableValues->isChecked());
 	app->customizeTables(buttonBackground->color(), buttonText->color(),
 			buttonHeader->color(), textFont, headerFont, boxTableComments->isChecked());
-	// 2D plots page: options tab
+	// 2D plots page: options tab
 	app->d_in_place_editing = !boxLabelsEditing->isChecked();
 	app->titleOn=boxTitle->isChecked();
 	app->allAxesOn = boxAllAxes->isChecked();
@@ -1593,10 +1593,10 @@ void ConfigDialog::apply()
 	setFont(appFont);
 	app->changeAppStyle(boxStyle->currentText());
 	app->autoSearchUpdates = boxSearchUpdates->isChecked();
-	app->setSaveSettings(boxSave->isChecked(), boxMinutes->value());
+	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();
 
diff --git a/Code/Mantid/MantidPlot/src/ConfigDialog.h b/Code/Mantid/MantidPlot/src/ConfigDialog.h
index 28f3f0af4ad9f32ab279e4d3a68da283ab1861d4..0385aaf1cb31d57897f8287be9306ee9bc13620f 100644
--- a/Code/Mantid/MantidPlot/src/ConfigDialog.h
+++ b/Code/Mantid/MantidPlot/src/ConfigDialog.h
@@ -208,7 +208,7 @@ private:
 	QCheckBox *boxPromptRenameTables, *boxBackupProject, *boxLabelsEditing;
 	QWidget *fileLocationsPage;
 	QLabel *lblTranslationsPath, *lblHelpPath, *lblUndoStackSize, *lblEndOfLine;
-	QLineEdit *translationsPathLine, *helpPathLine;
+	QLineEdit *translationsPathLine, *helpPathLine;
 	QSpinBox *undoStackSizeBox;
 	QComboBox *boxEndLine;
   QCheckBox* cbApplyToMantid;
diff --git a/Code/Mantid/MantidPlot/src/ContourLinesEditor.cpp b/Code/Mantid/MantidPlot/src/ContourLinesEditor.cpp
index 0183b245a6b434072dc9cb673c5a63d684a1e85a..3379ca837232501d8abbc69cd75cf253a581f21b 100644
--- a/Code/Mantid/MantidPlot/src/ContourLinesEditor.cpp
+++ b/Code/Mantid/MantidPlot/src/ContourLinesEditor.cpp
@@ -26,31 +26,31 @@
  *                                                                         *
  ***************************************************************************/
 #include "ContourLinesEditor.h"
-#include "DoubleSpinBox.h"
-#include "Spectrogram.h"
+#include "DoubleSpinBox.h"
+#include "Spectrogram.h"
 #include "PenStyleBox.h"
-#include "ColorButton.h"
+#include "ColorButton.h"
 
 #include <QPushButton>
 #include <QTableWidget>
 #include <QHeaderView>
 #include <QCheckBox>
-#include <QLayout>
+#include <QLayout>
 #include <QLabel>
 #include <QKeyEvent>
 #include <QMouseEvent>
-#include <QMessageBox>
+#include <QMessageBox>
 #include <QPainter>
-#include <QGroupBox>
+#include <QGroupBox>
 
 ContourLinesEditor::ContourLinesEditor(const QLocale& locale, int precision, QWidget* parent)
-				: QWidget(parent),
+				: QWidget(parent),
 				d_spectrogram(NULL),
 				d_locale(locale),
 				d_precision(precision)
 {
 	table = new QTableWidget();
-	table->setColumnCount(2);
+	table->setColumnCount(2);
 	table->hideColumn(1);
 	table->setSelectionMode(QAbstractItemView::SingleSelection);
 	table->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
@@ -82,97 +82,97 @@ ContourLinesEditor::ContourLinesEditor(const QLocale& locale, int precision, QWi
 	vl->addLayout(hb);
 
 	setFocusProxy(table);
-	setMaximumWidth(200);
-
+	setMaximumWidth(200);
+
 	penDialog = NULL;
 }
 
 void ContourLinesEditor::updateContourLevels()
-{
-	if (!d_spectrogram)
-		return;
-
-	int rows = table->rowCount();
-	QwtValueList levels;
-	for (int i = 0; i < rows; i++)
-		levels << ((DoubleSpinBox*)table->cellWidget(i, 0))->value();
-
+{
+	if (!d_spectrogram)
+		return;
+
+	int rows = table->rowCount();
+	QwtValueList levels;
+	for (int i = 0; i < rows; i++)
+		levels << ((DoubleSpinBox*)table->cellWidget(i, 0))->value();
+
 	d_spectrogram->setContourLevels(levels);
 }
-
-void ContourLinesEditor::updateContourPens()
-{
-	if (!d_spectrogram)
-		return;
-
-	if (!table->isColumnHidden(1))
-		d_spectrogram->setContourPenList(d_pen_list);
-}
+
+void ContourLinesEditor::updateContourPens()
+{
+	if (!d_spectrogram)
+		return;
+
+	if (!table->isColumnHidden(1))
+		d_spectrogram->setContourPenList(d_pen_list);
+}
 
 void ContourLinesEditor::setSpectrogram(Spectrogram *sp)
-{
-	if (!sp || d_spectrogram == sp)
-		return;
-
+{
+	if (!sp || d_spectrogram == sp)
+		return;
+
 	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;
+{
+	if (!d_spectrogram)
+		return;
 
 	int row = table->currentRow();
 	DoubleSpinBox *sb = (DoubleSpinBox*)table->cellWidget(row, 0);
 	if (!sb)
 		return;
-
+
 	QwtDoubleInterval range = d_spectrogram->data().range();
 	double current_value = sb->value();
 	double previous_value = range.minValue ();
@@ -192,37 +192,37 @@ void ContourLinesEditor::insertLevel()
 	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);
-
+
+	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());
+	enableButtons(table->currentRow());
 	d_pen_list.insert(row, pen);
 }
 
 void ContourLinesEditor::deleteLevel()
-{
+{
 	int index = table->currentRow();
-	table->removeRow (index);
-
-	if (index >=0 && index < d_pen_list.size())
+	table->removeRow (index);
+
+	if (index >=0 && index < d_pen_list.size())
 		d_pen_list.removeAt(index);
 }
 
@@ -233,119 +233,119 @@ void ContourLinesEditor::showPenDialog(int row, int col)
 
 	enableButtons(row);
 
-	QPen pen = d_pen_list[row];
-
-	if (!penDialog){
-		penDialog = new QDialog(this);
-		penDialog->setWindowTitle(tr("MantidPlot - Edit pen"));
-
-		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);
-
-		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);
-
-		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);
-
-		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 *closeBtn = new QPushButton(tr("&Close"));
-		connect(closeBtn, SIGNAL(clicked()), penDialog, SLOT(reject()));
-
-		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());
-	}
-
-	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);
+	QPen pen = d_pen_list[row];
+
+	if (!penDialog){
+		penDialog = new QDialog(this);
+		penDialog->setWindowTitle(tr("MantidPlot - Edit pen"));
+
+		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);
+
+		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);
+
+		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);
+
+		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 *closeBtn = new QPushButton(tr("&Close"));
+		connect(closeBtn, SIGNAL(clicked()), penDialog, SLOT(reject()));
+
+		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());
+	}
+
+	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::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)
 {
@@ -376,8 +376,8 @@ void ContourLinesEditor::enableButtons(int row)
 {
 	if (row < 0)
 		return;
-
-	deleteBtn->setEnabled(true);
+
+	deleteBtn->setEnabled(true);
 	insertBtn->setEnabled(true);
 }
 
@@ -395,18 +395,18 @@ void ContourLinesEditor::spinBoxActivated(DoubleSpinBox *sb)
 			return;
 		}
 	}
-}
-
-void ContourLinesEditor::showPenColumn(bool on)
-{
-	if (on)
-		table->showColumn(1);
-	else
-		table->hideColumn(1);
-}
-
-ContourLinesEditor::~ContourLinesEditor()
-{
-	if(penDialog)
-        delete penDialog;
+}
+
+void ContourLinesEditor::showPenColumn(bool on)
+{
+	if (on)
+		table->showColumn(1);
+	else
+		table->hideColumn(1);
+}
+
+ContourLinesEditor::~ContourLinesEditor()
+{
+	if(penDialog)
+        delete penDialog;
 }
diff --git a/Code/Mantid/MantidPlot/src/ContourLinesEditor.h b/Code/Mantid/MantidPlot/src/ContourLinesEditor.h
index fd765453232020fc5819adbb61cafb93f0be6b85..8efeab3ac9ca00cf4c8d4644bb321ac8f06b3076 100644
--- a/Code/Mantid/MantidPlot/src/ContourLinesEditor.h
+++ b/Code/Mantid/MantidPlot/src/ContourLinesEditor.h
@@ -34,9 +34,9 @@
 class QPushButton;
 class QTableWidget;
 class QCheckBox;
-class DoubleSpinBox;
-class Spectrogram;
-class ColorButton;
+class DoubleSpinBox;
+class Spectrogram;
+class ColorButton;
 class PenStyleBox;
 
 //! A complex widget allowing to customize contour line plots.
@@ -55,15 +55,15 @@ public:
 	/**
 	* @param parent :: parent widget (only affects placement of the widget)
 	*/
-	ContourLinesEditor(const QLocale& locale = QLocale::system(), int precision = 6, QWidget* parent = 0);
+	ContourLinesEditor(const QLocale& locale = QLocale::system(), int precision = 6, QWidget* parent = 0);
 	~ContourLinesEditor();
 	//! 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 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:
@@ -71,31 +71,31 @@ protected slots:
 	void showPenDialog(int row, int col);
 	void insertLevel();
 	void deleteLevel();
-	void spinBoxActivated(DoubleSpinBox *);
+	void spinBoxActivated(DoubleSpinBox *);
 	void updatePen();
 
 	bool eventFilter(QObject *object, QEvent *e);
 
-private:
-	void updatePenColumn();
+private:
+	void updatePenColumn();
 
 	//! Table displaying the values ranges in the first column and their corresponding pens in the second column
 	QTableWidget *table;
-	QPushButton *insertBtn, *deleteBtn;
+	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;
-
-	QDialog *penDialog;
-	ColorButton *penColorBox;
-	PenStyleBox *penStyleBox;
-	DoubleSpinBox *penWidthBox;
-	QCheckBox *applyAllColorBox, *applyAllWidthBox, *applyAllStyleBox;
-
-	int d_pen_index;
+	int d_precision;
+
+	QDialog *penDialog;
+	ColorButton *penColorBox;
+	PenStyleBox *penStyleBox;
+	DoubleSpinBox *penWidthBox;
+	QCheckBox *applyAllColorBox, *applyAllWidthBox, *applyAllStyleBox;
+
+	int d_pen_index;
 	QList<QPen> d_pen_list;
 };
 
diff --git a/Code/Mantid/MantidPlot/src/Convolution.cpp b/Code/Mantid/MantidPlot/src/Convolution.cpp
index d832e3d363fe038c631cbf7325a2f70ff6b5511d..68edb1709821894537af2ce8ea343035466a2d21 100644
--- a/Code/Mantid/MantidPlot/src/Convolution.cpp
+++ b/Code/Mantid/MantidPlot/src/Convolution.cpp
@@ -123,8 +123,8 @@ void Convolution::setDataFromTable(Table *t, const QString& signalColName, const
 void Convolution::output()
 {
 	convlv(d_x, d_n_signal, d_y, d_n_response, 1);
-	addResultCurve();
-    d_result_table = d_table;
+	addResultCurve();
+    d_result_table = d_table;
 }
 
 void Convolution::addResultCurve()
@@ -235,6 +235,6 @@ Deconvolution::Deconvolution(ApplicationWindow *parent, Table *t, const QString&
 void Deconvolution::output()
 {
 	convlv(d_x, signalDataSize(), d_y, responseDataSize(), -1);
-	addResultCurve();
+	addResultCurve();
     d_result_table = d_table;
 }
diff --git a/Code/Mantid/MantidPlot/src/Correlation.cpp b/Code/Mantid/MantidPlot/src/Correlation.cpp
index 2af1f40612ed930fcb8e02bf981505292414ec92..3e75e64a2ad13faeea75126640ae32f802fb8719 100644
--- a/Code/Mantid/MantidPlot/src/Correlation.cpp
+++ b/Code/Mantid/MantidPlot/src/Correlation.cpp
@@ -45,9 +45,9 @@ Correlation::Correlation(ApplicationWindow *parent, Table *t, const QString& col
 
 bool Correlation::setDataFromTable(Table *t, const QString& colName1, const QString& colName2, int startRow, int endRow)
 {
-    if (!t)
-        return false;
-
+    if (!t)
+        return false;
+
     d_table = t;
 
     int col1 = d_table->colIndex(colName1);
@@ -69,15 +69,15 @@ bool Correlation::setDataFromTable(Table *t, const QString& colName1, const QStr
 		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);
+
+    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
@@ -85,12 +85,12 @@ bool Correlation::setDataFromTable(Table *t, const QString& colName1, const QStr
 		d_n *= 2;
 
     d_x = new double[d_n];
-	d_y = 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++){
+		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);
@@ -99,9 +99,9 @@ bool Correlation::setDataFromTable(Table *t, const QString& colName1, const QStr
 		QMessageBox::critical((ApplicationWindow *)parent(), tr("MantidPlot") + " - " + tr("Error"),
                         tr("Could not allocate memory, operation aborted!"));
         d_init_err = true;
-		d_n = 0;
+		d_n = 0;
 		return false;
-	}
+	}
 	return true;
 }
 
@@ -130,7 +130,7 @@ void Correlation::output()
 
 	gsl_fft_halfcomplex_radix2_inverse(d_x, 1, d_n );	//inverse FFT
 
-	addResultCurve();
+	addResultCurve();
     d_result_table = d_table;
 }
 
@@ -142,15 +142,15 @@ void Correlation::addResultCurve()
 
     QLocale locale = app->locale();
 
-    if (d_n > d_table->numRows())
-        d_table->setNumRows(d_n);
+    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;
-
+	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;
@@ -160,8 +160,8 @@ void Correlation::addResultCurve()
         if(i < n)
 			y = d_x[n + i];
 		else
-			y = d_x[i - n];
-        y_temp[i] = y;
+			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));
@@ -175,7 +175,7 @@ void Correlation::addResultCurve()
 	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();
@@ -185,5 +185,5 @@ void Correlation::addResultCurve()
     	c->setPen(QPen(ColorBox::color(d_curveColorIndex), 1));
 		d_output_graph->insertPlotItem(c, Graph::Line);
 		d_output_graph->updatePlot();
-	}
+	}
 }
diff --git a/Code/Mantid/MantidPlot/src/CustomActionDialog.cpp b/Code/Mantid/MantidPlot/src/CustomActionDialog.cpp
index 767cd629fdb89c4e62481d52bb341c0b9b9f6f7f..59bc059e5ad953eaf0559999d5ab74e8e2d2f2f5 100644
--- a/Code/Mantid/MantidPlot/src/CustomActionDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/CustomActionDialog.cpp
@@ -1,601 +1,601 @@
-/***************************************************************************
-    File                 : CustomActionDialog.cpp
-    Project              : QtiPlot
-    --------------------------------------------------------------------
-    Copyright            : (C) 2007 by Ion Vasilief
-    Email (use @ for *)  : ion_vasilief*yahoo.fr
-    Description          : Custom Action dialog
-
- ***************************************************************************/
-
-/***************************************************************************
- *                                                                         *
- *  This program is free software; you can redistribute it and/or modify   *
- *  it under the terms of the GNU General Public License as published by   *
- *  the Free Software Foundation; either version 2 of the License, or      *
- *  (at your option) any later version.                                    *
- *                                                                         *
- *  This program is distributed in the hope that it will be useful,        *
- *  but WITHOUT 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, write to the Free Software           *
- *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
- *   Boston, MA  02110-1301  USA                                           *
- *                                                                         *
- ***************************************************************************/
-#include "CustomActionDialog.h"
-#include "ApplicationWindow.h"
-
-#include <QPushButton>
-#include <QRadioButton>
-#include <QLabel>
-#include <QGroupBox>
-#include <QComboBox>
-#include <QLineEdit>
-#include <QAction>
-#include <QApplication>
-#include <QDir>
-#include <QListWidget>
-#include <QLayout>
-#include <QFileDialog>
-#include <QToolBar>
-#include <QMenu>
-#include <QImageReader>
-#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)));
-}
-
-void CustomActionDialog::init()
-{
-	ApplicationWindow *app = (ApplicationWindow *)parent();
-	folderBox->setText(app->customActionsDirPath);
-
-	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("&");
-	   }
-    }
-	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;
-		}
-    }
-    toolBars.sort();
-	toolBarBox->addItems(toolBars);
-
-	updateDisplayList();
-}
-
-void CustomActionDialog::updateDisplayList()
-{
-	itemsList->clear();
-
-	QList<QAction *> actionsList = ((ApplicationWindow *)parentWidget())->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);
-}
-
-QAction* CustomActionDialog::addAction()
-{
-	QAction *action = NULL;
-    ApplicationWindow *app = (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 + ")";
-
-    	QListWidgetItem *it = new QListWidgetItem(text, itemsList);
-    	if (!action->icon().isNull())
-        	it->setIcon(action->icon());
-    	itemsList->addItem(it);
-    	itemsList->setCurrentItem(it);
-
-    	saveAction(action);
-	}
-    return action;
-}
-
-bool CustomActionDialog::validUserInput()
-{
-	QString folder = folderBox->text();
-    while (folder.isEmpty() || !QFileInfo(folder).exists() || !QFileInfo(folder).isReadable()){
-        chooseFolder();
-		folder = folderBox->text();
-	}
-
-	ApplicationWindow *app = (ApplicationWindow *)this->parent();
-	QList<QAction *>actions = app->customActionsList();
-
-	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"),
-        tr("Dot characters are not allowed in the description text!"));
-        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 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;
-    }
-
-	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;
-}
-
-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());
-    }
-
-    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 = (ApplicationWindow *)parentWidget();
-    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
-		ApplicationWindow *app = (ApplicationWindow *)parent();
-		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;
-                }
-            }
-        }
-		saveAction(newAction);
-		delete action;
-	} else {
-		customizeAction(action);
-		saveAction(action);
-	}
-}
-
-void CustomActionDialog::saveAction(QAction *action)
-{
-    if (!action)
-        return;
-
-    ApplicationWindow *app = (ApplicationWindow *)parent();
-    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::chooseFile()
-{
-    QString fileName = QFileDialog::getOpenFileName(this, tr("Choose script file"), fileBox->text());
-    if (!fileName.isEmpty())
-        fileBox->setText(fileName);
-}
-
-void CustomActionDialog::chooseFolder()
-{
-    ApplicationWindow *app = (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);
-
-        app->customActionsDirPath = dir;
-        app->loadCustomActions();
-		updateDisplayList();
-        folderBox->setText(dir);
-    }
-}
-
-QAction * CustomActionDialog::actionAt(int row)
-{
-	ApplicationWindow *app = (ApplicationWindow *)this->parent();
-	QList<QAction *>actions = app->customActionsList();
-	if (actions.isEmpty() || row < 0 || row >= actions.count())
-        return 0;
-
-    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 (w->isA("QToolBar")){
-    	int index = toolBarBox->findText(((QToolBar*)w)->windowTitle());
-    	if (index >= 0){
-        	toolBarBox->setCurrentIndex(index);
-        	toolBarBtn->setChecked(true);
-    	}
-	} else {
-        int index = menuBox->findText(((QMenu*)w)->title().remove("&"));
-        if (index >= 0){
-            menuBox->setCurrentIndex(index);
-            menuBtn->setChecked(true);
-        }
-    }
-}
-
-/*****************************************************************************
- *
- * Class CustomActionHandler
- *
- *****************************************************************************/
-
-CustomActionHandler::CustomActionHandler(QAction *action)
-     : d_action(action)
- {
-     metFitTag = false;
-     filePath = QString();
-	 d_widget_name = QString();
- }
-
-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;
-}
-
-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;
+/***************************************************************************
+    File                 : CustomActionDialog.cpp
+    Project              : QtiPlot
+    --------------------------------------------------------------------
+    Copyright            : (C) 2007 by Ion Vasilief
+    Email (use @ for *)  : ion_vasilief*yahoo.fr
+    Description          : Custom Action dialog
+
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *  This program is free software; you can redistribute it and/or modify   *
+ *  it under the terms of the GNU General Public License as published by   *
+ *  the Free Software Foundation; either version 2 of the License, or      *
+ *  (at your option) any later version.                                    *
+ *                                                                         *
+ *  This program is distributed in the hope that it will be useful,        *
+ *  but WITHOUT 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, write to the Free Software           *
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
+ *   Boston, MA  02110-1301  USA                                           *
+ *                                                                         *
+ ***************************************************************************/
+#include "CustomActionDialog.h"
+#include "ApplicationWindow.h"
+
+#include <QPushButton>
+#include <QRadioButton>
+#include <QLabel>
+#include <QGroupBox>
+#include <QComboBox>
+#include <QLineEdit>
+#include <QAction>
+#include <QApplication>
+#include <QDir>
+#include <QListWidget>
+#include <QLayout>
+#include <QFileDialog>
+#include <QToolBar>
+#include <QMenu>
+#include <QImageReader>
+#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)));
+}
+
+void CustomActionDialog::init()
+{
+	ApplicationWindow *app = (ApplicationWindow *)parent();
+	folderBox->setText(app->customActionsDirPath);
+
+	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("&");
+	   }
+    }
+	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;
+		}
+    }
+    toolBars.sort();
+	toolBarBox->addItems(toolBars);
+
+	updateDisplayList();
+}
+
+void CustomActionDialog::updateDisplayList()
+{
+	itemsList->clear();
+
+	QList<QAction *> actionsList = ((ApplicationWindow *)parentWidget())->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);
+}
+
+QAction* CustomActionDialog::addAction()
+{
+	QAction *action = NULL;
+    ApplicationWindow *app = (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 + ")";
+
+    	QListWidgetItem *it = new QListWidgetItem(text, itemsList);
+    	if (!action->icon().isNull())
+        	it->setIcon(action->icon());
+    	itemsList->addItem(it);
+    	itemsList->setCurrentItem(it);
+
+    	saveAction(action);
+	}
+    return action;
+}
+
+bool CustomActionDialog::validUserInput()
+{
+	QString folder = folderBox->text();
+    while (folder.isEmpty() || !QFileInfo(folder).exists() || !QFileInfo(folder).isReadable()){
+        chooseFolder();
+		folder = folderBox->text();
+	}
+
+	ApplicationWindow *app = (ApplicationWindow *)this->parent();
+	QList<QAction *>actions = app->customActionsList();
+
+	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"),
+        tr("Dot characters are not allowed in the description text!"));
+        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 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;
+    }
+
+	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;
+}
+
+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());
+    }
+
+    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 = (ApplicationWindow *)parentWidget();
+    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
+		ApplicationWindow *app = (ApplicationWindow *)parent();
+		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;
+                }
+            }
+        }
+		saveAction(newAction);
+		delete action;
+	} else {
+		customizeAction(action);
+		saveAction(action);
+	}
+}
+
+void CustomActionDialog::saveAction(QAction *action)
+{
+    if (!action)
+        return;
+
+    ApplicationWindow *app = (ApplicationWindow *)parent();
+    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::chooseFile()
+{
+    QString fileName = QFileDialog::getOpenFileName(this, tr("Choose script file"), fileBox->text());
+    if (!fileName.isEmpty())
+        fileBox->setText(fileName);
+}
+
+void CustomActionDialog::chooseFolder()
+{
+    ApplicationWindow *app = (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);
+
+        app->customActionsDirPath = dir;
+        app->loadCustomActions();
+		updateDisplayList();
+        folderBox->setText(dir);
+    }
+}
+
+QAction * CustomActionDialog::actionAt(int row)
+{
+	ApplicationWindow *app = (ApplicationWindow *)this->parent();
+	QList<QAction *>actions = app->customActionsList();
+	if (actions.isEmpty() || row < 0 || row >= actions.count())
+        return 0;
+
+    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 (w->isA("QToolBar")){
+    	int index = toolBarBox->findText(((QToolBar*)w)->windowTitle());
+    	if (index >= 0){
+        	toolBarBox->setCurrentIndex(index);
+        	toolBarBtn->setChecked(true);
+    	}
+	} else {
+        int index = menuBox->findText(((QMenu*)w)->title().remove("&"));
+        if (index >= 0){
+            menuBox->setCurrentIndex(index);
+            menuBtn->setChecked(true);
+        }
+    }
+}
+
+/*****************************************************************************
+ *
+ * Class CustomActionHandler
+ *
+ *****************************************************************************/
+
+CustomActionHandler::CustomActionHandler(QAction *action)
+     : d_action(action)
+ {
+     metFitTag = false;
+     filePath = QString();
+	 d_widget_name = QString();
+ }
+
+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;
+}
+
+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;
 }
diff --git a/Code/Mantid/MantidPlot/src/CustomActionDialog.h b/Code/Mantid/MantidPlot/src/CustomActionDialog.h
index ba74b14539c2e0d5b883b2e1e4e77186e6d90375..8711b84133115dc7dd006de1b651f50711207d8e 100644
--- a/Code/Mantid/MantidPlot/src/CustomActionDialog.h
+++ b/Code/Mantid/MantidPlot/src/CustomActionDialog.h
@@ -1,107 +1,107 @@
-/***************************************************************************
-    File                 : CustomActionDialog.h
-    Project              : QtiPlot
-    --------------------------------------------------------------------
-    Copyright            : (C) 2007 by Ion Vasilief
-    Email (use @ for *)  : ion_vasilief*yahoo.fr
-    Description          : Custom Action dialog
-
- ***************************************************************************/
-
-/***************************************************************************
- *                                                                         *
- *  This program is free software; you can redistribute it and/or modify   *
- *  it under the terms of the GNU General Public License as published by   *
- *  the Free Software Foundation; either version 2 of the License, or      *
- *  (at your option) any later version.                                    *
- *                                                                         *
- *  This program is distributed in the hope that it will be useful,        *
- *  but WITHOUT 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, write to the Free Software           *
- *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
- *   Boston, MA  02110-1301  USA                                           *
- *                                                                         *
- ***************************************************************************/
-#ifndef CustomActionDialog_H
-#define CustomActionDialog_H
-
-#include <QDialog>
-#include <QXmlDefaultHandler>
-
-class QGroupBox;
-class QPushButton;
-class QRadioButton;
-class QComboBox;
-class QListWidget;
-class QLineEdit;
-class QMenu;
-class QToolBar;
-
-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 );
-
-private slots:
-	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;
-
-	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;
-};
-
-class CustomActionHandler : public QXmlDefaultHandler
-{
-public:
-    CustomActionHandler(QAction *action);
-
-    bool startElement(const QString &namespaceURI, const QString &localName,
-                       const QString &qName, const QXmlAttributes &attributes);
-    bool endElement(const QString &namespaceURI, const QString &localName,
-                     const QString &qName);
-    bool characters(const QString &str){currentText += str; return true;};
-    bool fatalError(const QXmlParseException &){return false;};
-    QString errorString() const {return errorStr;};
-	QString parentName(){return d_widget_name;};
-
-private:
-    bool metFitTag;
-    QString currentText;
-    QString errorStr;
-    QString filePath;
-	QString d_widget_name;
-    QAction *d_action;
-};
+/***************************************************************************
+    File                 : CustomActionDialog.h
+    Project              : QtiPlot
+    --------------------------------------------------------------------
+    Copyright            : (C) 2007 by Ion Vasilief
+    Email (use @ for *)  : ion_vasilief*yahoo.fr
+    Description          : Custom Action dialog
+
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *  This program is free software; you can redistribute it and/or modify   *
+ *  it under the terms of the GNU General Public License as published by   *
+ *  the Free Software Foundation; either version 2 of the License, or      *
+ *  (at your option) any later version.                                    *
+ *                                                                         *
+ *  This program is distributed in the hope that it will be useful,        *
+ *  but WITHOUT 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, write to the Free Software           *
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
+ *   Boston, MA  02110-1301  USA                                           *
+ *                                                                         *
+ ***************************************************************************/
+#ifndef CustomActionDialog_H
+#define CustomActionDialog_H
+
+#include <QDialog>
+#include <QXmlDefaultHandler>
+
+class QGroupBox;
+class QPushButton;
+class QRadioButton;
+class QComboBox;
+class QListWidget;
+class QLineEdit;
+class QMenu;
+class QToolBar;
+
+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 );
+
+private slots:
+	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;
+
+	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;
+};
+
+class CustomActionHandler : public QXmlDefaultHandler
+{
+public:
+    CustomActionHandler(QAction *action);
+
+    bool startElement(const QString &namespaceURI, const QString &localName,
+                       const QString &qName, const QXmlAttributes &attributes);
+    bool endElement(const QString &namespaceURI, const QString &localName,
+                     const QString &qName);
+    bool characters(const QString &str){currentText += str; return true;};
+    bool fatalError(const QXmlParseException &){return false;};
+    QString errorString() const {return errorStr;};
+	QString parentName(){return d_widget_name;};
+
+private:
+    bool metFitTag;
+    QString currentText;
+    QString errorStr;
+    QString filePath;
+	QString d_widget_name;
+    QAction *d_action;
+};
 #endif
diff --git a/Code/Mantid/MantidPlot/src/DataPickerTool.cpp b/Code/Mantid/MantidPlot/src/DataPickerTool.cpp
index 429683efa00d30f8bdb528d928232353f4aca9f7..270897440f1951c90c2310c68b711cdd68b99061 100644
--- a/Code/Mantid/MantidPlot/src/DataPickerTool.cpp
+++ b/Code/Mantid/MantidPlot/src/DataPickerTool.cpp
@@ -189,23 +189,23 @@ bool DataPickerTool::keyEventFilter(QKeyEvent *ke)
 		case Qt::Key_Return:
 			emit selected(d_selected_curve, d_selected_point);
 			return true;
-
-        case Qt::Key_Home:
-			setSelection(d_selected_curve, 0);
-			return true;
-
-		case Qt::Key_End:
-			setSelection(d_selected_curve, d_selected_curve->dataSize() - 1);
-			return true;
+
+        case Qt::Key_Home:
+			setSelection(d_selected_curve, 0);
+			return true;
+
+		case Qt::Key_End:
+			setSelection(d_selected_curve, d_selected_curve->dataSize() - 1);
+			return true;
 
 		case Qt::Key_Up:
 			{
 				int n_curves = d_graph->curves();
 				int start = d_graph->curveIndex(d_selected_curve) + 1;
 				for (int i = start; i < start + n_curves; ++i)
-					if (d_graph->curve(i % n_curves)->dataSize() > 0) {
-					    QwtPlotCurve *c = d_graph->curve(i % n_curves);
-					    if (c)
+					if (d_graph->curve(i % n_curves)->dataSize() > 0) {
+					    QwtPlotCurve *c = d_graph->curve(i % n_curves);
+					    if (c)
                             setSelection(c, findClosestPoint(c, d_selected_curve->x(d_selected_point), true));
 						break;
 					}
@@ -219,9 +219,9 @@ bool DataPickerTool::keyEventFilter(QKeyEvent *ke)
 				int start = d_graph->curveIndex(d_selected_curve) + n_curves - 1;
 				for (int i = start; i > start - n_curves; --i)
 					if (d_graph->curve(i % n_curves)->dataSize() > 0) {
-						QwtPlotCurve *c = d_graph->curve(i % n_curves);
-					    if (c)
-                            setSelection(c, findClosestPoint(c, d_selected_curve->x(d_selected_point), false));
+						QwtPlotCurve *c = d_graph->curve(i % n_curves);
+					    if (c)
+                            setSelection(c, findClosestPoint(c, d_selected_curve->x(d_selected_point), false));
 
 						break;
 					}
@@ -232,9 +232,9 @@ bool DataPickerTool::keyEventFilter(QKeyEvent *ke)
 		case Qt::Key_Right:
 		case Qt::Key_Plus:
 			if (d_selected_curve) {
-				int n_points = d_selected_curve->dataSize();
-				if (ke->modifiers () == Qt::ShiftModifier)
-                    setSelection(d_selected_curve, (d_selected_point + 10) % n_points);
+				int n_points = d_selected_curve->dataSize();
+				if (ke->modifiers () == Qt::ShiftModifier)
+                    setSelection(d_selected_curve, (d_selected_point + 10) % n_points);
                 else if (ke->modifiers () == Qt::NoModifier)
                     setSelection(d_selected_curve, (d_selected_point + 1) % n_points);
 				d_graph->plotWidget()->replot();
@@ -245,9 +245,9 @@ bool DataPickerTool::keyEventFilter(QKeyEvent *ke)
 		case Qt::Key_Left:
 		case Qt::Key_Minus:
 			if (d_selected_curve) {
-				int n_points = d_selected_curve->dataSize();
-				if (ke->modifiers () == Qt::ShiftModifier)
-                    setSelection(d_selected_curve, (d_selected_point - 10 + n_points) % n_points);
+				int n_points = d_selected_curve->dataSize();
+				if (ke->modifiers () == Qt::ShiftModifier)
+                    setSelection(d_selected_curve, (d_selected_point - 10 + n_points) % n_points);
                 else if (ke->modifiers () == Qt::NoModifier)
                     setSelection(d_selected_curve, (d_selected_point - 1 + n_points) % n_points);
 				d_graph->plotWidget()->replot();
@@ -518,29 +518,29 @@ void DataPickerTool::selectTableRow()
     int row = ((DataCurve*)d_selected_curve)->tableRow(d_selected_point);
     t->goToRow(row + 1);
 }
-
-int DataPickerTool::findClosestPoint(QwtPlotCurve *c, double x, bool up)
-{
-    if (!c)
-        return -1;
-
-    if (c->minXValue() > x)
-        return 0;
-
-    if (c->maxXValue() < x)
-        return c->dataSize() - 1;
-
-    int index_left = 0;
-    int index_right = c->dataSize() - 1;
-    while ((index_right - index_left)>1) {
-        int middle = (index_right + index_left)/2;
-        if (c->x(index_left) < x && c->x(middle) > x)
-            index_right = middle;
-        else
-            index_left = middle;
-    }
-    if (up)
-        return index_left;
-    else
-        return index_right;
+
+int DataPickerTool::findClosestPoint(QwtPlotCurve *c, double x, bool up)
+{
+    if (!c)
+        return -1;
+
+    if (c->minXValue() > x)
+        return 0;
+
+    if (c->maxXValue() < x)
+        return c->dataSize() - 1;
+
+    int index_left = 0;
+    int index_right = c->dataSize() - 1;
+    while ((index_right - index_left)>1) {
+        int middle = (index_right + index_left)/2;
+        if (c->x(index_left) < x && c->x(middle) > x)
+            index_right = middle;
+        else
+            index_left = middle;
+    }
+    if (up)
+        return index_left;
+    else
+        return index_right;
 }
diff --git a/Code/Mantid/MantidPlot/src/DataPickerTool.h b/Code/Mantid/MantidPlot/src/DataPickerTool.h
index 1b1dfd97eaa8de6656f27e59e7e486bcc761f443..1094b9e9f7c05a60300f2af32ddbd3c5c9013736 100644
--- a/Code/Mantid/MantidPlot/src/DataPickerTool.h
+++ b/Code/Mantid/MantidPlot/src/DataPickerTool.h
@@ -56,9 +56,9 @@ class DataPickerTool : public QwtPlotPicker, public PlotToolInterface
         void copySelection();
         void cutSelection();
         void pasteSelection();
-        void removePoint();
-        //! Searches the index of the closest point to the given x coordinate
-        int findClosestPoint(QwtPlotCurve *c, double x, bool up);
+        void removePoint();
+        //! Searches the index of the closest point to the given x coordinate
+        int findClosestPoint(QwtPlotCurve *c, double x, bool up);
 
         virtual int rtti() const {return PlotToolInterface::Rtti_DataPicker;};
 
diff --git a/Code/Mantid/MantidPlot/src/Differentiation.cpp b/Code/Mantid/MantidPlot/src/Differentiation.cpp
index 87b9000bc01d971503ec1c32a4115510f193f276..b7a96bde24f92b355b3cd2d57830f2e649d94370 100644
--- a/Code/Mantid/MantidPlot/src/Differentiation.cpp
+++ b/Code/Mantid/MantidPlot/src/Differentiation.cpp
@@ -91,13 +91,13 @@ void Differentiation::output()
 		if (!d_output_graph)
 			d_output_graph = createOutputGraph()->activeGraph();
 
-    	d_output_graph->insertCurve(d_result_table, tableName + "_2", 0);
+    	d_output_graph->insertCurve(d_result_table, tableName + "_2", 0);
     	QString legend = "\\l(1)" + tr("Derivative") + " " + tr("of","Derivative of") + " " + dataSet;
     	LegendWidget *l = d_output_graph->legend();
 		if (l){
-    		l->setText(legend);
-    		l->repaint();
-        } else
+    		l->setText(legend);
+    		l->repaint();
+        } else
             d_output_graph->newLegend(legend);
 	}
 }
diff --git a/Code/Mantid/MantidPlot/src/DoubleSpinBox.cpp b/Code/Mantid/MantidPlot/src/DoubleSpinBox.cpp
index 06d962c4b287070ca4743290d9e6cd717a8f12db..be4d529b11ef9b843eabd6288ce7f5b6061807db 100644
--- a/Code/Mantid/MantidPlot/src/DoubleSpinBox.cpp
+++ b/Code/Mantid/MantidPlot/src/DoubleSpinBox.cpp
@@ -1,169 +1,169 @@
-/***************************************************************************
-    File                 : DoubleSpinBox.cpp
-    Project              : QtiPlot
-    --------------------------------------------------------------------
-    Copyright            : (C) 2007-2008 by Ion Vasilief
-    Email (use @ for *)  : ion_vasilief*yahoo.fr
-    Description          : A Double Spin Box
-
- ***************************************************************************/
-
-/***************************************************************************
- *                                                                         *
- *  This program is free software; you can redistribute it and/or modify   *
- *  it under the terms of the GNU General Public License as published by   *
- *  the Free Software Foundation; either version 2 of the License, or      *
- *  (at your option) any later version.                                    *
- *                                                                         *
- *  This program is distributed in the hope that it will be useful,        *
- *  but WITHOUT 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, write to the Free Software           *
- *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
- *   Boston, MA  02110-1301  USA                                           *
- *                                                                         *
- ***************************************************************************/
-#include "DoubleSpinBox.h"
-#include <QLineEdit>
-#include <QHBoxLayout>
-#include <QCloseEvent>
-#include <float.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(1)
-{
-    lineEdit()->setText(locale().toString(d_value, d_format, d_prec));
-	setKeyboardTracking(false);
-	setWrapping(false);
-	connect(this, SIGNAL(editingFinished()), this, SLOT(interpretText()));
-}
-
-void DoubleSpinBox::setSingleStep(double val)
-{
-    if (d_step != val && val < d_max_val)
-        d_step = val;
-}
-
-void DoubleSpinBox::setMaximum(double max)
-{
-	if (max == d_max_val || max > DBL_MAX)
-		return;
-
-	d_max_val = max;
-}
-
-void DoubleSpinBox::setMinimum(double min)
-{
-	if (min == d_min_val || min < -DBL_MAX)
-		return;
-
-	d_min_val = min;
-}
-
-void DoubleSpinBox::setRange(double min, double max)
-{
-	setMinimum(min);
-	setMaximum(max);
-}
-
-void DoubleSpinBox::interpretText()
-{
-	bool ok = false;
-	double value = locale().toDouble(text(), &ok);
-	if (ok && setValue(value))
-        emit valueChanged(d_value);
-    else
-        lineEdit()->setText(textFromValue(d_value));
-}
-
-void DoubleSpinBox::stepBy ( int steps )
-{
-	if (setValue(d_value + steps * d_step))
-        emit valueChanged(d_value);
-}
-
-QAbstractSpinBox::StepEnabled DoubleSpinBox::stepEnabled () const
-{
-	QAbstractSpinBox::StepEnabled stepDown = QAbstractSpinBox::StepNone;
-	if (d_value > d_min_val)
-		stepDown = StepDownEnabled;
-
-	QAbstractSpinBox::StepEnabled stepUp = QAbstractSpinBox::StepNone;
-	if (d_value < d_max_val)
-		stepUp = StepUpEnabled;
-
-	return stepDown | stepUp;
-}
-
-bool DoubleSpinBox::setValue(double val)
-{
-	if (val < d_min_val || val > d_max_val){
-        lineEdit()->setText(textFromValue(d_value));
-        return false;
-	}
-
-    d_value = val;
-	lineEdit()->setText(textFromValue(d_value));
-	return true;
-}
-
-QString DoubleSpinBox::textFromValue ( double value) const
-{
-	if (d_prec < 14)
-		return locale().toString(value, d_format, d_prec);
-
-	return locale().toString(value, d_format, 6);
-}
-
-QValidator::State DoubleSpinBox::validate(QString & , int & ) const
-{
-	return QValidator::Acceptable;
-}
-
-/*****************************************************************************
- *
- * Class RangeLimitBox
- *
- *****************************************************************************/
-
-RangeLimitBox::RangeLimitBox(LimitType type, QWidget * parent)
-:QWidget(parent),
-d_type(type)
-{
-    d_checkbox = new QCheckBox();
-	d_spin_box = new DoubleSpinBox();
-	d_spin_box->setSpecialValueText(" ");
-	d_spin_box->setValue(-DBL_MAX);
-	d_spin_box->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
-	d_spin_box->setEnabled(false);
-
-	QHBoxLayout *l = new QHBoxLayout(this);
-	l->setMargin(0);
-	l->setSpacing(0);
-	l->addWidget(d_checkbox);
-	l->addWidget(d_spin_box);
-
-	setFocusPolicy(Qt::StrongFocus);
-    setFocusProxy(d_spin_box);
-	connect(d_checkbox, SIGNAL(toggled(bool)), d_spin_box, SLOT(setEnabled(bool)));
-}
-
-double RangeLimitBox::value()
-{
-	if (d_checkbox->isChecked())
-		return d_spin_box->value();
-
-	double val = -DBL_MAX;
-	if (d_type == RightLimit)
-		return DBL_MAX;
-	return val;
+/***************************************************************************
+    File                 : DoubleSpinBox.cpp
+    Project              : QtiPlot
+    --------------------------------------------------------------------
+    Copyright            : (C) 2007-2008 by Ion Vasilief
+    Email (use @ for *)  : ion_vasilief*yahoo.fr
+    Description          : A Double Spin Box
+
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *  This program is free software; you can redistribute it and/or modify   *
+ *  it under the terms of the GNU General Public License as published by   *
+ *  the Free Software Foundation; either version 2 of the License, or      *
+ *  (at your option) any later version.                                    *
+ *                                                                         *
+ *  This program is distributed in the hope that it will be useful,        *
+ *  but WITHOUT 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, write to the Free Software           *
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
+ *   Boston, MA  02110-1301  USA                                           *
+ *                                                                         *
+ ***************************************************************************/
+#include "DoubleSpinBox.h"
+#include <QLineEdit>
+#include <QHBoxLayout>
+#include <QCloseEvent>
+#include <float.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(1)
+{
+    lineEdit()->setText(locale().toString(d_value, d_format, d_prec));
+	setKeyboardTracking(false);
+	setWrapping(false);
+	connect(this, SIGNAL(editingFinished()), this, SLOT(interpretText()));
+}
+
+void DoubleSpinBox::setSingleStep(double val)
+{
+    if (d_step != val && val < d_max_val)
+        d_step = val;
+}
+
+void DoubleSpinBox::setMaximum(double max)
+{
+	if (max == d_max_val || max > DBL_MAX)
+		return;
+
+	d_max_val = max;
+}
+
+void DoubleSpinBox::setMinimum(double min)
+{
+	if (min == d_min_val || min < -DBL_MAX)
+		return;
+
+	d_min_val = min;
+}
+
+void DoubleSpinBox::setRange(double min, double max)
+{
+	setMinimum(min);
+	setMaximum(max);
+}
+
+void DoubleSpinBox::interpretText()
+{
+	bool ok = false;
+	double value = locale().toDouble(text(), &ok);
+	if (ok && setValue(value))
+        emit valueChanged(d_value);
+    else
+        lineEdit()->setText(textFromValue(d_value));
+}
+
+void DoubleSpinBox::stepBy ( int steps )
+{
+	if (setValue(d_value + steps * d_step))
+        emit valueChanged(d_value);
+}
+
+QAbstractSpinBox::StepEnabled DoubleSpinBox::stepEnabled () const
+{
+	QAbstractSpinBox::StepEnabled stepDown = QAbstractSpinBox::StepNone;
+	if (d_value > d_min_val)
+		stepDown = StepDownEnabled;
+
+	QAbstractSpinBox::StepEnabled stepUp = QAbstractSpinBox::StepNone;
+	if (d_value < d_max_val)
+		stepUp = StepUpEnabled;
+
+	return stepDown | stepUp;
+}
+
+bool DoubleSpinBox::setValue(double val)
+{
+	if (val < d_min_val || val > d_max_val){
+        lineEdit()->setText(textFromValue(d_value));
+        return false;
+	}
+
+    d_value = val;
+	lineEdit()->setText(textFromValue(d_value));
+	return true;
+}
+
+QString DoubleSpinBox::textFromValue ( double value) const
+{
+	if (d_prec < 14)
+		return locale().toString(value, d_format, d_prec);
+
+	return locale().toString(value, d_format, 6);
+}
+
+QValidator::State DoubleSpinBox::validate(QString & , int & ) const
+{
+	return QValidator::Acceptable;
+}
+
+/*****************************************************************************
+ *
+ * Class RangeLimitBox
+ *
+ *****************************************************************************/
+
+RangeLimitBox::RangeLimitBox(LimitType type, QWidget * parent)
+:QWidget(parent),
+d_type(type)
+{
+    d_checkbox = new QCheckBox();
+	d_spin_box = new DoubleSpinBox();
+	d_spin_box->setSpecialValueText(" ");
+	d_spin_box->setValue(-DBL_MAX);
+	d_spin_box->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
+	d_spin_box->setEnabled(false);
+
+	QHBoxLayout *l = new QHBoxLayout(this);
+	l->setMargin(0);
+	l->setSpacing(0);
+	l->addWidget(d_checkbox);
+	l->addWidget(d_spin_box);
+
+	setFocusPolicy(Qt::StrongFocus);
+    setFocusProxy(d_spin_box);
+	connect(d_checkbox, SIGNAL(toggled(bool)), d_spin_box, SLOT(setEnabled(bool)));
+}
+
+double RangeLimitBox::value()
+{
+	if (d_checkbox->isChecked())
+		return d_spin_box->value();
+
+	double val = -DBL_MAX;
+	if (d_type == RightLimit)
+		return DBL_MAX;
+	return val;
 }
diff --git a/Code/Mantid/MantidPlot/src/DoubleSpinBox.h b/Code/Mantid/MantidPlot/src/DoubleSpinBox.h
index 300d26bc71b8f20adc420ee0d091d35c905007bd..217cbba66e983d6f172f219c2b6da264c76a2445 100644
--- a/Code/Mantid/MantidPlot/src/DoubleSpinBox.h
+++ b/Code/Mantid/MantidPlot/src/DoubleSpinBox.h
@@ -1,90 +1,90 @@
-/***************************************************************************
-    File                 : DoubleSpinBox.h
-    Project              : QtiPlot
-    --------------------------------------------------------------------
-    Copyright            : (C) 2007-2008 by Ion Vasilief
-    Email (use @ for *)  : ion_vasilief*yahoo.fr
-    Description          : A Double Spin Box
-
- ***************************************************************************/
-
-/***************************************************************************
- *                                                                         *
- *  This program is free software; you can redistribute it and/or modify   *
- *  it under the terms of the GNU General Public License as published by   *
- *  the Free Software Foundation; either version 2 of the License, or      *
- *  (at your option) any later version.                                    *
- *                                                                         *
- *  This program is distributed in the hope that it will be useful,        *
- *  but WITHOUT 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, write to the Free Software           *
- *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
- *   Boston, MA  02110-1301  USA                                           *
- *                                                                         *
- ***************************************************************************/
-#ifndef DoubleSpinBox_H
-#define DoubleSpinBox_H
-
-#include <QAbstractSpinBox>
-#include <QCheckBox>
-
-class DoubleSpinBox : public QAbstractSpinBox
-{
-	Q_OBJECT
-
-public:
-    DoubleSpinBox(const char format = 'g', QWidget * parent = 0);
-
-	void setSingleStep(double val);
-	void setMaximum(double max);
-	void setMinimum(double min);
-	void setRange(double min, double max);
-
-	int decimals(){return d_prec;};
-	void setDecimals(int prec){if (prec >= 0) d_prec = prec;};
-
-	double value(){return d_value;};
-	bool setValue(double val);
-
-	QString textFromValue ( double value ) const;
-	virtual QValidator::State validate ( QString & input, int & pos ) const;
-
-signals:
-	void valueChanged ( double d );
-
-private slots:
-	void interpretText();
-
-protected:
-	void stepBy ( int steps );
-	StepEnabled stepEnabled () const;
-
-private:
-    const char d_format;
-	double d_min_val;
-	double d_max_val;
-	double d_value;
-	double d_step;
-	int d_prec;
-};
-
-class RangeLimitBox : public QWidget
-{
-public:
-	enum LimitType{LeftLimit, RightLimit};
-
-    RangeLimitBox(LimitType type, QWidget * parent = 0);	
-	void setDecimals(int prec){d_spin_box->setDecimals(prec);};
-	double value();
-	bool isChecked(){return d_checkbox->isChecked();};
-
-private:
-    DoubleSpinBox *d_spin_box;
-    QCheckBox *d_checkbox;
-	LimitType d_type;
-};
+/***************************************************************************
+    File                 : DoubleSpinBox.h
+    Project              : QtiPlot
+    --------------------------------------------------------------------
+    Copyright            : (C) 2007-2008 by Ion Vasilief
+    Email (use @ for *)  : ion_vasilief*yahoo.fr
+    Description          : A Double Spin Box
+
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *  This program is free software; you can redistribute it and/or modify   *
+ *  it under the terms of the GNU General Public License as published by   *
+ *  the Free Software Foundation; either version 2 of the License, or      *
+ *  (at your option) any later version.                                    *
+ *                                                                         *
+ *  This program is distributed in the hope that it will be useful,        *
+ *  but WITHOUT 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, write to the Free Software           *
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
+ *   Boston, MA  02110-1301  USA                                           *
+ *                                                                         *
+ ***************************************************************************/
+#ifndef DoubleSpinBox_H
+#define DoubleSpinBox_H
+
+#include <QAbstractSpinBox>
+#include <QCheckBox>
+
+class DoubleSpinBox : public QAbstractSpinBox
+{
+	Q_OBJECT
+
+public:
+    DoubleSpinBox(const char format = 'g', QWidget * parent = 0);
+
+	void setSingleStep(double val);
+	void setMaximum(double max);
+	void setMinimum(double min);
+	void setRange(double min, double max);
+
+	int decimals(){return d_prec;};
+	void setDecimals(int prec){if (prec >= 0) d_prec = prec;};
+
+	double value(){return d_value;};
+	bool setValue(double val);
+
+	QString textFromValue ( double value ) const;
+	virtual QValidator::State validate ( QString & input, int & pos ) const;
+
+signals:
+	void valueChanged ( double d );
+
+private slots:
+	void interpretText();
+
+protected:
+	void stepBy ( int steps );
+	StepEnabled stepEnabled () const;
+
+private:
+    const char d_format;
+	double d_min_val;
+	double d_max_val;
+	double d_value;
+	double d_step;
+	int d_prec;
+};
+
+class RangeLimitBox : public QWidget
+{
+public:
+	enum LimitType{LeftLimit, RightLimit};
+
+    RangeLimitBox(LimitType type, QWidget * parent = 0);	
+	void setDecimals(int prec){d_spin_box->setDecimals(prec);};
+	double value();
+	bool isChecked(){return d_checkbox->isChecked();};
+
+private:
+    DoubleSpinBox *d_spin_box;
+    QCheckBox *d_checkbox;
+	LimitType d_type;
+};
 #endif // FITDIALOG_H
diff --git a/Code/Mantid/MantidPlot/src/ExponentialFit.cpp b/Code/Mantid/MantidPlot/src/ExponentialFit.cpp
index 2b64dfb7c17df9cbee7d156e1806b9c5738614b3..15816c9637bfd24975ec694f75c1fb6922a57c27 100644
--- a/Code/Mantid/MantidPlot/src/ExponentialFit.cpp
+++ b/Code/Mantid/MantidPlot/src/ExponentialFit.cpp
@@ -93,11 +93,11 @@ void ExponentialFit::init()
 }
 
 void ExponentialFit::customizeFitResults()
-{
+{
 	if (is_exp_growth)
 		d_results[1] = -1.0/d_results[1];
 	else
-		d_results[1] = 1.0/d_results[1];
+		d_results[1] = 1.0/d_results[1];
 }
 
 void ExponentialFit::calculateFitCurveData(double *X, double *Y)
@@ -108,13 +108,13 @@ void ExponentialFit::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++) {
+		for (int i=0; i<d_points; i++) {
 		    double x = X0+i*step;
 			X[i] = x;
-			Y[i] = a*exp(l*x) + y0;
+			Y[i] = a*exp(l*x) + y0;
 		}
 	} else {
-		for (int i=0; i<d_points; i++) {
+		for (int i=0; i<d_points; i++) {
 		    double x = d_x[i];
 			X[i] = x;
 			Y[i] = a*exp(l*x) + y0;
@@ -171,7 +171,7 @@ void TwoExpFit::init()
 }
 
 void TwoExpFit::customizeFitResults()
-{
+{
     d_results[1] = 1.0/d_results[1];
 	d_results[3] = 1.0/d_results[3];
 }
@@ -187,19 +187,19 @@ void TwoExpFit::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++){
+		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++){
+		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;
 		}
 	}
-}
+}
 
 /*****************************************************************************
  *
@@ -269,13 +269,13 @@ void ThreeExpFit::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++){
+		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++){
+		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/Code/Mantid/MantidPlot/src/ExponentialFit.h b/Code/Mantid/MantidPlot/src/ExponentialFit.h
index 74b0ec99ff8e185debe8b4d6d81e74350aaea816..364750c64fa682f259b8f3695651df9b9a5685a4 100644
--- a/Code/Mantid/MantidPlot/src/ExponentialFit.h
+++ b/Code/Mantid/MantidPlot/src/ExponentialFit.h
@@ -41,13 +41,13 @@ class ExponentialFit : public Fit
 		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){return par[0]*exp(-par[1]*x) + par[2];};
+
+        double eval(double *par, double x){return par[0]*exp(-par[1]*x) + par[2];};
 
 	private:
 		void init();
 		void customizeFitResults();
-		void calculateFitCurveData(double *X, double *Y);
+		void calculateFitCurveData(double *X, double *Y);
 
 		bool is_exp_growth;
 };
@@ -61,8 +61,8 @@ class TwoExpFit : public Fit
 		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){return par[0]*exp(-par[1]*x)+par[2]*exp(-par[3]*x)+par[4];};
+
+        double eval(double *par, double x){return par[0]*exp(-par[1]*x)+par[2]*exp(-par[3]*x)+par[4];};
 
 	private:
 		void init();
@@ -79,8 +79,8 @@ class ThreeExpFit : public Fit
 		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){return par[0]*exp(-x*par[1])+par[2]*exp(-x*par[3])+par[4]*exp(-x*par[5])+par[6];};
+
+        double eval(double *par, double x){return par[0]*exp(-x*par[1])+par[2]*exp(-x*par[3])+par[4]*exp(-x*par[5])+par[6];};
 
 	private:
 		void init();
diff --git a/Code/Mantid/MantidPlot/src/ExportDialog.cpp b/Code/Mantid/MantidPlot/src/ExportDialog.cpp
index cfe5ec54e1a60c37219aae8ae91b0dfef66b2f4e..1f3779ac67259da42228d0d69078c6addf734eda 100644
--- a/Code/Mantid/MantidPlot/src/ExportDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ExportDialog.cpp
@@ -85,16 +85,16 @@ ExportDialog::ExportDialog(const QString& tableName, QWidget* parent, Qt::WFlags
 
 	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 );
 
 	QVBoxLayout *vl1 = new QVBoxLayout();
 	vl1->addLayout( gl1 );
-	vl1->addWidget( boxNames );
+	vl1->addWidget( boxNames );
 	vl1->addWidget( boxComments );
 	vl1->addWidget( boxSelection );
 
@@ -113,17 +113,17 @@ ExportDialog::ExportDialog(const QString& tableName, QWidget* parent, Qt::WFlags
 	vl->addStretch();
 	vl->addLayout(hbox3);
 
-    // signals and slots connections
+    // 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)){
-		boxTable->setCurrentIndex(boxTable->findText(tableName));
-		updateOptions(tableName);
-    }
+	connect( boxAllTables, SIGNAL( toggled(bool) ), this, SLOT( enableTableName(bool) ) );
+
+    if (tables.contains(tableName)){
+		boxTable->setCurrentIndex(boxTable->findText(tableName));
+		updateOptions(tableName);
+    }
 }
 
 void ExportDialog::help()
@@ -193,7 +193,7 @@ void ExportDialog::closeEvent(QCloseEvent* e)
 	ApplicationWindow *app = (ApplicationWindow *)this->parent();
 	if (app){
 		app->d_export_col_names = boxNames->isChecked();
-		app->d_export_table_selection = boxSelection->isChecked();
+		app->d_export_table_selection = boxSelection->isChecked();
 		app->d_export_col_comment = boxComments->isChecked();
 
 		QString sep = boxSeparator->currentText();
@@ -206,22 +206,22 @@ void ExportDialog::closeEvent(QCloseEvent* e)
 
 	e->accept();
 }
-
-void ExportDialog::updateOptions(const QString & name)
-{
-    ApplicationWindow *app = (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(!w->isA("MantidMatrix"));
-	boxSeparator->setEnabled(!w->isA("MantidMatrix"));
-	boxAllTables->setEnabled(!w->isA("MantidMatrix"));
-	sepText->setEnabled(!w->isA("MantidMatrix"));
-
+
+void ExportDialog::updateOptions(const QString & name)
+{
+    ApplicationWindow *app = (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(!w->isA("MantidMatrix"));
+	boxSeparator->setEnabled(!w->isA("MantidMatrix"));
+	boxAllTables->setEnabled(!w->isA("MantidMatrix"));
+	sepText->setEnabled(!w->isA("MantidMatrix"));
+
 }
diff --git a/Code/Mantid/MantidPlot/src/ExportDialog.h b/Code/Mantid/MantidPlot/src/ExportDialog.h
index bddd505a3988773dbf115da07a6f11c52403ce56..ed20a812fc246000a30845601105245d319bfdfe 100644
--- a/Code/Mantid/MantidPlot/src/ExportDialog.h
+++ b/Code/Mantid/MantidPlot/src/ExportDialog.h
@@ -55,7 +55,7 @@ private:
     QPushButton* buttonOk;
 	QPushButton* buttonCancel;
 	QPushButton* buttonHelp;
-    QCheckBox* boxNames;
+    QCheckBox* boxNames;
     QCheckBox* boxComments;
     QCheckBox* boxSelection;
 	QCheckBox* boxAllTables;
@@ -73,9 +73,9 @@ private slots:
 	 * 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 enableTableName(bool ok);
+
+	//! Enable/disable export options depending if the selected window is a Table or a Matrix.
 	void updateOptions(const QString & name);
 
 protected slots:
diff --git a/Code/Mantid/MantidPlot/src/FFT.cpp b/Code/Mantid/MantidPlot/src/FFT.cpp
index 6922cc630d1c9a76fd3a00ade9645f71444749d8..52a83d996bee4fc68b73594b5575ac8210482014 100644
--- a/Code/Mantid/MantidPlot/src/FFT.cpp
+++ b/Code/Mantid/MantidPlot/src/FFT.cpp
@@ -50,13 +50,13 @@ FFT::FFT(ApplicationWindow *parent, Graph *g, const QString& curveTitle)
 	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 ()
 {
@@ -66,7 +66,7 @@ void FFT::init ()
     d_shift_order = true;
     d_real_col = -1;
     d_imag_col = -1;
-	d_sampling = 1.0;
+	d_sampling = 1.0;
 	d_output_graph = 0;
 }
 
@@ -261,25 +261,25 @@ void FFT::output(const QString &text)
     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)
+	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();
 	}
 }
diff --git a/Code/Mantid/MantidPlot/src/FFT.h b/Code/Mantid/MantidPlot/src/FFT.h
index 6c69fe04e12244e177af6f3b5c9d0bb1dc7ee76d..be6682e02d70965f7ef1dd6aaa5a48e6c6726869 100644
--- a/Code/Mantid/MantidPlot/src/FFT.h
+++ b/Code/Mantid/MantidPlot/src/FFT.h
@@ -37,7 +37,7 @@ 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);
     FFT(ApplicationWindow *parent, Graph *g, const QString& curveTitle, double start, double end);
 
     void setInverseFFT(bool inverse = true){d_inverse = inverse;};
diff --git a/Code/Mantid/MantidPlot/src/FFTDialog.cpp b/Code/Mantid/MantidPlot/src/FFTDialog.cpp
index e47964478d27acd2dece063d9b9b0e04a41f41bf..e19b38747a0e35ba5cb14ab67c23e4c5630b4742 100644
--- a/Code/Mantid/MantidPlot/src/FFTDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/FFTDialog.cpp
@@ -34,8 +34,8 @@
 #include "Table.h"
 #include "Plot.h"
 #include "FFT.h"
-#include "Matrix.h"
-#include "analysis/fft2D.h"
+#include "Matrix.h"
+#include "analysis/fft2D.h"
 
 #include <QRadioButton>
 #include <QGroupBox>
@@ -46,16 +46,16 @@
 #include <QLineEdit>
 #include <QComboBox>
 #include <QLayout>
-#include <QApplication>
+#include <QApplication>
 
 FFTDialog::FFTDialog(int type, QWidget* parent, Qt::WFlags fl )
 : QDialog( parent, fl )
 {
 	setWindowTitle(tr("MantidPlot - FFT Options"));
-
+
     d_matrix = 0;
 	d_table = 0;
-	graph = 0;
+	graph = 0;
 	d_type = type;
 
 	forwardBtn = new QRadioButton(tr("&Forward"));
@@ -74,12 +74,12 @@ FFTDialog::FFTDialog(int type, QWidget* parent, Qt::WFlags fl )
 	    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();
+        boxName = new QComboBox();
         connect( boxName, SIGNAL( activated(const QString&) ), this, SLOT( activateCurve(const QString&) ) );
-        gl1->addWidget(boxName, 0, 1);
-        setFocusProxy(boxName);
+        gl1->addWidget(boxName, 0, 1);
+        setFocusProxy(boxName);
     }
 
     boxSampling = new QLineEdit();
@@ -91,31 +91,31 @@ FFTDialog::FFTDialog(int type, QWidget* parent, Qt::WFlags fl )
 		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);
+            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);
 
 	boxNormalize = new QCheckBox(tr( "&Normalize Amplitude" ));
 	boxNormalize->setChecked(true);
-
+
     if (d_type != onMatrix){
         boxOrder = new QCheckBox(tr( "&Shift Results" ));
-        boxOrder->setChecked(true);
+        boxOrder->setChecked(true);
     }
 
     QVBoxLayout *vbox1 = new QVBoxLayout();
     vbox1->addWidget(gb1);
     vbox1->addWidget(gb2);
-    vbox1->addWidget(boxNormalize);
+    vbox1->addWidget(boxNormalize);
     if (d_type != onMatrix)
         vbox1->addWidget(boxOrder);
 	vbox1->addStretch();
@@ -139,12 +139,12 @@ FFTDialog::FFTDialog(int type, QWidget* parent, Qt::WFlags fl )
 }
 
 void FFTDialog::accept()
-{
-    if (d_type == onMatrix){
-        fftMatrix();
-        close();
-        return;
-    }
+{
+    if (d_type == onMatrix){
+        fftMatrix();
+        close();
+        return;
+    }
 
 	double sampling;
 	try
@@ -234,136 +234,136 @@ void FFTDialog::setTable(Table *t)
 		boxImaginary->setCurrentItem(t->colIndex(l[1]));
 	}
 };
-
-void FFTDialog::setMatrix(Matrix *m)
-{
-    ApplicationWindow *app = (ApplicationWindow *)parent();
-    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 = (ApplicationWindow *)parent();
-    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;
+
+void FFTDialog::setMatrix(Matrix *m)
+{
+    ApplicationWindow *app = (ApplicationWindow *)parent();
+    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 = (ApplicationWindow *)parent();
+    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;
+    {
+        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){
+	if (!x_int_im){
 	    Matrix::freeMatrixData(x_int_re, height);
-		return;
+		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);
-        }
-    }
-
-    double **x_fin_re, **x_fin_im;
-    if (inverse){
-        x_fin_re = Matrix::allocateMatrixData(height, width); // coeff of the initial image
+
+    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, **x_fin_im;
+    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);
+		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));
-            }
-        }
-    }
-
-    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);
-            }
-        }
-    }
-
-    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();
+
+        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 (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);
+            }
+        }
+    }
+
+    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/Code/Mantid/MantidPlot/src/FFTDialog.h b/Code/Mantid/MantidPlot/src/FFTDialog.h
index 79d608eafcbbadef9279c6fd4834232a164ebf6d..b3e67e5a3abed52a275e08a7a7d0d0848ad518ce 100644
--- a/Code/Mantid/MantidPlot/src/FFTDialog.h
+++ b/Code/Mantid/MantidPlot/src/FFTDialog.h
@@ -38,7 +38,7 @@ class QComboBox;
 class QCheckBox;
 class Graph;
 class Table;
-class Matrix;
+class Matrix;
 
 //! Fast Fourier transform options dialog
 class FFTDialog : public QDialog
@@ -52,17 +52,17 @@ public:
 
 public slots:
 	void setGraph(Graph *g);
-	void setTable(Table *t);
+	void setTable(Table *t);
 	void setMatrix(Matrix *m);
 	void activateCurve(const QString& curveName);
 	void accept();
 
-private:
-    void fftMatrix();
+private:
+    void fftMatrix();
 
 	Graph *graph;
-	Table *d_table;
-	Matrix *d_matrix;
+	Table *d_table;
+	Matrix *d_matrix;
 	int d_type;
 
 	QPushButton* buttonOK;
diff --git a/Code/Mantid/MantidPlot/src/Filter.cpp b/Code/Mantid/MantidPlot/src/Filter.cpp
index 383b53180e01417f4543dc5f442668a19265e116..d93f15db354940153032692fdb581d27938672bc 100644
--- a/Code/Mantid/MantidPlot/src/Filter.cpp
+++ b/Code/Mantid/MantidPlot/src/Filter.cpp
@@ -71,7 +71,7 @@ void Filter::init()
     d_min_points = 2;
     d_explanation = objectName();
     d_graph = 0;
-    d_table = 0;
+    d_table = 0;
     d_result_table = 0;
 	d_output_graph = 0;
 	d_graphics_display = true;
@@ -233,7 +233,7 @@ int Filter::sortedCurveData(QwtPlotCurve *c, double start, double end, double **
     (*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);
@@ -245,7 +245,7 @@ int Filter::sortedCurveData(QwtPlotCurve *c, double start, double end, double **
         (*x)[i] = xtemp[p[i]];
   	    (*y)[i] = ytemp[p[i]];
     }
-
+
     delete[] xtemp;
     delete[] ytemp;
     delete[] p;
@@ -267,7 +267,7 @@ int Filter::curveData(QwtPlotCurve *c, double start, double end, double **x, dou
     for (int i = i_start; i <= i_end; i++){
         (*x)[j] = c->x(i);
         (*y)[j++] = c->y(i);
-    }
+    }
     return n;
 }
 
@@ -378,13 +378,13 @@ bool Filter::setDataFromTable(Table *t, const QString& xColName, const QString&
 	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);
+    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;
diff --git a/Code/Mantid/MantidPlot/src/Filter.h b/Code/Mantid/MantidPlot/src/Filter.h
index 9a6f2c495768d5b9a7d2d0a50c683175e0d728db..9e47662c2a680479d6e0afc72dc86f607bf74726 100644
--- a/Code/Mantid/MantidPlot/src/Filter.h
+++ b/Code/Mantid/MantidPlot/src/Filter.h
@@ -86,11 +86,11 @@ class Filter : public QObject
 		//! 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;};
+		double* x(){return d_x;};
 		//! Returns the y values of the input data set
-		double* y(){return d_y;};
+		double* y(){return d_y;};
 		//! Returns a pointer to the table created to display the results
-        Table *resultTable(){return d_result_table;};
+        Table *resultTable(){return d_result_table;};
 
         bool error(){return d_init_err;};
 
@@ -132,9 +132,9 @@ class Filter : public QObject
 
         //! 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;
diff --git a/Code/Mantid/MantidPlot/src/Fit.cpp b/Code/Mantid/MantidPlot/src/Fit.cpp
index ab0e7cad6adfe01fe15c64d5916de2ed97febe8e..72f2d70b9ba318b9114b8936cba3770fe379c50b 100644
--- a/Code/Mantid/MantidPlot/src/Fit.cpp
+++ b/Code/Mantid/MantidPlot/src/Fit.cpp
@@ -34,7 +34,7 @@
 #include "FunctionCurve.h"
 #include "ColorBox.h"
 #include "MultiLayer.h"
-#include "FitModelHandler.h"
+#include "FitModelHandler.h"
 
 #include <gsl/gsl_statistics.h>
 #include <gsl/gsl_blas.h>
@@ -43,7 +43,7 @@
 #include <QMessageBox>
 #include <QDateTime>
 #include <QLocale>
-#include <QTextStream>
+#include <QTextStream>
 
 Fit::Fit( ApplicationWindow *parent, Graph *g, const QString& name)
 : Filter( parent, g, name)
@@ -85,8 +85,8 @@ void Fit::init()
 	d_prec = (((ApplicationWindow *)parent())->fit_output_precision);
 	d_param_table = 0;
 	d_cov_matrix = 0;
-	covar = 0;
-	d_param_init = 0;
+	covar = 0;
+	d_param_init = 0;
 	d_fit_type = BuiltIn;
 	d_param_range_left = 0;
 	d_param_range_right = 0;
@@ -155,36 +155,36 @@ gsl_multimin_fminimizer * Fit::fitSimplex(gsl_multimin_function f, int &iteratio
 	gsl_multimin_fminimizer *s_min = gsl_multimin_fminimizer_alloc (T, f.n);
 	status = gsl_multimin_fminimizer_set (s_min, &f, d_param_init, ss);
 	double size;
-	size_t iter = 0;
-	bool inRange = true;
-	for (int i=0; i<d_p; i++){
-		double p = gsl_vector_get(d_param_init, i);
-		d_results[i] = p;
-		if (p < d_param_range_left[i] || p > d_param_range_right[i]){
-			inRange = false;
-			break;
-		}
-	}
+	size_t iter = 0;
+	bool inRange = true;
+	for (int i=0; i<d_p; i++){
+		double p = gsl_vector_get(d_param_init, i);
+		d_results[i] = p;
+		if (p < d_param_range_left[i] || p > d_param_range_right[i]){
+			inRange = false;
+			break;
+		}
+	}
 
 	do{
 		iter++;
 		status = gsl_multimin_fminimizer_iterate (s_min);
 
 		if (status)
-			break;
-
-        for (int i=0; i<d_p; i++){
-			double p = gsl_vector_get(s_min->x, i);
-			if (p < d_param_range_left[i] || p > d_param_range_right[i]){
-				inRange = false;
-				break;
-			}
-		}
-		if (!inRange)
-			break;
-
-		for (int i=0; i<d_p; i++)
-			d_results[i] = gsl_vector_get(s_min->x, i);
+			break;
+
+        for (int i=0; i<d_p; i++){
+			double p = gsl_vector_get(s_min->x, i);
+			if (p < d_param_range_left[i] || p > d_param_range_right[i]){
+				inRange = false;
+				break;
+			}
+		}
+		if (!inRange)
+			break;
+
+		for (int i=0; i<d_p; i++)
+			d_results[i] = gsl_vector_get(s_min->x, i);
 
 		size = gsl_multimin_fminimizer_size (s_min);
 		status = gsl_multimin_test_size (size, d_tolerance);
@@ -305,9 +305,9 @@ QString Fit::logFitInfo(int iterations, int status)
 	info+=tr("From x")+" = "+locale.toString(d_x[0], 'e', d_prec)+" "+tr("to x")+" = "+locale.toString(d_x[d_n-1], 'e', d_prec)+"\n";
 	double chi_2_dof = chi_2/(d_n - d_p);
 	for (int i=0; i<d_p; i++){
-		info += d_param_names[i];
-		if (!d_param_explain[i].isEmpty())
-            info += " (" + d_param_explain[i] + ")";
+		info += d_param_names[i];
+		if (!d_param_explain[i].isEmpty())
+            info += " (" + d_param_explain[i] + ")";
 		info += " = " + locale.toString(d_results[i], 'e', d_prec) + " +/- ";
 		if (d_scale_errors)
 			info += locale.toString(sqrt(chi_2_dof*gsl_matrix_get(covar, i, i)), 'e', d_prec) + "\n";
@@ -602,12 +602,12 @@ void Fit::generateFitCurve()
 {
 	if (!d_gen_function)
 		d_points = d_n;
-
+
 	double *X = new double[d_points];
 	double *Y = new double[d_points];
 
 	calculateFitCurveData(X, Y);
-    customizeFitResults();
+    customizeFitResults();
 
 	if (d_graphics_display){
 		if (!d_output_graph)
@@ -629,14 +629,14 @@ void Fit::insertFitFunctionCurve(const QString& name, double *x, double *y, int
 	for (int j=0; j<d_p; j++){
 		QString parameter = QString::number(d_results[j], 'e', d_prec);
 		formula.replace(d_param_names[j], parameter);
-	}
-
-	formula = formula.replace("-+", "-").replace("+-", "-");
-	if (formula.startsWith ("--", Qt::CaseInsensitive))
-        formula = formula.right(formula.length() - 2);
-	formula.replace("(--", "(");
+	}
+
+	formula = formula.replace("-+", "-").replace("+-", "-");
+	if (formula.startsWith ("--", Qt::CaseInsensitive))
+        formula = formula.right(formula.length() - 2);
+	formula.replace("(--", "(");
 	formula.replace("--", "+");
-	d_result_formula = formula;
+	d_result_formula = formula;
 
 	QString title = d_output_graph->generateFunctionName(name);
 	FunctionCurve *c = new FunctionCurve(FunctionCurve::Normal, title);
@@ -647,65 +647,65 @@ void Fit::insertFitFunctionCurve(const QString& name, double *x, double *y, int
 	d_output_graph->insertPlotItem(c, Graph::Line);
 	d_output_graph->addFitCurve(c);
 }
-
-bool Fit::save(const QString& fileName)
-{
-    QFile f(fileName);
-	if ( !f.open( QIODevice::WriteOnly ) ){
-		QApplication::restoreOverrideCursor();
-		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));
-		return false;
-	}
-
-    QTextStream out( &f );
-    out.setCodec("UTF-8");
-    out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
-         << "<!DOCTYPE fit>\n"
-         << "<fit version=\"1.0\">\n";
-
-     out << "<model>" + objectName() + "</model>\n";
+
+bool Fit::save(const QString& fileName)
+{
+    QFile f(fileName);
+	if ( !f.open( QIODevice::WriteOnly ) ){
+		QApplication::restoreOverrideCursor();
+		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));
+		return false;
+	}
+
+    QTextStream out( &f );
+    out.setCodec("UTF-8");
+    out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+         << "<!DOCTYPE fit>\n"
+         << "<fit version=\"1.0\">\n";
+
+     out << "<model>" + objectName() + "</model>\n";
      out << "<type>" + QString::number(d_fit_type) + "</type>\n";
 
-	 QString function = d_formula;
-     out << "<function>" + function.replace("<", "&lt;").replace(">", "&gt;") + "</function>\n";
-
-     QString indent = QString(4, ' ');
-     for (int i=0; i< d_p; i++){
-         out << "<parameter>\n";
-         out << indent << "<name>" + d_param_names[i] + "</name>\n";
-         out << indent << "<explanation>" + d_param_explain[i] + "</explanation>\n";
-         out << indent << "<value>" + QString::number(gsl_vector_get(d_param_init, i), 'e', 13) + "</value>\n";
-         out << "</parameter>\n";
-     }
-     out << "</fit>\n";
-     d_file_name = fileName;
-     return true;
-}
-
-bool Fit::load(const QString& fileName)
-{
-    FitModelHandler handler(this);
-    QXmlSimpleReader reader;
-    reader.setContentHandler(&handler);
-    reader.setErrorHandler(&handler);
-
-    QFile file(fileName);
-    if (!file.open(QFile::ReadOnly | QFile::Text)) {
-        QMessageBox::warning(((ApplicationWindow *)parent()), tr("MantidPlot Fit Model"),
-                              tr("Cannot read file %1:\n%2.")
-                              .arg(fileName)
-                              .arg(file.errorString()));
-        return false;
-    }
-
-    QXmlInputSource xmlInputSource(&file);
-    if (reader.parse(xmlInputSource)){
-        d_file_name = fileName;
-        return true;
-    }
-    return false;
-}
+	 QString function = d_formula;
+     out << "<function>" + function.replace("<", "&lt;").replace(">", "&gt;") + "</function>\n";
+
+     QString indent = QString(4, ' ');
+     for (int i=0; i< d_p; i++){
+         out << "<parameter>\n";
+         out << indent << "<name>" + d_param_names[i] + "</name>\n";
+         out << indent << "<explanation>" + d_param_explain[i] + "</explanation>\n";
+         out << indent << "<value>" + QString::number(gsl_vector_get(d_param_init, i), 'e', 13) + "</value>\n";
+         out << "</parameter>\n";
+     }
+     out << "</fit>\n";
+     d_file_name = fileName;
+     return true;
+}
+
+bool Fit::load(const QString& fileName)
+{
+    FitModelHandler handler(this);
+    QXmlSimpleReader reader;
+    reader.setContentHandler(&handler);
+    reader.setErrorHandler(&handler);
+
+    QFile file(fileName);
+    if (!file.open(QFile::ReadOnly | QFile::Text)) {
+        QMessageBox::warning(((ApplicationWindow *)parent()), tr("MantidPlot Fit Model"),
+                              tr("Cannot read file %1:\n%2.")
+                              .arg(fileName)
+                              .arg(file.errorString()));
+        return false;
+    }
+
+    QXmlInputSource xmlInputSource(&file);
+    if (reader.parse(xmlInputSource)){
+        d_file_name = fileName;
+        return true;
+    }
+    return false;
+}
 
 void Fit::setParameterRange(int parIndex, double left, double right)
 {
@@ -741,11 +741,11 @@ void Fit::freeWorkspace()
 	if (d_param_range_left) delete[] d_param_range_left;
 	if (d_param_range_right) delete[] d_param_range_right;
 }
-
-void Fit::freeMemory()
-{
-	if (!d_p)
-		return;
+
+void Fit::freeMemory()
+{
+	if (!d_p)
+		return;
 
 	if (d_x){
 		delete[] d_x;
@@ -754,8 +754,8 @@ void Fit::freeMemory()
 	if (d_y) {
 		delete[] d_y;
 		d_y = NULL;
-	}
-}
+	}
+}
 
 Fit::~Fit()
 {
diff --git a/Code/Mantid/MantidPlot/src/Fit.h b/Code/Mantid/MantidPlot/src/Fit.h
index a04a9cee22091632e943bc49c3979f650886fc90..4f21fcc2561bc3b8799995c2d007dcebf446e185 100644
--- a/Code/Mantid/MantidPlot/src/Fit.h
+++ b/Code/Mantid/MantidPlot/src/Fit.h
@@ -54,7 +54,7 @@ class Fit : public Filter
 
 		enum Algorithm{ScaledLevenbergMarquardt, UnscaledLevenbergMarquardt, NelderMeadSimplex};
 		enum WeightingMethod{NoWeighting, Instrumental, Statistical, Dataset};
-        enum FitType{BuiltIn = 0, Plugin = 1, User = 2};
+        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());
@@ -71,14 +71,14 @@ class Fit : public Filter
 		bool setDataFromTable(Table *t, const QString& xColName, const QString& yColName, int from = 1, int to = -1);
 
 		QString resultFormula(){return d_result_formula;};
-		QString formula(){return d_formula;};
-		virtual void setFormula(const QString&){};
+		QString formula(){return d_formula;};
+		virtual void setFormula(const QString&){};
 
 		int numParameters(){return d_p;};
-		QStringList parameterNames(){return d_param_names;};
+		QStringList parameterNames(){return d_param_names;};
 		virtual void setParametersList(const QStringList&){};
-        void setParameterExplanations(const QStringList& lst){d_param_explain = lst;};
-
+        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);
@@ -113,21 +113,21 @@ class Fit : public Filter
 		void writeParametersToTable(Table *t, bool append = false);
 
 		Matrix* covarianceMatrix(const QString& matrixName);
-
-        bool save(const QString& fileName);
-        bool load(const QString& fileName);
-
-        FitType type(){return d_fit_type;};
-        void setType(FitType t){d_fit_type = t;};
-
-        QString fileName(){return d_file_name;};
-		void setFileName(const QString& fn){d_file_name = fn;};
-
-        //! Frees the memory allocated for the X and Y data sets
-        void freeMemory();
-
-        //! Calculates the data for the output fit curve
-        virtual double eval(double *, double){return 0.0;};
+
+        bool save(const QString& fileName);
+        bool load(const QString& fileName);
+
+        FitType type(){return d_fit_type;};
+        void setType(FitType t){d_fit_type = t;};
+
+        QString fileName(){return d_file_name;};
+		void setFileName(const QString& fn){d_file_name = fn;};
+
+        //! Frees the memory allocated for the X and Y data sets
+        void freeMemory();
+
+        //! Calculates the data for the output fit curve
+        virtual double eval(double *, double){return 0.0;};
 
 	private:
 		void init();
@@ -151,9 +151,9 @@ class Fit : public Filter
 
 		//! Adds the result curve to the plot
 		virtual void generateFitCurve();
-
-        //! 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 and store itin the X an Y vectors
+		virtual void calculateFitCurveData(double *X, double *Y) {Q_UNUSED(X) Q_UNUSED(Y)};
 
 		//! Output string added to the result log
 		virtual QString logFitInfo(int iterations, int status);
@@ -220,11 +220,11 @@ class Fit : public Filter
 		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
+		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
diff --git a/Code/Mantid/MantidPlot/src/FitDialog.cpp b/Code/Mantid/MantidPlot/src/FitDialog.cpp
index 8ea46218fcd64b82c0097b918b4741a0a9431a93..0e10c57112e30d2b6a6c4e9fb9c0bc8f6b5d4a73 100644
--- a/Code/Mantid/MantidPlot/src/FitDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/FitDialog.cpp
@@ -39,7 +39,7 @@
 #include "NonLinearFit.h"
 #include "SigmoidalFit.h"
 #include "LogisticFit.h"
-#include "Matrix.h"
+#include "Matrix.h"
 #include "DoubleSpinBox.h"
 
 #include <QListWidget>
@@ -61,8 +61,8 @@
 #include <QLibrary>
 #include <QLocale>
 #include <stdio.h>
-
-#include <qwt_plot_curve.h>
+
+#include <qwt_plot_curve.h>
 
 FitDialog::FitDialog(Graph *g, QWidget* parent, Qt::WFlags fl )
 : QDialog( parent, fl )
@@ -72,7 +72,7 @@ FitDialog::FitDialog(Graph *g, QWidget* parent, Qt::WFlags fl )
 	setSizeGripEnabled(true);
 
 	d_param_table = 0;
-	d_current_fit = 0;
+	d_current_fit = 0;
 	d_preview_curve = 0;
 
 	tw = new QStackedWidget();
@@ -88,15 +88,15 @@ FitDialog::FitDialog(Graph *g, QWidget* parent, Qt::WFlags fl )
 	categoryBox->setCurrentRow (2);
 	funcBox->setCurrentRow (0);
 
-	setGraph(g);
-	initBuiltInFunctions();
-    loadPlugins();
-    loadUserFunctions();
+	setGraph(g);
+	initBuiltInFunctions();
+    loadPlugins();
+    loadUserFunctions();
 }
 
 void FitDialog::initFitPage()
-{
-    ApplicationWindow *app = (ApplicationWindow *)parent();
+{
+    ApplicationWindow *app = (ApplicationWindow *)parent();
 
     QGridLayout *gl1 = new QGridLayout();
     gl1->addWidget(new QLabel(tr("Curve")), 0, 0);
@@ -111,21 +111,21 @@ void FitDialog::initFitPage()
     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);
+    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);
 
@@ -140,8 +140,8 @@ void FitDialog::initFitPage()
     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->verticalHeader()->hide();
+    boxParams->hideColumn(1);
     boxParams->hideColumn(3);
     gl1->addWidget(boxParams, 3, 1);
 
@@ -162,20 +162,20 @@ void FitDialog::initFitPage()
 
     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);
+
+	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(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);
+
+	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);
+    gl2->addWidget(boxTo, 1, 1);
 
     QGroupBox *gb2 = new QGroupBox();
     gb2->setLayout(gl2);
@@ -187,15 +187,15 @@ void FitDialog::initFitPage()
 	boxPoints->setSingleStep(50);
 	boxPoints->setValue(1000);
     gl3->addWidget(boxPoints, 0, 1);
-	gl3->addWidget(new QLabel( tr("Tolerance")), 1, 0);
+	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);
+	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);
@@ -596,7 +596,7 @@ void FitDialog::saveUserFunction()
 					"<p>You must choose another name for your function!"));
 		editBox->setFocus();
 		return;
-	}
+	}
 
 	if (editBox->text().contains(boxName->text())){
 		QMessageBox::critical(this, tr("MantidPlot - Input function error"),
@@ -605,76 +605,76 @@ void FitDialog::saveUserFunction()
 		return;
 	}
 
-	QString name = boxName->text();
+	QString name = boxName->text();
     QStringList lst = userFunctionNames();
 	QString formula = parseFormula(editBox->text().simplified());
 	if (lst.contains(name)){
 		int index = lst.findIndex(name);
-		d_current_fit = (NonLinearFit *)d_user_functions[index];
-		d_current_fit->setParametersList(boxParam->text().split(QRegExp("[,;]+[\\s]*"), QString::SkipEmptyParts));
-        d_current_fit->setFormula(formula);
-        d_current_fit->save(d_current_fit->fileName());
-
+		d_current_fit = (NonLinearFit *)d_user_functions[index];
+		d_current_fit->setParametersList(boxParam->text().split(QRegExp("[,;]+[\\s]*"), QString::SkipEmptyParts));
+        d_current_fit->setFormula(formula);
+        d_current_fit->save(d_current_fit->fileName());
+
 		if (funcBox->currentItem()->text() == name)
 			showExpression(index);
-	} else {
-	    ApplicationWindow *app = (ApplicationWindow *)this->parent();
-		QString filter = tr("MantidPlot fit model")+" (*.fit);;";
-		filter += tr("All files")+" (*.*)";
-		QString fn = QFileDialog::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 = lst.indexOf(name);
-                d_user_functions.insert (index, d_current_fit);
-
-                if (categoryBox->currentRow() == 0){
+	} else {
+	    ApplicationWindow *app = (ApplicationWindow *)this->parent();
+		QString filter = tr("MantidPlot fit model")+" (*.fit);;";
+		filter += tr("All files")+" (*.*)";
+		QString fn = QFileDialog::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 = 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);
-            }
+                    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();
+{
+    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());
+
+		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);
+            d_user_functions.removeAt(index);
 		}
-
+
         lst.remove(name);
 		funcBox->clear();
 		funcBox->addItems(lst);
@@ -695,36 +695,36 @@ void FitDialog::showFitPage()
 	}
 
 	ApplicationWindow *app = (ApplicationWindow *)parent();
-    if (!boxUseBuiltIn->isChecked()){
-        d_current_fit = new NonLinearFit(app, d_graph);
+    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 && 
 		(d_current_fit->isA("PolynomialFit") || d_current_fit->isA("LinearFit")
-		|| d_current_fit->isA("LinearSlopeFit"))){
-        btnParamRange->setEnabled(false);
+		|| d_current_fit->isA("LinearSlopeFit"))){
+        btnParamRange->setEnabled(false);
         boxAlgorithm->setEnabled(false);
 		boxPoints->setEnabled(false);
-		boxTolerance->setEnabled(false);
-    } else {
-        btnParamRange->setEnabled(true);
+		boxTolerance->setEnabled(false);
+    } else {
+        btnParamRange->setEnabled(true);
         boxAlgorithm->setEnabled(true);
 		boxPoints->setEnabled(true);
-		boxTolerance->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;
@@ -782,12 +782,12 @@ void FitDialog::showFitPage()
 
 	tw->setCurrentWidget (fitPage);
 	if (previewBox->isChecked())
-		updatePreview();
+		updatePreview();
 }
 
 void FitDialog::showEditPage()
-{
-    if (d_current_fit)
+{
+    if (d_current_fit)
         d_current_fit->freeMemory();
 	tw->setCurrentWidget(editPage);
 }
@@ -842,20 +842,20 @@ void FitDialog::showFunctionsList(int category)
 		case 0:
 			if (d_user_functions.count() > 0){
 				boxUseBuiltIn->setEnabled(true);
-
-                QStringList lst;
-                foreach(Fit *fit, d_user_functions)
-                    lst << fit->objectName();
+
+                QStringList lst;
+                foreach(Fit *fit, d_user_functions)
+                    lst << fit->objectName();
                 funcBox->addItems(lst);
-			}
-            buttonPlugins->setText(tr("Choose &models folder..."));
+			}
+            buttonPlugins->setText(tr("Choose &models folder..."));
             buttonPlugins->show();
 			boxUseBuiltIn->setText(tr("Fit with selected &user function"));
 			boxUseBuiltIn->show();
 			btnDelFunc->setEnabled(true);
         break;
 
-		case 1:
+		case 1:
 			boxUseBuiltIn->setText(tr("Fit using &built-in function"));
 			boxUseBuiltIn->show();
 			boxUseBuiltIn->setEnabled(true);
@@ -867,15 +867,15 @@ void FitDialog::showFunctionsList(int category)
         break;
 
 		case 3:
-            buttonPlugins->setText(tr("Choose plug&ins folder..."));
+            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);
+            boxUseBuiltIn->setEnabled(d_plugins.size() > 0);
+            QStringList lst;
+            foreach(Fit *fit, d_plugins)
+                lst << fit->objectName();
+            funcBox->addItems(lst);
         break;
 	}
     funcBox->blockSignals(false);
@@ -884,7 +884,7 @@ void FitDialog::showFunctionsList(int category)
 
 void FitDialog::chooseFolder()
 {
-	ApplicationWindow *app = (ApplicationWindow *)this->parent();
+	ApplicationWindow *app = (ApplicationWindow *)this->parent();
 	if (categoryBox->currentRow() == 3){//plugins
         QString dir = QFileDialog::getExistingDirectory(this, tr("Choose the plugins folder"), app->fitPluginsPath);
         if (!dir.isEmpty()){
@@ -892,50 +892,50 @@ void FitDialog::chooseFolder()
             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");
-        }
+        }
+	} 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)();
 
 	ApplicationWindow *app = (ApplicationWindow *)this->parent();
-	QString path = app->fitPluginsPath + "/";
+	QString path = app->fitPluginsPath + "/";
 	QString modelsDirPath = app->fitModelsPath + "/";
 	QDir dir(path);
-	QStringList lst = dir.entryList(QDir::Files|QDir::NoSymLinks, QDir::Name);
+	QStringList lst = dir.entryList(QDir::Files|QDir::NoSymLinks, QDir::Name);
     QStringList names;
-	for (int i=0; i<lst.count(); i++){
-	    QString file = lst[i];
+	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.library());
-            d_plugins << fit;
-            names << fit->objectName();
-            fit->setFileName(modelsDirPath + fit->objectName() + ".fit");
+            QLibrary lib(path + file);
+            PluginFit *fit = new PluginFit(app, d_graph);
+            fit->load(lib.library());
+            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
+	}
+
+    if (d_plugins.size() > 0){
+        funcBox->addItems(names);
+        funcBox->setCurrentRow(0);
+        boxUseBuiltIn->setEnabled(true);
+    } else
         boxUseBuiltIn->setEnabled(false);
 }
 
@@ -970,13 +970,13 @@ void FitDialog::showExpression(int function)
 		setFunction(boxUseBuiltIn->isChecked());
 	} else if (categoryBox->currentRow() == 0){
 		if (d_user_functions.size() > function){
-			d_current_fit = d_user_functions[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){
+		if (d_plugins.size() > 0){
 		    d_current_fit = d_plugins[function];
 			explainBox->setText(d_current_fit->formula());
 			setFunction(boxUseBuiltIn->isChecked());
@@ -1023,8 +1023,8 @@ void FitDialog::accept()
 		return;
 	}
 
-	double start = boxFrom->value();
-	double end = boxTo->value();
+	double start = boxFrom->value();
+	double end = boxTo->value();
 	double eps = boxTolerance->value();
 
 	if (start >= end){
@@ -1206,12 +1206,12 @@ void FitDialog::enableWeightingParameters(int index)
 }
 
 void FitDialog::closeEvent (QCloseEvent * e)
-{							
-    if (d_preview_curve){
-        d_preview_curve->detach();
-        d_graph->replot();
-        delete d_preview_curve;
-    }
+{							
+    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();
@@ -1240,7 +1240,7 @@ void FitDialog::resetFunction()
 
 void FitDialog::initBuiltInFunctions()
 {
-	ApplicationWindow *app = (ApplicationWindow *)this->parent();
+	ApplicationWindow *app = (ApplicationWindow *)this->parent();
 
 	d_built_in_functions << new SigmoidalFit(app, d_graph);
 	d_built_in_functions << new ExponentialFit(app, d_graph);
@@ -1263,10 +1263,10 @@ void FitDialog::initBuiltInFunctions()
 	fit->setPeakCurvesColor(app->peakCurvesColor);
 	d_built_in_functions << fit;
 
-	d_built_in_functions << new PolynomialFit(app, d_graph, 1);
-
-    QString path = app->fitModelsPath + "/";
-    foreach(Fit *fit, d_built_in_functions)
+	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");
 }
 
@@ -1290,154 +1290,154 @@ QStringList FitDialog::builtInFunctionNames()
 		lst << fit->objectName();
 	return lst;
 }
-
-void FitDialog::loadUserFunctions()
-{
-    d_user_functions.clear();
-	ApplicationWindow *app = (ApplicationWindow *)this->parent();
-	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);
-}
-
-QStringList FitDialog::userFunctionNames()
-{
-	QStringList lst;
-	foreach(Fit *fit, d_user_functions)
-		lst << fit->objectName();
-	return lst;
-}
-
-void FitDialog::saveInitialGuesses()
-{
-    if (!d_current_fit)
-        return;
-
-	int rows = boxParams->rowCount();
-    for (int i=0; i<rows; i++)
-        d_current_fit->setInitialGuess(i, ((DoubleSpinBox*)boxParams->cellWidget(i, 2))->value());
-
-    QString fileName = d_current_fit->fileName();
-    if (!fileName.isEmpty())
-        d_current_fit->save(fileName);
-    else {
-	    ApplicationWindow *app = (ApplicationWindow *)this->parent();
-		QString filter = tr("MantidPlot fit model") + " (*.fit);;";
-		filter += tr("All files") + " (*.*)";
-		QString fn = QFileDialog::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;
-}
+
+void FitDialog::loadUserFunctions()
+{
+    d_user_functions.clear();
+	ApplicationWindow *app = (ApplicationWindow *)this->parent();
+	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);
+}
+
+QStringList FitDialog::userFunctionNames()
+{
+	QStringList lst;
+	foreach(Fit *fit, d_user_functions)
+		lst << fit->objectName();
+	return lst;
+}
+
+void FitDialog::saveInitialGuesses()
+{
+    if (!d_current_fit)
+        return;
+
+	int rows = boxParams->rowCount();
+    for (int i=0; i<rows; i++)
+        d_current_fit->setInitialGuess(i, ((DoubleSpinBox*)boxParams->cellWidget(i, 2))->value());
+
+    QString fileName = d_current_fit->fileName();
+    if (!fileName.isEmpty())
+        d_current_fit->save(fileName);
+    else {
+	    ApplicationWindow *app = (ApplicationWindow *)this->parent();
+		QString filter = tr("MantidPlot fit model") + " (*.fit);;";
+		filter += tr("All files") + " (*.*)";
+		QString fn = QFileDialog::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;
+}
 
 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;
-    }
-
-    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] = ((DoubleSpinBox*)boxParams->cellWidget(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());
-	}
-
-    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::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;
+
+    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] = ((DoubleSpinBox*)boxParams->cellWidget(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());
+	}
+
+    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);
+    }
+}
 
 QString FitDialog::parseFormula(const QString& s)
 {
diff --git a/Code/Mantid/MantidPlot/src/FitDialog.h b/Code/Mantid/MantidPlot/src/FitDialog.h
index 6f483bfe4c44f7a453d602eaf0f0febf9d0b43ab..d8d3838e1bfc14f7a653dfba2fe826cadd4fe062 100644
--- a/Code/Mantid/MantidPlot/src/FitDialog.h
+++ b/Code/Mantid/MantidPlot/src/FitDialog.h
@@ -47,9 +47,9 @@ class QRadioButton;
 class QLineEdit;
 class ColorBox;
 class Fit;
-class Table;
+class Table;
 class DoubleSpinBox;
-class QwtPlotCurve;
+class QwtPlotCurve;
 
 //! Fit Wizard
 class FitDialog : public QDialog
@@ -57,8 +57,8 @@ 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);
 
 protected:
@@ -100,27 +100,27 @@ private slots:
 
     //! Enable the "Apply" button
 	void enableApplyChanges(int = 0);
-	void setNumPeaks(int peaks);
+	void setNumPeaks(int peaks);
 	void saveInitialGuesses();
-	void returnToFitPage();
-	void updatePreview();
+	void returnToFitPage();
+	void updatePreview();
 	void showParameterRange(bool);
 
-private:
-	void loadPlugins();
+private:
+	void loadPlugins();
     void loadUserFunctions();
 	void initBuiltInFunctions();
 	void modifyGuesses(double* initVal);
-	QStringList builtInFunctionNames();
-	QStringList userFunctionNames();
+	QStringList builtInFunctionNames();
+	QStringList userFunctionNames();
 	QStringList plugInNames();
 	QString parseFormula(const QString& s);
 
     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;
+	QList <Fit*> d_user_functions, d_built_in_functions, d_plugins;
+	QList <MdiSubWindow*> srcTables;
 	QwtPlotCurve *d_preview_curve;
 
     QCheckBox* boxUseBuiltIn;
@@ -132,7 +132,7 @@ private:
 	QPushButton* buttonAdvanced;
 	QPushButton* buttonClear;
 	QPushButton* buttonPlugins;
-	QPushButton* btnBack;
+	QPushButton* btnBack;
 	QPushButton* btnSaveGuesses;
 	QComboBox* boxCurve;
 	QComboBox* boxAlgorithm;
@@ -153,7 +153,7 @@ private:
 	QRadioButton *generatePointsBtn, *samePointsBtn;
 	QPushButton *btnParamTable, *btnCovMatrix, *btnParamRange;
 	QLineEdit *covMatrixName, *paramTableName;
-	QCheckBox *plotLabelBox, *logBox, *scaleErrorsBox, *globalParamTableBox;
+	QCheckBox *plotLabelBox, *logBox, *scaleErrorsBox, *globalParamTableBox;
 	QCheckBox *previewBox;
 };
 #endif // FITDIALOG_H
diff --git a/Code/Mantid/MantidPlot/src/FitModelHandler.cpp b/Code/Mantid/MantidPlot/src/FitModelHandler.cpp
index 245befa0eeb0fb0deec332b612f83308a6fde074..ae11ee02abfca4e84612e2feda14fd18c152de08 100644
--- a/Code/Mantid/MantidPlot/src/FitModelHandler.cpp
+++ b/Code/Mantid/MantidPlot/src/FitModelHandler.cpp
@@ -1,97 +1,97 @@
-/***************************************************************************
-    File                 : FitModelHandler.cpp
-    Project              : QtiPlot
-    --------------------------------------------------------------------
-    Copyright            : (C) 2007 by Ion Vasilief
-    Email (use @ for *)  : ion_vasilief*yahoo.fr
-    Description          : An XML handler for the Fit class
-
- ***************************************************************************/
-
-/***************************************************************************
- *                                                                         *
- *  This program is free software; you can redistribute it and/or modify   *
- *  it under the terms of the GNU General Public License as published by   *
- *  the Free Software Foundation; either version 2 of the License, or      *
- *  (at your option) any later version.                                    *
- *                                                                         *
- *  This program is distributed in the hope that it will be useful,        *
- *  but WITHOUT 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, write to the Free Software           *
- *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
- *   Boston, MA  02110-1301  USA                                           *
- *                                                                         *
- ***************************************************************************/
-#include "FitModelHandler.h"
-#include "Fit.h"
-
-#include <QMessageBox>
-
-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;
-     }
-
-     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;
- }
-
-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;
- }
-
- bool FitModelHandler::characters(const QString &str)
- {
-     currentText += str;
-     return true;
- }
-
- QString FitModelHandler::errorString() const
- {
-     return errorStr;
+/***************************************************************************
+    File                 : FitModelHandler.cpp
+    Project              : QtiPlot
+    --------------------------------------------------------------------
+    Copyright            : (C) 2007 by Ion Vasilief
+    Email (use @ for *)  : ion_vasilief*yahoo.fr
+    Description          : An XML handler for the Fit class
+
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *  This program is free software; you can redistribute it and/or modify   *
+ *  it under the terms of the GNU General Public License as published by   *
+ *  the Free Software Foundation; either version 2 of the License, or      *
+ *  (at your option) any later version.                                    *
+ *                                                                         *
+ *  This program is distributed in the hope that it will be useful,        *
+ *  but WITHOUT 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, write to the Free Software           *
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
+ *   Boston, MA  02110-1301  USA                                           *
+ *                                                                         *
+ ***************************************************************************/
+#include "FitModelHandler.h"
+#include "Fit.h"
+
+#include <QMessageBox>
+
+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;
+     }
+
+     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;
+ }
+
+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;
+ }
+
+ bool FitModelHandler::characters(const QString &str)
+ {
+     currentText += str;
+     return true;
+ }
+
+ QString FitModelHandler::errorString() const
+ {
+     return errorStr;
  }
diff --git a/Code/Mantid/MantidPlot/src/FitModelHandler.h b/Code/Mantid/MantidPlot/src/FitModelHandler.h
index 61f135f378a251de4e760076ac6442e2579a17ab..4f971edbee0b9e06ec1880b95f209f3ff0a7c013 100644
--- a/Code/Mantid/MantidPlot/src/FitModelHandler.h
+++ b/Code/Mantid/MantidPlot/src/FitModelHandler.h
@@ -1,61 +1,61 @@
-/***************************************************************************
-    File                 : FitModelHandler.h
-    Project              : QtiPlot
-    --------------------------------------------------------------------
-    Copyright            : (C) 2007 by Ion Vasilief
-    Email (use @ for *)  : ion_vasilief*yahoo.fr
-    Description          : An XML handler for the Fit class
-
- ***************************************************************************/
-
-/***************************************************************************
- *                                                                         *
- *  This program is free software; you can redistribute it and/or modify   *
- *  it under the terms of the GNU General Public License as published by   *
- *  the Free Software Foundation; either version 2 of the License, or      *
- *  (at your option) any later version.                                    *
- *                                                                         *
- *  This program is distributed in the hope that it will be useful,        *
- *  but WITHOUT 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, write to the Free Software           *
- *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
- *   Boston, MA  02110-1301  USA                                           *
- *                                                                         *
- ***************************************************************************/
-#ifndef FITMODELHANDLER_H
-#define FITMODELHANDLER_H
-
-#include <QXmlDefaultHandler>
-#include <QVarLengthArray>
-
-class Fit;
-
-class FitModelHandler : public QXmlDefaultHandler
-{
-public:
-    FitModelHandler(Fit *fit);
-
-    bool startElement(const QString &namespaceURI, const QString &localName,
-                       const QString &qName, const QXmlAttributes &attributes);
-    bool endElement(const QString &namespaceURI, const QString &localName,
-                     const QString &qName);
-    bool characters(const QString &str);
-    bool fatalError(const QXmlParseException &){return false;};
-    QString errorString() const;
-
-private:
-    Fit* d_fit;
-    bool metFitTag;
-    QString currentText;
-    QString errorStr;
-    QString d_formula;
-    QStringList d_parameters;
-    QStringList d_explanations;
-    QVarLengthArray<double> d_values;
-};
-
-#endif
+/***************************************************************************
+    File                 : FitModelHandler.h
+    Project              : QtiPlot
+    --------------------------------------------------------------------
+    Copyright            : (C) 2007 by Ion Vasilief
+    Email (use @ for *)  : ion_vasilief*yahoo.fr
+    Description          : An XML handler for the Fit class
+
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *  This program is free software; you can redistribute it and/or modify   *
+ *  it under the terms of the GNU General Public License as published by   *
+ *  the Free Software Foundation; either version 2 of the License, or      *
+ *  (at your option) any later version.                                    *
+ *                                                                         *
+ *  This program is distributed in the hope that it will be useful,        *
+ *  but WITHOUT 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, write to the Free Software           *
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
+ *   Boston, MA  02110-1301  USA                                           *
+ *                                                                         *
+ ***************************************************************************/
+#ifndef FITMODELHANDLER_H
+#define FITMODELHANDLER_H
+
+#include <QXmlDefaultHandler>
+#include <QVarLengthArray>
+
+class Fit;
+
+class FitModelHandler : public QXmlDefaultHandler
+{
+public:
+    FitModelHandler(Fit *fit);
+
+    bool startElement(const QString &namespaceURI, const QString &localName,
+                       const QString &qName, const QXmlAttributes &attributes);
+    bool endElement(const QString &namespaceURI, const QString &localName,
+                     const QString &qName);
+    bool characters(const QString &str);
+    bool fatalError(const QXmlParseException &){return false;};
+    QString errorString() const;
+
+private:
+    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/Code/Mantid/MantidPlot/src/Folder.cpp b/Code/Mantid/MantidPlot/src/Folder.cpp
index 6df5e6b49a4b0f26d2e001f07c1d1b69cf04afcc..279774180bfa8eaa2fe66600dcbe24e76168df54 100644
--- a/Code/Mantid/MantidPlot/src/Folder.cpp
+++ b/Code/Mantid/MantidPlot/src/Folder.cpp
@@ -183,7 +183,7 @@ void Folder::addWindow( MdiSubWindow *w )
 {
 	if (w) {
 		lstWindows.append( w );
-		w->setFolder(this);
+		w->setFolder(this);
 	}
 }
 
diff --git a/Code/Mantid/MantidPlot/src/FunctionDialog.cpp b/Code/Mantid/MantidPlot/src/FunctionDialog.cpp
index f234e2497da38d54d216af4cc15b99d1ca0341bb..acea2cfc6f13c4958c4705d80a557240b62623fb 100644
--- a/Code/Mantid/MantidPlot/src/FunctionDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/FunctionDialog.cpp
@@ -80,7 +80,7 @@ FunctionDialog::FunctionDialog( QWidget* parent, Qt::WFlags fl )
 	boxPoints->setRange(2, 1000000);
 	boxPoints->setSingleStep(100);
 	boxPoints->setValue(100);
-	gl1->addWidget(boxPoints, 3, 1);
+	gl1->addWidget(boxPoints, 3, 1);
 
 	functionPage = new QWidget();
 	functionPage->setLayout(gl1);
@@ -112,7 +112,7 @@ FunctionDialog::FunctionDialog( QWidget* parent, Qt::WFlags fl )
 	boxParPoints->setRange(2, 1000000);
 	boxParPoints->setSingleStep(100);
 	boxParPoints->setValue(100);
-	gl2->addWidget(boxParPoints, 5, 1);
+	gl2->addWidget(boxParPoints, 5, 1);
 	gl2->setRowStretch(6, 1);
 
 	parametricPage = new QWidget();
@@ -145,7 +145,7 @@ FunctionDialog::FunctionDialog( QWidget* parent, Qt::WFlags fl )
 	boxPolarPoints->setRange(2, 1000000);
 	boxPolarPoints->setSingleStep(100);
 	boxPolarPoints->setValue(100);
-	gl3->addWidget(boxPolarPoints, 6, 1);
+	gl3->addWidget(boxPolarPoints, 6, 1);
 	gl3->setRowStretch(7, 1);
 
 	polarPage = new QWidget();
@@ -204,7 +204,7 @@ void FunctionDialog::setCurveToModify(Graph *g, int curve)
 		return;
 
 	curveID = curve;
-	QStringList formulas = c->formulas();
+	QStringList formulas = c->formulas();
 
 	if (c->functionType() == FunctionCurve::Normal){
 		boxFunction->setText(formulas[0]);
diff --git a/Code/Mantid/MantidPlot/src/Graph3D.cpp b/Code/Mantid/MantidPlot/src/Graph3D.cpp
index 27433a92155d8bebc4541ec884d285d15bcf5337..bc80c8d2a474b0e89d55a787ab9ed433e7fea9d1 100644
--- a/Code/Mantid/MantidPlot/src/Graph3D.cpp
+++ b/Code/Mantid/MantidPlot/src/Graph3D.cpp
@@ -1339,20 +1339,20 @@ void Graph3D::updateScalesFromMatrix(double xl, double xr, double yl,
 {	double xStart = qMin(d_matrix->xStart(), d_matrix->xEnd());
 	double xEnd = qMax(d_matrix->xStart(), d_matrix->xEnd());
 	double yStart = qMin(d_matrix->yStart(), d_matrix->yEnd());
-	double yEnd = qMax(d_matrix->yStart(), d_matrix->yEnd());
+	double yEnd = qMax(d_matrix->yStart(), d_matrix->yEnd());
 
 	double dx = fabs((xEnd - xStart)/double(d_matrix->numCols()-1));
 	double dy = fabs((yEnd - yStart)/double(d_matrix->numRows()-1));
 
 	int nc = int(fabs(xr - xl)/dx)+1;
 	int nr = int(fabs(yr - yl)/dy)+1;
-
-    double x_begin = qMin(xl, xr);
-	double y_begin = qMin(yl, yr);
-
+
+    double x_begin = qMin(xl, xr);
+	double y_begin = qMin(yl, yr);
+
 	double **data_matrix = Matrix::allocateMatrixData(nc, nr);
 	for (int i = 0; i < nc; i++){
-		double x = x_begin + i*dx;
+		double x = x_begin + i*dx;
         double dli,dlf;
         dlf = modf(abs((x - xStart)/dx),&dli);
         int l = dli; if (dlf > 0.5) l++;
@@ -1875,18 +1875,18 @@ void Graph3D::setBackGrid(bool b)
 
 void Graph3D::print()
 {
-	QPrinter printer;
+	QPrinter printer;
 	if (width() > height())
-        printer.setOrientation(QPrinter::Landscape);
-    else
+        printer.setOrientation(QPrinter::Landscape);
+    else
         printer.setOrientation(QPrinter::Portrait);
 	printer.setColorMode (QPrinter::Color);
 	printer.setFullPage(false);
-	if (printer.setup()){
-        QImage im = sp->grabFrameBuffer(true);
-        QPainter paint(&printer);
-        paint.drawImage(printer.pageRect(), im);
-        paint.end();
+	if (printer.setup()){
+        QImage im = sp->grabFrameBuffer(true);
+        QPainter paint(&printer);
+        paint.drawImage(printer.pageRect(), im);
+        paint.end();
 	}
 }
 
@@ -2036,26 +2036,26 @@ bool Graph3D::eventFilter(QObject *object, QEvent *e)
 		QWheelEvent *wheelevent=dynamic_cast<QWheelEvent*>(e);
 		if(wheelevent)
 		{
-			if (wheelevent->orientation() == Qt::Vertical) {
-
+			if (wheelevent->orientation() == Qt::Vertical) {
+
 				double zoom=sp->zoom();
-				int delta=wheelevent->delta() ;
-				//zoom in on mouse wheel forward rotation  
-				if(delta>0)
+				int delta=wheelevent->delta() ;
+				//zoom in on mouse wheel forward rotation  
+				if(delta>0)
 				{	m_zoomOutScale=1;
 				m_zoomInScale+=0.003125; 
 				setZoom(zoom*m_zoomInScale);
-				}
-				else 
+				}
+				else 
 				{	//zoom out on mouse wheel backward rotation  
 					m_zoomInScale=1;
 					m_zoomOutScale+=0.003125;
 					setZoom(zoom/m_zoomOutScale);
-				}
-				return true;
-			}
-			
-		}
+				}
+				return true;
+			}
+			
+		}
 	}
 	
 	return MdiSubWindow::eventFilter(object, e);
@@ -2462,16 +2462,16 @@ QString Graph3D::saveToString(const QString& geometry, bool)
 	s+="</SurfacePlot>\n";
 	return s;
 }
-
-QString Graph3D::saveAsTemplate(const QString& geometryInfo)
-{
-	QString s = saveToString(geometryInfo);
-	QStringList lst = s.split("\n", QString::SkipEmptyParts);
-	QStringList l = lst[3].split("\t");
-	l[1] = QString();
-	lst[3] = l.join("\t");
-	return lst.join("\n");
-}
+
+QString Graph3D::saveAsTemplate(const QString& geometryInfo)
+{
+	QString s = saveToString(geometryInfo);
+	QStringList lst = s.split("\n", QString::SkipEmptyParts);
+	QStringList l = lst[3].split("\t");
+	l[1] = QString();
+	lst[3] = l.join("\t");
+	return lst.join("\n");
+}
 
 void Graph3D::showColorLegend(bool show)
 {
diff --git a/Code/Mantid/MantidPlot/src/Grid.cpp b/Code/Mantid/MantidPlot/src/Grid.cpp
index ca044bbf45e0af272be12696dcf2fc49dc426b37..9b97a114f42e5e2d76bd9edc4557ad50273795ac 100644
--- a/Code/Mantid/MantidPlot/src/Grid.cpp
+++ b/Code/Mantid/MantidPlot/src/Grid.cpp
@@ -45,7 +45,7 @@ mrkY(-1)
 	setMajPen(QPen(Qt::blue, 0.5, Qt::SolidLine));
 	setMinPen(QPen(Qt::gray, 0.4, Qt::DotLine));
 	enableX(false);
-	enableY(false);
+	enableY(false);
     setRenderHint(QwtPlotItem::RenderAntialiased, false);
 }
 
@@ -137,21 +137,21 @@ void Grid::load(const QStringList& grid)
 	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());
-
+		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()));
@@ -255,7 +255,7 @@ void Grid::copy(Grid *grid)
 	setAxis(grid->xAxis(), grid->yAxis());
 
 	enableZeroLineX(grid->xZeroLineEnabled());
-	enableZeroLineY(grid->yZeroLineEnabled());
+	enableZeroLineY(grid->yZeroLineEnabled());
 	setRenderHint(QwtPlotItem::RenderAntialiased, grid->testRenderHint(QwtPlotItem::RenderAntialiased));
 }
 
@@ -266,27 +266,27 @@ QString Grid::saveToString()
 	s += QString::number(xMinEnabled())+"\t";
 	s += QString::number(yEnabled())+"\t";
 	s += QString::number(yMinEnabled())+"\t";
-
+
 	s += majPenX().color().name()+"\t";
 	s += QString::number(majPenX().style() - 1)+"\t";
-	s += QString::number(majPenX().widthF())+"\t";
+	s += QString::number(majPenX().widthF())+"\t";
 
 	s += minPenX().color().name()+"\t";
 	s += QString::number(minPenX().style() - 1)+"\t";
 	s += QString::number(minPenX().widthF())+"\t";
-
-    s += majPenY().color().name()+"\t";
-	s += QString::number(majPenY().style() - 1)+"\t";
-	s += QString::number(majPenY().widthF())+"\t";
-
-	s += minPenY().color().name()+"\t";
-	s += QString::number(minPenY().style() - 1)+"\t";
-	s += QString::number(minPenY().widthF())+"\t";
+
+    s += majPenY().color().name()+"\t";
+	s += QString::number(majPenY().style() - 1)+"\t";
+	s += QString::number(majPenY().widthF())+"\t";
+
+	s += minPenY().color().name()+"\t";
+	s += QString::number(minPenY().style() - 1)+"\t";
+	s += QString::number(minPenY().widthF())+"\t";
 
 	s += QString::number(xZeroLineEnabled())+"\t";
 	s += QString::number(yZeroLineEnabled())+"\t";
 	s += QString::number(xAxis())+"\t";
-	s += QString::number(yAxis())+"\t";
+	s += QString::number(yAxis())+"\t";
 	s += QString::number(testRenderHint(QwtPlotItem::RenderAntialiased))+"\n";
 	return s;
 }
diff --git a/Code/Mantid/MantidPlot/src/ImageExportDialog.cpp b/Code/Mantid/MantidPlot/src/ImageExportDialog.cpp
index 481404f9b76d04962822e2102adfa8b3fe74bfbc..3f9be29971f9fe9420f32e57f69ebdf99de05fc2 100644
--- a/Code/Mantid/MantidPlot/src/ImageExportDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ImageExportDialog.cpp
@@ -54,10 +54,10 @@ ImageExportDialog::ImageExportDialog(QWidget * parent, bool vector_options, bool
 	#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++)
@@ -91,16 +91,16 @@ void ImageExportDialog::initAdvancedOptions()
 	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);
+	vector_layout->addWidget(resLabel, 1, 0);
 	resLabel->hide();
 	d_resolution = new QSpinBox();
 	d_resolution->setRange(0, 1000);
-	//d_resolution->setValue(app->d_export_resolution);
-	//only printing with screen resolution works correctly for the moment
+	//d_resolution->setValue(app->d_export_resolution);
+	//only printing with screen resolution works correctly for the moment
 	d_resolution->setValue(QPrinter().resolution());
-	vector_layout->addWidget(d_resolution, 1, 1);
+	vector_layout->addWidget(d_resolution, 1, 1);
 	d_resolution->hide();
 
 	d_color = new QCheckBox();
diff --git a/Code/Mantid/MantidPlot/src/ImportASCIIDialog.cpp b/Code/Mantid/MantidPlot/src/ImportASCIIDialog.cpp
index a4c17cc75c356329ea79292e06bed214e92cd1be..73dd29fe04d1c8716395e573a97ac0c1ae266ecb 100644
--- a/Code/Mantid/MantidPlot/src/ImportASCIIDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/ImportASCIIDialog.cpp
@@ -1,817 +1,817 @@
-/***************************************************************************
-    File                 : ImportASCIIDialog.cpp
-    Project              : QtiPlot
-    --------------------------------------------------------------------
-    Copyright            : (C) 2006,2007 by Ion Vasilief, Knut Franke
-    Email (use @ for *)  : ion_vasilief*yahoo.fr, knut.franke*gmx.de
-    Description          : Import ASCII file(s) dialog
-
- ***************************************************************************/
-
-
-/***************************************************************************
- *                                                                         *
- *  This program is free software; you can redistribute it and/or modify   *
- *  it under the terms of the GNU General Public License as published by   *
- *  the Free Software Foundation; either version 2 of the License, or      *
- *  (at your option) any later version.                                    *
- *                                                                         *
- *  This program is distributed in the hope that it will be useful,        *
- *  but WITHOUT 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, write to the Free Software           *
- *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
- *   Boston, MA  02110-1301  USA                                           *
- *                                                                         *
- ***************************************************************************/
-
-#include "ImportASCIIDialog.h"
-#include "ApplicationWindow.h"
-#include "Table.h"
-#include "Matrix.h"
-#include "MatrixModel.h"
-
-#include <QLayout>
-#include <QGroupBox>
-#include <QPushButton>
-#include <QRegExp>
-#include <QMessageBox>
-#include <QTextStream>
-#include <QApplication>
-#include <QProgressDialog>
-#include <QStackedWidget>
-#include <QHeaderView>
-
-#include <gsl/gsl_math.h>
-#include<iostream>
-
-ImportASCIIDialog::ImportASCIIDialog(bool new_windows_only, QWidget * parent, bool extended, Qt::WFlags flags )
-: ExtensibleFileDialog(parent, extended, flags )
-{
-	setWindowTitle(tr("MantidPlot - Import ASCII File(s)"));
-
-	QStringList filters;
-	filters << tr("All files") + " (*)";
-	filters << tr("Text files") + " (*.TXT *.txt)";
-	filters << tr("Data files") + " (*.DAT *.dat)";
-	filters << tr("Comma Separated Values") + " (*.CSV *.csv)";
-	setFilters( filters );
-
-	setFileMode( QFileDialog::ExistingFiles );
-
-	d_current_path = QString::null;
-
-	initAdvancedOptions();
-	setNewWindowsOnly(new_windows_only);
-	setExtensionWidget(d_advanced_options);
-
-	// get rembered option values
-	ApplicationWindow *app = (ApplicationWindow *)parent;
-	setLocale(app->locale());
-
-	d_strip_spaces->setChecked(app->strip_spaces);
-	d_simplify_spaces->setChecked(app->simplify_spaces);
-	d_ignored_lines->setValue(app->ignoredLines);
-	d_rename_columns->setChecked(app->renameColumns);
-	setColumnSeparator(app->columnSeparator);
-    d_comment_string->setText(app->d_ASCII_comment_string);
-    d_import_comments->setChecked(app->d_ASCII_import_comments);
-    d_read_only->setChecked(app->d_ASCII_import_read_only);
-
-	if (app->d_ASCII_import_locale.name() == QLocale::c().name())
-        boxDecimalSeparator->setCurrentIndex(1);
-    else if (app->d_ASCII_import_locale.name() == QLocale(QLocale::German).name())
-        boxDecimalSeparator->setCurrentIndex(2);
-    else if (app->d_ASCII_import_locale.name() == QLocale(QLocale::French).name())
-        boxDecimalSeparator->setCurrentIndex(3);
-	boxDecimalSeparator->setEnabled(app->d_import_dec_separators);
-	d_import_dec_separators->setChecked(app->d_import_dec_separators);
-
-	connect(d_import_mode, SIGNAL(currentIndexChanged(int)), this, SLOT(updateImportMode(int)));
-
-	if (app->d_ASCII_import_mode < d_import_mode->count())
-		d_import_mode->setCurrentIndex(app->d_ASCII_import_mode);
-
-	d_preview_lines_box->setValue(app->d_preview_lines);
-	d_preview_button->setChecked(app->d_ASCII_import_preview);
-
-    boxEndLine->setCurrentIndex((int)app->d_ASCII_end_line);
-
-	if (!app->d_ASCII_import_preview)
-		d_preview_stack->hide();
-
-	initPreview(d_import_mode->currentIndex());
-
-    connect(d_preview_lines_box, SIGNAL(valueChanged(int)), this, SLOT(preview()));
-    connect(d_rename_columns, SIGNAL(clicked()), this, SLOT(preview()));
-    connect(d_import_comments, SIGNAL(clicked()), this, SLOT(preview()));
-    connect(d_strip_spaces, SIGNAL(clicked()), this, SLOT(preview()));
-    connect(d_simplify_spaces, SIGNAL(clicked()), this, SLOT(preview()));
-    connect(d_ignored_lines, SIGNAL(valueChanged(int)), this, SLOT(preview()));
-    connect(d_import_dec_separators, SIGNAL(clicked()), this, SLOT(preview()));
-    connect(d_column_separator, SIGNAL(currentIndexChanged(int)), this, SLOT(preview()));
-    connect(boxDecimalSeparator, SIGNAL(currentIndexChanged(int)), this, SLOT(preview()));
-    connect(d_comment_string, SIGNAL(textChanged(const QString&)), this, SLOT(preview()));
-    connect(this, SIGNAL(currentChanged(const QString&)), this, SLOT(changePreviewFile(const QString&)));
-}
-void ImportASCIIDialog::addColumnSeparators()
-{
-	if(!d_column_separator) return;
-	d_column_separator->addItem(tr("TAB"));
-	d_column_separator->addItem(tr("SPACE"));
-	d_column_separator->addItem(";" + tr("TAB"));
-	d_column_separator->addItem("," + tr("TAB"));
-	d_column_separator->addItem(";" + tr("SPACE"));
-	d_column_separator->addItem("," + tr("SPACE"));
-	d_column_separator->addItem(";");
-	d_column_separator->addItem(",");
-}
-void ImportASCIIDialog::addColumnSeparatorsforLoadAscii()
-{
-	if(!d_column_separator) return;
-	d_column_separator->addItem(tr("CSV"));
-	d_column_separator->addItem(tr("Tab"));
-	d_column_separator->addItem(tr("Space"));
-	d_column_separator->addItem(tr("SemiColon"));
-	d_column_separator->addItem(tr("Colon"));
-}
-QString ImportASCIIDialog::getselectedColumnSeparator()
-{return d_column_separator->currentText();
-}
-void ImportASCIIDialog::initAdvancedOptions()
-{
-	d_advanced_options = new QGroupBox();
-	QVBoxLayout *main_layout = new QVBoxLayout(d_advanced_options);
-	QGridLayout *advanced_layout = new QGridLayout();
-	main_layout->addLayout(advanced_layout);
-
-	advanced_layout->addWidget(new QLabel(tr("Import each file as: ")), 0, 0);
-	d_import_mode = new QComboBox();
-	// Important: Keep this in sync with the ImportMode enum.
-	d_import_mode->addItem(tr("New Table"));
-	d_import_mode->addItem(tr("New Matrice"));
-	d_import_mode->addItem(tr("New Workspace"));
-	d_import_mode->addItem(tr("New Columns"));
-	d_import_mode->addItem(tr("New Rows"));
-	d_import_mode->addItem(tr("Overwrite Current Window"));
-	
-	advanced_layout->addWidget(d_import_mode, 0, 1);
-
-	QLabel *label_column_separator = new QLabel(tr("Separator:"));
-	advanced_layout->addWidget(label_column_separator, 1, 0);
-	d_column_separator = new QComboBox();
-	addColumnSeparators();
-	d_column_separator->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed );
-	d_column_separator->setEditable( true );
-	advanced_layout->addWidget(d_column_separator, 1, 1);
-	// context-sensitive help
-	QString help_column_separator = 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_column_separator += "\n"+tr("The separator must not contain the following characters: \n0-9eE.+-");
-	d_column_separator->setWhatsThis(help_column_separator);
-	label_column_separator->setToolTip(help_column_separator);
-	d_column_separator->setToolTip(help_column_separator);
-	label_column_separator->setWhatsThis(help_column_separator);
-
-	QLabel *label_ignore_lines = new QLabel(tr( "Ignore first" ));
-	advanced_layout->addWidget(label_ignore_lines, 2, 0);
-	d_ignored_lines = new QSpinBox();
-	d_ignored_lines->setRange( 0, 10000 );
-	d_ignored_lines->setSuffix(" " + tr("lines"));
-	d_ignored_lines->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed );
-	advanced_layout->addWidget(d_ignored_lines, 2, 1);
-
-	advanced_layout->addWidget(new QLabel(tr("Ignore lines starting with")), 3, 0);
-	d_comment_string = new QLineEdit();
-    advanced_layout->addWidget(d_comment_string, 3, 1);
-
-	d_rename_columns = new QCheckBox(tr("Use first row to &name columns"));
-	advanced_layout->addWidget(d_rename_columns, 0, 2, 1, 2);
-
-    d_import_comments = new QCheckBox(tr("Use second row as &comments"));
-	advanced_layout->addWidget(d_import_comments, 1, 2, 1, 2);
-	connect(d_rename_columns, SIGNAL(toggled(bool)), d_import_comments, SLOT(setEnabled(bool)));
-
-	d_strip_spaces = new QCheckBox(tr("&Remove white spaces from line ends"));
-	advanced_layout->addWidget(d_strip_spaces, 2, 2, 1, 2);
-	// context-sensitive help
-	QString help_strip_spaces = tr("By checking this option all white spaces will be \nremoved from the beginning and the end of \nthe lines in the ASCII file.","when translating this check the what's this functions and tool tips to place the '\\n's correctly");
-	help_strip_spaces +="\n\n"+tr("Warning: checking this option leads to column \noverlaping if the columns in the ASCII file don't \nhave the same number of rows.");
-	help_strip_spaces +="\n"+tr("To avoid this problem you should precisely \ndefine the column separator using TAB and \nSPACE characters.","when translating this check the what's this functions and tool tips to place the '\\n's correctly");
-	d_strip_spaces->setWhatsThis(help_strip_spaces);
-	d_strip_spaces->setToolTip(help_strip_spaces);
-
-	d_simplify_spaces = new QCheckBox(tr("&Simplify white spaces" ));
-	advanced_layout->addWidget(d_simplify_spaces, 3, 2, 1, 2);
-	// context-sensitive help
-	QString help_simplify_spaces = tr("By checking this option all white spaces will be \nremoved from the beginning and the end of the \nlines and each sequence of internal \nwhitespaces (including the TAB character) will \nbe replaced with a single space.","when translating this check the what's this functions and tool tips to place the '\\n's correctly");
-	help_simplify_spaces +="\n\n"+tr("Warning: checking this option leads to column \noverlaping if the columns in the ASCII file don't \nhave the same number of rows.","when translating this check the what's this functions and tool tips to place the '\\n's correctly");
-	help_simplify_spaces +="\n"+tr("To avoid this problem you should precisely \ndefine the column separator using TAB and \nSPACE characters.","when translating this check the what's this functions and tool tips to place the '\\n's correctly");
-	d_simplify_spaces->setWhatsThis(help_simplify_spaces);
-	d_simplify_spaces->setToolTip(help_simplify_spaces);
-
-	advanced_layout->addWidget(new QLabel(tr("Decimal Separators")), 4, 0);
-	boxDecimalSeparator = new QComboBox();
-	boxDecimalSeparator->addItem(tr("System Locale Setting"));
-	boxDecimalSeparator->addItem("1,000.0");
-	boxDecimalSeparator->addItem("1.000,0");
-	boxDecimalSeparator->addItem("1 000,0");
-	advanced_layout->addWidget(boxDecimalSeparator, 4, 1);
-
-	d_import_dec_separators = new QCheckBox(tr("Import &decimal separators"));
-	connect(d_import_dec_separators, SIGNAL(toggled(bool)), boxDecimalSeparator, SLOT(setEnabled(bool)));
-	advanced_layout->addWidget(d_import_dec_separators, 4, 2, 1, 2);
-
-	advanced_layout->addWidget(new QLabel(tr("Endline character")), 5, 0);
-	boxEndLine = new QComboBox();
-	boxEndLine->addItem(tr("LF (Unix)"));
-	boxEndLine->addItem(tr("CRLF (Windows)"));
-	boxEndLine->addItem(tr("CR (Mac)"));
-    connect(boxEndLine, SIGNAL(activated(int)), this, SLOT(preview()));
-	advanced_layout->addWidget(boxEndLine, 5, 1);
-
-    d_read_only = new QCheckBox(tr("Import as &read-only"));
-	advanced_layout->addWidget(d_read_only, 5, 2);
-
-	d_preview_button = new QCheckBox(tr("&Preview Lines"));
-	connect(d_preview_button, SIGNAL(clicked()), this, SLOT(preview()));
-	advanced_layout->addWidget(d_preview_button, 6, 0);
-
-	d_preview_lines_box = new QSpinBox();
-	d_preview_lines_box->setMaximum (INT_MAX);
-	d_preview_lines_box->setValue(100);
-	d_preview_lines_box->setSingleStep(10);
-	d_preview_lines_box->setSpecialValueText(tr("All"));
-	advanced_layout->addWidget(d_preview_lines_box, 6, 1);
-
-	d_help_button = new QPushButton(tr("&Help"));
-	connect(d_help_button, SIGNAL(clicked()), this, SLOT(displayHelp()));
-	advanced_layout->addWidget(d_help_button, 6, 2);
-
-	d_preview_table = NULL;
-	d_preview_matrix = NULL;
-	d_preview_stack = new QStackedWidget();
-	main_layout->addWidget(d_preview_stack);
-}
-
-void ImportASCIIDialog::initPreview(int previewMode)
-{
-	if (previewMode < NewTables || previewMode > Overwrite)
-		return;
-
-	ApplicationWindow *app = (ApplicationWindow *)parent();
-	if (!app)
-		return;
-
-	if (d_preview_table){
-		delete d_preview_table;
-		d_preview_table = NULL;
-	}
-
-	if (d_preview_matrix){
-		delete d_preview_matrix;
-		d_preview_matrix = NULL;
-	}
-
-	switch(previewMode){
-		case NewTables:
-			d_preview_table = new PreviewTable(30, 2, this);
-			d_preview_table->setNumericPrecision(app->d_decimal_digits);
-			d_preview_stack->addWidget(d_preview_table);
-			enableTableOptions(true);
-		break;
-
-		case NewMatrices:
-			d_preview_matrix = new PreviewMatrix(app);
-			d_preview_stack->addWidget(d_preview_matrix);
-			enableTableOptions(false);
-		break;
-
-		case NewColumns:
-		case NewRows:
-		case Overwrite:
-			MdiSubWindow *w = app->activeWindow();
-			if (!w)
-				return;
-
-			if (w->inherits("Table")){
-				d_preview_table = new PreviewTable(30, 2, this);
-				d_preview_table->setNumericPrecision(app->d_decimal_digits);
-				d_preview_stack->addWidget(d_preview_table);
-				enableTableOptions(true);
-			} else if (w->isA("Matrix")){
-				d_preview_matrix = new PreviewMatrix(app, (Matrix *)w);
-				d_preview_stack->addWidget(d_preview_matrix);
-				enableTableOptions(false);
-			}
-			break;
-	}
-	preview();
-}
-
-void ImportASCIIDialog::enableTableOptions(bool on)
-{
-	d_rename_columns->setEnabled(on);
-	d_import_comments->setEnabled(on && d_rename_columns->isChecked());
-	d_read_only->setEnabled(on);
-}
-
-void ImportASCIIDialog::setColumnSeparator(const QString& sep)
-{
-	if (sep=="\t")
-		d_column_separator->setCurrentIndex(0);
-	else if (sep==" ")
-		d_column_separator->setCurrentIndex(1);
-	else if (sep==";\t")
-		d_column_separator->setCurrentIndex(2);
-	else if (sep==",\t")
-		d_column_separator->setCurrentIndex(3);
-	else if (sep=="; ")
-		d_column_separator->setCurrentIndex(4);
-	else if (sep==", ")
-		d_column_separator->setCurrentIndex(5);
-	else if (sep==";")
-		d_column_separator->setCurrentIndex(6);
-	else if (sep==",")
-		d_column_separator->setCurrentIndex(7);
-	else {
-		QString separator = sep;
-		d_column_separator->setEditText(separator.replace(" ","\\s").replace("\t","\\t"));
-	}
-}
-
-const QString ImportASCIIDialog::columnSeparator() const
-{
-	QString sep = d_column_separator->currentText();
-
-	if (d_simplify_spaces->isChecked())
-		sep.replace(tr("TAB"), " ", Qt::CaseInsensitive);
-	else
-		sep.replace(tr("TAB"), "\t", Qt::CaseInsensitive);
-
-	sep.replace(tr("SPACE"), " ", Qt::CaseInsensitive);
-	sep.replace("\\s", " ");
-	sep.replace("\\t", "\t");
-
-	/* TODO
-	if (sep.contains(QRegExp("[0-9.eE+-]")))
-		QMessageBox::warning(this, tr("QtiPlot - Import options error"),
-				tr("The separator must not contain the following characters: 0-9eE.+-"));
-	*/
-
-	return sep;
-}
-
-void ImportASCIIDialog::displayHelp()
-{
-	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.+-") + "\n\n";
-	s += tr( "Remove white spaces from line ends" )+ ":\n";
-	s += tr("By checking this option all white spaces will be removed from the beginning and the end of the lines in the ASCII file.") + "\n\n";
-	s += tr( "Simplify white spaces" )+ ":\n";
-	s += tr("By checking this option each sequence of internal whitespaces (including the TAB character) will be replaced with a single space.");
-	s += tr("By checking this option all white spaces will be removed from the beginning and the end of the lines and each sequence of internal whitespaces (including the TAB character) will be replaced with a single space.");
-
-	s +="\n\n"+tr("Warning: using these two last options leads to column overlaping if the columns in the ASCII file don't have the same number of rows.");
-	s +="\n"+tr("To avoid this problem you should precisely define the column separator using TAB and SPACE characters.");
-
-	QMessageBox::about(this, tr("MantidPlot - Help"), s);
-}
-
-void ImportASCIIDialog::updateImportMode(int mode)
-{
-	if (mode == Overwrite)
-		setFileMode( QFileDialog::ExistingFile );
-	else
-		setFileMode( QFileDialog::ExistingFiles );
-	if(mode==NewWorkspace)
-	{
-		d_column_separator->clear();
-		addColumnSeparatorsforLoadAscii();
-	}
-	else
-	{	d_column_separator->clear();
-		addColumnSeparators();
-	}
-
-	initPreview(mode);
-}
-
-void ImportASCIIDialog::closeEvent(QCloseEvent* e)
-{
-	ApplicationWindow *app = (ApplicationWindow *)this->parent();
-	if (app){
-		app->d_extended_import_ASCII_dialog = this->isExtended();
-		app->d_ASCII_file_filter = this->selectedFilter();
-		app->d_ASCII_import_preview = d_preview_button->isChecked();
-		app->d_preview_lines = d_preview_lines_box->value();
-	}
-
-	e->accept();
-}
-
-QLocale ImportASCIIDialog::decimalSeparators()
-{
-	QLocale locale;
-    switch (boxDecimalSeparator->currentIndex()){
-        case 0:
-            locale = QLocale::system();
-        break;
-        case 1:
-            locale = QLocale::c();
-        break;
-        case 2:
-            locale = QLocale(QLocale::German);
-        break;
-        case 3:
-            locale = QLocale(QLocale::French);
-        break;
-    }
-	return locale;
-}
-
-void ImportASCIIDialog::preview()
-{
-    if (!d_preview_button->isChecked()){
-		d_preview_stack->hide();
-        return;
-    } else
-		d_preview_stack->show();
-
-	if (d_preview_table)
-		previewTable();
-	else if (d_preview_matrix)
-		previewMatrix();
-}
-
-void ImportASCIIDialog::previewTable()
-{
-	if (!d_preview_table)
-		return;
-
-	if (!d_preview_table->isVisible())
-		d_preview_table->show();
-
-	if (d_current_path.trimmed().isEmpty()){
-		d_preview_table->clear();
-		d_preview_table->resetHeader();
-        return;
-    }
-
-	int importMode = d_import_mode->currentIndex();
-	if (importMode == NewTables)
-		importMode = Table::Overwrite;
-	else
-		importMode -= 2;
-
-	d_preview_table->resetHeader();
-	d_preview_table->importASCII(d_current_path, columnSeparator(), d_ignored_lines->value(),
-							d_rename_columns->isChecked(), d_strip_spaces->isChecked(),
-							d_simplify_spaces->isChecked(), d_import_comments->isChecked(),
-                            d_comment_string->text(), (Table::ImportMode)importMode, 
-                            boxEndLine->currentIndex(), d_preview_lines_box->value());
-
-	if (d_import_dec_separators->isChecked())
-		d_preview_table->updateDecimalSeparators(decimalSeparators());
-    if (!d_preview_table->isVisible())
-        d_preview_table->show();
-}
-
-void ImportASCIIDialog::previewMatrix()
-{
-	if (!d_preview_matrix)
-		return;
-
-	if (d_current_path.trimmed().isEmpty()){
-		d_preview_matrix->clear();
-        return;
-    }
-
-	int importMode = d_import_mode->currentIndex();
-	if (importMode == NewMatrices)
-		importMode = Matrix::Overwrite;
-	else
-		importMode -= 2;
-
-	QLocale locale = d_preview_matrix->locale();
-	if(d_import_dec_separators->isChecked())
-		locale = decimalSeparators();
-
-	d_preview_matrix->importASCII(d_current_path, columnSeparator(), d_ignored_lines->value(),
-							d_strip_spaces->isChecked(), d_simplify_spaces->isChecked(),
-                            d_comment_string->text(), importMode, locale,
-                            boxEndLine->currentIndex(), d_preview_lines_box->value());
-	d_preview_matrix->resizeColumnsToContents();
-}
-
-void ImportASCIIDialog::changePreviewFile(const QString& path)
-{
-	if (path.isEmpty())
-		return;
-
-	QFileInfo fi(path);
-	if (!fi.exists() || fi.isDir() || !fi.isFile())
-		return;
-
-	if (!fi.isReadable()){
-		QMessageBox::critical(this, tr("MantidPlot - File openning error"),
-		tr("You don't have the permission to open this file: <b>%1</b>").arg(path));
-		return;
-	}
-
-  if (fi.suffix().toLower() == "csv")
-  {
-    int index = d_column_separator->findText("CSV",Qt::MatchExactly);
-    if (index < 0) index = d_column_separator->findText(",",Qt::MatchExactly);
-    if (index >= 0)
-    {
-      d_column_separator->setCurrentIndex(index);
-    }
-  }
-
-	d_current_path = path;
-	preview();
-}
-
-void ImportASCIIDialog::setNewWindowsOnly(bool on)
-{
-    if (on){
-        d_import_mode->clear();
-        d_import_mode->addItem(tr("New Table"));
-        d_import_mode->addItem(tr("New Matrice"));
-		d_import_mode->addItem(tr("New Workspace"));
-    }
-
-    d_preview_button->setChecked(false);
-}
-
-/*****************************************************************************
- *
- * Class PreviewTable
- *
- *****************************************************************************/
-
-PreviewTable::PreviewTable(int numRows, int numCols, QWidget * parent, const char * name)
-:Q3Table(numRows, numCols, parent, name)
-{
-	setAttribute(Qt::WA_DeleteOnClose);
-	setSelectionMode(Q3Table::NoSelection);
-	setReadOnly(true);
-	setRowMovingEnabled(false);
-	setColumnMovingEnabled(false);
-	verticalHeader()->setResizeEnabled(false);
-
-	for (int i=0; i<numCols; i++){
-		comments << "";
-		col_label << QString::number(i+1);
-	}
-	setHeader();
-#ifdef Q_OS_MAC
-	setMinimumHeight(4*horizontalHeader()->height());
-#else
-	setMinimumHeight(2*horizontalHeader()->height());
-#endif
-}
-
-void PreviewTable::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)
-{
-	int rows;
-	QString name = MdiSubWindow::parseAsciiFile(fname, commentString, endLine, ignoredLines, maxRows, rows);
-	if (name.isEmpty())
-		return;
-	
-	QFile f(name);
-	if (f.open(QIODevice::ReadOnly)){
-        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-        QTextStream t(&f);
-		QString s = t.readLine();//read first line
-		if (simplifySpaces)
-			s = s.simplifyWhiteSpace();
-		else if (stripSpaces)
-			s = s.stripWhiteSpace();
-
-		QStringList line = s.split(sep);
-		int cols = line.size();
-
-		bool allNumbers = true;
-		for (int i=0; i<cols; i++)
-		{//verify if the strings in the line used to rename the columns are not all numbers
-			locale().toDouble(line[i], &allNumbers);
-			if (!allNumbers)
-				break;
-		}
-        if (renameCols && !allNumbers){
-            rows--;
-            if (importComments)
-                rows--;
-        }
-
-        int startRow = 0, startCol = 0;
-        int c = numCols();
-        int r = numRows();
-		switch(importMode){
-			case Table::Overwrite:
-                if (numRows() != rows)
-                    setNumRows(rows);
-
-                if (c != cols){
-                    if (c < cols)
-                        addColumns(cols - c);
-                    else
-                        setNumCols(cols);
-                }
-			break;
-			case Table::NewColumns:
-                startCol = c;
-                addColumns(cols);
-                if (r < rows)
-                    setNumRows(rows);
-			break;
-			case Table::NewRows:
-                startRow = r;
-                if (c < cols)
-                    addColumns(cols - c);
-                setNumRows(r + rows);
-			break;
-		}
-
-		if (renameCols && !allNumbers){//use first line to set the table header
-			for (int i = 0; i<cols; i++){
-			    int aux = i + startCol;
-                col_label[aux] = QString::null;
-			    if (!importComments)
-                    comments[aux] = line[i];
-				s = line[i].replace("-","_").remove(QRegExp("\\W")).replace("_","-");
-				int n = col_label.count(s);
-				if(n){//avoid identical col names
-					while (col_label.contains(s + QString::number(n)))
-						n++;
-					s += QString::number(n);
-				}
-				col_label[aux] = s;
-			}
-
-            if (importComments){//import comments
-                s = t.readLine();//read 2nd line
-                if (simplifySpaces)
-                    s = s.simplifyWhiteSpace();
-                else if (stripSpaces)
-                    s = s.stripWhiteSpace();
-                line = s.split(sep, QString::SkipEmptyParts);
-                for (int i=0; i<line.size(); i++)
-                    comments[startCol + i] = line[i];
-                qApp->processEvents(QEventLoop::ExcludeUserInput);
-            }
-        } else if (rows > 0){//put values in the first line of the table
-            for (int i = 0; i<cols; i++)
-				setText(startRow, startCol + i, line[i]);
-            startRow++;
-        }
-
-        blockSignals(true);
-		setHeader();
-
-        QApplication::restoreOverrideCursor();
-
-		int row = startRow;
-		rows = numRows();
-		while (!t.atEnd() && row < rows){
-		    s = t.readLine();
-			if (simplifySpaces)
-				s = s.simplifyWhiteSpace();
-			else if (stripSpaces)
-				s = s.stripWhiteSpace();
-			line = s.split(sep);
-			int lc = line.size();
-			if (lc > cols) {
-				addColumns(lc - cols);
-				cols = lc;
-			}
-			for (int j=0; j<cols && j<lc; j++)
-				setText(row, startCol + j, line[j]);
-
-            row++;
-            qApp->processEvents(QEventLoop::ExcludeUserInput);
-		}
-		blockSignals(false);
-		f.remove();
-	}
-}
-
-void PreviewTable::resetHeader()
-{
-	for (int i=0; i<numCols(); i++){
-	    comments[i] = QString::null;
-		col_label[i] = QString::number(i+1);
-	}
-}
-
-void PreviewTable::clear()
-{
-	for (int i=0; i<numCols(); i++){
-		for (int j=0; j<numRows(); j++)
-			setText(j, i, QString::null);
-	}
-}
-
-void PreviewTable::updateDecimalSeparators(const QLocale& oldSeparators)
-{
-	QLocale locale = ((QWidget *)parent())->locale();
-	for (int i=0; i<numCols(); i++){
-        for (int j=0; j<numRows(); j++){
-            if (!text(j, i).isEmpty()){
-				double val = oldSeparators.toDouble(text(j, i));
-                setText(j, i, locale.toString(val, 'g', d_numeric_precision));
-			}
-		}
-	}
-}
-
-void PreviewTable::setHeader()
-{
-	Q3Header *head = horizontalHeader();
-	for (int i=0; i<numCols(); i++){
-		QString s = col_label[i];
-		int lines = columnWidth(i)/head->fontMetrics().averageCharWidth();
-	#ifdef Q_OS_MAC
-		head->setLabel(i, s.remove("\n"));
-	#else
-		head->setLabel(i, s.remove("\n") + "\n" + QString(lines, '_') + "\n" + comments[i]);
-	#endif
-	}
-}
-
-void PreviewTable::addColumns(int c)
-{
-	int max=0, cols = numCols();
-	for (int i=0; i<cols; i++){
-		if (!col_label[i].contains(QRegExp ("\\D"))){
-			int index=col_label[i].toInt();
-			if (index>max)
-				max=index;
-		}
-	}
-	max++;
-	insertColumns(cols, c);
-	for (int i=0; i<c; i++){
-		comments << QString();
-		col_label<< QString::number(max+i);
-	}
-}
-
-/*****************************************************************************
- *
- * Class PreviewMatrix
- *
- *****************************************************************************/
-
-PreviewMatrix::PreviewMatrix(QWidget *parent, Matrix * m):QTableView(parent)
-{
-	d_matrix_model = new MatrixModel(32, 32, m);
-	if (!m){
-		ApplicationWindow *app = (ApplicationWindow *)parent;
-		if (app){
-			d_matrix_model->setLocale(app->locale());
-			d_matrix_model->setNumericFormat('f', app->d_decimal_digits);
-		}
-	}
-	setModel(d_matrix_model);
-
-	setAttribute(Qt::WA_DeleteOnClose);
-	setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
-    setSelectionMode(QAbstractItemView::NoSelection);
-    setEditTriggers(QAbstractItemView::NoEditTriggers);
-    setFocusPolicy(Qt::NoFocus);
-
-    QPalette pal = palette();
-	pal.setColor(QColorGroup::Base, QColor(255, 255, 128));
-	setPalette(pal);
-
-	// set header properties
-	horizontalHeader()->setMovable(false);
-	horizontalHeader()->setResizeMode(QHeaderView::Fixed);
-	for(int i=0; i<d_matrix_model->columnCount(); i++)
-		setColumnWidth(i, 100);
-
-	verticalHeader()->setMovable(false);
-	verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
-}
-
-void PreviewMatrix::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)
-{
-	d_matrix_model->importASCII(fname, sep, ignoredLines, stripSpaces,
-		simplifySpaces, commentString, importAs, locale, endLine, maxRows);
-}
-
-void PreviewMatrix::clear()
-{
-	d_matrix_model->clear();
-	reset();
+/***************************************************************************
+    File                 : ImportASCIIDialog.cpp
+    Project              : QtiPlot
+    --------------------------------------------------------------------
+    Copyright            : (C) 2006,2007 by Ion Vasilief, Knut Franke
+    Email (use @ for *)  : ion_vasilief*yahoo.fr, knut.franke*gmx.de
+    Description          : Import ASCII file(s) dialog
+
+ ***************************************************************************/
+
+
+/***************************************************************************
+ *                                                                         *
+ *  This program is free software; you can redistribute it and/or modify   *
+ *  it under the terms of the GNU General Public License as published by   *
+ *  the Free Software Foundation; either version 2 of the License, or      *
+ *  (at your option) any later version.                                    *
+ *                                                                         *
+ *  This program is distributed in the hope that it will be useful,        *
+ *  but WITHOUT 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, write to the Free Software           *
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
+ *   Boston, MA  02110-1301  USA                                           *
+ *                                                                         *
+ ***************************************************************************/
+
+#include "ImportASCIIDialog.h"
+#include "ApplicationWindow.h"
+#include "Table.h"
+#include "Matrix.h"
+#include "MatrixModel.h"
+
+#include <QLayout>
+#include <QGroupBox>
+#include <QPushButton>
+#include <QRegExp>
+#include <QMessageBox>
+#include <QTextStream>
+#include <QApplication>
+#include <QProgressDialog>
+#include <QStackedWidget>
+#include <QHeaderView>
+
+#include <gsl/gsl_math.h>
+#include<iostream>
+
+ImportASCIIDialog::ImportASCIIDialog(bool new_windows_only, QWidget * parent, bool extended, Qt::WFlags flags )
+: ExtensibleFileDialog(parent, extended, flags )
+{
+	setWindowTitle(tr("MantidPlot - Import ASCII File(s)"));
+
+	QStringList filters;
+	filters << tr("All files") + " (*)";
+	filters << tr("Text files") + " (*.TXT *.txt)";
+	filters << tr("Data files") + " (*.DAT *.dat)";
+	filters << tr("Comma Separated Values") + " (*.CSV *.csv)";
+	setFilters( filters );
+
+	setFileMode( QFileDialog::ExistingFiles );
+
+	d_current_path = QString::null;
+
+	initAdvancedOptions();
+	setNewWindowsOnly(new_windows_only);
+	setExtensionWidget(d_advanced_options);
+
+	// get rembered option values
+	ApplicationWindow *app = (ApplicationWindow *)parent;
+	setLocale(app->locale());
+
+	d_strip_spaces->setChecked(app->strip_spaces);
+	d_simplify_spaces->setChecked(app->simplify_spaces);
+	d_ignored_lines->setValue(app->ignoredLines);
+	d_rename_columns->setChecked(app->renameColumns);
+	setColumnSeparator(app->columnSeparator);
+    d_comment_string->setText(app->d_ASCII_comment_string);
+    d_import_comments->setChecked(app->d_ASCII_import_comments);
+    d_read_only->setChecked(app->d_ASCII_import_read_only);
+
+	if (app->d_ASCII_import_locale.name() == QLocale::c().name())
+        boxDecimalSeparator->setCurrentIndex(1);
+    else if (app->d_ASCII_import_locale.name() == QLocale(QLocale::German).name())
+        boxDecimalSeparator->setCurrentIndex(2);
+    else if (app->d_ASCII_import_locale.name() == QLocale(QLocale::French).name())
+        boxDecimalSeparator->setCurrentIndex(3);
+	boxDecimalSeparator->setEnabled(app->d_import_dec_separators);
+	d_import_dec_separators->setChecked(app->d_import_dec_separators);
+
+	connect(d_import_mode, SIGNAL(currentIndexChanged(int)), this, SLOT(updateImportMode(int)));
+
+	if (app->d_ASCII_import_mode < d_import_mode->count())
+		d_import_mode->setCurrentIndex(app->d_ASCII_import_mode);
+
+	d_preview_lines_box->setValue(app->d_preview_lines);
+	d_preview_button->setChecked(app->d_ASCII_import_preview);
+
+    boxEndLine->setCurrentIndex((int)app->d_ASCII_end_line);
+
+	if (!app->d_ASCII_import_preview)
+		d_preview_stack->hide();
+
+	initPreview(d_import_mode->currentIndex());
+
+    connect(d_preview_lines_box, SIGNAL(valueChanged(int)), this, SLOT(preview()));
+    connect(d_rename_columns, SIGNAL(clicked()), this, SLOT(preview()));
+    connect(d_import_comments, SIGNAL(clicked()), this, SLOT(preview()));
+    connect(d_strip_spaces, SIGNAL(clicked()), this, SLOT(preview()));
+    connect(d_simplify_spaces, SIGNAL(clicked()), this, SLOT(preview()));
+    connect(d_ignored_lines, SIGNAL(valueChanged(int)), this, SLOT(preview()));
+    connect(d_import_dec_separators, SIGNAL(clicked()), this, SLOT(preview()));
+    connect(d_column_separator, SIGNAL(currentIndexChanged(int)), this, SLOT(preview()));
+    connect(boxDecimalSeparator, SIGNAL(currentIndexChanged(int)), this, SLOT(preview()));
+    connect(d_comment_string, SIGNAL(textChanged(const QString&)), this, SLOT(preview()));
+    connect(this, SIGNAL(currentChanged(const QString&)), this, SLOT(changePreviewFile(const QString&)));
+}
+void ImportASCIIDialog::addColumnSeparators()
+{
+	if(!d_column_separator) return;
+	d_column_separator->addItem(tr("TAB"));
+	d_column_separator->addItem(tr("SPACE"));
+	d_column_separator->addItem(";" + tr("TAB"));
+	d_column_separator->addItem("," + tr("TAB"));
+	d_column_separator->addItem(";" + tr("SPACE"));
+	d_column_separator->addItem("," + tr("SPACE"));
+	d_column_separator->addItem(";");
+	d_column_separator->addItem(",");
+}
+void ImportASCIIDialog::addColumnSeparatorsforLoadAscii()
+{
+	if(!d_column_separator) return;
+	d_column_separator->addItem(tr("CSV"));
+	d_column_separator->addItem(tr("Tab"));
+	d_column_separator->addItem(tr("Space"));
+	d_column_separator->addItem(tr("SemiColon"));
+	d_column_separator->addItem(tr("Colon"));
+}
+QString ImportASCIIDialog::getselectedColumnSeparator()
+{return d_column_separator->currentText();
+}
+void ImportASCIIDialog::initAdvancedOptions()
+{
+	d_advanced_options = new QGroupBox();
+	QVBoxLayout *main_layout = new QVBoxLayout(d_advanced_options);
+	QGridLayout *advanced_layout = new QGridLayout();
+	main_layout->addLayout(advanced_layout);
+
+	advanced_layout->addWidget(new QLabel(tr("Import each file as: ")), 0, 0);
+	d_import_mode = new QComboBox();
+	// Important: Keep this in sync with the ImportMode enum.
+	d_import_mode->addItem(tr("New Table"));
+	d_import_mode->addItem(tr("New Matrice"));
+	d_import_mode->addItem(tr("New Workspace"));
+	d_import_mode->addItem(tr("New Columns"));
+	d_import_mode->addItem(tr("New Rows"));
+	d_import_mode->addItem(tr("Overwrite Current Window"));
+	
+	advanced_layout->addWidget(d_import_mode, 0, 1);
+
+	QLabel *label_column_separator = new QLabel(tr("Separator:"));
+	advanced_layout->addWidget(label_column_separator, 1, 0);
+	d_column_separator = new QComboBox();
+	addColumnSeparators();
+	d_column_separator->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed );
+	d_column_separator->setEditable( true );
+	advanced_layout->addWidget(d_column_separator, 1, 1);
+	// context-sensitive help
+	QString help_column_separator = 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_column_separator += "\n"+tr("The separator must not contain the following characters: \n0-9eE.+-");
+	d_column_separator->setWhatsThis(help_column_separator);
+	label_column_separator->setToolTip(help_column_separator);
+	d_column_separator->setToolTip(help_column_separator);
+	label_column_separator->setWhatsThis(help_column_separator);
+
+	QLabel *label_ignore_lines = new QLabel(tr( "Ignore first" ));
+	advanced_layout->addWidget(label_ignore_lines, 2, 0);
+	d_ignored_lines = new QSpinBox();
+	d_ignored_lines->setRange( 0, 10000 );
+	d_ignored_lines->setSuffix(" " + tr("lines"));
+	d_ignored_lines->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed );
+	advanced_layout->addWidget(d_ignored_lines, 2, 1);
+
+	advanced_layout->addWidget(new QLabel(tr("Ignore lines starting with")), 3, 0);
+	d_comment_string = new QLineEdit();
+    advanced_layout->addWidget(d_comment_string, 3, 1);
+
+	d_rename_columns = new QCheckBox(tr("Use first row to &name columns"));
+	advanced_layout->addWidget(d_rename_columns, 0, 2, 1, 2);
+
+    d_import_comments = new QCheckBox(tr("Use second row as &comments"));
+	advanced_layout->addWidget(d_import_comments, 1, 2, 1, 2);
+	connect(d_rename_columns, SIGNAL(toggled(bool)), d_import_comments, SLOT(setEnabled(bool)));
+
+	d_strip_spaces = new QCheckBox(tr("&Remove white spaces from line ends"));
+	advanced_layout->addWidget(d_strip_spaces, 2, 2, 1, 2);
+	// context-sensitive help
+	QString help_strip_spaces = tr("By checking this option all white spaces will be \nremoved from the beginning and the end of \nthe lines in the ASCII file.","when translating this check the what's this functions and tool tips to place the '\\n's correctly");
+	help_strip_spaces +="\n\n"+tr("Warning: checking this option leads to column \noverlaping if the columns in the ASCII file don't \nhave the same number of rows.");
+	help_strip_spaces +="\n"+tr("To avoid this problem you should precisely \ndefine the column separator using TAB and \nSPACE characters.","when translating this check the what's this functions and tool tips to place the '\\n's correctly");
+	d_strip_spaces->setWhatsThis(help_strip_spaces);
+	d_strip_spaces->setToolTip(help_strip_spaces);
+
+	d_simplify_spaces = new QCheckBox(tr("&Simplify white spaces" ));
+	advanced_layout->addWidget(d_simplify_spaces, 3, 2, 1, 2);
+	// context-sensitive help
+	QString help_simplify_spaces = tr("By checking this option all white spaces will be \nremoved from the beginning and the end of the \nlines and each sequence of internal \nwhitespaces (including the TAB character) will \nbe replaced with a single space.","when translating this check the what's this functions and tool tips to place the '\\n's correctly");
+	help_simplify_spaces +="\n\n"+tr("Warning: checking this option leads to column \noverlaping if the columns in the ASCII file don't \nhave the same number of rows.","when translating this check the what's this functions and tool tips to place the '\\n's correctly");
+	help_simplify_spaces +="\n"+tr("To avoid this problem you should precisely \ndefine the column separator using TAB and \nSPACE characters.","when translating this check the what's this functions and tool tips to place the '\\n's correctly");
+	d_simplify_spaces->setWhatsThis(help_simplify_spaces);
+	d_simplify_spaces->setToolTip(help_simplify_spaces);
+
+	advanced_layout->addWidget(new QLabel(tr("Decimal Separators")), 4, 0);
+	boxDecimalSeparator = new QComboBox();
+	boxDecimalSeparator->addItem(tr("System Locale Setting"));
+	boxDecimalSeparator->addItem("1,000.0");
+	boxDecimalSeparator->addItem("1.000,0");
+	boxDecimalSeparator->addItem("1 000,0");
+	advanced_layout->addWidget(boxDecimalSeparator, 4, 1);
+
+	d_import_dec_separators = new QCheckBox(tr("Import &decimal separators"));
+	connect(d_import_dec_separators, SIGNAL(toggled(bool)), boxDecimalSeparator, SLOT(setEnabled(bool)));
+	advanced_layout->addWidget(d_import_dec_separators, 4, 2, 1, 2);
+
+	advanced_layout->addWidget(new QLabel(tr("Endline character")), 5, 0);
+	boxEndLine = new QComboBox();
+	boxEndLine->addItem(tr("LF (Unix)"));
+	boxEndLine->addItem(tr("CRLF (Windows)"));
+	boxEndLine->addItem(tr("CR (Mac)"));
+    connect(boxEndLine, SIGNAL(activated(int)), this, SLOT(preview()));
+	advanced_layout->addWidget(boxEndLine, 5, 1);
+
+    d_read_only = new QCheckBox(tr("Import as &read-only"));
+	advanced_layout->addWidget(d_read_only, 5, 2);
+
+	d_preview_button = new QCheckBox(tr("&Preview Lines"));
+	connect(d_preview_button, SIGNAL(clicked()), this, SLOT(preview()));
+	advanced_layout->addWidget(d_preview_button, 6, 0);
+
+	d_preview_lines_box = new QSpinBox();
+	d_preview_lines_box->setMaximum (INT_MAX);
+	d_preview_lines_box->setValue(100);
+	d_preview_lines_box->setSingleStep(10);
+	d_preview_lines_box->setSpecialValueText(tr("All"));
+	advanced_layout->addWidget(d_preview_lines_box, 6, 1);
+
+	d_help_button = new QPushButton(tr("&Help"));
+	connect(d_help_button, SIGNAL(clicked()), this, SLOT(displayHelp()));
+	advanced_layout->addWidget(d_help_button, 6, 2);
+
+	d_preview_table = NULL;
+	d_preview_matrix = NULL;
+	d_preview_stack = new QStackedWidget();
+	main_layout->addWidget(d_preview_stack);
+}
+
+void ImportASCIIDialog::initPreview(int previewMode)
+{
+	if (previewMode < NewTables || previewMode > Overwrite)
+		return;
+
+	ApplicationWindow *app = (ApplicationWindow *)parent();
+	if (!app)
+		return;
+
+	if (d_preview_table){
+		delete d_preview_table;
+		d_preview_table = NULL;
+	}
+
+	if (d_preview_matrix){
+		delete d_preview_matrix;
+		d_preview_matrix = NULL;
+	}
+
+	switch(previewMode){
+		case NewTables:
+			d_preview_table = new PreviewTable(30, 2, this);
+			d_preview_table->setNumericPrecision(app->d_decimal_digits);
+			d_preview_stack->addWidget(d_preview_table);
+			enableTableOptions(true);
+		break;
+
+		case NewMatrices:
+			d_preview_matrix = new PreviewMatrix(app);
+			d_preview_stack->addWidget(d_preview_matrix);
+			enableTableOptions(false);
+		break;
+
+		case NewColumns:
+		case NewRows:
+		case Overwrite:
+			MdiSubWindow *w = app->activeWindow();
+			if (!w)
+				return;
+
+			if (w->inherits("Table")){
+				d_preview_table = new PreviewTable(30, 2, this);
+				d_preview_table->setNumericPrecision(app->d_decimal_digits);
+				d_preview_stack->addWidget(d_preview_table);
+				enableTableOptions(true);
+			} else if (w->isA("Matrix")){
+				d_preview_matrix = new PreviewMatrix(app, (Matrix *)w);
+				d_preview_stack->addWidget(d_preview_matrix);
+				enableTableOptions(false);
+			}
+			break;
+	}
+	preview();
+}
+
+void ImportASCIIDialog::enableTableOptions(bool on)
+{
+	d_rename_columns->setEnabled(on);
+	d_import_comments->setEnabled(on && d_rename_columns->isChecked());
+	d_read_only->setEnabled(on);
+}
+
+void ImportASCIIDialog::setColumnSeparator(const QString& sep)
+{
+	if (sep=="\t")
+		d_column_separator->setCurrentIndex(0);
+	else if (sep==" ")
+		d_column_separator->setCurrentIndex(1);
+	else if (sep==";\t")
+		d_column_separator->setCurrentIndex(2);
+	else if (sep==",\t")
+		d_column_separator->setCurrentIndex(3);
+	else if (sep=="; ")
+		d_column_separator->setCurrentIndex(4);
+	else if (sep==", ")
+		d_column_separator->setCurrentIndex(5);
+	else if (sep==";")
+		d_column_separator->setCurrentIndex(6);
+	else if (sep==",")
+		d_column_separator->setCurrentIndex(7);
+	else {
+		QString separator = sep;
+		d_column_separator->setEditText(separator.replace(" ","\\s").replace("\t","\\t"));
+	}
+}
+
+const QString ImportASCIIDialog::columnSeparator() const
+{
+	QString sep = d_column_separator->currentText();
+
+	if (d_simplify_spaces->isChecked())
+		sep.replace(tr("TAB"), " ", Qt::CaseInsensitive);
+	else
+		sep.replace(tr("TAB"), "\t", Qt::CaseInsensitive);
+
+	sep.replace(tr("SPACE"), " ", Qt::CaseInsensitive);
+	sep.replace("\\s", " ");
+	sep.replace("\\t", "\t");
+
+	/* TODO
+	if (sep.contains(QRegExp("[0-9.eE+-]")))
+		QMessageBox::warning(this, tr("QtiPlot - Import options error"),
+				tr("The separator must not contain the following characters: 0-9eE.+-"));
+	*/
+
+	return sep;
+}
+
+void ImportASCIIDialog::displayHelp()
+{
+	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.+-") + "\n\n";
+	s += tr( "Remove white spaces from line ends" )+ ":\n";
+	s += tr("By checking this option all white spaces will be removed from the beginning and the end of the lines in the ASCII file.") + "\n\n";
+	s += tr( "Simplify white spaces" )+ ":\n";
+	s += tr("By checking this option each sequence of internal whitespaces (including the TAB character) will be replaced with a single space.");
+	s += tr("By checking this option all white spaces will be removed from the beginning and the end of the lines and each sequence of internal whitespaces (including the TAB character) will be replaced with a single space.");
+
+	s +="\n\n"+tr("Warning: using these two last options leads to column overlaping if the columns in the ASCII file don't have the same number of rows.");
+	s +="\n"+tr("To avoid this problem you should precisely define the column separator using TAB and SPACE characters.");
+
+	QMessageBox::about(this, tr("MantidPlot - Help"), s);
+}
+
+void ImportASCIIDialog::updateImportMode(int mode)
+{
+	if (mode == Overwrite)
+		setFileMode( QFileDialog::ExistingFile );
+	else
+		setFileMode( QFileDialog::ExistingFiles );
+	if(mode==NewWorkspace)
+	{
+		d_column_separator->clear();
+		addColumnSeparatorsforLoadAscii();
+	}
+	else
+	{	d_column_separator->clear();
+		addColumnSeparators();
+	}
+
+	initPreview(mode);
+}
+
+void ImportASCIIDialog::closeEvent(QCloseEvent* e)
+{
+	ApplicationWindow *app = (ApplicationWindow *)this->parent();
+	if (app){
+		app->d_extended_import_ASCII_dialog = this->isExtended();
+		app->d_ASCII_file_filter = this->selectedFilter();
+		app->d_ASCII_import_preview = d_preview_button->isChecked();
+		app->d_preview_lines = d_preview_lines_box->value();
+	}
+
+	e->accept();
+}
+
+QLocale ImportASCIIDialog::decimalSeparators()
+{
+	QLocale locale;
+    switch (boxDecimalSeparator->currentIndex()){
+        case 0:
+            locale = QLocale::system();
+        break;
+        case 1:
+            locale = QLocale::c();
+        break;
+        case 2:
+            locale = QLocale(QLocale::German);
+        break;
+        case 3:
+            locale = QLocale(QLocale::French);
+        break;
+    }
+	return locale;
+}
+
+void ImportASCIIDialog::preview()
+{
+    if (!d_preview_button->isChecked()){
+		d_preview_stack->hide();
+        return;
+    } else
+		d_preview_stack->show();
+
+	if (d_preview_table)
+		previewTable();
+	else if (d_preview_matrix)
+		previewMatrix();
+}
+
+void ImportASCIIDialog::previewTable()
+{
+	if (!d_preview_table)
+		return;
+
+	if (!d_preview_table->isVisible())
+		d_preview_table->show();
+
+	if (d_current_path.trimmed().isEmpty()){
+		d_preview_table->clear();
+		d_preview_table->resetHeader();
+        return;
+    }
+
+	int importMode = d_import_mode->currentIndex();
+	if (importMode == NewTables)
+		importMode = Table::Overwrite;
+	else
+		importMode -= 2;
+
+	d_preview_table->resetHeader();
+	d_preview_table->importASCII(d_current_path, columnSeparator(), d_ignored_lines->value(),
+							d_rename_columns->isChecked(), d_strip_spaces->isChecked(),
+							d_simplify_spaces->isChecked(), d_import_comments->isChecked(),
+                            d_comment_string->text(), (Table::ImportMode)importMode, 
+                            boxEndLine->currentIndex(), d_preview_lines_box->value());
+
+	if (d_import_dec_separators->isChecked())
+		d_preview_table->updateDecimalSeparators(decimalSeparators());
+    if (!d_preview_table->isVisible())
+        d_preview_table->show();
+}
+
+void ImportASCIIDialog::previewMatrix()
+{
+	if (!d_preview_matrix)
+		return;
+
+	if (d_current_path.trimmed().isEmpty()){
+		d_preview_matrix->clear();
+        return;
+    }
+
+	int importMode = d_import_mode->currentIndex();
+	if (importMode == NewMatrices)
+		importMode = Matrix::Overwrite;
+	else
+		importMode -= 2;
+
+	QLocale locale = d_preview_matrix->locale();
+	if(d_import_dec_separators->isChecked())
+		locale = decimalSeparators();
+
+	d_preview_matrix->importASCII(d_current_path, columnSeparator(), d_ignored_lines->value(),
+							d_strip_spaces->isChecked(), d_simplify_spaces->isChecked(),
+                            d_comment_string->text(), importMode, locale,
+                            boxEndLine->currentIndex(), d_preview_lines_box->value());
+	d_preview_matrix->resizeColumnsToContents();
+}
+
+void ImportASCIIDialog::changePreviewFile(const QString& path)
+{
+	if (path.isEmpty())
+		return;
+
+	QFileInfo fi(path);
+	if (!fi.exists() || fi.isDir() || !fi.isFile())
+		return;
+
+	if (!fi.isReadable()){
+		QMessageBox::critical(this, tr("MantidPlot - File openning error"),
+		tr("You don't have the permission to open this file: <b>%1</b>").arg(path));
+		return;
+	}
+
+  if (fi.suffix().toLower() == "csv")
+  {
+    int index = d_column_separator->findText("CSV",Qt::MatchExactly);
+    if (index < 0) index = d_column_separator->findText(",",Qt::MatchExactly);
+    if (index >= 0)
+    {
+      d_column_separator->setCurrentIndex(index);
+    }
+  }
+
+	d_current_path = path;
+	preview();
+}
+
+void ImportASCIIDialog::setNewWindowsOnly(bool on)
+{
+    if (on){
+        d_import_mode->clear();
+        d_import_mode->addItem(tr("New Table"));
+        d_import_mode->addItem(tr("New Matrice"));
+		d_import_mode->addItem(tr("New Workspace"));
+    }
+
+    d_preview_button->setChecked(false);
+}
+
+/*****************************************************************************
+ *
+ * Class PreviewTable
+ *
+ *****************************************************************************/
+
+PreviewTable::PreviewTable(int numRows, int numCols, QWidget * parent, const char * name)
+:Q3Table(numRows, numCols, parent, name)
+{
+	setAttribute(Qt::WA_DeleteOnClose);
+	setSelectionMode(Q3Table::NoSelection);
+	setReadOnly(true);
+	setRowMovingEnabled(false);
+	setColumnMovingEnabled(false);
+	verticalHeader()->setResizeEnabled(false);
+
+	for (int i=0; i<numCols; i++){
+		comments << "";
+		col_label << QString::number(i+1);
+	}
+	setHeader();
+#ifdef Q_OS_MAC
+	setMinimumHeight(4*horizontalHeader()->height());
+#else
+	setMinimumHeight(2*horizontalHeader()->height());
+#endif
+}
+
+void PreviewTable::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)
+{
+	int rows;
+	QString name = MdiSubWindow::parseAsciiFile(fname, commentString, endLine, ignoredLines, maxRows, rows);
+	if (name.isEmpty())
+		return;
+	
+	QFile f(name);
+	if (f.open(QIODevice::ReadOnly)){
+        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+        QTextStream t(&f);
+		QString s = t.readLine();//read first line
+		if (simplifySpaces)
+			s = s.simplifyWhiteSpace();
+		else if (stripSpaces)
+			s = s.stripWhiteSpace();
+
+		QStringList line = s.split(sep);
+		int cols = line.size();
+
+		bool allNumbers = true;
+		for (int i=0; i<cols; i++)
+		{//verify if the strings in the line used to rename the columns are not all numbers
+			locale().toDouble(line[i], &allNumbers);
+			if (!allNumbers)
+				break;
+		}
+        if (renameCols && !allNumbers){
+            rows--;
+            if (importComments)
+                rows--;
+        }
+
+        int startRow = 0, startCol = 0;
+        int c = numCols();
+        int r = numRows();
+		switch(importMode){
+			case Table::Overwrite:
+                if (numRows() != rows)
+                    setNumRows(rows);
+
+                if (c != cols){
+                    if (c < cols)
+                        addColumns(cols - c);
+                    else
+                        setNumCols(cols);
+                }
+			break;
+			case Table::NewColumns:
+                startCol = c;
+                addColumns(cols);
+                if (r < rows)
+                    setNumRows(rows);
+			break;
+			case Table::NewRows:
+                startRow = r;
+                if (c < cols)
+                    addColumns(cols - c);
+                setNumRows(r + rows);
+			break;
+		}
+
+		if (renameCols && !allNumbers){//use first line to set the table header
+			for (int i = 0; i<cols; i++){
+			    int aux = i + startCol;
+                col_label[aux] = QString::null;
+			    if (!importComments)
+                    comments[aux] = line[i];
+				s = line[i].replace("-","_").remove(QRegExp("\\W")).replace("_","-");
+				int n = col_label.count(s);
+				if(n){//avoid identical col names
+					while (col_label.contains(s + QString::number(n)))
+						n++;
+					s += QString::number(n);
+				}
+				col_label[aux] = s;
+			}
+
+            if (importComments){//import comments
+                s = t.readLine();//read 2nd line
+                if (simplifySpaces)
+                    s = s.simplifyWhiteSpace();
+                else if (stripSpaces)
+                    s = s.stripWhiteSpace();
+                line = s.split(sep, QString::SkipEmptyParts);
+                for (int i=0; i<line.size(); i++)
+                    comments[startCol + i] = line[i];
+                qApp->processEvents(QEventLoop::ExcludeUserInput);
+            }
+        } else if (rows > 0){//put values in the first line of the table
+            for (int i = 0; i<cols; i++)
+				setText(startRow, startCol + i, line[i]);
+            startRow++;
+        }
+
+        blockSignals(true);
+		setHeader();
+
+        QApplication::restoreOverrideCursor();
+
+		int row = startRow;
+		rows = numRows();
+		while (!t.atEnd() && row < rows){
+		    s = t.readLine();
+			if (simplifySpaces)
+				s = s.simplifyWhiteSpace();
+			else if (stripSpaces)
+				s = s.stripWhiteSpace();
+			line = s.split(sep);
+			int lc = line.size();
+			if (lc > cols) {
+				addColumns(lc - cols);
+				cols = lc;
+			}
+			for (int j=0; j<cols && j<lc; j++)
+				setText(row, startCol + j, line[j]);
+
+            row++;
+            qApp->processEvents(QEventLoop::ExcludeUserInput);
+		}
+		blockSignals(false);
+		f.remove();
+	}
+}
+
+void PreviewTable::resetHeader()
+{
+	for (int i=0; i<numCols(); i++){
+	    comments[i] = QString::null;
+		col_label[i] = QString::number(i+1);
+	}
+}
+
+void PreviewTable::clear()
+{
+	for (int i=0; i<numCols(); i++){
+		for (int j=0; j<numRows(); j++)
+			setText(j, i, QString::null);
+	}
+}
+
+void PreviewTable::updateDecimalSeparators(const QLocale& oldSeparators)
+{
+	QLocale locale = ((QWidget *)parent())->locale();
+	for (int i=0; i<numCols(); i++){
+        for (int j=0; j<numRows(); j++){
+            if (!text(j, i).isEmpty()){
+				double val = oldSeparators.toDouble(text(j, i));
+                setText(j, i, locale.toString(val, 'g', d_numeric_precision));
+			}
+		}
+	}
+}
+
+void PreviewTable::setHeader()
+{
+	Q3Header *head = horizontalHeader();
+	for (int i=0; i<numCols(); i++){
+		QString s = col_label[i];
+		int lines = columnWidth(i)/head->fontMetrics().averageCharWidth();
+	#ifdef Q_OS_MAC
+		head->setLabel(i, s.remove("\n"));
+	#else
+		head->setLabel(i, s.remove("\n") + "\n" + QString(lines, '_') + "\n" + comments[i]);
+	#endif
+	}
+}
+
+void PreviewTable::addColumns(int c)
+{
+	int max=0, cols = numCols();
+	for (int i=0; i<cols; i++){
+		if (!col_label[i].contains(QRegExp ("\\D"))){
+			int index=col_label[i].toInt();
+			if (index>max)
+				max=index;
+		}
+	}
+	max++;
+	insertColumns(cols, c);
+	for (int i=0; i<c; i++){
+		comments << QString();
+		col_label<< QString::number(max+i);
+	}
+}
+
+/*****************************************************************************
+ *
+ * Class PreviewMatrix
+ *
+ *****************************************************************************/
+
+PreviewMatrix::PreviewMatrix(QWidget *parent, Matrix * m):QTableView(parent)
+{
+	d_matrix_model = new MatrixModel(32, 32, m);
+	if (!m){
+		ApplicationWindow *app = (ApplicationWindow *)parent;
+		if (app){
+			d_matrix_model->setLocale(app->locale());
+			d_matrix_model->setNumericFormat('f', app->d_decimal_digits);
+		}
+	}
+	setModel(d_matrix_model);
+
+	setAttribute(Qt::WA_DeleteOnClose);
+	setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
+    setSelectionMode(QAbstractItemView::NoSelection);
+    setEditTriggers(QAbstractItemView::NoEditTriggers);
+    setFocusPolicy(Qt::NoFocus);
+
+    QPalette pal = palette();
+	pal.setColor(QColorGroup::Base, QColor(255, 255, 128));
+	setPalette(pal);
+
+	// set header properties
+	horizontalHeader()->setMovable(false);
+	horizontalHeader()->setResizeMode(QHeaderView::Fixed);
+	for(int i=0; i<d_matrix_model->columnCount(); i++)
+		setColumnWidth(i, 100);
+
+	verticalHeader()->setMovable(false);
+	verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
+}
+
+void PreviewMatrix::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)
+{
+	d_matrix_model->importASCII(fname, sep, ignoredLines, stripSpaces,
+		simplifySpaces, commentString, importAs, locale, endLine, maxRows);
+}
+
+void PreviewMatrix::clear()
+{
+	d_matrix_model->clear();
+	reset();
 }
diff --git a/Code/Mantid/MantidPlot/src/ImportASCIIDialog.h b/Code/Mantid/MantidPlot/src/ImportASCIIDialog.h
index 7b8773f681acab5d8f77839589b89afbbfb46ff4..376d944471b6feb94a7c9b380195322d00042201 100644
--- a/Code/Mantid/MantidPlot/src/ImportASCIIDialog.h
+++ b/Code/Mantid/MantidPlot/src/ImportASCIIDialog.h
@@ -33,8 +33,8 @@
 
 #include <QComboBox>
 #include <QCheckBox>
-#include <QSpinBox>
-#include <QLineEdit>
+#include <QSpinBox>
+#include <QLineEdit>
 #include <QTableView>
 
 class QGroupBox;
@@ -93,7 +93,7 @@ public:
 	 * 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)
+		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
@@ -135,13 +135,13 @@ public:
 	//! 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
+	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 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();};
@@ -165,7 +165,7 @@ private:
 
 	void closeEvent(QCloseEvent*);
 	//! Initialise #d_advanced_options and everything it contains.
-	void initAdvancedOptions();
+	void initAdvancedOptions();
 	void setNewWindowsOnly(bool on);
 	void addColumnSeparators();
 	void addColumnSeparatorsforLoadAscii();
@@ -178,7 +178,7 @@ private:
 	// 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;
+	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;
diff --git a/Code/Mantid/MantidPlot/src/IntDialog.cpp b/Code/Mantid/MantidPlot/src/IntDialog.cpp
index 9cdb894583dbfef1b198466cb481a1e62cfb4d8b..f02ea469f148f833e9d2ef3cd8b4aa3961f2cf4f 100644
--- a/Code/Mantid/MantidPlot/src/IntDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/IntDialog.cpp
@@ -28,7 +28,7 @@
  ***************************************************************************/
 #include "IntDialog.h"
 #include "ApplicationWindow.h"
-#include "Graph.h"
+#include "Graph.h"
 #include "Integration.h"
 #include "DoubleSpinBox.h"
 
@@ -53,14 +53,14 @@ IntDialog::IntDialog(QWidget* parent, Graph *g, Qt::WFlags fl )
     QGroupBox *gb1 = new QGroupBox();
     QGridLayout *gl1 = new QGridLayout(gb1);
 	gl1->addWidget(new QLabel(tr("Function")), 0, 0);
-	boxName = new QTextEdit();
+	boxName = new QTextEdit();
 	boxName->setMaximumHeight(60);
 	gl1->addWidget(boxName, 0, 1);
-
-    gl1->addWidget(new QLabel(tr("Variable")), 1, 0);
-	boxVariable = new QLineEdit();
-	boxVariable->setText("x");
-	gl1->addWidget(boxVariable, 1, 1);
+
+    gl1->addWidget(new QLabel(tr("Variable")), 1, 0);
+	boxVariable = new QLineEdit();
+	boxVariable->setText("x");
+	gl1->addWidget(boxVariable, 1, 1);
 
 	gl1->addWidget(new QLabel(tr("Order (1 - 5, 1 = Trapezoidal Rule)")), 2, 0);
 	boxOrder = new QSpinBox();
@@ -77,7 +77,7 @@ IntDialog::IntDialog(QWidget* parent, Graph *g, Qt::WFlags fl )
 	gl1->addWidget(new QLabel(tr("Tolerance")), 4, 0);
 	boxTol = new DoubleSpinBox();
 	boxTol->setLocale(locale);
-	boxTol->setValue(0.01);
+	boxTol->setValue(0.01);
 	boxTol->setMinimum(0.0);
 	boxTol->setSingleStep(0.001);
 	gl1->addWidget(boxTol, 4, 1);
@@ -89,12 +89,12 @@ IntDialog::IntDialog(QWidget* parent, Graph *g, Qt::WFlags fl )
 
 	gl1->addWidget(new QLabel(tr("Upper limit")), 6, 0);
 	boxEnd = new DoubleSpinBox();
-	boxEnd->setLocale(locale);
+	boxEnd->setLocale(locale);
 	boxEnd->setValue(1.0);
-	gl1->addWidget(boxEnd, 6, 1);
-
+	gl1->addWidget(boxEnd, 6, 1);
+
     boxPlot = new QCheckBox(tr("&Plot area"));
-	boxPlot->setChecked(true);
+	boxPlot->setChecked(true);
     gl1->addWidget(boxPlot, 7, 1);
     gl1->setRowStretch(8, 1);
 
@@ -116,15 +116,15 @@ IntDialog::IntDialog(QWidget* parent, Graph *g, Qt::WFlags fl )
 }
 
 void IntDialog::accept()
-{
+{
     QString formula = boxName->text().remove("\n");
-	Integration *i = new Integration(formula, boxVariable->text(),
+	Integration *i = new Integration(formula, boxVariable->text(),
                     (ApplicationWindow *)this->parent(), d_graph, boxStart->value(), boxEnd->value());
 	i->setTolerance(boxTol->text().toDouble());
 	i->setMaximumIterations(boxSteps->value());
-	i->setMethodOrder(boxOrder->value());
-	if (d_graph && boxPlot->isChecked())
-	    i->enableGraphicsDisplay(true, d_graph);
-    i->run();
+	i->setMethodOrder(boxOrder->value());
+	if (d_graph && boxPlot->isChecked())
+	    i->enableGraphicsDisplay(true, d_graph);
+    i->run();
     delete i;
 }
diff --git a/Code/Mantid/MantidPlot/src/IntDialog.h b/Code/Mantid/MantidPlot/src/IntDialog.h
index 42392e2de22adf848a2bcd7534b41b1083ec4b45..4716893348902aa5661cb14beaec0116694a7be6 100644
--- a/Code/Mantid/MantidPlot/src/IntDialog.h
+++ b/Code/Mantid/MantidPlot/src/IntDialog.h
@@ -56,7 +56,7 @@ private:
     QPushButton* buttonOk;
 	QPushButton* buttonCancel;
     QCheckBox* boxPlot;
-	QTextEdit* boxName;
+	QTextEdit* boxName;
 	QLineEdit* boxVariable;
 	QSpinBox* boxOrder;
 	QSpinBox* boxSteps;
diff --git a/Code/Mantid/MantidPlot/src/Integration.cpp b/Code/Mantid/MantidPlot/src/Integration.cpp
index dc688e0241126ef776f2c2ba31aa4199bcacb4c1..161026847d59dc1d9951e8982c3d52252ba3d8c2 100644
--- a/Code/Mantid/MantidPlot/src/Integration.cpp
+++ b/Code/Mantid/MantidPlot/src/Integration.cpp
@@ -30,7 +30,7 @@
 #include "nrutil.h"
 #include "MultiLayer.h"
 #include "MyParser.h"
-#include "FunctionCurve.h"
+#include "FunctionCurve.h"
 
 #include <QMessageBox>
 #include <QDateTime>
@@ -40,7 +40,7 @@
 
 Integration::Integration(const QString& formula, const QString& var, ApplicationWindow *parent, Graph *g, double start, double end)
 : Filter(parent, g),
-d_formula(formula),
+d_formula(formula),
 d_variable(var)
 {
 	d_init_err = false;
@@ -113,14 +113,14 @@ double Integration::trapez()
 		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.ascii(), &x);
-	parser.SetExpr(d_formula.ascii());
+{
+    MyParser parser;
+	double x = d_from;
+	parser.DefineVar(d_variable.ascii(), &x);
+	parser.SetExpr(d_formula.ascii());
 
     static double s;
     if (n == 1){
@@ -140,35 +140,35 @@ double Integration::trapezf(int n)
         for(int j=1; j <= it; j++, x += del)
             sum += parser.Eval();
 
-        s = 0.5*(s + (d_to - d_from)*sum/tnm);
+        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;
+
+// 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;
-}
+        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()
 {
@@ -224,20 +224,20 @@ void Integration::setMethodOrder(int n)
         return;
     }
     d_method = n;
-}
-
-void Integration::output()
-{
-    if(d_integrand != AnalyticalFunction || d_init_err)
-        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();
-    }
+}
+
+void Integration::output()
+{
+    if(d_integrand != AnalyticalFunction || d_init_err)
+        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();
+    }
 }
diff --git a/Code/Mantid/MantidPlot/src/Integration.h b/Code/Mantid/MantidPlot/src/Integration.h
index 0010f9ea19488ec6e9f65c75df6745fa733a6aef..c7a9140384da2a7182ee57a26cb552bb6bf9cb24 100644
--- a/Code/Mantid/MantidPlot/src/Integration.h
+++ b/Code/Mantid/MantidPlot/src/Integration.h
@@ -42,12 +42,12 @@ public:
 	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,
+	Integration(const QString& formula, const QString& var, ApplicationWindow *parent,
                 Graph *g, double start, double end);
 
     int method(){return d_method;};
-    void setMethodOrder(int n);
-
+    void setMethodOrder(int n);
+
     double area(){return d_area;};
 
 private:
@@ -56,22 +56,22 @@ private:
 
     void output();
 
-	double trapez();
-	double trapezf(int n);
-    //! Returns the number of iterations used to calculate the area if d_integrand = AnalyticalFunction.
+	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 value of the integral
+    int d_method;
+
+    //! 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_formula;
+	//! Variable name for the function to be integrated
 	QString d_variable;
 };
 
diff --git a/Code/Mantid/MantidPlot/src/Interpolation.cpp b/Code/Mantid/MantidPlot/src/Interpolation.cpp
index f88f93480851570ce79c81e7aa5336075116a4e1..0cd57678aaf3327f9151a99b464d8d88a095a8f9 100644
--- a/Code/Mantid/MantidPlot/src/Interpolation.cpp
+++ b/Code/Mantid/MantidPlot/src/Interpolation.cpp
@@ -101,21 +101,21 @@ if (d_n < min_points){
     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_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;
 	}
 }
 
diff --git a/Code/Mantid/MantidPlot/src/LayerDialog.cpp b/Code/Mantid/MantidPlot/src/LayerDialog.cpp
index 1e42a0afb1e8fb4e4ba14d2e8fab2a299b6a1dc2..cd1c45f3fa7495b1002ec04e7caaf535d0a8eb68 100644
--- a/Code/Mantid/MantidPlot/src/LayerDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/LayerDialog.cpp
@@ -217,7 +217,7 @@ void LayerDialog::setMultiLayer(MultiLayer *g)
 	alignVertBox->setCurrentItem(g->verticalAlignement());
 
 	boxLayerSrc->setRange(1, g->layers());
-	boxLayerDest->setRange(1, g->layers());
+	boxLayerDest->setRange(1, g->layers());
 	boxLayerDest->setValue(g->layers());
 }
 
diff --git a/Code/Mantid/MantidPlot/src/LegendWidget.h b/Code/Mantid/MantidPlot/src/LegendWidget.h
index 7c2c35b1b23a837e125d39e5f5b1527324902884..3cc243aa939035280044e93239c3045e3303e9f0 100644
--- a/Code/Mantid/MantidPlot/src/LegendWidget.h
+++ b/Code/Mantid/MantidPlot/src/LegendWidget.h
@@ -71,24 +71,24 @@ public:
 	void setFont(const QFont& font);
 
 	int angle(){return d_angle;};
-	void setAngle(int ang){d_angle = ang;};
+	void setAngle(int ang){d_angle = ang;};
 
 	double xValue();
 	double yValue();
-
+
 	void setSelected(bool on = true);
 
 	void showTextEditor();
 	void showTextDialog(){emit showDialog();};
 	void showContextMenu(){emit showMenu();};
-
+
     void print(QPainter *p, const QwtScaleMap map[QwtPlot::axisCnt]);
 	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 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<long>, int);
 
@@ -96,7 +96,7 @@ private:
 	int symbolsMaxWidth();
 	QString parse(const QString& str);
 
-	virtual void paintEvent(QPaintEvent *e);
+	virtual void paintEvent(QPaintEvent *e);
     void mousePressEvent(QMouseEvent *);
 	void contextMenuEvent(QContextMenuEvent * ){emit showMenu();};
 
@@ -120,7 +120,7 @@ private:
 
 	//! Length of the symbol line
 	int line_length;
-
+
 	SelectionMoveResizer *d_selector;
 	
 	double d_x, d_y;
diff --git a/Code/Mantid/MantidPlot/src/LogisticFit.cpp b/Code/Mantid/MantidPlot/src/LogisticFit.cpp
index fb2f89390192deae447ccd9a08610fdac4e2d5ec..f5c1834ff32d543199ee5e3d224799e888c93b55 100644
--- a/Code/Mantid/MantidPlot/src/LogisticFit.cpp
+++ b/Code/Mantid/MantidPlot/src/LogisticFit.cpp
@@ -68,8 +68,8 @@ void LogisticFit::init()
 	d_explanation = tr("Logistic Fit");
 	d_formula = "A2+(A1-A2)/(1+(x/x0)^p))";
 	d_p = 4;    
-	initWorkspace(d_p);
-}
+	initWorkspace(d_p);
+}
 
 void LogisticFit::calculateFitCurveData(double *X, double *Y)
 {
@@ -80,17 +80,17 @@ void LogisticFit::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);
+		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;
+        	Y[i] = (a1 - a2)/(1 + pow(x/x0, p)) + a2;
 		} 
-	} else {
+	} 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;
+        	Y[i] = (a1 - a2)/(1 + pow(x/x0, p)) + a2;
 		}
 	}
 }
diff --git a/Code/Mantid/MantidPlot/src/LogisticFit.h b/Code/Mantid/MantidPlot/src/LogisticFit.h
index 3edc2db58fd0f01f3b5e11677ecb2a14ad65d7d0..9f820d9d9bab2fc1719e249a5ebbb684845e1049 100644
--- a/Code/Mantid/MantidPlot/src/LogisticFit.h
+++ b/Code/Mantid/MantidPlot/src/LogisticFit.h
@@ -41,12 +41,12 @@ class LogisticFit : public Fit
 		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();
-        double eval(double *par, double x){return (par[0]-par[1])/(1+pow(x/par[2], par[3]))+par[1];};
+		void guessInitialValues();
+        double eval(double *par, double x){return (par[0]-par[1])/(1+pow(x/par[2], par[3]))+par[1];};
 
 	private:
 		void init();
-		void calculateFitCurveData(double *X, double *Y);
+		void calculateFitCurveData(double *X, double *Y);
 };
 
 #endif
diff --git a/Code/Mantid/MantidPlot/src/Mantid/AbstractMantidLog.cpp b/Code/Mantid/MantidPlot/src/Mantid/AbstractMantidLog.cpp
index 8669cbfe26f8fcd6423c239badda39f3203c4702..73faad65970fff6552c1e134061d219d840d91eb 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/AbstractMantidLog.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/AbstractMantidLog.cpp
@@ -1,12 +1,12 @@
-#include "AbstractMantidLog.h"
-
-#include "MantidKernel/SignalChannel.h"
-#include "Poco/LoggingRegistry.h"
-#include "boost/bind.hpp"
-
-#include <QMessageBox>
-
-void AbstractMantidLog::connect()
+#include "AbstractMantidLog.h"
+
+#include "MantidKernel/SignalChannel.h"
+#include "Poco/LoggingRegistry.h"
+#include "boost/bind.hpp"
+
+#include <QMessageBox>
+
+void AbstractMantidLog::connect()
 {
     try
     {
@@ -23,10 +23,10 @@ void AbstractMantidLog::connect()
         QMessageBox::warning(0,"MantidLog","Channel signalChannel not found");
         return;
     }
-}
-
-void AbstractMantidLog::log(const Poco::Message& msg)
-{
-  (void) msg;
-}
-
+}
+
+void AbstractMantidLog::log(const Poco::Message& msg)
+{
+  (void) msg;
+}
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/AbstractMantidLog.h b/Code/Mantid/MantidPlot/src/Mantid/AbstractMantidLog.h
index a6e198e1b0c46d30faefdb63218f4a7398f10a39..44a0e69ffdaa91cf0de8511906eabd987d0b5adc 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/AbstractMantidLog.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/AbstractMantidLog.h
@@ -7,14 +7,14 @@
 #endif
 
 #include <QObject>
-#include "Poco/Message.h"
-
-/** 
-
-   class AbstractMantidLog connects to Mantid's SignalChannel
-   Method log() receives the message from SignalChannel
-
-*/
+#include "Poco/Message.h"
+
+/** 
+
+   class AbstractMantidLog connects to Mantid's SignalChannel
+   Method log() receives the message from SignalChannel
+
+*/
 class AbstractMantidLog : public QObject
 {
 public:
diff --git a/Code/Mantid/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp b/Code/Mantid/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp
index 8003b44f29fadc31f8dcb5b6d157cec4c5baf42a..a7fa171458d9f2c880563b7556c71d39a8a9c6b2 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp
@@ -1,674 +1,674 @@
-#include "AlgorithmHistoryWindow.h"
-#include "MantidKernel/DateAndTime.h"
-
-using namespace Mantid::Kernel;
-using namespace Mantid::API;
-
-// Get a reference to the logger
-Mantid::Kernel::Logger& AlgorithmHistoryWindow::g_log = Mantid::Kernel::Logger::get("AlgorithmHistoryWindow");
-Mantid::Kernel::Logger& AlgHistoryTreeWidget::g_log = Mantid::Kernel::Logger::get("AlgHistoryTreeWidget");
-
-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->setReadOnly(1);
-  m_execDurationlabel=new QLabel("&Duration:",this,0);
-  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)
-    m_execDateTimeEdit->setReadOnly(1);
-  m_Datelabel=new QLabel("&Date:",this,0);
-  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);
-    setLayout(formLayout);
-  }
-  setGeometry (5,210,205,130);
-
-}
-AlgExecSummaryGrpBox::~AlgExecSummaryGrpBox()
-{
-  if(m_execDurationlabel){
-    delete m_execDurationlabel;
-    m_execDurationlabel=NULL;
-  }
-  if(m_execDurationEdit){
-    delete m_execDurationEdit;
-    m_execDurationEdit=NULL;
-  }
-  if(m_Datelabel){
-    delete m_Datelabel;
-    m_Datelabel=NULL;
-  }
-  if(m_Datelabel){
-    delete m_Datelabel;
-    m_Datelabel=NULL;
-  }
-  if(m_execDateTimeEdit){
-    delete m_execDateTimeEdit;
-    m_execDateTimeEdit=NULL;
-  }
-}
-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 );
-	
-  QString str("");
-  str=datetime.toString("dd/MM/yyyy hh:mm:ss");
-	
-  QLineEdit* datetimeEdit=getAlgExecDateCtrl();
-  if(datetimeEdit)datetimeEdit->setText(str);
-
-}
-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("&OSName:",this,0);
-  if(m_osNameLabel)m_osNameLabel->setBuddy(m_osNameEdit);
-
-  //OS Version Label & Edit Box
-  m_osVersionEdit=new QLineEdit("",this);
-  if(m_osVersionEdit)
-  {
-    m_osVersionEdit->setReadOnly(1);
-    m_osVersionLabel=new QLabel("&OSVersion:",this,0);
-  }
-  if(m_osVersionLabel)
-    m_osVersionLabel->setBuddy(m_osVersionEdit);
-
-  //Mantid FRamework Version Label & Edit Box
-  m_frmwkVersnEdit=new QLineEdit("",this);
-  if(m_frmwkVersnEdit)
-    m_frmwkVersnEdit->setReadOnly(1);
-  m_frmworkVersionLabel=new QLabel("&FrameWorkVersion:",this,0);
-  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);
-    setLayout(formLayout);
-  }
-  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;}
-}
-AlgHistScriptButton::AlgHistScriptButton(QString title,QWidget* w):QPushButton(title,w)
-{
-  setGeometry (400,350,160,30);
-  //connect(this,SIGNAL(clicked()),w,SLOT(saveScriptToFile()));
-  QMenu* scriptMenu=new QMenu(this);
-  if(scriptMenu)
-  {QAction* fileAction= new QAction(" To File",this);
-    connect(fileAction,SIGNAL(triggered()),w,SLOT(writeToScriptFile()));
-    QAction* clipboardAction= new QAction(" To Clipboard",this);
-    connect(clipboardAction,SIGNAL(triggered()),w,SLOT(copytoClipboard()));
-    scriptMenu->addAction(fileAction);
-    scriptMenu->addAction(clipboardAction);
-    this->setMenu(scriptMenu);
-  }
-}
-
-AlgHistScriptButton::~AlgHistScriptButton()
-{
-}
-
-AlgorithmHistoryWindow::AlgorithmHistoryWindow(ApplicationWindow *w,const std::vector<AlgorithmHistory> &algHist,const EnvironmentHistory& envHist):
-  MantidDialog(w),m_algHist(algHist),m_histPropWindow(NULL),m_execSumGrpBox(NULL),m_envHistGrpBox(NULL),m_algName(""),m_nVersion(0)
-{
-  setWindowTitle(tr("Algorithm History"));
-  setMinimumHeight(400);
-  setMinimumWidth(570);
-  setGeometry(50,150,540,380); 
-
-
-  //Create a tree widget to display the algorithm names in the workspacehistory
-  m_Historytree = new AlgHistoryTreeWidget(this);
-  if(m_Historytree)
-  {
-    m_Historytree->setHeaderLabel("Algorithms");
-    m_Historytree->setGeometry (5,5,205,200);   
-  }
-  //Populate the History Tree widget
-  populateAlgHistoryTreeWidget();
-
-  //create a tree widget to dispaly history properties
-  if(!m_histPropWindow)
-    m_histPropWindow=createAlgHistoryPropWindow();
-  connect(m_Historytree,SIGNAL(updateAlgorithmHistoryWindow(QString, int,int)),this,SLOT(updateAll(QString,int,int)));
-
-  // The tree and the history details layout
-  QHBoxLayout *treeLayout = new QHBoxLayout;
-  treeLayout->addWidget(m_Historytree,1); // History stretches 1
-  treeLayout->addWidget(m_histPropWindow->m_histpropTree,2); // 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(envHist);
-
-  QHBoxLayout *environmentLayout = new QHBoxLayout;
-  environmentLayout->addWidget(m_execSumGrpBox, 1);
-  environmentLayout->addWidget(m_envHistGrpBox, 2);
-
-  // The button at the bottom
-  m_scriptButton = CreateScriptButton();
-  if(m_scriptButton==NULL) QMessageBox::critical(this,"Mantid","Generate script Button Creation failed");
-  QHBoxLayout *buttonLayout = new QHBoxLayout;
-  buttonLayout->addStretch(1); // Align the button to the right
-  buttonLayout->addWidget(m_scriptButton);
-
-  //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;}
-  if(m_scriptButton){delete m_scriptButton;m_scriptButton=NULL;}
-}
-
-QPushButton * AlgorithmHistoryWindow::CreateScriptButton()
-{	return  (new AlgHistScriptButton("Generate Script",this));//QPushButton("Script",this);
-}
-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
-    for (std::vector <AlgorithmHistory>::const_iterator algIter= m_algHist.begin( );
-	 algIter != m_algHist.end( ); algIter++ )
-    {
-      double duration=0;
-      duration=(*algIter).executionDuration();
-      Mantid::Kernel::DateAndTime date=(*algIter).executionDate();
-      pgrpBox->setData(duration,date);
-    }
-    return pgrpBox;
-  }
-  else{
-    QMessageBox::critical(this,"Mantid","Invalid Pointer");
-    return 0;
-  }
-	
-}
-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");
-    return 0;
-  }
-	
-}
-AlgHistoryProperties* AlgorithmHistoryWindow::createAlgHistoryPropWindow()
-{	
-  std::vector<PropertyHistory> histProp;
-  std::vector <AlgorithmHistory>::reverse_iterator rIter=m_algHist.rbegin();
-  histProp=(*rIter).getProperties();
-
-  //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){
-    phistPropWindow->displayAlgHistoryProperties();
-    return phistPropWindow;
-  }
-  else{QMessageBox::critical(this,"Mantid","Invalid Pointer");
-    return 0;
-  }
-}
-void AlgorithmHistoryWindow::handleException( const std::exception& e )
-{
-  QMessageBox::critical(0,"Mantid-Error",QString::fromStdString(e.what()));
-}
-void AlgorithmHistoryWindow::generateScript(QString &script)
-{	
-  std::string algParam("");
-  std::string tempScript("");
-  std::vector<Property*> algPropUnmngd;
-  std::vector<Property*>::const_iterator itUmnngd;
-  std::vector<PropertyHistory>algHistProp;
-  IAlgorithm_sptr  ialg_Sptr;
-	
-  typedef std::map<unsigned int,std::string> orderedHistMap;
-  orderedHistMap ordMap;
-	
-  //getting the properties from the algorithmhistory
-  for (std::vector <AlgorithmHistory>::const_iterator algHistIter=m_algHist.begin( );
-       algHistIter!=m_algHist.end();algHistIter++)
-  {
-    algHistProp=(*algHistIter).getProperties();
-    std::string name=(*algHistIter).name();
-    int nVersion=(*algHistIter).version();
-    int nexecCount=(*algHistIter).execCount();
-    //creating an unmanaged instance of the selected algorithm
-    //this is bcoz algorith history is giving dynamically generated workspaces for some 
-    //algorithms like LoadRaw.But python script for LoadRaw has only one output workspace parameter
-    //To eliminate the dynamically generated parameters unmanged instances created and compared with it.
-						
-    ialg_Sptr= AlgorithmManager::Instance().createUnmanaged(name,nVersion);
-    if(ialg_Sptr)
-    {	
-      ialg_Sptr->initialize();
-      algPropUnmngd= ialg_Sptr->getProperties();
-      itUmnngd=algPropUnmngd.begin();
-    }
-    //iterating through the properties
-    for (std::vector<PropertyHistory>::const_iterator propIter = algHistProp.begin();
-	 propIter != algHistProp.end(); ++propIter )
-    { 
-      std::string name= (*propIter).name();
-      std::string value=(*propIter).value();
-      bool bdefault=(*propIter).isDefault();
-      //if it's not a default property  add it to 
-      //algorithm parameters to form the script
-      if(!bdefault)
-      {
-	//if the property name obtained by unmanaged instance of the algorithm
-	//is same as the algorithm history property add it to algParam string
-	//to generate script
-	if (name==(*itUmnngd)->name())
-	{
-	  std::string sanitisedname=sanitizePropertyName(name);
-	  algParam+=sanitisedname;
-	  algParam+="=\"";
-	  algParam+=value;
-	  algParam+="\",";
-	}
-      }
-
-      itUmnngd++;
-      if(itUmnngd==algPropUnmngd.end())
-	break;
-    } //end of properties loop
-
-    //erasing the last "," from the parameter list
-    //as concatenation is done in loop last "," is erasing 
-    int nIndex=algParam.find_last_of(",");
-    if(static_cast<int>(std::string::npos) != nIndex)
-      algParam=algParam.erase(nIndex);
-    //script string
-    tempScript=tempScript+name+"(";
-    tempScript=tempScript+algParam+")";
-    tempScript+="\n";
-    //string str=tempScript.toStdString();
-    // writing to map for ordering by execution count
-    ordMap.insert(orderedHistMap::value_type(nexecCount,tempScript));
-    tempScript.clear();
-    algParam.clear();
-				
-  }//end of algorithm history for loop
-
-  std::map<unsigned int,std::string>::iterator m3_pIter;
-  for (m3_pIter=ordMap.begin( );m3_pIter!=ordMap.end( );m3_pIter++)
-  {
-    QString qtemp=QString::fromStdString(m3_pIter->second);
-    script+=qtemp;
-  }
-}
-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
-  {
-    scriptDir = prevDir;
-  }
-  QString filePath = QFileDialog::getSaveFileName(this,tr("Save Script As "),scriptDir,tr("Script files (*.py)"));
-  // An empty string indicates they clicked cancel
-  if( filePath.isEmpty() ) return;
-  
-  QFile scriptfile(filePath);
-  if (!scriptfile.open(QIODevice::WriteOnly | QIODevice::Text))
-  {
-    QMessageBox::information(this, "Algorithm History", "Unable to write to file. Check you have write permission on this location.");
-    return;
-  }
-
-  QString script("");
-  generateScript(script);
-  QTextStream out(&scriptfile);
-  out<<"######################################################################\n";
-  out<<"#Python Script Generated by Algorithm History Display \n";
-  out<<"######################################################################\n";
-  out<<script<<"\n";
-  scriptfile.close();
-  //save the file path
-  MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(QFileInfo(filePath).absoluteDir().path());
-}
-std::string AlgorithmHistoryWindow::sanitizePropertyName(const std::string & name)
-{
-  std::string arg;
-  std::string::const_iterator sIter = name.begin();
-  std::string::const_iterator sEnd = name.end();
-  for( ; sIter != sEnd; ++sIter )
-  {
-    int letter = (int)(*sIter);
-    if( (letter >= 48 && letter <= 57) || (letter >= 97 && letter <= 122) ||
-	(letter >= 65 && letter <= 90) )
-    {
-      arg.push_back(*sIter);
-    }
-  }
-  return arg;
-}
-void AlgorithmHistoryWindow::setAlgorithmName(const QString& algName)
-{
-  m_algName=algName;
-}
-const QString &AlgorithmHistoryWindow::getAlgorithmName() const
-{	return m_algName;
-}
-void AlgorithmHistoryWindow::setAlgorithmVersion(const int& version) 
-{
-  m_nVersion=version;
-}
-const int& AlgorithmHistoryWindow::getAlgorithmVersion()const
-{
-  return m_nVersion;
-}
-void AlgorithmHistoryWindow::populateAlgHistoryTreeWidget()
-{	
-  std::vector<AlgorithmHistory>::reverse_iterator ralgHistory_Iter=m_algHist.rbegin( );
-  std::string algrithmName;
-  algrithmName=(*ralgHistory_Iter).name();
-  QString algName=algrithmName.c_str();
-  int nAlgVersion=(*ralgHistory_Iter).version();
-  concatVersionwithName(algName,nAlgVersion);
-	
-  QTreeWidgetItem * item= new	QTreeWidgetItem(QStringList(algName),QTreeWidgetItem::Type);
-  if(m_Historytree)m_Historytree->addTopLevelItem(item);
-  ralgHistory_Iter++;
-  for ( ; ralgHistory_Iter != m_algHist.rend( ) ; ralgHistory_Iter++ )
-  {
-    algrithmName=(*ralgHistory_Iter).name();
-    nAlgVersion=(*ralgHistory_Iter).version();
-    algName=algrithmName.c_str();
-    concatVersionwithName(algName,nAlgVersion);
-    QTreeWidgetItem * subitem= new	QTreeWidgetItem(QStringList(algName));
-    if(item)item->addChild(subitem);
-  }
-		
-}
-void AlgorithmHistoryWindow::concatVersionwithName( QString& algName,const int version)
-{
-  algName= algName+" v.";
-  QString algVersion=QString::number(version,10);
-  algName+=algVersion;
-}
-
-void AlgEnvHistoryGrpBox::fillEnvHistoryGroupBox(const EnvironmentHistory& envHistory)
-{
-  std::string osname=envHistory.osName();
-  std::string osversion=envHistory.osVersion();
-  std::string userName=envHistory.userName();
-  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());
-
-  QLineEdit* frmwkVersnEdit=getfrmworkVersionEdit();
-  if(frmwkVersnEdit)frmwkVersnEdit->setText(frwkversn.c_str());
-
-}
-void AlgorithmHistoryWindow::updateAll(QString algName,int version,int index)
-{	
-  int nSize=m_algHist.size();
-  //indicates the position of the ALgorithmHistory Object in the history vector
-  int pos=0;
-  //index =-1 for the parent item(root item)
-  if (index==-1)
-  {	//parent in the algorithHistoryTree widget comes here
-    pos=nSize-1;
-    g_log.debug()<< "selected algorithm is at position "<<pos<<"  in the History vector "<<std::endl;
-  }
-  else
-  {	pos=nSize-2-index;
-    g_log.debug ()<< "selected algorithm is at position  "<<pos <<"  in the History vector "<<std::endl;
-  }
-  updateAlgHistoryProperties(algName,version,pos);
-  updateExecSummaryGrpBox(algName,version,pos);
-  setAlgorithmName(algName);
-  setAlgorithmVersion(version);
-	
-}
-void AlgorithmHistoryWindow::updateAlgHistoryProperties(QString algName,int version,int pos)
-{
-  std::vector<PropertyHistory> histProp;
-  //getting the selcted algorithm at pos from History vector
-  const AlgorithmHistory & algHist=m_algHist.at(pos);
-  std::string name=algHist.name();
-  int nVer=algHist.version();
-  //if name and version in the history is same as selected item
-  //get the properties and display it.
-  if((algName==name.c_str())&& (nVer==version))
-  {
-    histProp=algHist.getProperties();
-    if(m_histPropWindow)
-    {  m_histPropWindow->setAlgProperties(histProp);
-      m_histPropWindow->clearData();
-      m_histPropWindow->displayAlgHistoryProperties();
-    }
-  }
-}
-void AlgorithmHistoryWindow::updateExecSummaryGrpBox(const QString& algName,const int & version,int pos)
-{
-  //getting the selcted algorithm at pos from History vector
-  const AlgorithmHistory & algHist=m_algHist.at(pos);
-  std::string name=algHist.name();
-  int nVer=algHist.version();
-  //if name and version in the history is same as selected item
-  //get the properties and display it.
-  if((algName==name.c_str())&& (nVer==version))
-  {
-    double duration=algHist.executionDuration();
-    Mantid::Kernel::DateAndTime date=algHist.executionDate();
-    if(m_execSumGrpBox)m_execSumGrpBox->setData(duration,date);
-  }
-}
-void AlgorithmHistoryWindow::copytoClipboard()
-{	
-  QString comments ("######################################################################\n"
-		    "#Python Script Generated by Algorithm History Display \n"
-		    "######################################################################\n");
-  QString script("");
-  generateScript(script);
-  QClipboard *clipboard = QApplication::clipboard();
-  if(clipboard)
-  {	QString clipboardData=comments+script;
-    clipboard->setText(clipboardData);
-  }
-}
-
-AlgHistoryProperties::AlgHistoryProperties(QWidget*w,const std::vector<PropertyHistory>& propHist):
-  m_Histprop(propHist)
-{
-  QStringList hList;
-  hList<<"Name"<<"Value"<<"Default?:"<<"Direction"<<"";
-  m_histpropTree = new  QTreeWidget(w);
-  if(m_histpropTree)
-  {	m_histpropTree->setColumnCount(5);
-    m_histpropTree->setSelectionMode(QAbstractItemView::NoSelection);
-    m_histpropTree->setHeaderLabels(hList);
-    //m_histpropTree->setGeometry (213,5,385,200);
-    m_histpropTree->setGeometry (213,5,350,200);
-  }
-}
-void AlgHistoryProperties::clearData()
-{
-  if(m_histpropTree)
-  {   m_histpropTree->clear();
-    int ntopcount=m_histpropTree->topLevelItemCount() ;
-    while(ntopcount--)
-    {m_histpropTree->topLevelItem(ntopcount);
-    }
-  }
-}
-void AlgHistoryProperties::setAlgProperties( const std::vector<PropertyHistory>& histProp)
-{
-  m_Histprop.assign(histProp.begin(),histProp.end());
-}
-const std::vector<PropertyHistory>& AlgHistoryProperties:: getAlgProperties()
-{
-  return m_Histprop;
-}
-void AlgHistoryProperties::displayAlgHistoryProperties()
-{
-  QStringList propList;
-  std::string sProperty;
-  bool bisDefault;
-  int nDirection=0;
-  for ( std::vector<Mantid::Kernel::PropertyHistory>::const_iterator pIter = m_Histprop.begin();
-	pIter != m_Histprop.end(); ++pIter )
-  {
-    sProperty=(*pIter).name();
-    propList.append(sProperty.c_str());
-    sProperty=(*pIter).value();
-    propList.append(sProperty.c_str());
-		
-    bisDefault=(*pIter).isDefault();
-    bisDefault? (sProperty="Yes"):(sProperty="No");
-		
-    propList.append(sProperty.c_str());
-    nDirection=(*pIter).direction();
-    switch(nDirection)
-    {
-    case 0:{sProperty="Input";break;}
-    case 1:{sProperty="Output";break;}
-    case 2:{sProperty="InOut";break;}
-    default:sProperty="N/A";
-    }
-    propList.append(sProperty.c_str());
-    QTreeWidgetItem * item= new	QTreeWidgetItem(propList);
-    if(m_histpropTree)m_histpropTree->addTopLevelItem(item);
-    propList.clear();
-
-  }// end of properties for loop
-    
-}
-void AlgHistoryTreeWidget::treeSelectionChanged()
-{	
-  QString algName("");int nVersion=-1;int nIndex=-1;
-  getSelectedAlgorithmName(algName,nVersion,nIndex);
-  emit updateAlgorithmHistoryWindow(algName,nVersion,nIndex);
-}
-void AlgHistoryTreeWidget::setAlgorithmName(const QString& algName)
-{
-  m_algName=algName;
-}
-const QString AlgHistoryTreeWidget::getAlgorithmName()
-{	return m_algName;
-}
-void AlgHistoryTreeWidget::setAlgorithmVersion(const int& version)
-{
-  m_nVersion=version;
-}
-const int& AlgHistoryTreeWidget::getAlgorithmVersion()
-{
-  return m_nVersion;
-}
-void AlgHistoryTreeWidget::getSelectedAlgorithmName(QString& algName,int & version,int & index)
-{	
-  QList<QTreeWidgetItem*> items = selectedItems();
-  if( !items.empty() )
-  {QTreeWidgetItem *item = items[0];
-    if(item)
-    {	//finding the index of the selected item
-      QModelIndex modelIndex=indexFromItem(item);
-      int row=modelIndex.row();
-      if(row!=0)
-      {g_log.debug()<< "It's child Item"<<std::endl;
-	index=row;
-      }
-      else if (row==0)
-      {
-	//row can be zero for 1st child item and parent item
-	QTreeWidgetItem * parent=NULL;
-	parent=item->parent();
-	if(parent)
-	{//if it's child item at row zero set index =0
-	  g_log.debug()<< "It's child Item"<<std::endl;
-	  index=0;
-	}
-	else
-	{	//if it's parent item set index = -1
-	  g_log.debug()<< "It's parent  item "<<std::endl;
-	  index=-1;
-	}
-      }
-      QString  str=item->text(0);
-      int nDotIndex=str.indexOf(".",0,Qt::CaseSensitive );
-      algName=str.left(nDotIndex-2);
-      version=str.right(str.length()-nDotIndex-1).toInt();
-      g_log.debug()<< "selected alg name =  "<< algName.toStdString()<<" index number =  "<<index<<std::endl;
-    }
-  }
-}
-void AlgHistoryTreeWidget::mouseDoubleClickEvent(QMouseEvent *e)
-{		
-  QString algName("");int nVersion=-1;int nIndex=-1;
-  getSelectedAlgorithmName(algName,nVersion,nIndex);
-  emit updateAlgorithmHistoryWindow(algName,nVersion,nIndex);
-  QTreeWidget::mouseDoubleClickEvent(e);
-}
+#include "AlgorithmHistoryWindow.h"
+#include "MantidKernel/DateAndTime.h"
+
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
+
+// Get a reference to the logger
+Mantid::Kernel::Logger& AlgorithmHistoryWindow::g_log = Mantid::Kernel::Logger::get("AlgorithmHistoryWindow");
+Mantid::Kernel::Logger& AlgHistoryTreeWidget::g_log = Mantid::Kernel::Logger::get("AlgHistoryTreeWidget");
+
+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->setReadOnly(1);
+  m_execDurationlabel=new QLabel("&Duration:",this,0);
+  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)
+    m_execDateTimeEdit->setReadOnly(1);
+  m_Datelabel=new QLabel("&Date:",this,0);
+  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);
+    setLayout(formLayout);
+  }
+  setGeometry (5,210,205,130);
+
+}
+AlgExecSummaryGrpBox::~AlgExecSummaryGrpBox()
+{
+  if(m_execDurationlabel){
+    delete m_execDurationlabel;
+    m_execDurationlabel=NULL;
+  }
+  if(m_execDurationEdit){
+    delete m_execDurationEdit;
+    m_execDurationEdit=NULL;
+  }
+  if(m_Datelabel){
+    delete m_Datelabel;
+    m_Datelabel=NULL;
+  }
+  if(m_Datelabel){
+    delete m_Datelabel;
+    m_Datelabel=NULL;
+  }
+  if(m_execDateTimeEdit){
+    delete m_execDateTimeEdit;
+    m_execDateTimeEdit=NULL;
+  }
+}
+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 );
+	
+  QString str("");
+  str=datetime.toString("dd/MM/yyyy hh:mm:ss");
+	
+  QLineEdit* datetimeEdit=getAlgExecDateCtrl();
+  if(datetimeEdit)datetimeEdit->setText(str);
+
+}
+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("&OSName:",this,0);
+  if(m_osNameLabel)m_osNameLabel->setBuddy(m_osNameEdit);
+
+  //OS Version Label & Edit Box
+  m_osVersionEdit=new QLineEdit("",this);
+  if(m_osVersionEdit)
+  {
+    m_osVersionEdit->setReadOnly(1);
+    m_osVersionLabel=new QLabel("&OSVersion:",this,0);
+  }
+  if(m_osVersionLabel)
+    m_osVersionLabel->setBuddy(m_osVersionEdit);
+
+  //Mantid FRamework Version Label & Edit Box
+  m_frmwkVersnEdit=new QLineEdit("",this);
+  if(m_frmwkVersnEdit)
+    m_frmwkVersnEdit->setReadOnly(1);
+  m_frmworkVersionLabel=new QLabel("&FrameWorkVersion:",this,0);
+  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);
+    setLayout(formLayout);
+  }
+  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;}
+}
+AlgHistScriptButton::AlgHistScriptButton(QString title,QWidget* w):QPushButton(title,w)
+{
+  setGeometry (400,350,160,30);
+  //connect(this,SIGNAL(clicked()),w,SLOT(saveScriptToFile()));
+  QMenu* scriptMenu=new QMenu(this);
+  if(scriptMenu)
+  {QAction* fileAction= new QAction(" To File",this);
+    connect(fileAction,SIGNAL(triggered()),w,SLOT(writeToScriptFile()));
+    QAction* clipboardAction= new QAction(" To Clipboard",this);
+    connect(clipboardAction,SIGNAL(triggered()),w,SLOT(copytoClipboard()));
+    scriptMenu->addAction(fileAction);
+    scriptMenu->addAction(clipboardAction);
+    this->setMenu(scriptMenu);
+  }
+}
+
+AlgHistScriptButton::~AlgHistScriptButton()
+{
+}
+
+AlgorithmHistoryWindow::AlgorithmHistoryWindow(ApplicationWindow *w,const std::vector<AlgorithmHistory> &algHist,const EnvironmentHistory& envHist):
+  MantidDialog(w),m_algHist(algHist),m_histPropWindow(NULL),m_execSumGrpBox(NULL),m_envHistGrpBox(NULL),m_algName(""),m_nVersion(0)
+{
+  setWindowTitle(tr("Algorithm History"));
+  setMinimumHeight(400);
+  setMinimumWidth(570);
+  setGeometry(50,150,540,380); 
+
+
+  //Create a tree widget to display the algorithm names in the workspacehistory
+  m_Historytree = new AlgHistoryTreeWidget(this);
+  if(m_Historytree)
+  {
+    m_Historytree->setHeaderLabel("Algorithms");
+    m_Historytree->setGeometry (5,5,205,200);   
+  }
+  //Populate the History Tree widget
+  populateAlgHistoryTreeWidget();
+
+  //create a tree widget to dispaly history properties
+  if(!m_histPropWindow)
+    m_histPropWindow=createAlgHistoryPropWindow();
+  connect(m_Historytree,SIGNAL(updateAlgorithmHistoryWindow(QString, int,int)),this,SLOT(updateAll(QString,int,int)));
+
+  // The tree and the history details layout
+  QHBoxLayout *treeLayout = new QHBoxLayout;
+  treeLayout->addWidget(m_Historytree,1); // History stretches 1
+  treeLayout->addWidget(m_histPropWindow->m_histpropTree,2); // 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(envHist);
+
+  QHBoxLayout *environmentLayout = new QHBoxLayout;
+  environmentLayout->addWidget(m_execSumGrpBox, 1);
+  environmentLayout->addWidget(m_envHistGrpBox, 2);
+
+  // The button at the bottom
+  m_scriptButton = CreateScriptButton();
+  if(m_scriptButton==NULL) QMessageBox::critical(this,"Mantid","Generate script Button Creation failed");
+  QHBoxLayout *buttonLayout = new QHBoxLayout;
+  buttonLayout->addStretch(1); // Align the button to the right
+  buttonLayout->addWidget(m_scriptButton);
+
+  //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;}
+  if(m_scriptButton){delete m_scriptButton;m_scriptButton=NULL;}
+}
+
+QPushButton * AlgorithmHistoryWindow::CreateScriptButton()
+{	return  (new AlgHistScriptButton("Generate Script",this));//QPushButton("Script",this);
+}
+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
+    for (std::vector <AlgorithmHistory>::const_iterator algIter= m_algHist.begin( );
+	 algIter != m_algHist.end( ); algIter++ )
+    {
+      double duration=0;
+      duration=(*algIter).executionDuration();
+      Mantid::Kernel::DateAndTime date=(*algIter).executionDate();
+      pgrpBox->setData(duration,date);
+    }
+    return pgrpBox;
+  }
+  else{
+    QMessageBox::critical(this,"Mantid","Invalid Pointer");
+    return 0;
+  }
+	
+}
+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");
+    return 0;
+  }
+	
+}
+AlgHistoryProperties* AlgorithmHistoryWindow::createAlgHistoryPropWindow()
+{	
+  std::vector<PropertyHistory> histProp;
+  std::vector <AlgorithmHistory>::reverse_iterator rIter=m_algHist.rbegin();
+  histProp=(*rIter).getProperties();
+
+  //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){
+    phistPropWindow->displayAlgHistoryProperties();
+    return phistPropWindow;
+  }
+  else{QMessageBox::critical(this,"Mantid","Invalid Pointer");
+    return 0;
+  }
+}
+void AlgorithmHistoryWindow::handleException( const std::exception& e )
+{
+  QMessageBox::critical(0,"Mantid-Error",QString::fromStdString(e.what()));
+}
+void AlgorithmHistoryWindow::generateScript(QString &script)
+{	
+  std::string algParam("");
+  std::string tempScript("");
+  std::vector<Property*> algPropUnmngd;
+  std::vector<Property*>::const_iterator itUmnngd;
+  std::vector<PropertyHistory>algHistProp;
+  IAlgorithm_sptr  ialg_Sptr;
+	
+  typedef std::map<unsigned int,std::string> orderedHistMap;
+  orderedHistMap ordMap;
+	
+  //getting the properties from the algorithmhistory
+  for (std::vector <AlgorithmHistory>::const_iterator algHistIter=m_algHist.begin( );
+       algHistIter!=m_algHist.end();algHistIter++)
+  {
+    algHistProp=(*algHistIter).getProperties();
+    std::string name=(*algHistIter).name();
+    int nVersion=(*algHistIter).version();
+    int nexecCount=(*algHistIter).execCount();
+    //creating an unmanaged instance of the selected algorithm
+    //this is bcoz algorith history is giving dynamically generated workspaces for some 
+    //algorithms like LoadRaw.But python script for LoadRaw has only one output workspace parameter
+    //To eliminate the dynamically generated parameters unmanged instances created and compared with it.
+						
+    ialg_Sptr= AlgorithmManager::Instance().createUnmanaged(name,nVersion);
+    if(ialg_Sptr)
+    {	
+      ialg_Sptr->initialize();
+      algPropUnmngd= ialg_Sptr->getProperties();
+      itUmnngd=algPropUnmngd.begin();
+    }
+    //iterating through the properties
+    for (std::vector<PropertyHistory>::const_iterator propIter = algHistProp.begin();
+	 propIter != algHistProp.end(); ++propIter )
+    { 
+      std::string name= (*propIter).name();
+      std::string value=(*propIter).value();
+      bool bdefault=(*propIter).isDefault();
+      //if it's not a default property  add it to 
+      //algorithm parameters to form the script
+      if(!bdefault)
+      {
+	//if the property name obtained by unmanaged instance of the algorithm
+	//is same as the algorithm history property add it to algParam string
+	//to generate script
+	if (name==(*itUmnngd)->name())
+	{
+	  std::string sanitisedname=sanitizePropertyName(name);
+	  algParam+=sanitisedname;
+	  algParam+="=\"";
+	  algParam+=value;
+	  algParam+="\",";
+	}
+      }
+
+      itUmnngd++;
+      if(itUmnngd==algPropUnmngd.end())
+	break;
+    } //end of properties loop
+
+    //erasing the last "," from the parameter list
+    //as concatenation is done in loop last "," is erasing 
+    int nIndex=algParam.find_last_of(",");
+    if(static_cast<int>(std::string::npos) != nIndex)
+      algParam=algParam.erase(nIndex);
+    //script string
+    tempScript=tempScript+name+"(";
+    tempScript=tempScript+algParam+")";
+    tempScript+="\n";
+    //string str=tempScript.toStdString();
+    // writing to map for ordering by execution count
+    ordMap.insert(orderedHistMap::value_type(nexecCount,tempScript));
+    tempScript.clear();
+    algParam.clear();
+				
+  }//end of algorithm history for loop
+
+  std::map<unsigned int,std::string>::iterator m3_pIter;
+  for (m3_pIter=ordMap.begin( );m3_pIter!=ordMap.end( );m3_pIter++)
+  {
+    QString qtemp=QString::fromStdString(m3_pIter->second);
+    script+=qtemp;
+  }
+}
+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
+  {
+    scriptDir = prevDir;
+  }
+  QString filePath = QFileDialog::getSaveFileName(this,tr("Save Script As "),scriptDir,tr("Script files (*.py)"));
+  // An empty string indicates they clicked cancel
+  if( filePath.isEmpty() ) return;
+  
+  QFile scriptfile(filePath);
+  if (!scriptfile.open(QIODevice::WriteOnly | QIODevice::Text))
+  {
+    QMessageBox::information(this, "Algorithm History", "Unable to write to file. Check you have write permission on this location.");
+    return;
+  }
+
+  QString script("");
+  generateScript(script);
+  QTextStream out(&scriptfile);
+  out<<"######################################################################\n";
+  out<<"#Python Script Generated by Algorithm History Display \n";
+  out<<"######################################################################\n";
+  out<<script<<"\n";
+  scriptfile.close();
+  //save the file path
+  MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(QFileInfo(filePath).absoluteDir().path());
+}
+std::string AlgorithmHistoryWindow::sanitizePropertyName(const std::string & name)
+{
+  std::string arg;
+  std::string::const_iterator sIter = name.begin();
+  std::string::const_iterator sEnd = name.end();
+  for( ; sIter != sEnd; ++sIter )
+  {
+    int letter = (int)(*sIter);
+    if( (letter >= 48 && letter <= 57) || (letter >= 97 && letter <= 122) ||
+	(letter >= 65 && letter <= 90) )
+    {
+      arg.push_back(*sIter);
+    }
+  }
+  return arg;
+}
+void AlgorithmHistoryWindow::setAlgorithmName(const QString& algName)
+{
+  m_algName=algName;
+}
+const QString &AlgorithmHistoryWindow::getAlgorithmName() const
+{	return m_algName;
+}
+void AlgorithmHistoryWindow::setAlgorithmVersion(const int& version) 
+{
+  m_nVersion=version;
+}
+const int& AlgorithmHistoryWindow::getAlgorithmVersion()const
+{
+  return m_nVersion;
+}
+void AlgorithmHistoryWindow::populateAlgHistoryTreeWidget()
+{	
+  std::vector<AlgorithmHistory>::reverse_iterator ralgHistory_Iter=m_algHist.rbegin( );
+  std::string algrithmName;
+  algrithmName=(*ralgHistory_Iter).name();
+  QString algName=algrithmName.c_str();
+  int nAlgVersion=(*ralgHistory_Iter).version();
+  concatVersionwithName(algName,nAlgVersion);
+	
+  QTreeWidgetItem * item= new	QTreeWidgetItem(QStringList(algName),QTreeWidgetItem::Type);
+  if(m_Historytree)m_Historytree->addTopLevelItem(item);
+  ralgHistory_Iter++;
+  for ( ; ralgHistory_Iter != m_algHist.rend( ) ; ralgHistory_Iter++ )
+  {
+    algrithmName=(*ralgHistory_Iter).name();
+    nAlgVersion=(*ralgHistory_Iter).version();
+    algName=algrithmName.c_str();
+    concatVersionwithName(algName,nAlgVersion);
+    QTreeWidgetItem * subitem= new	QTreeWidgetItem(QStringList(algName));
+    if(item)item->addChild(subitem);
+  }
+		
+}
+void AlgorithmHistoryWindow::concatVersionwithName( QString& algName,const int version)
+{
+  algName= algName+" v.";
+  QString algVersion=QString::number(version,10);
+  algName+=algVersion;
+}
+
+void AlgEnvHistoryGrpBox::fillEnvHistoryGroupBox(const EnvironmentHistory& envHistory)
+{
+  std::string osname=envHistory.osName();
+  std::string osversion=envHistory.osVersion();
+  std::string userName=envHistory.userName();
+  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());
+
+  QLineEdit* frmwkVersnEdit=getfrmworkVersionEdit();
+  if(frmwkVersnEdit)frmwkVersnEdit->setText(frwkversn.c_str());
+
+}
+void AlgorithmHistoryWindow::updateAll(QString algName,int version,int index)
+{	
+  int nSize=m_algHist.size();
+  //indicates the position of the ALgorithmHistory Object in the history vector
+  int pos=0;
+  //index =-1 for the parent item(root item)
+  if (index==-1)
+  {	//parent in the algorithHistoryTree widget comes here
+    pos=nSize-1;
+    g_log.debug()<< "selected algorithm is at position "<<pos<<"  in the History vector "<<std::endl;
+  }
+  else
+  {	pos=nSize-2-index;
+    g_log.debug ()<< "selected algorithm is at position  "<<pos <<"  in the History vector "<<std::endl;
+  }
+  updateAlgHistoryProperties(algName,version,pos);
+  updateExecSummaryGrpBox(algName,version,pos);
+  setAlgorithmName(algName);
+  setAlgorithmVersion(version);
+	
+}
+void AlgorithmHistoryWindow::updateAlgHistoryProperties(QString algName,int version,int pos)
+{
+  std::vector<PropertyHistory> histProp;
+  //getting the selcted algorithm at pos from History vector
+  const AlgorithmHistory & algHist=m_algHist.at(pos);
+  std::string name=algHist.name();
+  int nVer=algHist.version();
+  //if name and version in the history is same as selected item
+  //get the properties and display it.
+  if((algName==name.c_str())&& (nVer==version))
+  {
+    histProp=algHist.getProperties();
+    if(m_histPropWindow)
+    {  m_histPropWindow->setAlgProperties(histProp);
+      m_histPropWindow->clearData();
+      m_histPropWindow->displayAlgHistoryProperties();
+    }
+  }
+}
+void AlgorithmHistoryWindow::updateExecSummaryGrpBox(const QString& algName,const int & version,int pos)
+{
+  //getting the selcted algorithm at pos from History vector
+  const AlgorithmHistory & algHist=m_algHist.at(pos);
+  std::string name=algHist.name();
+  int nVer=algHist.version();
+  //if name and version in the history is same as selected item
+  //get the properties and display it.
+  if((algName==name.c_str())&& (nVer==version))
+  {
+    double duration=algHist.executionDuration();
+    Mantid::Kernel::DateAndTime date=algHist.executionDate();
+    if(m_execSumGrpBox)m_execSumGrpBox->setData(duration,date);
+  }
+}
+void AlgorithmHistoryWindow::copytoClipboard()
+{	
+  QString comments ("######################################################################\n"
+		    "#Python Script Generated by Algorithm History Display \n"
+		    "######################################################################\n");
+  QString script("");
+  generateScript(script);
+  QClipboard *clipboard = QApplication::clipboard();
+  if(clipboard)
+  {	QString clipboardData=comments+script;
+    clipboard->setText(clipboardData);
+  }
+}
+
+AlgHistoryProperties::AlgHistoryProperties(QWidget*w,const std::vector<PropertyHistory>& propHist):
+  m_Histprop(propHist)
+{
+  QStringList hList;
+  hList<<"Name"<<"Value"<<"Default?:"<<"Direction"<<"";
+  m_histpropTree = new  QTreeWidget(w);
+  if(m_histpropTree)
+  {	m_histpropTree->setColumnCount(5);
+    m_histpropTree->setSelectionMode(QAbstractItemView::NoSelection);
+    m_histpropTree->setHeaderLabels(hList);
+    //m_histpropTree->setGeometry (213,5,385,200);
+    m_histpropTree->setGeometry (213,5,350,200);
+  }
+}
+void AlgHistoryProperties::clearData()
+{
+  if(m_histpropTree)
+  {   m_histpropTree->clear();
+    int ntopcount=m_histpropTree->topLevelItemCount() ;
+    while(ntopcount--)
+    {m_histpropTree->topLevelItem(ntopcount);
+    }
+  }
+}
+void AlgHistoryProperties::setAlgProperties( const std::vector<PropertyHistory>& histProp)
+{
+  m_Histprop.assign(histProp.begin(),histProp.end());
+}
+const std::vector<PropertyHistory>& AlgHistoryProperties:: getAlgProperties()
+{
+  return m_Histprop;
+}
+void AlgHistoryProperties::displayAlgHistoryProperties()
+{
+  QStringList propList;
+  std::string sProperty;
+  bool bisDefault;
+  int nDirection=0;
+  for ( std::vector<Mantid::Kernel::PropertyHistory>::const_iterator pIter = m_Histprop.begin();
+	pIter != m_Histprop.end(); ++pIter )
+  {
+    sProperty=(*pIter).name();
+    propList.append(sProperty.c_str());
+    sProperty=(*pIter).value();
+    propList.append(sProperty.c_str());
+		
+    bisDefault=(*pIter).isDefault();
+    bisDefault? (sProperty="Yes"):(sProperty="No");
+		
+    propList.append(sProperty.c_str());
+    nDirection=(*pIter).direction();
+    switch(nDirection)
+    {
+    case 0:{sProperty="Input";break;}
+    case 1:{sProperty="Output";break;}
+    case 2:{sProperty="InOut";break;}
+    default:sProperty="N/A";
+    }
+    propList.append(sProperty.c_str());
+    QTreeWidgetItem * item= new	QTreeWidgetItem(propList);
+    if(m_histpropTree)m_histpropTree->addTopLevelItem(item);
+    propList.clear();
+
+  }// end of properties for loop
+    
+}
+void AlgHistoryTreeWidget::treeSelectionChanged()
+{	
+  QString algName("");int nVersion=-1;int nIndex=-1;
+  getSelectedAlgorithmName(algName,nVersion,nIndex);
+  emit updateAlgorithmHistoryWindow(algName,nVersion,nIndex);
+}
+void AlgHistoryTreeWidget::setAlgorithmName(const QString& algName)
+{
+  m_algName=algName;
+}
+const QString AlgHistoryTreeWidget::getAlgorithmName()
+{	return m_algName;
+}
+void AlgHistoryTreeWidget::setAlgorithmVersion(const int& version)
+{
+  m_nVersion=version;
+}
+const int& AlgHistoryTreeWidget::getAlgorithmVersion()
+{
+  return m_nVersion;
+}
+void AlgHistoryTreeWidget::getSelectedAlgorithmName(QString& algName,int & version,int & index)
+{	
+  QList<QTreeWidgetItem*> items = selectedItems();
+  if( !items.empty() )
+  {QTreeWidgetItem *item = items[0];
+    if(item)
+    {	//finding the index of the selected item
+      QModelIndex modelIndex=indexFromItem(item);
+      int row=modelIndex.row();
+      if(row!=0)
+      {g_log.debug()<< "It's child Item"<<std::endl;
+	index=row;
+      }
+      else if (row==0)
+      {
+	//row can be zero for 1st child item and parent item
+	QTreeWidgetItem * parent=NULL;
+	parent=item->parent();
+	if(parent)
+	{//if it's child item at row zero set index =0
+	  g_log.debug()<< "It's child Item"<<std::endl;
+	  index=0;
+	}
+	else
+	{	//if it's parent item set index = -1
+	  g_log.debug()<< "It's parent  item "<<std::endl;
+	  index=-1;
+	}
+      }
+      QString  str=item->text(0);
+      int nDotIndex=str.indexOf(".",0,Qt::CaseSensitive );
+      algName=str.left(nDotIndex-2);
+      version=str.right(str.length()-nDotIndex-1).toInt();
+      g_log.debug()<< "selected alg name =  "<< algName.toStdString()<<" index number =  "<<index<<std::endl;
+    }
+  }
+}
+void AlgHistoryTreeWidget::mouseDoubleClickEvent(QMouseEvent *e)
+{		
+  QString algName("");int nVersion=-1;int nIndex=-1;
+  getSelectedAlgorithmName(algName,nVersion,nIndex);
+  emit updateAlgorithmHistoryWindow(algName,nVersion,nIndex);
+  QTreeWidget::mouseDoubleClickEvent(e);
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/AlgorithmHistoryWindow.h b/Code/Mantid/MantidPlot/src/Mantid/AlgorithmHistoryWindow.h
index a7bdcd92f4fb61108cf5ca4abcb57aae0291f806..821f0995a98757fff5150f9fac411b2888c472a4 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/AlgorithmHistoryWindow.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/AlgorithmHistoryWindow.h
@@ -1,182 +1,182 @@
-#ifndef ALGORITHMHISTORYWINDOW_H 
-#define ALGORITHMHISTORYWINDOW_H
-
-#include <QWidget>
-#include <QTreeWidget>
-#include <QMainWindow>
-#include <QGroupBox>
-#include <QDateTimeEdit>
-#include <QLabel>
-#include <QDateTimeEdit>
-#include <QDialog>
-#include <ctime>
-#include <QLineEdit>
-#include <QVBoxLayout>
-#include <QFileDialog>
-#include <QFile>
-#include <QTextStream>
-#include <QFormLayout>
-#include <QMenu>
-#include <QAction>
-#include <QApplication>
-#include <QClipboard>
-
-#include "MantidAPI/Workspace.h"
-#include "MantidAPI/AlgorithmHistory.h"
-#include "MantidKernel/DateAndTime.h"
-#include "MantidKernel/EnvironmentHistory.h"
-#include "MantidAPI/AlgorithmManager.h"
-#include "MantidKernel/Property.h"
-#include "MantidQtAPI/AlgorithmInputHistory.h"
-#include "MantidQtAPI/MantidDialog.h"
-#include "../ApplicationWindow.h"
-#include "MantidKernel/Logger.h"
-#include "QMessageBox"
-
-class AlgHistoryTreeWidget:public QTreeWidget
-{
-  Q_OBJECT
-  signals:
-  void updateAlgorithmHistoryWindow(QString algName,int algVersion,int Index);
-public:
-  /// Constructor
-  AlgHistoryTreeWidget(QWidget *w):QTreeWidget(w),m_algName(""),m_nVersion(0)
-  {
-    connect(this,SIGNAL(itemSelectionChanged()),this,SLOT(treeSelectionChanged()));
-  }
-  void getSelectedAlgorithmName(QString& algName,int & version,int & index);
-  const QString getAlgorithmName();
-  const int& getAlgorithmVersion();
-public slots:
-  void treeSelectionChanged();
-private:
-  void mouseDoubleClickEvent(QMouseEvent *e);
-  void setAlgorithmName(const QString& );
-  void setAlgorithmVersion(const int& version);
-	
-private:
-  QString m_algName;
-  int m_nVersion;
-  static Mantid::Kernel::Logger& g_log;
-
-};
-
-class AlgExecSummaryGrpBox: public QGroupBox
-{
-  Q_OBJECT
-  public:
-  AlgExecSummaryGrpBox(QWidget*w):QGroupBox(w){}
-  AlgExecSummaryGrpBox(QString,QWidget*w);
-  ~AlgExecSummaryGrpBox();
-  void setData(const double execDuration,const Mantid::Kernel::DateAndTime execDate);
-private:
-  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;	
-};
-
-class AlgEnvHistoryGrpBox: public QGroupBox
-{
-  Q_OBJECT
-  public:
-  AlgEnvHistoryGrpBox(QWidget*w):QGroupBox(w){}
-  AlgEnvHistoryGrpBox(QString,QWidget*w);
-  ~AlgEnvHistoryGrpBox();
-
-  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;
-  QLabel *m_osVersionLabel;
-  QLineEdit *m_osVersionEdit;
-  QLabel *m_frmworkVersionLabel;
-  QLineEdit *m_frmwkVersnEdit;
-};
-
-class AlgHistScriptButton:public QPushButton
-{
-  Q_OBJECT
-  public:
-  AlgHistScriptButton(QWidget*w):QPushButton(w){}
-  AlgHistScriptButton(QString title,QWidget* w);
-  ~AlgHistScriptButton();
-};
-
-class AlgHistoryProperties;
-class AlgorithmHistoryWindow: public MantidQt::API::MantidDialog
-{
-  Q_OBJECT
-  signals:
-  void updateAlgorithmHistoryWindow(QString algName);
-public:
-  AlgorithmHistoryWindow(QWidget*w) : MantidQt::API::MantidDialog(w){}
-  AlgorithmHistoryWindow(ApplicationWindow *w,const std::vector<Mantid::API::AlgorithmHistory>&alghist,
-			 const Mantid::Kernel::EnvironmentHistory&);
-  ~AlgorithmHistoryWindow();
-private slots:
-  void updateAll( QString algName,int algVersion,int nIndex);
-	
-  void copytoClipboard();
-  void writeToScriptFile();
-private:
-  AlgExecSummaryGrpBox* createExecSummaryGrpBox();
-  AlgEnvHistoryGrpBox* createEnvHistGrpBox(const Mantid::Kernel::EnvironmentHistory& envHistory);
-  //AlgHistoryProperties * createAlgHistoryPropWindow(const QString& algName,int version);
-  AlgHistoryProperties * createAlgHistoryPropWindow();
-  void populateAlgHistoryTreeWidget();
-  QPushButton * CreateScriptButton();
-  QFileDialog* createScriptDialog(const QString& algName);
-  //void updateExecSummaryGrpBox(const QString& algName,const int & version);
-  void updateExecSummaryGrpBox(const QString& algName,const int & version,int index);
-  //void updateAlgHistoryProperties(QString algName,int version);
-  void updateAlgHistoryProperties(QString algName,int version,int pos);
-  void concatVersionwithName(QString& algName,const int version);
-  void  generateScript(QString& script);
-  std::string sanitizePropertyName(const std::string & name);
-  void handleException( const std::exception& e );
-  void setAlgorithmName(const QString& algName);
-  const QString& getAlgorithmName() const;
-  void setAlgorithmVersion(const int& version);
-  const int& getAlgorithmVersion()const;
-  static Mantid::Kernel::Logger& g_log;
-	
-private:
-  std::vector<Mantid::API::AlgorithmHistory> m_algHist;
-  QPushButton *m_scriptButton;
-  AlgHistoryTreeWidget *m_Historytree;
-  AlgHistoryProperties * m_histPropWindow; 
-  AlgExecSummaryGrpBox *m_execSumGrpBox ;
-  AlgEnvHistoryGrpBox * m_envHistGrpBox;
-  QString m_algName;
-  int m_nVersion;
-};
-
-class AlgHistoryProperties: public QObject
-{
-  Q_OBJECT
-  public:
-  //AlgHistoryProperties(QWidget *w,
-  //const std::vector<Mantid::API::AlgorithmHistory> &);
-  AlgHistoryProperties(QWidget*w,const std::vector<Mantid::Kernel::PropertyHistory>& propHist);
-  void displayAlgHistoryProperties();
-  void clearData();
-  void setAlgProperties( const std::vector<Mantid::Kernel::PropertyHistory>& histProp);
-  const std::vector<Mantid::Kernel::PropertyHistory>& getAlgProperties();
-public:
-  QTreeWidget *m_histpropTree;
-private:
-  //std::vector<Mantid::API::AlgorithmHistory>m_algHist;
-  std::vector<Mantid::Kernel::PropertyHistory> m_Histprop;
-};
-#endif
-
-
-
+#ifndef ALGORITHMHISTORYWINDOW_H 
+#define ALGORITHMHISTORYWINDOW_H
+
+#include <QWidget>
+#include <QTreeWidget>
+#include <QMainWindow>
+#include <QGroupBox>
+#include <QDateTimeEdit>
+#include <QLabel>
+#include <QDateTimeEdit>
+#include <QDialog>
+#include <ctime>
+#include <QLineEdit>
+#include <QVBoxLayout>
+#include <QFileDialog>
+#include <QFile>
+#include <QTextStream>
+#include <QFormLayout>
+#include <QMenu>
+#include <QAction>
+#include <QApplication>
+#include <QClipboard>
+
+#include "MantidAPI/Workspace.h"
+#include "MantidAPI/AlgorithmHistory.h"
+#include "MantidKernel/DateAndTime.h"
+#include "MantidKernel/EnvironmentHistory.h"
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidKernel/Property.h"
+#include "MantidQtAPI/AlgorithmInputHistory.h"
+#include "MantidQtAPI/MantidDialog.h"
+#include "../ApplicationWindow.h"
+#include "MantidKernel/Logger.h"
+#include "QMessageBox"
+
+class AlgHistoryTreeWidget:public QTreeWidget
+{
+  Q_OBJECT
+  signals:
+  void updateAlgorithmHistoryWindow(QString algName,int algVersion,int Index);
+public:
+  /// Constructor
+  AlgHistoryTreeWidget(QWidget *w):QTreeWidget(w),m_algName(""),m_nVersion(0)
+  {
+    connect(this,SIGNAL(itemSelectionChanged()),this,SLOT(treeSelectionChanged()));
+  }
+  void getSelectedAlgorithmName(QString& algName,int & version,int & index);
+  const QString getAlgorithmName();
+  const int& getAlgorithmVersion();
+public slots:
+  void treeSelectionChanged();
+private:
+  void mouseDoubleClickEvent(QMouseEvent *e);
+  void setAlgorithmName(const QString& );
+  void setAlgorithmVersion(const int& version);
+	
+private:
+  QString m_algName;
+  int m_nVersion;
+  static Mantid::Kernel::Logger& g_log;
+
+};
+
+class AlgExecSummaryGrpBox: public QGroupBox
+{
+  Q_OBJECT
+  public:
+  AlgExecSummaryGrpBox(QWidget*w):QGroupBox(w){}
+  AlgExecSummaryGrpBox(QString,QWidget*w);
+  ~AlgExecSummaryGrpBox();
+  void setData(const double execDuration,const Mantid::Kernel::DateAndTime execDate);
+private:
+  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;	
+};
+
+class AlgEnvHistoryGrpBox: public QGroupBox
+{
+  Q_OBJECT
+  public:
+  AlgEnvHistoryGrpBox(QWidget*w):QGroupBox(w){}
+  AlgEnvHistoryGrpBox(QString,QWidget*w);
+  ~AlgEnvHistoryGrpBox();
+
+  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;
+  QLabel *m_osVersionLabel;
+  QLineEdit *m_osVersionEdit;
+  QLabel *m_frmworkVersionLabel;
+  QLineEdit *m_frmwkVersnEdit;
+};
+
+class AlgHistScriptButton:public QPushButton
+{
+  Q_OBJECT
+  public:
+  AlgHistScriptButton(QWidget*w):QPushButton(w){}
+  AlgHistScriptButton(QString title,QWidget* w);
+  ~AlgHistScriptButton();
+};
+
+class AlgHistoryProperties;
+class AlgorithmHistoryWindow: public MantidQt::API::MantidDialog
+{
+  Q_OBJECT
+  signals:
+  void updateAlgorithmHistoryWindow(QString algName);
+public:
+  AlgorithmHistoryWindow(QWidget*w) : MantidQt::API::MantidDialog(w){}
+  AlgorithmHistoryWindow(ApplicationWindow *w,const std::vector<Mantid::API::AlgorithmHistory>&alghist,
+			 const Mantid::Kernel::EnvironmentHistory&);
+  ~AlgorithmHistoryWindow();
+private slots:
+  void updateAll( QString algName,int algVersion,int nIndex);
+	
+  void copytoClipboard();
+  void writeToScriptFile();
+private:
+  AlgExecSummaryGrpBox* createExecSummaryGrpBox();
+  AlgEnvHistoryGrpBox* createEnvHistGrpBox(const Mantid::Kernel::EnvironmentHistory& envHistory);
+  //AlgHistoryProperties * createAlgHistoryPropWindow(const QString& algName,int version);
+  AlgHistoryProperties * createAlgHistoryPropWindow();
+  void populateAlgHistoryTreeWidget();
+  QPushButton * CreateScriptButton();
+  QFileDialog* createScriptDialog(const QString& algName);
+  //void updateExecSummaryGrpBox(const QString& algName,const int & version);
+  void updateExecSummaryGrpBox(const QString& algName,const int & version,int index);
+  //void updateAlgHistoryProperties(QString algName,int version);
+  void updateAlgHistoryProperties(QString algName,int version,int pos);
+  void concatVersionwithName(QString& algName,const int version);
+  void  generateScript(QString& script);
+  std::string sanitizePropertyName(const std::string & name);
+  void handleException( const std::exception& e );
+  void setAlgorithmName(const QString& algName);
+  const QString& getAlgorithmName() const;
+  void setAlgorithmVersion(const int& version);
+  const int& getAlgorithmVersion()const;
+  static Mantid::Kernel::Logger& g_log;
+	
+private:
+  std::vector<Mantid::API::AlgorithmHistory> m_algHist;
+  QPushButton *m_scriptButton;
+  AlgHistoryTreeWidget *m_Historytree;
+  AlgHistoryProperties * m_histPropWindow; 
+  AlgExecSummaryGrpBox *m_execSumGrpBox ;
+  AlgEnvHistoryGrpBox * m_envHistGrpBox;
+  QString m_algName;
+  int m_nVersion;
+};
+
+class AlgHistoryProperties: public QObject
+{
+  Q_OBJECT
+  public:
+  //AlgHistoryProperties(QWidget *w,
+  //const std::vector<Mantid::API::AlgorithmHistory> &);
+  AlgHistoryProperties(QWidget*w,const std::vector<Mantid::Kernel::PropertyHistory>& propHist);
+  void displayAlgHistoryProperties();
+  void clearData();
+  void setAlgProperties( const std::vector<Mantid::Kernel::PropertyHistory>& histProp);
+  const std::vector<Mantid::Kernel::PropertyHistory>& getAlgProperties();
+public:
+  QTreeWidget *m_histpropTree;
+private:
+  //std::vector<Mantid::API::AlgorithmHistory>m_algHist;
+  std::vector<Mantid::Kernel::PropertyHistory> m_Histprop;
+};
+#endif
+
+
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/FitParameterTie.cpp b/Code/Mantid/MantidPlot/src/Mantid/FitParameterTie.cpp
index 1d8b0fb55d856035285f316100d54bfb7d0980ce..6de777651cac5bdd9a988fef50fcc203f7370872 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/FitParameterTie.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/FitParameterTie.cpp
@@ -1,165 +1,165 @@
-#include "FitParameterTie.h"
-#include "MantidAPI/CompositeFunction.h"
-#include <QRegExp>
-#include <stdexcept>
-#include <iostream>
-
-/// Constructor
-FitParameterTie::FitParameterTie(boost::shared_ptr<Mantid::API::CompositeFunction> cf)
-:m_compositeFunction(cf),m_prop(0)
-{}
-
-/// Destructor
-FitParameterTie::~FitParameterTie()
-{
-  if (m_prop)
-  {
-    //delete m_prop;
-  }
-}
-
-/** Set the tying expression. The function names (f0,f1,f2,...) are changed to
- * 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)
-{
-  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 == estr.size())
-  {
-    throw std::invalid_argument("The tying expression is missing.\n"
-      "Syntax: <tied_name> = <tying_expression>");
-  }
-
-  if (estr.mid(ieq+1).trimmed().isEmpty())
-  {
-    throw std::invalid_argument("The tying expression is missing.\n"
-      "Syntax: <tied_name> = <tying_expression>");
-  }
-
-  QString parName = estr.left(ieq).trimmed();
-
-  // 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.HWHM");
-  }
-
-  m_expr = estr;
-  for(int i=rx.indexIn(m_expr);i>=0;)
-  {
-    int iFun = rx.cap(1).toInt();
-    int j = m_iFunctions.indexOf(iFun);
-    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());
-  }
-
-}
-
-/// The tying expression
-QString FitParameterTie::expr(bool removePrefix)const
-{
-  QString str = m_expr;
-  for(int j=0;j<m_iFunctions.size();j++)
-  {
-    QString ph = "#"+QString::number(j);
-    QString fi;
-    if (removePrefix)
-    {
-      ph += ".";
-      fi = "";
-    }
-    else
-    {
-      fi = "f"+QString::number(m_iFunctions[j]);
-    }
-    str.replace(ph,fi);
-  }
-  return str;
-}
-
-/// The parameter name
-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);
-  }
-  return str;
-}
-
-/// Returns the right-hand side of the expression
-QString FitParameterTie::exprRHS()const
-{
-  QString ex = expr();
-  int ieq = ex.indexOf('=');
-  if (ieq<0)
-  {
-    return ex;
-  }
-  if (ieq==ex.size()-1)
-  {
-    return "";
-  }
-  return ex.mid(ieq+1);
-}
-
-/**
- * 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
- *   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)
-    {
-      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.
- * @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)
-    {
-      return false;
-    }
-    if (m_iFunctions[j] > i)
-    {
-      m_iFunctions[j]--;
-    }
-  }
-  return true;
-}
+#include "FitParameterTie.h"
+#include "MantidAPI/CompositeFunction.h"
+#include <QRegExp>
+#include <stdexcept>
+#include <iostream>
+
+/// Constructor
+FitParameterTie::FitParameterTie(boost::shared_ptr<Mantid::API::CompositeFunction> cf)
+:m_compositeFunction(cf),m_prop(0)
+{}
+
+/// Destructor
+FitParameterTie::~FitParameterTie()
+{
+  if (m_prop)
+  {
+    //delete m_prop;
+  }
+}
+
+/** Set the tying expression. The function names (f0,f1,f2,...) are changed to
+ * 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)
+{
+  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 == estr.size())
+  {
+    throw std::invalid_argument("The tying expression is missing.\n"
+      "Syntax: <tied_name> = <tying_expression>");
+  }
+
+  if (estr.mid(ieq+1).trimmed().isEmpty())
+  {
+    throw std::invalid_argument("The tying expression is missing.\n"
+      "Syntax: <tied_name> = <tying_expression>");
+  }
+
+  QString parName = estr.left(ieq).trimmed();
+
+  // 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.HWHM");
+  }
+
+  m_expr = estr;
+  for(int i=rx.indexIn(m_expr);i>=0;)
+  {
+    int iFun = rx.cap(1).toInt();
+    int j = m_iFunctions.indexOf(iFun);
+    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());
+  }
+
+}
+
+/// The tying expression
+QString FitParameterTie::expr(bool removePrefix)const
+{
+  QString str = m_expr;
+  for(int j=0;j<m_iFunctions.size();j++)
+  {
+    QString ph = "#"+QString::number(j);
+    QString fi;
+    if (removePrefix)
+    {
+      ph += ".";
+      fi = "";
+    }
+    else
+    {
+      fi = "f"+QString::number(m_iFunctions[j]);
+    }
+    str.replace(ph,fi);
+  }
+  return str;
+}
+
+/// The parameter name
+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);
+  }
+  return str;
+}
+
+/// Returns the right-hand side of the expression
+QString FitParameterTie::exprRHS()const
+{
+  QString ex = expr();
+  int ieq = ex.indexOf('=');
+  if (ieq<0)
+  {
+    return ex;
+  }
+  if (ieq==ex.size()-1)
+  {
+    return "";
+  }
+  return ex.mid(ieq+1);
+}
+
+/**
+ * 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
+ *   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)
+    {
+      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.
+ * @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)
+    {
+      return false;
+    }
+    if (m_iFunctions[j] > i)
+    {
+      m_iFunctions[j]--;
+    }
+  }
+  return true;
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/FitParameterTie.h b/Code/Mantid/MantidPlot/src/Mantid/FitParameterTie.h
index d0a0df2663df3ecc8c451e23bcdfd9c8e5ed54f9..a598a11c26644c9b837997581a234998397572c1 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/FitParameterTie.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/FitParameterTie.h
@@ -1,57 +1,57 @@
-#ifndef FITPARAMETERTIE_H
-#define FITPARAMETERTIE_H
-
-#include <QString>
-#include <QList>
-#include <boost/shared_ptr.hpp>
-
-namespace Mantid
-{
-  namespace API
-  {
-    class CompositeFunction;
-  }
-}
-
-class QtProperty;
-
-/**
- * Class FitParameterTie is for editing parameter ties in Mantid functions.
- */
-class FitParameterTie
-{
-public:
-  /// Constructor
-  FitParameterTie(boost::shared_ptr<Mantid::API::CompositeFunction> cf);
-  /// Destructor
-  ~FitParameterTie();
-  /// Set the tying expression, e.g. "f1.Sigma = 2*f0.Sigma + 1"
-  void set(const QString& estr);
-  /// The tying expression
-  QString expr(bool removePrefix=false)const;
-  /// The parameter name
-  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 
-  /// 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;}
-  /// Get property
-  QtProperty* getProperty()const{return m_prop;}
-private:
-  /// The tying expression
-  QString m_expr;
-  /// Function indeces used in the expression
-  QList<int> m_iFunctions;
+#ifndef FITPARAMETERTIE_H
+#define FITPARAMETERTIE_H
+
+#include <QString>
+#include <QList>
+#include <boost/shared_ptr.hpp>
+
+namespace Mantid
+{
+  namespace API
+  {
+    class CompositeFunction;
+  }
+}
+
+class QtProperty;
+
+/**
+ * Class FitParameterTie is for editing parameter ties in Mantid functions.
+ */
+class FitParameterTie
+{
+public:
+  /// Constructor
+  FitParameterTie(boost::shared_ptr<Mantid::API::CompositeFunction> cf);
+  /// Destructor
+  ~FitParameterTie();
+  /// Set the tying expression, e.g. "f1.Sigma = 2*f0.Sigma + 1"
+  void set(const QString& estr);
+  /// The tying expression
+  QString expr(bool removePrefix=false)const;
+  /// The parameter name
+  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 
+  /// 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;}
+  /// Get property
+  QtProperty* getProperty()const{return m_prop;}
+private:
+  /// The tying expression
+  QString m_expr;
+  /// Function indeces used in the expression
+  QList<int> m_iFunctions;
   /// A copy of the edited function
   boost::shared_ptr<Mantid::API::CompositeFunction> m_compositeFunction;
   /// The property
   QtProperty* m_prop;
-};
-
-#endif /* FITPARAMETERTIE_H */
+};
+
+#endif /* FITPARAMETERTIE_H */
diff --git a/Code/Mantid/MantidPlot/src/Mantid/FitPropertyBrowser.cpp b/Code/Mantid/MantidPlot/src/Mantid/FitPropertyBrowser.cpp
index b0bfde8566b8c9a1d58f36ebbf147bdf3284537b..80389ecee8d33cf49462252db5aafa3869fe2b89 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/FitPropertyBrowser.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/FitPropertyBrowser.cpp
@@ -1,2174 +1,2174 @@
-#include "FitPropertyBrowser.h"
-#include "PropertyHandler.h"
-#include "SequentialFitDialog.h"
-
-#include "MantidAPI/FunctionFactory.h"
-#include "MantidAPI/IPeakFunction.h"
-#include "MantidAPI/IBackgroundFunction.h"
-#include "MantidAPI/CompositeFunctionMW.h"
-#include "MantidAPI/AlgorithmManager.h"
-#include "MantidAPI/MatrixWorkspace.h"
-#include "MantidAPI/WorkspaceGroup.h"
-#include "MantidAPI/TableRow.h"
-#include "MantidAPI/ParameterTie.h"
-#include "MantidAPI/IConstraint.h"
-#include "MantidAPI/ConstraintFactory.h"
-#include "MantidKernel/ConfigService.h"
-#include "MantidKernel/LibraryManager.h"
-
-#include "MantidQtMantidWidgets/UserFunctionDialog.h"
-
-#include "StringDialogEditorFactory.h"
-#include "DoubleEditorFactory.h"
-
-#include "qttreepropertybrowser.h"
-#include "qtpropertymanager.h"
-#include "qteditorfactory.h"
-
-#include "../ApplicationWindow.h"
-#include "MantidUI.h"
-#include <QVBoxLayout>
-#include <QHBoxLayout>
-#include <QGridLayout>
-#include <QPushButton>
-#include <QMenu>
-#include <QMessageBox>
-#include <QInputDialog>
-#include <QSettings>
-#include <QFileInfo>
-#include <QApplication>
-#include <QClipboard>
-
-#include <algorithm>
-
-class FormulaDialogEditor: public StringDialogEditor
-{
-public:
-  FormulaDialogEditor(QtProperty *property, QWidget *parent)
-    :StringDialogEditor(property,parent){}
-protected slots:
-  void runDialog()
-  {
-    MantidQt::MantidWidgets::UserFunctionDialog *dlg = new MantidQt::MantidWidgets::UserFunctionDialog((QWidget*)parent(),getText());
-    if (dlg->exec() == QDialog::Accepted)
-    {
-      setText(dlg->getFormula());
-      updateProperty();
-    };
-  }
-};
-
-class FormulaDialogEditorFactory: public StringDialogEditorFactory
-{
-public:
-  FormulaDialogEditorFactory(QObject* parent):StringDialogEditorFactory(parent){}
-protected:
-  QWidget *createEditor(QtStringPropertyManager *manager, QtProperty *property,QWidget *parent)
-  {
-    (void) manager; //Avoid unused warning
-    return new FormulaDialogEditor(property,parent);
-  }
-};
-
-/**
- * Constructor
- * @param parent :: The parent widget - must be an ApplicationWindow
- */
-FitPropertyBrowser::FitPropertyBrowser(QWidget* parent)
-:QDockWidget("Fit Function",parent),
-m_appWindow((ApplicationWindow*)parent),
-m_currentHandler(0),
-m_logValue(NULL),
-m_compositeFunction(0),
-m_defaultFunction("Gaussian"),
-m_defaultPeak("Gaussian"),
-m_defaultBackground("LinearBackground"),
-m_guessOutputName(true),
-m_changeSlotsEnabled(false),
-m_peakToolOn(false),
-m_auto_back(false),
-m_autoBgName(QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("curvefitting.autoBackground"))),
-m_autoBackground(NULL),
-m_decimals(-1)
-{
-  QSettings settings;
-  settings.beginGroup("Mantid/FitBrowser");
-
-  // Make sure plugins are loaded
-  std::string libpath = Mantid::Kernel::ConfigService::Instance().getString("plugins.directory");
-  if( !libpath.empty() )
-  {
-    Mantid::Kernel::LibraryManager::Instance().OpenAllLibraries(libpath);
-  }
-
-  // Try to create a Gaussian. Failing will mean that CurveFitting dll is not loaded
-  boost::shared_ptr<Mantid::API::IFitFunction> f = boost::shared_ptr<Mantid::API::IFitFunction>(
-    Mantid::API::FunctionFactory::Instance().createFitFunction("Gaussian"));
-  if (m_autoBgName.toLower() == "none")
-  {
-    m_autoBgName = "";
-  }
-  else
-  {
-    setAutoBackgroundName(m_autoBgName);
-  }
-
-  std::string def = Mantid::Kernel::ConfigService::Instance().getString("curvefitting.defaultPeak");
-  if (!def.empty())
-  {
-    m_defaultPeak = def;
-  }
-
-  def = Mantid::Kernel::ConfigService::Instance().getString("curvefitting.autoBackground");
-  if (!def.empty())
-  {
-    m_defaultBackground = def;
-  }
-  m_defaultFunction = m_defaultPeak;
-
-  setObjectName("FitFunction"); // this is needed for QMainWindow::restoreState()
-  setMinimumHeight(150);
-  setMinimumWidth(200);
-  m_appWindow->addDockWidget( Qt::LeftDockWidgetArea, this );
-
-  QWidget* w = new QWidget(parent);
-
-    /* Create property managers: they create, own properties, get and set values  */
-
-  m_groupManager =  new QtGroupPropertyManager(w);
-  m_doubleManager = new QtDoublePropertyManager(w);
-  m_stringManager = new QtStringPropertyManager(w);
-  m_enumManager =   new QtEnumPropertyManager(w);
-  m_intManager =    new QtIntPropertyManager(w);
-  m_boolManager = new QtBoolPropertyManager(w);
-  m_filenameManager = new QtStringPropertyManager(w);
-  m_formulaManager = new QtStringPropertyManager(w);
-
-    /* Create the top level group */
-
-  /*QtProperty* fitGroup = */m_groupManager->addProperty("Fit");
-
-  connect(m_enumManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(enumChanged(QtProperty*)));
-  connect(m_boolManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(boolChanged(QtProperty*)));
-  connect(m_intManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(intChanged(QtProperty*)));
-  connect(m_doubleManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(doubleChanged(QtProperty*)));
-  connect(m_stringManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(stringChanged(QtProperty*)));
-  connect(m_filenameManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(stringChanged(QtProperty*)));
-  connect(m_formulaManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(stringChanged(QtProperty*)));
-
-    /* Create function group */
-
-  QtProperty* functionsGroup = m_groupManager->addProperty("Functions");
-
-     /* Create input - output properties */
-
-  QtProperty* settingsGroup = m_groupManager->addProperty("Settings");
-
-  m_workspace = m_enumManager->addProperty("Workspace");
-  m_workspaceIndex = m_intManager->addProperty("Workspace Index");
-  m_startX = addDoubleProperty("StartX");
-  m_endX = addDoubleProperty("EndX");
-  m_output = m_stringManager->addProperty("Output");
-  m_minimizer = m_enumManager->addProperty("Minimizer");
-
-  m_minimizers << "Levenberg-Marquardt"
-               << "Simplex"
-               << "Conjugate gradient (Fletcher-Reeves imp.)"
-               << "Conjugate gradient (Polak-Ribiere imp.)"
-               << "BFGS";
-  m_enumManager->setEnumNames(m_minimizer, m_minimizers);
-
-  m_costFunction = m_enumManager->addProperty("Cost function");
-  m_costFunctions << "Least squares"
-                  << "Ignore positive peaks";
-  m_enumManager->setEnumNames(m_costFunction,m_costFunctions);
-  m_plotDiff = m_boolManager->addProperty("Plot Difference");
-  bool plotDiff = settings.value("Plot Difference",QVariant(true)).toBool();
-  m_boolManager->setValue(m_plotDiff,plotDiff);
-
-  settingsGroup->addSubProperty(m_workspace);
-  settingsGroup->addSubProperty(m_workspaceIndex);
-  settingsGroup->addSubProperty(m_startX);
-  settingsGroup->addSubProperty(m_endX);
-  settingsGroup->addSubProperty(m_output);
-  settingsGroup->addSubProperty(m_minimizer);
-  settingsGroup->addSubProperty(m_costFunction);
-  settingsGroup->addSubProperty(m_plotDiff);
-
-     /* Create editors and assign them to the managers */
-
-  QtCheckBoxFactory *checkBoxFactory = new QtCheckBoxFactory(w);
-  QtEnumEditorFactory *comboBoxFactory = new QtEnumEditorFactory(w);
-  QtSpinBoxFactory *spinBoxFactory = new QtSpinBoxFactory(w);
-  //QtDoubleSpinBoxFactory *doubleSpinBoxFactory = new QtDoubleSpinBoxFactory(w); //unused now
-  DoubleEditorFactory *doubleEditorFactory = new DoubleEditorFactory(w);
-  QtLineEditFactory *lineEditFactory = new QtLineEditFactory(w);
-  StringDialogEditorFactory* stringDialogEditFactory = new StringDialogEditorFactory(w);
-  FormulaDialogEditorFactory* formulaDialogEditFactory = new FormulaDialogEditorFactory(w);
-
-  m_browser = new QtTreePropertyBrowser();
-  m_browser->setFactoryForManager(m_enumManager, comboBoxFactory);
-  m_browser->setFactoryForManager(m_boolManager, checkBoxFactory);
-  m_browser->setFactoryForManager(m_intManager, spinBoxFactory);
-  //m_browser->setFactoryForManager(m_doubleManager, doubleSpinBoxFactory);
-  m_browser->setFactoryForManager(m_doubleManager, doubleEditorFactory);
-  m_browser->setFactoryForManager(m_stringManager, lineEditFactory);
-  m_browser->setFactoryForManager(m_filenameManager, stringDialogEditFactory);
-  m_browser->setFactoryForManager(m_formulaManager, formulaDialogEditFactory);
-
-  updateDecimals();
-
-  m_functionsGroup = m_browser->addProperty(functionsGroup);
-  m_settingsGroup = m_browser->addProperty(settingsGroup);
-
-  QVBoxLayout* layout = new QVBoxLayout(w);
-  QGridLayout* buttonsLayout = new QGridLayout();
-
-  m_btnFit = new QPushButton("Fit");
-  connect(m_btnFit,SIGNAL(clicked()),this,SLOT(fit()));
-
-  m_btnUnFit = new QPushButton("Undo Fit");
-  connect(m_btnUnFit,SIGNAL(clicked()),this,SLOT(undoFit()));
-
-  QPushButton* btnClear = new QPushButton("Clear all");
-  connect(btnClear,SIGNAL(clicked()),this,SLOT(clear()));
-
-  m_btnSeqFit = new QPushButton("Sequential fit");
-  connect(m_btnSeqFit,SIGNAL(clicked()),this,SLOT(sequentialFit()));
-
-  m_btnFindPeaks = new QPushButton("Find peaks");
-  connect(m_btnFindPeaks,SIGNAL(clicked()),this,SLOT(findPeaks()));
-
-  m_btnPlotGuess = new QPushButton("Plot guess");
-  connect(m_btnPlotGuess,SIGNAL(clicked()),this,SLOT(plotOrRemoveGuessAll()));
-  m_btnPlotGuess->setEnabled(false);
-
-  m_tip = new QLabel("",w);
-
-  buttonsLayout->addWidget(m_btnFit,0,0);
-  buttonsLayout->addWidget(m_btnUnFit,0,1);
-  buttonsLayout->addWidget(btnClear,0,2);
-  buttonsLayout->addWidget(m_btnSeqFit,1,0);
-  buttonsLayout->addWidget(m_btnFindPeaks,1,1);
-  buttonsLayout->addWidget(m_btnPlotGuess,1,2);
-
-  layout->addLayout(buttonsLayout);
-  layout->addWidget(m_tip);
-  layout->addWidget(m_browser);
-
-  setWidget(w);
-
-  m_browser->setContextMenuPolicy(Qt::CustomContextMenu);
-  connect(m_browser, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(popupMenu(const QPoint &)));
-  connect(m_browser, SIGNAL(currentItemChanged(QtBrowserItem*)), this, SLOT(currentItemChanged(QtBrowserItem*)));
-
-  createCompositeFunction();
-
-  m_changeSlotsEnabled = true;
-
-}
-
-/// Destructor
-FitPropertyBrowser::~FitPropertyBrowser()
-{
-  QSettings settings;
-  settings.beginGroup("Mantid/FitBrowser");
-  bool plotDiff = m_boolManager->value(m_plotDiff);
-  settings.setValue("Plot Difference",plotDiff);
-  if (m_compositeFunction) delete m_compositeFunction;
-}
-
-/// Get handler to the root composite function
-PropertyHandler* FitPropertyBrowser::getHandler()const
-{
-  return static_cast<PropertyHandler*>(m_compositeFunction->getHandler());
-}
-
-PropertyHandler* FitPropertyBrowser::addFunction(const std::string& fnName)
-{
-  PropertyHandler* h = getHandler()->addFunction(fnName);
-  emit functionChanged();
-  return h;
-}
-
-/** Slot. Called to add a new function
- */
-void FitPropertyBrowser::addFunction()
-{
-  QtBrowserItem * ci = m_browser->currentItem();
-  // Find the function which has ci as its top browser item 
-  const Mantid::API::CompositeFunction* cf = getHandler()->findCompositeFunction(ci);
-  if ( !cf ) return;
-  int i = m_registeredFunctions.indexOf(QString::fromStdString(m_defaultFunction));
-  bool ok = false;
-  QString fnName = 
-    QInputDialog::getItem(this, "MantidPlot - Fit", "Select function type", m_registeredFunctions,i,false,&ok);
-  if (ok)
-  {
-    PropertyHandler* h = getHandler()->findHandler(cf);
-    h->addFunction(fnName.toStdString());
-  }
-  emit functionChanged();
-}
-
-/// Create CompositeFunction
-void FitPropertyBrowser::createCompositeFunction(const QString& str)
-{
- if (m_compositeFunction)
-  {
-    emit functionRemoved();
-    delete m_compositeFunction;
-    m_autoBackground = NULL;
-  }
-  if (str.isEmpty())
-  {
-    m_compositeFunction = new Mantid::API::CompositeFunctionMW();
-  }
-  else
-  {
-    Mantid::API::IFitFunction* f = Mantid::API::FunctionFactory::Instance().createInitialized(str.toStdString());
-    if (!f)
-    {
-      createCompositeFunction();
-      return;
-    }
-    Mantid::API::CompositeFunction* cf = dynamic_cast<Mantid::API::CompositeFunction*>(f);
-    if (!cf || cf->name() != "CompositeFunctionMW")
-    {
-      m_compositeFunction = new Mantid::API::CompositeFunctionMW();
-      m_compositeFunction->addFunction(f);
-    }
-    else
-    {
-      m_compositeFunction = cf;
-    }
-  }
-  setWorkspace(m_compositeFunction);
-
-  PropertyHandler* h = new PropertyHandler(m_compositeFunction,NULL,this);
-  m_compositeFunction->setHandler(h);
-  setCurrentFunction(h);
-
-  if (m_auto_back)
-  {
-    addAutoBackground();
-  }
-
-  disableUndo();
-  setFitEnabled(m_compositeFunction->nFunctions() > 0);
-  emit functionChanged();
-}
-
-void FitPropertyBrowser::popupMenu(const QPoint &)
-{
-  QtBrowserItem * ci = m_browser->currentItem();
-  if (!ci) return;
-  QMenu *menu = new QMenu(m_appWindow);
-  QAction *action;
-
-  bool isFunctionsGroup = ci == m_functionsGroup;
-  bool isSettingsGroup = ci == m_settingsGroup;
-  bool isASetting = ci->parent() == m_settingsGroup;
-  bool isFunction = getHandler()->findFunction(ci) != NULL;
-  bool isCompositeFunction = isFunction && getHandler()->findCompositeFunction(ci);
-
-  //if (!isFunction)
-  //{
-  //  const Mantid::API::IFitFunction* h = getHandler()->findFunction(ci);
-  //}
-
-  PropertyHandler* h = getHandler()->findHandler(ci->property());
-
-  if (isFunctionsGroup)
-  {
-    action = new QAction("Add function",this);
-    connect(action,SIGNAL(triggered()),this,SLOT(addFunction()));
-    menu->addAction(action);
-
-    if (m_peakToolOn)
-    {
-      if (h && h->hasPlot())
-      {
-        action = new QAction("Remove plot",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(removeGuessAll()));
-        menu->addAction(action);
-      }
-      else
-      {
-        action = new QAction("Plot",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(plotGuessAll()));
-        menu->addAction(action);
-      }
-    }
-
-    menu->addSeparator();
-
-    action = new QAction("Save",this);
-    connect(action,SIGNAL(triggered()),this,SLOT(saveFunction()));
-    menu->addAction(action);
-
-    action = new QAction("Load",this);
-    connect(action,SIGNAL(triggered()),this,SLOT(loadFunction()));
-    menu->addAction(action);
-
-    action = new QAction("Copy",this);
-    connect(action,SIGNAL(triggered()),this,SLOT(copy()));
-    menu->addAction(action);
-
-    //action = new QAction("Paste",this);
-    //connect(action,SIGNAL(triggered()),this,SLOT(paste()));
-    //menu->addAction(action);
-
-    menu->addSeparator();
-  }
-  else if (isFunctionsGroup || isSettingsGroup || isASetting)
-  {
-    if (isFitEnabled())
-    {
-      action = new QAction("Fit",this);
-      connect(action,SIGNAL(triggered()),this,SLOT(fit()));
-      menu->addAction(action);
-    }
-
-    if (isUndoEnabled())
-    {
-      action = new QAction("Undo Fit",this);
-      connect(action,SIGNAL(triggered()),this,SLOT(undoFit()));
-      menu->addAction(action);
-    }
-
-    action = new QAction("Clear all",this);
-    connect(action,SIGNAL(triggered()),this,SLOT(clear()));
-    menu->addAction(action);
-
-  }
-  else if (isFunction)
-  {
-    if (isCompositeFunction)
-    {
-      action = new QAction("Add function",this);
-      connect(action,SIGNAL(triggered()),this,SLOT(addFunction()));
-      menu->addAction(action);
-    }
-
-    action = new QAction("Remove",this);
-    connect(action,SIGNAL(triggered()),this,SLOT(deleteFunction()));
-    menu->addAction(action);
-
-    if (m_peakToolOn)
-    {
-      if (h && h->hasPlot())
-      {
-        action = new QAction("Remove plot",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(removeGuessCurrent()));
-        menu->addAction(action);
-      }
-      else
-      {
-        action = new QAction("Plot",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(plotGuessCurrent()));
-        menu->addAction(action);
-      }
-    }
-
-    menu->addSeparator();
-  }
-  else if (h)
-  {
-    bool isParameter = h->isParameter(ci->property());
-    bool isTie = !isParameter && ci->property()->propertyName() == "Tie";
-    bool isLowerBound = !isParameter && ci->property()->propertyName() == "Lower Bound";
-    bool isUpperBound = !isParameter && ci->property()->propertyName() == "Upper Bound";
-    bool isType = isParameter && ci->property()->propertyName() == "Type";
-    if (isType)
-    {
-      isParameter = false;
-    }
-
-    if (isTie)
-    {
-      //menu->addSeparator();
-      action = new QAction("Remove",this);
-      connect(action,SIGNAL(triggered()),this,SLOT(deleteTie()));
-      menu->addAction(action);
-    }
-    else if (isLowerBound || isUpperBound)
-    {
-      action = new QAction("Remove",this);
-      connect(action,SIGNAL(triggered()),this,SLOT(removeBounds()));
-      menu->addAction(action);
-    }
-    else if (count() > 0 && isParameter)
-    {
-      bool hasTies;
-      bool hasBounds;
-      hasConstraints(ci->property(),hasTies,hasBounds);
-
-      if (!hasTies && !hasBounds)
-      {
-        action = new QAction("Fix",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(addFixTie()));
-        menu->addAction(action);
-      }
-
-      if (!hasTies)
-      {
-        QMenu *constraintMenu = menu->addMenu("Constraint");
-
-        QMenu* detailMenu = constraintMenu->addMenu("Lower Bound");
-
-        action = new QAction("10%",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(addLowerBound10()));
-        detailMenu->addAction(action);
-
-        action = new QAction("50%",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(addLowerBound50()));
-        detailMenu->addAction(action);
-
-        action = new QAction("Custom",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(addLowerBound()));
-        detailMenu->addAction(action);
-        detailMenu = constraintMenu->addMenu("Upper Bound");
-
-        action = new QAction("10%",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(addUpperBound10()));
-        detailMenu->addAction(action);
-
-        action = new QAction("50%",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(addUpperBound50()));
-        detailMenu->addAction(action);
-
-        action = new QAction("Custom",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(addUpperBound()));
-        detailMenu->addAction(action);
-        detailMenu = constraintMenu->addMenu("Both Bounds");
-
-        action = new QAction("10%",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(addBothBounds10()));
-        detailMenu->addAction(action);
-
-        action = new QAction("50%",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(addBothBounds50()));
-        detailMenu->addAction(action);
-
-        action = new QAction("Custom",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(addBothBounds()));
-        detailMenu->addAction(action);
-      }
-
-      if (hasBounds)
-      {
-        action = new QAction("Remove constraints",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(removeBounds()));
-        menu->addAction(action);
-      }
-
-      if (!hasTies && !hasBounds)
-      {
-        if (count() == 1)
-        {
-          action = new QAction("Tie",this);
-          connect(action,SIGNAL(triggered()),this,SLOT(addTie()));
-          menu->addAction(action);
-        }
-        else
-        {
-          QMenu* detail = menu->addMenu("Tie");
-
-          action = new QAction("To function",this);
-          connect(action,SIGNAL(triggered()),this,SLOT(addTieToFunction()));
-          detail->addAction(action);
-
-          action = new QAction("Custom Tie",this);
-          connect(action,SIGNAL(triggered()),this,SLOT(addTie()));
-          detail->addAction(action);
-        }
-      }
-      else if (hasTies)
-      {
-        action = new QAction("Remove tie",this);
-        connect(action,SIGNAL(triggered()),this,SLOT(deleteTie()));
-        menu->addAction(action);
-      }
-    }
-  }
-
-  menu->popup(QCursor::pos());
-}
-
-/** Slot. Called to remove a function
- */
-void FitPropertyBrowser::deleteFunction()
-{
-  QtBrowserItem* ci = m_browser->currentItem();
-  PropertyHandler* h = getHandler()->findHandler(ci->property());
-  if (h)
-  {
-    getHandler()->removePlot();
-    h->removeFunction();
-    compositeFunction()->checkFunction();
-    emit functionRemoved();
-    emit functionChanged();
-  }
-}
-
-//***********************************************************************************//
-
-
-// Get the default function name
-std::string FitPropertyBrowser::defaultFunctionType()const
-{
-  return m_defaultFunction;
-}
-
-// Get the default function name
-void FitPropertyBrowser::setDefaultFunctionType(const std::string& fnType)
-{
-  m_defaultFunction = fnType;
-}
-
-/// Get the default peak type
-std::string FitPropertyBrowser::defaultPeakType()const
-{
-  return m_defaultPeak;
-}
-/// Set the default peak type
-void FitPropertyBrowser::setDefaultPeakType(const std::string& fnType)
-{
-  m_defaultPeak = fnType;
-  setDefaultFunctionType(fnType);
-  Mantid::Kernel::ConfigService::Instance().setString("curvefitting.defaultPeak", fnType);
-}
-/// Get the default background type
-std::string FitPropertyBrowser::defaultBackgroundType()const
-{
-  return m_defaultBackground;
-}
-/// Set the default background type
-void FitPropertyBrowser::setDefaultBackgroundType(const std::string& fnType)
-{
-  m_defaultBackground = fnType;
-  setDefaultFunctionType(fnType);
-}
-
-
-/// Get the input workspace name
-std::string FitPropertyBrowser::workspaceName()const
-{
-  int i = m_enumManager->value(m_workspace);
-  std::string res = "";
-  if (i >= 0)
-  {
-    res = m_workspaceNames[i].toStdString();
-  }
-  return res;
-}
-
-/// Set the input workspace name
-void FitPropertyBrowser::setWorkspaceName(const QString& wsName)
-{
-  int i = m_workspaceNames.indexOf(wsName);
-  if (i >= 0)
-  {
-    m_enumManager->setValue(m_workspace,i);
-  }
-  if (!isWorkspaceAGroup())
-  {
-    m_groupMember = wsName.toStdString();
-  }
-}
-
-/// Get workspace index
-int FitPropertyBrowser::workspaceIndex()const
-{
-  return m_intManager->value(m_workspaceIndex);
-}
-
-/// Set workspace index
-void FitPropertyBrowser::setWorkspaceIndex(int i)
-{
-  m_intManager->setValue(m_workspaceIndex,i);
-}
-
-/// Get the output name
-std::string FitPropertyBrowser::outputName()const
-{
-  return m_stringManager->value(m_output).toStdString();
-}
-
-/// Get the output name
-void FitPropertyBrowser::setOutputName(const std::string& name)
-{
-  m_stringManager->setValue(m_output,QString::fromStdString(name));
-}
-
-/// Get the minimizer
-std::string FitPropertyBrowser::minimizer()const
-{
-  int i = m_enumManager->value(m_minimizer);
-  return m_minimizers[i].toStdString();
-}
-
-/// Get the cost function
-std::string FitPropertyBrowser::costFunction()const
-{
-  int i = m_enumManager->value(m_costFunction);
-  return m_costFunctions[i].toStdString();
-}
-
-/** Called when the function name property changed
- * @param prop :: A pointer to the function name property m_functionName
- */
-void FitPropertyBrowser::enumChanged(QtProperty* prop)
-{
-  if ( ! m_changeSlotsEnabled ) return;
-
-  if (prop == m_workspace)
-  {
-    if (m_guessOutputName)
-    {
-      if (isWorkspaceAGroup())
-      {
-        m_stringManager->setValue(m_output,QString::fromStdString(workspaceName()+"_params"));
-      }
-      else
-      {
-        m_stringManager->setValue(m_output,QString::fromStdString(workspaceName()));
-      }
-    }
-    if (isWorkspaceAGroup())
-    {
-      setLogValue();
-    }
-    else
-    {
-      m_groupMember = workspaceName();
-      removeLogValue();
-    }
-    emit workspaceNameChanged(QString::fromStdString(workspaceName()));
-  }
-  else if (prop->propertyName() == "Type")
-  {
-      disableUndo();
-      PropertyHandler* h = getHandler()->findHandler(prop);
-      if (!h) return;
-      if (!h->parentHandler()) return;
-      Mantid::API::IFitFunction* f = h->changeType(prop);
-      if (f) setCurrentFunction(f);
-      emit functionChanged();
-  }
-}
-
-/** Called when a bool property changed
- * @param prop :: A pointer to the property 
- */
-void FitPropertyBrowser::boolChanged(QtProperty*)
-{
-  if ( ! m_changeSlotsEnabled ) return;
-
-}
-
-/** Called when an int property changed
- * @param prop :: A pointer to the property 
- */
-void FitPropertyBrowser::intChanged(QtProperty* prop)
-{
-  if ( ! m_changeSlotsEnabled ) return;
-
-  if (prop == m_workspaceIndex)
-  {
-    Mantid::API::MatrixWorkspace_sptr ws = 
-      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-      m_appWindow->mantidUI->getWorkspace(QString::fromStdString(workspaceName()))
-      );
-    if (!ws)
-    {
-      setWorkspaceIndex(0);
-      return;
-    }
-    int n = ws->getNumberHistograms();
-    int wi = workspaceIndex();
-    if (wi < 0)
-    {
-      setWorkspaceIndex(0);
-    }
-    else if (wi >= n)
-    {
-      setWorkspaceIndex(n-1);
-    }
-    emit workspaceIndexChanged(wi);
-  }
-  else
-  {// it could be an attribute
-    PropertyHandler* h = getHandler()->findHandler(prop);
-    if (!h) return;
-    h->setAttribute(prop);
-  }
-}
-
-/** Called when a double property changed
- * @param prop :: A pointer to the property 
- */
-void FitPropertyBrowser::doubleChanged(QtProperty* prop)
-{
-  if ( ! m_changeSlotsEnabled ) return;
-
-  double value = m_doubleManager->value(prop);
-  if (prop == m_startX )
-  {
-    // call setWorkspace to change maxX in functions
-    setWorkspace(m_compositeFunction);
-    getHandler()->setAttribute("StartX",value);
-    emit startXChanged(startX());
-    return;
-  }
-  else if (prop == m_endX )
-  {
-    // call setWorkspace to change minX in functions
-    setWorkspace(m_compositeFunction);
-    getHandler()->setAttribute("EndX",value);
-    emit endXChanged(endX());
-    return;
-  }
-  else if(getHandler()->setParameter(prop))
-  {
-    return;
-  }
-  else
-  {// check if it is a constraint
-    PropertyHandler* h = getHandler()->findHandler(prop);
-    if (!h) return;
-
-    QtProperty* parProp = h->getParameterProperty(prop);
-    if (parProp)
-    {
-      if (prop->propertyName() == "LowerBound")
-      {
-        double loBound = m_doubleManager->value(prop);
-        h->addConstraint(parProp,true,false,loBound,0);
-      }
-      else if (prop->propertyName() == "UpperBound")
-      {
-        double upBound = m_doubleManager->value(prop);
-        h->addConstraint(parProp,false,true,0,upBound);
-      }
-    }
-    else
-    {// it could be an attribute
-      h->setAttribute(prop);
-    }
-  }
-}
-/** Called when a string property changed
- * @param prop :: A pointer to the property 
- */
-void FitPropertyBrowser::stringChanged(QtProperty* prop)
-{
-  if ( ! m_changeSlotsEnabled ) return;
-
-  if (prop == m_output)
-  {
-    std::string oName = outputName();
-    if (oName.find_first_not_of(' ') == std::string::npos)
-    {
-      setOutputName("");
-    }
-    else if (workspaceName() == oName || oName.empty())
-    {
-      m_guessOutputName = true;
-    }
-    else
-    {
-      m_guessOutputName = false;
-    }
-  }
-  else if (prop->propertyName() == "Tie")
-  {
-    PropertyHandler* h = getHandler()->findHandler(prop);
-    if (!h) return;
-
-    QtProperty* parProp = h->getParameterProperty(prop);
-    if (!parProp) return;
-
-    QString parName = h->functionPrefix()+"."+parProp->propertyName();
-
-    QString str = m_stringManager->value(prop);
-    Mantid::API::ParameterTie* tie = 
-      new Mantid::API::ParameterTie(compositeFunction(),parName.toStdString());
-    try
-    {
-      tie->set(str.toStdString());
-      h->addTie(parName+"="+str);
-    }
-    catch(...){std::cerr<<"Failed\n";}
-    delete tie;
-  }
-  else if (getHandler()->setAttribute(prop))
-  {// setting an attribute may change function parameters
-    emit functionChanged();
-    return;
-  }
-}
-
-/** Called when a filename property changed
- * @param prop :: A pointer to the property 
- */
-void FitPropertyBrowser::filenameChanged(QtProperty* prop)
-{
-  if ( ! m_changeSlotsEnabled ) return;
-
-  if (getHandler()->setAttribute(prop))
-  {
-    return;
-  }
-}
-// Centre of the current peak
-double FitPropertyBrowser::centre()const
-{
-  if (m_currentHandler && m_currentHandler->pfun())
-  {
-    return m_currentHandler->pfun()->centre();
-  }
-  return 0;
-}
-
-/** Set centre of the current peak
- * @param value :: The new centre value
- */
-void FitPropertyBrowser::setCentre(double value)
-{
-  if (m_currentHandler)
-  {
-    m_currentHandler->setCentre(value);
-  }
-}
-
-// Height of the current peak
-double FitPropertyBrowser::height()const
-{
-  if (m_currentHandler && m_currentHandler->pfun())
-  {
-    return m_currentHandler->pfun()->height();
-  }
-  return 0.;
-}
-
-/** Set height of the current peak
- * @param value :: The new height value
- */
-void FitPropertyBrowser::setHeight(double value)
-{
-  if (m_currentHandler)
-  {
-    m_currentHandler->setHeight(value);
-  }
-}
-
-// Width of the current peak
-double FitPropertyBrowser::width()const
-{
-  if (m_currentHandler && m_currentHandler->pfun())
-  {
-    return m_currentHandler->pfun()->width();
-  }
-  return 0;
-}
-
-/** Set width of the current peak
- * @param value :: The new width value
- */
-void FitPropertyBrowser::setWidth(double value)
-{
-  if (m_currentHandler)
-  {
-    m_currentHandler->setWidth(value);
-  }
-}
-
-/// Get the registered function names
-void FitPropertyBrowser::populateFunctionNames()
-{
-  const std::vector<std::string> names = Mantid::API::FunctionFactory::Instance().getKeys();
-  m_registeredFunctions.clear();
-  m_registeredPeaks.clear();
-  m_registeredBackgrounds.clear();
-  for(size_t i=0;i<names.size();i++)
-  {
-    std::string fnName = names[i];
-    QString qfnName = QString::fromStdString(fnName);
-    m_registeredFunctions << qfnName;
-    boost::shared_ptr<Mantid::API::IFitFunction> f = boost::shared_ptr<Mantid::API::IFitFunction>(
-      Mantid::API::FunctionFactory::Instance().createFitFunction(fnName));
-    Mantid::API::IPeakFunction* pf = dynamic_cast<Mantid::API::IPeakFunction*>(f.get());
-    //Mantid::API::CompositeFunction* cf = dynamic_cast<Mantid::API::CompositeFunction*>(f.get());
-    if (pf)
-    {
-      m_registeredPeaks << qfnName;
-    }
-    else if (dynamic_cast<Mantid::API::IBackgroundFunction*>(f.get()))
-    {
-      m_registeredBackgrounds << qfnName;
-    }
-    else
-    {
-      m_registeredOther << qfnName;
-    }
-  }
-}
-
-
-/// Get number of functions in CompositeFunction
-int FitPropertyBrowser::count()const
-{
-  return m_compositeFunction->nFunctions();
-}
-
-/// Get the current function
-PropertyHandler* FitPropertyBrowser::currentHandler()const
-{
-  return m_currentHandler;
-}
-
-/** Set new current function
- * @param h :: New current function
- */
-void FitPropertyBrowser::setCurrentFunction(PropertyHandler* h)const
-{
-  m_currentHandler = h;
-  if (m_currentHandler)
-  {
-    m_browser->setCurrentItem(m_currentHandler->item());
-    emit currentChanged();
-  }
-}
-
-/** Set new current function
- * @param f :: New current function
- */
-void FitPropertyBrowser::setCurrentFunction(const Mantid::API::IFitFunction* f)const
-{
-  setCurrentFunction(getHandler()->findHandler(f));
-}
-
-#include "../FitDialog.h"
-/**
- * Creates an instance of Fit algorithm, sets its properties and launches it.
- */
-void FitPropertyBrowser::fit()
-{
-  std::string wsName = workspaceName();
-  if (wsName.empty())
-  {
-    m_appWindow->mantidUI->showCritical("Workspace name is not set");
-    return;
-  }
-  try
-  {
-    m_initialParameters.resize(compositeFunction()->nParams());
-    for(int i=0;i<compositeFunction()->nParams();i++)
-    {
-      m_initialParameters[i] = compositeFunction()->getParameter(i);
-    }
-    m_btnUnFit->setEnabled(true);
-
-    std::string funStr;
-    if (m_compositeFunction->nFunctions() > 1)
-    {
-      funStr = *m_compositeFunction;
-    }
-    else
-    {
-      funStr = *(m_compositeFunction->getFunction(0));
-    }
-
-    if (isWorkspaceAGroup())
-    {
-      Mantid::API::IAlgorithm_sptr alg = 
-        Mantid::API::AlgorithmManager::Instance().create("PlotPeakByLogValue");
-      alg->initialize();
-      alg->setPropertyValue("InputWorkspace",wsName);
-      alg->setProperty("WorkspaceIndex",workspaceIndex());
-      alg->setProperty("StartX",startX());
-      alg->setProperty("EndX",endX());
-      alg->setPropertyValue("OutputWorkspace",outputName());
-      alg->setPropertyValue("Function",funStr);
-      alg->setPropertyValue("LogValue",getLogValue());
-      //alg->setPropertyValue("Minimizer",minimizer());
-      //alg->setPropertyValue("CostFunction",costFunction());
-
-      observeFinish(alg);
-      alg->executeAsync();
-    }
-    else
-    {
-      Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("Fit");
-      alg->initialize();
-      alg->setPropertyValue("InputWorkspace",wsName);
-      alg->setProperty("WorkspaceIndex",workspaceIndex());
-      alg->setProperty("StartX",startX());
-      alg->setProperty("EndX",endX());
-      alg->setPropertyValue("Output",outputName());
-      alg->setPropertyValue("Function",funStr);
-      alg->setPropertyValue("Minimizer",minimizer());
-      alg->setPropertyValue("CostFunction",costFunction());
-
-      observeFinish(alg);
-      alg->executeAsync();
-    }
-  }
-  catch(std::exception& e)
-  {
-    QString msg = "Fit algorithm failed.\n\n"+QString(e.what())+"\n";
-    m_appWindow->mantidUI->showCritical(msg);
-  }
-}
-
-void FitPropertyBrowser::finishHandle(const Mantid::API::IAlgorithm* alg)
-{
-  std::string out = alg->getProperty("OutputWorkspace");
-  getFitResults();
-  if (!isWorkspaceAGroup())
-  {
-    emit algorithmFinished(QString::fromStdString(out));
-  }
-}
-
-/// Get and store available workspace names
-void FitPropertyBrowser::populateWorkspaceNames()
-{
-  m_workspaceNames.clear();
-  QStringList tmp = m_appWindow->mantidUI->getWorkspaceNames();
-  for(int i=0;i<tmp.size();i++)
-  {
-    Mantid::API::Workspace_sptr ws = m_appWindow->mantidUI->getWorkspace(tmp[i]);
-    if (isWorkspaceValid(ws))
-    {
-      m_workspaceNames.append(tmp[i]);
-    }
-  }
-  m_enumManager->setEnumNames(m_workspace, m_workspaceNames);
-}
-
-void FitPropertyBrowser::workspace_added(const QString &wsName, Mantid::API::Workspace_sptr ws)
-{
-  if ( !isWorkspaceValid(ws) ) return;
-  QString oldName = QString::fromStdString(workspaceName());
-  int i = m_workspaceNames.indexOf(wsName);
-  if (i < 0)
-  {
-    m_workspaceNames.append(wsName);
-    m_workspaceNames.sort();
-  }
-  m_enumManager->setEnumNames(m_workspace, m_workspaceNames);
-  i = m_workspaceNames.indexOf(oldName);
-  if (i >= 0)
-  {
-    m_enumManager->setValue(m_workspace,i);
-  }
-}
-
-void FitPropertyBrowser::workspace_removed(const QString &wsName)
-{
-  QString oldName = QString::fromStdString(workspaceName());
-  int i = m_workspaceNames.indexOf(wsName);
-  if (i >= 0)
-  {
-    m_workspaceNames.removeAt(i);
-  }
-  m_enumManager->setEnumNames(m_workspace, m_workspaceNames);
-  i = m_workspaceNames.indexOf(oldName);
-  if (i >= 0)
-  {
-    m_enumManager->setValue(m_workspace,i);
-  }
-}
-
-void FitPropertyBrowser::init()
-{
-  populateFunctionNames();
-  populateWorkspaceNames();
-  connect(m_appWindow->mantidUI,SIGNAL(workspace_added(const QString &, Mantid::API::Workspace_sptr)),
-    this,SLOT(workspace_added(const QString &, Mantid::API::Workspace_sptr)));
-  connect(m_appWindow->mantidUI,SIGNAL(workspace_removed(const QString &)),
-    this,SLOT(workspace_removed(const QString &)));
-}
-
-/** Check if the workspace can be used in the fit. The accepted types are
-  * MatrixWorkspaces same size
-  * @param ws :: The workspace
-  */
-bool FitPropertyBrowser::isWorkspaceValid(Mantid::API::Workspace_sptr ws)const
-{
-  if (dynamic_cast<Mantid::API::MatrixWorkspace*>(ws.get()) != 0)
-  {
-    return true;
-  }
-  else
-  {
-    return false;
-  }
-}
-
-bool FitPropertyBrowser::isWorkspaceAGroup()const
-{
-  // MG: Disabled as there is an issue with replacing workspace groups and the browser
-  return false;
-}
-
-/// Is the current function a peak?
-bool FitPropertyBrowser::isPeak()const
-{
-  if (count() == 0)
-  {
-    return false;
-  }
-  return m_currentHandler && m_currentHandler->pfun();
-}
-
-/// Get the start X
-double FitPropertyBrowser::startX()const
-{
-  return m_doubleManager->value(m_startX);
-}
-
-/// Set the start X
-void FitPropertyBrowser::setStartX(double value)
-{
-  m_doubleManager->setValue(m_startX,value);
-}
-
-/// Get the end X
-double FitPropertyBrowser::endX()const
-{
-  return m_doubleManager->value(m_endX);
-}
-
-/// Set the end X
-void FitPropertyBrowser::setEndX(double value)
-{
-  m_doubleManager->setValue(m_endX,value);
-}
-
-QtBrowserItem* FitPropertyBrowser::findItem(QtBrowserItem* parent,QtProperty* prop)const
-{
-  QList<QtBrowserItem*> children = parent->children();
-  QtBrowserItem* res = 0;
-  for(int i=0;i<children.size();i++)
-  {
-    if (children[i]->property() == prop)
-    {
-      return children[i];
-    }
-    QList<QtBrowserItem*> grand_children = children[i]->children();
-    if (grand_children.size() > 0) res = findItem(children[i],prop);
-    if (res) return res;
-  }
-  return 0;
-}
-
-/**
- * Slot. Responds to changing the current item
- */
-void FitPropertyBrowser::currentItemChanged(QtBrowserItem * current )
-{
-  if (current)
-  {
-    m_currentHandler = getHandler()->findHandler(current->property());
-  }
-  else
-  {
-    m_currentHandler = NULL;
-  }
-  emit currentChanged();
-}
-
-/** Update the function parameter properties. 
- */
-void FitPropertyBrowser::updateParameters()
-{
-  getHandler()->updateParameters();
-}
-
-/**
- * Slot. Removes all functions.
- */
-void FitPropertyBrowser::clear()
-{
-  getHandler()->removeAllPlots();
-  clearBrowser();
-  createCompositeFunction();
-  emit functionCleared();
-}
-
-void FitPropertyBrowser::clearBrowser()
-{
-  QList<QtProperty*> props = m_functionsGroup->property()->subProperties();
-  QtProperty* prop;
-  foreach(prop,props)
-  {
-    m_functionsGroup->property()->removeSubProperty(prop);
-  }
-}
-
-/// Set the parameters to the fit outcome
-void FitPropertyBrowser::getFitResults()
-{
-  if (isWorkspaceAGroup())
-  {
-    std::string wsName = outputName();
-    Mantid::API::ITableWorkspace_sptr ws = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(
-      Mantid::API::AnalysisDataService::Instance().retrieve(wsName) );
-    if (ws)
-    {
-      if ((ws->columnCount() - 1)/2 != compositeFunction()->nParams()) return;
-      Mantid::API::WorkspaceGroup_sptr wsg = boost::dynamic_pointer_cast<Mantid::API::WorkspaceGroup>(
-        Mantid::API::AnalysisDataService::Instance().retrieve(workspaceName()) );
-      std::vector<std::string> names = wsg->getNames();
-      std::vector<std::string>::iterator it = 
-        std::find(names.begin(),names.end(),m_groupMember);
-      if (it == names.end()) return;
-      int row = int(it - names.begin()) - 1;// take into account the group name
-      if (row >= ws->rowCount()) return;
-      for(int i=0;i<compositeFunction()->nParams();++i)
-      {
-        compositeFunction()->setParameter(i,ws->Double(row,2*i+1));
-      }
-      updateParameters();
-      plotGuessAll();
-    }
-  }
-  else
-  {
-    std::string wsName = outputName() + "_Parameters";
-    Mantid::API::ITableWorkspace_sptr ws = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(
-      Mantid::API::AnalysisDataService::Instance().retrieve(wsName) );
-
-    if (ws)
-    {
-      Mantid::API::TableRow row = ws->getFirstRow();
-      do
-      {
-        try
-        {
-          std::string name;
-          double value;
-          row >> name >> value;
-          // In case of a single function Fit doesn't create a CompositeFunction
-          if (count() == 1)
-          {
-            name.insert(0,"f0.");
-          }
-          compositeFunction()->setParameter(name,value);
-        }
-        catch(...)
-        {
-          // do nothing
-        }
-      }
-      while(row.next());
-      updateParameters();
-    }
-  }
-}
-
-/**
- * Slot. Undoes the fit: restores the parameters to their initial values.
- */
-void FitPropertyBrowser::undoFit()
-{
-  if (static_cast<int>(m_initialParameters.size()) == compositeFunction()->nParams())
-  {
-    for(int i=0;i<compositeFunction()->nParams();i++)
-    {
-      compositeFunction()->setParameter(i,m_initialParameters[i]);
-    }
-    updateParameters();
-  }
-  disableUndo();
-}
-
-/// disable undo when the function changes
-void FitPropertyBrowser::disableUndo()
-{
-  m_initialParameters.clear();
-  m_btnUnFit->setEnabled(false);
-}
-
-/// Tells if undo can be done
-bool FitPropertyBrowser::isUndoEnabled()const
-{
-  return m_initialParameters.size() && compositeFunction()->nParams() == static_cast<int>(m_initialParameters.size());
-}
-
-/// Enable/disable the Fit button;
-void FitPropertyBrowser::setFitEnabled(bool yes)
-{
-  m_btnFit->setEnabled(yes);
-  m_btnSeqFit->setEnabled(yes);
-}
-
-/// Returns true if the function is ready for a fit
-bool FitPropertyBrowser::isFitEnabled()const
-{
-  return m_btnFit->isEnabled();
-}
-
-/** 
- * Slot. Adds a tie. Full expression to be entered <name>=<formula>
- */
-void FitPropertyBrowser::addTie()
-{
-  QtBrowserItem * ci = m_browser->currentItem();
-  QtProperty* paramProp = ci->property();
-  PropertyHandler* h = getHandler()->findHandler(paramProp);
-  if (!h->isParameter(paramProp)) return;
-  if (!h) return;
-
-  const Mantid::API::IFitFunction* f = h->function();
-  if (!f) return;
-
-  bool ok = false;
-  QString tieStr = 
-    QInputDialog::getText(this, "MantidPlot - Fit", "Enter tie expression", QLineEdit::Normal,"",&ok);
-  if (ok)
-  {
-    tieStr = tieStr.trimmed();
-    if (!tieStr.contains('='))
-    {
-      tieStr = h->functionPrefix()+"."+paramProp->propertyName() + "=" + tieStr;
-    }
-    h->addTie(tieStr);
-  } // if (ok)
-}
-
-/** 
- * Slot. Ties a parameter to a parameter with the same name of a different function
- */
-void FitPropertyBrowser::addTieToFunction()
-{
-  QtBrowserItem * ci = m_browser->currentItem();
-  QtProperty* paramProp = ci->property();
-  PropertyHandler* h = getHandler()->findHandler(paramProp);
-  if (!h) return;
-  if (!h->isParameter(paramProp)) return;
-  std::string parName = paramProp->propertyName().toStdString();
-  QStringList fnNames;
-
-  int iPar = -1;
-  for(int i=0;i<m_compositeFunction->nParams();i++)
-  {
-    Mantid::API::ParameterReference ref(m_compositeFunction,i);
-    Mantid::API::IFitFunction* fun = ref.getFunction();
-    // Pick out parameters with the same name as the one we're tying from
-    if ( fun->parameterName(ref.getIndex()) == parName )
-    {
-      if ( iPar == -1 && fun == h->function() ) // If this is the 'tied from' parameter, remember it
-      {
-        iPar = i;
-      }
-      else  // Otherwise add it to the list of potential 'tyees'
-      {
-        fnNames << QString::fromStdString(m_compositeFunction->parameterName(i));
-      }
-    }
-  }
-  if (fnNames.empty() || iPar < 0)
-  {
-    QMessageBox::information(m_appWindow,"Mantid - information","Cannot tie this parameter to any function");
-    return;
-  }
-
-  bool ok;
-  QString tieName =
-    QInputDialog::getItem(this, "MantidPlot - Fit", "Select function", fnNames,0,false,&ok);
-
-  if (!ok) return;
-
-  QString tieExpr = QString::fromStdString(m_compositeFunction->parameterName(iPar)) + "=" + tieName;
-
-  h->addTie(tieExpr);
-
-}
-
-/** 
- * Slot. Adds a tie. The current item must be a function parameter
- */
-void FitPropertyBrowser::addFixTie()
-{
-  QtBrowserItem * ci = m_browser->currentItem();
-  QtProperty* paramProp = ci->property();
-  PropertyHandler* h = getHandler()->findHandler(paramProp);
-  if (!h) return;
-  if (!h->isParameter(paramProp)) return;
-  h->fix(paramProp->propertyName());
-}
-
-/** 
- * Slot. Deletes a tie. 
- */
-void FitPropertyBrowser::deleteTie()
-{
-  QtBrowserItem * ci = m_browser->currentItem();
-  QtProperty* paramProp = ci->property();
-  PropertyHandler* h = getHandler()->findHandler(paramProp);
-
-  if (ci->property()->propertyName() != "Tie") 
-  {
-    h->removeTie(ci->property()->propertyName());
-  }
-  else
-  {
-    h->removeTie(ci->property());
-  }
-}
-
-/** Does a parameter have a tie
- * @param parProp :: The property for a function parameter
- */
-void FitPropertyBrowser::hasConstraints(QtProperty* parProp,
-                                        bool& hasTie,
-                                        bool& hasBounds)const
-{
-  hasTie = false;
-  hasBounds = false;
-  QList<QtProperty*> subs = parProp->subProperties();
-  for(int i=0;i<subs.size();i++)
-  {
-    if (subs[i]->propertyName() == "Tie")
-    {
-      hasTie = true;
-    }
-    if (subs[i]->propertyName() == "LowerBound")
-    {
-      hasBounds = true;
-    }
-    if (subs[i]->propertyName() == "UpperBound")
-    {
-      hasBounds = true;
-    }
-  }
-}
-
-/** Returns the tie property for a parameter property, or NULL
- * @param The :: parameter property
- */
-QtProperty* FitPropertyBrowser::getTieProperty(QtProperty* parProp)const
-{
-  QList<QtProperty*> subs = parProp->subProperties();
-  for(int i=0;i<subs.size();i++)
-  {
-    if (subs[i]->propertyName() == "Tie")
-    {
-      return subs[i];
-    }
-  }
-  return NULL;
-}
-
-/** Display a tip
- * @param txt :: The text to display
- */
-void FitPropertyBrowser::setTip(const QString& txt)
-{
-  m_tip->setText(txt);
-}
-
-/**
- * Slot. Adds lower bound to the selected parameter property
- * and sets it f % below parameter's current value
- */
-void FitPropertyBrowser::addConstraint(int f,bool lo,bool up)
-{
-  QtBrowserItem * ci = m_browser->currentItem();
-  QtProperty* parProp = ci->property();
-  PropertyHandler* h = getHandler()->findHandler(parProp);
-  if (!h) return;
-
-  double x = m_doubleManager->value(parProp);
-  double loBound = x*(1-0.01*f);
-  double upBound = x*(1+0.01*f);
-
-  h->addConstraint(ci->property(),lo,up,loBound,upBound);
-}
-
-/**
- * Slot. Adds lower bound to the selected parameter property
- */
-void FitPropertyBrowser::addLowerBound()
-{
-  addConstraint(0,true,false);
-}
-
-/**
- * Slot. Adds lower bound to the selected parameter property
- */
-void FitPropertyBrowser::addLowerBound10()
-{
-  addConstraint(10,true,false);
-}
-
-/**
- * Slot. Adds lower bound to the selected parameter property
- */
-void FitPropertyBrowser::addLowerBound50()
-{
-  addConstraint(50,true,false);
-}
-
-/**
- * Slot.Adds upper bound to the selected parameter property
- */
-void FitPropertyBrowser::addUpperBound10()
-{
-  addConstraint(10,false,true);
-}
-
-/**
- * Slot.Adds upper bound to the selected parameter property
- */
-void FitPropertyBrowser::addUpperBound50()
-{
-  addConstraint(50,false,true);
-}
-
-/**
- * Slot.Adds upper bound to the selected parameter property
- */
-void FitPropertyBrowser::addUpperBound()
-{
-  addConstraint(0,false,true);
-}
-
-/**
- * Slot.Sets the lower and upper bounds of the selected parameter to 10% of its value
- */
-void FitPropertyBrowser::addBothBounds10()
-{
-  addConstraint(10,true,true);
-}
-
-/**
- * Slot.Sets the lower and upper bounds of the selected parameter to 50% of its value
- */
-void FitPropertyBrowser::addBothBounds50()
-{
-  addConstraint(50,true,true);
-}
-
-/**
- * Slot.Adds lower and upper bounds to the selected parameter property
- */
-void FitPropertyBrowser::addBothBounds()
-{
-  addConstraint(0,true,true);
-}
-
-
-/**
- * Slot.Removes lower and upper bounds from the selected parameter property
- */
-void FitPropertyBrowser::removeBounds()
-{
-  QtBrowserItem * ci = m_browser->currentItem();
-  QtProperty* parProp = ci->property();
-  PropertyHandler* h = getHandler()->findHandler(parProp);
-  if (!h) return;
-
-  h->removeConstraint(parProp);
-}
-
-/**
- * Slot. Sends a signal to plot the guess for the current (selected) function
- */
-void FitPropertyBrowser::plotGuessCurrent()
-{
-  emit plotCurrentGuess();
-}
-
-/**
- * Slot. Sends a signal to plot the guess for the whole function
- */
-void FitPropertyBrowser::plotGuessAll()
-{
-  emit plotGuess();
-}
-
-/**
- * Slot. Sends a signal to remove the guess for the current (selected) function
- */
-void FitPropertyBrowser::removeGuessCurrent()
-{
-  emit removeCurrentGuess();
-}
-
-/**
- * Slot. Sends a signal to remove the guess for the whole function
- */
-void FitPropertyBrowser::removeGuessAll()
-{
-  emit removeGuess();
-}
-
-void FitPropertyBrowser::plotOrRemoveGuessAll()
-{
-  if (getHandler()->hasPlot())
-  {
-    removeGuessAll();
-  }
-  else
-  {
-    plotGuessAll();
-  }
-}
-
-/** Create a double property and set some settings
- * @param name :: The name of the new property
- * @return Pointer to the created property
- */
-QtProperty* FitPropertyBrowser::addDoubleProperty(const QString& name)const
-{
-  QtProperty* prop = m_doubleManager->addProperty(name);
-  m_doubleManager->setDecimals(prop,m_decimals);
-  m_doubleManager->setRange(prop,-DBL_MAX,DBL_MAX);
-  return prop;
-}
-
-/** Create a string property and selects a property manager for it
- * based on the property name
- * @param name :: The name of the new property
- * @return Pointer to the created property
- */
-QtProperty* FitPropertyBrowser::addStringProperty(const QString& name)const
-{
-  QtProperty* prop;
-  QString propName = name.toLower();
-  if (propName == "filename")
-  {
-    prop = m_filenameManager->addProperty(name);
-  }
-  else if (propName == "formula")
-  {
-    //!!! dont forget to change the manager !!!
-    prop = m_formulaManager->addProperty(name);
-  }
-  else
-  {
-    prop = m_stringManager->addProperty(name);
-  }
-  return prop;
-}
-
-/**
- * Set a value to a string property.
- * @param prop :: A pointer to the property
- * @param value :: New value for the property
- */
-void FitPropertyBrowser::setStringPropertyValue(QtProperty* prop,const QString& value)const
-{
-  QtStringPropertyManager* manager = dynamic_cast<QtStringPropertyManager*>(prop->propertyManager());
-  if (manager)
-  {
-    manager->setValue(prop,value);
-  }
-}
-
-QString FitPropertyBrowser::getStringPropertyValue(QtProperty* prop)const
-{
-  QtStringPropertyManager* manager = dynamic_cast<QtStringPropertyManager*>(prop->propertyManager());
-  if (manager)
-    return manager->value(prop);
-  else
-    return QString("");
-}
-
-const Mantid::API::IFitFunction* FitPropertyBrowser::theFunction()const
-{
-  return dynamic_cast<Mantid::API::CompositeFunction*>(m_compositeFunction);
-}
-
-void FitPropertyBrowser::checkFunction()
-{
-
-}
-
-void FitPropertyBrowser::saveFunction()
-{
-  QString fnName = QInputDialog::getText(this,"Mantid - Input","Please select a name for the function");
-  QSettings settings;
-  settings.beginGroup("Mantid/FitBrowser/SavedFunctions");
-  QStringList names = settings.childKeys();
-  if (names.contains(fnName) && QMessageBox::question(this,"Mantid - Question","Function with this name already exists.\n"
-    "Would you like to replace it?",QMessageBox::Yes) != QMessageBox::Yes)
-  {
-    return;
-  }
-  settings.setValue(fnName,QString::fromStdString(*theFunction()));
-}
-
-void FitPropertyBrowser::loadFunction()
-{
-  QSettings settings;
-  settings.beginGroup("Mantid/FitBrowser/SavedFunctions");
-  QStringList names = settings.childKeys();
-  if (names.isEmpty())
-  {
-    QMessageBox::information(this,"Mantid - Information","There are no saved functions");
-    return;
-  }
-  QString name = QInputDialog::getItem(this,"Mantid - Input","Please select a function to load",names,0,false);
-  if (!name.isEmpty())
-  {
-    QString str = settings.value(name).toString();
-  
-    getHandler()->removeAllPlots();
-    clearBrowser();
-    createCompositeFunction(str);
-  }
-}
-
-void FitPropertyBrowser::copy()
-{
-  QClipboard *clipboard = QApplication::clipboard();
-  clipboard->setText(QString::fromStdString(*theFunction()));
-}
-
-void FitPropertyBrowser::paste()
-{
-  QClipboard *clipboard = QApplication::clipboard();
-  QString str = clipboard->text();
-  createCompositeFunction(str);
-}
-
-void FitPropertyBrowser::reset()
-{
-  QString str = QString::fromStdString(*theFunction());
-  //getHandler()->removeAllPlots();// this crashes mantidplot
-  clearBrowser();
-  createCompositeFunction(str);
-}
-
-void FitPropertyBrowser::setWorkspace(Mantid::API::IFitFunction* f)const
-{
-  std::string wsName = workspaceName();
-  if (!wsName.empty())
-  {
-    try
-    {
-      Mantid::API::MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-        Mantid::API::AnalysisDataService::Instance().retrieve(wsName));
-      if (ws)
-      {
-        //int xMin=-1,xMax;
-        //double sX = startX();
-        //double eX = endX();
-        //const Mantid::MantidVec& X = ws->readX(workspaceIndex());
-        //for(xMax = 0;xMax < ws->blocksize(); ++xMax)
-        //{
-        //  if (X[xMax] < sX) continue;
-        //  else if (xMin < 0)
-        //  {
-        //    xMin = xMax;
-        //  }
-        //  if (X[xMax] > eX) break;
-        //}
-        QString slice = "WorkspaceIndex="+QString::number(workspaceIndex())+
-          ",StartX="+QString::number(startX())+",EndX="+QString::number(endX());
-        f->setWorkspace(ws,slice.toStdString());
-      }
-    }
-    catch(...){}
-  }
-}
-
-void FitPropertyBrowser::addAutoBackground()
-{
-  if (m_autoBgName.isEmpty()) return;
-  bool hasPlot = false;
-  PropertyHandler* ch = currentHandler();
-  if (m_autoBackground)
-  {// remove old background
-    if (ch == m_autoBackground)
-    {
-      ch = NULL;
-    }
-    hasPlot = m_autoBackground->hasPlot();
-    m_autoBackground->removeFunction();
-    m_autoBackground = NULL;
-  }
-  // Create the function
-  PropertyHandler* h = getHandler()->addFunction(m_autoBgName.toStdString());
-  if (!h) return;
-  if (!m_autoBgAttributes.isEmpty())
-  {// set attributes
-    QStringList attList = m_autoBgAttributes.split(' ');
-    foreach(QString att,attList)
-    {
-      QStringList name_value = att.split('=');
-      if (name_value.size() == 2)
-      {
-        QString name  = name_value[0].trimmed();
-        QString value = name_value[1].trimmed();
-        if (h->function()->hasAttribute(name.toStdString()))
-        {
-          h->setAttribute(name,value);
-        }
-      }
-    }
-  }
-  h->fit();
-  m_autoBackground = h;
-  getHandler()->calcBaseAll();
-  if (hasPlot)
-  {
-    setCurrentFunction(h);
-    emit plotCurrentGuess();
-    if (ch)
-    {
-      setCurrentFunction(ch);
-    }
-  }
-}
-
-void FitPropertyBrowser::refitAutoBackground()
-{
-  if (m_autoBackground)
-  {
-    m_autoBackground->fit();
-  }
-}
-
-/**
-  * Remember a background function name to be used for creating auto-background
-  * @param aName :: A name of the auto-background. The may be followed by function
-  * attributes as name=value pairs separated by spaces.
-  */
-void FitPropertyBrowser::setAutoBackgroundName(const QString& aName)
-{
-  try
-  {
-    QStringList nameList = aName.split(' ');
-    if (nameList.isEmpty()) return;
-    QString name = nameList[0];
-    boost::shared_ptr<Mantid::API::IFitFunction> f = boost::shared_ptr<Mantid::API::IFitFunction>(
-      Mantid::API::FunctionFactory::Instance().createFitFunction(name.toStdString()));
-    m_auto_back = true;
-    m_autoBgName = name;
-    if (nameList.size() > 1)
-    {
-      nameList.removeFirst();
-      m_autoBgAttributes = nameList.join(" ");
-    }
-    Mantid::Kernel::ConfigService::Instance().setString("curvefitting.autoBackground",aName.toStdString());
-  }
-  catch(...)
-  {
-    m_auto_back = false;
-  }
-}
-
-/// Set LogValue for PlotPeakByLogValue
-void FitPropertyBrowser::setLogValue(const QString& lv)
-{
-  if (isWorkspaceAGroup())
-  {
-    validateGroupMember();
-    if (!m_logValue)
-    {
-      m_logValue = m_enumManager->addProperty("LogValue");
-      m_settingsGroup->property()->addSubProperty(m_logValue);
-    }
-    m_logs.clear();
-    m_logs << "";
-    if (!m_groupMember.empty())
-    {
-      Mantid::API::MatrixWorkspace_sptr ws = 
-        boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-        Mantid::API::AnalysisDataService::Instance().retrieve(m_groupMember)
-        );
-      if (ws)
-      {
-        const std::vector<Mantid::Kernel::Property*> logs = ws->run().getLogData();
-        for(int i=0;i<static_cast<int>(logs.size()); ++i)
-        {
-          m_logs << QString::fromStdString(logs[i]->name());
-        }
-      }
-    }
-    m_enumManager->setEnumNames(m_logValue,m_logs);
-    int i = m_logs.indexOf(lv);
-    if (i < 0) i = 0;
-    m_enumManager->setValue(m_logValue,i);
-  }
-}
-
-std::string FitPropertyBrowser::getLogValue()const
-{
-  if (isWorkspaceAGroup() && m_logValue)
-  {
-    int i = m_enumManager->value(m_logValue);
-    if (i < m_logs.size()) return m_logs[i].toStdString();
-  }
-  return "";
-}
-
-/// Remove LogValue from the browser
-void FitPropertyBrowser::removeLogValue()
-{
-  if (isWorkspaceAGroup()) return;
-  m_settingsGroup->property()->removeSubProperty(m_logValue);
-  m_logValue = NULL;
-}
-
-void FitPropertyBrowser::validateGroupMember()
-{
-  std::string wsName = workspaceName();
-  Mantid::API::WorkspaceGroup_sptr wsg = boost::dynamic_pointer_cast<Mantid::API::WorkspaceGroup>(
-    Mantid::API::AnalysisDataService::Instance().retrieve(wsName) );
-  if (!wsg)
-  {
-    m_groupMember = workspaceName();
-    return;
-  }
-  std::vector<std::string> names = wsg->getNames();
-  if (names.empty())
-  {
-    m_groupMember = "";
-    return;
-  }
-  if (std::find(names.begin(),names.end(),m_groupMember) != names.end())
-  {
-    return;
-  }
-  if (names[0] == wsName)
-  {
-    if (names.size() > 1)
-    {
-      m_groupMember = names[1];
-    }
-    else
-    {
-      m_groupMember = "";
-    }
-  }
-  else
-  {
-    m_groupMember = names[0];
-  }
-}
-
-void FitPropertyBrowser::sequentialFit()
-{
-  if (workspaceName() == outputName())
-  {
-    setOutputName(outputName() + "_res");
-  }
-  SequentialFitDialog* dlg = new SequentialFitDialog(this);
-  std::string wsName = workspaceName();
-  if (!wsName.empty() && dlg->addWorkspaces(QStringList(QString::fromStdString(wsName))))
-  {
-    dlg->show();
-  }
-  
-}
-
-void FitPropertyBrowser::findPeaks()
-{
-  std::string wsName = workspaceName();
-  if (wsName.empty())
-  {
-    m_appWindow->mantidUI->showCritical("Workspace name is not set");
-    return;
-  }
-
-  std::string peakListName = wsName + "_PeakList_tmp";
-
-  int FWHM,Tolerance;
-  QString setting = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("curvefitting.findPeaksFWHM"));
-  FWHM = setting.isEmpty() ? 7 : setting.toInt();
-
-  setting = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("curvefitting.findPeaksTolerance"));
-  Tolerance = setting.isEmpty() ? 4 : setting.toInt();
-
-  Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("FindPeaks");
-  alg->initialize();
-  alg->setPropertyValue("InputWorkspace",wsName);
-  alg->setProperty("WorkspaceIndex",workspaceIndex());
-  alg->setPropertyValue("PeaksList",peakListName);
-  alg->setProperty("FWHM",FWHM);
-  alg->setProperty("Tolerance",Tolerance);
-
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-  Mantid::API::MatrixWorkspace_sptr inputWS =
-      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-          Mantid::API::AnalysisDataService::Instance().retrieve(workspaceName()));
-
-  try
-  {
-    alg->execute();
-    Mantid::API::ITableWorkspace_sptr ws = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(
-      Mantid::API::AnalysisDataService::Instance().retrieve(peakListName) );
-
-    clear();
-    Mantid::API::ColumnVector<double> centre = ws->getVector("centre");
-    Mantid::API::ColumnVector<double> width = ws->getVector("width");
-    Mantid::API::ColumnVector<double> height = ws->getVector("height");
-    for(int i=0; i<centre.size(); ++i)
-    {
-      if (centre[i] < startX() || centre[i] > endX()) continue;
-      Mantid::API::IPeakFunction* f = dynamic_cast<Mantid::API::IPeakFunction*>(
-        Mantid::API::FunctionFactory::Instance().createFunction(defaultPeakType())
-        );
-      if (!f) break;
-      f->setMatrixWorkspace(inputWS,workspaceIndex(),-1,-1);
-      f->setCentre(centre[i]);
-      f->setWidth(width[i]);
-      f->setHeight(height[i]);
-      addFunction(*f);
-      delete f;
-    }
-  }
-  catch(...)
-  {
-    QApplication::restoreOverrideCursor();
-    throw;
-  }
-
-	QApplication::restoreOverrideCursor();
-}
-
-void FitPropertyBrowser::setPeakToolOn(bool on)
-{
-  m_peakToolOn = on;
-  m_btnPlotGuess->setEnabled(on);
-}
-
-void FitPropertyBrowser::updateDecimals()
-{
-  if (m_decimals < 0)
-  {
-    QSettings settings;
-    settings.beginGroup("Mantid/FitBrowser");
-    m_decimals = settings.value("decimals",6).toInt();
-  }
-  QSet<QtProperty *> props = m_doubleManager->properties();
-  foreach(QtProperty *prop,props)
-  {
-    m_doubleManager->setDecimals(prop,m_decimals);
-  }
-}
-
-void FitPropertyBrowser::setDecimals(int d)
-{
-  m_decimals = d;
-  QSettings settings;
-  settings.beginGroup("Mantid/FitBrowser");
-  settings.setValue("decimals",d);
-  updateDecimals();
-}
-
-bool FitPropertyBrowser::plotDiff()const
-{
-  return m_boolManager->value(m_plotDiff);
-}
-
+#include "FitPropertyBrowser.h"
+#include "PropertyHandler.h"
+#include "SequentialFitDialog.h"
+
+#include "MantidAPI/FunctionFactory.h"
+#include "MantidAPI/IPeakFunction.h"
+#include "MantidAPI/IBackgroundFunction.h"
+#include "MantidAPI/CompositeFunctionMW.h"
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidAPI/MatrixWorkspace.h"
+#include "MantidAPI/WorkspaceGroup.h"
+#include "MantidAPI/TableRow.h"
+#include "MantidAPI/ParameterTie.h"
+#include "MantidAPI/IConstraint.h"
+#include "MantidAPI/ConstraintFactory.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidKernel/LibraryManager.h"
+
+#include "MantidQtMantidWidgets/UserFunctionDialog.h"
+
+#include "StringDialogEditorFactory.h"
+#include "DoubleEditorFactory.h"
+
+#include "qttreepropertybrowser.h"
+#include "qtpropertymanager.h"
+#include "qteditorfactory.h"
+
+#include "../ApplicationWindow.h"
+#include "MantidUI.h"
+#include <QVBoxLayout>
+#include <QHBoxLayout>
+#include <QGridLayout>
+#include <QPushButton>
+#include <QMenu>
+#include <QMessageBox>
+#include <QInputDialog>
+#include <QSettings>
+#include <QFileInfo>
+#include <QApplication>
+#include <QClipboard>
+
+#include <algorithm>
+
+class FormulaDialogEditor: public StringDialogEditor
+{
+public:
+  FormulaDialogEditor(QtProperty *property, QWidget *parent)
+    :StringDialogEditor(property,parent){}
+protected slots:
+  void runDialog()
+  {
+    MantidQt::MantidWidgets::UserFunctionDialog *dlg = new MantidQt::MantidWidgets::UserFunctionDialog((QWidget*)parent(),getText());
+    if (dlg->exec() == QDialog::Accepted)
+    {
+      setText(dlg->getFormula());
+      updateProperty();
+    };
+  }
+};
+
+class FormulaDialogEditorFactory: public StringDialogEditorFactory
+{
+public:
+  FormulaDialogEditorFactory(QObject* parent):StringDialogEditorFactory(parent){}
+protected:
+  QWidget *createEditor(QtStringPropertyManager *manager, QtProperty *property,QWidget *parent)
+  {
+    (void) manager; //Avoid unused warning
+    return new FormulaDialogEditor(property,parent);
+  }
+};
+
+/**
+ * Constructor
+ * @param parent :: The parent widget - must be an ApplicationWindow
+ */
+FitPropertyBrowser::FitPropertyBrowser(QWidget* parent)
+:QDockWidget("Fit Function",parent),
+m_appWindow((ApplicationWindow*)parent),
+m_currentHandler(0),
+m_logValue(NULL),
+m_compositeFunction(0),
+m_defaultFunction("Gaussian"),
+m_defaultPeak("Gaussian"),
+m_defaultBackground("LinearBackground"),
+m_guessOutputName(true),
+m_changeSlotsEnabled(false),
+m_peakToolOn(false),
+m_auto_back(false),
+m_autoBgName(QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("curvefitting.autoBackground"))),
+m_autoBackground(NULL),
+m_decimals(-1)
+{
+  QSettings settings;
+  settings.beginGroup("Mantid/FitBrowser");
+
+  // Make sure plugins are loaded
+  std::string libpath = Mantid::Kernel::ConfigService::Instance().getString("plugins.directory");
+  if( !libpath.empty() )
+  {
+    Mantid::Kernel::LibraryManager::Instance().OpenAllLibraries(libpath);
+  }
+
+  // Try to create a Gaussian. Failing will mean that CurveFitting dll is not loaded
+  boost::shared_ptr<Mantid::API::IFitFunction> f = boost::shared_ptr<Mantid::API::IFitFunction>(
+    Mantid::API::FunctionFactory::Instance().createFitFunction("Gaussian"));
+  if (m_autoBgName.toLower() == "none")
+  {
+    m_autoBgName = "";
+  }
+  else
+  {
+    setAutoBackgroundName(m_autoBgName);
+  }
+
+  std::string def = Mantid::Kernel::ConfigService::Instance().getString("curvefitting.defaultPeak");
+  if (!def.empty())
+  {
+    m_defaultPeak = def;
+  }
+
+  def = Mantid::Kernel::ConfigService::Instance().getString("curvefitting.autoBackground");
+  if (!def.empty())
+  {
+    m_defaultBackground = def;
+  }
+  m_defaultFunction = m_defaultPeak;
+
+  setObjectName("FitFunction"); // this is needed for QMainWindow::restoreState()
+  setMinimumHeight(150);
+  setMinimumWidth(200);
+  m_appWindow->addDockWidget( Qt::LeftDockWidgetArea, this );
+
+  QWidget* w = new QWidget(parent);
+
+    /* Create property managers: they create, own properties, get and set values  */
+
+  m_groupManager =  new QtGroupPropertyManager(w);
+  m_doubleManager = new QtDoublePropertyManager(w);
+  m_stringManager = new QtStringPropertyManager(w);
+  m_enumManager =   new QtEnumPropertyManager(w);
+  m_intManager =    new QtIntPropertyManager(w);
+  m_boolManager = new QtBoolPropertyManager(w);
+  m_filenameManager = new QtStringPropertyManager(w);
+  m_formulaManager = new QtStringPropertyManager(w);
+
+    /* Create the top level group */
+
+  /*QtProperty* fitGroup = */m_groupManager->addProperty("Fit");
+
+  connect(m_enumManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(enumChanged(QtProperty*)));
+  connect(m_boolManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(boolChanged(QtProperty*)));
+  connect(m_intManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(intChanged(QtProperty*)));
+  connect(m_doubleManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(doubleChanged(QtProperty*)));
+  connect(m_stringManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(stringChanged(QtProperty*)));
+  connect(m_filenameManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(stringChanged(QtProperty*)));
+  connect(m_formulaManager,SIGNAL(propertyChanged(QtProperty*)),this,SLOT(stringChanged(QtProperty*)));
+
+    /* Create function group */
+
+  QtProperty* functionsGroup = m_groupManager->addProperty("Functions");
+
+     /* Create input - output properties */
+
+  QtProperty* settingsGroup = m_groupManager->addProperty("Settings");
+
+  m_workspace = m_enumManager->addProperty("Workspace");
+  m_workspaceIndex = m_intManager->addProperty("Workspace Index");
+  m_startX = addDoubleProperty("StartX");
+  m_endX = addDoubleProperty("EndX");
+  m_output = m_stringManager->addProperty("Output");
+  m_minimizer = m_enumManager->addProperty("Minimizer");
+
+  m_minimizers << "Levenberg-Marquardt"
+               << "Simplex"
+               << "Conjugate gradient (Fletcher-Reeves imp.)"
+               << "Conjugate gradient (Polak-Ribiere imp.)"
+               << "BFGS";
+  m_enumManager->setEnumNames(m_minimizer, m_minimizers);
+
+  m_costFunction = m_enumManager->addProperty("Cost function");
+  m_costFunctions << "Least squares"
+                  << "Ignore positive peaks";
+  m_enumManager->setEnumNames(m_costFunction,m_costFunctions);
+  m_plotDiff = m_boolManager->addProperty("Plot Difference");
+  bool plotDiff = settings.value("Plot Difference",QVariant(true)).toBool();
+  m_boolManager->setValue(m_plotDiff,plotDiff);
+
+  settingsGroup->addSubProperty(m_workspace);
+  settingsGroup->addSubProperty(m_workspaceIndex);
+  settingsGroup->addSubProperty(m_startX);
+  settingsGroup->addSubProperty(m_endX);
+  settingsGroup->addSubProperty(m_output);
+  settingsGroup->addSubProperty(m_minimizer);
+  settingsGroup->addSubProperty(m_costFunction);
+  settingsGroup->addSubProperty(m_plotDiff);
+
+     /* Create editors and assign them to the managers */
+
+  QtCheckBoxFactory *checkBoxFactory = new QtCheckBoxFactory(w);
+  QtEnumEditorFactory *comboBoxFactory = new QtEnumEditorFactory(w);
+  QtSpinBoxFactory *spinBoxFactory = new QtSpinBoxFactory(w);
+  //QtDoubleSpinBoxFactory *doubleSpinBoxFactory = new QtDoubleSpinBoxFactory(w); //unused now
+  DoubleEditorFactory *doubleEditorFactory = new DoubleEditorFactory(w);
+  QtLineEditFactory *lineEditFactory = new QtLineEditFactory(w);
+  StringDialogEditorFactory* stringDialogEditFactory = new StringDialogEditorFactory(w);
+  FormulaDialogEditorFactory* formulaDialogEditFactory = new FormulaDialogEditorFactory(w);
+
+  m_browser = new QtTreePropertyBrowser();
+  m_browser->setFactoryForManager(m_enumManager, comboBoxFactory);
+  m_browser->setFactoryForManager(m_boolManager, checkBoxFactory);
+  m_browser->setFactoryForManager(m_intManager, spinBoxFactory);
+  //m_browser->setFactoryForManager(m_doubleManager, doubleSpinBoxFactory);
+  m_browser->setFactoryForManager(m_doubleManager, doubleEditorFactory);
+  m_browser->setFactoryForManager(m_stringManager, lineEditFactory);
+  m_browser->setFactoryForManager(m_filenameManager, stringDialogEditFactory);
+  m_browser->setFactoryForManager(m_formulaManager, formulaDialogEditFactory);
+
+  updateDecimals();
+
+  m_functionsGroup = m_browser->addProperty(functionsGroup);
+  m_settingsGroup = m_browser->addProperty(settingsGroup);
+
+  QVBoxLayout* layout = new QVBoxLayout(w);
+  QGridLayout* buttonsLayout = new QGridLayout();
+
+  m_btnFit = new QPushButton("Fit");
+  connect(m_btnFit,SIGNAL(clicked()),this,SLOT(fit()));
+
+  m_btnUnFit = new QPushButton("Undo Fit");
+  connect(m_btnUnFit,SIGNAL(clicked()),this,SLOT(undoFit()));
+
+  QPushButton* btnClear = new QPushButton("Clear all");
+  connect(btnClear,SIGNAL(clicked()),this,SLOT(clear()));
+
+  m_btnSeqFit = new QPushButton("Sequential fit");
+  connect(m_btnSeqFit,SIGNAL(clicked()),this,SLOT(sequentialFit()));
+
+  m_btnFindPeaks = new QPushButton("Find peaks");
+  connect(m_btnFindPeaks,SIGNAL(clicked()),this,SLOT(findPeaks()));
+
+  m_btnPlotGuess = new QPushButton("Plot guess");
+  connect(m_btnPlotGuess,SIGNAL(clicked()),this,SLOT(plotOrRemoveGuessAll()));
+  m_btnPlotGuess->setEnabled(false);
+
+  m_tip = new QLabel("",w);
+
+  buttonsLayout->addWidget(m_btnFit,0,0);
+  buttonsLayout->addWidget(m_btnUnFit,0,1);
+  buttonsLayout->addWidget(btnClear,0,2);
+  buttonsLayout->addWidget(m_btnSeqFit,1,0);
+  buttonsLayout->addWidget(m_btnFindPeaks,1,1);
+  buttonsLayout->addWidget(m_btnPlotGuess,1,2);
+
+  layout->addLayout(buttonsLayout);
+  layout->addWidget(m_tip);
+  layout->addWidget(m_browser);
+
+  setWidget(w);
+
+  m_browser->setContextMenuPolicy(Qt::CustomContextMenu);
+  connect(m_browser, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(popupMenu(const QPoint &)));
+  connect(m_browser, SIGNAL(currentItemChanged(QtBrowserItem*)), this, SLOT(currentItemChanged(QtBrowserItem*)));
+
+  createCompositeFunction();
+
+  m_changeSlotsEnabled = true;
+
+}
+
+/// Destructor
+FitPropertyBrowser::~FitPropertyBrowser()
+{
+  QSettings settings;
+  settings.beginGroup("Mantid/FitBrowser");
+  bool plotDiff = m_boolManager->value(m_plotDiff);
+  settings.setValue("Plot Difference",plotDiff);
+  if (m_compositeFunction) delete m_compositeFunction;
+}
+
+/// Get handler to the root composite function
+PropertyHandler* FitPropertyBrowser::getHandler()const
+{
+  return static_cast<PropertyHandler*>(m_compositeFunction->getHandler());
+}
+
+PropertyHandler* FitPropertyBrowser::addFunction(const std::string& fnName)
+{
+  PropertyHandler* h = getHandler()->addFunction(fnName);
+  emit functionChanged();
+  return h;
+}
+
+/** Slot. Called to add a new function
+ */
+void FitPropertyBrowser::addFunction()
+{
+  QtBrowserItem * ci = m_browser->currentItem();
+  // Find the function which has ci as its top browser item 
+  const Mantid::API::CompositeFunction* cf = getHandler()->findCompositeFunction(ci);
+  if ( !cf ) return;
+  int i = m_registeredFunctions.indexOf(QString::fromStdString(m_defaultFunction));
+  bool ok = false;
+  QString fnName = 
+    QInputDialog::getItem(this, "MantidPlot - Fit", "Select function type", m_registeredFunctions,i,false,&ok);
+  if (ok)
+  {
+    PropertyHandler* h = getHandler()->findHandler(cf);
+    h->addFunction(fnName.toStdString());
+  }
+  emit functionChanged();
+}
+
+/// Create CompositeFunction
+void FitPropertyBrowser::createCompositeFunction(const QString& str)
+{
+ if (m_compositeFunction)
+  {
+    emit functionRemoved();
+    delete m_compositeFunction;
+    m_autoBackground = NULL;
+  }
+  if (str.isEmpty())
+  {
+    m_compositeFunction = new Mantid::API::CompositeFunctionMW();
+  }
+  else
+  {
+    Mantid::API::IFitFunction* f = Mantid::API::FunctionFactory::Instance().createInitialized(str.toStdString());
+    if (!f)
+    {
+      createCompositeFunction();
+      return;
+    }
+    Mantid::API::CompositeFunction* cf = dynamic_cast<Mantid::API::CompositeFunction*>(f);
+    if (!cf || cf->name() != "CompositeFunctionMW")
+    {
+      m_compositeFunction = new Mantid::API::CompositeFunctionMW();
+      m_compositeFunction->addFunction(f);
+    }
+    else
+    {
+      m_compositeFunction = cf;
+    }
+  }
+  setWorkspace(m_compositeFunction);
+
+  PropertyHandler* h = new PropertyHandler(m_compositeFunction,NULL,this);
+  m_compositeFunction->setHandler(h);
+  setCurrentFunction(h);
+
+  if (m_auto_back)
+  {
+    addAutoBackground();
+  }
+
+  disableUndo();
+  setFitEnabled(m_compositeFunction->nFunctions() > 0);
+  emit functionChanged();
+}
+
+void FitPropertyBrowser::popupMenu(const QPoint &)
+{
+  QtBrowserItem * ci = m_browser->currentItem();
+  if (!ci) return;
+  QMenu *menu = new QMenu(m_appWindow);
+  QAction *action;
+
+  bool isFunctionsGroup = ci == m_functionsGroup;
+  bool isSettingsGroup = ci == m_settingsGroup;
+  bool isASetting = ci->parent() == m_settingsGroup;
+  bool isFunction = getHandler()->findFunction(ci) != NULL;
+  bool isCompositeFunction = isFunction && getHandler()->findCompositeFunction(ci);
+
+  //if (!isFunction)
+  //{
+  //  const Mantid::API::IFitFunction* h = getHandler()->findFunction(ci);
+  //}
+
+  PropertyHandler* h = getHandler()->findHandler(ci->property());
+
+  if (isFunctionsGroup)
+  {
+    action = new QAction("Add function",this);
+    connect(action,SIGNAL(triggered()),this,SLOT(addFunction()));
+    menu->addAction(action);
+
+    if (m_peakToolOn)
+    {
+      if (h && h->hasPlot())
+      {
+        action = new QAction("Remove plot",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(removeGuessAll()));
+        menu->addAction(action);
+      }
+      else
+      {
+        action = new QAction("Plot",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(plotGuessAll()));
+        menu->addAction(action);
+      }
+    }
+
+    menu->addSeparator();
+
+    action = new QAction("Save",this);
+    connect(action,SIGNAL(triggered()),this,SLOT(saveFunction()));
+    menu->addAction(action);
+
+    action = new QAction("Load",this);
+    connect(action,SIGNAL(triggered()),this,SLOT(loadFunction()));
+    menu->addAction(action);
+
+    action = new QAction("Copy",this);
+    connect(action,SIGNAL(triggered()),this,SLOT(copy()));
+    menu->addAction(action);
+
+    //action = new QAction("Paste",this);
+    //connect(action,SIGNAL(triggered()),this,SLOT(paste()));
+    //menu->addAction(action);
+
+    menu->addSeparator();
+  }
+  else if (isFunctionsGroup || isSettingsGroup || isASetting)
+  {
+    if (isFitEnabled())
+    {
+      action = new QAction("Fit",this);
+      connect(action,SIGNAL(triggered()),this,SLOT(fit()));
+      menu->addAction(action);
+    }
+
+    if (isUndoEnabled())
+    {
+      action = new QAction("Undo Fit",this);
+      connect(action,SIGNAL(triggered()),this,SLOT(undoFit()));
+      menu->addAction(action);
+    }
+
+    action = new QAction("Clear all",this);
+    connect(action,SIGNAL(triggered()),this,SLOT(clear()));
+    menu->addAction(action);
+
+  }
+  else if (isFunction)
+  {
+    if (isCompositeFunction)
+    {
+      action = new QAction("Add function",this);
+      connect(action,SIGNAL(triggered()),this,SLOT(addFunction()));
+      menu->addAction(action);
+    }
+
+    action = new QAction("Remove",this);
+    connect(action,SIGNAL(triggered()),this,SLOT(deleteFunction()));
+    menu->addAction(action);
+
+    if (m_peakToolOn)
+    {
+      if (h && h->hasPlot())
+      {
+        action = new QAction("Remove plot",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(removeGuessCurrent()));
+        menu->addAction(action);
+      }
+      else
+      {
+        action = new QAction("Plot",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(plotGuessCurrent()));
+        menu->addAction(action);
+      }
+    }
+
+    menu->addSeparator();
+  }
+  else if (h)
+  {
+    bool isParameter = h->isParameter(ci->property());
+    bool isTie = !isParameter && ci->property()->propertyName() == "Tie";
+    bool isLowerBound = !isParameter && ci->property()->propertyName() == "Lower Bound";
+    bool isUpperBound = !isParameter && ci->property()->propertyName() == "Upper Bound";
+    bool isType = isParameter && ci->property()->propertyName() == "Type";
+    if (isType)
+    {
+      isParameter = false;
+    }
+
+    if (isTie)
+    {
+      //menu->addSeparator();
+      action = new QAction("Remove",this);
+      connect(action,SIGNAL(triggered()),this,SLOT(deleteTie()));
+      menu->addAction(action);
+    }
+    else if (isLowerBound || isUpperBound)
+    {
+      action = new QAction("Remove",this);
+      connect(action,SIGNAL(triggered()),this,SLOT(removeBounds()));
+      menu->addAction(action);
+    }
+    else if (count() > 0 && isParameter)
+    {
+      bool hasTies;
+      bool hasBounds;
+      hasConstraints(ci->property(),hasTies,hasBounds);
+
+      if (!hasTies && !hasBounds)
+      {
+        action = new QAction("Fix",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(addFixTie()));
+        menu->addAction(action);
+      }
+
+      if (!hasTies)
+      {
+        QMenu *constraintMenu = menu->addMenu("Constraint");
+
+        QMenu* detailMenu = constraintMenu->addMenu("Lower Bound");
+
+        action = new QAction("10%",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(addLowerBound10()));
+        detailMenu->addAction(action);
+
+        action = new QAction("50%",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(addLowerBound50()));
+        detailMenu->addAction(action);
+
+        action = new QAction("Custom",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(addLowerBound()));
+        detailMenu->addAction(action);
+        detailMenu = constraintMenu->addMenu("Upper Bound");
+
+        action = new QAction("10%",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(addUpperBound10()));
+        detailMenu->addAction(action);
+
+        action = new QAction("50%",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(addUpperBound50()));
+        detailMenu->addAction(action);
+
+        action = new QAction("Custom",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(addUpperBound()));
+        detailMenu->addAction(action);
+        detailMenu = constraintMenu->addMenu("Both Bounds");
+
+        action = new QAction("10%",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(addBothBounds10()));
+        detailMenu->addAction(action);
+
+        action = new QAction("50%",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(addBothBounds50()));
+        detailMenu->addAction(action);
+
+        action = new QAction("Custom",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(addBothBounds()));
+        detailMenu->addAction(action);
+      }
+
+      if (hasBounds)
+      {
+        action = new QAction("Remove constraints",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(removeBounds()));
+        menu->addAction(action);
+      }
+
+      if (!hasTies && !hasBounds)
+      {
+        if (count() == 1)
+        {
+          action = new QAction("Tie",this);
+          connect(action,SIGNAL(triggered()),this,SLOT(addTie()));
+          menu->addAction(action);
+        }
+        else
+        {
+          QMenu* detail = menu->addMenu("Tie");
+
+          action = new QAction("To function",this);
+          connect(action,SIGNAL(triggered()),this,SLOT(addTieToFunction()));
+          detail->addAction(action);
+
+          action = new QAction("Custom Tie",this);
+          connect(action,SIGNAL(triggered()),this,SLOT(addTie()));
+          detail->addAction(action);
+        }
+      }
+      else if (hasTies)
+      {
+        action = new QAction("Remove tie",this);
+        connect(action,SIGNAL(triggered()),this,SLOT(deleteTie()));
+        menu->addAction(action);
+      }
+    }
+  }
+
+  menu->popup(QCursor::pos());
+}
+
+/** Slot. Called to remove a function
+ */
+void FitPropertyBrowser::deleteFunction()
+{
+  QtBrowserItem* ci = m_browser->currentItem();
+  PropertyHandler* h = getHandler()->findHandler(ci->property());
+  if (h)
+  {
+    getHandler()->removePlot();
+    h->removeFunction();
+    compositeFunction()->checkFunction();
+    emit functionRemoved();
+    emit functionChanged();
+  }
+}
+
+//***********************************************************************************//
+
+
+// Get the default function name
+std::string FitPropertyBrowser::defaultFunctionType()const
+{
+  return m_defaultFunction;
+}
+
+// Get the default function name
+void FitPropertyBrowser::setDefaultFunctionType(const std::string& fnType)
+{
+  m_defaultFunction = fnType;
+}
+
+/// Get the default peak type
+std::string FitPropertyBrowser::defaultPeakType()const
+{
+  return m_defaultPeak;
+}
+/// Set the default peak type
+void FitPropertyBrowser::setDefaultPeakType(const std::string& fnType)
+{
+  m_defaultPeak = fnType;
+  setDefaultFunctionType(fnType);
+  Mantid::Kernel::ConfigService::Instance().setString("curvefitting.defaultPeak", fnType);
+}
+/// Get the default background type
+std::string FitPropertyBrowser::defaultBackgroundType()const
+{
+  return m_defaultBackground;
+}
+/// Set the default background type
+void FitPropertyBrowser::setDefaultBackgroundType(const std::string& fnType)
+{
+  m_defaultBackground = fnType;
+  setDefaultFunctionType(fnType);
+}
+
+
+/// Get the input workspace name
+std::string FitPropertyBrowser::workspaceName()const
+{
+  int i = m_enumManager->value(m_workspace);
+  std::string res = "";
+  if (i >= 0)
+  {
+    res = m_workspaceNames[i].toStdString();
+  }
+  return res;
+}
+
+/// Set the input workspace name
+void FitPropertyBrowser::setWorkspaceName(const QString& wsName)
+{
+  int i = m_workspaceNames.indexOf(wsName);
+  if (i >= 0)
+  {
+    m_enumManager->setValue(m_workspace,i);
+  }
+  if (!isWorkspaceAGroup())
+  {
+    m_groupMember = wsName.toStdString();
+  }
+}
+
+/// Get workspace index
+int FitPropertyBrowser::workspaceIndex()const
+{
+  return m_intManager->value(m_workspaceIndex);
+}
+
+/// Set workspace index
+void FitPropertyBrowser::setWorkspaceIndex(int i)
+{
+  m_intManager->setValue(m_workspaceIndex,i);
+}
+
+/// Get the output name
+std::string FitPropertyBrowser::outputName()const
+{
+  return m_stringManager->value(m_output).toStdString();
+}
+
+/// Get the output name
+void FitPropertyBrowser::setOutputName(const std::string& name)
+{
+  m_stringManager->setValue(m_output,QString::fromStdString(name));
+}
+
+/// Get the minimizer
+std::string FitPropertyBrowser::minimizer()const
+{
+  int i = m_enumManager->value(m_minimizer);
+  return m_minimizers[i].toStdString();
+}
+
+/// Get the cost function
+std::string FitPropertyBrowser::costFunction()const
+{
+  int i = m_enumManager->value(m_costFunction);
+  return m_costFunctions[i].toStdString();
+}
+
+/** Called when the function name property changed
+ * @param prop :: A pointer to the function name property m_functionName
+ */
+void FitPropertyBrowser::enumChanged(QtProperty* prop)
+{
+  if ( ! m_changeSlotsEnabled ) return;
+
+  if (prop == m_workspace)
+  {
+    if (m_guessOutputName)
+    {
+      if (isWorkspaceAGroup())
+      {
+        m_stringManager->setValue(m_output,QString::fromStdString(workspaceName()+"_params"));
+      }
+      else
+      {
+        m_stringManager->setValue(m_output,QString::fromStdString(workspaceName()));
+      }
+    }
+    if (isWorkspaceAGroup())
+    {
+      setLogValue();
+    }
+    else
+    {
+      m_groupMember = workspaceName();
+      removeLogValue();
+    }
+    emit workspaceNameChanged(QString::fromStdString(workspaceName()));
+  }
+  else if (prop->propertyName() == "Type")
+  {
+      disableUndo();
+      PropertyHandler* h = getHandler()->findHandler(prop);
+      if (!h) return;
+      if (!h->parentHandler()) return;
+      Mantid::API::IFitFunction* f = h->changeType(prop);
+      if (f) setCurrentFunction(f);
+      emit functionChanged();
+  }
+}
+
+/** Called when a bool property changed
+ * @param prop :: A pointer to the property 
+ */
+void FitPropertyBrowser::boolChanged(QtProperty*)
+{
+  if ( ! m_changeSlotsEnabled ) return;
+
+}
+
+/** Called when an int property changed
+ * @param prop :: A pointer to the property 
+ */
+void FitPropertyBrowser::intChanged(QtProperty* prop)
+{
+  if ( ! m_changeSlotsEnabled ) return;
+
+  if (prop == m_workspaceIndex)
+  {
+    Mantid::API::MatrixWorkspace_sptr ws = 
+      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+      m_appWindow->mantidUI->getWorkspace(QString::fromStdString(workspaceName()))
+      );
+    if (!ws)
+    {
+      setWorkspaceIndex(0);
+      return;
+    }
+    int n = ws->getNumberHistograms();
+    int wi = workspaceIndex();
+    if (wi < 0)
+    {
+      setWorkspaceIndex(0);
+    }
+    else if (wi >= n)
+    {
+      setWorkspaceIndex(n-1);
+    }
+    emit workspaceIndexChanged(wi);
+  }
+  else
+  {// it could be an attribute
+    PropertyHandler* h = getHandler()->findHandler(prop);
+    if (!h) return;
+    h->setAttribute(prop);
+  }
+}
+
+/** Called when a double property changed
+ * @param prop :: A pointer to the property 
+ */
+void FitPropertyBrowser::doubleChanged(QtProperty* prop)
+{
+  if ( ! m_changeSlotsEnabled ) return;
+
+  double value = m_doubleManager->value(prop);
+  if (prop == m_startX )
+  {
+    // call setWorkspace to change maxX in functions
+    setWorkspace(m_compositeFunction);
+    getHandler()->setAttribute("StartX",value);
+    emit startXChanged(startX());
+    return;
+  }
+  else if (prop == m_endX )
+  {
+    // call setWorkspace to change minX in functions
+    setWorkspace(m_compositeFunction);
+    getHandler()->setAttribute("EndX",value);
+    emit endXChanged(endX());
+    return;
+  }
+  else if(getHandler()->setParameter(prop))
+  {
+    return;
+  }
+  else
+  {// check if it is a constraint
+    PropertyHandler* h = getHandler()->findHandler(prop);
+    if (!h) return;
+
+    QtProperty* parProp = h->getParameterProperty(prop);
+    if (parProp)
+    {
+      if (prop->propertyName() == "LowerBound")
+      {
+        double loBound = m_doubleManager->value(prop);
+        h->addConstraint(parProp,true,false,loBound,0);
+      }
+      else if (prop->propertyName() == "UpperBound")
+      {
+        double upBound = m_doubleManager->value(prop);
+        h->addConstraint(parProp,false,true,0,upBound);
+      }
+    }
+    else
+    {// it could be an attribute
+      h->setAttribute(prop);
+    }
+  }
+}
+/** Called when a string property changed
+ * @param prop :: A pointer to the property 
+ */
+void FitPropertyBrowser::stringChanged(QtProperty* prop)
+{
+  if ( ! m_changeSlotsEnabled ) return;
+
+  if (prop == m_output)
+  {
+    std::string oName = outputName();
+    if (oName.find_first_not_of(' ') == std::string::npos)
+    {
+      setOutputName("");
+    }
+    else if (workspaceName() == oName || oName.empty())
+    {
+      m_guessOutputName = true;
+    }
+    else
+    {
+      m_guessOutputName = false;
+    }
+  }
+  else if (prop->propertyName() == "Tie")
+  {
+    PropertyHandler* h = getHandler()->findHandler(prop);
+    if (!h) return;
+
+    QtProperty* parProp = h->getParameterProperty(prop);
+    if (!parProp) return;
+
+    QString parName = h->functionPrefix()+"."+parProp->propertyName();
+
+    QString str = m_stringManager->value(prop);
+    Mantid::API::ParameterTie* tie = 
+      new Mantid::API::ParameterTie(compositeFunction(),parName.toStdString());
+    try
+    {
+      tie->set(str.toStdString());
+      h->addTie(parName+"="+str);
+    }
+    catch(...){std::cerr<<"Failed\n";}
+    delete tie;
+  }
+  else if (getHandler()->setAttribute(prop))
+  {// setting an attribute may change function parameters
+    emit functionChanged();
+    return;
+  }
+}
+
+/** Called when a filename property changed
+ * @param prop :: A pointer to the property 
+ */
+void FitPropertyBrowser::filenameChanged(QtProperty* prop)
+{
+  if ( ! m_changeSlotsEnabled ) return;
+
+  if (getHandler()->setAttribute(prop))
+  {
+    return;
+  }
+}
+// Centre of the current peak
+double FitPropertyBrowser::centre()const
+{
+  if (m_currentHandler && m_currentHandler->pfun())
+  {
+    return m_currentHandler->pfun()->centre();
+  }
+  return 0;
+}
+
+/** Set centre of the current peak
+ * @param value :: The new centre value
+ */
+void FitPropertyBrowser::setCentre(double value)
+{
+  if (m_currentHandler)
+  {
+    m_currentHandler->setCentre(value);
+  }
+}
+
+// Height of the current peak
+double FitPropertyBrowser::height()const
+{
+  if (m_currentHandler && m_currentHandler->pfun())
+  {
+    return m_currentHandler->pfun()->height();
+  }
+  return 0.;
+}
+
+/** Set height of the current peak
+ * @param value :: The new height value
+ */
+void FitPropertyBrowser::setHeight(double value)
+{
+  if (m_currentHandler)
+  {
+    m_currentHandler->setHeight(value);
+  }
+}
+
+// Width of the current peak
+double FitPropertyBrowser::width()const
+{
+  if (m_currentHandler && m_currentHandler->pfun())
+  {
+    return m_currentHandler->pfun()->width();
+  }
+  return 0;
+}
+
+/** Set width of the current peak
+ * @param value :: The new width value
+ */
+void FitPropertyBrowser::setWidth(double value)
+{
+  if (m_currentHandler)
+  {
+    m_currentHandler->setWidth(value);
+  }
+}
+
+/// Get the registered function names
+void FitPropertyBrowser::populateFunctionNames()
+{
+  const std::vector<std::string> names = Mantid::API::FunctionFactory::Instance().getKeys();
+  m_registeredFunctions.clear();
+  m_registeredPeaks.clear();
+  m_registeredBackgrounds.clear();
+  for(size_t i=0;i<names.size();i++)
+  {
+    std::string fnName = names[i];
+    QString qfnName = QString::fromStdString(fnName);
+    m_registeredFunctions << qfnName;
+    boost::shared_ptr<Mantid::API::IFitFunction> f = boost::shared_ptr<Mantid::API::IFitFunction>(
+      Mantid::API::FunctionFactory::Instance().createFitFunction(fnName));
+    Mantid::API::IPeakFunction* pf = dynamic_cast<Mantid::API::IPeakFunction*>(f.get());
+    //Mantid::API::CompositeFunction* cf = dynamic_cast<Mantid::API::CompositeFunction*>(f.get());
+    if (pf)
+    {
+      m_registeredPeaks << qfnName;
+    }
+    else if (dynamic_cast<Mantid::API::IBackgroundFunction*>(f.get()))
+    {
+      m_registeredBackgrounds << qfnName;
+    }
+    else
+    {
+      m_registeredOther << qfnName;
+    }
+  }
+}
+
+
+/// Get number of functions in CompositeFunction
+int FitPropertyBrowser::count()const
+{
+  return m_compositeFunction->nFunctions();
+}
+
+/// Get the current function
+PropertyHandler* FitPropertyBrowser::currentHandler()const
+{
+  return m_currentHandler;
+}
+
+/** Set new current function
+ * @param h :: New current function
+ */
+void FitPropertyBrowser::setCurrentFunction(PropertyHandler* h)const
+{
+  m_currentHandler = h;
+  if (m_currentHandler)
+  {
+    m_browser->setCurrentItem(m_currentHandler->item());
+    emit currentChanged();
+  }
+}
+
+/** Set new current function
+ * @param f :: New current function
+ */
+void FitPropertyBrowser::setCurrentFunction(const Mantid::API::IFitFunction* f)const
+{
+  setCurrentFunction(getHandler()->findHandler(f));
+}
+
+#include "../FitDialog.h"
+/**
+ * Creates an instance of Fit algorithm, sets its properties and launches it.
+ */
+void FitPropertyBrowser::fit()
+{
+  std::string wsName = workspaceName();
+  if (wsName.empty())
+  {
+    m_appWindow->mantidUI->showCritical("Workspace name is not set");
+    return;
+  }
+  try
+  {
+    m_initialParameters.resize(compositeFunction()->nParams());
+    for(int i=0;i<compositeFunction()->nParams();i++)
+    {
+      m_initialParameters[i] = compositeFunction()->getParameter(i);
+    }
+    m_btnUnFit->setEnabled(true);
+
+    std::string funStr;
+    if (m_compositeFunction->nFunctions() > 1)
+    {
+      funStr = *m_compositeFunction;
+    }
+    else
+    {
+      funStr = *(m_compositeFunction->getFunction(0));
+    }
+
+    if (isWorkspaceAGroup())
+    {
+      Mantid::API::IAlgorithm_sptr alg = 
+        Mantid::API::AlgorithmManager::Instance().create("PlotPeakByLogValue");
+      alg->initialize();
+      alg->setPropertyValue("InputWorkspace",wsName);
+      alg->setProperty("WorkspaceIndex",workspaceIndex());
+      alg->setProperty("StartX",startX());
+      alg->setProperty("EndX",endX());
+      alg->setPropertyValue("OutputWorkspace",outputName());
+      alg->setPropertyValue("Function",funStr);
+      alg->setPropertyValue("LogValue",getLogValue());
+      //alg->setPropertyValue("Minimizer",minimizer());
+      //alg->setPropertyValue("CostFunction",costFunction());
+
+      observeFinish(alg);
+      alg->executeAsync();
+    }
+    else
+    {
+      Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("Fit");
+      alg->initialize();
+      alg->setPropertyValue("InputWorkspace",wsName);
+      alg->setProperty("WorkspaceIndex",workspaceIndex());
+      alg->setProperty("StartX",startX());
+      alg->setProperty("EndX",endX());
+      alg->setPropertyValue("Output",outputName());
+      alg->setPropertyValue("Function",funStr);
+      alg->setPropertyValue("Minimizer",minimizer());
+      alg->setPropertyValue("CostFunction",costFunction());
+
+      observeFinish(alg);
+      alg->executeAsync();
+    }
+  }
+  catch(std::exception& e)
+  {
+    QString msg = "Fit algorithm failed.\n\n"+QString(e.what())+"\n";
+    m_appWindow->mantidUI->showCritical(msg);
+  }
+}
+
+void FitPropertyBrowser::finishHandle(const Mantid::API::IAlgorithm* alg)
+{
+  std::string out = alg->getProperty("OutputWorkspace");
+  getFitResults();
+  if (!isWorkspaceAGroup())
+  {
+    emit algorithmFinished(QString::fromStdString(out));
+  }
+}
+
+/// Get and store available workspace names
+void FitPropertyBrowser::populateWorkspaceNames()
+{
+  m_workspaceNames.clear();
+  QStringList tmp = m_appWindow->mantidUI->getWorkspaceNames();
+  for(int i=0;i<tmp.size();i++)
+  {
+    Mantid::API::Workspace_sptr ws = m_appWindow->mantidUI->getWorkspace(tmp[i]);
+    if (isWorkspaceValid(ws))
+    {
+      m_workspaceNames.append(tmp[i]);
+    }
+  }
+  m_enumManager->setEnumNames(m_workspace, m_workspaceNames);
+}
+
+void FitPropertyBrowser::workspace_added(const QString &wsName, Mantid::API::Workspace_sptr ws)
+{
+  if ( !isWorkspaceValid(ws) ) return;
+  QString oldName = QString::fromStdString(workspaceName());
+  int i = m_workspaceNames.indexOf(wsName);
+  if (i < 0)
+  {
+    m_workspaceNames.append(wsName);
+    m_workspaceNames.sort();
+  }
+  m_enumManager->setEnumNames(m_workspace, m_workspaceNames);
+  i = m_workspaceNames.indexOf(oldName);
+  if (i >= 0)
+  {
+    m_enumManager->setValue(m_workspace,i);
+  }
+}
+
+void FitPropertyBrowser::workspace_removed(const QString &wsName)
+{
+  QString oldName = QString::fromStdString(workspaceName());
+  int i = m_workspaceNames.indexOf(wsName);
+  if (i >= 0)
+  {
+    m_workspaceNames.removeAt(i);
+  }
+  m_enumManager->setEnumNames(m_workspace, m_workspaceNames);
+  i = m_workspaceNames.indexOf(oldName);
+  if (i >= 0)
+  {
+    m_enumManager->setValue(m_workspace,i);
+  }
+}
+
+void FitPropertyBrowser::init()
+{
+  populateFunctionNames();
+  populateWorkspaceNames();
+  connect(m_appWindow->mantidUI,SIGNAL(workspace_added(const QString &, Mantid::API::Workspace_sptr)),
+    this,SLOT(workspace_added(const QString &, Mantid::API::Workspace_sptr)));
+  connect(m_appWindow->mantidUI,SIGNAL(workspace_removed(const QString &)),
+    this,SLOT(workspace_removed(const QString &)));
+}
+
+/** Check if the workspace can be used in the fit. The accepted types are
+  * MatrixWorkspaces same size
+  * @param ws :: The workspace
+  */
+bool FitPropertyBrowser::isWorkspaceValid(Mantid::API::Workspace_sptr ws)const
+{
+  if (dynamic_cast<Mantid::API::MatrixWorkspace*>(ws.get()) != 0)
+  {
+    return true;
+  }
+  else
+  {
+    return false;
+  }
+}
+
+bool FitPropertyBrowser::isWorkspaceAGroup()const
+{
+  // MG: Disabled as there is an issue with replacing workspace groups and the browser
+  return false;
+}
+
+/// Is the current function a peak?
+bool FitPropertyBrowser::isPeak()const
+{
+  if (count() == 0)
+  {
+    return false;
+  }
+  return m_currentHandler && m_currentHandler->pfun();
+}
+
+/// Get the start X
+double FitPropertyBrowser::startX()const
+{
+  return m_doubleManager->value(m_startX);
+}
+
+/// Set the start X
+void FitPropertyBrowser::setStartX(double value)
+{
+  m_doubleManager->setValue(m_startX,value);
+}
+
+/// Get the end X
+double FitPropertyBrowser::endX()const
+{
+  return m_doubleManager->value(m_endX);
+}
+
+/// Set the end X
+void FitPropertyBrowser::setEndX(double value)
+{
+  m_doubleManager->setValue(m_endX,value);
+}
+
+QtBrowserItem* FitPropertyBrowser::findItem(QtBrowserItem* parent,QtProperty* prop)const
+{
+  QList<QtBrowserItem*> children = parent->children();
+  QtBrowserItem* res = 0;
+  for(int i=0;i<children.size();i++)
+  {
+    if (children[i]->property() == prop)
+    {
+      return children[i];
+    }
+    QList<QtBrowserItem*> grand_children = children[i]->children();
+    if (grand_children.size() > 0) res = findItem(children[i],prop);
+    if (res) return res;
+  }
+  return 0;
+}
+
+/**
+ * Slot. Responds to changing the current item
+ */
+void FitPropertyBrowser::currentItemChanged(QtBrowserItem * current )
+{
+  if (current)
+  {
+    m_currentHandler = getHandler()->findHandler(current->property());
+  }
+  else
+  {
+    m_currentHandler = NULL;
+  }
+  emit currentChanged();
+}
+
+/** Update the function parameter properties. 
+ */
+void FitPropertyBrowser::updateParameters()
+{
+  getHandler()->updateParameters();
+}
+
+/**
+ * Slot. Removes all functions.
+ */
+void FitPropertyBrowser::clear()
+{
+  getHandler()->removeAllPlots();
+  clearBrowser();
+  createCompositeFunction();
+  emit functionCleared();
+}
+
+void FitPropertyBrowser::clearBrowser()
+{
+  QList<QtProperty*> props = m_functionsGroup->property()->subProperties();
+  QtProperty* prop;
+  foreach(prop,props)
+  {
+    m_functionsGroup->property()->removeSubProperty(prop);
+  }
+}
+
+/// Set the parameters to the fit outcome
+void FitPropertyBrowser::getFitResults()
+{
+  if (isWorkspaceAGroup())
+  {
+    std::string wsName = outputName();
+    Mantid::API::ITableWorkspace_sptr ws = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(
+      Mantid::API::AnalysisDataService::Instance().retrieve(wsName) );
+    if (ws)
+    {
+      if ((ws->columnCount() - 1)/2 != compositeFunction()->nParams()) return;
+      Mantid::API::WorkspaceGroup_sptr wsg = boost::dynamic_pointer_cast<Mantid::API::WorkspaceGroup>(
+        Mantid::API::AnalysisDataService::Instance().retrieve(workspaceName()) );
+      std::vector<std::string> names = wsg->getNames();
+      std::vector<std::string>::iterator it = 
+        std::find(names.begin(),names.end(),m_groupMember);
+      if (it == names.end()) return;
+      int row = int(it - names.begin()) - 1;// take into account the group name
+      if (row >= ws->rowCount()) return;
+      for(int i=0;i<compositeFunction()->nParams();++i)
+      {
+        compositeFunction()->setParameter(i,ws->Double(row,2*i+1));
+      }
+      updateParameters();
+      plotGuessAll();
+    }
+  }
+  else
+  {
+    std::string wsName = outputName() + "_Parameters";
+    Mantid::API::ITableWorkspace_sptr ws = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(
+      Mantid::API::AnalysisDataService::Instance().retrieve(wsName) );
+
+    if (ws)
+    {
+      Mantid::API::TableRow row = ws->getFirstRow();
+      do
+      {
+        try
+        {
+          std::string name;
+          double value;
+          row >> name >> value;
+          // In case of a single function Fit doesn't create a CompositeFunction
+          if (count() == 1)
+          {
+            name.insert(0,"f0.");
+          }
+          compositeFunction()->setParameter(name,value);
+        }
+        catch(...)
+        {
+          // do nothing
+        }
+      }
+      while(row.next());
+      updateParameters();
+    }
+  }
+}
+
+/**
+ * Slot. Undoes the fit: restores the parameters to their initial values.
+ */
+void FitPropertyBrowser::undoFit()
+{
+  if (static_cast<int>(m_initialParameters.size()) == compositeFunction()->nParams())
+  {
+    for(int i=0;i<compositeFunction()->nParams();i++)
+    {
+      compositeFunction()->setParameter(i,m_initialParameters[i]);
+    }
+    updateParameters();
+  }
+  disableUndo();
+}
+
+/// disable undo when the function changes
+void FitPropertyBrowser::disableUndo()
+{
+  m_initialParameters.clear();
+  m_btnUnFit->setEnabled(false);
+}
+
+/// Tells if undo can be done
+bool FitPropertyBrowser::isUndoEnabled()const
+{
+  return m_initialParameters.size() && compositeFunction()->nParams() == static_cast<int>(m_initialParameters.size());
+}
+
+/// Enable/disable the Fit button;
+void FitPropertyBrowser::setFitEnabled(bool yes)
+{
+  m_btnFit->setEnabled(yes);
+  m_btnSeqFit->setEnabled(yes);
+}
+
+/// Returns true if the function is ready for a fit
+bool FitPropertyBrowser::isFitEnabled()const
+{
+  return m_btnFit->isEnabled();
+}
+
+/** 
+ * Slot. Adds a tie. Full expression to be entered <name>=<formula>
+ */
+void FitPropertyBrowser::addTie()
+{
+  QtBrowserItem * ci = m_browser->currentItem();
+  QtProperty* paramProp = ci->property();
+  PropertyHandler* h = getHandler()->findHandler(paramProp);
+  if (!h->isParameter(paramProp)) return;
+  if (!h) return;
+
+  const Mantid::API::IFitFunction* f = h->function();
+  if (!f) return;
+
+  bool ok = false;
+  QString tieStr = 
+    QInputDialog::getText(this, "MantidPlot - Fit", "Enter tie expression", QLineEdit::Normal,"",&ok);
+  if (ok)
+  {
+    tieStr = tieStr.trimmed();
+    if (!tieStr.contains('='))
+    {
+      tieStr = h->functionPrefix()+"."+paramProp->propertyName() + "=" + tieStr;
+    }
+    h->addTie(tieStr);
+  } // if (ok)
+}
+
+/** 
+ * Slot. Ties a parameter to a parameter with the same name of a different function
+ */
+void FitPropertyBrowser::addTieToFunction()
+{
+  QtBrowserItem * ci = m_browser->currentItem();
+  QtProperty* paramProp = ci->property();
+  PropertyHandler* h = getHandler()->findHandler(paramProp);
+  if (!h) return;
+  if (!h->isParameter(paramProp)) return;
+  std::string parName = paramProp->propertyName().toStdString();
+  QStringList fnNames;
+
+  int iPar = -1;
+  for(int i=0;i<m_compositeFunction->nParams();i++)
+  {
+    Mantid::API::ParameterReference ref(m_compositeFunction,i);
+    Mantid::API::IFitFunction* fun = ref.getFunction();
+    // Pick out parameters with the same name as the one we're tying from
+    if ( fun->parameterName(ref.getIndex()) == parName )
+    {
+      if ( iPar == -1 && fun == h->function() ) // If this is the 'tied from' parameter, remember it
+      {
+        iPar = i;
+      }
+      else  // Otherwise add it to the list of potential 'tyees'
+      {
+        fnNames << QString::fromStdString(m_compositeFunction->parameterName(i));
+      }
+    }
+  }
+  if (fnNames.empty() || iPar < 0)
+  {
+    QMessageBox::information(m_appWindow,"Mantid - information","Cannot tie this parameter to any function");
+    return;
+  }
+
+  bool ok;
+  QString tieName =
+    QInputDialog::getItem(this, "MantidPlot - Fit", "Select function", fnNames,0,false,&ok);
+
+  if (!ok) return;
+
+  QString tieExpr = QString::fromStdString(m_compositeFunction->parameterName(iPar)) + "=" + tieName;
+
+  h->addTie(tieExpr);
+
+}
+
+/** 
+ * Slot. Adds a tie. The current item must be a function parameter
+ */
+void FitPropertyBrowser::addFixTie()
+{
+  QtBrowserItem * ci = m_browser->currentItem();
+  QtProperty* paramProp = ci->property();
+  PropertyHandler* h = getHandler()->findHandler(paramProp);
+  if (!h) return;
+  if (!h->isParameter(paramProp)) return;
+  h->fix(paramProp->propertyName());
+}
+
+/** 
+ * Slot. Deletes a tie. 
+ */
+void FitPropertyBrowser::deleteTie()
+{
+  QtBrowserItem * ci = m_browser->currentItem();
+  QtProperty* paramProp = ci->property();
+  PropertyHandler* h = getHandler()->findHandler(paramProp);
+
+  if (ci->property()->propertyName() != "Tie") 
+  {
+    h->removeTie(ci->property()->propertyName());
+  }
+  else
+  {
+    h->removeTie(ci->property());
+  }
+}
+
+/** Does a parameter have a tie
+ * @param parProp :: The property for a function parameter
+ */
+void FitPropertyBrowser::hasConstraints(QtProperty* parProp,
+                                        bool& hasTie,
+                                        bool& hasBounds)const
+{
+  hasTie = false;
+  hasBounds = false;
+  QList<QtProperty*> subs = parProp->subProperties();
+  for(int i=0;i<subs.size();i++)
+  {
+    if (subs[i]->propertyName() == "Tie")
+    {
+      hasTie = true;
+    }
+    if (subs[i]->propertyName() == "LowerBound")
+    {
+      hasBounds = true;
+    }
+    if (subs[i]->propertyName() == "UpperBound")
+    {
+      hasBounds = true;
+    }
+  }
+}
+
+/** Returns the tie property for a parameter property, or NULL
+ * @param The :: parameter property
+ */
+QtProperty* FitPropertyBrowser::getTieProperty(QtProperty* parProp)const
+{
+  QList<QtProperty*> subs = parProp->subProperties();
+  for(int i=0;i<subs.size();i++)
+  {
+    if (subs[i]->propertyName() == "Tie")
+    {
+      return subs[i];
+    }
+  }
+  return NULL;
+}
+
+/** Display a tip
+ * @param txt :: The text to display
+ */
+void FitPropertyBrowser::setTip(const QString& txt)
+{
+  m_tip->setText(txt);
+}
+
+/**
+ * Slot. Adds lower bound to the selected parameter property
+ * and sets it f % below parameter's current value
+ */
+void FitPropertyBrowser::addConstraint(int f,bool lo,bool up)
+{
+  QtBrowserItem * ci = m_browser->currentItem();
+  QtProperty* parProp = ci->property();
+  PropertyHandler* h = getHandler()->findHandler(parProp);
+  if (!h) return;
+
+  double x = m_doubleManager->value(parProp);
+  double loBound = x*(1-0.01*f);
+  double upBound = x*(1+0.01*f);
+
+  h->addConstraint(ci->property(),lo,up,loBound,upBound);
+}
+
+/**
+ * Slot. Adds lower bound to the selected parameter property
+ */
+void FitPropertyBrowser::addLowerBound()
+{
+  addConstraint(0,true,false);
+}
+
+/**
+ * Slot. Adds lower bound to the selected parameter property
+ */
+void FitPropertyBrowser::addLowerBound10()
+{
+  addConstraint(10,true,false);
+}
+
+/**
+ * Slot. Adds lower bound to the selected parameter property
+ */
+void FitPropertyBrowser::addLowerBound50()
+{
+  addConstraint(50,true,false);
+}
+
+/**
+ * Slot.Adds upper bound to the selected parameter property
+ */
+void FitPropertyBrowser::addUpperBound10()
+{
+  addConstraint(10,false,true);
+}
+
+/**
+ * Slot.Adds upper bound to the selected parameter property
+ */
+void FitPropertyBrowser::addUpperBound50()
+{
+  addConstraint(50,false,true);
+}
+
+/**
+ * Slot.Adds upper bound to the selected parameter property
+ */
+void FitPropertyBrowser::addUpperBound()
+{
+  addConstraint(0,false,true);
+}
+
+/**
+ * Slot.Sets the lower and upper bounds of the selected parameter to 10% of its value
+ */
+void FitPropertyBrowser::addBothBounds10()
+{
+  addConstraint(10,true,true);
+}
+
+/**
+ * Slot.Sets the lower and upper bounds of the selected parameter to 50% of its value
+ */
+void FitPropertyBrowser::addBothBounds50()
+{
+  addConstraint(50,true,true);
+}
+
+/**
+ * Slot.Adds lower and upper bounds to the selected parameter property
+ */
+void FitPropertyBrowser::addBothBounds()
+{
+  addConstraint(0,true,true);
+}
+
+
+/**
+ * Slot.Removes lower and upper bounds from the selected parameter property
+ */
+void FitPropertyBrowser::removeBounds()
+{
+  QtBrowserItem * ci = m_browser->currentItem();
+  QtProperty* parProp = ci->property();
+  PropertyHandler* h = getHandler()->findHandler(parProp);
+  if (!h) return;
+
+  h->removeConstraint(parProp);
+}
+
+/**
+ * Slot. Sends a signal to plot the guess for the current (selected) function
+ */
+void FitPropertyBrowser::plotGuessCurrent()
+{
+  emit plotCurrentGuess();
+}
+
+/**
+ * Slot. Sends a signal to plot the guess for the whole function
+ */
+void FitPropertyBrowser::plotGuessAll()
+{
+  emit plotGuess();
+}
+
+/**
+ * Slot. Sends a signal to remove the guess for the current (selected) function
+ */
+void FitPropertyBrowser::removeGuessCurrent()
+{
+  emit removeCurrentGuess();
+}
+
+/**
+ * Slot. Sends a signal to remove the guess for the whole function
+ */
+void FitPropertyBrowser::removeGuessAll()
+{
+  emit removeGuess();
+}
+
+void FitPropertyBrowser::plotOrRemoveGuessAll()
+{
+  if (getHandler()->hasPlot())
+  {
+    removeGuessAll();
+  }
+  else
+  {
+    plotGuessAll();
+  }
+}
+
+/** Create a double property and set some settings
+ * @param name :: The name of the new property
+ * @return Pointer to the created property
+ */
+QtProperty* FitPropertyBrowser::addDoubleProperty(const QString& name)const
+{
+  QtProperty* prop = m_doubleManager->addProperty(name);
+  m_doubleManager->setDecimals(prop,m_decimals);
+  m_doubleManager->setRange(prop,-DBL_MAX,DBL_MAX);
+  return prop;
+}
+
+/** Create a string property and selects a property manager for it
+ * based on the property name
+ * @param name :: The name of the new property
+ * @return Pointer to the created property
+ */
+QtProperty* FitPropertyBrowser::addStringProperty(const QString& name)const
+{
+  QtProperty* prop;
+  QString propName = name.toLower();
+  if (propName == "filename")
+  {
+    prop = m_filenameManager->addProperty(name);
+  }
+  else if (propName == "formula")
+  {
+    //!!! dont forget to change the manager !!!
+    prop = m_formulaManager->addProperty(name);
+  }
+  else
+  {
+    prop = m_stringManager->addProperty(name);
+  }
+  return prop;
+}
+
+/**
+ * Set a value to a string property.
+ * @param prop :: A pointer to the property
+ * @param value :: New value for the property
+ */
+void FitPropertyBrowser::setStringPropertyValue(QtProperty* prop,const QString& value)const
+{
+  QtStringPropertyManager* manager = dynamic_cast<QtStringPropertyManager*>(prop->propertyManager());
+  if (manager)
+  {
+    manager->setValue(prop,value);
+  }
+}
+
+QString FitPropertyBrowser::getStringPropertyValue(QtProperty* prop)const
+{
+  QtStringPropertyManager* manager = dynamic_cast<QtStringPropertyManager*>(prop->propertyManager());
+  if (manager)
+    return manager->value(prop);
+  else
+    return QString("");
+}
+
+const Mantid::API::IFitFunction* FitPropertyBrowser::theFunction()const
+{
+  return dynamic_cast<Mantid::API::CompositeFunction*>(m_compositeFunction);
+}
+
+void FitPropertyBrowser::checkFunction()
+{
+
+}
+
+void FitPropertyBrowser::saveFunction()
+{
+  QString fnName = QInputDialog::getText(this,"Mantid - Input","Please select a name for the function");
+  QSettings settings;
+  settings.beginGroup("Mantid/FitBrowser/SavedFunctions");
+  QStringList names = settings.childKeys();
+  if (names.contains(fnName) && QMessageBox::question(this,"Mantid - Question","Function with this name already exists.\n"
+    "Would you like to replace it?",QMessageBox::Yes) != QMessageBox::Yes)
+  {
+    return;
+  }
+  settings.setValue(fnName,QString::fromStdString(*theFunction()));
+}
+
+void FitPropertyBrowser::loadFunction()
+{
+  QSettings settings;
+  settings.beginGroup("Mantid/FitBrowser/SavedFunctions");
+  QStringList names = settings.childKeys();
+  if (names.isEmpty())
+  {
+    QMessageBox::information(this,"Mantid - Information","There are no saved functions");
+    return;
+  }
+  QString name = QInputDialog::getItem(this,"Mantid - Input","Please select a function to load",names,0,false);
+  if (!name.isEmpty())
+  {
+    QString str = settings.value(name).toString();
+  
+    getHandler()->removeAllPlots();
+    clearBrowser();
+    createCompositeFunction(str);
+  }
+}
+
+void FitPropertyBrowser::copy()
+{
+  QClipboard *clipboard = QApplication::clipboard();
+  clipboard->setText(QString::fromStdString(*theFunction()));
+}
+
+void FitPropertyBrowser::paste()
+{
+  QClipboard *clipboard = QApplication::clipboard();
+  QString str = clipboard->text();
+  createCompositeFunction(str);
+}
+
+void FitPropertyBrowser::reset()
+{
+  QString str = QString::fromStdString(*theFunction());
+  //getHandler()->removeAllPlots();// this crashes mantidplot
+  clearBrowser();
+  createCompositeFunction(str);
+}
+
+void FitPropertyBrowser::setWorkspace(Mantid::API::IFitFunction* f)const
+{
+  std::string wsName = workspaceName();
+  if (!wsName.empty())
+  {
+    try
+    {
+      Mantid::API::MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+        Mantid::API::AnalysisDataService::Instance().retrieve(wsName));
+      if (ws)
+      {
+        //int xMin=-1,xMax;
+        //double sX = startX();
+        //double eX = endX();
+        //const Mantid::MantidVec& X = ws->readX(workspaceIndex());
+        //for(xMax = 0;xMax < ws->blocksize(); ++xMax)
+        //{
+        //  if (X[xMax] < sX) continue;
+        //  else if (xMin < 0)
+        //  {
+        //    xMin = xMax;
+        //  }
+        //  if (X[xMax] > eX) break;
+        //}
+        QString slice = "WorkspaceIndex="+QString::number(workspaceIndex())+
+          ",StartX="+QString::number(startX())+",EndX="+QString::number(endX());
+        f->setWorkspace(ws,slice.toStdString());
+      }
+    }
+    catch(...){}
+  }
+}
+
+void FitPropertyBrowser::addAutoBackground()
+{
+  if (m_autoBgName.isEmpty()) return;
+  bool hasPlot = false;
+  PropertyHandler* ch = currentHandler();
+  if (m_autoBackground)
+  {// remove old background
+    if (ch == m_autoBackground)
+    {
+      ch = NULL;
+    }
+    hasPlot = m_autoBackground->hasPlot();
+    m_autoBackground->removeFunction();
+    m_autoBackground = NULL;
+  }
+  // Create the function
+  PropertyHandler* h = getHandler()->addFunction(m_autoBgName.toStdString());
+  if (!h) return;
+  if (!m_autoBgAttributes.isEmpty())
+  {// set attributes
+    QStringList attList = m_autoBgAttributes.split(' ');
+    foreach(QString att,attList)
+    {
+      QStringList name_value = att.split('=');
+      if (name_value.size() == 2)
+      {
+        QString name  = name_value[0].trimmed();
+        QString value = name_value[1].trimmed();
+        if (h->function()->hasAttribute(name.toStdString()))
+        {
+          h->setAttribute(name,value);
+        }
+      }
+    }
+  }
+  h->fit();
+  m_autoBackground = h;
+  getHandler()->calcBaseAll();
+  if (hasPlot)
+  {
+    setCurrentFunction(h);
+    emit plotCurrentGuess();
+    if (ch)
+    {
+      setCurrentFunction(ch);
+    }
+  }
+}
+
+void FitPropertyBrowser::refitAutoBackground()
+{
+  if (m_autoBackground)
+  {
+    m_autoBackground->fit();
+  }
+}
+
+/**
+  * Remember a background function name to be used for creating auto-background
+  * @param aName :: A name of the auto-background. The may be followed by function
+  * attributes as name=value pairs separated by spaces.
+  */
+void FitPropertyBrowser::setAutoBackgroundName(const QString& aName)
+{
+  try
+  {
+    QStringList nameList = aName.split(' ');
+    if (nameList.isEmpty()) return;
+    QString name = nameList[0];
+    boost::shared_ptr<Mantid::API::IFitFunction> f = boost::shared_ptr<Mantid::API::IFitFunction>(
+      Mantid::API::FunctionFactory::Instance().createFitFunction(name.toStdString()));
+    m_auto_back = true;
+    m_autoBgName = name;
+    if (nameList.size() > 1)
+    {
+      nameList.removeFirst();
+      m_autoBgAttributes = nameList.join(" ");
+    }
+    Mantid::Kernel::ConfigService::Instance().setString("curvefitting.autoBackground",aName.toStdString());
+  }
+  catch(...)
+  {
+    m_auto_back = false;
+  }
+}
+
+/// Set LogValue for PlotPeakByLogValue
+void FitPropertyBrowser::setLogValue(const QString& lv)
+{
+  if (isWorkspaceAGroup())
+  {
+    validateGroupMember();
+    if (!m_logValue)
+    {
+      m_logValue = m_enumManager->addProperty("LogValue");
+      m_settingsGroup->property()->addSubProperty(m_logValue);
+    }
+    m_logs.clear();
+    m_logs << "";
+    if (!m_groupMember.empty())
+    {
+      Mantid::API::MatrixWorkspace_sptr ws = 
+        boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+        Mantid::API::AnalysisDataService::Instance().retrieve(m_groupMember)
+        );
+      if (ws)
+      {
+        const std::vector<Mantid::Kernel::Property*> logs = ws->run().getLogData();
+        for(int i=0;i<static_cast<int>(logs.size()); ++i)
+        {
+          m_logs << QString::fromStdString(logs[i]->name());
+        }
+      }
+    }
+    m_enumManager->setEnumNames(m_logValue,m_logs);
+    int i = m_logs.indexOf(lv);
+    if (i < 0) i = 0;
+    m_enumManager->setValue(m_logValue,i);
+  }
+}
+
+std::string FitPropertyBrowser::getLogValue()const
+{
+  if (isWorkspaceAGroup() && m_logValue)
+  {
+    int i = m_enumManager->value(m_logValue);
+    if (i < m_logs.size()) return m_logs[i].toStdString();
+  }
+  return "";
+}
+
+/// Remove LogValue from the browser
+void FitPropertyBrowser::removeLogValue()
+{
+  if (isWorkspaceAGroup()) return;
+  m_settingsGroup->property()->removeSubProperty(m_logValue);
+  m_logValue = NULL;
+}
+
+void FitPropertyBrowser::validateGroupMember()
+{
+  std::string wsName = workspaceName();
+  Mantid::API::WorkspaceGroup_sptr wsg = boost::dynamic_pointer_cast<Mantid::API::WorkspaceGroup>(
+    Mantid::API::AnalysisDataService::Instance().retrieve(wsName) );
+  if (!wsg)
+  {
+    m_groupMember = workspaceName();
+    return;
+  }
+  std::vector<std::string> names = wsg->getNames();
+  if (names.empty())
+  {
+    m_groupMember = "";
+    return;
+  }
+  if (std::find(names.begin(),names.end(),m_groupMember) != names.end())
+  {
+    return;
+  }
+  if (names[0] == wsName)
+  {
+    if (names.size() > 1)
+    {
+      m_groupMember = names[1];
+    }
+    else
+    {
+      m_groupMember = "";
+    }
+  }
+  else
+  {
+    m_groupMember = names[0];
+  }
+}
+
+void FitPropertyBrowser::sequentialFit()
+{
+  if (workspaceName() == outputName())
+  {
+    setOutputName(outputName() + "_res");
+  }
+  SequentialFitDialog* dlg = new SequentialFitDialog(this);
+  std::string wsName = workspaceName();
+  if (!wsName.empty() && dlg->addWorkspaces(QStringList(QString::fromStdString(wsName))))
+  {
+    dlg->show();
+  }
+  
+}
+
+void FitPropertyBrowser::findPeaks()
+{
+  std::string wsName = workspaceName();
+  if (wsName.empty())
+  {
+    m_appWindow->mantidUI->showCritical("Workspace name is not set");
+    return;
+  }
+
+  std::string peakListName = wsName + "_PeakList_tmp";
+
+  int FWHM,Tolerance;
+  QString setting = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("curvefitting.findPeaksFWHM"));
+  FWHM = setting.isEmpty() ? 7 : setting.toInt();
+
+  setting = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("curvefitting.findPeaksTolerance"));
+  Tolerance = setting.isEmpty() ? 4 : setting.toInt();
+
+  Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("FindPeaks");
+  alg->initialize();
+  alg->setPropertyValue("InputWorkspace",wsName);
+  alg->setProperty("WorkspaceIndex",workspaceIndex());
+  alg->setPropertyValue("PeaksList",peakListName);
+  alg->setProperty("FWHM",FWHM);
+  alg->setProperty("Tolerance",Tolerance);
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  Mantid::API::MatrixWorkspace_sptr inputWS =
+      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+          Mantid::API::AnalysisDataService::Instance().retrieve(workspaceName()));
+
+  try
+  {
+    alg->execute();
+    Mantid::API::ITableWorkspace_sptr ws = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(
+      Mantid::API::AnalysisDataService::Instance().retrieve(peakListName) );
+
+    clear();
+    Mantid::API::ColumnVector<double> centre = ws->getVector("centre");
+    Mantid::API::ColumnVector<double> width = ws->getVector("width");
+    Mantid::API::ColumnVector<double> height = ws->getVector("height");
+    for(int i=0; i<centre.size(); ++i)
+    {
+      if (centre[i] < startX() || centre[i] > endX()) continue;
+      Mantid::API::IPeakFunction* f = dynamic_cast<Mantid::API::IPeakFunction*>(
+        Mantid::API::FunctionFactory::Instance().createFunction(defaultPeakType())
+        );
+      if (!f) break;
+      f->setMatrixWorkspace(inputWS,workspaceIndex(),-1,-1);
+      f->setCentre(centre[i]);
+      f->setWidth(width[i]);
+      f->setHeight(height[i]);
+      addFunction(*f);
+      delete f;
+    }
+  }
+  catch(...)
+  {
+    QApplication::restoreOverrideCursor();
+    throw;
+  }
+
+	QApplication::restoreOverrideCursor();
+}
+
+void FitPropertyBrowser::setPeakToolOn(bool on)
+{
+  m_peakToolOn = on;
+  m_btnPlotGuess->setEnabled(on);
+}
+
+void FitPropertyBrowser::updateDecimals()
+{
+  if (m_decimals < 0)
+  {
+    QSettings settings;
+    settings.beginGroup("Mantid/FitBrowser");
+    m_decimals = settings.value("decimals",6).toInt();
+  }
+  QSet<QtProperty *> props = m_doubleManager->properties();
+  foreach(QtProperty *prop,props)
+  {
+    m_doubleManager->setDecimals(prop,m_decimals);
+  }
+}
+
+void FitPropertyBrowser::setDecimals(int d)
+{
+  m_decimals = d;
+  QSettings settings;
+  settings.beginGroup("Mantid/FitBrowser");
+  settings.setValue("decimals",d);
+  updateDecimals();
+}
+
+bool FitPropertyBrowser::plotDiff()const
+{
+  return m_boolManager->value(m_plotDiff);
+}
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/FitPropertyBrowser.h b/Code/Mantid/MantidPlot/src/Mantid/FitPropertyBrowser.h
index 6bf18f063c3d613538bc86a81467ea01005235eb..e92b05f8755ee71ad04a6b5de566c9e6d4cb4122 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/FitPropertyBrowser.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/FitPropertyBrowser.h
@@ -1,258 +1,258 @@
-#ifndef FITPROPERTYBROWSER_H_
-#define FITPROPERTYBROWSER_H_
-
+#ifndef FITPROPERTYBROWSER_H_
+#define FITPROPERTYBROWSER_H_
+
 #include "MantidAPI/Workspace.h"
 #include "MantidAPI/AlgorithmObserver.h"
 
-#include <QDockWidget>
-#include <QMap>
-
-    /* Forward declarations */
-
-class QtTreePropertyBrowser;
-class QtGroupPropertyManager;
-class QtDoublePropertyManager;
-class QtIntPropertyManager;
-class QtBoolPropertyManager;
-class QtStringPropertyManager;
-class QtEnumPropertyManager;
-class QtProperty;
-class QtBrowserItem;
-
-class QPushButton;
-class QLabel;
-
-class ApplicationWindow;
-
-namespace Mantid
-{
-  namespace API
-  {
-    class IFitFunction;
-    class IPeakFunction;
-    class CompositeFunction;
-    class Workspace;
-    class ParameterTie;
-  }
-}
-
-class PropertyHandler;
-/**
- * Class FitPropertyBrowser implements QtPropertyBrowser to display 
- * and control fitting function parameters and settings.
- * 
+#include <QDockWidget>
+#include <QMap>
+
+    /* Forward declarations */
+
+class QtTreePropertyBrowser;
+class QtGroupPropertyManager;
+class QtDoublePropertyManager;
+class QtIntPropertyManager;
+class QtBoolPropertyManager;
+class QtStringPropertyManager;
+class QtEnumPropertyManager;
+class QtProperty;
+class QtBrowserItem;
+
+class QPushButton;
+class QLabel;
+
+class ApplicationWindow;
+
+namespace Mantid
+{
+  namespace API
+  {
+    class IFitFunction;
+    class IPeakFunction;
+    class CompositeFunction;
+    class Workspace;
+    class ParameterTie;
+  }
+}
+
+class PropertyHandler;
+/**
+ * Class FitPropertyBrowser implements QtPropertyBrowser to display 
+ * and control fitting function parameters and settings.
+ * 
  * @autor Roman Tolchenov, Tessella Support Services plc
- * @date 13/11/2009
- */
-
-class FitPropertyBrowser: public QDockWidget, public Mantid::API::AlgorithmObserver
-{
-  Q_OBJECT
-public:
-  /// Constructor
-  FitPropertyBrowser(QWidget* parent);
-  /// Destructor
-  ~FitPropertyBrowser();
-  /// Get handler to the root composite function
-  PropertyHandler* getHandler()const;
-
-  /// Centre of the current peak
-  double centre()const;
-  /// Set centre of the current peak
-  void setCentre(double value);
-  /// Height of the current peak
-  double height()const;
-  /// Set height of the current peak
-  void setHeight(double value);
-  /// Width of the current peak
-  double width()const;
-  /// Set width of the current peak
-  void setWidth(double value);
-  /// Get count
-  int count()const;
-  /// Is the current function a peak?
-  bool isPeak()const;
-  /// Get the current function
-  PropertyHandler* currentHandler()const;
-  /// Set new current function
-  void setCurrentFunction(PropertyHandler* h)const;
-  /// Get the current function
-  const Mantid::API::IFitFunction* theFunction()const;
-  /// Update the function parameters
-  void updateParameters();
-
-  /// Create a new function
-  PropertyHandler* addFunction(const std::string& fnName);
-  /// Get Composite Function
-  Mantid::API::CompositeFunction* compositeFunction()const{return m_compositeFunction;}
-  /// Get the default function type
-  std::string defaultFunctionType()const;
-  /// Set the default function type
-  void setDefaultFunctionType(const std::string& fnType);
-  /// Get the default peak type
-  std::string defaultPeakType()const;
-  /// Set the default peak type
-  void setDefaultPeakType(const std::string& fnType);
-  /// Get the default background type
-  std::string defaultBackgroundType()const;
-  /// Set the default background type
-  void setDefaultBackgroundType(const std::string& fnType);
-
-  /// Get the input workspace name
-  std::string workspaceName()const;
-  /// Set the input workspace name
-  void setWorkspaceName(const QString& wsName);
-  /// Get workspace index
-  int workspaceIndex()const;
-  /// Set workspace index
-  void setWorkspaceIndex(int i);
-  /// Get the output name
-  std::string outputName()const;
-  /// Set the output name
-  void setOutputName(const std::string&);
-  /// Get the minimizer
-  std::string minimizer()const;
-  /// Get the cost function
-  std::string costFunction()const;
-
-  /// Get the start X
-  double startX()const;
-  /// Set the start X
-  void setStartX(double);
-  /// Get the end X
-  double endX()const;
-  /// Set the end X
-  void setEndX(double);
-
-  /// Set LogValue for PlotPeakByLogValue
-  void setLogValue(const QString& lv = "");
-  /// Get LogValue
-  std::string getLogValue()const;
-  /// Remove LogValue from the browser
-  void removeLogValue();
-
-  /// Return a list of registered functions
-  const QStringList& registeredFunctions()const{return m_registeredFunctions;}
-  /// Return a list of registered peaks
-  const QStringList& registeredPeaks()const{return m_registeredPeaks;}
-  /// Return a list of registered backgrounds
-  const QStringList& registeredBackgrounds()const{return m_registeredBackgrounds;}
-  /// Return a list of registered other functions
-  const QStringList& registeredOthers()const{return m_registeredOther;}
-
-  /// Tells if undo can be done
-  bool isUndoEnabled()const;
-  /// Returns true if the function is ready for a fit
-  bool isFitEnabled()const;
-
-  /// Display a tip
-  void setTip(const QString& txt);
-
-  /// Creates the "Ties" property value for the Fit algorithm
-  QString getTieString()const;
-
-  /// Creates the "Constraints" property value for the Fit algorithm
-  QString getConstraintsString()const;
-
-  void init();
-
-  // send parameterChanged signal
-  void sendParameterChanged(const Mantid::API::IFitFunction* f){emit parameterChanged(f);}
-
-  /// Creates and adds the autobackground
-  void addAutoBackground();
-  bool isAutoBack()const{return m_autoBackground!=NULL;}
-  void setAutoBackgroundName(const QString& aName);
-  void refitAutoBackground();
-  QString getAutoBackgroundString()const{return m_autoBgName + " " + m_autoBgAttributes;}
-
-  /// Number of decimal places in double properties
-  int getDecimals()const{return m_decimals;}
-  void setDecimals(int d);
-
-  /// Returns true if the difference plot should be drawn
-  bool plotDiff()const;
-
-public slots:
-  void fit();
-  void sequentialFit();
-  void undoFit();
-  void clear();
-  void clearBrowser();
-  void setPeakToolOn(bool on);
-  void findPeaks();
-
-signals:
-  void currentChanged()const;
-  void functionRemoved();
-  void algorithmFinished(const QString&);
-  void workspaceIndexChanged(int i);
-  void workspaceNameChanged(const QString&);
-  void functionChanged();
-  void startXChanged(double);
-  void endXChanged(double);
-  void parameterChanged(const Mantid::API::IFitFunction*);
-  void functionCleared();
-  void plotGuess();
-  void plotCurrentGuess();
-  void removeGuess();
-  void removeCurrentGuess();
-
-private slots:
-
-  void enumChanged(QtProperty* prop);
-  void boolChanged(QtProperty* prop);
-  void intChanged(QtProperty* prop);
-  void doubleChanged(QtProperty* prop);
-  void stringChanged(QtProperty* prop);
-  void filenameChanged(QtProperty* prop);
-  void workspace_added(const QString &, Mantid::API::Workspace_sptr);
-  void workspace_removed(const QString &);
-  void currentItemChanged(QtBrowserItem*);
-  void addTie();
-  void addTieToFunction();
-  void addFixTie();
-  void deleteTie();
-  void addLowerBound10();
-  void addLowerBound50();
-  void addLowerBound();
-  void addConstraint(int f,bool lo,bool up);
-  void addUpperBound10();
-  void addUpperBound50();
-  void addUpperBound();
-  void addBothBounds10();
-  void addBothBounds50();
-  void addBothBounds();
-  void removeBounds();
-  void plotGuessCurrent();
-  void plotGuessAll();
-  void removeGuessCurrent();
-  void removeGuessAll();
-  void plotOrRemoveGuessAll();
-  void saveFunction();
-  void loadFunction();
-  void copy();///< Copy the function string to the clipboard
-  void paste();///< Paste a function string from the clipboard
-  void updateDecimals();
-  void reset();///< reset the function part, renew function, all handlers are new
-
-  void popupMenu(const QPoint &);
-  /* Context menu slots */
-  void addFunction();
-  void deleteFunction();
-private:
-
-  /// Create CompositeFunction
-  void createCompositeFunction(const QString& str = "");
-  /// Get and store available workspace names
-  void populateWorkspaceNames();
-  /// Get the registered function names
-  void populateFunctionNames();
-  /// Check if the workspace can be used in the fit
-  bool isWorkspaceValid(Mantid::API::Workspace_sptr)const;
-  /// Check if the input workspace is a group
-  bool isWorkspaceAGroup()const;
-  /// Called when the fit is finished
+ * @date 13/11/2009
+ */
+
+class FitPropertyBrowser: public QDockWidget, public Mantid::API::AlgorithmObserver
+{
+  Q_OBJECT
+public:
+  /// Constructor
+  FitPropertyBrowser(QWidget* parent);
+  /// Destructor
+  ~FitPropertyBrowser();
+  /// Get handler to the root composite function
+  PropertyHandler* getHandler()const;
+
+  /// Centre of the current peak
+  double centre()const;
+  /// Set centre of the current peak
+  void setCentre(double value);
+  /// Height of the current peak
+  double height()const;
+  /// Set height of the current peak
+  void setHeight(double value);
+  /// Width of the current peak
+  double width()const;
+  /// Set width of the current peak
+  void setWidth(double value);
+  /// Get count
+  int count()const;
+  /// Is the current function a peak?
+  bool isPeak()const;
+  /// Get the current function
+  PropertyHandler* currentHandler()const;
+  /// Set new current function
+  void setCurrentFunction(PropertyHandler* h)const;
+  /// Get the current function
+  const Mantid::API::IFitFunction* theFunction()const;
+  /// Update the function parameters
+  void updateParameters();
+
+  /// Create a new function
+  PropertyHandler* addFunction(const std::string& fnName);
+  /// Get Composite Function
+  Mantid::API::CompositeFunction* compositeFunction()const{return m_compositeFunction;}
+  /// Get the default function type
+  std::string defaultFunctionType()const;
+  /// Set the default function type
+  void setDefaultFunctionType(const std::string& fnType);
+  /// Get the default peak type
+  std::string defaultPeakType()const;
+  /// Set the default peak type
+  void setDefaultPeakType(const std::string& fnType);
+  /// Get the default background type
+  std::string defaultBackgroundType()const;
+  /// Set the default background type
+  void setDefaultBackgroundType(const std::string& fnType);
+
+  /// Get the input workspace name
+  std::string workspaceName()const;
+  /// Set the input workspace name
+  void setWorkspaceName(const QString& wsName);
+  /// Get workspace index
+  int workspaceIndex()const;
+  /// Set workspace index
+  void setWorkspaceIndex(int i);
+  /// Get the output name
+  std::string outputName()const;
+  /// Set the output name
+  void setOutputName(const std::string&);
+  /// Get the minimizer
+  std::string minimizer()const;
+  /// Get the cost function
+  std::string costFunction()const;
+
+  /// Get the start X
+  double startX()const;
+  /// Set the start X
+  void setStartX(double);
+  /// Get the end X
+  double endX()const;
+  /// Set the end X
+  void setEndX(double);
+
+  /// Set LogValue for PlotPeakByLogValue
+  void setLogValue(const QString& lv = "");
+  /// Get LogValue
+  std::string getLogValue()const;
+  /// Remove LogValue from the browser
+  void removeLogValue();
+
+  /// Return a list of registered functions
+  const QStringList& registeredFunctions()const{return m_registeredFunctions;}
+  /// Return a list of registered peaks
+  const QStringList& registeredPeaks()const{return m_registeredPeaks;}
+  /// Return a list of registered backgrounds
+  const QStringList& registeredBackgrounds()const{return m_registeredBackgrounds;}
+  /// Return a list of registered other functions
+  const QStringList& registeredOthers()const{return m_registeredOther;}
+
+  /// Tells if undo can be done
+  bool isUndoEnabled()const;
+  /// Returns true if the function is ready for a fit
+  bool isFitEnabled()const;
+
+  /// Display a tip
+  void setTip(const QString& txt);
+
+  /// Creates the "Ties" property value for the Fit algorithm
+  QString getTieString()const;
+
+  /// Creates the "Constraints" property value for the Fit algorithm
+  QString getConstraintsString()const;
+
+  void init();
+
+  // send parameterChanged signal
+  void sendParameterChanged(const Mantid::API::IFitFunction* f){emit parameterChanged(f);}
+
+  /// Creates and adds the autobackground
+  void addAutoBackground();
+  bool isAutoBack()const{return m_autoBackground!=NULL;}
+  void setAutoBackgroundName(const QString& aName);
+  void refitAutoBackground();
+  QString getAutoBackgroundString()const{return m_autoBgName + " " + m_autoBgAttributes;}
+
+  /// Number of decimal places in double properties
+  int getDecimals()const{return m_decimals;}
+  void setDecimals(int d);
+
+  /// Returns true if the difference plot should be drawn
+  bool plotDiff()const;
+
+public slots:
+  void fit();
+  void sequentialFit();
+  void undoFit();
+  void clear();
+  void clearBrowser();
+  void setPeakToolOn(bool on);
+  void findPeaks();
+
+signals:
+  void currentChanged()const;
+  void functionRemoved();
+  void algorithmFinished(const QString&);
+  void workspaceIndexChanged(int i);
+  void workspaceNameChanged(const QString&);
+  void functionChanged();
+  void startXChanged(double);
+  void endXChanged(double);
+  void parameterChanged(const Mantid::API::IFitFunction*);
+  void functionCleared();
+  void plotGuess();
+  void plotCurrentGuess();
+  void removeGuess();
+  void removeCurrentGuess();
+
+private slots:
+
+  void enumChanged(QtProperty* prop);
+  void boolChanged(QtProperty* prop);
+  void intChanged(QtProperty* prop);
+  void doubleChanged(QtProperty* prop);
+  void stringChanged(QtProperty* prop);
+  void filenameChanged(QtProperty* prop);
+  void workspace_added(const QString &, Mantid::API::Workspace_sptr);
+  void workspace_removed(const QString &);
+  void currentItemChanged(QtBrowserItem*);
+  void addTie();
+  void addTieToFunction();
+  void addFixTie();
+  void deleteTie();
+  void addLowerBound10();
+  void addLowerBound50();
+  void addLowerBound();
+  void addConstraint(int f,bool lo,bool up);
+  void addUpperBound10();
+  void addUpperBound50();
+  void addUpperBound();
+  void addBothBounds10();
+  void addBothBounds50();
+  void addBothBounds();
+  void removeBounds();
+  void plotGuessCurrent();
+  void plotGuessAll();
+  void removeGuessCurrent();
+  void removeGuessAll();
+  void plotOrRemoveGuessAll();
+  void saveFunction();
+  void loadFunction();
+  void copy();///< Copy the function string to the clipboard
+  void paste();///< Paste a function string from the clipboard
+  void updateDecimals();
+  void reset();///< reset the function part, renew function, all handlers are new
+
+  void popupMenu(const QPoint &);
+  /* Context menu slots */
+  void addFunction();
+  void deleteFunction();
+private:
+
+  /// Create CompositeFunction
+  void createCompositeFunction(const QString& str = "");
+  /// Get and store available workspace names
+  void populateWorkspaceNames();
+  /// Get the registered function names
+  void populateFunctionNames();
+  /// Check if the workspace can be used in the fit
+  bool isWorkspaceValid(Mantid::API::Workspace_sptr)const;
+  /// Check if the input workspace is a group
+  bool isWorkspaceAGroup()const;
+  /// Called when the fit is finished
   void finishHandle(const Mantid::API::IAlgorithm* alg);
   /// Find QtBrowserItem for a property prop among the chidren of 
   QtBrowserItem* findItem(QtBrowserItem* parent,QtProperty* prop)const;
@@ -262,27 +262,27 @@ private:
   void disableUndo();
   /// Enable/disable the Fit button;
   void setFitEnabled(bool yes);
-  /// Create a double property and set some settings
-  QtProperty* addDoubleProperty(const QString& name)const;
-  /// 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;
-  /// Check that the properties match the function
-  void checkFunction();
-  /// Sets the workspace to a function
-  void setWorkspace(Mantid::API::IFitFunction* f)const;
-
-  void setCurrentFunction(const Mantid::API::IFitFunction* f)const;
-
-  /// Does a parameter have a tie
-  void hasConstraints(QtProperty* parProp,bool& hasTie,bool& hasBounds)const;
-  /// Returns the tie property for a parameter property, or NULL
-  QtProperty* getTieProperty(QtProperty* parProp)const;
-
-  /// Make sure m_groupMember belongs to the group
-  void validateGroupMember();
-
+  /// Create a double property and set some settings
+  QtProperty* addDoubleProperty(const QString& name)const;
+  /// 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;
+  /// Check that the properties match the function
+  void checkFunction();
+  /// Sets the workspace to a function
+  void setWorkspace(Mantid::API::IFitFunction* f)const;
+
+  void setCurrentFunction(const Mantid::API::IFitFunction* f)const;
+
+  /// Does a parameter have a tie
+  void hasConstraints(QtProperty* parProp,bool& hasTie,bool& hasBounds)const;
+  /// Returns the tie property for a parameter property, or NULL
+  QtProperty* getTieProperty(QtProperty* parProp)const;
+
+  /// Make sure m_groupMember belongs to the group
+  void validateGroupMember();
+
   /// Button for doing fit
   QPushButton* m_btnFit;
   /// Button for undoing fit
@@ -295,56 +295,56 @@ private:
   QPushButton* m_btnFindPeaks;
   /// To display a tip text
   QLabel* m_tip;
-
-  QtTreePropertyBrowser* m_browser;
-  /// Property managers:
-  QtGroupPropertyManager  *m_groupManager;
-  QtDoublePropertyManager *m_doubleManager;
-  QtEnumPropertyManager *m_enumManager;
-  QtIntPropertyManager *m_intManager;
-  QtBoolPropertyManager *m_boolManager;
-  QtStringPropertyManager *m_stringManager;
-  QtStringPropertyManager *m_filenameManager;
-  QtStringPropertyManager *m_formulaManager;
-  /// String property managers for special case attributes such as Filename or Formula
-  /// <attribute_name,string_manager>
-  QMap<QString,QtStringPropertyManager*> m_stringManagers;
-
-  // The main application window
+
+  QtTreePropertyBrowser* m_browser;
+  /// Property managers:
+  QtGroupPropertyManager  *m_groupManager;
+  QtDoublePropertyManager *m_doubleManager;
+  QtEnumPropertyManager *m_enumManager;
+  QtIntPropertyManager *m_intManager;
+  QtBoolPropertyManager *m_boolManager;
+  QtStringPropertyManager *m_stringManager;
+  QtStringPropertyManager *m_filenameManager;
+  QtStringPropertyManager *m_formulaManager;
+  /// String property managers for special case attributes such as Filename or Formula
+  /// <attribute_name,string_manager>
+  QMap<QString,QtStringPropertyManager*> m_stringManagers;
+
+  // The main application window
   ApplicationWindow* m_appWindow;
 
-  mutable PropertyHandler* m_currentHandler;
-
-  /// Group for functions
-  QtBrowserItem* m_functionsGroup;
-  /// Group for input/output settings
-  QtBrowserItem* m_settingsGroup;
-
-  QtProperty *m_workspace;
-  QtProperty *m_workspaceIndex;
-  QtProperty *m_startX;
-  QtProperty *m_endX;
-  QtProperty *m_output;
-  QtProperty *m_minimizer;
-  QtProperty *m_costFunction;
-  QtProperty *m_logValue;
-  QtProperty *m_plotDiff;
-
-  /// A list of registered functions
-  mutable QStringList m_registeredFunctions;
-  /// A list of registered peaks
-  mutable QStringList m_registeredPeaks;
-  /// A list of registered backgrounds
-  mutable QStringList m_registeredBackgrounds;
-  /// A list of registered functions that are neither peaks nor backgrounds
-  mutable QStringList m_registeredOther;
-  /// A list of available workspaces
-  mutable QStringList m_workspaceNames;
-  /// A list of available minimizers
-  mutable QStringList m_minimizers;
-  /// A list of available cost functions
-  mutable QStringList m_costFunctions;
-
+  mutable PropertyHandler* m_currentHandler;
+
+  /// Group for functions
+  QtBrowserItem* m_functionsGroup;
+  /// Group for input/output settings
+  QtBrowserItem* m_settingsGroup;
+
+  QtProperty *m_workspace;
+  QtProperty *m_workspaceIndex;
+  QtProperty *m_startX;
+  QtProperty *m_endX;
+  QtProperty *m_output;
+  QtProperty *m_minimizer;
+  QtProperty *m_costFunction;
+  QtProperty *m_logValue;
+  QtProperty *m_plotDiff;
+
+  /// A list of registered functions
+  mutable QStringList m_registeredFunctions;
+  /// A list of registered peaks
+  mutable QStringList m_registeredPeaks;
+  /// A list of registered backgrounds
+  mutable QStringList m_registeredBackgrounds;
+  /// A list of registered functions that are neither peaks nor backgrounds
+  mutable QStringList m_registeredOther;
+  /// A list of available workspaces
+  mutable QStringList m_workspaceNames;
+  /// A list of available minimizers
+  mutable QStringList m_minimizers;
+  /// A list of available cost functions
+  mutable QStringList m_costFunctions;
+
   /// A copy of the edited function
   Mantid::API::CompositeFunction* m_compositeFunction;
   /// To keep a copy of the initial parameters in case for undo fit
@@ -395,10 +395,10 @@ private:
   friend class SetAttribute;
   friend class SetAttributeProperty;
   friend class SequentialFitDialog;
-
-};
-
-
-
-
+
+};
+
+
+
+
 #endif /*FITPROPERTYBROWSER_H_*/
\ No newline at end of file
diff --git a/Code/Mantid/MantidPlot/src/Mantid/IFunctionWrapper.cpp b/Code/Mantid/MantidPlot/src/Mantid/IFunctionWrapper.cpp
index 3ffd0599faa0bfdd5b69ec7f270c7979e478ae85..645e26533e874f6daf8f9da63519a74471293b0a 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/IFunctionWrapper.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/IFunctionWrapper.cpp
@@ -1,27 +1,27 @@
-#include "IFunctionWrapper.h"
-#include "MantidAPI/FunctionFactory.h"
-#include "MantidAPI/CompositeFunctionMW.h"
-#include "MantidAPI/IPeakFunction.h"
-
-void IFunctionWrapper::setFunction(const QString& name)
-{
-  try
-  {
-    m_function = dynamic_cast<Mantid::API::CompositeFunctionMW*>(Mantid::API::FunctionFactory::Instance().createFunction(name.toStdString()));
-    m_compositeFunction = dynamic_cast<Mantid::API::CompositeFunctionMW*>(m_function);
-    m_peakFunction = dynamic_cast<Mantid::API::IPeakFunction*>(m_function);
-  }
-  catch(...)
-  {
-    m_function = NULL;
-    m_compositeFunction = NULL;
-    m_peakFunction = NULL;
-  }
-}
-
-void IFunctionWrapper::setFunction(Mantid::API::IFitFunction* function)
-{
-  m_function = function;
-  m_compositeFunction = dynamic_cast<Mantid::API::CompositeFunctionMW*>(m_function);
-  m_peakFunction = dynamic_cast<Mantid::API::IPeakFunction*>(m_function);
-}
+#include "IFunctionWrapper.h"
+#include "MantidAPI/FunctionFactory.h"
+#include "MantidAPI/CompositeFunctionMW.h"
+#include "MantidAPI/IPeakFunction.h"
+
+void IFunctionWrapper::setFunction(const QString& name)
+{
+  try
+  {
+    m_function = dynamic_cast<Mantid::API::CompositeFunctionMW*>(Mantid::API::FunctionFactory::Instance().createFunction(name.toStdString()));
+    m_compositeFunction = dynamic_cast<Mantid::API::CompositeFunctionMW*>(m_function);
+    m_peakFunction = dynamic_cast<Mantid::API::IPeakFunction*>(m_function);
+  }
+  catch(...)
+  {
+    m_function = NULL;
+    m_compositeFunction = NULL;
+    m_peakFunction = NULL;
+  }
+}
+
+void IFunctionWrapper::setFunction(Mantid::API::IFitFunction* function)
+{
+  m_function = function;
+  m_compositeFunction = dynamic_cast<Mantid::API::CompositeFunctionMW*>(m_function);
+  m_peakFunction = dynamic_cast<Mantid::API::IPeakFunction*>(m_function);
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/IFunctionWrapper.h b/Code/Mantid/MantidPlot/src/Mantid/IFunctionWrapper.h
index 732cee8a4031e14677b4c8546e0fda79c7565e93..bf632ccfc4ab4ca6d21889c1a793c6585b81babf 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/IFunctionWrapper.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/IFunctionWrapper.h
@@ -1,22 +1,22 @@
-#ifndef IFUNCTIONWRAPPER_H
-#define IFUNCTIONWRAPPER_H
-
-#include <QObject>
-
-namespace Mantid
-{
-  namespace API
-  {
-    class IFitFunction;
-    class CompositeFunctionMW;
-    class IPeakFunction;
-  }
-}
-
-/**
- * IFunctionWrapper is a wrapper for IFunction pointer which is a QObject
- * and can send and recieve signals.
- */
+#ifndef IFUNCTIONWRAPPER_H
+#define IFUNCTIONWRAPPER_H
+
+#include <QObject>
+
+namespace Mantid
+{
+  namespace API
+  {
+    class IFitFunction;
+    class CompositeFunctionMW;
+    class IPeakFunction;
+  }
+}
+
+/**
+ * IFunctionWrapper is a wrapper for IFunction pointer which is a QObject
+ * and can send and recieve signals.
+ */
 class IFunctionWrapper: public QObject
 {
   Q_OBJECT
@@ -40,5 +40,5 @@ private:
   Mantid::API::CompositeFunctionMW* m_compositeFunction;
   Mantid::API::IPeakFunction* m_peakFunction;
 };
-
-#endif /* IFUNCTIONWRAPPER_H */
+
+#endif /* IFUNCTIONWRAPPER_H */
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InputHistory.cpp b/Code/Mantid/MantidPlot/src/Mantid/InputHistory.cpp
index 8af4e08ad678373ca244286f98519a2562fc0021..8f1e530dfd673c1bc551d086b10d7a8273ee6ad4 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InputHistory.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InputHistory.cpp
@@ -1,10 +1,10 @@
-#include "InputHistory.h"
-#include <MantidAPI/Algorithm.h>
-
-#include <QSettings>
+#include "InputHistory.h"
+#include <MantidAPI/Algorithm.h>
+
+#include <QSettings>
 #include <vector>
-#include <iostream>
-
+#include <iostream>
+
 using namespace Mantid::API;
 using namespace Mantid::Kernel;
 
@@ -30,14 +30,14 @@ InputHistoryImpl::InputHistoryImpl()
     for(int i=0;i<algNames.size();i++)
     {
         QString algName = algNames[i];
-        QList< PropertyData > prop_hist_list;
+        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);
+            PropertyData prop_hist(keys[i],value);
+            prop_hist_list.push_back(prop_hist);
         }
         settings.endGroup();
         m_history[algName] = prop_hist_list;
@@ -60,8 +60,8 @@ void InputHistoryImpl::save()
         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);
+        for(QList< PropertyData >::const_iterator prop=prop_hist.begin();prop!=prop_hist.end();prop++)
+            settings.setValue(prop->name,prop->value);
         settings.endGroup();
     }
     settings.endGroup();
@@ -72,20 +72,20 @@ void InputHistoryImpl::save()
 */
 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);
-    }
-    m_history[QString::fromStdString(alg->name())] = prop_hist_list;
+    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);
+    }
+    m_history[QString::fromStdString(alg->name())] = prop_hist_list;
 }
 
 void InputHistoryImpl::printAll()
@@ -96,8 +96,8 @@ void InputHistoryImpl::printAll()
         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';
+        for(QList< PropertyData >::const_iterator prop=prop_list.begin();prop!=prop_list.end();prop++)
+            std::cerr<<prop->name.toStdString()<<": "<<prop->value.toStdString()<<'\n';
     }
 }
 
@@ -111,9 +111,9 @@ QMap< QString,QString > InputHistoryImpl::algorithmProperties(const QString& alg
     {
         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;
+        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 >();
 }
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InputHistory.h b/Code/Mantid/MantidPlot/src/Mantid/InputHistory.h
index 54f0d6719be9ca73b1e88a45729624eacebcf8b0..28f2fcaad60940165dad8f49eceaf8e012901ceb 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InputHistory.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InputHistory.h
@@ -24,34 +24,34 @@ struct PropertyData
     QString value;
 };
 
-/** @class InputHistory
-
- Keeps history of Mantid-related user input, such as algorithm parameters, etc.
-
- @author Roman Tolchenov, Tessella Support Services plc
- @date 15/10/2008
-
- Copyright &copy; 2007-8 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>.
- Code Documentation is available at: <http://doxygen.mantidproject.org>
- */
-
+/** @class InputHistory
+
+ Keeps history of Mantid-related user input, such as algorithm parameters, etc.
+
+ @author Roman Tolchenov, Tessella Support Services plc
+ @date 15/10/2008
+
+ Copyright &copy; 2007-8 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>.
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+ */
+
 class InputHistoryImpl
 {
 public:
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/BinDialog.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/BinDialog.cpp
index 6568f5e3a71ee64b90d5e01f56349726ef2fb54e..02d7be28e1c98def26e69ac08281b6017aa45a85 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/BinDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/BinDialog.cpp
@@ -1,94 +1,94 @@
-#include "BinDialog.h"
-
-///< Qt Includes
-#include <QString>
-#include <QGroupBox>
-#include <QGridLayout>
-#include <QDoubleValidator>
-#include <QPushButton>
-#include <QLabel>
-#include <QLineEdit>
-#include <QRadioButton>
-
-/**
- *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);
-
-	//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 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()
-{
-}
-
-/** 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);
-}
-
-
-/** 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);
-}
+#include "BinDialog.h"
+
+///< Qt Includes
+#include <QString>
+#include <QGroupBox>
+#include <QGridLayout>
+#include <QDoubleValidator>
+#include <QPushButton>
+#include <QLabel>
+#include <QLineEdit>
+#include <QRadioButton>
+
+/**
+ *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);
+
+	//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 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()
+{
+}
+
+/** 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);
+}
+
+
+/** 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);
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/BinDialog.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/BinDialog.h
index b7035e0195474e39243093f32fd7e87c734a30fb..a03c3bfb2efbca0bf6ce0dfb65c6c8174d10f381 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/BinDialog.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/BinDialog.h
@@ -1,12 +1,12 @@
-#ifndef BINDIALOG_H_
-#define BINDIALOG_H_
+#ifndef BINDIALOG_H_
+#define BINDIALOG_H_
 
-#include <QDialog>
-#include <QCheckBox>
+#include <QDialog>
+#include <QCheckBox>
 
 // Qt forward declarations
 class QLineEdit;
-class QRadioButton;
+class QRadioButton;
 
 /**
   \class  BinDialog
@@ -15,10 +15,10 @@ class QRadioButton;
   \date   November 2008
   \version 1.0
 
-  BinDialog class handles the Input Dialog for bin selection:
-  e.g. enter bin range from X1 to X2.
+  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
+  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
 
   This file is part of Mantid.
  	
@@ -36,32 +36,32 @@ class QRadioButton;
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
   
   File change history is stored at: <https://svn.mantidproject.org/mantid/trunk/Code/Mantid>
- */
+ */
 
 
-class BinDialog: public QDialog
-{
-  Q_OBJECT
-
+class BinDialog: public QDialog
+{
+  Q_OBJECT
+
 public:
   BinDialog(QWidget *parent = 0);
-  ~BinDialog();
-  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;
-
-};
-
-#endif /*BINDIALOG_H_*/
-
+  ~BinDialog();
+  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;
+
+};
+
+#endif /*BINDIALOG_H_*/
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/CompAssemblyActor.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/CompAssemblyActor.cpp
index 04ebba7215dc691baf19ee01a50d642a032e2dd7..d32651611e1524979aa10e18b76ff7c2a555e68e 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/CompAssemblyActor.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/CompAssemblyActor.cpp
@@ -1,409 +1,409 @@
-#include "MantidGeometry/IInstrument.h"
-#include "MantidGeometry/V3D.h"
-#include "MantidGeometry/Objects/Object.h"
-#include "MantidGeometry/ICompAssembly.h"
-#include "MantidGeometry/Instrument/ObjCompAssembly.h"
-//#include "MantidGeometry/Instrument/ParObjCompAssembly.h"
-#include "MantidGeometry/IObjComponent.h"
-#include "MantidGeometry/IDetector.h"
-#include "MantidGeometry/Instrument/RectangularDetector.h"
-#include "MantidKernel/Exception.h"
-#include "MantidObject.h"
-#include "CompAssemblyActor.h"
-#include "ObjComponentActor.h"
-#include "ObjCompAssemblyActor.h"
-#include "RectangularDetectorActor.h"
-#include <cfloat>
-
-using Mantid::Geometry::IInstrument;
-using Mantid::Geometry::IComponent;
-using Mantid::Geometry::IObjComponent;
-using Mantid::Geometry::ICompAssembly;
-using Mantid::Geometry::ObjCompAssembly;
-//using Mantid::Geometry::ParObjCompAssembly;
-using Mantid::Geometry::ComponentID;
-using Mantid::Geometry::RectangularDetector;
-using Mantid::Geometry::RectangularDetector;
-using Mantid::Geometry::IDetector;
-using Mantid::Geometry::Object;
-
-
-/**
- * This is default constructor for CompAssembly Actor
- * @param withDisplayList :: true to create a display list for the compassembly and its subcomponents
- */
-CompAssemblyActor::CompAssemblyActor(bool withDisplayList):
-    ICompAssemblyActor(withDisplayList)
-{
-}
-
-/**
- * This is a constructor for CompAssembly Actor
- * @param objs :: list of objects that are used by IObjCompenent actors and will be filled with the new objects
- * @param id :: ComponentID of this object of CompAssembly
- * @param ins :: Instrument
- * @param withDisplayList :: true to create a display list for the compassembly and its subcomponents
- */
-CompAssemblyActor::CompAssemblyActor(
-    boost::shared_ptr<std::map<const boost::shared_ptr<const Object>,MantidObject*> >& objs,
-    ComponentID id,boost::shared_ptr<IInstrument> ins,
-    bool withDisplayList):
-    ICompAssemblyActor(withDisplayList)
-{
-  // Initialises
-  mId=id;
-  mInstrument=ins;
-  mObjects=objs;
-  this->setName( ins->getName() );
-  //Create the subcomponent actors
-  initChilds(withDisplayList);
-}
-
-/**
- * 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::define()
-{
-  mColor->paint(GLColor::MATERIAL);
-  mColor->paint(GLColor::PLAIN);
-  //Only draw the CompAssembly Children only if they are visible
-  if(mVisible)
-  {
-    //Iterate through the ObjCompActor children and draw them
-    for(std::vector<ObjComponentActor*>::iterator itrObjComp=mChildObjCompActors.begin();itrObjComp!=mChildObjCompActors.end();itrObjComp++)
-    {
-      (*itrObjComp)->getColor()->paint(GLColor::MATERIAL);
-      (*itrObjComp)->getColor()->paint(GLColor::PLAIN);
-      //Only draw the ObjCompActor if its visible
-      if((*itrObjComp)->getVisibility())
-      {
-        //std::cout << (*itrObjComp)->getName() << " is gonna draw. From define()\n";
-        (*itrObjComp)->draw();
-      }
-      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++)
-    {
-      //std::cout << (*itrObjAssem)->getName() << " is gonna draw. From define()\n";
-      (*itrObjAssem)->draw();
-    }
-  }
-  else
-  {
-    //std::cout << this->getName() << " is not visible\n";
-  }
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * This method draws the children with the ColorID rather than the children actual color. used in picking the component
- */
-void CompAssemblyActor::drawUsingColorID()
-{
-  //Check whether this assembly and its child components can be drawn
-  if(mVisible)
-  {
-    //Iterate throught the children with the starting reference color mColorStartID and incrementing
-    int rgb=mColorStartID;
-    int r,g,b;
-    for(std::vector<ObjComponentActor*>::iterator itrObjComp=mChildObjCompActors.begin();itrObjComp!=mChildObjCompActors.end();itrObjComp++)
-    {
-      r=(rgb/65536);
-      g=((rgb%65536)/256);
-      b=((rgb%65536)%256);
-      glColor3f(r/255.0,g/255.0,b/255.0);
-      if((*itrObjComp)->getVisibility())
-        (*itrObjComp)->draw();
-      rgb++;
-    }
-    for(std::vector<ICompAssemblyActor*>::iterator itrObjAssem=mChildCompAssemActors.begin();itrObjAssem!=mChildCompAssemActors.end();itrObjAssem++)
-    {
-      (*itrObjAssem)->drawUsingColorID();
-    }
-  }
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * Initialises the CompAssembly Children and creates actors for each children
- * @param withDisplayList :: the new actors for the children with same display list attribute as parent
- */
-void CompAssemblyActor::initChilds(bool withDisplayList)
-{
-  boost::shared_ptr<IComponent> CompPtr;
-  if(mId == mInstrument->getComponentID())
-    CompPtr=mInstrument;
-  else
-    CompPtr=mInstrument->getComponentByID(mId);
-  //bounding box of the overall instrument
-  Mantid::Geometry::V3D minBound;
-  Mantid::Geometry::V3D maxBound;
-  //Iterate through CompAssembly children
-  boost::shared_ptr<ICompAssembly> CompAssemPtr=boost::dynamic_pointer_cast<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<ICompAssembly>())
-      {
-        boost::shared_ptr<ObjCompAssembly> ChildOCAPtr=boost::dynamic_pointer_cast<ObjCompAssembly>(ChildCompPtr);
-        boost::shared_ptr<RectangularDetector> ChildRDPtr=boost::dynamic_pointer_cast<RectangularDetector>(ChildCompPtr);
-
-        if (ChildRDPtr)
-        {
-          //If the child is a RectangularDetector, then create a RectangularDetectorActor for it.
-          RectangularDetectorActor* iActor = new RectangularDetectorActor(ChildRDPtr);
-          iActor->getBoundingBox(minBound,maxBound);
-          AppendBoundingBox(minBound,maxBound);
-          mNumberOfDetectors+=iActor->getNumberOfDetectors();
-          mChildCompAssemActors.push_back(iActor);
-        }
-        else if (ChildOCAPtr)
-        {
-          ObjCompAssemblyActor* iActor =
-              new ObjCompAssemblyActor(mObjects,ChildCAPtr->getComponentID(),mInstrument,withDisplayList);
-          iActor->getBoundingBox(minBound,maxBound);
-          AppendBoundingBox(minBound,maxBound);
-          mNumberOfDetectors+=iActor->getNumberOfDetectors();
-          mChildCompAssemActors.push_back(iActor);
-        }
-        else
-        {
-          CompAssemblyActor* iActor=new CompAssemblyActor(mObjects,ChildCAPtr->getComponentID(),mInstrument,withDisplayList);
-          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(getMantidObject(ChildObjPtr->shape(),withDisplayList), ChildObjPtr,false);
-        iActor->getBoundingBox(minBound,maxBound);
-        AppendBoundingBox(minBound,maxBound);
-        mChildObjCompActors.push_back(iActor);
-        mNumberOfDetectors++;
-      }
-    }
-  }
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * This method checks the list of Objects in mObjects for obj, if found returns the MantidObject. if the obj is not found
- * then creates a new MantidObject for obj and adds to the list of mObjects and returns the newly created MantidObject.
- * @param obj :: Object input for which MantidObject needed
- * @param withDisplayList :: whether the new MantidObject if needed uses the display list attribute
- * @return  the MantidObject corresponding to the obj.
- */
-MantidObject*	CompAssemblyActor::getMantidObject(const boost::shared_ptr<const Mantid::Geometry::Object> obj, bool withDisplayList)
-{
-  if (!obj)
-  {
-    throw std::runtime_error("An instrument component does not have a shape.");
-  }
-  std::map<const boost::shared_ptr<const Object>,MantidObject*>::iterator iObj=mObjects->find(obj);
-  if(iObj==mObjects->end()) //create an new Mantid Object
-  {
-    MantidObject* retObj=new MantidObject(obj,withDisplayList);
-    retObj->draw();
-    mObjects->insert(mObjects->begin(),std::pair<const boost::shared_ptr<const Object>,MantidObject*>(obj,retObj));
-    return retObj;
-  }
-  return (*iObj).second;
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * Concrete implementation of init method of GLObject. this method draws the children
- */
-void CompAssemblyActor::init()
-{
-  for_each(mChildObjCompActors.begin(),mChildObjCompActors.end(),std::mem_fun(&GLActor::draw));
-  for_each(mChildCompAssemActors.begin(),mChildCompAssemActors.end(),std::mem_fun(&GLActor::draw));
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * This method adds the detector ids of the children of CompAssembly to the input idList.
- * @param idList :: output list of detector ids for child detectors
- */
-void CompAssemblyActor::appendObjCompID(std::vector<int>& idList)
-{
-  for(std::vector<ObjComponentActor*>::const_iterator iObjComp=mChildObjCompActors.begin();iObjComp!=mChildObjCompActors.end(); ++iObjComp)
-  {
-    //If the object is a detector or a RectangularDetector, it will append the ID(s)
-    (*iObjComp)->appendObjCompID(idList);
-  }
-
-  for(std::vector<ICompAssemblyActor*>::const_iterator iAssem=mChildCompAssemActors.begin();iAssem!=mChildCompAssemActors.end(); ++iAssem)
-  {
-    (*iAssem)->appendObjCompID(idList);
-  }
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * The colors are set using the iterator of the color list. The order of the detectors
- * in this color list was defined by the calls to appendObjCompID().
- *
- * @param list :: Color list iterator
- * @return the number of detectors
- */
-int CompAssemblyActor::setInternalDetectorColors(std::vector<boost::shared_ptr<GLColor> >::iterator & list)
-{
-  int count=0;
-  for(std::vector<ObjComponentActor*>::iterator iObjComp=mChildObjCompActors.begin();iObjComp!=mChildObjCompActors.end();iObjComp++)
-  {
-    //Each child will set its color and increment the list
-    int num=(*iObjComp)->setInternalDetectorColors(list);
-    count+=num;
-  }
-
-  for(std::vector<ICompAssemblyActor*>::iterator iAssem = mChildCompAssemActors.begin();iAssem!=mChildCompAssemActors.end();iAssem++)
-  {
-    //Each assembly does the same
-    int num=(*iAssem)->setInternalDetectorColors(list);
-    //list+=num;
-    count+=num;
-  }
-  //std::cout << "CompAssemblyActor::setInternalDetectorColors() called with "<< count << " entries added.\n";
-  return count;
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * This method redraws the CompAssembly children compassembly actors redraw. this method is used to redraw all the children
- */
-void CompAssemblyActor::redraw()
-{
-  mChanged=true;
-  for(std::vector<ICompAssemblyActor*>::iterator iAssem=mChildCompAssemActors.begin();iAssem!=mChildCompAssemActors.end();iAssem++)
-    (*iAssem)->redraw();
-  construct();
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * Set the starting color reference for CompAssembly
- * @param rgb :: input color id
- * @return  the number of color ids that are used.
- */
-int CompAssemblyActor::setStartingReferenceColor(int rgb)
-{
-  mColorStartID=rgb;
-  int val = rgb;
-  for(std::vector<ObjComponentActor*>::iterator itrObjComp=mChildObjCompActors.begin();itrObjComp!=mChildObjCompActors.end();itrObjComp++)
-    {
-      (*itrObjComp)->setStartingReferenceColor(val);
-      val++;
-    }
-  for(std::vector<ICompAssemblyActor*>::iterator itrObjAssem=mChildCompAssemActors.begin();itrObjAssem!=mChildCompAssemActors.end();itrObjAssem++)
-    {
-      val+=(*itrObjAssem)->setStartingReferenceColor(val);
-    }
-  return val-rgb;
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * This method searches the child actors for the input rgb color and returns the detector id corresponding to the rgb color. if the
- * detector is not found then returns -1.
- * @param  rgb :: input color id
- * @return the detector id of the input rgb color.if detector id not found then returns -1
- */
-int CompAssemblyActor::findDetectorIDUsingColor(int rgb)
-{
-  int n_comp_actors = static_cast<int>(mChildObjCompActors.size());
-  int diff_rgb = rgb - this->mColorStartID;
-  if(diff_rgb >= 0 && diff_rgb < n_comp_actors)
-  {
-    const boost::shared_ptr<IDetector>  iDec= boost::dynamic_pointer_cast<IDetector>((mChildObjCompActors[diff_rgb])->getObjComponent());
-    if(iDec!=boost::shared_ptr<IDetector>())
-    {
-      return iDec->getID();
-    }
-  }
-
-  for(std::vector<ICompAssemblyActor*>::iterator iAssem=mChildCompAssemActors.begin();iAssem!=mChildCompAssemActors.end();iAssem++)
-  {
-    int colorStart = (*iAssem)->getColorStartID();
-    if(rgb >= colorStart && rgb < (*iAssem)->getNumberOfDetectors()+colorStart )
-      return (*iAssem)->findDetectorIDUsingColor(rgb);
-  }
-  return -1;
-}
-
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * 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::Geometry::V3D& minBound,const Mantid::Geometry::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::addToUnwrappedList(UnwrappedCylinder& cylinder, QList<UnwrappedDetectorCyl>& list)
-//{
-//  for(std::vector<ObjComponentActor*>::iterator iObjComp=mChildObjCompActors.begin();iObjComp!=mChildObjCompActors.end();iObjComp++)
-//  {
-//    (**iObjComp).addToUnwrappedList(cylinder,list);
-//  }
-
-//  for(std::vector<ICompAssemblyActor*>::iterator iAssem = mChildCompAssemActors.begin();iAssem!=mChildCompAssemActors.end();iAssem++)
-//  {
-//    (**iAssem).addToUnwrappedList(cylinder,list);
-//  }
-//}
-
-void CompAssemblyActor::detectorCallback(DetectorCallback* callback)const
-{
-  for(std::vector<ObjComponentActor*>::const_iterator iObjComp=mChildObjCompActors.begin();iObjComp!=mChildObjCompActors.end();iObjComp++)
-  {
-    (**iObjComp).detectorCallback(callback);
-  }
-
-  for(std::vector<ICompAssemblyActor*>::const_iterator iAssem = mChildCompAssemActors.begin();iAssem!=mChildCompAssemActors.end();iAssem++)
-  {
-    (**iAssem).detectorCallback(callback);
-  }
-}
+#include "MantidGeometry/IInstrument.h"
+#include "MantidGeometry/V3D.h"
+#include "MantidGeometry/Objects/Object.h"
+#include "MantidGeometry/ICompAssembly.h"
+#include "MantidGeometry/Instrument/ObjCompAssembly.h"
+//#include "MantidGeometry/Instrument/ParObjCompAssembly.h"
+#include "MantidGeometry/IObjComponent.h"
+#include "MantidGeometry/IDetector.h"
+#include "MantidGeometry/Instrument/RectangularDetector.h"
+#include "MantidKernel/Exception.h"
+#include "MantidObject.h"
+#include "CompAssemblyActor.h"
+#include "ObjComponentActor.h"
+#include "ObjCompAssemblyActor.h"
+#include "RectangularDetectorActor.h"
+#include <cfloat>
+
+using Mantid::Geometry::IInstrument;
+using Mantid::Geometry::IComponent;
+using Mantid::Geometry::IObjComponent;
+using Mantid::Geometry::ICompAssembly;
+using Mantid::Geometry::ObjCompAssembly;
+//using Mantid::Geometry::ParObjCompAssembly;
+using Mantid::Geometry::ComponentID;
+using Mantid::Geometry::RectangularDetector;
+using Mantid::Geometry::RectangularDetector;
+using Mantid::Geometry::IDetector;
+using Mantid::Geometry::Object;
+
+
+/**
+ * This is default constructor for CompAssembly Actor
+ * @param withDisplayList :: true to create a display list for the compassembly and its subcomponents
+ */
+CompAssemblyActor::CompAssemblyActor(bool withDisplayList):
+    ICompAssemblyActor(withDisplayList)
+{
+}
+
+/**
+ * This is a constructor for CompAssembly Actor
+ * @param objs :: list of objects that are used by IObjCompenent actors and will be filled with the new objects
+ * @param id :: ComponentID of this object of CompAssembly
+ * @param ins :: Instrument
+ * @param withDisplayList :: true to create a display list for the compassembly and its subcomponents
+ */
+CompAssemblyActor::CompAssemblyActor(
+    boost::shared_ptr<std::map<const boost::shared_ptr<const Object>,MantidObject*> >& objs,
+    ComponentID id,boost::shared_ptr<IInstrument> ins,
+    bool withDisplayList):
+    ICompAssemblyActor(withDisplayList)
+{
+  // Initialises
+  mId=id;
+  mInstrument=ins;
+  mObjects=objs;
+  this->setName( ins->getName() );
+  //Create the subcomponent actors
+  initChilds(withDisplayList);
+}
+
+/**
+ * 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::define()
+{
+  mColor->paint(GLColor::MATERIAL);
+  mColor->paint(GLColor::PLAIN);
+  //Only draw the CompAssembly Children only if they are visible
+  if(mVisible)
+  {
+    //Iterate through the ObjCompActor children and draw them
+    for(std::vector<ObjComponentActor*>::iterator itrObjComp=mChildObjCompActors.begin();itrObjComp!=mChildObjCompActors.end();itrObjComp++)
+    {
+      (*itrObjComp)->getColor()->paint(GLColor::MATERIAL);
+      (*itrObjComp)->getColor()->paint(GLColor::PLAIN);
+      //Only draw the ObjCompActor if its visible
+      if((*itrObjComp)->getVisibility())
+      {
+        //std::cout << (*itrObjComp)->getName() << " is gonna draw. From define()\n";
+        (*itrObjComp)->draw();
+      }
+      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++)
+    {
+      //std::cout << (*itrObjAssem)->getName() << " is gonna draw. From define()\n";
+      (*itrObjAssem)->draw();
+    }
+  }
+  else
+  {
+    //std::cout << this->getName() << " is not visible\n";
+  }
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * This method draws the children with the ColorID rather than the children actual color. used in picking the component
+ */
+void CompAssemblyActor::drawUsingColorID()
+{
+  //Check whether this assembly and its child components can be drawn
+  if(mVisible)
+  {
+    //Iterate throught the children with the starting reference color mColorStartID and incrementing
+    int rgb=mColorStartID;
+    int r,g,b;
+    for(std::vector<ObjComponentActor*>::iterator itrObjComp=mChildObjCompActors.begin();itrObjComp!=mChildObjCompActors.end();itrObjComp++)
+    {
+      r=(rgb/65536);
+      g=((rgb%65536)/256);
+      b=((rgb%65536)%256);
+      glColor3f(r/255.0,g/255.0,b/255.0);
+      if((*itrObjComp)->getVisibility())
+        (*itrObjComp)->draw();
+      rgb++;
+    }
+    for(std::vector<ICompAssemblyActor*>::iterator itrObjAssem=mChildCompAssemActors.begin();itrObjAssem!=mChildCompAssemActors.end();itrObjAssem++)
+    {
+      (*itrObjAssem)->drawUsingColorID();
+    }
+  }
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Initialises the CompAssembly Children and creates actors for each children
+ * @param withDisplayList :: the new actors for the children with same display list attribute as parent
+ */
+void CompAssemblyActor::initChilds(bool withDisplayList)
+{
+  boost::shared_ptr<IComponent> CompPtr;
+  if(mId == mInstrument->getComponentID())
+    CompPtr=mInstrument;
+  else
+    CompPtr=mInstrument->getComponentByID(mId);
+  //bounding box of the overall instrument
+  Mantid::Geometry::V3D minBound;
+  Mantid::Geometry::V3D maxBound;
+  //Iterate through CompAssembly children
+  boost::shared_ptr<ICompAssembly> CompAssemPtr=boost::dynamic_pointer_cast<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<ICompAssembly>())
+      {
+        boost::shared_ptr<ObjCompAssembly> ChildOCAPtr=boost::dynamic_pointer_cast<ObjCompAssembly>(ChildCompPtr);
+        boost::shared_ptr<RectangularDetector> ChildRDPtr=boost::dynamic_pointer_cast<RectangularDetector>(ChildCompPtr);
+
+        if (ChildRDPtr)
+        {
+          //If the child is a RectangularDetector, then create a RectangularDetectorActor for it.
+          RectangularDetectorActor* iActor = new RectangularDetectorActor(ChildRDPtr);
+          iActor->getBoundingBox(minBound,maxBound);
+          AppendBoundingBox(minBound,maxBound);
+          mNumberOfDetectors+=iActor->getNumberOfDetectors();
+          mChildCompAssemActors.push_back(iActor);
+        }
+        else if (ChildOCAPtr)
+        {
+          ObjCompAssemblyActor* iActor =
+              new ObjCompAssemblyActor(mObjects,ChildCAPtr->getComponentID(),mInstrument,withDisplayList);
+          iActor->getBoundingBox(minBound,maxBound);
+          AppendBoundingBox(minBound,maxBound);
+          mNumberOfDetectors+=iActor->getNumberOfDetectors();
+          mChildCompAssemActors.push_back(iActor);
+        }
+        else
+        {
+          CompAssemblyActor* iActor=new CompAssemblyActor(mObjects,ChildCAPtr->getComponentID(),mInstrument,withDisplayList);
+          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(getMantidObject(ChildObjPtr->shape(),withDisplayList), ChildObjPtr,false);
+        iActor->getBoundingBox(minBound,maxBound);
+        AppendBoundingBox(minBound,maxBound);
+        mChildObjCompActors.push_back(iActor);
+        mNumberOfDetectors++;
+      }
+    }
+  }
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * This method checks the list of Objects in mObjects for obj, if found returns the MantidObject. if the obj is not found
+ * then creates a new MantidObject for obj and adds to the list of mObjects and returns the newly created MantidObject.
+ * @param obj :: Object input for which MantidObject needed
+ * @param withDisplayList :: whether the new MantidObject if needed uses the display list attribute
+ * @return  the MantidObject corresponding to the obj.
+ */
+MantidObject*	CompAssemblyActor::getMantidObject(const boost::shared_ptr<const Mantid::Geometry::Object> obj, bool withDisplayList)
+{
+  if (!obj)
+  {
+    throw std::runtime_error("An instrument component does not have a shape.");
+  }
+  std::map<const boost::shared_ptr<const Object>,MantidObject*>::iterator iObj=mObjects->find(obj);
+  if(iObj==mObjects->end()) //create an new Mantid Object
+  {
+    MantidObject* retObj=new MantidObject(obj,withDisplayList);
+    retObj->draw();
+    mObjects->insert(mObjects->begin(),std::pair<const boost::shared_ptr<const Object>,MantidObject*>(obj,retObj));
+    return retObj;
+  }
+  return (*iObj).second;
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Concrete implementation of init method of GLObject. this method draws the children
+ */
+void CompAssemblyActor::init()
+{
+  for_each(mChildObjCompActors.begin(),mChildObjCompActors.end(),std::mem_fun(&GLActor::draw));
+  for_each(mChildCompAssemActors.begin(),mChildCompAssemActors.end(),std::mem_fun(&GLActor::draw));
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * This method adds the detector ids of the children of CompAssembly to the input idList.
+ * @param idList :: output list of detector ids for child detectors
+ */
+void CompAssemblyActor::appendObjCompID(std::vector<int>& idList)
+{
+  for(std::vector<ObjComponentActor*>::const_iterator iObjComp=mChildObjCompActors.begin();iObjComp!=mChildObjCompActors.end(); ++iObjComp)
+  {
+    //If the object is a detector or a RectangularDetector, it will append the ID(s)
+    (*iObjComp)->appendObjCompID(idList);
+  }
+
+  for(std::vector<ICompAssemblyActor*>::const_iterator iAssem=mChildCompAssemActors.begin();iAssem!=mChildCompAssemActors.end(); ++iAssem)
+  {
+    (*iAssem)->appendObjCompID(idList);
+  }
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * The colors are set using the iterator of the color list. The order of the detectors
+ * in this color list was defined by the calls to appendObjCompID().
+ *
+ * @param list :: Color list iterator
+ * @return the number of detectors
+ */
+int CompAssemblyActor::setInternalDetectorColors(std::vector<boost::shared_ptr<GLColor> >::iterator & list)
+{
+  int count=0;
+  for(std::vector<ObjComponentActor*>::iterator iObjComp=mChildObjCompActors.begin();iObjComp!=mChildObjCompActors.end();iObjComp++)
+  {
+    //Each child will set its color and increment the list
+    int num=(*iObjComp)->setInternalDetectorColors(list);
+    count+=num;
+  }
+
+  for(std::vector<ICompAssemblyActor*>::iterator iAssem = mChildCompAssemActors.begin();iAssem!=mChildCompAssemActors.end();iAssem++)
+  {
+    //Each assembly does the same
+    int num=(*iAssem)->setInternalDetectorColors(list);
+    //list+=num;
+    count+=num;
+  }
+  //std::cout << "CompAssemblyActor::setInternalDetectorColors() called with "<< count << " entries added.\n";
+  return count;
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * This method redraws the CompAssembly children compassembly actors redraw. this method is used to redraw all the children
+ */
+void CompAssemblyActor::redraw()
+{
+  mChanged=true;
+  for(std::vector<ICompAssemblyActor*>::iterator iAssem=mChildCompAssemActors.begin();iAssem!=mChildCompAssemActors.end();iAssem++)
+    (*iAssem)->redraw();
+  construct();
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Set the starting color reference for CompAssembly
+ * @param rgb :: input color id
+ * @return  the number of color ids that are used.
+ */
+int CompAssemblyActor::setStartingReferenceColor(int rgb)
+{
+  mColorStartID=rgb;
+  int val = rgb;
+  for(std::vector<ObjComponentActor*>::iterator itrObjComp=mChildObjCompActors.begin();itrObjComp!=mChildObjCompActors.end();itrObjComp++)
+    {
+      (*itrObjComp)->setStartingReferenceColor(val);
+      val++;
+    }
+  for(std::vector<ICompAssemblyActor*>::iterator itrObjAssem=mChildCompAssemActors.begin();itrObjAssem!=mChildCompAssemActors.end();itrObjAssem++)
+    {
+      val+=(*itrObjAssem)->setStartingReferenceColor(val);
+    }
+  return val-rgb;
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * This method searches the child actors for the input rgb color and returns the detector id corresponding to the rgb color. if the
+ * detector is not found then returns -1.
+ * @param  rgb :: input color id
+ * @return the detector id of the input rgb color.if detector id not found then returns -1
+ */
+int CompAssemblyActor::findDetectorIDUsingColor(int rgb)
+{
+  int n_comp_actors = static_cast<int>(mChildObjCompActors.size());
+  int diff_rgb = rgb - this->mColorStartID;
+  if(diff_rgb >= 0 && diff_rgb < n_comp_actors)
+  {
+    const boost::shared_ptr<IDetector>  iDec= boost::dynamic_pointer_cast<IDetector>((mChildObjCompActors[diff_rgb])->getObjComponent());
+    if(iDec!=boost::shared_ptr<IDetector>())
+    {
+      return iDec->getID();
+    }
+  }
+
+  for(std::vector<ICompAssemblyActor*>::iterator iAssem=mChildCompAssemActors.begin();iAssem!=mChildCompAssemActors.end();iAssem++)
+  {
+    int colorStart = (*iAssem)->getColorStartID();
+    if(rgb >= colorStart && rgb < (*iAssem)->getNumberOfDetectors()+colorStart )
+      return (*iAssem)->findDetectorIDUsingColor(rgb);
+  }
+  return -1;
+}
+
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * 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::Geometry::V3D& minBound,const Mantid::Geometry::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::addToUnwrappedList(UnwrappedCylinder& cylinder, QList<UnwrappedDetectorCyl>& list)
+//{
+//  for(std::vector<ObjComponentActor*>::iterator iObjComp=mChildObjCompActors.begin();iObjComp!=mChildObjCompActors.end();iObjComp++)
+//  {
+//    (**iObjComp).addToUnwrappedList(cylinder,list);
+//  }
+
+//  for(std::vector<ICompAssemblyActor*>::iterator iAssem = mChildCompAssemActors.begin();iAssem!=mChildCompAssemActors.end();iAssem++)
+//  {
+//    (**iAssem).addToUnwrappedList(cylinder,list);
+//  }
+//}
+
+void CompAssemblyActor::detectorCallback(DetectorCallback* callback)const
+{
+  for(std::vector<ObjComponentActor*>::const_iterator iObjComp=mChildObjCompActors.begin();iObjComp!=mChildObjCompActors.end();iObjComp++)
+  {
+    (**iObjComp).detectorCallback(callback);
+  }
+
+  for(std::vector<ICompAssemblyActor*>::const_iterator iAssem = mChildCompAssemActors.begin();iAssem!=mChildCompAssemActors.end();iAssem++)
+  {
+    (**iAssem).detectorCallback(callback);
+  }
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/CompAssemblyActor.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/CompAssemblyActor.h
index eae66417c8f010ba53c8610b69cc0de8527df6e2..01cc4e119e4556608e765073313898c045d91b92 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/CompAssemblyActor.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/CompAssemblyActor.h
@@ -1,79 +1,79 @@
-#ifndef COMPASSEMBLY_ACTOR__H_
-#define COMPASSEMBLY_ACTOR__H_
-#include "GLActor.h"
-#include "ICompAssemblyActor.h"
-#include "MantidGeometry/IComponent.h"
-#include "MantidGeometry/V3D.h"
-/**
-  \class  CompAssemblyActor
-  \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.
-
-  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-namespace Mantid
-{
-
-namespace Geometry
-{
-  class IInstrument;
-  class ICompAssembly;
-  class Object;
-  class V3D;
-}
-
-}
-
-class MantidObject;
-class ObjComponentActor;
-
-class CompAssemblyActor : public ICompAssemblyActor
-{
-private:
-  void AppendBoundingBox(const Mantid::Geometry::V3D& minBound,const Mantid::Geometry::V3D& maxBound);
-protected:
-  std::vector<ObjComponentActor*> mChildObjCompActors;     ///< List of ObjComponent Actors
-  std::vector<ICompAssemblyActor*> mChildCompAssemActors;   ///< List of CompAssembly Actors
-  void initChilds(bool);
-  void init();
-  void redraw();
-  void appendObjCompID(std::vector<int>&);
-  MantidObject*	getMantidObject(const boost::shared_ptr<const Mantid::Geometry::Object>,bool withDisplayList);
-  int setInternalDetectorColors(std::vector<boost::shared_ptr<GLColor> >::iterator& list);
-  int findDetectorIDUsingColor(int rgb);
-public:
-  CompAssemblyActor(bool withDisplayList);                       ///< Constructor
-  CompAssemblyActor(boost::shared_ptr<std::map<const boost::shared_ptr<const Mantid::Geometry::Object>,MantidObject*> >& ,  Mantid::Geometry::ComponentID id, boost::shared_ptr<Mantid::Geometry::IInstrument> ins,bool withDisplayList); ///< Constructor
-  virtual ~CompAssemblyActor();								   ///< Destructor
-  int  setStartingReferenceColor(int rgb);
-  virtual std::string type()const {return "CompAssemblyActor";} ///< Type of the GL object
-  void define();  ///< Method that defines ObjComponent geometry. Calls ObjComponent draw method
-  void drawUsingColorID();
-  //void addToUnwrappedList(UnwrappedCylinder& cylinder, QList<UnwrappedDetectorCyl>& list);
-  void detectorCallback(DetectorCallback* callback)const;
-};
-
-#endif /*GLTRIANGLE_H_*/
-
+#ifndef COMPASSEMBLY_ACTOR__H_
+#define COMPASSEMBLY_ACTOR__H_
+#include "GLActor.h"
+#include "ICompAssemblyActor.h"
+#include "MantidGeometry/IComponent.h"
+#include "MantidGeometry/V3D.h"
+/**
+  \class  CompAssemblyActor
+  \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.
+
+  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+*/
+namespace Mantid
+{
+
+namespace Geometry
+{
+  class IInstrument;
+  class ICompAssembly;
+  class Object;
+  class V3D;
+}
+
+}
+
+class MantidObject;
+class ObjComponentActor;
+
+class CompAssemblyActor : public ICompAssemblyActor
+{
+private:
+  void AppendBoundingBox(const Mantid::Geometry::V3D& minBound,const Mantid::Geometry::V3D& maxBound);
+protected:
+  std::vector<ObjComponentActor*> mChildObjCompActors;     ///< List of ObjComponent Actors
+  std::vector<ICompAssemblyActor*> mChildCompAssemActors;   ///< List of CompAssembly Actors
+  void initChilds(bool);
+  void init();
+  void redraw();
+  void appendObjCompID(std::vector<int>&);
+  MantidObject*	getMantidObject(const boost::shared_ptr<const Mantid::Geometry::Object>,bool withDisplayList);
+  int setInternalDetectorColors(std::vector<boost::shared_ptr<GLColor> >::iterator& list);
+  int findDetectorIDUsingColor(int rgb);
+public:
+  CompAssemblyActor(bool withDisplayList);                       ///< Constructor
+  CompAssemblyActor(boost::shared_ptr<std::map<const boost::shared_ptr<const Mantid::Geometry::Object>,MantidObject*> >& ,  Mantid::Geometry::ComponentID id, boost::shared_ptr<Mantid::Geometry::IInstrument> ins,bool withDisplayList); ///< Constructor
+  virtual ~CompAssemblyActor();								   ///< Destructor
+  int  setStartingReferenceColor(int rgb);
+  virtual std::string type()const {return "CompAssemblyActor";} ///< Type of the GL object
+  void define();  ///< Method that defines ObjComponent geometry. Calls ObjComponent draw method
+  void drawUsingColorID();
+  //void addToUnwrappedList(UnwrappedCylinder& cylinder, QList<UnwrappedDetectorCyl>& list);
+  void detectorCallback(DetectorCallback* callback)const;
+};
+
+#endif /*GLTRIANGLE_H_*/
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GL3DWidget.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GL3DWidget.cpp
index 26da44302e98a556ef1d9ec485a425e9bdd22c2b..166ea7f7ed7a874a7f2107b9eabbb4568cb8d0e7 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GL3DWidget.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GL3DWidget.cpp
@@ -1,1026 +1,1026 @@
-#ifdef WIN32
-#include <windows.h>
-#endif
-#include "GL3DWidget.h"
-#include "GLActor.h"
-#include "GLColor.h"
-#include "InstrumentActor.h"
-#include "UnwrappedCylinder.h"
-#include "UnwrappedSphere.h"
-#include "OpenGLError.h"
-#include "DetSelector.h"
-#include "MantidGeometry/IInstrument.h"
-#include "MantidGeometry/Objects/Object.h"
-
-#include "boost/shared_ptr.hpp"
-
-#include <QtOpenGL>
-#include <QSpinBox>
-#include <QApplication>
-#include <QTime>
-
-#include <map>
-#include <string>
-#include <iostream>
-#include <cfloat>
-#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
-
-
-GL3DWidget::GL3DWidget(QWidget* parent):
-  QGLWidget(QGLFormat(QGL::DepthBuffer|QGL::NoAlphaChannel|QGL::SampleBuffers),parent)
-{
-
-  if (!this->format().depth())
-    std::cout << "Warning! OpenGL Depth buffer could not be initialized.\n";
-  //std::cout << "Depth buffer size is " << this->format().depthBufferSize() << "\n";
-
-  makeCurrent();
-  _viewport=new GLViewport;
-  _trackball=new GLTrackball(_viewport);
-  isKeyPressed=false;
-  scene=boost::shared_ptr<GLActorCollection>(new GLActorCollection());
-  mPickedActor=NULL;
-  mPickingDraw=true;
-  iInteractionMode=GL3DWidget::MoveMode;
-  mPickBox=new GLGroupPickBox();
-  setFocusPolicy(Qt::StrongFocus);
-  setAutoFillBackground(false);
-  bgColor=QColor(0,0,0,1);
-  m3DAxesShown = true;
-  m_polygonMode = SOLID;
-  m_lightingState = 0;
-  m_firstFrame = true;
-  m_renderMode = FULL3D;
-  m_unwrappedSurface = NULL;
-  m_unwrappedSurfaceChanged = true;
-  m_unwrappedViewChanged = true;
-
-  //Enable right-click in pick mode
-  setContextMenuPolicy(Qt::DefaultContextMenu);
-
-}
-
-GL3DWidget::~GL3DWidget()
-{
-  delete _viewport;
-  delete _trackball;
-  if (m_unwrappedSurface)
-  {
-    delete m_unwrappedSurface;
-  }
-}
-
-void GL3DWidget::setInteractionModePick()
-{
-  iInteractionMode = GL3DWidget::PickMode;// Pick mode
-  setMouseTracking(true);
-  mPickingDraw = true;
-  update();
-}
-
-void GL3DWidget::setInteractionModeNormal()
-{
-  iInteractionMode = GL3DWidget::MoveMode;//Normal mode
-  setMouseTracking(false);
-  setCursor(Qt::PointingHandCursor);
-  glEnable(GL_NORMALIZE);
-  if (m_lightingState > 0)
-  {
-    glEnable(GL_LIGHTING);
-  }
-  update();
-}
-
-GLActor* GL3DWidget::getPickedActor()
-{
-  return mPickedActor;
-}
-
-/**
- * This method initializes the opengl settings. its invoked defaultly by Qt when the widget
- * is initialized.
- */
-void GL3DWidget::initializeGL()
-{
-  setCursor(Qt::PointingHandCursor); // This is to set the initial window mouse cursor to Hand icon
-  
-  // Set the relevant OpenGL rendering options
-  setRenderingOptions();
-  
-  // Clear the memory buffers
-  glClearColor(bgColor.red()/255.0,bgColor.green()/255.0,bgColor.blue()/255.0,1.0);
-  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-}
-
-void GL3DWidget::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);
-
-}
-
-/**
- * Toggles the use of high resolution lighting
- * @param state :: An integer indicating lighting state. (Note that this is not a boolean because Qt's CheckBox emits an integer signal)
- * Unchecked = 0, ,PartiallyChecked = 1, Checked = 2
- */
-void GL3DWidget::setLightingModel(int state)
-{
-  // Basic lighting
-  if( state == 0 )
-  {
-    glShadeModel(GL_FLAT);
-    glDisable(GL_LIGHTING);
-    glDisable(GL_LIGHT0);
-    glDisable(GL_LINE_SMOOTH);
-  }
-  // High end shading and lighting
-  else if( state == 2 )
-  {
-    glShadeModel(GL_SMOOTH);           // Shade model is smooth (expensive but looks pleasing)
-    glEnable (GL_LIGHTING);            // Enable light
-    glEnable(GL_LIGHT0);               // Enable opengl first light
-    glEnable(GL_LINE_SMOOTH);          // Set line should be drawn smoothly
-    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
-    float lamp_ambient[4]={0.0,0.0,0.0,1.0};
-    float lamp_diffuse[4]={1.0,1.0,1.0,1.0};
-    float lamp_specular[4]={1.0,1.0,1.0,1.0};
-    glLightfv(GL_LIGHT0, GL_AMBIENT,lamp_ambient );
-    glLightfv(GL_LIGHT0, GL_DIFFUSE, lamp_diffuse);
-    glLightfv(GL_LIGHT0, GL_SPECULAR, lamp_specular);
-    float lamp_pos[4]={0.0,0.0,1.0,0.0};
-    glLightfv(GL_LIGHT0, GL_POSITION, lamp_pos);
-  }
-  else return;
-}
-
-/** Draw 3D axes centered at the origin (if the option is selected)
- *
- */
-void GL3DWidget::drawAxes(double axis_length)
-{
-  //Don't do anything if the checkbox is unchecked.
-  if (!m3DAxesShown)
-    return;
-
-  glPointSize(3.0);
-  glLineWidth(3.0);
-
-  //To make sure the lines are colored
-  glEnable(GL_COLOR_MATERIAL);
-  glDisable(GL_TEXTURE_2D);
-  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();
-}
-
-/**
- * This method draws the scene onto the graphics context
- */
-void GL3DWidget::drawDisplayScene()
-{
-  if (m_renderMode == FULL3D)
-  {
-    draw3D();
-  }
-  else
-  {
-    drawUnwrapped();
-  }
-}
-/**
-  * This method draws the scene onto the graphics context
-  */
-void GL3DWidget::draw3D()
-{
-  glGetError();
-  glMatrixMode(GL_MODELVIEW);
-  glLoadIdentity();
-  // Clear the background to the bg color set previously.
-  glClearColor(bgColor.red()/255.0,bgColor.green()/255.0,bgColor.blue()/255.0,1.0);
-  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-  OpenGLError::check("GL3DWidget::draw3D()[clear] ");
-
-  // Issue the rotation, translation and zooming of the trackball to the object
-  _trackball->IssueRotation();
-  
-  if (m_polygonMode == SOLID)
-  {
-    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-  }
-  else
-  {
-    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
-  }
-
-  glPushMatrix();
-  if(isKeyPressed)
-  {
-    if (m_lightingState > 0)
-    {
-      setLightingModel(m_lightingState);
-    }
-    scene->draw();
-    setLightingModel(0);
-    this->drawAxes();
-    OpenGLError::check("GL3DWidget::draw3D()[scene draw 1] ");
-  }
-  else
-  {
-    QApplication::setOverrideCursor(Qt::WaitCursor);
-
-    //Set the lighting
-    if (m_lightingState > 0)
-      setLightingModel(m_lightingState);
-    else
-      setLightingModel(0);
-
-    scene->draw();
-    OpenGLError::check("GL3DWidget::draw3D()[scene draw] ");
-
-    //This draws a point at the origin, I guess
-    glPointSize(3.0);
-    glBegin(GL_POINTS);
-    glVertex3d(0.0,0.0,0.0);
-    glEnd();
-
-    //Also some axes
-    setLightingModel(0);
-    this->drawAxes();
-
-
-    QApplication::restoreOverrideCursor();
-
-
-  }
-  glPopMatrix();
-  OpenGLError::check("GL3DWidget::draw3D()");
-  QPainter painter(this);
-  painter.end();
-}
-
-/**
- * This method draws the scenc when in pick mode i.e with reference colors to actors
- */
-void GL3DWidget::drawPickingScene()
-{
-  makeCurrent();
-  glGetError();
-  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-  glClearColor(0.0,0.0,0.0,1.0);
-  glMatrixMode(GL_MODELVIEW);
-  glLoadIdentity();
-  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-  // Issue the rotation, translation and zooming of the trackball to the object
-  _trackball->IssueRotation();
-  glPushMatrix();
-  drawSceneUsingColorID();
-  glPopMatrix();
-}
-
-/**
- * Switches to picking mode does all the operations to create and set the images to GLGroupPickBox
- */
-void GL3DWidget::switchToPickingMode()
-{
-  if (m_renderMode == FULL3D)
-  {
-    //First we draw the regular scene and save it to display
-    drawDisplayScene();
-    glReadBuffer(GL_FRONT);
-    mPickBox->setDisplayImage(grabFrameBuffer(false));
-
-    // Now we draw the picking scene with the special colors
-
-    glDisable(GL_MULTISAMPLE);  //This will disable antialiasing which is build in by default for samplebuffers
-    glDisable(GL_NORMALIZE);
-    drawPickingScene();
-    glReadBuffer(GL_BACK);
-    mPickBox->setPickImage(grabFrameBuffer(false));
-    glEnable(GL_MULTISAMPLE);   //enable antialiasing
-    mPickingDraw=false;
-    OpenGLError::check("GL3DWidget::switchToPickingMode() ");
-  }
-  else
-  {
-    drawUnwrapped();
-  }
-}
-
-
-/**
- * This is overridden function which is called by Qt when the widget needs to be repainted.
- */
-void GL3DWidget::paintEvent(QPaintEvent *event)
-{
-  (void) event; //avoid compiler warning
-  makeCurrent();
-  if(iInteractionMode == GL3DWidget::PickMode)
-  {
-    if (m_renderMode == FULL3D)
-    {
-      if(mPickingDraw==true)
-      {
-        switchToPickingMode();
-      }
-      QPainter painter(this);
-      painter.setRenderHint(QPainter::Antialiasing);
-      mPickBox->draw(&painter);
-      painter.end();
-    }
-    else
-    {
-      drawUnwrapped();
-    }
-  }
-  else
-  {
-    drawDisplayScene();
-  }
-
-
-  if (m_firstFrame)
-  {
-    update();
-    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 GL3DWidget::resizeGL(int width, int height)
-{
-  makeCurrent();
-  _viewport->resize(width,height);
-  _viewport->issueGL();
-  
-  if( iInteractionMode == GL3DWidget::PickMode) //This is when in picking mode and the window is resized so update the image
-  {
-    mPickingDraw=true;
-  }
-  m_unwrappedViewChanged = true;
-
-  OpenGLError::check("GL3DWidget::resizeGL");
-}
-
-/**
- * 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 GL3DWidget::mousePressEvent(QMouseEvent* event)
-{
-  if (m_renderMode != FULL3D && m_unwrappedSurface)
-  {
-    if(event->buttons() & Qt::RightButton)
-    {
-      if (getInteractionMode() == MoveMode)
-      {
-        m_unwrappedSurface->unzoom();
-      }
-    }
-    else
-    {
-      m_unwrappedSurface->startSelection(event->x(),event->y());
-    }
-    update();
-    OpenGLError::check("GL3DWidget::mousePressEvent");
-    return;
-  }
-
-  // Pick Mode
-  if( iInteractionMode == GL3DWidget::PickMode && (event->buttons() & Qt::LeftButton) )
-  { 
-    setCursor(Qt::CrossCursor);
-    QRgb tmpColor = mPickBox->pickPoint(event->x(), event->y());
-    emit actorHighlighted(tmpColor);
-    mPickBox->mousePressed(event->buttons(), event->pos());
-    return;
-  } //end of pick mode and start of normal mode
-  
-  if (event->buttons() & Qt::MidButton)
-  {
-    setCursor(Qt::SizeVerCursor);
-    _trackball->initZoomFrom(event->x(),event->y());
-    isKeyPressed=true;
-    setSceneLowResolution();
-  }
-  else if (event->buttons() & Qt::LeftButton)
-  {
-    setCursor(Qt::OpenHandCursor);
-    _trackball->initRotationFrom(event->x(),event->y());
-    isKeyPressed=true;
-    setSceneLowResolution();
-  }
-  else if(event->buttons() & Qt::RightButton)
-  {
-    setCursor(Qt::CrossCursor);
-    _trackball->initTranslateFrom(event->x(),event->y());
-    isKeyPressed=true;
-    setSceneLowResolution();
-  }
-  OpenGLError::check("GL3DWidget::mousePressEvent");
-}
-
-/**
- * Called when a context menu event is recieved
- */
-void GL3DWidget::contextMenuEvent(QContextMenuEvent * event)
-{
-  (void) event; //avoid compiler warning
-  if( iInteractionMode == GL3DWidget::PickMode )
-  {
-    mPickBox->mousePressed(Qt::RightButton, QCursor::pos());
-    mPickBox->mouseReleased(Qt::RightButton, QCursor::pos());
-    std::set<QRgb> result=mPickBox->getListOfColorsPicked();
-    if(!result.empty())
-    {
-      emit actorsPicked(result);
-    }
-
-  }
-}
-
-/**
- * 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 GL3DWidget::mouseMoveEvent(QMouseEvent* event)
-{
-  makeCurrent();
-  if (m_renderMode != FULL3D && m_unwrappedSurface)
-  {
-    if (event->buttons() & Qt::LeftButton)
-    {
-      m_unwrappedSurface->moveSelection(event->x(),event->y());
-      update();
-    }
-    else
-    {
-      int detId = m_unwrappedSurface->getDetectorID(event->x(),event->y());
-      emit actorHighlighted(detId);
-    }
-    OpenGLError::check("GL3DWidget::mouseMoveEvent");
-    return;
-  }
-
-  if(iInteractionMode == GL3DWidget::PickMode)
-  {
-    setCursor(Qt::CrossCursor);
-    QRgb tmpColor = mPickBox->pickPoint(event->x(), event->y());
-    if (event->buttons() & Qt::LeftButton)
-    {
-      emit increaseSelection(tmpColor);
-      mPickBox->mouseMoveEvent(event);
-      update();
-    }
-    else
-    {
-      emit actorHighlighted(tmpColor);
-    }
-  }
-  else
-  {
-    if (event->buttons() & Qt::LeftButton)
-    {
-      setCursor(Qt::ClosedHandCursor);
-      _trackball->generateRotationTo(event->x(),event->y());
-      update();
-      _trackball->initRotationFrom(event->x(),event->y());
-    }
-    else if(event->buttons() & Qt::RightButton)
-    { //Translate
-      setCursor(Qt::CrossCursor);
-      _trackball->generateTranslationTo(event->x(),event->y());
-      update();
-      _trackball->initTranslateFrom(event->x(),event->y());
-    }
-    else if(event->buttons() & Qt::MidButton)
-    { //Zoom
-      setCursor(Qt::SizeVerCursor);
-      _trackball->generateZoomTo(event->x(),event->y());
-      update();
-      _trackball->initZoomFrom(event->x(),event->y());
-    }
-  }
-  OpenGLError::check("GL3DWidget::mouseMoveEvent");
-}
-
-/**
- * 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 GL3DWidget::mouseReleaseEvent(QMouseEvent* event)
-{
-  if (m_renderMode != FULL3D && m_unwrappedSurface)
-  {
-    if (getInteractionMode() == PickMode && m_unwrappedSurface->hasSelection())
-    {
-      showUnwrappedContextMenu();
-    }
-    m_unwrappedSurface->endSelection(event->x(),event->y());
-    update();
-    return;
-  }
-
-  setCursor(Qt::PointingHandCursor);
-  isKeyPressed=false;
-  setSceneHighResolution();
-  if(iInteractionMode == GL3DWidget::PickMode)
-  {
-    mPickBox->mouseReleased(event->buttons(), event->pos());
-    std::set<QRgb> result=mPickBox->getListOfColorsPicked();
-    if(!result.empty())
-    {
-      emit actorsPicked(result);
-    }
-  }
-  update();
-}
-
-/**
- * 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 GL3DWidget::wheelEvent(QWheelEvent* event)
-{
-  makeCurrent();
-  setCursor(Qt::SizeVerCursor);
-  _trackball->initZoomFrom(event->x(),event->y());
-  _trackball->generateZoomTo(event->x(),event->y()-event->delta());
-  update();
-  setCursor(Qt::PointingHandCursor);
-  OpenGLError::check("GL3DWidget::wheelEvent");
-}
-
-/**
- * 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 GL3DWidget::keyPressEvent(QKeyEvent *event)
-{
-  makeCurrent();
-  grabKeyboard();
-  // Ignore keyboard event when in pick mode
-  if( iInteractionMode== GL3DWidget::PickMode) return; 
-  int width,height;
-  _viewport->getViewport(&width,&height);
-  int halfwidth=width/2;
-  int halfheight=height/2;
-  switch(event->key())
-    {
-      //-----------------------Translation-----------------
-    case Qt::Key_Left:
-      isKeyPressed=true;
-      setCursor(Qt::CrossCursor);
-      _trackball->initTranslateFrom(1,0);
-      _trackball->generateTranslationTo(0,0);
-      update();
-      break;
-    case Qt::Key_Right:
-      isKeyPressed=true;
-      setCursor(Qt::CrossCursor);
-      _trackball->initTranslateFrom(0,0);
-      _trackball->generateTranslationTo(1,0);
-      update();
-      break;
-    case Qt::Key_Up:
-      isKeyPressed=true;
-      setCursor(Qt::CrossCursor);
-      _trackball->initTranslateFrom(0,1);
-      _trackball->generateTranslationTo(0,0);
-      update();
-      break;
-    case Qt::Key_Down:
-      isKeyPressed=true;
-      setCursor(Qt::CrossCursor);
-      _trackball->initTranslateFrom(0,0);
-      _trackball->generateTranslationTo(0,1);
-      update();
-      break;
-      //--------------------End of Translation---------------
-      //--------------------Rotation-------------------------
-    case Qt::Key_1:
-      isKeyPressed=true;
-      setCursor(Qt::ClosedHandCursor);
-      _trackball->initRotationFrom(halfwidth,halfheight);
-      _trackball->generateRotationTo(halfwidth-1,halfheight+1);
-      update();
-      break;
-    case Qt::Key_2:
-      isKeyPressed=true;
-      setCursor(Qt::ClosedHandCursor);
-      _trackball->initRotationFrom(halfwidth,halfheight);
-      _trackball->generateRotationTo(halfwidth,halfheight+1);
-      update();
-      break;
-    case Qt::Key_3:
-      isKeyPressed=true;
-      setCursor(Qt::ClosedHandCursor);
-      _trackball->initRotationFrom(halfwidth,halfheight);
-      _trackball->generateRotationTo(halfwidth+1,halfheight+1);
-      update();
-      break;
-    case Qt::Key_4:
-      isKeyPressed=true;
-      setCursor(Qt::ClosedHandCursor);
-      _trackball->initRotationFrom(halfwidth,halfheight);
-      _trackball->generateRotationTo(halfwidth-1,halfheight);
-      update();
-      break;
-    case Qt::Key_6:
-      isKeyPressed=true;
-      setCursor(Qt::ClosedHandCursor);
-      _trackball->initRotationFrom(halfwidth,halfheight);
-      _trackball->generateRotationTo(halfwidth+1,halfheight);
-      update();
-      break;
-    case Qt::Key_7:
-      isKeyPressed=true;
-      setCursor(Qt::ClosedHandCursor);
-      _trackball->initRotationFrom(halfwidth,halfheight);
-      _trackball->generateRotationTo(halfwidth-1,halfheight-1);
-      update();
-      break;
-    case Qt::Key_8:
-      isKeyPressed=true;
-      setCursor(Qt::ClosedHandCursor);
-      _trackball->initRotationFrom(halfwidth,halfheight);
-      _trackball->generateRotationTo(halfwidth,halfheight-1);
-      update();
-      break;
-    case Qt::Key_9:
-      isKeyPressed=true;
-      setCursor(Qt::ClosedHandCursor);
-      _trackball->initRotationFrom(halfwidth,halfheight);
-      _trackball->generateRotationTo(halfwidth+1,halfheight-1);
-      update();
-      break;
-      //---------------------------------End of Rotation--------------
-      //---------------------------------Zoom-------------------------
-    case Qt::Key_PageUp:
-      isKeyPressed=true;
-      setCursor(Qt::SizeVerCursor);
-      _trackball->initZoomFrom(halfwidth,halfheight);
-      _trackball->generateZoomTo(halfwidth,halfheight-1);
-      update();
-      break;
-    case Qt::Key_PageDown:
-      isKeyPressed=true;
-      setCursor(Qt::SizeVerCursor);
-      _trackball->initZoomFrom(halfwidth,halfheight);
-      _trackball->generateZoomTo(halfwidth,halfheight+1);
-      update();
-      break;
-    }
-  OpenGLError::check("GL3DWidget::keyPressEvent");
-}
-
-/**
- * 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 GL3DWidget::keyReleaseEvent(QKeyEvent *event)
-{
-  releaseKeyboard();
-  setCursor(Qt::PointingHandCursor);
-  isKeyPressed=false;
-  if(!event->isAutoRepeat())
-  {
-    update();
-  }
-  OpenGLError::check("GL3DWidget::keyReleaseEvent");
-}
-/**
- * This method sets the collection of actors that widget needs to display
- * @param col :: input collection of actors
- */
-void GL3DWidget::setActorCollection(boost::shared_ptr<GLActorCollection> col)
-{
-  scene=col;
-  update();
-  OpenGLError::check("GL3DWidget::setActorCollection");
-}
-
-/**
- * This default object initialization method. usually used for testing or added a default
- * object to all the widgets.
- */
-void GL3DWidget::MakeObject()
-{
-}
-
-/**
- * Sets the default view to input provided
- */
-void GL3DWidget::setViewDirection(AxisDirection dir)
-{
-  makeCurrent();
-  Mantid::Geometry::V3D minPoint,maxPoint;
-  double _bbmin[3],_bbmax[3];
-  getBoundingBox(minPoint,maxPoint);
-  Mantid::Geometry::V3D centre=(maxPoint+minPoint)/2.0;
-  defaultProjection();
-  _viewport->getProjection(_bbmin[0],_bbmax[0],_bbmin[1],_bbmax[1],_bbmin[2],_bbmax[2]);
-  switch(dir)
-  {
-  case XPOSITIVE:
-    _trackball->setViewToXPositive();
-    _trackball->rotateBoundingBox(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],minPoint[2],maxPoint[2]);
-    _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],_bbmin[2],_bbmax[2]);
-    break;
-  case YPOSITIVE:
-    _trackball->setViewToYPositive();
-    _trackball->rotateBoundingBox(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],minPoint[2],maxPoint[2]);
-    _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],_bbmin[2],_bbmax[2]);
-    break;
-  case ZPOSITIVE:
-    _trackball->setViewToZPositive();
-    _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],_bbmin[2],_bbmax[2]);
-    break;
-  case XNEGATIVE:
-    _trackball->setViewToXNegative();
-    _trackball->rotateBoundingBox(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],minPoint[2],maxPoint[2]);
-    _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],_bbmin[2],_bbmax[2]);
-    break;
-  case YNEGATIVE:
-    _trackball->setViewToYNegative();
-    _trackball->rotateBoundingBox(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],minPoint[2],maxPoint[2]);
-    _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],_bbmin[2],_bbmax[2]);
-    break;
-  case ZNEGATIVE:
-    _trackball->setViewToZNegative();
-    _trackball->rotateBoundingBox(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],minPoint[2],maxPoint[2]);
-    _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],_bbmin[2],_bbmax[2]);
-    break;
-  }
-  OpenGLError::check("GL3DWidget::setViewDirection");
-  _viewport->issueGL();
-  update();
-}
-
-/**
- * This method calculates the default projection
- */
-void GL3DWidget::defaultProjection()
-{
-  makeCurrent();
-  // Getting the bounding box of the scene and setting the orthagonal projection
-  // such that the orthogonal projection places the object completly in the screen
-  // Its a simplified version of placing the object completly in screen with same
-  // min and max values in all directions.
-  Mantid::Geometry::V3D minPoint,maxPoint;
-  getBoundingBox(minPoint,maxPoint);
-  if(minPoint[0]==DBL_MAX||minPoint[1]==DBL_MAX||minPoint[2]==DBL_MAX||maxPoint[0]==-DBL_MAX||maxPoint[1]==-DBL_MAX||maxPoint[2]==-DBL_MAX)
-  {
-    minPoint=Mantid::Geometry::V3D(-1.0,-1.0,-1.0);
-    maxPoint=Mantid::Geometry::V3D( 1.0, 1.0, 1.0);
-  }
-  double minValue,maxValue;
-  minValue=minPoint[0];
-  if(minValue>minPoint[1])minValue=minPoint[1];
-  if(minValue>minPoint[2])minValue=minPoint[2];
-  maxValue=maxPoint[0];
-  if(maxValue<maxPoint[1])maxValue=maxPoint[1];
-  if(maxValue<maxPoint[2])maxValue=maxPoint[2];
-  if(minValue>maxValue)
-  {
-    double tmp;
-    tmp=maxValue;
-    maxValue=minValue;
-    minValue=maxValue;
-  }
-  double temp=minValue-fabs(maxValue-minValue);
-  maxValue=maxValue+fabs(maxValue-minValue);
-  minValue=temp;
-  
-  _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],minValue*-1,maxValue*-1);
-  OpenGLError::check("GL3DWidget::defaultProjection()");
-  Mantid::Geometry::V3D center;
-  center=(minPoint+maxPoint)/2.0;
-  _viewport->issueGL();
-}
-
-/**
- * Sets the flag indicating the visibility of the orientation axes
- *
- */
-void GL3DWidget::set3DAxesState(bool state)
-{
-  m3DAxesShown = state;
-
-  // Update the display
-  update();
-}
-
-
-
-/**
- * This method set the background color.
- */
-void GL3DWidget::setBackgroundColor(QColor input)
-{
-  makeCurrent();
-  bgColor = input;
-  glClearColor(bgColor.red()/255.0,bgColor.green()/255.0,bgColor.blue()/255.0,1.0);
-  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-  OpenGLError::check("GL3DWidget::setBackgroundColor");
-  m_unwrappedSurfaceChanged = true;
-  update();
-}
-
-QColor GL3DWidget::currentBackgroundColor() const
-{
-  return bgColor;
-}
-
-/**
- * This saves the GL scene to a file.
- * @param filename :: The name of the file
- */
-void GL3DWidget::saveToFile(const QString & filename)
-{
-  if( filename.isEmpty() ) return;
-  //  QPixmap pm = renderPixmap();
-  //pm.save(filename);
-  // It seems QGLWidget grabs the back buffer
-  this->swapBuffers(); // temporarily swap the buffers
-  QImage image = this->grabFrameBuffer();
-  this->swapBuffers(); // swap them back
-  OpenGLError::check("GL3DWidget::saveToFile");
-  image.save(filename);
-}
-
-/**
- * Resets the widget for new instrument definition
- */
-void GL3DWidget::resetWidget()
-{
-  setActorCollection(boost::shared_ptr<GLActorCollection>(new GLActorCollection()));
-}
-
-/**
-  * Enables / disables lighting
-  * @param on :: Set true to turn lighting on or false to turn it off.
-  */
-void GL3DWidget::enableLighting(bool on)
-{
-  m_lightingState = on? 2 : 0;
-  setLightingModel(m_lightingState);
-  if (m_unwrappedSurface)
-  {
-    m_unwrappedSurface->updateView();
-  }
-  update();
-}
-
-/**
-  * Set wireframe view on or off
-  * @param on :: If true set wireframe, otherwise it's SOLID
-  */
-void GL3DWidget::setWireframe(bool on)
-{
-  m_polygonMode = on ? WIREFRAME : SOLID;
-  update();
-}
-
-void GL3DWidget::setRenderMode(int mode)
-{
-  makeCurrent();
-  if (mode < RENDERMODE_SIZE)
-  {
-    m_renderMode = RenderMode(mode);
-    resetUnwrappedViews();
-  }
-  if (mode == FULL3D)
-  {
-    _viewport->issueGL();
-  }
-  update();
-}
-
-void GL3DWidget::resetUnwrappedViews()
-{
-  if (m_unwrappedSurface)
-  {
-    delete m_unwrappedSurface;
-    m_unwrappedSurface = NULL;
-  }
-  m_unwrappedSurfaceChanged = true;
-}
-
-void GL3DWidget::drawUnwrapped()
-{
-  QApplication::setOverrideCursor(Qt::WaitCursor);
-  if (m_unwrappedSurfaceChanged)
-  {
-    GLActor* actor = scene->getActor(0);
-    if (!actor) return;
-    InstrumentActor* instrActor = dynamic_cast<InstrumentActor*>(actor);
-    if (!instrActor) return;
-    boost::shared_ptr<Mantid::Geometry::IInstrument> instr = instrActor->getInstrument();
-    Mantid::Geometry::IObjComponent_sptr sample = instr->getSample();
-    Mantid::Geometry::V3D sample_pos = sample->getPos();
-
-    QTime time;
-    time.start();
-    if (m_unwrappedSurface) delete m_unwrappedSurface;
-    Mantid::Geometry::V3D axis;
-    if (m_renderMode == SPHERICAL_Y || m_renderMode == CYLINDRICAL_Y)
-    {
-      axis = Mantid::Geometry::V3D(0,1,0);
-    }
-    else if (m_renderMode == SPHERICAL_Z || m_renderMode == CYLINDRICAL_Z)
-    {
-      axis = Mantid::Geometry::V3D(0,0,1);
-    }
-    else // SPHERICAL_X || CYLINDRICAL_X
-    {
-      axis = Mantid::Geometry::V3D(1,0,0);
-    }
-
-    if (m_renderMode <= CYLINDRICAL_X)
-    {
-      m_unwrappedSurface = new UnwrappedCylinder(instrActor,sample_pos,axis);
-    }
-    else // SPHERICAL
-    {
-      m_unwrappedSurface = new UnwrappedSphere(instrActor,sample_pos,axis);
-    }
-
-    m_unwrappedSurfaceChanged = false;
-  }
-
-  m_unwrappedSurface->draw(this);
-
-  QApplication::restoreOverrideCursor();
-  OpenGLError::check("GL3DWidget::drawUnwrapped()");
-}
-
-void GL3DWidget::redrawUnwrapped()
-{
-  if (m_unwrappedSurface)
-  {
-    m_unwrappedSurface->updateDetectors();
-  }
-}
-
-void GL3DWidget::componentSelected(Mantid::Geometry::ComponentID id)
-{
-  if (m_unwrappedSurface)
-  {
-    m_unwrappedSurface->componentSelected(id);
-    update();
-  }
-}
-
-void GL3DWidget::setSelectionType(int type)
-{
-  m_detSelector.reset(DetSelector::create((DetSelectionType)type));
-}
+#ifdef WIN32
+#include <windows.h>
+#endif
+#include "GL3DWidget.h"
+#include "GLActor.h"
+#include "GLColor.h"
+#include "InstrumentActor.h"
+#include "UnwrappedCylinder.h"
+#include "UnwrappedSphere.h"
+#include "OpenGLError.h"
+#include "DetSelector.h"
+#include "MantidGeometry/IInstrument.h"
+#include "MantidGeometry/Objects/Object.h"
+
+#include "boost/shared_ptr.hpp"
+
+#include <QtOpenGL>
+#include <QSpinBox>
+#include <QApplication>
+#include <QTime>
+
+#include <map>
+#include <string>
+#include <iostream>
+#include <cfloat>
+#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
+
+
+GL3DWidget::GL3DWidget(QWidget* parent):
+  QGLWidget(QGLFormat(QGL::DepthBuffer|QGL::NoAlphaChannel|QGL::SampleBuffers),parent)
+{
+
+  if (!this->format().depth())
+    std::cout << "Warning! OpenGL Depth buffer could not be initialized.\n";
+  //std::cout << "Depth buffer size is " << this->format().depthBufferSize() << "\n";
+
+  makeCurrent();
+  _viewport=new GLViewport;
+  _trackball=new GLTrackball(_viewport);
+  isKeyPressed=false;
+  scene=boost::shared_ptr<GLActorCollection>(new GLActorCollection());
+  mPickedActor=NULL;
+  mPickingDraw=true;
+  iInteractionMode=GL3DWidget::MoveMode;
+  mPickBox=new GLGroupPickBox();
+  setFocusPolicy(Qt::StrongFocus);
+  setAutoFillBackground(false);
+  bgColor=QColor(0,0,0,1);
+  m3DAxesShown = true;
+  m_polygonMode = SOLID;
+  m_lightingState = 0;
+  m_firstFrame = true;
+  m_renderMode = FULL3D;
+  m_unwrappedSurface = NULL;
+  m_unwrappedSurfaceChanged = true;
+  m_unwrappedViewChanged = true;
+
+  //Enable right-click in pick mode
+  setContextMenuPolicy(Qt::DefaultContextMenu);
+
+}
+
+GL3DWidget::~GL3DWidget()
+{
+  delete _viewport;
+  delete _trackball;
+  if (m_unwrappedSurface)
+  {
+    delete m_unwrappedSurface;
+  }
+}
+
+void GL3DWidget::setInteractionModePick()
+{
+  iInteractionMode = GL3DWidget::PickMode;// Pick mode
+  setMouseTracking(true);
+  mPickingDraw = true;
+  update();
+}
+
+void GL3DWidget::setInteractionModeNormal()
+{
+  iInteractionMode = GL3DWidget::MoveMode;//Normal mode
+  setMouseTracking(false);
+  setCursor(Qt::PointingHandCursor);
+  glEnable(GL_NORMALIZE);
+  if (m_lightingState > 0)
+  {
+    glEnable(GL_LIGHTING);
+  }
+  update();
+}
+
+GLActor* GL3DWidget::getPickedActor()
+{
+  return mPickedActor;
+}
+
+/**
+ * This method initializes the opengl settings. its invoked defaultly by Qt when the widget
+ * is initialized.
+ */
+void GL3DWidget::initializeGL()
+{
+  setCursor(Qt::PointingHandCursor); // This is to set the initial window mouse cursor to Hand icon
+  
+  // Set the relevant OpenGL rendering options
+  setRenderingOptions();
+  
+  // Clear the memory buffers
+  glClearColor(bgColor.red()/255.0,bgColor.green()/255.0,bgColor.blue()/255.0,1.0);
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+}
+
+void GL3DWidget::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);
+
+}
+
+/**
+ * Toggles the use of high resolution lighting
+ * @param state :: An integer indicating lighting state. (Note that this is not a boolean because Qt's CheckBox emits an integer signal)
+ * Unchecked = 0, ,PartiallyChecked = 1, Checked = 2
+ */
+void GL3DWidget::setLightingModel(int state)
+{
+  // Basic lighting
+  if( state == 0 )
+  {
+    glShadeModel(GL_FLAT);
+    glDisable(GL_LIGHTING);
+    glDisable(GL_LIGHT0);
+    glDisable(GL_LINE_SMOOTH);
+  }
+  // High end shading and lighting
+  else if( state == 2 )
+  {
+    glShadeModel(GL_SMOOTH);           // Shade model is smooth (expensive but looks pleasing)
+    glEnable (GL_LIGHTING);            // Enable light
+    glEnable(GL_LIGHT0);               // Enable opengl first light
+    glEnable(GL_LINE_SMOOTH);          // Set line should be drawn smoothly
+    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
+    float lamp_ambient[4]={0.0,0.0,0.0,1.0};
+    float lamp_diffuse[4]={1.0,1.0,1.0,1.0};
+    float lamp_specular[4]={1.0,1.0,1.0,1.0};
+    glLightfv(GL_LIGHT0, GL_AMBIENT,lamp_ambient );
+    glLightfv(GL_LIGHT0, GL_DIFFUSE, lamp_diffuse);
+    glLightfv(GL_LIGHT0, GL_SPECULAR, lamp_specular);
+    float lamp_pos[4]={0.0,0.0,1.0,0.0};
+    glLightfv(GL_LIGHT0, GL_POSITION, lamp_pos);
+  }
+  else return;
+}
+
+/** Draw 3D axes centered at the origin (if the option is selected)
+ *
+ */
+void GL3DWidget::drawAxes(double axis_length)
+{
+  //Don't do anything if the checkbox is unchecked.
+  if (!m3DAxesShown)
+    return;
+
+  glPointSize(3.0);
+  glLineWidth(3.0);
+
+  //To make sure the lines are colored
+  glEnable(GL_COLOR_MATERIAL);
+  glDisable(GL_TEXTURE_2D);
+  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();
+}
+
+/**
+ * This method draws the scene onto the graphics context
+ */
+void GL3DWidget::drawDisplayScene()
+{
+  if (m_renderMode == FULL3D)
+  {
+    draw3D();
+  }
+  else
+  {
+    drawUnwrapped();
+  }
+}
+/**
+  * This method draws the scene onto the graphics context
+  */
+void GL3DWidget::draw3D()
+{
+  glGetError();
+  glMatrixMode(GL_MODELVIEW);
+  glLoadIdentity();
+  // Clear the background to the bg color set previously.
+  glClearColor(bgColor.red()/255.0,bgColor.green()/255.0,bgColor.blue()/255.0,1.0);
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+  OpenGLError::check("GL3DWidget::draw3D()[clear] ");
+
+  // Issue the rotation, translation and zooming of the trackball to the object
+  _trackball->IssueRotation();
+  
+  if (m_polygonMode == SOLID)
+  {
+    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+  }
+  else
+  {
+    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+  }
+
+  glPushMatrix();
+  if(isKeyPressed)
+  {
+    if (m_lightingState > 0)
+    {
+      setLightingModel(m_lightingState);
+    }
+    scene->draw();
+    setLightingModel(0);
+    this->drawAxes();
+    OpenGLError::check("GL3DWidget::draw3D()[scene draw 1] ");
+  }
+  else
+  {
+    QApplication::setOverrideCursor(Qt::WaitCursor);
+
+    //Set the lighting
+    if (m_lightingState > 0)
+      setLightingModel(m_lightingState);
+    else
+      setLightingModel(0);
+
+    scene->draw();
+    OpenGLError::check("GL3DWidget::draw3D()[scene draw] ");
+
+    //This draws a point at the origin, I guess
+    glPointSize(3.0);
+    glBegin(GL_POINTS);
+    glVertex3d(0.0,0.0,0.0);
+    glEnd();
+
+    //Also some axes
+    setLightingModel(0);
+    this->drawAxes();
+
+
+    QApplication::restoreOverrideCursor();
+
+
+  }
+  glPopMatrix();
+  OpenGLError::check("GL3DWidget::draw3D()");
+  QPainter painter(this);
+  painter.end();
+}
+
+/**
+ * This method draws the scenc when in pick mode i.e with reference colors to actors
+ */
+void GL3DWidget::drawPickingScene()
+{
+  makeCurrent();
+  glGetError();
+  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+  glClearColor(0.0,0.0,0.0,1.0);
+  glMatrixMode(GL_MODELVIEW);
+  glLoadIdentity();
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+  // Issue the rotation, translation and zooming of the trackball to the object
+  _trackball->IssueRotation();
+  glPushMatrix();
+  drawSceneUsingColorID();
+  glPopMatrix();
+}
+
+/**
+ * Switches to picking mode does all the operations to create and set the images to GLGroupPickBox
+ */
+void GL3DWidget::switchToPickingMode()
+{
+  if (m_renderMode == FULL3D)
+  {
+    //First we draw the regular scene and save it to display
+    drawDisplayScene();
+    glReadBuffer(GL_FRONT);
+    mPickBox->setDisplayImage(grabFrameBuffer(false));
+
+    // Now we draw the picking scene with the special colors
+
+    glDisable(GL_MULTISAMPLE);  //This will disable antialiasing which is build in by default for samplebuffers
+    glDisable(GL_NORMALIZE);
+    drawPickingScene();
+    glReadBuffer(GL_BACK);
+    mPickBox->setPickImage(grabFrameBuffer(false));
+    glEnable(GL_MULTISAMPLE);   //enable antialiasing
+    mPickingDraw=false;
+    OpenGLError::check("GL3DWidget::switchToPickingMode() ");
+  }
+  else
+  {
+    drawUnwrapped();
+  }
+}
+
+
+/**
+ * This is overridden function which is called by Qt when the widget needs to be repainted.
+ */
+void GL3DWidget::paintEvent(QPaintEvent *event)
+{
+  (void) event; //avoid compiler warning
+  makeCurrent();
+  if(iInteractionMode == GL3DWidget::PickMode)
+  {
+    if (m_renderMode == FULL3D)
+    {
+      if(mPickingDraw==true)
+      {
+        switchToPickingMode();
+      }
+      QPainter painter(this);
+      painter.setRenderHint(QPainter::Antialiasing);
+      mPickBox->draw(&painter);
+      painter.end();
+    }
+    else
+    {
+      drawUnwrapped();
+    }
+  }
+  else
+  {
+    drawDisplayScene();
+  }
+
+
+  if (m_firstFrame)
+  {
+    update();
+    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 GL3DWidget::resizeGL(int width, int height)
+{
+  makeCurrent();
+  _viewport->resize(width,height);
+  _viewport->issueGL();
+  
+  if( iInteractionMode == GL3DWidget::PickMode) //This is when in picking mode and the window is resized so update the image
+  {
+    mPickingDraw=true;
+  }
+  m_unwrappedViewChanged = true;
+
+  OpenGLError::check("GL3DWidget::resizeGL");
+}
+
+/**
+ * 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 GL3DWidget::mousePressEvent(QMouseEvent* event)
+{
+  if (m_renderMode != FULL3D && m_unwrappedSurface)
+  {
+    if(event->buttons() & Qt::RightButton)
+    {
+      if (getInteractionMode() == MoveMode)
+      {
+        m_unwrappedSurface->unzoom();
+      }
+    }
+    else
+    {
+      m_unwrappedSurface->startSelection(event->x(),event->y());
+    }
+    update();
+    OpenGLError::check("GL3DWidget::mousePressEvent");
+    return;
+  }
+
+  // Pick Mode
+  if( iInteractionMode == GL3DWidget::PickMode && (event->buttons() & Qt::LeftButton) )
+  { 
+    setCursor(Qt::CrossCursor);
+    QRgb tmpColor = mPickBox->pickPoint(event->x(), event->y());
+    emit actorHighlighted(tmpColor);
+    mPickBox->mousePressed(event->buttons(), event->pos());
+    return;
+  } //end of pick mode and start of normal mode
+  
+  if (event->buttons() & Qt::MidButton)
+  {
+    setCursor(Qt::SizeVerCursor);
+    _trackball->initZoomFrom(event->x(),event->y());
+    isKeyPressed=true;
+    setSceneLowResolution();
+  }
+  else if (event->buttons() & Qt::LeftButton)
+  {
+    setCursor(Qt::OpenHandCursor);
+    _trackball->initRotationFrom(event->x(),event->y());
+    isKeyPressed=true;
+    setSceneLowResolution();
+  }
+  else if(event->buttons() & Qt::RightButton)
+  {
+    setCursor(Qt::CrossCursor);
+    _trackball->initTranslateFrom(event->x(),event->y());
+    isKeyPressed=true;
+    setSceneLowResolution();
+  }
+  OpenGLError::check("GL3DWidget::mousePressEvent");
+}
+
+/**
+ * Called when a context menu event is recieved
+ */
+void GL3DWidget::contextMenuEvent(QContextMenuEvent * event)
+{
+  (void) event; //avoid compiler warning
+  if( iInteractionMode == GL3DWidget::PickMode )
+  {
+    mPickBox->mousePressed(Qt::RightButton, QCursor::pos());
+    mPickBox->mouseReleased(Qt::RightButton, QCursor::pos());
+    std::set<QRgb> result=mPickBox->getListOfColorsPicked();
+    if(!result.empty())
+    {
+      emit actorsPicked(result);
+    }
+
+  }
+}
+
+/**
+ * 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 GL3DWidget::mouseMoveEvent(QMouseEvent* event)
+{
+  makeCurrent();
+  if (m_renderMode != FULL3D && m_unwrappedSurface)
+  {
+    if (event->buttons() & Qt::LeftButton)
+    {
+      m_unwrappedSurface->moveSelection(event->x(),event->y());
+      update();
+    }
+    else
+    {
+      int detId = m_unwrappedSurface->getDetectorID(event->x(),event->y());
+      emit actorHighlighted(detId);
+    }
+    OpenGLError::check("GL3DWidget::mouseMoveEvent");
+    return;
+  }
+
+  if(iInteractionMode == GL3DWidget::PickMode)
+  {
+    setCursor(Qt::CrossCursor);
+    QRgb tmpColor = mPickBox->pickPoint(event->x(), event->y());
+    if (event->buttons() & Qt::LeftButton)
+    {
+      emit increaseSelection(tmpColor);
+      mPickBox->mouseMoveEvent(event);
+      update();
+    }
+    else
+    {
+      emit actorHighlighted(tmpColor);
+    }
+  }
+  else
+  {
+    if (event->buttons() & Qt::LeftButton)
+    {
+      setCursor(Qt::ClosedHandCursor);
+      _trackball->generateRotationTo(event->x(),event->y());
+      update();
+      _trackball->initRotationFrom(event->x(),event->y());
+    }
+    else if(event->buttons() & Qt::RightButton)
+    { //Translate
+      setCursor(Qt::CrossCursor);
+      _trackball->generateTranslationTo(event->x(),event->y());
+      update();
+      _trackball->initTranslateFrom(event->x(),event->y());
+    }
+    else if(event->buttons() & Qt::MidButton)
+    { //Zoom
+      setCursor(Qt::SizeVerCursor);
+      _trackball->generateZoomTo(event->x(),event->y());
+      update();
+      _trackball->initZoomFrom(event->x(),event->y());
+    }
+  }
+  OpenGLError::check("GL3DWidget::mouseMoveEvent");
+}
+
+/**
+ * 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 GL3DWidget::mouseReleaseEvent(QMouseEvent* event)
+{
+  if (m_renderMode != FULL3D && m_unwrappedSurface)
+  {
+    if (getInteractionMode() == PickMode && m_unwrappedSurface->hasSelection())
+    {
+      showUnwrappedContextMenu();
+    }
+    m_unwrappedSurface->endSelection(event->x(),event->y());
+    update();
+    return;
+  }
+
+  setCursor(Qt::PointingHandCursor);
+  isKeyPressed=false;
+  setSceneHighResolution();
+  if(iInteractionMode == GL3DWidget::PickMode)
+  {
+    mPickBox->mouseReleased(event->buttons(), event->pos());
+    std::set<QRgb> result=mPickBox->getListOfColorsPicked();
+    if(!result.empty())
+    {
+      emit actorsPicked(result);
+    }
+  }
+  update();
+}
+
+/**
+ * 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 GL3DWidget::wheelEvent(QWheelEvent* event)
+{
+  makeCurrent();
+  setCursor(Qt::SizeVerCursor);
+  _trackball->initZoomFrom(event->x(),event->y());
+  _trackball->generateZoomTo(event->x(),event->y()-event->delta());
+  update();
+  setCursor(Qt::PointingHandCursor);
+  OpenGLError::check("GL3DWidget::wheelEvent");
+}
+
+/**
+ * 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 GL3DWidget::keyPressEvent(QKeyEvent *event)
+{
+  makeCurrent();
+  grabKeyboard();
+  // Ignore keyboard event when in pick mode
+  if( iInteractionMode== GL3DWidget::PickMode) return; 
+  int width,height;
+  _viewport->getViewport(&width,&height);
+  int halfwidth=width/2;
+  int halfheight=height/2;
+  switch(event->key())
+    {
+      //-----------------------Translation-----------------
+    case Qt::Key_Left:
+      isKeyPressed=true;
+      setCursor(Qt::CrossCursor);
+      _trackball->initTranslateFrom(1,0);
+      _trackball->generateTranslationTo(0,0);
+      update();
+      break;
+    case Qt::Key_Right:
+      isKeyPressed=true;
+      setCursor(Qt::CrossCursor);
+      _trackball->initTranslateFrom(0,0);
+      _trackball->generateTranslationTo(1,0);
+      update();
+      break;
+    case Qt::Key_Up:
+      isKeyPressed=true;
+      setCursor(Qt::CrossCursor);
+      _trackball->initTranslateFrom(0,1);
+      _trackball->generateTranslationTo(0,0);
+      update();
+      break;
+    case Qt::Key_Down:
+      isKeyPressed=true;
+      setCursor(Qt::CrossCursor);
+      _trackball->initTranslateFrom(0,0);
+      _trackball->generateTranslationTo(0,1);
+      update();
+      break;
+      //--------------------End of Translation---------------
+      //--------------------Rotation-------------------------
+    case Qt::Key_1:
+      isKeyPressed=true;
+      setCursor(Qt::ClosedHandCursor);
+      _trackball->initRotationFrom(halfwidth,halfheight);
+      _trackball->generateRotationTo(halfwidth-1,halfheight+1);
+      update();
+      break;
+    case Qt::Key_2:
+      isKeyPressed=true;
+      setCursor(Qt::ClosedHandCursor);
+      _trackball->initRotationFrom(halfwidth,halfheight);
+      _trackball->generateRotationTo(halfwidth,halfheight+1);
+      update();
+      break;
+    case Qt::Key_3:
+      isKeyPressed=true;
+      setCursor(Qt::ClosedHandCursor);
+      _trackball->initRotationFrom(halfwidth,halfheight);
+      _trackball->generateRotationTo(halfwidth+1,halfheight+1);
+      update();
+      break;
+    case Qt::Key_4:
+      isKeyPressed=true;
+      setCursor(Qt::ClosedHandCursor);
+      _trackball->initRotationFrom(halfwidth,halfheight);
+      _trackball->generateRotationTo(halfwidth-1,halfheight);
+      update();
+      break;
+    case Qt::Key_6:
+      isKeyPressed=true;
+      setCursor(Qt::ClosedHandCursor);
+      _trackball->initRotationFrom(halfwidth,halfheight);
+      _trackball->generateRotationTo(halfwidth+1,halfheight);
+      update();
+      break;
+    case Qt::Key_7:
+      isKeyPressed=true;
+      setCursor(Qt::ClosedHandCursor);
+      _trackball->initRotationFrom(halfwidth,halfheight);
+      _trackball->generateRotationTo(halfwidth-1,halfheight-1);
+      update();
+      break;
+    case Qt::Key_8:
+      isKeyPressed=true;
+      setCursor(Qt::ClosedHandCursor);
+      _trackball->initRotationFrom(halfwidth,halfheight);
+      _trackball->generateRotationTo(halfwidth,halfheight-1);
+      update();
+      break;
+    case Qt::Key_9:
+      isKeyPressed=true;
+      setCursor(Qt::ClosedHandCursor);
+      _trackball->initRotationFrom(halfwidth,halfheight);
+      _trackball->generateRotationTo(halfwidth+1,halfheight-1);
+      update();
+      break;
+      //---------------------------------End of Rotation--------------
+      //---------------------------------Zoom-------------------------
+    case Qt::Key_PageUp:
+      isKeyPressed=true;
+      setCursor(Qt::SizeVerCursor);
+      _trackball->initZoomFrom(halfwidth,halfheight);
+      _trackball->generateZoomTo(halfwidth,halfheight-1);
+      update();
+      break;
+    case Qt::Key_PageDown:
+      isKeyPressed=true;
+      setCursor(Qt::SizeVerCursor);
+      _trackball->initZoomFrom(halfwidth,halfheight);
+      _trackball->generateZoomTo(halfwidth,halfheight+1);
+      update();
+      break;
+    }
+  OpenGLError::check("GL3DWidget::keyPressEvent");
+}
+
+/**
+ * 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 GL3DWidget::keyReleaseEvent(QKeyEvent *event)
+{
+  releaseKeyboard();
+  setCursor(Qt::PointingHandCursor);
+  isKeyPressed=false;
+  if(!event->isAutoRepeat())
+  {
+    update();
+  }
+  OpenGLError::check("GL3DWidget::keyReleaseEvent");
+}
+/**
+ * This method sets the collection of actors that widget needs to display
+ * @param col :: input collection of actors
+ */
+void GL3DWidget::setActorCollection(boost::shared_ptr<GLActorCollection> col)
+{
+  scene=col;
+  update();
+  OpenGLError::check("GL3DWidget::setActorCollection");
+}
+
+/**
+ * This default object initialization method. usually used for testing or added a default
+ * object to all the widgets.
+ */
+void GL3DWidget::MakeObject()
+{
+}
+
+/**
+ * Sets the default view to input provided
+ */
+void GL3DWidget::setViewDirection(AxisDirection dir)
+{
+  makeCurrent();
+  Mantid::Geometry::V3D minPoint,maxPoint;
+  double _bbmin[3],_bbmax[3];
+  getBoundingBox(minPoint,maxPoint);
+  Mantid::Geometry::V3D centre=(maxPoint+minPoint)/2.0;
+  defaultProjection();
+  _viewport->getProjection(_bbmin[0],_bbmax[0],_bbmin[1],_bbmax[1],_bbmin[2],_bbmax[2]);
+  switch(dir)
+  {
+  case XPOSITIVE:
+    _trackball->setViewToXPositive();
+    _trackball->rotateBoundingBox(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],minPoint[2],maxPoint[2]);
+    _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],_bbmin[2],_bbmax[2]);
+    break;
+  case YPOSITIVE:
+    _trackball->setViewToYPositive();
+    _trackball->rotateBoundingBox(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],minPoint[2],maxPoint[2]);
+    _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],_bbmin[2],_bbmax[2]);
+    break;
+  case ZPOSITIVE:
+    _trackball->setViewToZPositive();
+    _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],_bbmin[2],_bbmax[2]);
+    break;
+  case XNEGATIVE:
+    _trackball->setViewToXNegative();
+    _trackball->rotateBoundingBox(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],minPoint[2],maxPoint[2]);
+    _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],_bbmin[2],_bbmax[2]);
+    break;
+  case YNEGATIVE:
+    _trackball->setViewToYNegative();
+    _trackball->rotateBoundingBox(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],minPoint[2],maxPoint[2]);
+    _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],_bbmin[2],_bbmax[2]);
+    break;
+  case ZNEGATIVE:
+    _trackball->setViewToZNegative();
+    _trackball->rotateBoundingBox(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],minPoint[2],maxPoint[2]);
+    _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],_bbmin[2],_bbmax[2]);
+    break;
+  }
+  OpenGLError::check("GL3DWidget::setViewDirection");
+  _viewport->issueGL();
+  update();
+}
+
+/**
+ * This method calculates the default projection
+ */
+void GL3DWidget::defaultProjection()
+{
+  makeCurrent();
+  // Getting the bounding box of the scene and setting the orthagonal projection
+  // such that the orthogonal projection places the object completly in the screen
+  // Its a simplified version of placing the object completly in screen with same
+  // min and max values in all directions.
+  Mantid::Geometry::V3D minPoint,maxPoint;
+  getBoundingBox(minPoint,maxPoint);
+  if(minPoint[0]==DBL_MAX||minPoint[1]==DBL_MAX||minPoint[2]==DBL_MAX||maxPoint[0]==-DBL_MAX||maxPoint[1]==-DBL_MAX||maxPoint[2]==-DBL_MAX)
+  {
+    minPoint=Mantid::Geometry::V3D(-1.0,-1.0,-1.0);
+    maxPoint=Mantid::Geometry::V3D( 1.0, 1.0, 1.0);
+  }
+  double minValue,maxValue;
+  minValue=minPoint[0];
+  if(minValue>minPoint[1])minValue=minPoint[1];
+  if(minValue>minPoint[2])minValue=minPoint[2];
+  maxValue=maxPoint[0];
+  if(maxValue<maxPoint[1])maxValue=maxPoint[1];
+  if(maxValue<maxPoint[2])maxValue=maxPoint[2];
+  if(minValue>maxValue)
+  {
+    double tmp;
+    tmp=maxValue;
+    maxValue=minValue;
+    minValue=maxValue;
+  }
+  double temp=minValue-fabs(maxValue-minValue);
+  maxValue=maxValue+fabs(maxValue-minValue);
+  minValue=temp;
+  
+  _viewport->setOrtho(minPoint[0],maxPoint[0],minPoint[1],maxPoint[1],minValue*-1,maxValue*-1);
+  OpenGLError::check("GL3DWidget::defaultProjection()");
+  Mantid::Geometry::V3D center;
+  center=(minPoint+maxPoint)/2.0;
+  _viewport->issueGL();
+}
+
+/**
+ * Sets the flag indicating the visibility of the orientation axes
+ *
+ */
+void GL3DWidget::set3DAxesState(bool state)
+{
+  m3DAxesShown = state;
+
+  // Update the display
+  update();
+}
+
+
+
+/**
+ * This method set the background color.
+ */
+void GL3DWidget::setBackgroundColor(QColor input)
+{
+  makeCurrent();
+  bgColor = input;
+  glClearColor(bgColor.red()/255.0,bgColor.green()/255.0,bgColor.blue()/255.0,1.0);
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+  OpenGLError::check("GL3DWidget::setBackgroundColor");
+  m_unwrappedSurfaceChanged = true;
+  update();
+}
+
+QColor GL3DWidget::currentBackgroundColor() const
+{
+  return bgColor;
+}
+
+/**
+ * This saves the GL scene to a file.
+ * @param filename :: The name of the file
+ */
+void GL3DWidget::saveToFile(const QString & filename)
+{
+  if( filename.isEmpty() ) return;
+  //  QPixmap pm = renderPixmap();
+  //pm.save(filename);
+  // It seems QGLWidget grabs the back buffer
+  this->swapBuffers(); // temporarily swap the buffers
+  QImage image = this->grabFrameBuffer();
+  this->swapBuffers(); // swap them back
+  OpenGLError::check("GL3DWidget::saveToFile");
+  image.save(filename);
+}
+
+/**
+ * Resets the widget for new instrument definition
+ */
+void GL3DWidget::resetWidget()
+{
+  setActorCollection(boost::shared_ptr<GLActorCollection>(new GLActorCollection()));
+}
+
+/**
+  * Enables / disables lighting
+  * @param on :: Set true to turn lighting on or false to turn it off.
+  */
+void GL3DWidget::enableLighting(bool on)
+{
+  m_lightingState = on? 2 : 0;
+  setLightingModel(m_lightingState);
+  if (m_unwrappedSurface)
+  {
+    m_unwrappedSurface->updateView();
+  }
+  update();
+}
+
+/**
+  * Set wireframe view on or off
+  * @param on :: If true set wireframe, otherwise it's SOLID
+  */
+void GL3DWidget::setWireframe(bool on)
+{
+  m_polygonMode = on ? WIREFRAME : SOLID;
+  update();
+}
+
+void GL3DWidget::setRenderMode(int mode)
+{
+  makeCurrent();
+  if (mode < RENDERMODE_SIZE)
+  {
+    m_renderMode = RenderMode(mode);
+    resetUnwrappedViews();
+  }
+  if (mode == FULL3D)
+  {
+    _viewport->issueGL();
+  }
+  update();
+}
+
+void GL3DWidget::resetUnwrappedViews()
+{
+  if (m_unwrappedSurface)
+  {
+    delete m_unwrappedSurface;
+    m_unwrappedSurface = NULL;
+  }
+  m_unwrappedSurfaceChanged = true;
+}
+
+void GL3DWidget::drawUnwrapped()
+{
+  QApplication::setOverrideCursor(Qt::WaitCursor);
+  if (m_unwrappedSurfaceChanged)
+  {
+    GLActor* actor = scene->getActor(0);
+    if (!actor) return;
+    InstrumentActor* instrActor = dynamic_cast<InstrumentActor*>(actor);
+    if (!instrActor) return;
+    boost::shared_ptr<Mantid::Geometry::IInstrument> instr = instrActor->getInstrument();
+    Mantid::Geometry::IObjComponent_sptr sample = instr->getSample();
+    Mantid::Geometry::V3D sample_pos = sample->getPos();
+
+    QTime time;
+    time.start();
+    if (m_unwrappedSurface) delete m_unwrappedSurface;
+    Mantid::Geometry::V3D axis;
+    if (m_renderMode == SPHERICAL_Y || m_renderMode == CYLINDRICAL_Y)
+    {
+      axis = Mantid::Geometry::V3D(0,1,0);
+    }
+    else if (m_renderMode == SPHERICAL_Z || m_renderMode == CYLINDRICAL_Z)
+    {
+      axis = Mantid::Geometry::V3D(0,0,1);
+    }
+    else // SPHERICAL_X || CYLINDRICAL_X
+    {
+      axis = Mantid::Geometry::V3D(1,0,0);
+    }
+
+    if (m_renderMode <= CYLINDRICAL_X)
+    {
+      m_unwrappedSurface = new UnwrappedCylinder(instrActor,sample_pos,axis);
+    }
+    else // SPHERICAL
+    {
+      m_unwrappedSurface = new UnwrappedSphere(instrActor,sample_pos,axis);
+    }
+
+    m_unwrappedSurfaceChanged = false;
+  }
+
+  m_unwrappedSurface->draw(this);
+
+  QApplication::restoreOverrideCursor();
+  OpenGLError::check("GL3DWidget::drawUnwrapped()");
+}
+
+void GL3DWidget::redrawUnwrapped()
+{
+  if (m_unwrappedSurface)
+  {
+    m_unwrappedSurface->updateDetectors();
+  }
+}
+
+void GL3DWidget::componentSelected(Mantid::Geometry::ComponentID id)
+{
+  if (m_unwrappedSurface)
+  {
+    m_unwrappedSurface->componentSelected(id);
+    update();
+  }
+}
+
+void GL3DWidget::setSelectionType(int type)
+{
+  m_detSelector.reset(DetSelector::create((DetSelectionType)type));
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GL3DWidget.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GL3DWidget.h
index ba0ca7ae2430e3dcdbf5378726f26d083f82a961..671274a76d978c46c5728b9a30d8c999aab779be 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GL3DWidget.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GL3DWidget.h
@@ -1,147 +1,147 @@
-#ifndef GL3DWIDGET_H_
-#define GL3DWIDGET_H_
-
-#include "MantidGeometry/IComponent.h"
-
-#include <QGLWidget>
-#include <QString>
-#include "GLViewport.h"
-#include "GLTrackball.h"
-#include "GLActorCollection.h"
-#include "GLGroupPickBox.h"
-#include "DetSelector.h"
-
-#include "boost/shared_ptr.hpp"
-#include "boost/scoped_ptr.hpp"
-
-class UnwrappedSurface;
-
-/**
-  \class  GL3DWidget
-  \brief  OpenGL Qt Widget which renders Mantid Geometry ObjComponents
-  \author Chapon Laurent & Srikanth Nagella
-  \date   August 2008
-  \version 1.0
-
-  This Class takes input as ObjComponents and renders them with in the Qt widget. also
-  provides the user interaction with the rendered object.
-
-  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-
-class GL3DWidget : public QGLWidget
-{
-  Q_OBJECT
-public:
-  enum InteractionMode {MoveMode = 0, PickMode = 1};
-  enum AxisDirection{ XPOSITIVE,YPOSITIVE,ZPOSITIVE,XNEGATIVE,YNEGATIVE,ZNEGATIVE};
-  enum PolygonMode{ SOLID, WIREFRAME };
-  enum RenderMode{ FULL3D = 0, CYLINDRICAL_Y, CYLINDRICAL_Z, CYLINDRICAL_X, SPHERICAL_Y, SPHERICAL_Z, SPHERICAL_X, RENDERMODE_SIZE };
-  GL3DWidget(QWidget* parent=0); ///< Constructor
-  virtual ~GL3DWidget();         ///< Destructor
-  void setActorCollection(boost::shared_ptr<GLActorCollection>);
-  void setInteractionModePick();
-  void setInteractionModeNormal();
-  InteractionMode getInteractionMode()const{return iInteractionMode;}
-  GLActor* getPickedActor();
-  void setViewDirection(AxisDirection);
-  void setBackgroundColor(QColor);
-  QColor currentBackgroundColor() const;
-  void saveToFile(const QString & filename);
-  void getViewport(int& w,int& h){_viewport->getViewport(&w,&h);}
-  RenderMode getRenderMode()const{return m_renderMode;}
-  bool areAxesOn()const{return m3DAxesShown;}
-
-signals:
-  void actorsPicked(const std::set<QRgb>& );
-  void actorHighlighted( QRgb );
-  void actorHighlighted( int );
-  void increaseSelection(QRgb);                   ///< emitted while the user is draging with the left mouse button clicked over detectors
-
-public slots:
-  void enableLighting(bool);
-  void setWireframe(bool);
-  void resetUnwrappedViews();
-  void componentSelected(Mantid::Geometry::ComponentID);
-  void hidePickBox(){mPickBox->hide();}
-  void setSelectionType(int);
-  void set3DAxesState(bool);
-  void setRenderMode(int);
-
-protected:
-  void initializeGL();
-  void resetWidget();
-  void MakeObject();
-  void paintEvent(QPaintEvent *event);
-  void resizeGL(int,int);
-  void mousePressEvent(QMouseEvent*);
-  void contextMenuEvent(QContextMenuEvent*);
-  void mouseMoveEvent(QMouseEvent*);
-  void mouseReleaseEvent(QMouseEvent*);
-  void wheelEvent(QWheelEvent *);
-  void keyPressEvent(QKeyEvent *);
-  void keyReleaseEvent(QKeyEvent *);
-  void defaultProjection();
-  void redrawUnwrapped();
-  void checkGLError(const QString& funName);
-  
-  virtual void drawSceneUsingColorID()=0;
-  virtual void setSceneLowResolution()=0;
-  virtual void setSceneHighResolution()=0;
-  virtual void getBoundingBox(Mantid::Geometry::V3D& minBound,Mantid::Geometry::V3D& maxBound)=0;
-  virtual void showUnwrappedContextMenu() = 0;
-
-  boost::shared_ptr<GLActorCollection> scene;      ///< Collection of actors
-  GLTrackball* _trackball;       ///< Trackball for user interaction
-  GLViewport* _viewport;         ///< Opengl View port [World -> Window]
-
-private:
-  void setRenderingOptions();
-  void setLightingModel(int);
-  void drawAxes(double axis_length = 100.0);
-  void drawDisplayScene();
-  void drawPickingScene();
-  void switchToPickingMode();
-  void draw3D();
-  void drawUnwrapped();
-
-  QColor bgColor; ///< Background color
-  InteractionMode iInteractionMode;
-  bool mPickingDraw;
-  GLGroupPickBox* mPickBox;      ///< Picker used for user selecting a object in window
-  GLActor* mPickedActor;
-  bool isKeyPressed;
-  bool m3DAxesShown;              ///< true when the 3D axes are to be shown
-  int m_lightingState;           ///< 0 = light off; 2 = light on
-  PolygonMode m_polygonMode;     ///< SOLID or WIREFRAME
-  bool m_firstFrame;
-
-protected:
-  // Unwrapping stuff
-  RenderMode m_renderMode;       ///< 3D view or unwrapped
-  UnwrappedSurface* m_unwrappedSurface;
-  bool m_unwrappedSurfaceChanged;
-  bool m_unwrappedViewChanged;   ///< set when the unwrapped image must be redrawn, but the surface is the same
-  boost::scoped_ptr<DetSelector> m_detSelector;    ///< draws the selection region
-
-};
-
-#endif /*GL3DWIDGET_H_*/
-
+#ifndef GL3DWIDGET_H_
+#define GL3DWIDGET_H_
+
+#include "MantidGeometry/IComponent.h"
+
+#include <QGLWidget>
+#include <QString>
+#include "GLViewport.h"
+#include "GLTrackball.h"
+#include "GLActorCollection.h"
+#include "GLGroupPickBox.h"
+#include "DetSelector.h"
+
+#include "boost/shared_ptr.hpp"
+#include "boost/scoped_ptr.hpp"
+
+class UnwrappedSurface;
+
+/**
+  \class  GL3DWidget
+  \brief  OpenGL Qt Widget which renders Mantid Geometry ObjComponents
+  \author Chapon Laurent & Srikanth Nagella
+  \date   August 2008
+  \version 1.0
+
+  This Class takes input as ObjComponents and renders them with in the Qt widget. also
+  provides the user interaction with the rendered object.
+
+  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+*/
+
+class GL3DWidget : public QGLWidget
+{
+  Q_OBJECT
+public:
+  enum InteractionMode {MoveMode = 0, PickMode = 1};
+  enum AxisDirection{ XPOSITIVE,YPOSITIVE,ZPOSITIVE,XNEGATIVE,YNEGATIVE,ZNEGATIVE};
+  enum PolygonMode{ SOLID, WIREFRAME };
+  enum RenderMode{ FULL3D = 0, CYLINDRICAL_Y, CYLINDRICAL_Z, CYLINDRICAL_X, SPHERICAL_Y, SPHERICAL_Z, SPHERICAL_X, RENDERMODE_SIZE };
+  GL3DWidget(QWidget* parent=0); ///< Constructor
+  virtual ~GL3DWidget();         ///< Destructor
+  void setActorCollection(boost::shared_ptr<GLActorCollection>);
+  void setInteractionModePick();
+  void setInteractionModeNormal();
+  InteractionMode getInteractionMode()const{return iInteractionMode;}
+  GLActor* getPickedActor();
+  void setViewDirection(AxisDirection);
+  void setBackgroundColor(QColor);
+  QColor currentBackgroundColor() const;
+  void saveToFile(const QString & filename);
+  void getViewport(int& w,int& h){_viewport->getViewport(&w,&h);}
+  RenderMode getRenderMode()const{return m_renderMode;}
+  bool areAxesOn()const{return m3DAxesShown;}
+
+signals:
+  void actorsPicked(const std::set<QRgb>& );
+  void actorHighlighted( QRgb );
+  void actorHighlighted( int );
+  void increaseSelection(QRgb);                   ///< emitted while the user is draging with the left mouse button clicked over detectors
+
+public slots:
+  void enableLighting(bool);
+  void setWireframe(bool);
+  void resetUnwrappedViews();
+  void componentSelected(Mantid::Geometry::ComponentID);
+  void hidePickBox(){mPickBox->hide();}
+  void setSelectionType(int);
+  void set3DAxesState(bool);
+  void setRenderMode(int);
+
+protected:
+  void initializeGL();
+  void resetWidget();
+  void MakeObject();
+  void paintEvent(QPaintEvent *event);
+  void resizeGL(int,int);
+  void mousePressEvent(QMouseEvent*);
+  void contextMenuEvent(QContextMenuEvent*);
+  void mouseMoveEvent(QMouseEvent*);
+  void mouseReleaseEvent(QMouseEvent*);
+  void wheelEvent(QWheelEvent *);
+  void keyPressEvent(QKeyEvent *);
+  void keyReleaseEvent(QKeyEvent *);
+  void defaultProjection();
+  void redrawUnwrapped();
+  void checkGLError(const QString& funName);
+  
+  virtual void drawSceneUsingColorID()=0;
+  virtual void setSceneLowResolution()=0;
+  virtual void setSceneHighResolution()=0;
+  virtual void getBoundingBox(Mantid::Geometry::V3D& minBound,Mantid::Geometry::V3D& maxBound)=0;
+  virtual void showUnwrappedContextMenu() = 0;
+
+  boost::shared_ptr<GLActorCollection> scene;      ///< Collection of actors
+  GLTrackball* _trackball;       ///< Trackball for user interaction
+  GLViewport* _viewport;         ///< Opengl View port [World -> Window]
+
+private:
+  void setRenderingOptions();
+  void setLightingModel(int);
+  void drawAxes(double axis_length = 100.0);
+  void drawDisplayScene();
+  void drawPickingScene();
+  void switchToPickingMode();
+  void draw3D();
+  void drawUnwrapped();
+
+  QColor bgColor; ///< Background color
+  InteractionMode iInteractionMode;
+  bool mPickingDraw;
+  GLGroupPickBox* mPickBox;      ///< Picker used for user selecting a object in window
+  GLActor* mPickedActor;
+  bool isKeyPressed;
+  bool m3DAxesShown;              ///< true when the 3D axes are to be shown
+  int m_lightingState;           ///< 0 = light off; 2 = light on
+  PolygonMode m_polygonMode;     ///< SOLID or WIREFRAME
+  bool m_firstFrame;
+
+protected:
+  // Unwrapping stuff
+  RenderMode m_renderMode;       ///< 3D view or unwrapped
+  UnwrappedSurface* m_unwrappedSurface;
+  bool m_unwrappedSurfaceChanged;
+  bool m_unwrappedViewChanged;   ///< set when the unwrapped image must be redrawn, but the surface is the same
+  boost::scoped_ptr<DetSelector> m_detSelector;    ///< draws the selection region
+
+};
+
+#endif /*GL3DWIDGET_H_*/
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActor.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActor.cpp
index 7c5099e6981d175916e1c58cd0fef2885874f37d..952d5fac13a3262a9ff7fbf591d5fd3640dfd2ad 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActor.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActor.cpp
@@ -1,58 +1,58 @@
-#include "GLActor.h"
-
-
-boost::shared_ptr<GLColor> redColor(new GLColor(1.0,0.5,0.0,1.0));
-
-GLActor::GLActor(bool withDisplayList):
-    GLObject(withDisplayList), mPicked(false), mVisible(true)
-{
-	mColor=redColor;
-}
-
-GLActor::~GLActor()
-{
-}
-
-
-/**
- * This method marks the Actor as picked
- */
-void GLActor::markPicked()
-{
-    mPicked=true;
-}
-
-/**
- * This method unmarks/clears the Actor pick. set the status as unpicked
- */
-void GLActor::markUnPicked()
-{
-    mPicked=false;
-}
-
-/**
- * This method sets the color for the actor
- * @param color :: input color for the actor
- */
-void GLActor::setColor(boost::shared_ptr<GLColor> color)
-{
-    mColor=color;
-}
-
-/**
- * This method sets the visiblity of the actor
- * @param visible :: input visibility ( true for visible and false for hidden
- */
-void GLActor::setVisibility(bool visible)
-{
-	mVisible=visible;
-}
-
-/**
- * This method gets the visibility of the actor
- * @return true for actor visible and false for hidden
- */
-bool GLActor::getVisibility()
-{
-	return mVisible;
-}
+#include "GLActor.h"
+
+
+boost::shared_ptr<GLColor> redColor(new GLColor(1.0,0.5,0.0,1.0));
+
+GLActor::GLActor(bool withDisplayList):
+    GLObject(withDisplayList), mPicked(false), mVisible(true)
+{
+	mColor=redColor;
+}
+
+GLActor::~GLActor()
+{
+}
+
+
+/**
+ * This method marks the Actor as picked
+ */
+void GLActor::markPicked()
+{
+    mPicked=true;
+}
+
+/**
+ * This method unmarks/clears the Actor pick. set the status as unpicked
+ */
+void GLActor::markUnPicked()
+{
+    mPicked=false;
+}
+
+/**
+ * This method sets the color for the actor
+ * @param color :: input color for the actor
+ */
+void GLActor::setColor(boost::shared_ptr<GLColor> color)
+{
+    mColor=color;
+}
+
+/**
+ * This method sets the visiblity of the actor
+ * @param visible :: input visibility ( true for visible and false for hidden
+ */
+void GLActor::setVisibility(bool visible)
+{
+	mVisible=visible;
+}
+
+/**
+ * This method gets the visibility of the actor
+ * @return true for actor visible and false for hidden
+ */
+bool GLActor::getVisibility()
+{
+	return mVisible;
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActor.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActor.h
index c81e48af1979ddac2793d46b7c61c1c3677e961b..1948415e0d4457752ccf18c30ca5f8646f82f712 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActor.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActor.h
@@ -1,104 +1,104 @@
-/**________________________________________________
-* Library        : NTK
-* Name           : GLActor.h
-* Author         : L.C.Chapon
-* Date           : 8 Nov 2006
-* Description    : Base class for all objects in a 3D Scene.
-*                  Methods are provide to position and
-*                  rotate the objects. The objects can also
-*                  be set as active or not. Actors maintian safe pointer
-*                  to a GLObject.
-*________________________________________________
-*/
-#ifndef GLACTOR_H_
-#define GLACTOR_H_
-#include "MantidGeometry/V3D.h"
-#include "GLObject.h"
-#include "GLColor.h"
-#include "boost/shared_ptr.hpp"
-#include <ostream>
-
-#include <QList>
-//#include <QObject>
-
-class UnwrappedCylinder;
-class UnwrappedDetectorCyl;
-
-namespace Mantid
-{
-  namespace Geometry
-  {
-    class IDetector;
-  }
-}
-
-struct DetectorCallbackData
-{
-  DetectorCallbackData(const GLColor& c):color(c){}
-  GLColor color;
-};
-
-/**
-  * Class for collecting information about detectors form actors.
-  * The information includes the detector id and the fields of the DetectorCallbackData struct
-  */
-class DetectorCallback
-{
-public:
-  /// An actor calls this method for each of its detectors and passes the detetctor id and
-  /// a reference to a DetectorCallbackData struct filled with the information about that detector
-  virtual void callback(boost::shared_ptr<const Mantid::Geometry::IDetector> det,const DetectorCallbackData& data) = 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.
-
-  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-class GLActor : public GLObject
-{
-public:
-
-  GLActor(bool withDisplayList);          ///< Constructor with name of actor as input string
-  GLActor(const GLActor&);        ///< Constructor with another actor as input
-  virtual ~GLActor();             ///< Virtual destructor
-  void setColor(boost::shared_ptr<GLColor>);
-  const boost::shared_ptr<GLColor> getColor()const{return mColor;}
-  void markPicked();
-  void markUnPicked();
-  void setVisibility(bool);
-  bool getVisibility();
-  virtual int  setStartingReferenceColor(int){return 1;}
-  /// Calls the DetectorCallback::callback method for each detector
-  virtual void detectorCallback(DetectorCallback* /*callback*/)const{}
-protected:
-  boost::shared_ptr<GLColor> mColor;           ///< Color of the geometry object
-  bool  mPicked;                   ///< Flag Whether the actor is picked by mouse click or not
-  bool  mVisible;					 ///< Flag whether the actor is visible or not
-};
-
-#endif /*GLACTOR_H_*/
+/**________________________________________________
+* Library        : NTK
+* Name           : GLActor.h
+* Author         : L.C.Chapon
+* Date           : 8 Nov 2006
+* Description    : Base class for all objects in a 3D Scene.
+*                  Methods are provide to position and
+*                  rotate the objects. The objects can also
+*                  be set as active or not. Actors maintian safe pointer
+*                  to a GLObject.
+*________________________________________________
+*/
+#ifndef GLACTOR_H_
+#define GLACTOR_H_
+#include "MantidGeometry/V3D.h"
+#include "GLObject.h"
+#include "GLColor.h"
+#include "boost/shared_ptr.hpp"
+#include <ostream>
+
+#include <QList>
+//#include <QObject>
+
+class UnwrappedCylinder;
+class UnwrappedDetectorCyl;
+
+namespace Mantid
+{
+  namespace Geometry
+  {
+    class IDetector;
+  }
+}
+
+struct DetectorCallbackData
+{
+  DetectorCallbackData(const GLColor& c):color(c){}
+  GLColor color;
+};
+
+/**
+  * Class for collecting information about detectors form actors.
+  * The information includes the detector id and the fields of the DetectorCallbackData struct
+  */
+class DetectorCallback
+{
+public:
+  /// An actor calls this method for each of its detectors and passes the detetctor id and
+  /// a reference to a DetectorCallbackData struct filled with the information about that detector
+  virtual void callback(boost::shared_ptr<const Mantid::Geometry::IDetector> det,const DetectorCallbackData& data) = 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.
+
+  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+*/
+class GLActor : public GLObject
+{
+public:
+
+  GLActor(bool withDisplayList);          ///< Constructor with name of actor as input string
+  GLActor(const GLActor&);        ///< Constructor with another actor as input
+  virtual ~GLActor();             ///< Virtual destructor
+  void setColor(boost::shared_ptr<GLColor>);
+  const boost::shared_ptr<GLColor> getColor()const{return mColor;}
+  void markPicked();
+  void markUnPicked();
+  void setVisibility(bool);
+  bool getVisibility();
+  virtual int  setStartingReferenceColor(int){return 1;}
+  /// Calls the DetectorCallback::callback method for each detector
+  virtual void detectorCallback(DetectorCallback* /*callback*/)const{}
+protected:
+  boost::shared_ptr<GLColor> mColor;           ///< Color of the geometry object
+  bool  mPicked;                   ///< Flag Whether the actor is picked by mouse click or not
+  bool  mVisible;					 ///< Flag whether the actor is visible or not
+};
+
+#endif /*GLACTOR_H_*/
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActorCollection.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActorCollection.cpp
index 8bdef4ad2db45479f10fa727d1ed709ccd3a5cb4..a2c1ca6ca12d0e1953556b21cf05090ca97f6f96 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActorCollection.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActorCollection.cpp
@@ -1,129 +1,129 @@
-#include "GLActorCollection.h"
-#include <stdexcept>
-#include <iostream>
-#include <functional>
-#include <algorithm>
-#include <float.h>
-
-//static int hash(unsigned char r, unsigned char g, unsigned char b)
-//{
-//	 return r*65536+g*256+b;
-//}
-
-GLActorCollection::GLActorCollection():GLObject(true)
-{
-	referenceColorID[0] = 0;
-	referenceColorID[1] = 0;
-	referenceColorID[2] = 1;
-}
-
-GLActorCollection::~GLActorCollection()
-{
-	for(std::vector<GLActor*>::iterator i=mActorsList.begin();i!=mActorsList.end();i++)
-	{
-	  delete (*i);
-	}
-	mActorsList.clear();
-}
-
-/**
- * This method does the drawing by calling the list of actors to draw themselfs
- */
-void GLActorCollection::define()
-{
-    for_each(mActorsList.begin(),mActorsList.end(),std::mem_fun(&GLActor::draw));
-}
-
-
-/**
- * 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);
-	int rgb = referenceColorID[0]*65536 + referenceColorID[1]*256 + referenceColorID[2];
-	int noOfColors = a->setStartingReferenceColor(rgb);
-	rgb += noOfColors;
-	referenceColorID[0] = rgb / 65536;
-	referenceColorID[1] = (rgb % 65536) / 256;
-	referenceColorID[2] = (rgb % 65536) % 256;
-}
-
-/**
- * Remove the input actor from the collection
- * @param a :: 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 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);
-}
-
-/**
- * This method is to find the matching input color id in the collection of actors color and mark the matched actor as picked.
- * @param color :: input color
- */
-GLActor* GLActorCollection::findColorID(unsigned char color[3])
-{
-  (void) color; //avoid compiler warning
-
-	GLActor* picked=0;
-	throw std::runtime_error("Find colorid not implemented");
-	//int key=hash(color[0],color[1],color[2]);
-	//Actormap::const_iterator it=_actors.find(key);
-	//if (it!=_actors.end())
-	//{
-	//	picked=(*it).second;
-	//	picked->markPicked();
-	//}
-	return picked;
-}
-
-/**
- * This method redraws the entire scene because of change in the color
- */
-void GLActorCollection::refresh()
-{
-	this->mChanged=true;
-}
-
-/**
- * This method calls all the initialisation of the Actors in the collection
- */
-void GLActorCollection::init()
-{
-    for_each(mActorsList.begin(),mActorsList.end(),std::mem_fun(&GLActor::init));
-}
-
-//void GLActorCollection::addToUnwrappedList(UnwrappedCylinder& cylinder, QList<UnwrappedDetectorCyl>& list)
-//{
-//  std::vector<GLActor*>::iterator it = mActorsList.begin();
-//  for(;it != mActorsList.end();++it)
-//  {
-//    (**it).addToUnwrappedList(cylinder,list);
-//  }
-//}
+#include "GLActorCollection.h"
+#include <stdexcept>
+#include <iostream>
+#include <functional>
+#include <algorithm>
+#include <float.h>
+
+//static int hash(unsigned char r, unsigned char g, unsigned char b)
+//{
+//	 return r*65536+g*256+b;
+//}
+
+GLActorCollection::GLActorCollection():GLObject(true)
+{
+	referenceColorID[0] = 0;
+	referenceColorID[1] = 0;
+	referenceColorID[2] = 1;
+}
+
+GLActorCollection::~GLActorCollection()
+{
+	for(std::vector<GLActor*>::iterator i=mActorsList.begin();i!=mActorsList.end();i++)
+	{
+	  delete (*i);
+	}
+	mActorsList.clear();
+}
+
+/**
+ * This method does the drawing by calling the list of actors to draw themselfs
+ */
+void GLActorCollection::define()
+{
+    for_each(mActorsList.begin(),mActorsList.end(),std::mem_fun(&GLActor::draw));
+}
+
+
+/**
+ * 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);
+	int rgb = referenceColorID[0]*65536 + referenceColorID[1]*256 + referenceColorID[2];
+	int noOfColors = a->setStartingReferenceColor(rgb);
+	rgb += noOfColors;
+	referenceColorID[0] = rgb / 65536;
+	referenceColorID[1] = (rgb % 65536) / 256;
+	referenceColorID[2] = (rgb % 65536) % 256;
+}
+
+/**
+ * Remove the input actor from the collection
+ * @param a :: 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 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);
+}
+
+/**
+ * This method is to find the matching input color id in the collection of actors color and mark the matched actor as picked.
+ * @param color :: input color
+ */
+GLActor* GLActorCollection::findColorID(unsigned char color[3])
+{
+  (void) color; //avoid compiler warning
+
+	GLActor* picked=0;
+	throw std::runtime_error("Find colorid not implemented");
+	//int key=hash(color[0],color[1],color[2]);
+	//Actormap::const_iterator it=_actors.find(key);
+	//if (it!=_actors.end())
+	//{
+	//	picked=(*it).second;
+	//	picked->markPicked();
+	//}
+	return picked;
+}
+
+/**
+ * This method redraws the entire scene because of change in the color
+ */
+void GLActorCollection::refresh()
+{
+	this->mChanged=true;
+}
+
+/**
+ * This method calls all the initialisation of the Actors in the collection
+ */
+void GLActorCollection::init()
+{
+    for_each(mActorsList.begin(),mActorsList.end(),std::mem_fun(&GLActor::init));
+}
+
+//void GLActorCollection::addToUnwrappedList(UnwrappedCylinder& cylinder, QList<UnwrappedDetectorCyl>& list)
+//{
+//  std::vector<GLActor*>::iterator it = mActorsList.begin();
+//  for(;it != mActorsList.end();++it)
+//  {
+//    (**it).addToUnwrappedList(cylinder,list);
+//  }
+//}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActorCollection.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActorCollection.h
index c9945f1ccb709c45f9dc76ce91073b5e9d2a1d17..b8f1b9ee876ddc21e7a8bbad5b5c591f1b771e25 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActorCollection.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLActorCollection.h
@@ -1,67 +1,67 @@
-#ifndef GLACTORCOLLECTION_H_
-#define GLACTORCOLLECTION_H_
-#include "GLActor.h"
-#include "GLObject.h"
-#include <vector>
-#include "MantidGeometry/V3D.h"
-
-#ifndef HAS_UNORDERED_MAP_H
-#include <map>
-#else
-#include <tr1/unordered_map>
-#endif
-
-
-
-/**
-  \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
-
-  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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-
-
-class GLActorCollection: public GLObject
-{
-public:
-  GLActorCollection(); ///< Default Constructor
-  virtual ~GLActorCollection(); ///< Destructor
-  void addActor(GLActor*);
-  void removeActor(GLActor*);
-  int  getNumberOfActors();
-  GLActor* getActor(int index);
-  void define();
-  GLActor* findColorID(unsigned char[3]);
-  void refresh();
-  //void addToUnwrappedList(UnwrappedCylinder& cylinder, QList<UnwrappedDetectorCyl>& list);
-private:
-  void init();
-  std::vector<GLActor*> mActorsList;    ///< Vector of GLActors for fast access.
-  unsigned char referenceColorID[3];
-};
-
-
-#endif /*GLACTORCOLLECTION_H_*/
+#ifndef GLACTORCOLLECTION_H_
+#define GLACTORCOLLECTION_H_
+#include "GLActor.h"
+#include "GLObject.h"
+#include <vector>
+#include "MantidGeometry/V3D.h"
+
+#ifndef HAS_UNORDERED_MAP_H
+#include <map>
+#else
+#include <tr1/unordered_map>
+#endif
+
+
+
+/**
+  \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
+
+  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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+*/
+
+
+class GLActorCollection: public GLObject
+{
+public:
+  GLActorCollection(); ///< Default Constructor
+  virtual ~GLActorCollection(); ///< Destructor
+  void addActor(GLActor*);
+  void removeActor(GLActor*);
+  int  getNumberOfActors();
+  GLActor* getActor(int index);
+  void define();
+  GLActor* findColorID(unsigned char[3]);
+  void refresh();
+  //void addToUnwrappedList(UnwrappedCylinder& cylinder, QList<UnwrappedDetectorCyl>& list);
+private:
+  void init();
+  std::vector<GLActor*> mActorsList;    ///< Vector of GLActors for fast access.
+  unsigned char referenceColorID[3];
+};
+
+
+#endif /*GLACTORCOLLECTION_H_*/
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLColor.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLColor.cpp
index 1c6b7f307e57ee68c4b5c374ee4e7487f7c766c8..8c86610f5e0368183180f45d332106b34c2d8ff4 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLColor.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLColor.cpp
@@ -1,92 +1,92 @@
-//--------------------------------
-// Includes
-//--------------------------------
-#include "GLColor.h"
-#include "MantidGeometry/Rendering/OpenGL_Headers.h"
-
-/**
- * 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] = red;
-  m_rgba[1] = green;
-  m_rgba[2] = blue;
-  m_rgba[3] = alpha;
-}
-
-/**
- * (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] = red;
-  m_rgba[1] = green;
-  m_rgba[2] = blue;
-  m_rgba[3] = alpha;
-}
-
-/**
- * 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 = m_rgba[0];
-  green = m_rgba[1];
-  blue = m_rgba[2];
-  alpha = m_rgba[3];
-}
-
-/**
-  * 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 = (unsigned char)(m_rgba[0]*255);
-  *(c+1) = (unsigned char)(m_rgba[1]*255);
-  *(c+2) = (unsigned char)(m_rgba[2]*255);
-}
-
-/**
- * This method executes opengl color commands based on the method provided.
- * @param pm :: type of opengl color to be used
- */
-void GLColor::paint(GLColor::PaintMethod pm)
-{
-  if(pm == PLAIN) 
-  {
-    glColor4fv(m_rgba);
-  }
-  else if(pm == MATERIAL)
-  {
-    //GLfloat mat_specular[]={1.0,1.0,1.0,1.0};
-    glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,m_rgba); 
-    glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,20.0);
-    //glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,mat_specular);
-  }
-  else 
-  {
-    glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,m_rgba);
-  }
-}
+//--------------------------------
+// Includes
+//--------------------------------
+#include "GLColor.h"
+#include "MantidGeometry/Rendering/OpenGL_Headers.h"
+
+/**
+ * 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] = red;
+  m_rgba[1] = green;
+  m_rgba[2] = blue;
+  m_rgba[3] = alpha;
+}
+
+/**
+ * (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] = red;
+  m_rgba[1] = green;
+  m_rgba[2] = blue;
+  m_rgba[3] = alpha;
+}
+
+/**
+ * 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 = m_rgba[0];
+  green = m_rgba[1];
+  blue = m_rgba[2];
+  alpha = m_rgba[3];
+}
+
+/**
+  * 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 = (unsigned char)(m_rgba[0]*255);
+  *(c+1) = (unsigned char)(m_rgba[1]*255);
+  *(c+2) = (unsigned char)(m_rgba[2]*255);
+}
+
+/**
+ * This method executes opengl color commands based on the method provided.
+ * @param pm :: type of opengl color to be used
+ */
+void GLColor::paint(GLColor::PaintMethod pm)
+{
+  if(pm == PLAIN) 
+  {
+    glColor4fv(m_rgba);
+  }
+  else if(pm == MATERIAL)
+  {
+    //GLfloat mat_specular[]={1.0,1.0,1.0,1.0};
+    glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,m_rgba); 
+    glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,20.0);
+    //glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,mat_specular);
+  }
+  else 
+  {
+    glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,m_rgba);
+  }
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLColor.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLColor.h
index 519909c2e9bd546a01faaa46b7e5945be11ce201..234bda02246dde38c561f2dbf8fd9949503b12ee 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLColor.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLColor.h
@@ -1,59 +1,59 @@
-#ifndef GLCOLOR_H_
-#define GLCOLOR_H_
-
-/**
-  \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
-
-  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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-class GLColor
-{
-public:
-  /// Enumeration for painting type
-  enum PaintMethod {PLAIN = 0, MATERIAL = 1, EMIT = 2};
-  
-  /// Default Constructor
-  GLColor(float red = 0, float green = 0,float blue = 0, float alpha = 0);
-  /// 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;
-  /// Retrieve the component colours
-  void getUB3(unsigned char* c)const;
-  /// Set the painting method
-  void paint(GLColor::PaintMethod pm);
-private:
-  /// The individual components
-  float m_rgba[4];
-};
-
-#endif /*GLCOLOR_H_*/
-
+#ifndef GLCOLOR_H_
+#define GLCOLOR_H_
+
+/**
+  \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
+
+  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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+*/
+class GLColor
+{
+public:
+  /// Enumeration for painting type
+  enum PaintMethod {PLAIN = 0, MATERIAL = 1, EMIT = 2};
+  
+  /// Default Constructor
+  GLColor(float red = 0, float green = 0,float blue = 0, float alpha = 0);
+  /// 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;
+  /// Retrieve the component colours
+  void getUB3(unsigned char* c)const;
+  /// Set the painting method
+  void paint(GLColor::PaintMethod pm);
+private:
+  /// The individual components
+  float m_rgba[4];
+};
+
+#endif /*GLCOLOR_H_*/
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLGroupPickBox.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLGroupPickBox.cpp
index f135ee8d41bb87c0ffa46fb452759d9191e5a007..31e40f89605373f316d1aa41cefbfd3740ae30a9 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLGroupPickBox.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLGroupPickBox.cpp
@@ -1,191 +1,191 @@
-#include "GLGroupPickBox.h"
-#ifdef WIN32
-#include <windows.h>
-#endif
-#include "GLActor.h"
-#include "MantidGeometry/V3D.h"
-#include "MantidObject.h"
-#include "GLActorCollection.h"
-#include <QMessageBox>
-
-GLGroupPickBox::GLGroupPickBox()
-{
-	mBoxStartPtX=0;
-	mBoxStartPtY=0;
-	mBoxEndPtX=0;
-	mBoxEndPtY=0;
-	mPickingActive=false;
-}
-
-GLGroupPickBox::~GLGroupPickBox()
-{
-}
-
-
-/**
- * This methods sets the display image and picker image. display image is used for displaying on the render
- * which is different from the image used for picking using mouse.
- * @param displayImage: input for the display image
- * @param pickerImage: input for the pick image
- */
-void GLGroupPickBox::setImages(QImage displayImage,QImage pickerImage)
-{
-	mDisplayImage=displayImage;
-	mPickImage=pickerImage;
-}
-
-/**
- * This method sets the display image.
- * @param displayImage: input for the display image
- */
-void GLGroupPickBox::setDisplayImage(QImage displayImage)
-{
-	mDisplayImage=displayImage;
-}
-
-/**
- * This method sets the pick image.
- * @param pickerImage: input for the pick image
- */
-void GLGroupPickBox::setPickImage(QImage pickerImage)
-{
-	mPickImage=pickerImage;
-}
-
-/**
- * This is the slot for the mouse move operation.
- * when mouse is moved with the button pressed then the picker box grows.
- * @param event: input with mouse event information such as button state
- */ 
-void GLGroupPickBox::mouseMoveEvent ( QMouseEvent * event )
-{
-  if(mPickingActive)
-  {
-    mBoxEndPtX=event->x();
-    mBoxEndPtY=event->y();		
-  }
-}
-
-/**
- * This is the slot for the mouse press event operation
- * when mouse button is pressed that point will be the start point of the pick box
- * @param event: input with mouse event information such as button state
- */
-void GLGroupPickBox::mousePressed(Qt::MouseButtons buttons, const QPoint & pos)
-{
-  if( (buttons & Qt::LeftButton) || (buttons & Qt::RightButton) )
-  {
-    mPickingActive = true;
-    mBoxStartPtX=pos.x();
-    mBoxStartPtY=pos.y();
-    mBoxEndPtX=pos.x();
-    mBoxEndPtY=pos.y();
-  }
-  else
-  {
-    mPickingActive = false;
-  }
-}
-
-/**
- * This is the slot for the mouse release event operation
- * when the mouse button is released then that point will be the end point of the pick box
- * @param event: input with mouse event information such as button state
- */
-void GLGroupPickBox::mouseReleased (Qt::MouseButtons buttons, const QPoint & pos )
-{
-  (void) buttons; //avoid compiler warning
-
-  if(mPickingActive)
-  {
-    mPickingActive=false;
-    mBoxEndPtX=pos.x();
-    mBoxEndPtY=pos.y();	
-    //Lookup in the actors collection which have same pixel color value as the
-    //pixels in the box, collect unique colors
-    std::set<QRgb> colorSet;
-    //Check for the box limits
-    int x,y,width,height;
-    x=mBoxStartPtX;
-    y=mBoxStartPtY;
-    width=mBoxEndPtX-mBoxStartPtX;
-    height=mBoxEndPtY-mBoxStartPtY;
-    if(width<0)
-    {
-      x=mBoxEndPtX;
-      width*=-1;
-    }
-    else if(width==0)
-    {
-      width=1;
-    }
-    if(height<0)
-    {
-      y=mBoxEndPtY;
-      height*=-1;
-    }
-    else if(height==0)
-    {
-      height=1;
-    }
-    QImage selectedImage=mPickImage.copy(x,y,width,height);
-    for(int iPix=0;iPix<selectedImage.width();iPix++)
-    {
-      for(int jPix=0;jPix<selectedImage.height();jPix++)
-      {
-	QRgb colorVal=selectedImage.pixel(iPix,jPix);
-	colorSet.insert(colorVal);
-      }
-    }
-    mColorSet=colorSet;
-  }
-}
-
-/**
- * Returns the list of colors picked
- */
-std::set<QRgb> GLGroupPickBox::getListOfColorsPicked()
-{
-	return mColorSet;
-}
-
-/**
- * picking a actor at a input point from image
- * @param x :: input x-dim value of the point
- * @param y :: input y-dim value of the point
- */
-QRgb GLGroupPickBox::pickPoint(int x, int y) // Picking object at coordinate of (x,y)
-{
-  if( mPickImage.valid(x, y) ) 
-  {
-    return mPickImage.pixel(x,y);
-  }
-  else return QRgb();
-}
-
-/**
- * This method draws the display image along with the box
- */
-void GLGroupPickBox::draw(QPainter* painter)
-{
-    painter->drawImage(0,0,mDisplayImage);
-    if (mBoxEndPtX != mBoxStartPtX && mBoxEndPtY != mBoxStartPtY)
-    {
-      drawPickBox(painter);
-    }
-  }
-
-/**
- * This method draws the pick box
- */
-void GLGroupPickBox::drawPickBox(QPainter* painter)
-{
-    painter->setPen(Qt::blue);
-    painter->drawRect(mBoxStartPtX,mBoxStartPtY,mBoxEndPtX-mBoxStartPtX,mBoxEndPtY-mBoxStartPtY);
-}
-
-void GLGroupPickBox::hide()
-{
-  mBoxEndPtX = mBoxStartPtX;
-  mBoxEndPtY = mBoxStartPtY;
-}
+#include "GLGroupPickBox.h"
+#ifdef WIN32
+#include <windows.h>
+#endif
+#include "GLActor.h"
+#include "MantidGeometry/V3D.h"
+#include "MantidObject.h"
+#include "GLActorCollection.h"
+#include <QMessageBox>
+
+GLGroupPickBox::GLGroupPickBox()
+{
+	mBoxStartPtX=0;
+	mBoxStartPtY=0;
+	mBoxEndPtX=0;
+	mBoxEndPtY=0;
+	mPickingActive=false;
+}
+
+GLGroupPickBox::~GLGroupPickBox()
+{
+}
+
+
+/**
+ * This methods sets the display image and picker image. display image is used for displaying on the render
+ * which is different from the image used for picking using mouse.
+ * @param displayImage: input for the display image
+ * @param pickerImage: input for the pick image
+ */
+void GLGroupPickBox::setImages(QImage displayImage,QImage pickerImage)
+{
+	mDisplayImage=displayImage;
+	mPickImage=pickerImage;
+}
+
+/**
+ * This method sets the display image.
+ * @param displayImage: input for the display image
+ */
+void GLGroupPickBox::setDisplayImage(QImage displayImage)
+{
+	mDisplayImage=displayImage;
+}
+
+/**
+ * This method sets the pick image.
+ * @param pickerImage: input for the pick image
+ */
+void GLGroupPickBox::setPickImage(QImage pickerImage)
+{
+	mPickImage=pickerImage;
+}
+
+/**
+ * This is the slot for the mouse move operation.
+ * when mouse is moved with the button pressed then the picker box grows.
+ * @param event: input with mouse event information such as button state
+ */ 
+void GLGroupPickBox::mouseMoveEvent ( QMouseEvent * event )
+{
+  if(mPickingActive)
+  {
+    mBoxEndPtX=event->x();
+    mBoxEndPtY=event->y();		
+  }
+}
+
+/**
+ * This is the slot for the mouse press event operation
+ * when mouse button is pressed that point will be the start point of the pick box
+ * @param event: input with mouse event information such as button state
+ */
+void GLGroupPickBox::mousePressed(Qt::MouseButtons buttons, const QPoint & pos)
+{
+  if( (buttons & Qt::LeftButton) || (buttons & Qt::RightButton) )
+  {
+    mPickingActive = true;
+    mBoxStartPtX=pos.x();
+    mBoxStartPtY=pos.y();
+    mBoxEndPtX=pos.x();
+    mBoxEndPtY=pos.y();
+  }
+  else
+  {
+    mPickingActive = false;
+  }
+}
+
+/**
+ * This is the slot for the mouse release event operation
+ * when the mouse button is released then that point will be the end point of the pick box
+ * @param event: input with mouse event information such as button state
+ */
+void GLGroupPickBox::mouseReleased (Qt::MouseButtons buttons, const QPoint & pos )
+{
+  (void) buttons; //avoid compiler warning
+
+  if(mPickingActive)
+  {
+    mPickingActive=false;
+    mBoxEndPtX=pos.x();
+    mBoxEndPtY=pos.y();	
+    //Lookup in the actors collection which have same pixel color value as the
+    //pixels in the box, collect unique colors
+    std::set<QRgb> colorSet;
+    //Check for the box limits
+    int x,y,width,height;
+    x=mBoxStartPtX;
+    y=mBoxStartPtY;
+    width=mBoxEndPtX-mBoxStartPtX;
+    height=mBoxEndPtY-mBoxStartPtY;
+    if(width<0)
+    {
+      x=mBoxEndPtX;
+      width*=-1;
+    }
+    else if(width==0)
+    {
+      width=1;
+    }
+    if(height<0)
+    {
+      y=mBoxEndPtY;
+      height*=-1;
+    }
+    else if(height==0)
+    {
+      height=1;
+    }
+    QImage selectedImage=mPickImage.copy(x,y,width,height);
+    for(int iPix=0;iPix<selectedImage.width();iPix++)
+    {
+      for(int jPix=0;jPix<selectedImage.height();jPix++)
+      {
+	QRgb colorVal=selectedImage.pixel(iPix,jPix);
+	colorSet.insert(colorVal);
+      }
+    }
+    mColorSet=colorSet;
+  }
+}
+
+/**
+ * Returns the list of colors picked
+ */
+std::set<QRgb> GLGroupPickBox::getListOfColorsPicked()
+{
+	return mColorSet;
+}
+
+/**
+ * picking a actor at a input point from image
+ * @param x :: input x-dim value of the point
+ * @param y :: input y-dim value of the point
+ */
+QRgb GLGroupPickBox::pickPoint(int x, int y) // Picking object at coordinate of (x,y)
+{
+  if( mPickImage.valid(x, y) ) 
+  {
+    return mPickImage.pixel(x,y);
+  }
+  else return QRgb();
+}
+
+/**
+ * This method draws the display image along with the box
+ */
+void GLGroupPickBox::draw(QPainter* painter)
+{
+    painter->drawImage(0,0,mDisplayImage);
+    if (mBoxEndPtX != mBoxStartPtX && mBoxEndPtY != mBoxStartPtY)
+    {
+      drawPickBox(painter);
+    }
+  }
+
+/**
+ * This method draws the pick box
+ */
+void GLGroupPickBox::drawPickBox(QPainter* painter)
+{
+    painter->setPen(Qt::blue);
+    painter->drawRect(mBoxStartPtX,mBoxStartPtY,mBoxEndPtX-mBoxStartPtX,mBoxEndPtY-mBoxStartPtY);
+}
+
+void GLGroupPickBox::hide()
+{
+  mBoxEndPtX = mBoxStartPtX;
+  mBoxEndPtY = mBoxStartPtY;
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLGroupPickBox.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLGroupPickBox.h
index 5fd09969a1c540fb0b4fc2fc932625d20f6c275b..eea59544ec903820d0e95987019e00e2a547f164 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLGroupPickBox.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLGroupPickBox.h
@@ -1,69 +1,69 @@
-#ifndef GLGROUPPICKBOX_H_
-#define GLGROUPPICKBOX_H_
-
-#include <QImage>
-#include <QPainter>
-#include <QMouseEvent>
-#include <vector>
-#include <set>
-/**
-  \class  GLGroupPickBox
-  \brief  class to display and pick group of detectors
-  \author Srikanth Nagella
-  \date   November 2008
-  \version 1.0
-
-  GLGroupPickBox class takes an image and based on mouse operations draws the box and fires the objects that are 
-  with in the box.
-
-  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-class GLActorCollection;
-class GLActor;
-class GLGroupPickBox
-{
-public:
-  GLGroupPickBox();  ///< Constructor
-  ~GLGroupPickBox();                   ///< Destructor
-  void setImages(QImage,QImage);
-  void setDisplayImage(QImage);
-  void setPickImage(QImage);
-  void draw(QPainter*);
-  void drawPickBox(QPainter* painter);
-  void mousePressed (Qt::MouseButtons buttons, const QPoint & pos );
-  void mouseMoveEvent ( QMouseEvent * event );
-  void mouseReleased(Qt::MouseButtons buttons, const QPoint & pos);
-  QRgb pickPoint(int x, int y);
-  std::set<QRgb> getListOfColorsPicked();
-  void hide();
-
-  QImage mDisplayImage;  ///< This image is used for rendering in the window.
-  QImage mPickImage;     ///< This image is used for picking the objects.
-private:
-  std::set<QRgb> mColorSet;
-  int    mBoxStartPtX; ///< X-dim value of start point in Rectangular Box for the pick selection
-  int    mBoxEndPtX; ///< X-dim value of end point in Rectangular Box for the pick selection
-  int    mBoxStartPtY; ///< Y-dim value of start point in Rectangular Box for the pick selection
-  int    mBoxEndPtY; ///< Y-dim value of end point Rectangular Box for the pick selection
-  bool   mPickingActive; ///< Holds whether picking is active or not
-};
-
-#endif /*GLGROUPPICKBOX_H_*/
-
+#ifndef GLGROUPPICKBOX_H_
+#define GLGROUPPICKBOX_H_
+
+#include <QImage>
+#include <QPainter>
+#include <QMouseEvent>
+#include <vector>
+#include <set>
+/**
+  \class  GLGroupPickBox
+  \brief  class to display and pick group of detectors
+  \author Srikanth Nagella
+  \date   November 2008
+  \version 1.0
+
+  GLGroupPickBox class takes an image and based on mouse operations draws the box and fires the objects that are 
+  with in the box.
+
+  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+*/
+class GLActorCollection;
+class GLActor;
+class GLGroupPickBox
+{
+public:
+  GLGroupPickBox();  ///< Constructor
+  ~GLGroupPickBox();                   ///< Destructor
+  void setImages(QImage,QImage);
+  void setDisplayImage(QImage);
+  void setPickImage(QImage);
+  void draw(QPainter*);
+  void drawPickBox(QPainter* painter);
+  void mousePressed (Qt::MouseButtons buttons, const QPoint & pos );
+  void mouseMoveEvent ( QMouseEvent * event );
+  void mouseReleased(Qt::MouseButtons buttons, const QPoint & pos);
+  QRgb pickPoint(int x, int y);
+  std::set<QRgb> getListOfColorsPicked();
+  void hide();
+
+  QImage mDisplayImage;  ///< This image is used for rendering in the window.
+  QImage mPickImage;     ///< This image is used for picking the objects.
+private:
+  std::set<QRgb> mColorSet;
+  int    mBoxStartPtX; ///< X-dim value of start point in Rectangular Box for the pick selection
+  int    mBoxEndPtX; ///< X-dim value of end point in Rectangular Box for the pick selection
+  int    mBoxStartPtY; ///< Y-dim value of start point in Rectangular Box for the pick selection
+  int    mBoxEndPtY; ///< Y-dim value of end point Rectangular Box for the pick selection
+  bool   mPickingActive; ///< Holds whether picking is active or not
+};
+
+#endif /*GLGROUPPICKBOX_H_*/
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLObject.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLObject.cpp
index a9aa4b1ee7210638ce401c125fa0c8a02b4e43d0..a23164296513af904c646a9265415ea1be46f27e 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLObject.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLObject.cpp
@@ -1,89 +1,89 @@
-#ifdef WIN32
-#include <windows.h>
-#endif
-#include "GLObject.h"
-#include "ObjCompAssemblyActor.h"
-#include "MantidKernel/Exception.h"
-#include "MantidKernel/System.h"
-#include <iostream>
-
-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);
-}
-
-/**
- * This method draws the opengl display list.
- */
-void GLObject::draw()
-{
-  //std::cout << "GLObject::draw() for " << this->mName << "\n";
-  if (mChanged) construct();
-  if (mDisplayListId!=0)
-  {
-    //std::cerr << mDisplayListId << '\n';
-    glCallList(mDisplayListId);
-  }
-  else
-  {
-    define();
-  }
-}
-
-/**
- * This method constructs the opengl display list
- */
-void GLObject::construct()
-{
-	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))
-        //std::cerr<<"construct " << getName() << ' ' << mDisplayListId << '\n';
-	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()
-{
-}
-
-/**
- * Virtual method which constructs the opengl rendering commands.
- */
-void GLObject::define()
-{
-}
-
-void GLObject::setName(const std::string& name)
-{
-	mName=name;
-}
-std::string GLObject::getName() const
-{
-	return mName;
-}
-
+#ifdef WIN32
+#include <windows.h>
+#endif
+#include "GLObject.h"
+#include "ObjCompAssemblyActor.h"
+#include "MantidKernel/Exception.h"
+#include "MantidKernel/System.h"
+#include <iostream>
+
+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);
+}
+
+/**
+ * This method draws the opengl display list.
+ */
+void GLObject::draw()
+{
+  //std::cout << "GLObject::draw() for " << this->mName << "\n";
+  if (mChanged) construct();
+  if (mDisplayListId!=0)
+  {
+    //std::cerr << mDisplayListId << '\n';
+    glCallList(mDisplayListId);
+  }
+  else
+  {
+    define();
+  }
+}
+
+/**
+ * This method constructs the opengl display list
+ */
+void GLObject::construct()
+{
+	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))
+        //std::cerr<<"construct " << getName() << ' ' << mDisplayListId << '\n';
+	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()
+{
+}
+
+/**
+ * Virtual method which constructs the opengl rendering commands.
+ */
+void GLObject::define()
+{
+}
+
+void GLObject::setName(const std::string& name)
+{
+	mName=name;
+}
+std::string GLObject::getName() const
+{
+	return mName;
+}
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLObject.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLObject.h
index b656522a2a6c513511200a8dfeb5417975eea537..b6db4e89a2fa5a21612e1d96695bdb5e600e3511 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLObject.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLObject.h
@@ -1,9 +1,9 @@
-#ifndef MANTIDPLOT_GLOBJECT_H_
-#define MANTIDPLOT_GLOBJECT_H_
-
-#include <string>
-#include "MantidGeometry/Rendering/OpenGL_Headers.h"
-
+#ifndef MANTIDPLOT_GLOBJECT_H_
+#define MANTIDPLOT_GLOBJECT_H_
+
+#include <string>
+#include "MantidGeometry/Rendering/OpenGL_Headers.h"
+
 /**
   \class  GLObject
   \brief  Interface for OpenGL object stored in a display list
@@ -11,11 +11,11 @@
   \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
+   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
+  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
 
   This file is part of Mantid.
 
@@ -33,35 +33,35 @@
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
   File change history is stored at: <https://svn.mantidproject.org/mantid/trunk/Code/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 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();
-  /// Define the drawing here.
-  virtual void define();
-  /// Don't know about this
-  virtual void init();
-  /// 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();
-protected:
-  /// Name
-  std::string mName;
-  GLuint mDisplayListId;                   ///< OpengGL Display list id
-  bool mChanged;                         ///< Flag holding the change in the object
-};
-#endif /*MANTIDPLOT_GLOBJECT_H*/
-
+*/
+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 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();
+  /// Define the drawing here.
+  virtual void define();
+  /// Don't know about this
+  virtual void init();
+  /// 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();
+protected:
+  /// Name
+  std::string mName;
+  GLuint mDisplayListId;                   ///< OpengGL Display list id
+  bool mChanged;                         ///< Flag holding the change in the object
+};
+#endif /*MANTIDPLOT_GLOBJECT_H*/
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLTrackball.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLTrackball.cpp
index 077516ff99908273dc178bc975f158b1571a5391..59ae7bc88004b53527e23621b4fe63f46ab0f0a8 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLTrackball.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLTrackball.cpp
@@ -1,245 +1,245 @@
-#include "GLTrackball.h"
-#include <cmath>
-#include "MantidGeometry/Rendering/OpenGL_Headers.h"
-#include "GLViewport.h"
-#include "OpenGLError.h"
-
-GLTrackball::GLTrackball(GLViewport* parent):_viewport(parent)
-{
-  reset();
-  // Rotation speed defines as such is equal 1 in relative units,
-  // i.e. the trackball will follow exactly the displacement of the mouse
-  // on the sceen. The factor 180/M_PI is simply rad to deg conversion. THis
-  // prevent recalculation of this factor every time a generateRotationTo call is issued.
-  _rotationspeed=180/M_PI;
-  _modelCenter=Mantid::Geometry::V3D(0.0,0.0,0.0);
-  hasOffset=false;
-}
-GLTrackball::~GLTrackball()
-{
-}
-void GLTrackball::initRotationFrom(int a,int b)
-{
-  projectOnSphere(a,b,_lastpoint);
-}
-void GLTrackball::generateRotationTo(int a,int b)
-{
-  Mantid::Geometry::V3D _newpoint;
-  projectOnSphere(a,b,_newpoint);
-  Mantid::Geometry::V3D diff(_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=_rotationspeed*_newpoint.angle(_lastpoint);
-  diff=_lastpoint.cross_prod(_newpoint);
-  // Create a quaternion from the angle and vector direction
-  Mantid::Geometry::Quat temp(angle,diff);
-  // Left multiply
-  temp*=_quaternion;
-  // Assignment of _quaternion
-  _quaternion(temp);
-  // Get the corresponding OpenGL rotation matrix
-  _quaternion.GLMatrix(&_rotationmatrix[0]);
-  return;
-}
-
-void GLTrackball::initTranslateFrom(int a,int b)
-{
-  generateTranslationPoint(a,b,_lastpoint);
-}
-
-void GLTrackball::generateTranslationTo(int a, int b)
-{
-  Mantid::Geometry::V3D _newpoint;
-  generateTranslationPoint(a,b,_newpoint);
-  // This is now the difference
-  _newpoint-=_lastpoint;
-  double x,y;
-  _viewport->getTranslation(x,y);
-  _viewport->setTranslation(x+_newpoint[0],y+_newpoint[1]);
-}
-
-void GLTrackball::initZoomFrom(int a,int b)
-{
-  if (a<=0 || b<=0)
-    return;
-  double x,y,z=0;
-  int _viewport_w, _viewport_h;
-  _viewport->getViewport(&_viewport_w,&_viewport_h);
-  if(a>=_viewport_w || b>=_viewport_h)
-    return;
-  x=static_cast<double>((_viewport_w-a));
-  y=static_cast<double>((b-_viewport_h));
-  _lastpoint(x,y,z);
-}
-
-void GLTrackball::generateZoomTo(int a, int b)
-{
-  double x,y=0;
-  int _viewport_w, _viewport_h;
-  _viewport->getViewport(&_viewport_w,&_viewport_h);
-  if(a>=_viewport_w || b>=_viewport_h||a <= 0||b<=0)return;
-  x=static_cast<double>((_viewport_w-a));
-  y=static_cast<double>((b-_viewport_h));
-  if(y==0) y=_lastpoint[1];
-  double diff= _lastpoint[1]/y ;
-  diff*=_viewport->getZoomFactor();
-  _viewport->setZoomFactor(diff);
-}
-
-
-void GLTrackball::IssueRotation() const
-{
-  if (_viewport)
-  {
-    // Translate if offset is defined
-    if (hasOffset)
-    {
-      glTranslated(_modelCenter[0],_modelCenter[1],_modelCenter[2]);
-    }
-    // Rotate with respect to the centre
-    glMultMatrixd(_rotationmatrix);
-    // Translate back
-    if (hasOffset)
-      glTranslated(-_modelCenter[0],-_modelCenter[1],-_modelCenter[2]);
-  }
-
-  OpenGLError::check("GLTrackball::IssueRotation()");
-  return;
-}
-
-void GLTrackball::setModelCenter(const Mantid::Geometry::V3D& center)
-{
-  _modelCenter=center;
-  if (_modelCenter.nullVector())
-    hasOffset=false;
-  else
-    hasOffset=true;
-}
-
-Mantid::Geometry::V3D GLTrackball::getModelCenter() const
-{
-  return _modelCenter;
-}
-
-void GLTrackball::projectOnSphere(int a,int b,Mantid::Geometry::V3D& point)
-{
-  // z initiaised to zero if out of the sphere
-  double x,y,z=0;
-  int _viewport_w, _viewport_h;
-  _viewport->getViewport(&_viewport_w,&_viewport_h);
-  x=static_cast<double>((2.0*a-_viewport_w)/_viewport_w);
-  y=static_cast<double>((_viewport_h-2.0*b)/_viewport_h);
-  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);
-}
-
-void GLTrackball::generateTranslationPoint(int a,int b,Mantid::Geometry::V3D& point)
-{
-  double x,y,z=0.0;
-  int _viewport_w, _viewport_h;
-  double xmin,xmax,ymin,ymax,zmin,zmax;
-  _viewport->getViewport(&_viewport_w,&_viewport_h);
-  _viewport->getProjection(xmin,xmax,ymin,ymax,zmin,zmax);
-  x=static_cast<double>((xmin+((xmax-xmin)*((double)a/(double)_viewport_w))));
-  y=static_cast<double>((ymin+((ymax-ymin)*(_viewport_h-b)/_viewport_h)));
-  double factor=_viewport->getZoomFactor();
-  x*=factor;
-  y*=factor;
-  // Assign new values to point
-  point(x,y,z);
-}
-void GLTrackball::setRotationSpeed(double r)
-{
-  // Rotation speed needs to contains conversion to degrees.
-  //
-  if (r>0) _rotationspeed=r*180.0/M_PI;
-}
-void GLTrackball::setViewport(GLViewport* v)
-{
-  if (v) _viewport=v;
-}
-
-void GLTrackball::reset()
-{
-  //Reset rotation,scale and translation
-  _quaternion.init();
-  _quaternion.GLMatrix(&_rotationmatrix[0]);
-  _viewport->setTranslation(0.0,0.0);
-  _viewport->setZoomFactor(1.0);
-}
-
-void GLTrackball::setViewToXPositive()
-{
-  reset();
-  Mantid::Geometry::Quat tempy(Mantid::Geometry::V3D(0.0,0.0,1.0),Mantid::Geometry::V3D(1.0,0.0,0.0));
-  _quaternion=tempy;
-  _quaternion.GLMatrix(&_rotationmatrix[0]);
-}
-
-void GLTrackball::setViewToYPositive()
-{
-  reset();
-  Mantid::Geometry::Quat tempy(Mantid::Geometry::V3D(0.0,0.0,1.0),Mantid::Geometry::V3D(0.0,1.0,0.0));
-  _quaternion=tempy;
-  _quaternion.GLMatrix(&_rotationmatrix[0]);
-}
-
-void GLTrackball::setViewToZPositive()
-{
-  reset();
-  _quaternion.init();
-  _quaternion.GLMatrix(&_rotationmatrix[0]);
-}
-
-void GLTrackball::setViewToXNegative()
-{
-  reset();
-  Mantid::Geometry::Quat tempy(Mantid::Geometry::V3D(0.0,0.0,1.0),Mantid::Geometry::V3D(-1.0,0.0,0.0));
-  _quaternion=tempy;
-  _quaternion.GLMatrix(&_rotationmatrix[0]);
-}
-
-void GLTrackball::setViewToYNegative()
-{
-  reset();
-  Mantid::Geometry::Quat tempy(Mantid::Geometry::V3D(0.0,0.0,1.0),Mantid::Geometry::V3D(0.0,-1.0,0.0));
-  _quaternion=tempy;
-  _quaternion.GLMatrix(&_rotationmatrix[0]);
-}
-
-void GLTrackball::setViewToZNegative()
-{
-  reset();
-  Mantid::Geometry::Quat tempy(180.0,Mantid::Geometry::V3D(0.0,1.0,0.0));
-  _quaternion=tempy;
-  _quaternion.GLMatrix(&_rotationmatrix[0]);
-}
-
-void GLTrackball::rotateBoundingBox(double& xmin,double& xmax,double& ymin,double& ymax,double& zmin,double& zmax)
-{
-  // remove offset
-  xmin-=_modelCenter[0];ymin-=_modelCenter[1];zmin-=_modelCenter[2];
-  xmax-=_modelCenter[0];ymax-=_modelCenter[1];zmax-=_modelCenter[2];
-  // Get the new bounding box
-  _quaternion.rotateBB(xmin,ymin,zmin,xmax,ymax,zmax);
-  // Re-apply offset
-  xmin+=_modelCenter[0];ymin+=_modelCenter[1];zmin+=_modelCenter[2];
-  xmax+=_modelCenter[0];ymax+=_modelCenter[1];zmax+=_modelCenter[2];
-  return;
-}
-
-void GLTrackball::setRotation(const Mantid::Geometry::Quat& quat)
-{
-  _quaternion=quat;
-  _quaternion.GLMatrix(&_rotationmatrix[0]);
-}
+#include "GLTrackball.h"
+#include <cmath>
+#include "MantidGeometry/Rendering/OpenGL_Headers.h"
+#include "GLViewport.h"
+#include "OpenGLError.h"
+
+GLTrackball::GLTrackball(GLViewport* parent):_viewport(parent)
+{
+  reset();
+  // Rotation speed defines as such is equal 1 in relative units,
+  // i.e. the trackball will follow exactly the displacement of the mouse
+  // on the sceen. The factor 180/M_PI is simply rad to deg conversion. THis
+  // prevent recalculation of this factor every time a generateRotationTo call is issued.
+  _rotationspeed=180/M_PI;
+  _modelCenter=Mantid::Geometry::V3D(0.0,0.0,0.0);
+  hasOffset=false;
+}
+GLTrackball::~GLTrackball()
+{
+}
+void GLTrackball::initRotationFrom(int a,int b)
+{
+  projectOnSphere(a,b,_lastpoint);
+}
+void GLTrackball::generateRotationTo(int a,int b)
+{
+  Mantid::Geometry::V3D _newpoint;
+  projectOnSphere(a,b,_newpoint);
+  Mantid::Geometry::V3D diff(_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=_rotationspeed*_newpoint.angle(_lastpoint);
+  diff=_lastpoint.cross_prod(_newpoint);
+  // Create a quaternion from the angle and vector direction
+  Mantid::Geometry::Quat temp(angle,diff);
+  // Left multiply
+  temp*=_quaternion;
+  // Assignment of _quaternion
+  _quaternion(temp);
+  // Get the corresponding OpenGL rotation matrix
+  _quaternion.GLMatrix(&_rotationmatrix[0]);
+  return;
+}
+
+void GLTrackball::initTranslateFrom(int a,int b)
+{
+  generateTranslationPoint(a,b,_lastpoint);
+}
+
+void GLTrackball::generateTranslationTo(int a, int b)
+{
+  Mantid::Geometry::V3D _newpoint;
+  generateTranslationPoint(a,b,_newpoint);
+  // This is now the difference
+  _newpoint-=_lastpoint;
+  double x,y;
+  _viewport->getTranslation(x,y);
+  _viewport->setTranslation(x+_newpoint[0],y+_newpoint[1]);
+}
+
+void GLTrackball::initZoomFrom(int a,int b)
+{
+  if (a<=0 || b<=0)
+    return;
+  double x,y,z=0;
+  int _viewport_w, _viewport_h;
+  _viewport->getViewport(&_viewport_w,&_viewport_h);
+  if(a>=_viewport_w || b>=_viewport_h)
+    return;
+  x=static_cast<double>((_viewport_w-a));
+  y=static_cast<double>((b-_viewport_h));
+  _lastpoint(x,y,z);
+}
+
+void GLTrackball::generateZoomTo(int a, int b)
+{
+  double x,y=0;
+  int _viewport_w, _viewport_h;
+  _viewport->getViewport(&_viewport_w,&_viewport_h);
+  if(a>=_viewport_w || b>=_viewport_h||a <= 0||b<=0)return;
+  x=static_cast<double>((_viewport_w-a));
+  y=static_cast<double>((b-_viewport_h));
+  if(y==0) y=_lastpoint[1];
+  double diff= _lastpoint[1]/y ;
+  diff*=_viewport->getZoomFactor();
+  _viewport->setZoomFactor(diff);
+}
+
+
+void GLTrackball::IssueRotation() const
+{
+  if (_viewport)
+  {
+    // Translate if offset is defined
+    if (hasOffset)
+    {
+      glTranslated(_modelCenter[0],_modelCenter[1],_modelCenter[2]);
+    }
+    // Rotate with respect to the centre
+    glMultMatrixd(_rotationmatrix);
+    // Translate back
+    if (hasOffset)
+      glTranslated(-_modelCenter[0],-_modelCenter[1],-_modelCenter[2]);
+  }
+
+  OpenGLError::check("GLTrackball::IssueRotation()");
+  return;
+}
+
+void GLTrackball::setModelCenter(const Mantid::Geometry::V3D& center)
+{
+  _modelCenter=center;
+  if (_modelCenter.nullVector())
+    hasOffset=false;
+  else
+    hasOffset=true;
+}
+
+Mantid::Geometry::V3D GLTrackball::getModelCenter() const
+{
+  return _modelCenter;
+}
+
+void GLTrackball::projectOnSphere(int a,int b,Mantid::Geometry::V3D& point)
+{
+  // z initiaised to zero if out of the sphere
+  double x,y,z=0;
+  int _viewport_w, _viewport_h;
+  _viewport->getViewport(&_viewport_w,&_viewport_h);
+  x=static_cast<double>((2.0*a-_viewport_w)/_viewport_w);
+  y=static_cast<double>((_viewport_h-2.0*b)/_viewport_h);
+  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);
+}
+
+void GLTrackball::generateTranslationPoint(int a,int b,Mantid::Geometry::V3D& point)
+{
+  double x,y,z=0.0;
+  int _viewport_w, _viewport_h;
+  double xmin,xmax,ymin,ymax,zmin,zmax;
+  _viewport->getViewport(&_viewport_w,&_viewport_h);
+  _viewport->getProjection(xmin,xmax,ymin,ymax,zmin,zmax);
+  x=static_cast<double>((xmin+((xmax-xmin)*((double)a/(double)_viewport_w))));
+  y=static_cast<double>((ymin+((ymax-ymin)*(_viewport_h-b)/_viewport_h)));
+  double factor=_viewport->getZoomFactor();
+  x*=factor;
+  y*=factor;
+  // Assign new values to point
+  point(x,y,z);
+}
+void GLTrackball::setRotationSpeed(double r)
+{
+  // Rotation speed needs to contains conversion to degrees.
+  //
+  if (r>0) _rotationspeed=r*180.0/M_PI;
+}
+void GLTrackball::setViewport(GLViewport* v)
+{
+  if (v) _viewport=v;
+}
+
+void GLTrackball::reset()
+{
+  //Reset rotation,scale and translation
+  _quaternion.init();
+  _quaternion.GLMatrix(&_rotationmatrix[0]);
+  _viewport->setTranslation(0.0,0.0);
+  _viewport->setZoomFactor(1.0);
+}
+
+void GLTrackball::setViewToXPositive()
+{
+  reset();
+  Mantid::Geometry::Quat tempy(Mantid::Geometry::V3D(0.0,0.0,1.0),Mantid::Geometry::V3D(1.0,0.0,0.0));
+  _quaternion=tempy;
+  _quaternion.GLMatrix(&_rotationmatrix[0]);
+}
+
+void GLTrackball::setViewToYPositive()
+{
+  reset();
+  Mantid::Geometry::Quat tempy(Mantid::Geometry::V3D(0.0,0.0,1.0),Mantid::Geometry::V3D(0.0,1.0,0.0));
+  _quaternion=tempy;
+  _quaternion.GLMatrix(&_rotationmatrix[0]);
+}
+
+void GLTrackball::setViewToZPositive()
+{
+  reset();
+  _quaternion.init();
+  _quaternion.GLMatrix(&_rotationmatrix[0]);
+}
+
+void GLTrackball::setViewToXNegative()
+{
+  reset();
+  Mantid::Geometry::Quat tempy(Mantid::Geometry::V3D(0.0,0.0,1.0),Mantid::Geometry::V3D(-1.0,0.0,0.0));
+  _quaternion=tempy;
+  _quaternion.GLMatrix(&_rotationmatrix[0]);
+}
+
+void GLTrackball::setViewToYNegative()
+{
+  reset();
+  Mantid::Geometry::Quat tempy(Mantid::Geometry::V3D(0.0,0.0,1.0),Mantid::Geometry::V3D(0.0,-1.0,0.0));
+  _quaternion=tempy;
+  _quaternion.GLMatrix(&_rotationmatrix[0]);
+}
+
+void GLTrackball::setViewToZNegative()
+{
+  reset();
+  Mantid::Geometry::Quat tempy(180.0,Mantid::Geometry::V3D(0.0,1.0,0.0));
+  _quaternion=tempy;
+  _quaternion.GLMatrix(&_rotationmatrix[0]);
+}
+
+void GLTrackball::rotateBoundingBox(double& xmin,double& xmax,double& ymin,double& ymax,double& zmin,double& zmax)
+{
+  // remove offset
+  xmin-=_modelCenter[0];ymin-=_modelCenter[1];zmin-=_modelCenter[2];
+  xmax-=_modelCenter[0];ymax-=_modelCenter[1];zmax-=_modelCenter[2];
+  // Get the new bounding box
+  _quaternion.rotateBB(xmin,ymin,zmin,xmax,ymax,zmax);
+  // Re-apply offset
+  xmin+=_modelCenter[0];ymin+=_modelCenter[1];zmin+=_modelCenter[2];
+  xmax+=_modelCenter[0];ymax+=_modelCenter[1];zmax+=_modelCenter[2];
+  return;
+}
+
+void GLTrackball::setRotation(const Mantid::Geometry::Quat& quat)
+{
+  _quaternion=quat;
+  _quaternion.GLMatrix(&_rotationmatrix[0]);
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLTrackball.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLTrackball.h
index 44cb9411e33dc19d3d09ba4258f2b5a4b030bb2c..8b9f001d0fc99446632faa83304216fded62db48 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLTrackball.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLTrackball.h
@@ -1,9 +1,9 @@
-#ifndef GLTRACKBALL_H_
-#define GLTRACKBALL_H_
-#include "MantidKernel/System.h"
-#include "MantidGeometry/V3D.h"
-#include "MantidGeometry/Quat.h"
-
+#ifndef GLTRACKBALL_H_
+#define GLTRACKBALL_H_
+#include "MantidKernel/System.h"
+#include "MantidGeometry/V3D.h"
+#include "MantidGeometry/Quat.h"
+
 /**
   \class  GLTrackball
   \brief  An class that implements virtual trackball using mouse interactions
@@ -14,7 +14,7 @@
   This class is an implementation of virtual trackball using mouse interactions. It uses Quaternions for
   performing the rotations.
 
-  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
+  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
 
   This file is part of Mantid.
 
@@ -32,76 +32,76 @@
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
   File change history is stored at: <https://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-
-/// Forward declaration of class GLViewport
-class GLViewport;
-///
-class GLTrackball
-{
-public:
-	GLTrackball(GLViewport* parent=0);
-	virtual ~GLTrackball();
-	//! Call when the mouse button is pressed to initiate rotation
-	void initRotationFrom(int,int);
-	//! Call when the mouse is moving during a rotation
-	void generateRotationTo(int,int);
-	//! Change the rotation speed
-	void setRotationSpeed(double);
-	//! To be called in the application drawing the OpenGL Scene
-	void IssueRotation() const;
-  //! Associate the Trackball to a new viewport.
-  void setViewport(GLViewport*);
-	//! Call when the mouse button is pressed to initiate zoom
-	void initZoomFrom(int,int);
-	//! Call when the mouse motion to issue zoom
-	void generateZoomTo(int,int);
-	//! Call when the mouse button is pressed to translate
-	void initTranslateFrom(int,int);
-	//! Call when the mouse is moving during a translation
-	void generateTranslationTo(int,int);
-	//! 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();
-	//! Set Rotation
-	void setRotation(const Mantid::Geometry::Quat& quat);
-	//! Set Model center
-	void setModelCenter(const Mantid::Geometry::V3D& center);
-	//! Get Model center
-	Mantid::Geometry::V3D getModelCenter() const;
-	//! Reset Trackball
-	void reset();
-	//! Rotates a bounding box
-	void rotateBoundingBox(double& xmin,double& xmax,double& ymin,double& ymax,double& zmin,double& zmax);
-private:
-	//! Pointer to the viewport to which the trackball is attached
-  GLViewport* _viewport;
-  //! Project a point on the trackball sphere from viewport coordinates x,y
-	void projectOnSphere(int x,int y, Mantid::Geometry::V3D& p);
-	//! Generate a 3D point coordinates from coordinates on the viewport.
-	void generateTranslationPoint(int x,int y, Mantid::Geometry::V3D& p);
-	//! Previous point selected on sphere
-	Mantid::Geometry::V3D _lastpoint;
-	//! Rotation matrix stored as a quaternion
-	Mantid::Geometry::Quat _quaternion;
-	//! Rotation matrix (4x4 stored as linear array) used in OpenGL
-  double _rotationmatrix[16];
-  //! Rotation speed of the trackball
-	double _rotationspeed;
-	//! Center of rotation
-	Mantid::Geometry::V3D  _modelCenter;
-	//! Is the centre of rotation offcentered
-	bool hasOffset;
-};
-
-
-#endif /*GLTRACKBALL_H_*/
+*/
+
+/// Forward declaration of class GLViewport
+class GLViewport;
+///
+class GLTrackball
+{
+public:
+	GLTrackball(GLViewport* parent=0);
+	virtual ~GLTrackball();
+	//! Call when the mouse button is pressed to initiate rotation
+	void initRotationFrom(int,int);
+	//! Call when the mouse is moving during a rotation
+	void generateRotationTo(int,int);
+	//! Change the rotation speed
+	void setRotationSpeed(double);
+	//! To be called in the application drawing the OpenGL Scene
+	void IssueRotation() const;
+  //! Associate the Trackball to a new viewport.
+  void setViewport(GLViewport*);
+	//! Call when the mouse button is pressed to initiate zoom
+	void initZoomFrom(int,int);
+	//! Call when the mouse motion to issue zoom
+	void generateZoomTo(int,int);
+	//! Call when the mouse button is pressed to translate
+	void initTranslateFrom(int,int);
+	//! Call when the mouse is moving during a translation
+	void generateTranslationTo(int,int);
+	//! 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();
+	//! Set Rotation
+	void setRotation(const Mantid::Geometry::Quat& quat);
+	//! Set Model center
+	void setModelCenter(const Mantid::Geometry::V3D& center);
+	//! Get Model center
+	Mantid::Geometry::V3D getModelCenter() const;
+	//! Reset Trackball
+	void reset();
+	//! Rotates a bounding box
+	void rotateBoundingBox(double& xmin,double& xmax,double& ymin,double& ymax,double& zmin,double& zmax);
+private:
+	//! Pointer to the viewport to which the trackball is attached
+  GLViewport* _viewport;
+  //! Project a point on the trackball sphere from viewport coordinates x,y
+	void projectOnSphere(int x,int y, Mantid::Geometry::V3D& p);
+	//! Generate a 3D point coordinates from coordinates on the viewport.
+	void generateTranslationPoint(int x,int y, Mantid::Geometry::V3D& p);
+	//! Previous point selected on sphere
+	Mantid::Geometry::V3D _lastpoint;
+	//! Rotation matrix stored as a quaternion
+	Mantid::Geometry::Quat _quaternion;
+	//! Rotation matrix (4x4 stored as linear array) used in OpenGL
+  double _rotationmatrix[16];
+  //! Rotation speed of the trackball
+	double _rotationspeed;
+	//! Center of rotation
+	Mantid::Geometry::V3D  _modelCenter;
+	//! Is the centre of rotation offcentered
+	bool hasOffset;
+};
+
+
+#endif /*GLTRACKBALL_H_*/
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLViewport.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLViewport.cpp
index 9e39c2fd1904ff35eedc73c785708b3fb77f2c35..ba309c32b134c2e1c08aebd6c74f32e96ea98f09 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLViewport.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLViewport.cpp
@@ -1,205 +1,205 @@
-#include "GLViewport.h"
-#include <math.h>
-#include <iostream>
-#include "MantidGeometry/Rendering/OpenGL_Headers.h"
-#include "MantidGeometry/V3D.h"
-#include "OpenGLError.h"
-
-GLViewport::GLViewport(int w, int h):mWidth(w),mHeight(h)
-{
-  mProjection=GLViewport::ORTHO;
-  mZoomFactor=1.0;
-  mXTrans=0.0;
-  mYTrans=0.0;
-  mLeft = -1;
-  mRight = 1;
-  mBottom = -1;
-  mTop = 1;
-  mNear = -1;
-  mFar = 1;
-}
-
-GLViewport::~GLViewport()
-{
-}
-void GLViewport::resize(int w,int h)
-{
-    mWidth=w;
-    mHeight=h;
-}
-void GLViewport::getViewport(int* w, int* h) const
-{
-    *w=mWidth;
-    *h=mHeight;
-}
-/**
- * This will set the projection to Ortho
- *
- * @param l :: left side of the Ortho projection (xmin)
- * @param r :: right side of the Ortho projection (xmax)
- * @param b :: bottom side of the Ortho projection (ymin)
- * @param t :: top side of the Ortho projection (ymax)
- * @param near :: near side of the Ortho Projection (zmin)
- * @param far :: far side of the Ortho Projection (zmax)
- * @param useZ :: If set to false near and far will not be used. It is a quick fix of a problem with viewing
- *          selected instrument pixels
- */
-void GLViewport::setOrtho(double l,double r,double b,double t,double nearz,double farz,bool useZ)
-{
-	mLeft=l;
-	mRight=r;
-	if (mLeft>mRight) std::swap(mLeft,mRight); // Make sure that it is only from back to front otherwise the
-	mBottom=b;
-	mTop=t;
-	if (mBottom>mTop) std::swap(mBottom,mTop);
-
-        if (useZ)
-        {
-          mNear=nearz;
-          mFar=farz;
-          if (mNear>mFar) std::swap(mNear,mFar);
-        }
-
-	mProjection=GLViewport::ORTHO;
-}
-
-/**
- * This will set the projection to perspective.
- * UNUSED! as of 2010-11-01.
- *
- * @param l :: left side of the perspective projection (xmin)
- * @param r :: right side of the perspective projection (xmax)
- * @param b :: bottom side of the perspective projection (ymin)
- * @param t :: top side of the perspective projection (ymax)
- * @param near :: near side of the perspective Projection (zmin)
- * @param far :: far side of the perspective Projection (zmax)
- */
-void GLViewport::setPrespective(double l,double r,double b,double t,double nearz,double farz)
-{
-	mLeft=l;
-	mRight=r;
-	mBottom=b;
-	mTop=t;
-	mNear=nearz;
-	mFar=farz;
-	mProjection=GLViewport::PERSPECTIVE;
-}
-
-GLViewport::ProjectionType GLViewport::getProjectionType()const
-{
-	return mProjection;
-}
-
-void GLViewport::getProjection(double& xmin,double& xmax,double& ymin,double& ymax,double& zmin,double& zmax)
-{
-	xmin=mLeft;
-	xmax=mRight;
-	ymin=mBottom;
-	ymax=mTop;
-	zmin=mNear;
-	zmax=mFar;
-}
-
-void GLViewport::setZoomFactor(double val)
-{
-	mZoomFactor=val;
-	issueGL();
-}
-
-double GLViewport::getZoomFactor()
-{
-	return mZoomFactor;
-}
-
-void GLViewport::setTranslation(double xval,double yval)
-{
-	mXTrans=xval;
-	mYTrans=yval;
-	issueGL();
-}
-void GLViewport::getTranslation(double& xval,double& yval)
-{
-	xval=mXTrans;
-	yval=mYTrans;
-}
-
-/** Issue the OpenGL commands that define the viewport and projection. */
-void GLViewport::issueGL() const
-{
-  Mantid::Geometry::V3D center((mRight+mLeft)/2.0,(mTop+mBottom)/2.0,(mNear+mFar)/2.0);
-
-  Mantid::Geometry::V3D distance(mRight-mLeft,mTop-mBottom,mNear-mFar);
-  //Window Aspect ratio
-  GLdouble windowAspect= mHeight > 0 ? (GLdouble)mWidth/(GLdouble)mHeight : 1.0;
-  //Adjust width and height to show the dimensions correct
-  //Adjust window aspect ratio
-  if(windowAspect<1.0) //window height is higher than width (x<y)
-  {
-    if(distance[0]<distance[1]&&distance[0]/windowAspect<distance[1])///TESTING
-    {
-      distance[0]=distance[1];
-      distance[0]*=windowAspect;
-    }
-    else
-    {
-      distance[1]=distance[0];
-      distance[1]/=windowAspect;
-    }
-  }
-  else
-  {
-    if(distance[0]<distance[1])
-    {
-      distance[0]=distance[1];
-      distance[0]*=windowAspect;
-    }
-    else if(distance[0]/windowAspect<distance[1])
-    {
-      distance[0]=distance[1];
-      distance[0]*=windowAspect;
-    }
-    else
-    {
-      distance[1]=distance[0];
-      distance[1]/=windowAspect;
-    }
-  }
-  //use zoom now
-  distance*=mZoomFactor/2.0;
-  glMatrixMode(GL_MODELVIEW);
-  glLoadIdentity();
-  glViewport(0, 0, mWidth, mHeight);
-
-
-  glMatrixMode(GL_PROJECTION);
-  glLoadIdentity();
-  OpenGLError::check("GLViewport::issueGL()");
-  if(mProjection==GLViewport::PERSPECTIVE)
-  {
-    glFrustum(center[0]-distance[0]-mXTrans, center[0]+distance[0]-mXTrans,
-              center[1]-distance[1]-mYTrans, center[1]+distance[1]-mYTrans,
-              center[2]+distance[2], mFar);
-  }
-  else
-  {
-    //    glOrtho(mLeft*mZoomFactor-mXTrans, mRight*mZoomFactor-mXTrans, mBottom*mZoomFactor-mYTrans, mTop*mZoomFactor-mYTrans, mNear*mZoomFactor, mFar);
-
-    double tmpNear = center[2]+distance[2];
-    double nearVal = tmpNear < mNear ? tmpNear : mNear;//center[2]+distance[2];
-    double farVal = mFar;
-
-    glOrtho(center[0]-distance[0]-mXTrans, center[0]+distance[0]-mXTrans,
-            center[1]-distance[1]-mYTrans, center[1]+distance[1]-mYTrans,
-            nearVal, farVal);
-
-    if (OpenGLError::hasError("GLViewport::issueGL()"))
-    {
-      OpenGLError::log() << "Arguments to glOrtho:\n";
-      OpenGLError::log() << center << '\n'
-                         << distance << '\n'
-                         << mXTrans << ' ' << mYTrans << '\n'
-                         << nearVal << ' ' << farVal << "\n\n";
-    }
-  }
-  glMatrixMode(GL_MODELVIEW);
-}
+#include "GLViewport.h"
+#include <math.h>
+#include <iostream>
+#include "MantidGeometry/Rendering/OpenGL_Headers.h"
+#include "MantidGeometry/V3D.h"
+#include "OpenGLError.h"
+
+GLViewport::GLViewport(int w, int h):mWidth(w),mHeight(h)
+{
+  mProjection=GLViewport::ORTHO;
+  mZoomFactor=1.0;
+  mXTrans=0.0;
+  mYTrans=0.0;
+  mLeft = -1;
+  mRight = 1;
+  mBottom = -1;
+  mTop = 1;
+  mNear = -1;
+  mFar = 1;
+}
+
+GLViewport::~GLViewport()
+{
+}
+void GLViewport::resize(int w,int h)
+{
+    mWidth=w;
+    mHeight=h;
+}
+void GLViewport::getViewport(int* w, int* h) const
+{
+    *w=mWidth;
+    *h=mHeight;
+}
+/**
+ * This will set the projection to Ortho
+ *
+ * @param l :: left side of the Ortho projection (xmin)
+ * @param r :: right side of the Ortho projection (xmax)
+ * @param b :: bottom side of the Ortho projection (ymin)
+ * @param t :: top side of the Ortho projection (ymax)
+ * @param near :: near side of the Ortho Projection (zmin)
+ * @param far :: far side of the Ortho Projection (zmax)
+ * @param useZ :: If set to false near and far will not be used. It is a quick fix of a problem with viewing
+ *          selected instrument pixels
+ */
+void GLViewport::setOrtho(double l,double r,double b,double t,double nearz,double farz,bool useZ)
+{
+	mLeft=l;
+	mRight=r;
+	if (mLeft>mRight) std::swap(mLeft,mRight); // Make sure that it is only from back to front otherwise the
+	mBottom=b;
+	mTop=t;
+	if (mBottom>mTop) std::swap(mBottom,mTop);
+
+        if (useZ)
+        {
+          mNear=nearz;
+          mFar=farz;
+          if (mNear>mFar) std::swap(mNear,mFar);
+        }
+
+	mProjection=GLViewport::ORTHO;
+}
+
+/**
+ * This will set the projection to perspective.
+ * UNUSED! as of 2010-11-01.
+ *
+ * @param l :: left side of the perspective projection (xmin)
+ * @param r :: right side of the perspective projection (xmax)
+ * @param b :: bottom side of the perspective projection (ymin)
+ * @param t :: top side of the perspective projection (ymax)
+ * @param near :: near side of the perspective Projection (zmin)
+ * @param far :: far side of the perspective Projection (zmax)
+ */
+void GLViewport::setPrespective(double l,double r,double b,double t,double nearz,double farz)
+{
+	mLeft=l;
+	mRight=r;
+	mBottom=b;
+	mTop=t;
+	mNear=nearz;
+	mFar=farz;
+	mProjection=GLViewport::PERSPECTIVE;
+}
+
+GLViewport::ProjectionType GLViewport::getProjectionType()const
+{
+	return mProjection;
+}
+
+void GLViewport::getProjection(double& xmin,double& xmax,double& ymin,double& ymax,double& zmin,double& zmax)
+{
+	xmin=mLeft;
+	xmax=mRight;
+	ymin=mBottom;
+	ymax=mTop;
+	zmin=mNear;
+	zmax=mFar;
+}
+
+void GLViewport::setZoomFactor(double val)
+{
+	mZoomFactor=val;
+	issueGL();
+}
+
+double GLViewport::getZoomFactor()
+{
+	return mZoomFactor;
+}
+
+void GLViewport::setTranslation(double xval,double yval)
+{
+	mXTrans=xval;
+	mYTrans=yval;
+	issueGL();
+}
+void GLViewport::getTranslation(double& xval,double& yval)
+{
+	xval=mXTrans;
+	yval=mYTrans;
+}
+
+/** Issue the OpenGL commands that define the viewport and projection. */
+void GLViewport::issueGL() const
+{
+  Mantid::Geometry::V3D center((mRight+mLeft)/2.0,(mTop+mBottom)/2.0,(mNear+mFar)/2.0);
+
+  Mantid::Geometry::V3D distance(mRight-mLeft,mTop-mBottom,mNear-mFar);
+  //Window Aspect ratio
+  GLdouble windowAspect= mHeight > 0 ? (GLdouble)mWidth/(GLdouble)mHeight : 1.0;
+  //Adjust width and height to show the dimensions correct
+  //Adjust window aspect ratio
+  if(windowAspect<1.0) //window height is higher than width (x<y)
+  {
+    if(distance[0]<distance[1]&&distance[0]/windowAspect<distance[1])///TESTING
+    {
+      distance[0]=distance[1];
+      distance[0]*=windowAspect;
+    }
+    else
+    {
+      distance[1]=distance[0];
+      distance[1]/=windowAspect;
+    }
+  }
+  else
+  {
+    if(distance[0]<distance[1])
+    {
+      distance[0]=distance[1];
+      distance[0]*=windowAspect;
+    }
+    else if(distance[0]/windowAspect<distance[1])
+    {
+      distance[0]=distance[1];
+      distance[0]*=windowAspect;
+    }
+    else
+    {
+      distance[1]=distance[0];
+      distance[1]/=windowAspect;
+    }
+  }
+  //use zoom now
+  distance*=mZoomFactor/2.0;
+  glMatrixMode(GL_MODELVIEW);
+  glLoadIdentity();
+  glViewport(0, 0, mWidth, mHeight);
+
+
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  OpenGLError::check("GLViewport::issueGL()");
+  if(mProjection==GLViewport::PERSPECTIVE)
+  {
+    glFrustum(center[0]-distance[0]-mXTrans, center[0]+distance[0]-mXTrans,
+              center[1]-distance[1]-mYTrans, center[1]+distance[1]-mYTrans,
+              center[2]+distance[2], mFar);
+  }
+  else
+  {
+    //    glOrtho(mLeft*mZoomFactor-mXTrans, mRight*mZoomFactor-mXTrans, mBottom*mZoomFactor-mYTrans, mTop*mZoomFactor-mYTrans, mNear*mZoomFactor, mFar);
+
+    double tmpNear = center[2]+distance[2];
+    double nearVal = tmpNear < mNear ? tmpNear : mNear;//center[2]+distance[2];
+    double farVal = mFar;
+
+    glOrtho(center[0]-distance[0]-mXTrans, center[0]+distance[0]-mXTrans,
+            center[1]-distance[1]-mYTrans, center[1]+distance[1]-mYTrans,
+            nearVal, farVal);
+
+    if (OpenGLError::hasError("GLViewport::issueGL()"))
+    {
+      OpenGLError::log() << "Arguments to glOrtho:\n";
+      OpenGLError::log() << center << '\n'
+                         << distance << '\n'
+                         << mXTrans << ' ' << mYTrans << '\n'
+                         << nearVal << ' ' << farVal << "\n\n";
+    }
+  }
+  glMatrixMode(GL_MODELVIEW);
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLViewport.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLViewport.h
index 59e8be88b7e67b22a64294d6064a2280c2b46388..8ff6fca6f34e9900254816f77c245ff2ad923112 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLViewport.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/GLViewport.h
@@ -1,76 +1,76 @@
-/**________________________________________________
-* Library        : NTK
-* Name           : GLViewport.h
-* Author         : L.C.Chapon
-* Date           : 9 Nov 2006
-* Descritption   : Base class for viewport with method
-*                  to resize and get viewport information. 
-*                  
-*________________________________________________
-*/
-#ifndef GLVIEWPORT_H_
-#define GLVIEWPORT_H_
-/**
-  \class  GLViewport
-  \brief  class handling OpenGL Viewport
-  \author Chapon Laurent & Srikanth Nagella
-  \date   August 2008
-  \version 1.0
-
-  Base class for viewport with method to resize and get viewport information as well as the projection system it uses and its dimensions. 
-
-  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-class GLViewport
-{
-public:
-	enum ProjectionType{ ORTHO, PERSPECTIVE};
-	GLViewport(int w=0,int h=0); ///< Constructor with Width (w) and Height(h) as inputs
-	~GLViewport();               ///< Destructor
-	//!Called by the display device when viewport is resized
-	void resize(int,int);
-	//!Called by client such as GLTrackball when _width and _height are needed
-	void getViewport(int*, int*) const;
-	ProjectionType getProjectionType()const;
-	void getProjection(double&,double&,double&,double&,double&,double&);
-	void issueGL() const;
-        void setOrtho(double,double,double,double,double,double,bool useZ = true);
-	void setPrespective(double,double,double,double,double,double);
-	void setZoomFactor(double);
-	double getZoomFactor();
-	void setTranslation(double,double);
-	void getTranslation(double&,double&);
-
-protected:
-	int mWidth         ///< Width of the viewport
-	, mHeight;     ///< Height of the viewport
-	double mZoomFactor;
-	double mXTrans,mYTrans;
-	ProjectionType mProjection; ///< Type of display projection
-	double mLeft   ///< Ortho/Prespective Projection xmin value (Left side of the x axis)
-	,mRight    ///< Ortho/Prespective Projection xmax value (Right side of the x axis)
-	,mBottom   ///< Ortho/Prespective Projection ymin value (Bottom side of the y axis)
-	,mTop      ///< Ortho/Prespective Projection ymax value (Top side of the y axis)
-	,mNear     ///< Ortho/Prespective Projection zmin value (Near side of the z axis)
-	,mFar;     ///< Ortho/Prespective Projection zmax value (Far side of the z axis)
-
-};
-
-#endif /*GLVIEWPORT_H_*/
+/**________________________________________________
+* Library        : NTK
+* Name           : GLViewport.h
+* Author         : L.C.Chapon
+* Date           : 9 Nov 2006
+* Descritption   : Base class for viewport with method
+*                  to resize and get viewport information. 
+*                  
+*________________________________________________
+*/
+#ifndef GLVIEWPORT_H_
+#define GLVIEWPORT_H_
+/**
+  \class  GLViewport
+  \brief  class handling OpenGL Viewport
+  \author Chapon Laurent & Srikanth Nagella
+  \date   August 2008
+  \version 1.0
+
+  Base class for viewport with method to resize and get viewport information as well as the projection system it uses and its dimensions. 
+
+  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+*/
+class GLViewport
+{
+public:
+	enum ProjectionType{ ORTHO, PERSPECTIVE};
+	GLViewport(int w=0,int h=0); ///< Constructor with Width (w) and Height(h) as inputs
+	~GLViewport();               ///< Destructor
+	//!Called by the display device when viewport is resized
+	void resize(int,int);
+	//!Called by client such as GLTrackball when _width and _height are needed
+	void getViewport(int*, int*) const;
+	ProjectionType getProjectionType()const;
+	void getProjection(double&,double&,double&,double&,double&,double&);
+	void issueGL() const;
+        void setOrtho(double,double,double,double,double,double,bool useZ = true);
+	void setPrespective(double,double,double,double,double,double);
+	void setZoomFactor(double);
+	double getZoomFactor();
+	void setTranslation(double,double);
+	void getTranslation(double&,double&);
+
+protected:
+	int mWidth         ///< Width of the viewport
+	, mHeight;     ///< Height of the viewport
+	double mZoomFactor;
+	double mXTrans,mYTrans;
+	ProjectionType mProjection; ///< Type of display projection
+	double mLeft   ///< Ortho/Prespective Projection xmin value (Left side of the x axis)
+	,mRight    ///< Ortho/Prespective Projection xmax value (Right side of the x axis)
+	,mBottom   ///< Ortho/Prespective Projection ymin value (Bottom side of the y axis)
+	,mTop      ///< Ortho/Prespective Projection ymax value (Top side of the y axis)
+	,mNear     ///< Ortho/Prespective Projection zmin value (Near side of the z axis)
+	,mFar;     ///< Ortho/Prespective Projection zmax value (Far side of the z axis)
+
+};
+
+#endif /*GLVIEWPORT_H_*/
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/Instrument3DWidget.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/Instrument3DWidget.cpp
index 10b6a45a67450a420cd81125c753816e39610c97..727b308534e5cf3ddfbcc87cd8ac42fe0ffb350c 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/Instrument3DWidget.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/Instrument3DWidget.cpp
@@ -1,1206 +1,1206 @@
-#include "Instrument3DWidget.h"
-#include "InstrumentActor.h"
-#include "InstrumentWindow.h"
-#include "MantidObject.h"
-#include "OpenGLError.h"
-#include "UnwrappedSurface.h"
-
-#include "MantidAPI/AnalysisDataService.h"
-#include "MantidAPI/MatrixWorkspace.h"
-#include "MantidAPI/Axis.h"
-#include "MantidAPI/SpectraDetectorMap.h"
-#include "MantidAPI/FrameworkManager.h"
-#include "MantidAPI/Algorithm.h"
-
-#include "MantidKernel/Exception.h"
-#include "MantidKernel/Timer.h"
-
-#include "MantidGeometry/Math/Matrix.h"
-#include "MantidGeometry/V3D.h"
-#include "MantidGeometry/IInstrument.h"
-#include "MantidGeometry/IComponent.h"
-#include "MantidGeometry/IObjComponent.h"
-#include "MantidGeometry/ICompAssembly.h"
-#include "MantidGeometry/Objects/Object.h"
-#include "MantidGeometry/Rendering/GeometryHandler.h"
-
-#include <QTimer>
-#include <QMessageBox>
-#include <QString>
-#include <QMenu>
-#include <QAction>
-#include <QSet>
-#include <QTemporaryFile>
-#include <QDir>
-#include <QApplication>
-#include <QFileDialog>
-
-#include <map>
-#include <cmath>
-#include <cfloat>
-#include <numeric>
-#include <fstream>
-
-using namespace Mantid::API;
-using namespace Mantid::Kernel;
-using namespace Mantid::Geometry;
-
-static const bool SHOWTIMING = false;
-
-/** A class for creating grouping xml files
-  */
-class DetXMLFile//: public DetectorCallback
-{
-public:
-  enum Option {List,Sum};
-  /// Create a grouping file to extract all detectors in detector_list excluding those in dets
-  DetXMLFile(const std::vector<int> detector_list, const QSet<int>& dets, 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 (!dets.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(const QSet<int>& dets, Option opt = List, const QString& fname = "")
-  {
-    if (dets.empty())
-    {
-      m_fileName = "";
-      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;
-    }
-
-    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 makeListFile(const QSet<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 makeSumFile(const QSet<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";
-  }
-
-  ~DetXMLFile()
-  {
-    if (m_delete)
-    {
-      QDir dir;
-      dir.remove(m_fileName);
-    }
-  }
-
-  /// 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
-};
-
-Instrument3DWidget::Instrument3DWidget(InstrumentWindow* parent):
-  GL3DWidget(parent),m_instrumentWindow(parent),mFastRendering(true), iTimeBin(0), mDataMapping(INTEGRAL),
-  mColorMap(), mInstrumentActor(NULL), mAxisDirection(Mantid::Geometry::V3D(0.0,0.0,1.0)),
-  mAxisUpVector(Mantid::Geometry::V3D(0.0,1.0,0.0)), mDataMinValue(DBL_MAX), mDataMaxValue(-DBL_MAX),
-  mBinMinValue(DBL_MAX), mBinMaxValue(-DBL_MAX),
-  mBinEntireRange(true),
-  mDataMinEdited(false), mDataMaxEdited(false),
-  mWkspDataMin(DBL_MAX), mWkspDataMax(-DBL_MAX), mWkspBinMin(DBL_MAX), mWkspBinMax(-DBL_MAX), 
-  mWorkspaceName(""), mWorkspace(), mScaledValues(0)
-{
-  connect(this, SIGNAL(actorsPicked(const std::set<QRgb>&)), this, SLOT(fireDetectorsPicked(const std::set<QRgb>&)));
-  connect(this, SIGNAL(actorHighlighted(QRgb)),this,SLOT(fireDetectorHighligted(QRgb)));
-  connect(this, SIGNAL(actorHighlighted(int)),this,SLOT(fireDetectorHighligted(int)));
-  connect(this, SIGNAL(increaseSelection(QRgb)),this,SLOT(detectorsHighligted(QRgb)));
-
-  m_ExtractDetsToWorkspaceAction = new QAction("Extract to new workspace",this);
-  connect(m_ExtractDetsToWorkspaceAction,SIGNAL(activated()),this,SLOT(extractDetsToWorkspace()));
-
-  m_SumDetsToWorkspaceAction = new QAction("Sum to new workspace",this);
-  connect(m_SumDetsToWorkspaceAction,SIGNAL(activated()),this,SLOT(sumDetsToWorkspace()));
-
-  m_createIncludeGroupingFileAction = new QAction("Include",this);
-  connect(m_createIncludeGroupingFileAction,SIGNAL(activated()),this,SLOT(createIncludeGroupingFile()));
-
-  m_createExcludeGroupingFileAction = new QAction("Exclude",this);
-  connect(m_createExcludeGroupingFileAction,SIGNAL(activated()),this,SLOT(createExcludeGroupingFile()));
-}
-
-Instrument3DWidget::~Instrument3DWidget()
-{
-  makeCurrent();
-}
-
-/**
- * Set the default Axis direction of the model
- */
-void Instrument3DWidget::setAxis(const Mantid::Geometry::V3D& direction)
-{
-	mAxisDirection = direction;
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * This method is the slot when the detectors are picked using mouse. This method emits
- * signals the ids of the detector and the spectra index(not spectra number).
- * @param pickedActor :: the input passed by the the signal.
- */
-void Instrument3DWidget::fireDetectorsPicked(const std::set<QRgb>& pickedColors)
-{
-  if (m_instrumentWindow->blocked())
-  {
-    return;
-  }
-  std::vector<int> detectorIds;
-  detectorIds.reserve(pickedColors.size());
-  for(std::set<QRgb>::const_iterator it = pickedColors.begin(); it!= pickedColors.end(); it++)
-  {
-    int iDecId = mInstrumentActor->getDetectorIDFromColor(qRed((*it))*65536+qGreen((*it))*256+qBlue((*it)));
-    if(iDecId != -1)
-    {
-      detectorIds.push_back(iDecId);
-    }
-  }
-  if( detectorIds.empty() ) return;
-
-  // fill in m_detector_ids and m_workspace_indices with the selected detector ids
-  createWorkspaceIndexList(detectorIds, true);
-
-  emit detectorsSelected();
-}
-//------------------------------------------------------------------------------------------------
-/**
- * This method is the slot when the detector is highlighted using mouse move. This method emits
- * signals the id of the detector and the spectra index(not spectra number).
- * @param pickedActor :: the input passed by the the signal.
- */
-void Instrument3DWidget::fireDetectorHighligted(QRgb pickedColor)
-{
-  if (m_instrumentWindow->blocked())
-  {
-    return;
-  }
-  //get the data for the detector currently under the cursor
-  const int iDetId = mInstrumentActor->getDetectorIDFromColor(qRed(pickedColor)*65536 + qGreen(pickedColor)*256 + qBlue(pickedColor));
-
-  //retrieve information about the selected detector
-  m_detInfo.setDet(iDetId);
-  //send this detector information off
-  emit actionDetectorHighlighted(m_detInfo);
-}
-/**
- * This method is the slot when the detector is highlighted using mouse move. This method emits
- * signals the id of the detector and the spectra index(not spectra number).
- * @param pickedActor :: the input passed by the the signal.
- */
-void Instrument3DWidget::detectorsHighligted(QRgb pickedColor)
-{
-  if (m_instrumentWindow->blocked())
-  {
-    return;
-  }
-  //get the data for the detector currently under the cursor
-  const int iDetId = mInstrumentActor->getDetectorIDFromColor(qRed(pickedColor)*65536 + qGreen(pickedColor)*256 + qBlue(pickedColor));
-
-  //retrieve information about the selected detector
-  m_detInfo.setEndRange(iDetId);
-  //send this detector information off
-  emit actionDetectorHighlighted(m_detInfo);
-}
-
-void Instrument3DWidget::fireDetectorHighligted(int detID)
-{
-  if (m_instrumentWindow->blocked())
-  {
-    return;
-  }
-  m_detInfo.setDet(detID);
-  emit actionDetectorHighlighted(m_detInfo);
-}
-//------------------------------------------------------------------------------------------------
-/**
- * This method sets the workspace name input to the widget.
- * @param wsName :: input workspace name
- */
-void Instrument3DWidget::setWorkspace(const QString& wsName)
-{
-  Timer timer;
-  makeCurrent();
-
-  MatrixWorkspace_sptr output = 
-    boost::dynamic_pointer_cast<MatrixWorkspace>(AnalysisDataService::Instance().retrieve(wsName.toStdString()));
-  if( !output )
-  {
-    QMessageBox::warning(this, "MantidPlot", QString("Error retrieving workspace \"") + 
-			 wsName + QString("\". Cannot render instrument"));
-    return;
-  }
-  // Save the workspace name
-  mWorkspaceName = wsName;
-  mWorkspace = output;
-  // Read the instrument geometry
-  boost::shared_ptr<Mantid::Geometry::IInstrument> ins = output->getInstrument();
-  this->ParseInstrumentGeometry(ins);
-  boost::shared_ptr<Mantid::Geometry::IObjComponent> sample = ins->getSample();
-  if( sample.get() )
-  {
-    _trackball->setModelCenter(sample->getPos());
-  }
-  else
-  {
-    _trackball->setModelCenter(Mantid::Geometry::V3D(0.0,0.0,0.0));
-  }
-  defaultProjection(); // Calculate and set projection
-
-  // Calculate bin values, data ranges and integrate data
-  calculateColorCounts(output, true);
-
-  if (SHOWTIMING) std::cout << "Instrument3DWidget::setWorkspace() took " << timer.elapsed() << " seconds\n";
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * This method parses the instrument information and creates the actors relating to the detectors.
- */
-void Instrument3DWidget::ParseInstrumentGeometry(boost::shared_ptr<Mantid::Geometry::IInstrument> ins)
-{
-  Timer timer;
-  makeCurrent();
-  boost::shared_ptr<GLActorCollection> scene = boost::shared_ptr<GLActorCollection>(new GLActorCollection);
-  mInstrumentActor = new InstrumentActor(ins, mFastRendering);
-  scene->addActor(mInstrumentActor);
-  this->setActorCollection(scene);
-  if (SHOWTIMING) std::cout << "Instrument3DWidget::ParseInstrumentGeometry() took " << timer.elapsed() << " seconds\n";
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * Calculate the minimum and maximum values of the bins for the set workspace
- */
-void Instrument3DWidget::calculateBinRange()
-{
-  Mantid::API::MatrixWorkspace_sptr workspace = mWorkspace;
-  Timer timer;
-
-  // Value has not been preset?
-  if (( std::fabs(mWkspBinMin - DBL_MAX)/DBL_MAX < 1e-08 ) && ( (mWkspBinMax + DBL_MAX)/DBL_MAX < 1e-08 ))
-  {
-    //Then we need to calculate
-    const int nHist = workspace->getNumberHistograms();
-    mWkspBinMin = DBL_MAX;
-    mWkspBinMax = -DBL_MAX;
-    for (int i = 0; i < nHist; ++i)
-    {
-      const Mantid::MantidVec & values = workspace->readX(i);
-      double xtest = values.front();
-      if( xtest != std::numeric_limits<double>::infinity() )
-      {
-
-        if( xtest < mWkspBinMin )
-        {
-          mWkspBinMin = xtest;
-        }
-        else if( xtest > mWkspBinMax )
-        {
-          mWkspBinMax = xtest;
-        }
-        else {}
-      }
-
-      xtest = values.back();
-      if( xtest != std::numeric_limits<double>::infinity() )
-      {
-        if( xtest < mWkspBinMin )
-        {
-          mWkspBinMin = xtest;
-        }
-        else if( xtest > mWkspBinMax )
-        {
-          mWkspBinMax = xtest;
-        }
-        else {}
-      }
-    }
-    if ( (std::fabs(mBinMinValue - DBL_MAX)/DBL_MAX < 1e-08) && 
-	 ( (mBinMaxValue + DBL_MAX)/DBL_MAX < 1e-08) )
-    {
-      mBinMinValue = mWkspBinMin;
-      mBinMaxValue = mWkspBinMax;
-    }
-  }
-
-  // Check validity
-  if( mBinMinValue < mWkspBinMin || mBinMinValue > mWkspBinMax )
-  {
-    mBinMinValue = mWkspBinMin;
-  }
-
-  if( mBinMaxValue > mWkspBinMax || mBinMaxValue < mWkspBinMin )
-  {
-    mBinMaxValue = mWkspBinMax;
-  }
-
-
-  if (SHOWTIMING) std::cout << "Instrument3DWidget::calculateBinRange() took " << timer.elapsed() << " seconds\n";
-
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * Integrate the workspace. This calculates the total counts
- * in all spectra and makes the color list for each pixel, using
- * the current color map.
- * @param workspace :: new workspace being set.
- * @param firstCalculation :: set to true when changing the workspace; false is simply changing the color scale
- *
- */
-void Instrument3DWidget::calculateColorCounts(boost::shared_ptr<Mantid::API::MatrixWorkspace> workspace, bool firstCalculation)
-{
-  Timer timer;
-  if( !workspace ) return;
-
-  // This looks like a strange way of doing this but the CompAssemblyActor needs the colours in the same
-  // order as it fills its detector lists!
-  if (detector_list.size() == 0)
-  {
-    Timer timerID;
-    //Only load the detector ID list once per instance
-    mInstrumentActor->getDetectorIDList(detector_list);
-    if (SHOWTIMING) std::cout << "Instrument3DWidget::calculateColorCounts(): mInstrumentActor->getDetectorIDList() took " << timerID.elapsed() << " seconds\n";
-  }
-
-  if( detector_list.empty() ) return;
-
-  //Make the workspace index list, and force a new one if needed.
-  createWorkspaceIndexList(detector_list, firstCalculation);
-
-
-  //TODO: Make this part in parallel if possible!
-
-  Timer timer2;
-
-  const int n_spec = m_workspace_indices.size();
-  std::vector<double> integrated_values( n_spec, -1.0 );
-
-  //Use the workspace function to get the integrated spectra
-  mWorkspace->getIntegratedSpectra(m_specIntegrs, (this->mBinMinValue), (this->mBinMaxValue), (this->mBinEntireRange));
-
-  mWkspDataMin = DBL_MAX;
-  mWkspDataMax = -DBL_MAX;
-
-  //Now we need to convert to a vector where each entry is the sum for the detector ID at that spot (in integrated_values).
-  for (int i=0; i < n_spec; i++)
-  {
-    int widx = m_workspace_indices[i];
-    if( widx != -1 )
-    {
-      double sum = m_specIntegrs[widx];
-      integrated_values[i] = sum;
-        if( sum < mWkspDataMin )
-          mWkspDataMin = sum;
-        else if( sum > mWkspDataMax )
-          mWkspDataMax = sum;
-    }
-  }
-
-
-  if (SHOWTIMING) std::cout << "Instrument3DWidget::calculateColorCounts():Integrating workspace took " << timer2.elapsed() << " seconds\n";
-
-  // No preset value
-  if( mDataMinEdited == false )
-  {
-    mDataMinValue = mWkspDataMin;
-  }
-
-  if( mDataMaxEdited == false )
-  {
-    mDataMaxValue = mWkspDataMax;
-  }
-
-  Timer timerColLists;
-
-  const short max_ncols = mColorMap.getLargestAllowedCIndex() + 1;
-  mScaledValues = std::vector<unsigned char>(n_spec, 0);
-  std::vector<boost::shared_ptr<GLColor> > colorlist(n_spec);
-  QwtDoubleInterval wksp_interval(mWkspDataMin, mWkspDataMax);
-  QwtDoubleInterval user_interval(mDataMinValue, mDataMaxValue);
-
-  std::vector<double>::iterator val_end = integrated_values.end();
-  int idx(0);
-  for( std::vector<double>::iterator val_itr = integrated_values.begin(); val_itr != val_end;
-      ++val_itr, ++idx )
-  {
-    unsigned char c_index(mColorMap.getTopCIndex());
-    if( (*val_itr) < 0.0 )
-    {
-      mScaledValues[idx] = mColorMap.getLargestAllowedCIndex();
-    }
-    else
-    {
-      // Index to store
-      short index = std::floor( mColorMap.normalize(user_interval, *val_itr)*max_ncols );
-      if( index >= max_ncols )
-      {
-        index = max_ncols;
-      }
-      else if( index < 0 )
-      {
-        index = 0;
-      }
-      else {}
-      mScaledValues[idx] = static_cast<unsigned char>(index);
-      c_index = mColorMap.colorIndex(user_interval, *val_itr);
-
-    }
-    colorlist[idx] = mColorMap.getColor(c_index);
-  }
-  if (SHOWTIMING) std::cout << "Instrument3DWidget::calculateColorCounts(): making the colorlist took " << timerColLists.elapsed() << " seconds\n";
-
-  Timer timerCols;
-  mInstrumentActor->setDetectorColors(colorlist);
-  if (SHOWTIMING) std::cout << "Instrument3DWidget::calculateColorCounts(): mInstrumentActor->setDetectorColors() took " << timerCols.elapsed() << " seconds\n";
-
-  if (SHOWTIMING) std::cout << "Instrument3DWidget::calculateColorCounts() took " << timer.elapsed() << " seconds\n";
-}
-//------------------------------------------------------------------------------------------------
-/**
- * Run a recount for the current workspace
- */
-void Instrument3DWidget::recount()
-{
-  calculateColorCounts(mWorkspace, false);
-  mInstrumentActor->refresh();
-  redrawUnwrapped();
-  update();
-}
-
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * For a change in the colour map, just update the color indices.
- */
-void Instrument3DWidget::updateColorsForNewMap()
-{
-  Timer timer;
-
-  const short max_ncols = mColorMap.getLargestAllowedCIndex() + 1;
-  const short ncols = mColorMap.getTopCIndex() + 1;
-
-  //Create a list of GLColor objects for every spectrum in the workspace
-  std::vector<boost::shared_ptr<GLColor> > colorlist(mScaledValues.size());
-  if( max_ncols == ncols )
-  {
-    std::vector<unsigned char>::const_iterator val_end = mScaledValues.end();
-    int idx(0);
-    for( std::vector<unsigned char>::const_iterator val_itr = mScaledValues.begin();
-        val_itr != val_end; ++val_itr, ++idx )
-    {
-      colorlist[idx] = mColorMap.getColor(*val_itr);
-    }
-  }
-  else
-  {
-    std::vector<unsigned char>::const_iterator val_end = mScaledValues.end();
-    int idx(0);
-    const double ratio = (double)ncols / max_ncols;
-    for( std::vector<unsigned char>::const_iterator val_itr = mScaledValues.begin();
-        val_itr != val_end; ++val_itr, ++idx )
-    {
-      short cache_value = static_cast<short>(*val_itr);
-      short c_index = std::ceil((cache_value + 1)*ratio);
-      if( c_index <= 0 ) c_index = 1;
-      else if( c_index > ncols) c_index = ncols;
-      else {}
-      colorlist[idx] = mColorMap.getColor(static_cast<unsigned char>(c_index - 1));
-    }
-  }
-
-  mInstrumentActor->setDetectorColors(colorlist);
-  mInstrumentActor->refresh();
-  update();
-
-  if (SHOWTIMING) std::cout << "Instrument3DWidget::updateColorsForNewMap() took " << timer.elapsed() << " seconds\n";
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * Update the colors based on a change in the maximum data value
- */
-void Instrument3DWidget::setMaxData(const double new_max)
-{
-  mDataMaxValue = new_max;
-  setDataMaxEdited(true);
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * Update the colors based on a change in the minimum data value
- */
-void Instrument3DWidget::setMinData(const double new_min)
-{
-  mDataMinValue = new_min;
-  setDataMinEdited(true);
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * Mark the min data as bein user edited
- * @param If :: true the data min value has been set by the user
- */
-void Instrument3DWidget::setDataMinEdited(bool state)
-{
-  mDataMinEdited = state;
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * Mark the min data as bein user edited
- * @param If :: true the data max value has been set by the user
- */
-void Instrument3DWidget::setDataMaxEdited(bool state)
-{
-  mDataMaxEdited = state;
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * This method returns the workspace index list for the input dectector id list:
- *  i.e. the detector at index i of det_ids has a spectrum at workspace index given in
- *      m_workspace_indices[i].
- *
- * @param det_ids :: is list of detector id's
- * @param forceNew :: set to true to force the creation of a new list; otherwise, the old one will be reused
- * if possible.
- */
-void Instrument3DWidget::createWorkspaceIndexList(const std::vector<int> & det_ids, bool forceNew)
-{
-  Timer timer;
-
-  if( det_ids.empty() ) return;
-  if (!forceNew)
-  {
-    //Don't force a new one, and the sizes match. We assume it is good.
-    if (m_workspace_indices.size() == det_ids.size())
-      return;
-  }
-  m_workspace_indices.resize(det_ids.size());
-  m_detector_ids = det_ids;
-
-  //the DetInfo object will collect information about selected detectors from the pointers and references passed
-  m_detInfo = DetInfo(mWorkspace, &m_specIntegrs);
-
-  //the DetInfo object can convert from detector IDs to spectra indices and so this creates a vector of spectra indices
-  std::transform(m_detector_ids.begin(), m_detector_ids.end(),
-                 m_workspace_indices.begin(), m_detInfo);
-  /*
-  std::vector<int>::const_iterator detIDsIn = m_detector_ids.begin();
-  std::vector<int>::iterator specIndsOut = m_workspace_indices.begin();
-  std::vector<int>::const_iterator end = m_detector_ids.end();
-  for( ; detIDsIn != end; ++detIDsIn, ++specIndsOut)
-  {
-    *specIndsOut = m_detInfo.getIndexOf(*detIDsIn);
-  }*/
-
-  if (SHOWTIMING) std::cout << "Instrument3DWidget::createWorkspaceIndexList() took " << timer.elapsed() << " seconds\n";
-
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * This method sets the Time bin values. the value has to be greater than zero
- * @param value :: input is the time bin value
- */
-void Instrument3DWidget::setTimeBin(int value)
-{
-  if(value>0)
-  {
-    this->iTimeBin=value;
-  }
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * Returns workspace name
- */
-QString Instrument3DWidget::getWorkspaceName() const
-{
-  return mWorkspaceName;
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * Returns a reference to the constant colormap
- */
-const MantidColorMap & Instrument3DWidget::getColorMap() const
-{
-  return mColorMap;
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * Returns a reference to the colormap
- */
-MantidColorMap & Instrument3DWidget::mutableColorMap()
-{
-  return mColorMap;
-}
-
-
-/**
- * This method takes the input name as the min value Colormap scale.
- */
-void Instrument3DWidget::setColorMapMinValue(double minValue)
-{
-	this->mDataMinValue=minValue;
-}
-
-/**
- * This method takes the input name as the min value Colormap scale.
- */
-void Instrument3DWidget::setColorMapMaxValue(double maxValue)
-{
-	this->mDataMaxValue = maxValue;
-}
-
-/**
- * This method returns min value. by default will be min value in the current timebin
- */
-double Instrument3DWidget::getDataMinValue() const
-{
-	return this->mDataMinValue;
-}
-
-/**
- * This method returns the max value. by default will be max value in the current timebin
- */
-double Instrument3DWidget::getDataMaxValue() const
-{
-	return this->mDataMaxValue;
-}
-
-/** Returns the current minimum bin value
- */
-double Instrument3DWidget::getBinMinValue() const
-{
-  return this->mBinMinValue;
-}
-
-/** Returns the current maximum bin value
- */
-double Instrument3DWidget::getBinMaxValue() const
-{
-    return this->mBinMaxValue;
-}
-
-/** Returns the current value for integrating all the bins (entire range)
- */
-bool Instrument3DWidget::getBinEntireRange() const
-{
-    return this->mBinEntireRange;
-}
-
-/**
- * This method sets the Data mapping type for the color mapping.
- */
-void Instrument3DWidget::setDataMappingType(DataMappingType dmType)
-{
-	mDataMapping=dmType;
-}
-
-void Instrument3DWidget::setDataMappingIntegral(double minValue,double maxValue, bool entireRange)
-{
-  this->mBinMinValue = minValue;
-  this->mBinMaxValue = maxValue;
-  this->mBinEntireRange = entireRange;
-  setDataMappingType(INTEGRAL);
-  if( this->isVisible() )
-  {
-    calculateColorCounts(mWorkspace, false);
-    mInstrumentActor->refresh();
-    update();
-  }
-}
-
-void Instrument3DWidget::setDataMappingSingleBin(int binNumber)
-{
-  this->iTimeBin=binNumber;
-  setDataMappingType(SINGLE_BIN);
-}
-
-/**
- * Sets the default view to X direction positive
- */
-void Instrument3DWidget::setViewDirectionXPositive()
-{
-	setViewDirection(XPOSITIVE);
-}
-
-/**
- * Sets the default view to Y direction positive
- */
-void Instrument3DWidget::setViewDirectionYPositive()
-{
-	setViewDirection(YPOSITIVE);
-}
-
-/**
- * Sets the default view to Z direction positive
- */
-void Instrument3DWidget::setViewDirectionZPositive()
-{
-	setViewDirection(ZPOSITIVE);
-}
-
-/**
- * Sets the default view to X direction negative
- */
-void Instrument3DWidget::setViewDirectionXNegative()
-{
-	setViewDirection(XNEGATIVE);
-}
-
-/**
- * Sets the default view to Y direction negative
- */
-void Instrument3DWidget::setViewDirectionYNegative()
-{
-	setViewDirection(YNEGATIVE);
-}
-
-/**
- * Sets the default view to Z direction negative
- */
-void Instrument3DWidget::setViewDirectionZNegative()
-{
-	setViewDirection(ZNEGATIVE);
-}
-
-/**
- * Sets the slow rendering not using display list
- * NOTE: This method will ***NOT*** have any effect after the workspace name is set.
- */
-void Instrument3DWidget::setSlowRendering()
-{
-	mFastRendering=false;
-}
-
-/**
- * Sets the fast rendering using display list
- * NOTE: This method will ***NOT*** have any effect after the workspace name is set.
- */
-void Instrument3DWidget::setFastRendering()
-{
-	mFastRendering=true;
-}
-
-
-/**
- * Completely resets the data in the instrument widget. ready for new workspace
- */
-void Instrument3DWidget::resetWidget()
-{
-	iTimeBin = 0;
-	mWorkspaceName = QString();
-	mBinMinValue = DBL_MAX;
-	mBinMaxValue = -DBL_MAX;
-	mDataMinValue = DBL_MAX;
-	mDataMaxValue = -DBL_MAX;
-	mDataMinEdited = false;
-	mDataMaxEdited = false;
-	mDataMapping = INTEGRAL;
-	mAxisDirection = Mantid::Geometry::V3D(0.0,0.0,1.0);
-	mAxisUpVector = Mantid::Geometry::V3D(0.0,1.0,0.0);
-	mScaledValues.clear();
-	GL3DWidget::resetWidget();
-}
-
-void Instrument3DWidget::setView(const V3D& pos,double xmax,double ymax,double zmax,double xmin,double ymin,double zmin)
-{
-	//Change the View to the axis orientation
-	V3D s=mAxisDirection.cross_prod(mAxisUpVector);
-	V3D u=s.cross_prod(mAxisDirection);
-	double Mat[16];
-	Mat[0]=s[0];              Mat[4]=s[1];              Mat[8]=s[2];               Mat[12]=0;
-	Mat[1]=u[0];              Mat[5]=u[1];              Mat[9]=u[2];               Mat[13]=0;
-	Mat[2]=-mAxisDirection[0];Mat[6]=-mAxisDirection[1];Mat[10]=-mAxisDirection[2];Mat[14]=0;
-	Mat[3]=0;                 Mat[7]=0;                 Mat[11]=0;                 Mat[15]=1;
-	Quat defaultView;
-	defaultView.setQuat(Mat);
-	defaultView.normalize();
-	//get the rotation to make the center of the bounding box to the view
-	V3D boundCentre;
-	boundCentre[0]=(xmax+xmin)/2.0;
-	boundCentre[1]=(ymax+ymin)/2.0;
-	boundCentre[2]=(zmax+zmin)/2.0;
-	V3D vcb=boundCentre-pos;
-	vcb.normalize();
-	V3D zaxis(0,0,1);
-	Quat rotation(zaxis,vcb);
-	rotation.inverse();
-	if(rotation!=Quat(0,0,0,0))
-		defaultView=rotation*defaultView;
-	_trackball->reset();
-	_trackball->setModelCenter(pos);
-	if(defaultView!=Quat(0,0,0,0))
-		_trackball->setRotation(defaultView);
-	_trackball->rotateBoundingBox(xmin,xmax,ymin,ymax,zmin,zmax);//rotate the bounding box
-        _viewport->setOrtho(xmin,xmax,ymin,ymax,-zmax,-zmin,false);
-	_viewport->issueGL();
-	update();
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * This method draws the scene using color id. this method is called in pick mode
- */
-void Instrument3DWidget::drawSceneUsingColorID()
-{
-	mInstrumentActor->drawUsingColorID();
-}
-
-/**
- * Draws the scene in low resolution. this method is called in interactive mode for faster response
- */
-void Instrument3DWidget::setSceneLowResolution()
-{
-	mInstrumentActor->setObjectResolutionToLow();
-}
-
-/**
- * Draws the scene in high resolution.
- */
-void Instrument3DWidget::setSceneHighResolution()
-{
-	mInstrumentActor->setObjectResolutionToHigh();
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * Returns the boundig box of the scene
- * @param minBound :: output min point of the bounding box of scene
- * @param maxBound :: output max point of the bounding box of scene
- */
-void Instrument3DWidget::getBoundingBox(Mantid::Geometry::V3D& minBound, Mantid::Geometry::V3D& maxBound)
-{
-	mInstrumentActor->getBoundingBox(minBound,maxBound);
-}
-
-/** Set pointers to the workspace data that is needed to obtain information about
-*  detectors
-*  @param DetID :: id number of the detector to retrieve information for
-*  @param workspace :: the workspace with counts data for the detector
-*  @param counts :: integral of the number of counts in each spectrum
-*  @throw runtime_error if there was an error creating the spectra index to detector index map
-*/
-Instrument3DWidget::DetInfo::DetInfo(Mantid::API::MatrixWorkspace_const_sptr workspace, const std::vector<double> * const counts) :
-    m_workspace(workspace),
-    m_integrals(counts),
-    m_firstDet(ERROR_FLAG), m_lastDet(ERROR_FLAG)
-{
-  if (m_workspace)
-  {
-    m_detID_to_wi_map = boost::shared_ptr<const IndexToIndexMap>(
-        m_workspace->getDetectorIDToWorkspaceIndexMap(false));
-  }
-}
-/// set the object to contain data for only one detector
-void Instrument3DWidget::DetInfo::setDet(const int detID)
-{
-  m_firstDet = detID;
-  m_lastDet = NO_INDEX;
-}
-/** specify a range of detectors by giving the id of a detector at the end of the range
-*  @param detID :: id number of detector to add
-*/
-void Instrument3DWidget::DetInfo::setEndRange(const int detID)
-{
-  if (is_good(detID))
-  {
-    m_lastDet = detID;
-  }
-  else
-  {
-    m_lastDet = m_firstDet = ERROR_FLAG;
-  }
-}
-/** Returns a string containing all this object's data in a human readable
-* form
-* @return all this objects data labeled and formated for user display
-*/
-QString Instrument3DWidget::DetInfo::display() const
-{
-  std::ostringstream out;
-  out << "Detector ID:  " << m_firstDet;
-
-  if (is_good(m_firstDet))
-  {
-    printSpectrum(getIndexOf(m_firstDet), out);
-    out << std::endl;
-    printLocation(out);
-  }
-  else
-  {// reserve a fixed width for displaying any data
-    out << std::endl;
-  }
-
-  return QString::fromStdString(out.str());
-}
-
-int Instrument3DWidget::DetInfo::getWorkspaceIndex()const
-{
-  return is_good(m_firstDet) ? getIndexOf(m_firstDet) : -1;
-}
-
-/** Writes the information about the spectrum whose index is passed to it
-*  in a human readble form to the stream provide, or nothing on error
-*  @param[in] index the index number of the spectrum to display
-*  @param[out] output information will be writen to this stream
-*/
-void Instrument3DWidget::DetInfo::printSpectrum(const int index, std::ostringstream & output) const
-{
-  if (is_good(index))
-  {
-    int spectrumNumber(NO_INDEX);
-    try
-    {
-      spectrumNumber = m_workspace->getAxis(1)->spectraNo(index);
-    }
-    catch (...)
-    {
-      //if some information couldn't be retrieved, default values will be displayed
-    }
-
-    if (index != spectrumNumber && is_good(spectrumNumber) )
-      output << "    Spectrum number: " << spectrumNumber << "  workspace index: " << index;
-    else
-      output << "    Spectrum number: " << spectrumNumber;
-    output << "    Count:  ";
-
-    if (m_integrals)
-    {
-      output << m_integrals->operator[](index);
-    }
-    else
-    {
-      output << "-";
-    }
-  }
-}
-/** Writes the location of any detectors whose information is retrievable
-*  in a human readable form
-*  @param[out] output information will be writen to this stream
-*/
-void Instrument3DWidget::DetInfo::printLocation(std::ostringstream & output) const
-{
-  // display location information for the detector, ignoring missing detectors
-  std::string units("");
-  try
-  {
-    IDetector_const_sptr locInfo =
-      m_workspace->getInstrument()->getDetector(m_firstDet);
-    V3D pos = locInfo->getPos();
-    output << "position:  ";
-    printV(pos, output);
-    units = " m";
-
-    locInfo = m_workspace->getInstrument()->getDetector(m_lastDet);
-    V3D endPos = locInfo->getPos();
-    output << " -> ";
-    printV(endPos, output);
-    output << " = ";
-    printV(pos-endPos, output);
-  }
-  catch(Exception::NotFoundError &)
-  {
-    //don't display data when there is an error retreiving it
-  }
-  output << units;
-}
-/** Writes a position vector in a nice way
-*  @param[in] pos coordinates to print
-*  @param[out] output information will be writen to this stream
-*/
-void Instrument3DWidget::DetInfo::printV(Mantid::Geometry::V3D pos, std::ostringstream & out) const
-{
-  out << "(" << pos.X() << "," << pos.Y() << "," << pos.Z() << ")";
-}
-/** Returns the index number of the spectrum generated by the detector whose ID number
-*  was passed or DetInfo::NO_INDEX on error
-*  @param someDetID :: an ID of a detector that exists in the workspace
-*  @return the index number of the spectrum associated with that detector or -1
-*/
-int Instrument3DWidget::DetInfo::getIndexOf(const int someDetID) const
-{
-  IndexToIndexMap::const_iterator it(m_detID_to_wi_map->find(someDetID));
-  if ( it != m_detID_to_wi_map->end() )
-  {
-    return it->second;
-  }
-  else return NO_INDEX;
-}
-
-void Instrument3DWidget::showUnwrappedContextMenu()
-{
-  QMenu context(this);
-
-  context.addAction(m_ExtractDetsToWorkspaceAction);
-  context.addAction(m_SumDetsToWorkspaceAction);
-  QMenu *gfileMenu = context.addMenu("Create grouping file");
-  gfileMenu->addAction(m_createIncludeGroupingFileAction);
-  gfileMenu->addAction(m_createExcludeGroupingFileAction);
-
-  context.exec(QCursor::pos());
-}
-
-void Instrument3DWidget::showInfo()
-{
-  if (!m_unwrappedSurface) return;
-
-  QSet<int> dets;
-  m_unwrappedSurface->getPickedDetector(dets);
-
-  QString msg;
-  if (dets.size() == 0) return;
-  else if (dets.size() == 1)
-  {
-    msg = "Detector ID " + QString::number(*dets.begin());
-  }
-  else
-  {
-    msg = "Selected " + QString::number(dets.size()) + " detectors";
-  }
-  QMessageBox::information(this,"MantidPlot",msg);
-}
-
-/**
-  * Extract selected detectors to a new workspace
-  */
-void Instrument3DWidget::extractDetsToWorkspace()
-{
-  if (!m_unwrappedSurface) return;
-  QSet<int> dets;
-  m_unwrappedSurface->getPickedDetector(dets);
-
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-  DetXMLFile mapFile(dets);
-  std::string fname = mapFile();
-
-  if (!fname.empty())
-  {
-    Mantid::API::IAlgorithm* alg = Mantid::API::FrameworkManager::Instance().createAlgorithm("GroupDetectors");
-    alg->setPropertyValue("InputWorkspace",getWorkspaceName().toStdString());
-    alg->setPropertyValue("MapFile",fname);
-    alg->setPropertyValue("OutputWorkspace",getWorkspaceName().toStdString()+"_selection");
-    alg->execute();
-  }
-
-  QApplication::restoreOverrideCursor();
-}
-
-/**
-  * Sum selected detectors to a new workspace
-  */
-void Instrument3DWidget::sumDetsToWorkspace()
-{
-  if (!m_unwrappedSurface) return;
-  QSet<int> dets;
-  m_unwrappedSurface->getPickedDetector(dets);
-
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-  DetXMLFile mapFile(dets,DetXMLFile::Sum);
-  std::string fname = mapFile();
-
-  if (!fname.empty())
-  {
-    Mantid::API::IAlgorithm* alg = Mantid::API::FrameworkManager::Instance().createAlgorithm("GroupDetectors");
-    alg->setPropertyValue("InputWorkspace",getWorkspaceName().toStdString());
-    alg->setPropertyValue("MapFile",fname);
-    alg->setPropertyValue("OutputWorkspace",getWorkspaceName().toStdString()+"_sum");
-    alg->execute();
-  }
-
-  QApplication::restoreOverrideCursor();
-}
-
-void Instrument3DWidget::createIncludeGroupingFile()
-{
-  if (!m_unwrappedSurface) return;
-  QSet<int> dets;
-  m_unwrappedSurface->getPickedDetector(dets);
-
-  QString fname = QFileDialog::getSaveFileName(this,"Save grouping file");
-  if (!fname.isEmpty())
-  {
-    DetXMLFile mapFile(dets,DetXMLFile::Sum,fname);
-  }
-
-}
-
-void Instrument3DWidget::createExcludeGroupingFile()
-{
-  if (!m_unwrappedSurface) return;
-  QSet<int> dets;
-  m_unwrappedSurface->getPickedDetector(dets);
-
-  QString fname = QFileDialog::getSaveFileName(this,"Save grouping file");
-  if (!fname.isEmpty())
-  {
-    DetXMLFile mapFile(detector_list,dets,fname);
-  }
-}
-
+#include "Instrument3DWidget.h"
+#include "InstrumentActor.h"
+#include "InstrumentWindow.h"
+#include "MantidObject.h"
+#include "OpenGLError.h"
+#include "UnwrappedSurface.h"
+
+#include "MantidAPI/AnalysisDataService.h"
+#include "MantidAPI/MatrixWorkspace.h"
+#include "MantidAPI/Axis.h"
+#include "MantidAPI/SpectraDetectorMap.h"
+#include "MantidAPI/FrameworkManager.h"
+#include "MantidAPI/Algorithm.h"
+
+#include "MantidKernel/Exception.h"
+#include "MantidKernel/Timer.h"
+
+#include "MantidGeometry/Math/Matrix.h"
+#include "MantidGeometry/V3D.h"
+#include "MantidGeometry/IInstrument.h"
+#include "MantidGeometry/IComponent.h"
+#include "MantidGeometry/IObjComponent.h"
+#include "MantidGeometry/ICompAssembly.h"
+#include "MantidGeometry/Objects/Object.h"
+#include "MantidGeometry/Rendering/GeometryHandler.h"
+
+#include <QTimer>
+#include <QMessageBox>
+#include <QString>
+#include <QMenu>
+#include <QAction>
+#include <QSet>
+#include <QTemporaryFile>
+#include <QDir>
+#include <QApplication>
+#include <QFileDialog>
+
+#include <map>
+#include <cmath>
+#include <cfloat>
+#include <numeric>
+#include <fstream>
+
+using namespace Mantid::API;
+using namespace Mantid::Kernel;
+using namespace Mantid::Geometry;
+
+static const bool SHOWTIMING = false;
+
+/** A class for creating grouping xml files
+  */
+class DetXMLFile//: public DetectorCallback
+{
+public:
+  enum Option {List,Sum};
+  /// Create a grouping file to extract all detectors in detector_list excluding those in dets
+  DetXMLFile(const std::vector<int> detector_list, const QSet<int>& dets, 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 (!dets.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(const QSet<int>& dets, Option opt = List, const QString& fname = "")
+  {
+    if (dets.empty())
+    {
+      m_fileName = "";
+      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;
+    }
+
+    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 makeListFile(const QSet<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 makeSumFile(const QSet<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";
+  }
+
+  ~DetXMLFile()
+  {
+    if (m_delete)
+    {
+      QDir dir;
+      dir.remove(m_fileName);
+    }
+  }
+
+  /// 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
+};
+
+Instrument3DWidget::Instrument3DWidget(InstrumentWindow* parent):
+  GL3DWidget(parent),m_instrumentWindow(parent),mFastRendering(true), iTimeBin(0), mDataMapping(INTEGRAL),
+  mColorMap(), mInstrumentActor(NULL), mAxisDirection(Mantid::Geometry::V3D(0.0,0.0,1.0)),
+  mAxisUpVector(Mantid::Geometry::V3D(0.0,1.0,0.0)), mDataMinValue(DBL_MAX), mDataMaxValue(-DBL_MAX),
+  mBinMinValue(DBL_MAX), mBinMaxValue(-DBL_MAX),
+  mBinEntireRange(true),
+  mDataMinEdited(false), mDataMaxEdited(false),
+  mWkspDataMin(DBL_MAX), mWkspDataMax(-DBL_MAX), mWkspBinMin(DBL_MAX), mWkspBinMax(-DBL_MAX), 
+  mWorkspaceName(""), mWorkspace(), mScaledValues(0)
+{
+  connect(this, SIGNAL(actorsPicked(const std::set<QRgb>&)), this, SLOT(fireDetectorsPicked(const std::set<QRgb>&)));
+  connect(this, SIGNAL(actorHighlighted(QRgb)),this,SLOT(fireDetectorHighligted(QRgb)));
+  connect(this, SIGNAL(actorHighlighted(int)),this,SLOT(fireDetectorHighligted(int)));
+  connect(this, SIGNAL(increaseSelection(QRgb)),this,SLOT(detectorsHighligted(QRgb)));
+
+  m_ExtractDetsToWorkspaceAction = new QAction("Extract to new workspace",this);
+  connect(m_ExtractDetsToWorkspaceAction,SIGNAL(activated()),this,SLOT(extractDetsToWorkspace()));
+
+  m_SumDetsToWorkspaceAction = new QAction("Sum to new workspace",this);
+  connect(m_SumDetsToWorkspaceAction,SIGNAL(activated()),this,SLOT(sumDetsToWorkspace()));
+
+  m_createIncludeGroupingFileAction = new QAction("Include",this);
+  connect(m_createIncludeGroupingFileAction,SIGNAL(activated()),this,SLOT(createIncludeGroupingFile()));
+
+  m_createExcludeGroupingFileAction = new QAction("Exclude",this);
+  connect(m_createExcludeGroupingFileAction,SIGNAL(activated()),this,SLOT(createExcludeGroupingFile()));
+}
+
+Instrument3DWidget::~Instrument3DWidget()
+{
+  makeCurrent();
+}
+
+/**
+ * Set the default Axis direction of the model
+ */
+void Instrument3DWidget::setAxis(const Mantid::Geometry::V3D& direction)
+{
+	mAxisDirection = direction;
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * This method is the slot when the detectors are picked using mouse. This method emits
+ * signals the ids of the detector and the spectra index(not spectra number).
+ * @param pickedActor :: the input passed by the the signal.
+ */
+void Instrument3DWidget::fireDetectorsPicked(const std::set<QRgb>& pickedColors)
+{
+  if (m_instrumentWindow->blocked())
+  {
+    return;
+  }
+  std::vector<int> detectorIds;
+  detectorIds.reserve(pickedColors.size());
+  for(std::set<QRgb>::const_iterator it = pickedColors.begin(); it!= pickedColors.end(); it++)
+  {
+    int iDecId = mInstrumentActor->getDetectorIDFromColor(qRed((*it))*65536+qGreen((*it))*256+qBlue((*it)));
+    if(iDecId != -1)
+    {
+      detectorIds.push_back(iDecId);
+    }
+  }
+  if( detectorIds.empty() ) return;
+
+  // fill in m_detector_ids and m_workspace_indices with the selected detector ids
+  createWorkspaceIndexList(detectorIds, true);
+
+  emit detectorsSelected();
+}
+//------------------------------------------------------------------------------------------------
+/**
+ * This method is the slot when the detector is highlighted using mouse move. This method emits
+ * signals the id of the detector and the spectra index(not spectra number).
+ * @param pickedActor :: the input passed by the the signal.
+ */
+void Instrument3DWidget::fireDetectorHighligted(QRgb pickedColor)
+{
+  if (m_instrumentWindow->blocked())
+  {
+    return;
+  }
+  //get the data for the detector currently under the cursor
+  const int iDetId = mInstrumentActor->getDetectorIDFromColor(qRed(pickedColor)*65536 + qGreen(pickedColor)*256 + qBlue(pickedColor));
+
+  //retrieve information about the selected detector
+  m_detInfo.setDet(iDetId);
+  //send this detector information off
+  emit actionDetectorHighlighted(m_detInfo);
+}
+/**
+ * This method is the slot when the detector is highlighted using mouse move. This method emits
+ * signals the id of the detector and the spectra index(not spectra number).
+ * @param pickedActor :: the input passed by the the signal.
+ */
+void Instrument3DWidget::detectorsHighligted(QRgb pickedColor)
+{
+  if (m_instrumentWindow->blocked())
+  {
+    return;
+  }
+  //get the data for the detector currently under the cursor
+  const int iDetId = mInstrumentActor->getDetectorIDFromColor(qRed(pickedColor)*65536 + qGreen(pickedColor)*256 + qBlue(pickedColor));
+
+  //retrieve information about the selected detector
+  m_detInfo.setEndRange(iDetId);
+  //send this detector information off
+  emit actionDetectorHighlighted(m_detInfo);
+}
+
+void Instrument3DWidget::fireDetectorHighligted(int detID)
+{
+  if (m_instrumentWindow->blocked())
+  {
+    return;
+  }
+  m_detInfo.setDet(detID);
+  emit actionDetectorHighlighted(m_detInfo);
+}
+//------------------------------------------------------------------------------------------------
+/**
+ * This method sets the workspace name input to the widget.
+ * @param wsName :: input workspace name
+ */
+void Instrument3DWidget::setWorkspace(const QString& wsName)
+{
+  Timer timer;
+  makeCurrent();
+
+  MatrixWorkspace_sptr output = 
+    boost::dynamic_pointer_cast<MatrixWorkspace>(AnalysisDataService::Instance().retrieve(wsName.toStdString()));
+  if( !output )
+  {
+    QMessageBox::warning(this, "MantidPlot", QString("Error retrieving workspace \"") + 
+			 wsName + QString("\". Cannot render instrument"));
+    return;
+  }
+  // Save the workspace name
+  mWorkspaceName = wsName;
+  mWorkspace = output;
+  // Read the instrument geometry
+  boost::shared_ptr<Mantid::Geometry::IInstrument> ins = output->getInstrument();
+  this->ParseInstrumentGeometry(ins);
+  boost::shared_ptr<Mantid::Geometry::IObjComponent> sample = ins->getSample();
+  if( sample.get() )
+  {
+    _trackball->setModelCenter(sample->getPos());
+  }
+  else
+  {
+    _trackball->setModelCenter(Mantid::Geometry::V3D(0.0,0.0,0.0));
+  }
+  defaultProjection(); // Calculate and set projection
+
+  // Calculate bin values, data ranges and integrate data
+  calculateColorCounts(output, true);
+
+  if (SHOWTIMING) std::cout << "Instrument3DWidget::setWorkspace() took " << timer.elapsed() << " seconds\n";
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * This method parses the instrument information and creates the actors relating to the detectors.
+ */
+void Instrument3DWidget::ParseInstrumentGeometry(boost::shared_ptr<Mantid::Geometry::IInstrument> ins)
+{
+  Timer timer;
+  makeCurrent();
+  boost::shared_ptr<GLActorCollection> scene = boost::shared_ptr<GLActorCollection>(new GLActorCollection);
+  mInstrumentActor = new InstrumentActor(ins, mFastRendering);
+  scene->addActor(mInstrumentActor);
+  this->setActorCollection(scene);
+  if (SHOWTIMING) std::cout << "Instrument3DWidget::ParseInstrumentGeometry() took " << timer.elapsed() << " seconds\n";
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Calculate the minimum and maximum values of the bins for the set workspace
+ */
+void Instrument3DWidget::calculateBinRange()
+{
+  Mantid::API::MatrixWorkspace_sptr workspace = mWorkspace;
+  Timer timer;
+
+  // Value has not been preset?
+  if (( std::fabs(mWkspBinMin - DBL_MAX)/DBL_MAX < 1e-08 ) && ( (mWkspBinMax + DBL_MAX)/DBL_MAX < 1e-08 ))
+  {
+    //Then we need to calculate
+    const int nHist = workspace->getNumberHistograms();
+    mWkspBinMin = DBL_MAX;
+    mWkspBinMax = -DBL_MAX;
+    for (int i = 0; i < nHist; ++i)
+    {
+      const Mantid::MantidVec & values = workspace->readX(i);
+      double xtest = values.front();
+      if( xtest != std::numeric_limits<double>::infinity() )
+      {
+
+        if( xtest < mWkspBinMin )
+        {
+          mWkspBinMin = xtest;
+        }
+        else if( xtest > mWkspBinMax )
+        {
+          mWkspBinMax = xtest;
+        }
+        else {}
+      }
+
+      xtest = values.back();
+      if( xtest != std::numeric_limits<double>::infinity() )
+      {
+        if( xtest < mWkspBinMin )
+        {
+          mWkspBinMin = xtest;
+        }
+        else if( xtest > mWkspBinMax )
+        {
+          mWkspBinMax = xtest;
+        }
+        else {}
+      }
+    }
+    if ( (std::fabs(mBinMinValue - DBL_MAX)/DBL_MAX < 1e-08) && 
+	 ( (mBinMaxValue + DBL_MAX)/DBL_MAX < 1e-08) )
+    {
+      mBinMinValue = mWkspBinMin;
+      mBinMaxValue = mWkspBinMax;
+    }
+  }
+
+  // Check validity
+  if( mBinMinValue < mWkspBinMin || mBinMinValue > mWkspBinMax )
+  {
+    mBinMinValue = mWkspBinMin;
+  }
+
+  if( mBinMaxValue > mWkspBinMax || mBinMaxValue < mWkspBinMin )
+  {
+    mBinMaxValue = mWkspBinMax;
+  }
+
+
+  if (SHOWTIMING) std::cout << "Instrument3DWidget::calculateBinRange() took " << timer.elapsed() << " seconds\n";
+
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Integrate the workspace. This calculates the total counts
+ * in all spectra and makes the color list for each pixel, using
+ * the current color map.
+ * @param workspace :: new workspace being set.
+ * @param firstCalculation :: set to true when changing the workspace; false is simply changing the color scale
+ *
+ */
+void Instrument3DWidget::calculateColorCounts(boost::shared_ptr<Mantid::API::MatrixWorkspace> workspace, bool firstCalculation)
+{
+  Timer timer;
+  if( !workspace ) return;
+
+  // This looks like a strange way of doing this but the CompAssemblyActor needs the colours in the same
+  // order as it fills its detector lists!
+  if (detector_list.size() == 0)
+  {
+    Timer timerID;
+    //Only load the detector ID list once per instance
+    mInstrumentActor->getDetectorIDList(detector_list);
+    if (SHOWTIMING) std::cout << "Instrument3DWidget::calculateColorCounts(): mInstrumentActor->getDetectorIDList() took " << timerID.elapsed() << " seconds\n";
+  }
+
+  if( detector_list.empty() ) return;
+
+  //Make the workspace index list, and force a new one if needed.
+  createWorkspaceIndexList(detector_list, firstCalculation);
+
+
+  //TODO: Make this part in parallel if possible!
+
+  Timer timer2;
+
+  const int n_spec = m_workspace_indices.size();
+  std::vector<double> integrated_values( n_spec, -1.0 );
+
+  //Use the workspace function to get the integrated spectra
+  mWorkspace->getIntegratedSpectra(m_specIntegrs, (this->mBinMinValue), (this->mBinMaxValue), (this->mBinEntireRange));
+
+  mWkspDataMin = DBL_MAX;
+  mWkspDataMax = -DBL_MAX;
+
+  //Now we need to convert to a vector where each entry is the sum for the detector ID at that spot (in integrated_values).
+  for (int i=0; i < n_spec; i++)
+  {
+    int widx = m_workspace_indices[i];
+    if( widx != -1 )
+    {
+      double sum = m_specIntegrs[widx];
+      integrated_values[i] = sum;
+        if( sum < mWkspDataMin )
+          mWkspDataMin = sum;
+        else if( sum > mWkspDataMax )
+          mWkspDataMax = sum;
+    }
+  }
+
+
+  if (SHOWTIMING) std::cout << "Instrument3DWidget::calculateColorCounts():Integrating workspace took " << timer2.elapsed() << " seconds\n";
+
+  // No preset value
+  if( mDataMinEdited == false )
+  {
+    mDataMinValue = mWkspDataMin;
+  }
+
+  if( mDataMaxEdited == false )
+  {
+    mDataMaxValue = mWkspDataMax;
+  }
+
+  Timer timerColLists;
+
+  const short max_ncols = mColorMap.getLargestAllowedCIndex() + 1;
+  mScaledValues = std::vector<unsigned char>(n_spec, 0);
+  std::vector<boost::shared_ptr<GLColor> > colorlist(n_spec);
+  QwtDoubleInterval wksp_interval(mWkspDataMin, mWkspDataMax);
+  QwtDoubleInterval user_interval(mDataMinValue, mDataMaxValue);
+
+  std::vector<double>::iterator val_end = integrated_values.end();
+  int idx(0);
+  for( std::vector<double>::iterator val_itr = integrated_values.begin(); val_itr != val_end;
+      ++val_itr, ++idx )
+  {
+    unsigned char c_index(mColorMap.getTopCIndex());
+    if( (*val_itr) < 0.0 )
+    {
+      mScaledValues[idx] = mColorMap.getLargestAllowedCIndex();
+    }
+    else
+    {
+      // Index to store
+      short index = std::floor( mColorMap.normalize(user_interval, *val_itr)*max_ncols );
+      if( index >= max_ncols )
+      {
+        index = max_ncols;
+      }
+      else if( index < 0 )
+      {
+        index = 0;
+      }
+      else {}
+      mScaledValues[idx] = static_cast<unsigned char>(index);
+      c_index = mColorMap.colorIndex(user_interval, *val_itr);
+
+    }
+    colorlist[idx] = mColorMap.getColor(c_index);
+  }
+  if (SHOWTIMING) std::cout << "Instrument3DWidget::calculateColorCounts(): making the colorlist took " << timerColLists.elapsed() << " seconds\n";
+
+  Timer timerCols;
+  mInstrumentActor->setDetectorColors(colorlist);
+  if (SHOWTIMING) std::cout << "Instrument3DWidget::calculateColorCounts(): mInstrumentActor->setDetectorColors() took " << timerCols.elapsed() << " seconds\n";
+
+  if (SHOWTIMING) std::cout << "Instrument3DWidget::calculateColorCounts() took " << timer.elapsed() << " seconds\n";
+}
+//------------------------------------------------------------------------------------------------
+/**
+ * Run a recount for the current workspace
+ */
+void Instrument3DWidget::recount()
+{
+  calculateColorCounts(mWorkspace, false);
+  mInstrumentActor->refresh();
+  redrawUnwrapped();
+  update();
+}
+
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * For a change in the colour map, just update the color indices.
+ */
+void Instrument3DWidget::updateColorsForNewMap()
+{
+  Timer timer;
+
+  const short max_ncols = mColorMap.getLargestAllowedCIndex() + 1;
+  const short ncols = mColorMap.getTopCIndex() + 1;
+
+  //Create a list of GLColor objects for every spectrum in the workspace
+  std::vector<boost::shared_ptr<GLColor> > colorlist(mScaledValues.size());
+  if( max_ncols == ncols )
+  {
+    std::vector<unsigned char>::const_iterator val_end = mScaledValues.end();
+    int idx(0);
+    for( std::vector<unsigned char>::const_iterator val_itr = mScaledValues.begin();
+        val_itr != val_end; ++val_itr, ++idx )
+    {
+      colorlist[idx] = mColorMap.getColor(*val_itr);
+    }
+  }
+  else
+  {
+    std::vector<unsigned char>::const_iterator val_end = mScaledValues.end();
+    int idx(0);
+    const double ratio = (double)ncols / max_ncols;
+    for( std::vector<unsigned char>::const_iterator val_itr = mScaledValues.begin();
+        val_itr != val_end; ++val_itr, ++idx )
+    {
+      short cache_value = static_cast<short>(*val_itr);
+      short c_index = std::ceil((cache_value + 1)*ratio);
+      if( c_index <= 0 ) c_index = 1;
+      else if( c_index > ncols) c_index = ncols;
+      else {}
+      colorlist[idx] = mColorMap.getColor(static_cast<unsigned char>(c_index - 1));
+    }
+  }
+
+  mInstrumentActor->setDetectorColors(colorlist);
+  mInstrumentActor->refresh();
+  update();
+
+  if (SHOWTIMING) std::cout << "Instrument3DWidget::updateColorsForNewMap() took " << timer.elapsed() << " seconds\n";
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Update the colors based on a change in the maximum data value
+ */
+void Instrument3DWidget::setMaxData(const double new_max)
+{
+  mDataMaxValue = new_max;
+  setDataMaxEdited(true);
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Update the colors based on a change in the minimum data value
+ */
+void Instrument3DWidget::setMinData(const double new_min)
+{
+  mDataMinValue = new_min;
+  setDataMinEdited(true);
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Mark the min data as bein user edited
+ * @param If :: true the data min value has been set by the user
+ */
+void Instrument3DWidget::setDataMinEdited(bool state)
+{
+  mDataMinEdited = state;
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Mark the min data as bein user edited
+ * @param If :: true the data max value has been set by the user
+ */
+void Instrument3DWidget::setDataMaxEdited(bool state)
+{
+  mDataMaxEdited = state;
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * This method returns the workspace index list for the input dectector id list:
+ *  i.e. the detector at index i of det_ids has a spectrum at workspace index given in
+ *      m_workspace_indices[i].
+ *
+ * @param det_ids :: is list of detector id's
+ * @param forceNew :: set to true to force the creation of a new list; otherwise, the old one will be reused
+ * if possible.
+ */
+void Instrument3DWidget::createWorkspaceIndexList(const std::vector<int> & det_ids, bool forceNew)
+{
+  Timer timer;
+
+  if( det_ids.empty() ) return;
+  if (!forceNew)
+  {
+    //Don't force a new one, and the sizes match. We assume it is good.
+    if (m_workspace_indices.size() == det_ids.size())
+      return;
+  }
+  m_workspace_indices.resize(det_ids.size());
+  m_detector_ids = det_ids;
+
+  //the DetInfo object will collect information about selected detectors from the pointers and references passed
+  m_detInfo = DetInfo(mWorkspace, &m_specIntegrs);
+
+  //the DetInfo object can convert from detector IDs to spectra indices and so this creates a vector of spectra indices
+  std::transform(m_detector_ids.begin(), m_detector_ids.end(),
+                 m_workspace_indices.begin(), m_detInfo);
+  /*
+  std::vector<int>::const_iterator detIDsIn = m_detector_ids.begin();
+  std::vector<int>::iterator specIndsOut = m_workspace_indices.begin();
+  std::vector<int>::const_iterator end = m_detector_ids.end();
+  for( ; detIDsIn != end; ++detIDsIn, ++specIndsOut)
+  {
+    *specIndsOut = m_detInfo.getIndexOf(*detIDsIn);
+  }*/
+
+  if (SHOWTIMING) std::cout << "Instrument3DWidget::createWorkspaceIndexList() took " << timer.elapsed() << " seconds\n";
+
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * This method sets the Time bin values. the value has to be greater than zero
+ * @param value :: input is the time bin value
+ */
+void Instrument3DWidget::setTimeBin(int value)
+{
+  if(value>0)
+  {
+    this->iTimeBin=value;
+  }
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Returns workspace name
+ */
+QString Instrument3DWidget::getWorkspaceName() const
+{
+  return mWorkspaceName;
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Returns a reference to the constant colormap
+ */
+const MantidColorMap & Instrument3DWidget::getColorMap() const
+{
+  return mColorMap;
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Returns a reference to the colormap
+ */
+MantidColorMap & Instrument3DWidget::mutableColorMap()
+{
+  return mColorMap;
+}
+
+
+/**
+ * This method takes the input name as the min value Colormap scale.
+ */
+void Instrument3DWidget::setColorMapMinValue(double minValue)
+{
+	this->mDataMinValue=minValue;
+}
+
+/**
+ * This method takes the input name as the min value Colormap scale.
+ */
+void Instrument3DWidget::setColorMapMaxValue(double maxValue)
+{
+	this->mDataMaxValue = maxValue;
+}
+
+/**
+ * This method returns min value. by default will be min value in the current timebin
+ */
+double Instrument3DWidget::getDataMinValue() const
+{
+	return this->mDataMinValue;
+}
+
+/**
+ * This method returns the max value. by default will be max value in the current timebin
+ */
+double Instrument3DWidget::getDataMaxValue() const
+{
+	return this->mDataMaxValue;
+}
+
+/** Returns the current minimum bin value
+ */
+double Instrument3DWidget::getBinMinValue() const
+{
+  return this->mBinMinValue;
+}
+
+/** Returns the current maximum bin value
+ */
+double Instrument3DWidget::getBinMaxValue() const
+{
+    return this->mBinMaxValue;
+}
+
+/** Returns the current value for integrating all the bins (entire range)
+ */
+bool Instrument3DWidget::getBinEntireRange() const
+{
+    return this->mBinEntireRange;
+}
+
+/**
+ * This method sets the Data mapping type for the color mapping.
+ */
+void Instrument3DWidget::setDataMappingType(DataMappingType dmType)
+{
+	mDataMapping=dmType;
+}
+
+void Instrument3DWidget::setDataMappingIntegral(double minValue,double maxValue, bool entireRange)
+{
+  this->mBinMinValue = minValue;
+  this->mBinMaxValue = maxValue;
+  this->mBinEntireRange = entireRange;
+  setDataMappingType(INTEGRAL);
+  if( this->isVisible() )
+  {
+    calculateColorCounts(mWorkspace, false);
+    mInstrumentActor->refresh();
+    update();
+  }
+}
+
+void Instrument3DWidget::setDataMappingSingleBin(int binNumber)
+{
+  this->iTimeBin=binNumber;
+  setDataMappingType(SINGLE_BIN);
+}
+
+/**
+ * Sets the default view to X direction positive
+ */
+void Instrument3DWidget::setViewDirectionXPositive()
+{
+	setViewDirection(XPOSITIVE);
+}
+
+/**
+ * Sets the default view to Y direction positive
+ */
+void Instrument3DWidget::setViewDirectionYPositive()
+{
+	setViewDirection(YPOSITIVE);
+}
+
+/**
+ * Sets the default view to Z direction positive
+ */
+void Instrument3DWidget::setViewDirectionZPositive()
+{
+	setViewDirection(ZPOSITIVE);
+}
+
+/**
+ * Sets the default view to X direction negative
+ */
+void Instrument3DWidget::setViewDirectionXNegative()
+{
+	setViewDirection(XNEGATIVE);
+}
+
+/**
+ * Sets the default view to Y direction negative
+ */
+void Instrument3DWidget::setViewDirectionYNegative()
+{
+	setViewDirection(YNEGATIVE);
+}
+
+/**
+ * Sets the default view to Z direction negative
+ */
+void Instrument3DWidget::setViewDirectionZNegative()
+{
+	setViewDirection(ZNEGATIVE);
+}
+
+/**
+ * Sets the slow rendering not using display list
+ * NOTE: This method will ***NOT*** have any effect after the workspace name is set.
+ */
+void Instrument3DWidget::setSlowRendering()
+{
+	mFastRendering=false;
+}
+
+/**
+ * Sets the fast rendering using display list
+ * NOTE: This method will ***NOT*** have any effect after the workspace name is set.
+ */
+void Instrument3DWidget::setFastRendering()
+{
+	mFastRendering=true;
+}
+
+
+/**
+ * Completely resets the data in the instrument widget. ready for new workspace
+ */
+void Instrument3DWidget::resetWidget()
+{
+	iTimeBin = 0;
+	mWorkspaceName = QString();
+	mBinMinValue = DBL_MAX;
+	mBinMaxValue = -DBL_MAX;
+	mDataMinValue = DBL_MAX;
+	mDataMaxValue = -DBL_MAX;
+	mDataMinEdited = false;
+	mDataMaxEdited = false;
+	mDataMapping = INTEGRAL;
+	mAxisDirection = Mantid::Geometry::V3D(0.0,0.0,1.0);
+	mAxisUpVector = Mantid::Geometry::V3D(0.0,1.0,0.0);
+	mScaledValues.clear();
+	GL3DWidget::resetWidget();
+}
+
+void Instrument3DWidget::setView(const V3D& pos,double xmax,double ymax,double zmax,double xmin,double ymin,double zmin)
+{
+	//Change the View to the axis orientation
+	V3D s=mAxisDirection.cross_prod(mAxisUpVector);
+	V3D u=s.cross_prod(mAxisDirection);
+	double Mat[16];
+	Mat[0]=s[0];              Mat[4]=s[1];              Mat[8]=s[2];               Mat[12]=0;
+	Mat[1]=u[0];              Mat[5]=u[1];              Mat[9]=u[2];               Mat[13]=0;
+	Mat[2]=-mAxisDirection[0];Mat[6]=-mAxisDirection[1];Mat[10]=-mAxisDirection[2];Mat[14]=0;
+	Mat[3]=0;                 Mat[7]=0;                 Mat[11]=0;                 Mat[15]=1;
+	Quat defaultView;
+	defaultView.setQuat(Mat);
+	defaultView.normalize();
+	//get the rotation to make the center of the bounding box to the view
+	V3D boundCentre;
+	boundCentre[0]=(xmax+xmin)/2.0;
+	boundCentre[1]=(ymax+ymin)/2.0;
+	boundCentre[2]=(zmax+zmin)/2.0;
+	V3D vcb=boundCentre-pos;
+	vcb.normalize();
+	V3D zaxis(0,0,1);
+	Quat rotation(zaxis,vcb);
+	rotation.inverse();
+	if(rotation!=Quat(0,0,0,0))
+		defaultView=rotation*defaultView;
+	_trackball->reset();
+	_trackball->setModelCenter(pos);
+	if(defaultView!=Quat(0,0,0,0))
+		_trackball->setRotation(defaultView);
+	_trackball->rotateBoundingBox(xmin,xmax,ymin,ymax,zmin,zmax);//rotate the bounding box
+        _viewport->setOrtho(xmin,xmax,ymin,ymax,-zmax,-zmin,false);
+	_viewport->issueGL();
+	update();
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * This method draws the scene using color id. this method is called in pick mode
+ */
+void Instrument3DWidget::drawSceneUsingColorID()
+{
+	mInstrumentActor->drawUsingColorID();
+}
+
+/**
+ * Draws the scene in low resolution. this method is called in interactive mode for faster response
+ */
+void Instrument3DWidget::setSceneLowResolution()
+{
+	mInstrumentActor->setObjectResolutionToLow();
+}
+
+/**
+ * Draws the scene in high resolution.
+ */
+void Instrument3DWidget::setSceneHighResolution()
+{
+	mInstrumentActor->setObjectResolutionToHigh();
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Returns the boundig box of the scene
+ * @param minBound :: output min point of the bounding box of scene
+ * @param maxBound :: output max point of the bounding box of scene
+ */
+void Instrument3DWidget::getBoundingBox(Mantid::Geometry::V3D& minBound, Mantid::Geometry::V3D& maxBound)
+{
+	mInstrumentActor->getBoundingBox(minBound,maxBound);
+}
+
+/** Set pointers to the workspace data that is needed to obtain information about
+*  detectors
+*  @param DetID :: id number of the detector to retrieve information for
+*  @param workspace :: the workspace with counts data for the detector
+*  @param counts :: integral of the number of counts in each spectrum
+*  @throw runtime_error if there was an error creating the spectra index to detector index map
+*/
+Instrument3DWidget::DetInfo::DetInfo(Mantid::API::MatrixWorkspace_const_sptr workspace, const std::vector<double> * const counts) :
+    m_workspace(workspace),
+    m_integrals(counts),
+    m_firstDet(ERROR_FLAG), m_lastDet(ERROR_FLAG)
+{
+  if (m_workspace)
+  {
+    m_detID_to_wi_map = boost::shared_ptr<const IndexToIndexMap>(
+        m_workspace->getDetectorIDToWorkspaceIndexMap(false));
+  }
+}
+/// set the object to contain data for only one detector
+void Instrument3DWidget::DetInfo::setDet(const int detID)
+{
+  m_firstDet = detID;
+  m_lastDet = NO_INDEX;
+}
+/** specify a range of detectors by giving the id of a detector at the end of the range
+*  @param detID :: id number of detector to add
+*/
+void Instrument3DWidget::DetInfo::setEndRange(const int detID)
+{
+  if (is_good(detID))
+  {
+    m_lastDet = detID;
+  }
+  else
+  {
+    m_lastDet = m_firstDet = ERROR_FLAG;
+  }
+}
+/** Returns a string containing all this object's data in a human readable
+* form
+* @return all this objects data labeled and formated for user display
+*/
+QString Instrument3DWidget::DetInfo::display() const
+{
+  std::ostringstream out;
+  out << "Detector ID:  " << m_firstDet;
+
+  if (is_good(m_firstDet))
+  {
+    printSpectrum(getIndexOf(m_firstDet), out);
+    out << std::endl;
+    printLocation(out);
+  }
+  else
+  {// reserve a fixed width for displaying any data
+    out << std::endl;
+  }
+
+  return QString::fromStdString(out.str());
+}
+
+int Instrument3DWidget::DetInfo::getWorkspaceIndex()const
+{
+  return is_good(m_firstDet) ? getIndexOf(m_firstDet) : -1;
+}
+
+/** Writes the information about the spectrum whose index is passed to it
+*  in a human readble form to the stream provide, or nothing on error
+*  @param[in] index the index number of the spectrum to display
+*  @param[out] output information will be writen to this stream
+*/
+void Instrument3DWidget::DetInfo::printSpectrum(const int index, std::ostringstream & output) const
+{
+  if (is_good(index))
+  {
+    int spectrumNumber(NO_INDEX);
+    try
+    {
+      spectrumNumber = m_workspace->getAxis(1)->spectraNo(index);
+    }
+    catch (...)
+    {
+      //if some information couldn't be retrieved, default values will be displayed
+    }
+
+    if (index != spectrumNumber && is_good(spectrumNumber) )
+      output << "    Spectrum number: " << spectrumNumber << "  workspace index: " << index;
+    else
+      output << "    Spectrum number: " << spectrumNumber;
+    output << "    Count:  ";
+
+    if (m_integrals)
+    {
+      output << m_integrals->operator[](index);
+    }
+    else
+    {
+      output << "-";
+    }
+  }
+}
+/** Writes the location of any detectors whose information is retrievable
+*  in a human readable form
+*  @param[out] output information will be writen to this stream
+*/
+void Instrument3DWidget::DetInfo::printLocation(std::ostringstream & output) const
+{
+  // display location information for the detector, ignoring missing detectors
+  std::string units("");
+  try
+  {
+    IDetector_const_sptr locInfo =
+      m_workspace->getInstrument()->getDetector(m_firstDet);
+    V3D pos = locInfo->getPos();
+    output << "position:  ";
+    printV(pos, output);
+    units = " m";
+
+    locInfo = m_workspace->getInstrument()->getDetector(m_lastDet);
+    V3D endPos = locInfo->getPos();
+    output << " -> ";
+    printV(endPos, output);
+    output << " = ";
+    printV(pos-endPos, output);
+  }
+  catch(Exception::NotFoundError &)
+  {
+    //don't display data when there is an error retreiving it
+  }
+  output << units;
+}
+/** Writes a position vector in a nice way
+*  @param[in] pos coordinates to print
+*  @param[out] output information will be writen to this stream
+*/
+void Instrument3DWidget::DetInfo::printV(Mantid::Geometry::V3D pos, std::ostringstream & out) const
+{
+  out << "(" << pos.X() << "," << pos.Y() << "," << pos.Z() << ")";
+}
+/** Returns the index number of the spectrum generated by the detector whose ID number
+*  was passed or DetInfo::NO_INDEX on error
+*  @param someDetID :: an ID of a detector that exists in the workspace
+*  @return the index number of the spectrum associated with that detector or -1
+*/
+int Instrument3DWidget::DetInfo::getIndexOf(const int someDetID) const
+{
+  IndexToIndexMap::const_iterator it(m_detID_to_wi_map->find(someDetID));
+  if ( it != m_detID_to_wi_map->end() )
+  {
+    return it->second;
+  }
+  else return NO_INDEX;
+}
+
+void Instrument3DWidget::showUnwrappedContextMenu()
+{
+  QMenu context(this);
+
+  context.addAction(m_ExtractDetsToWorkspaceAction);
+  context.addAction(m_SumDetsToWorkspaceAction);
+  QMenu *gfileMenu = context.addMenu("Create grouping file");
+  gfileMenu->addAction(m_createIncludeGroupingFileAction);
+  gfileMenu->addAction(m_createExcludeGroupingFileAction);
+
+  context.exec(QCursor::pos());
+}
+
+void Instrument3DWidget::showInfo()
+{
+  if (!m_unwrappedSurface) return;
+
+  QSet<int> dets;
+  m_unwrappedSurface->getPickedDetector(dets);
+
+  QString msg;
+  if (dets.size() == 0) return;
+  else if (dets.size() == 1)
+  {
+    msg = "Detector ID " + QString::number(*dets.begin());
+  }
+  else
+  {
+    msg = "Selected " + QString::number(dets.size()) + " detectors";
+  }
+  QMessageBox::information(this,"MantidPlot",msg);
+}
+
+/**
+  * Extract selected detectors to a new workspace
+  */
+void Instrument3DWidget::extractDetsToWorkspace()
+{
+  if (!m_unwrappedSurface) return;
+  QSet<int> dets;
+  m_unwrappedSurface->getPickedDetector(dets);
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  DetXMLFile mapFile(dets);
+  std::string fname = mapFile();
+
+  if (!fname.empty())
+  {
+    Mantid::API::IAlgorithm* alg = Mantid::API::FrameworkManager::Instance().createAlgorithm("GroupDetectors");
+    alg->setPropertyValue("InputWorkspace",getWorkspaceName().toStdString());
+    alg->setPropertyValue("MapFile",fname);
+    alg->setPropertyValue("OutputWorkspace",getWorkspaceName().toStdString()+"_selection");
+    alg->execute();
+  }
+
+  QApplication::restoreOverrideCursor();
+}
+
+/**
+  * Sum selected detectors to a new workspace
+  */
+void Instrument3DWidget::sumDetsToWorkspace()
+{
+  if (!m_unwrappedSurface) return;
+  QSet<int> dets;
+  m_unwrappedSurface->getPickedDetector(dets);
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  DetXMLFile mapFile(dets,DetXMLFile::Sum);
+  std::string fname = mapFile();
+
+  if (!fname.empty())
+  {
+    Mantid::API::IAlgorithm* alg = Mantid::API::FrameworkManager::Instance().createAlgorithm("GroupDetectors");
+    alg->setPropertyValue("InputWorkspace",getWorkspaceName().toStdString());
+    alg->setPropertyValue("MapFile",fname);
+    alg->setPropertyValue("OutputWorkspace",getWorkspaceName().toStdString()+"_sum");
+    alg->execute();
+  }
+
+  QApplication::restoreOverrideCursor();
+}
+
+void Instrument3DWidget::createIncludeGroupingFile()
+{
+  if (!m_unwrappedSurface) return;
+  QSet<int> dets;
+  m_unwrappedSurface->getPickedDetector(dets);
+
+  QString fname = QFileDialog::getSaveFileName(this,"Save grouping file");
+  if (!fname.isEmpty())
+  {
+    DetXMLFile mapFile(dets,DetXMLFile::Sum,fname);
+  }
+
+}
+
+void Instrument3DWidget::createExcludeGroupingFile()
+{
+  if (!m_unwrappedSurface) return;
+  QSet<int> dets;
+  m_unwrappedSurface->getPickedDetector(dets);
+
+  QString fname = QFileDialog::getSaveFileName(this,"Save grouping file");
+  if (!fname.isEmpty())
+  {
+    DetXMLFile mapFile(detector_list,dets,fname);
+  }
+}
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/Instrument3DWidget.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/Instrument3DWidget.h
index d48f9ec614c50ae3595edf57bab5b51cb8b25f7f..ae7c2c15a386e47c05ca38613538d3433a6f7aa7 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/Instrument3DWidget.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/Instrument3DWidget.h
@@ -1,220 +1,220 @@
-#ifndef INSTRUMENT3DWIDGET_H_
-#define INSTRUMENT3DWIDGET_H_
-
-#include "GL3DWidget.h"
-#include "MantidColorMap.h"
-#include "boost/shared_ptr.hpp"
-#include <vector>
-#include "MantidGeometry/V3D.h"
-#include "MantidAPI/MatrixWorkspace.h"
-
-class QAction;
-
-/**
-  \class  GL3DWidget
-  \brief  OpenGL Qt Widget which renders Instrument
-  \author Chapon Laurent & Srikanth Nagella
-  \date   August 2008
-  \version 1.0
-
-  This Class takes input a Instrument and renders them with in the Qt widget.
-
-  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-namespace Mantid
-{
-  namespace Geometry
-  {
-    class IInstrument;
-  }
-}
-
-class InstrumentActor;
-class InstrumentWindow;
-
-class Instrument3DWidget : public GL3DWidget
-{ 
-  Q_OBJECT
-  enum DataMappingType { SINGLE_BIN, INTEGRAL };
-  enum Handedness { LEFT, RIGHT };
-
-public:
-
-  /// Contains summary information about detectors for display to users
-  class DetInfo : public std::unary_function<int, int>
-  {
-  public:
-    /** Returns the index number of the spectrum for the given detector
-    *  @param someDetID :: id of detector to be queried
-    */
-    int operator()(const int someDetID) const{return getIndexOf(someDetID);}
-    /// Get pointers to the workspace that contain information about detectors
-    DetInfo(Mantid::API::MatrixWorkspace_const_sptr workspace=Mantid::API::MatrixWorkspace_const_sptr(), const std::vector<double> * const counts=NULL);
-
-    void setDet(const int detID);                                 ///< set up the object to contain data for only one detector
-    void setEndRange(const int detID);                            ///< for a detector with at least one detector set the detector for the end of the range
-    QString display() const;                                      ///< Creates a string with the object's data in a human readable form
-    Mantid::API::MatrixWorkspace_const_sptr getWorkspace()const{return m_workspace;}
-    int getDetID()const{return m_firstDet;}
-    int getWorkspaceIndex()const;
-    int getIndexOf(const int someDetID) const;                    ///< Gets the index number of the spectrum for the given detector
-  private:
-    static const int NO_INDEX = -1;                               ///< Value used to indicate missing data, detectors, spectra, etc...
-    static const int ERROR_FLAG = -2;                             ///< flags missing values but indicates an inconsistency in the data state
-    Mantid::API::MatrixWorkspace_const_sptr m_workspace;          ///< All data refer to this workspace
-    const std::vector<double> * m_integrals;                      ///< the integral of each spectra
-    boost::shared_ptr<const Mantid::API::IndexToIndexMap> m_detID_to_wi_map;///< used to get workspace indices from detector IDs
-    int m_firstDet;                                               ///< id number of the detector that was selected first
-    int m_lastDet;                                                ///< if more than one detector is selected this is the id number of the one selected last otherwise the NO_DATA value
-
-    void printSpectrum(const int index, std::ostringstream & output) const;///< Retrieves information about the spectrum whose index was passed
-    void printLocation(std::ostringstream & output) const;///< Writes the location of the detectors
-    void printV(Mantid::Geometry::V3D pos, std::ostringstream & out) const;///< Writes a position vector in a nice way
-    /** Returns true only if the value passed can't be missing data
-    *  @param testVal :: the data value to check
-    *  @return if there are no error flags returns true
-    */
-    bool is_good(const int testVal) const { return testVal > NO_INDEX; }
-  };
-
-  Instrument3DWidget(InstrumentWindow* parent); ///< Constructor
-  virtual ~Instrument3DWidget();         ///< Destructor
-  void setWorkspace(const QString& name);
-  QString getWorkspaceName() const;
-  const MantidColorMap & getColorMap() const;
-  MantidColorMap & mutableColorMap();
-  double getDataMinValue() const;
-  double getDataMaxValue() const;
-  double getBinMinValue() const;
-  double getBinMaxValue() const;
-  bool getBinEntireRange() const;
-  void setDataMappingType(DataMappingType);
-  void setView(const Mantid::Geometry::V3D&,double,double,double,double,double,double);
-  void setAxis(const Mantid::Geometry::V3D &direction);
-  void resetWidget();
-  void setFastRendering();
-  void setSlowRendering();
-  void updateColorsForNewMap();
-  void setMinData(const double);
-  void setMaxData(const double);
-  void setDataMinEdited(bool state);
-  void setDataMaxEdited(bool state);
-  bool dataMinValueEdited() const { return mDataMinEdited; }
-  bool dataMaxValueEdited() const { return mDataMaxEdited; }
-  
-  void recount();
-
-  const std::vector<int> & getSelectedDetectorIDs() const { return m_detector_ids; }
-  const std::vector<int> & getSelectedWorkspaceIndices() const { return m_workspace_indices; }
-
-public slots:
-  void fireDetectorsPicked(const std::set<QRgb>& );
-  void fireDetectorHighligted(QRgb);
-  void fireDetectorHighligted(int detID);
-  void detectorsHighligted(QRgb);
-  void setTimeBin(int value);
-  void setColorMapMinValue(double minValue);
-  void setColorMapMaxValue(double maxValue);
-  void setDataMappingIntegral(double minValue,double maxValue, bool entireRange);
-  void setDataMappingSingleBin(int binNumber);
-  void setViewDirectionXPositive();
-  void setViewDirectionYPositive();
-  void setViewDirectionZPositive();
-  void setViewDirectionXNegative();
-  void setViewDirectionYNegative();
-  void setViewDirectionZNegative();
-  void showInfo();
-  void extractDetsToWorkspace();
-  void sumDetsToWorkspace();
-  void createIncludeGroupingFile();
-  void createExcludeGroupingFile();
-
-
-signals:
-  void detectorsSelected();
-  void actionDetectorHighlighted(const Instrument3DWidget::DetInfo &);
-
-public:
-  void calculateBinRange();
-
-private:
-  void ParseInstrumentGeometry(boost::shared_ptr<Mantid::Geometry::IInstrument>);
-  void calculateColorCounts(boost::shared_ptr<Mantid::API::MatrixWorkspace> workspace, bool firstCalculation);
-
-  void drawSceneUsingColorID();
-  void setSceneLowResolution();
-  void setSceneHighResolution();
-  void getBoundingBox(Mantid::Geometry::V3D& minBound, Mantid::Geometry::V3D& maxBound);
-  void showUnwrappedContextMenu();
-
-  /// Convert the list of detector ids to a list of workspace indices and store them
-  void createWorkspaceIndexList(const std::vector<int> & idlist, bool forceNew);
-  boost::shared_ptr<Mantid::API::MatrixWorkspace> getMatrixWorkspace(QString ) const;
-
-  InstrumentWindow* m_instrumentWindow;
-
-  bool mFastRendering;
-  int iTimeBin;
-  DataMappingType mDataMapping;
-  MantidColorMap mColorMap;
-  
-  /// List of detector IDs used by the color mapping algorithms.
-  std::vector<int> detector_list;
-
-  InstrumentActor* mInstrumentActor;
-  Mantid::Geometry::V3D mAxisDirection;
-  Mantid::Geometry::V3D mAxisUpVector;
-
-  /// The user requested data and bin ranges
-  double mDataMinValue, mDataMaxValue;
-  double mBinMinValue, mBinMaxValue;
-
-  /// Bool set to true if you keep all the bins, no matter what. Defaults to true.
-  bool mBinEntireRange;
-
-  /// If true the data min or maxvalue has been set by the user
-  bool mDataMinEdited, mDataMaxEdited;
-
-  /// The workspace data and bin range limits
-  double mWkspDataMin, mWkspDataMax;
-  double mWkspBinMin, mWkspBinMax;
-
-  QString mWorkspaceName;
-  boost::shared_ptr<Mantid::API::MatrixWorkspace> mWorkspace;
-
-  /// Store a value between 0->255 for each of the integrated spectra.
-  std::vector<unsigned char> mScaledValues;
-
-  std::vector<int> m_detector_ids;
-  std::vector<int> m_workspace_indices;
-  /// integrated number of counts in each spectrum
-  std::vector<double> m_specIntegrs;
-
-  /// Contains information about selected detectors, when there is a selection
-  DetInfo m_detInfo;
-
-  QAction *m_ExtractDetsToWorkspaceAction;  ///< Extract selected detector ids to a new workspace
-  QAction *m_SumDetsToWorkspaceAction;      ///< Sum selected detectors to a new workspace
-  QAction *m_createIncludeGroupingFileAction; ///< Create grouping xml file which includes selected detectors
-  QAction *m_createExcludeGroupingFileAction; ///< Create grouping xml file which excludes selected detectors
-};
-
-#endif /*GL3DWIDGET_H_*/
-
+#ifndef INSTRUMENT3DWIDGET_H_
+#define INSTRUMENT3DWIDGET_H_
+
+#include "GL3DWidget.h"
+#include "MantidColorMap.h"
+#include "boost/shared_ptr.hpp"
+#include <vector>
+#include "MantidGeometry/V3D.h"
+#include "MantidAPI/MatrixWorkspace.h"
+
+class QAction;
+
+/**
+  \class  GL3DWidget
+  \brief  OpenGL Qt Widget which renders Instrument
+  \author Chapon Laurent & Srikanth Nagella
+  \date   August 2008
+  \version 1.0
+
+  This Class takes input a Instrument and renders them with in the Qt widget.
+
+  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+*/
+namespace Mantid
+{
+  namespace Geometry
+  {
+    class IInstrument;
+  }
+}
+
+class InstrumentActor;
+class InstrumentWindow;
+
+class Instrument3DWidget : public GL3DWidget
+{ 
+  Q_OBJECT
+  enum DataMappingType { SINGLE_BIN, INTEGRAL };
+  enum Handedness { LEFT, RIGHT };
+
+public:
+
+  /// Contains summary information about detectors for display to users
+  class DetInfo : public std::unary_function<int, int>
+  {
+  public:
+    /** Returns the index number of the spectrum for the given detector
+    *  @param someDetID :: id of detector to be queried
+    */
+    int operator()(const int someDetID) const{return getIndexOf(someDetID);}
+    /// Get pointers to the workspace that contain information about detectors
+    DetInfo(Mantid::API::MatrixWorkspace_const_sptr workspace=Mantid::API::MatrixWorkspace_const_sptr(), const std::vector<double> * const counts=NULL);
+
+    void setDet(const int detID);                                 ///< set up the object to contain data for only one detector
+    void setEndRange(const int detID);                            ///< for a detector with at least one detector set the detector for the end of the range
+    QString display() const;                                      ///< Creates a string with the object's data in a human readable form
+    Mantid::API::MatrixWorkspace_const_sptr getWorkspace()const{return m_workspace;}
+    int getDetID()const{return m_firstDet;}
+    int getWorkspaceIndex()const;
+    int getIndexOf(const int someDetID) const;                    ///< Gets the index number of the spectrum for the given detector
+  private:
+    static const int NO_INDEX = -1;                               ///< Value used to indicate missing data, detectors, spectra, etc...
+    static const int ERROR_FLAG = -2;                             ///< flags missing values but indicates an inconsistency in the data state
+    Mantid::API::MatrixWorkspace_const_sptr m_workspace;          ///< All data refer to this workspace
+    const std::vector<double> * m_integrals;                      ///< the integral of each spectra
+    boost::shared_ptr<const Mantid::API::IndexToIndexMap> m_detID_to_wi_map;///< used to get workspace indices from detector IDs
+    int m_firstDet;                                               ///< id number of the detector that was selected first
+    int m_lastDet;                                                ///< if more than one detector is selected this is the id number of the one selected last otherwise the NO_DATA value
+
+    void printSpectrum(const int index, std::ostringstream & output) const;///< Retrieves information about the spectrum whose index was passed
+    void printLocation(std::ostringstream & output) const;///< Writes the location of the detectors
+    void printV(Mantid::Geometry::V3D pos, std::ostringstream & out) const;///< Writes a position vector in a nice way
+    /** Returns true only if the value passed can't be missing data
+    *  @param testVal :: the data value to check
+    *  @return if there are no error flags returns true
+    */
+    bool is_good(const int testVal) const { return testVal > NO_INDEX; }
+  };
+
+  Instrument3DWidget(InstrumentWindow* parent); ///< Constructor
+  virtual ~Instrument3DWidget();         ///< Destructor
+  void setWorkspace(const QString& name);
+  QString getWorkspaceName() const;
+  const MantidColorMap & getColorMap() const;
+  MantidColorMap & mutableColorMap();
+  double getDataMinValue() const;
+  double getDataMaxValue() const;
+  double getBinMinValue() const;
+  double getBinMaxValue() const;
+  bool getBinEntireRange() const;
+  void setDataMappingType(DataMappingType);
+  void setView(const Mantid::Geometry::V3D&,double,double,double,double,double,double);
+  void setAxis(const Mantid::Geometry::V3D &direction);
+  void resetWidget();
+  void setFastRendering();
+  void setSlowRendering();
+  void updateColorsForNewMap();
+  void setMinData(const double);
+  void setMaxData(const double);
+  void setDataMinEdited(bool state);
+  void setDataMaxEdited(bool state);
+  bool dataMinValueEdited() const { return mDataMinEdited; }
+  bool dataMaxValueEdited() const { return mDataMaxEdited; }
+  
+  void recount();
+
+  const std::vector<int> & getSelectedDetectorIDs() const { return m_detector_ids; }
+  const std::vector<int> & getSelectedWorkspaceIndices() const { return m_workspace_indices; }
+
+public slots:
+  void fireDetectorsPicked(const std::set<QRgb>& );
+  void fireDetectorHighligted(QRgb);
+  void fireDetectorHighligted(int detID);
+  void detectorsHighligted(QRgb);
+  void setTimeBin(int value);
+  void setColorMapMinValue(double minValue);
+  void setColorMapMaxValue(double maxValue);
+  void setDataMappingIntegral(double minValue,double maxValue, bool entireRange);
+  void setDataMappingSingleBin(int binNumber);
+  void setViewDirectionXPositive();
+  void setViewDirectionYPositive();
+  void setViewDirectionZPositive();
+  void setViewDirectionXNegative();
+  void setViewDirectionYNegative();
+  void setViewDirectionZNegative();
+  void showInfo();
+  void extractDetsToWorkspace();
+  void sumDetsToWorkspace();
+  void createIncludeGroupingFile();
+  void createExcludeGroupingFile();
+
+
+signals:
+  void detectorsSelected();
+  void actionDetectorHighlighted(const Instrument3DWidget::DetInfo &);
+
+public:
+  void calculateBinRange();
+
+private:
+  void ParseInstrumentGeometry(boost::shared_ptr<Mantid::Geometry::IInstrument>);
+  void calculateColorCounts(boost::shared_ptr<Mantid::API::MatrixWorkspace> workspace, bool firstCalculation);
+
+  void drawSceneUsingColorID();
+  void setSceneLowResolution();
+  void setSceneHighResolution();
+  void getBoundingBox(Mantid::Geometry::V3D& minBound, Mantid::Geometry::V3D& maxBound);
+  void showUnwrappedContextMenu();
+
+  /// Convert the list of detector ids to a list of workspace indices and store them
+  void createWorkspaceIndexList(const std::vector<int> & idlist, bool forceNew);
+  boost::shared_ptr<Mantid::API::MatrixWorkspace> getMatrixWorkspace(QString ) const;
+
+  InstrumentWindow* m_instrumentWindow;
+
+  bool mFastRendering;
+  int iTimeBin;
+  DataMappingType mDataMapping;
+  MantidColorMap mColorMap;
+  
+  /// List of detector IDs used by the color mapping algorithms.
+  std::vector<int> detector_list;
+
+  InstrumentActor* mInstrumentActor;
+  Mantid::Geometry::V3D mAxisDirection;
+  Mantid::Geometry::V3D mAxisUpVector;
+
+  /// The user requested data and bin ranges
+  double mDataMinValue, mDataMaxValue;
+  double mBinMinValue, mBinMaxValue;
+
+  /// Bool set to true if you keep all the bins, no matter what. Defaults to true.
+  bool mBinEntireRange;
+
+  /// If true the data min or maxvalue has been set by the user
+  bool mDataMinEdited, mDataMaxEdited;
+
+  /// The workspace data and bin range limits
+  double mWkspDataMin, mWkspDataMax;
+  double mWkspBinMin, mWkspBinMax;
+
+  QString mWorkspaceName;
+  boost::shared_ptr<Mantid::API::MatrixWorkspace> mWorkspace;
+
+  /// Store a value between 0->255 for each of the integrated spectra.
+  std::vector<unsigned char> mScaledValues;
+
+  std::vector<int> m_detector_ids;
+  std::vector<int> m_workspace_indices;
+  /// integrated number of counts in each spectrum
+  std::vector<double> m_specIntegrs;
+
+  /// Contains information about selected detectors, when there is a selection
+  DetInfo m_detInfo;
+
+  QAction *m_ExtractDetsToWorkspaceAction;  ///< Extract selected detector ids to a new workspace
+  QAction *m_SumDetsToWorkspaceAction;      ///< Sum selected detectors to a new workspace
+  QAction *m_createIncludeGroupingFileAction; ///< Create grouping xml file which includes selected detectors
+  QAction *m_createExcludeGroupingFileAction; ///< Create grouping xml file which excludes selected detectors
+};
+
+#endif /*GL3DWIDGET_H_*/
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentActor.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentActor.cpp
index 93cfd3d6a18c711de0959cffc7cc23ffcc1c9737..a95e48a18adcf732a3b1a95ec763ab675edb49eb 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentActor.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentActor.cpp
@@ -1,97 +1,97 @@
-#include "MantidGeometry/IInstrument.h"
-#include "MantidGeometry/V3D.h"
-#include "MantidGeometry/Objects/Object.h"
-#include "MantidGeometry/ICompAssembly.h"
-#include "MantidGeometry/IObjComponent.h"
-#include "MantidKernel/Exception.h"
-#include "MantidObject.h"
-#include "ObjComponentActor.h"
-#include "InstrumentActor.h"
-
-using namespace Mantid::Geometry;
-
-/**
- * Constructor
- * @param ins :: Instrument
- * @param withDisplayList :: true use display list, false use immediate rendering
- */
-InstrumentActor::InstrumentActor(boost::shared_ptr<Mantid::Geometry::IInstrument> ins, bool withDisplayList):CompAssemblyActor(withDisplayList)
-{
-	mInstrument=ins;
-	mId=mInstrument->getComponentID();
-	mObjects = boost::shared_ptr<std::map<const boost::shared_ptr<const Mantid::Geometry::Object>,MantidObject*> >(new std::map<const boost::shared_ptr<const Mantid::Geometry::Object>,MantidObject*>());
-	initChilds(withDisplayList);
-}
-
-/**
- * Destructor
- */
-InstrumentActor::~InstrumentActor()
-{
-	for(std::map<const boost::shared_ptr<const Object>,MantidObject*>::iterator iObjs=mObjects->begin();iObjs!=mObjects->end();iObjs++)
-	{
-		delete (*iObjs).second;
-	}
-	mObjects->clear();
-}
-
-/**
- * This method returns the detector id's in the instrument
- * @param idList :: output a list of the detector id's in the instrument
- */
-void InstrumentActor::getDetectorIDList(std::vector<int>& idList)
-{
-	this->appendObjCompID(idList);
-}
-
-/**
- * This method sets the colors for the detectors, the list order should be the same as the getDetectorIDList output
- * @param list: list of detector colors, this should match the same order the detector id list in the getDetectorIDList
- */
-void InstrumentActor::setDetectorColors(std::vector<boost::shared_ptr<GLColor> >& list)
-{
-  std::vector<boost::shared_ptr<GLColor> >::iterator listItr=list.begin();
-  setInternalDetectorColors(listItr);
-}
-
-/**
- * Redraws the instrument
- */
-void InstrumentActor::refresh()
-{
-	this->redraw();
-	this->draw();
-}
-
-/** 
- * This method returns the detector id corresponding to the input reference color 
- * @param rgb:
- * @return the detector id correspondign to rgb.
- */
-int InstrumentActor::getDetectorIDFromColor(int rgb)
-{
-	if(rgb==0) return -1;
-	return findDetectorIDUsingColor(rgb);
-}
-
-/**
- * This method sets the instrument to render in low resolution. Useful rendering in interaction mode
- */
-void InstrumentActor::setObjectResolutionToLow()
-{
-	for(std::map<const boost::shared_ptr<const Mantid::Geometry::Object>,MantidObject*>::iterator itr=mObjects->begin();itr!=mObjects->end();itr++)
-	{
-		(itr->second)->setResolutionToLow();
-	}
-}
-
-/**
- * This method sets the instrument to render in high resolution.
- */
-void InstrumentActor::setObjectResolutionToHigh()
-{
-	for(std::map<const boost::shared_ptr<const Mantid::Geometry::Object>,MantidObject*>::iterator itr=mObjects->begin();itr!=mObjects->end();itr++)
-	{
-		(itr->second)->setResolutionToHigh();
-	}
-}
+#include "MantidGeometry/IInstrument.h"
+#include "MantidGeometry/V3D.h"
+#include "MantidGeometry/Objects/Object.h"
+#include "MantidGeometry/ICompAssembly.h"
+#include "MantidGeometry/IObjComponent.h"
+#include "MantidKernel/Exception.h"
+#include "MantidObject.h"
+#include "ObjComponentActor.h"
+#include "InstrumentActor.h"
+
+using namespace Mantid::Geometry;
+
+/**
+ * Constructor
+ * @param ins :: Instrument
+ * @param withDisplayList :: true use display list, false use immediate rendering
+ */
+InstrumentActor::InstrumentActor(boost::shared_ptr<Mantid::Geometry::IInstrument> ins, bool withDisplayList):CompAssemblyActor(withDisplayList)
+{
+	mInstrument=ins;
+	mId=mInstrument->getComponentID();
+	mObjects = boost::shared_ptr<std::map<const boost::shared_ptr<const Mantid::Geometry::Object>,MantidObject*> >(new std::map<const boost::shared_ptr<const Mantid::Geometry::Object>,MantidObject*>());
+	initChilds(withDisplayList);
+}
+
+/**
+ * Destructor
+ */
+InstrumentActor::~InstrumentActor()
+{
+	for(std::map<const boost::shared_ptr<const Object>,MantidObject*>::iterator iObjs=mObjects->begin();iObjs!=mObjects->end();iObjs++)
+	{
+		delete (*iObjs).second;
+	}
+	mObjects->clear();
+}
+
+/**
+ * This method returns the detector id's in the instrument
+ * @param idList :: output a list of the detector id's in the instrument
+ */
+void InstrumentActor::getDetectorIDList(std::vector<int>& idList)
+{
+	this->appendObjCompID(idList);
+}
+
+/**
+ * This method sets the colors for the detectors, the list order should be the same as the getDetectorIDList output
+ * @param list: list of detector colors, this should match the same order the detector id list in the getDetectorIDList
+ */
+void InstrumentActor::setDetectorColors(std::vector<boost::shared_ptr<GLColor> >& list)
+{
+  std::vector<boost::shared_ptr<GLColor> >::iterator listItr=list.begin();
+  setInternalDetectorColors(listItr);
+}
+
+/**
+ * Redraws the instrument
+ */
+void InstrumentActor::refresh()
+{
+	this->redraw();
+	this->draw();
+}
+
+/** 
+ * This method returns the detector id corresponding to the input reference color 
+ * @param rgb:
+ * @return the detector id correspondign to rgb.
+ */
+int InstrumentActor::getDetectorIDFromColor(int rgb)
+{
+	if(rgb==0) return -1;
+	return findDetectorIDUsingColor(rgb);
+}
+
+/**
+ * This method sets the instrument to render in low resolution. Useful rendering in interaction mode
+ */
+void InstrumentActor::setObjectResolutionToLow()
+{
+	for(std::map<const boost::shared_ptr<const Mantid::Geometry::Object>,MantidObject*>::iterator itr=mObjects->begin();itr!=mObjects->end();itr++)
+	{
+		(itr->second)->setResolutionToLow();
+	}
+}
+
+/**
+ * This method sets the instrument to render in high resolution.
+ */
+void InstrumentActor::setObjectResolutionToHigh()
+{
+	for(std::map<const boost::shared_ptr<const Mantid::Geometry::Object>,MantidObject*>::iterator itr=mObjects->begin();itr!=mObjects->end();itr++)
+	{
+		(itr->second)->setResolutionToHigh();
+	}
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentActor.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentActor.h
index 711827da0d88cae6d7d51a14de3437a7347b5e61..a17bac64715f9abd86a4015b2225b2d5ea6b7b6e 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentActor.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentActor.h
@@ -1,6 +1,6 @@
-#ifndef INSTRUMENTACTOR_H_
-#define INSTRUMENTACTOR_H_
-#include "CompAssemblyActor.h"
+#ifndef INSTRUMENTACTOR_H_
+#define INSTRUMENTACTOR_H_
+#include "CompAssemblyActor.h"
 /**
   \class  InstrumentActor
   \brief  InstrumentActor class is wrapper actor for the instrument.
@@ -11,7 +11,7 @@
    This class has the implementation for rendering Instrument. it provides the interface for picked ObjComponent and other
    operation for selective rendering of the instrument
 
-  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
+  Copyright &copy; 2007 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
 
   This file is part of Mantid.
 
@@ -29,20 +29,20 @@
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
   File change history is stored at: <https://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-class InstrumentActor : public CompAssemblyActor
-{
-public:
-	InstrumentActor(boost::shared_ptr<Mantid::Geometry::IInstrument> ins, bool withDisplayList); ///< Constructor
-	~InstrumentActor();								   ///< Destructor
-	virtual std::string type()const {return "InstrumentActor";} ///< Type of the GL object
-	void getDetectorIDList(std::vector<int>&);
-	void setDetectorColors(std::vector<boost::shared_ptr<GLColor> >& list);
-	void refresh();
-	int  getDetectorIDFromColor(int rgb);
-	void setObjectResolutionToLow();
-	void setObjectResolutionToHigh();
-};
-
-#endif /*GLTRIANGLE_H_*/
-
+*/
+class InstrumentActor : public CompAssemblyActor
+{
+public:
+	InstrumentActor(boost::shared_ptr<Mantid::Geometry::IInstrument> ins, bool withDisplayList); ///< Constructor
+	~InstrumentActor();								   ///< Destructor
+	virtual std::string type()const {return "InstrumentActor";} ///< Type of the GL object
+	void getDetectorIDList(std::vector<int>&);
+	void setDetectorColors(std::vector<boost::shared_ptr<GLColor> >& list);
+	void refresh();
+	int  getDetectorIDFromColor(int rgb);
+	void setObjectResolutionToLow();
+	void setObjectResolutionToHigh();
+};
+
+#endif /*GLTRIANGLE_H_*/
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeModel.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeModel.cpp
index 83b7587142403db5900ff45144bcd7ce3d3cbd5b..dc367d174dc0d0aab8306b0f70714a23a8bb301d 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeModel.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeModel.cpp
@@ -1,10 +1,10 @@
 #include "InstrumentTreeModel.h"
-#ifdef WIN32
-#include <windows.h>
+#ifdef WIN32
+#include <windows.h>
 #endif
 #include "MantidKernel/Exception.h"
-#include "MantidGeometry/ICompAssembly.h"
-#include "MantidGeometry/Instrument/Instrument.h"
+#include "MantidGeometry/ICompAssembly.h"
+#include "MantidGeometry/Instrument/Instrument.h"
 #include "MantidObject.h"
 
 using Mantid::Geometry::IInstrument;
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeModel.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeModel.h
index b719598995a4e2eac670439492366b3fef45c272..2675a73dbdb27d10bd3575f4877d6bb34e7fbf0b 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeModel.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeModel.h
@@ -1,18 +1,18 @@
-#ifndef INSTRUMENTTREEMODEL_H
-#define INSTRUMENTTREEMODEL_H
-
+#ifndef INSTRUMENTTREEMODEL_H
+#define INSTRUMENTTREEMODEL_H
+
 #include <QAbstractItemModel>
 #include <QModelIndex>
 #include "MantidGeometry/IInstrument.h"
-
-/**
- * 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: ???
+
+/**
+ * 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
@@ -34,4 +34,4 @@ private:
   boost::shared_ptr<Mantid::Geometry::IInstrument> mInstrument; ///< instrument to which the model corresponds to
 };
 
-#endif
+#endif
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeWidget.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeWidget.h
index 11dc03065e9cde6d796aed9b970873cc588ba1dd..bc8d79fb437ddc04e445c42cbe19b5f2a1d60334 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeWidget.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentTreeWidget.h
@@ -1,32 +1,32 @@
-#ifndef INSTRUMENTTREEWIDGET_H
-#define INSTRUMENTTREEWIDGET_H
-
-#include <QTreeView>
-#include "MantidGeometry/IInstrument.h"
-#include "InstrumentTreeModel.h"
-
-
-/** The InstrumentTreeWidget is a tree view
- * of the components of an instrument.
- *
- * Author: ???
- */
-
-class InstrumentTreeWidget:public QTreeView
-{
-  Q_OBJECT
-public:
-  InstrumentTreeWidget(QWidget *w):QTreeView(w), mTreeModel(0) {};
-  void setInstrument(boost::shared_ptr<Mantid::Geometry::IInstrument>);
-  void getSelectedBoundingBox(const QModelIndex& index,double &xmax, double &ymax, double &zmax, double &xmin, double &ymin, double &zmin);
-  Mantid::Geometry::V3D getSamplePos()const;
-  QModelIndex findComponentByName(const QString & name) const;
-  void sendComponentSelectedSignal(QModelIndex index);
-signals:
-  void componentSelected(const Mantid::Geometry::ComponentID);
-private:
-  boost::shared_ptr<Mantid::Geometry::IInstrument> mInstrument;
-  InstrumentTreeModel *mTreeModel;
-};
-
-#endif
+#ifndef INSTRUMENTTREEWIDGET_H
+#define INSTRUMENTTREEWIDGET_H
+
+#include <QTreeView>
+#include "MantidGeometry/IInstrument.h"
+#include "InstrumentTreeModel.h"
+
+
+/** The InstrumentTreeWidget is a tree view
+ * of the components of an instrument.
+ *
+ * Author: ???
+ */
+
+class InstrumentTreeWidget:public QTreeView
+{
+  Q_OBJECT
+public:
+  InstrumentTreeWidget(QWidget *w):QTreeView(w), mTreeModel(0) {};
+  void setInstrument(boost::shared_ptr<Mantid::Geometry::IInstrument>);
+  void getSelectedBoundingBox(const QModelIndex& index,double &xmax, double &ymax, double &zmax, double &xmin, double &ymin, double &zmin);
+  Mantid::Geometry::V3D getSamplePos()const;
+  QModelIndex findComponentByName(const QString & name) const;
+  void sendComponentSelectedSignal(QModelIndex index);
+signals:
+  void componentSelected(const Mantid::Geometry::ComponentID);
+private:
+  boost::shared_ptr<Mantid::Geometry::IInstrument> mInstrument;
+  InstrumentTreeModel *mTreeModel;
+};
+
+#endif
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindow.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindow.cpp
index 4c9b3bdedfbdacf7d297c0f71b3abbb0353c6178..ab1bbe78dc6f840ca175dfa0a7a20264da4fb815 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindow.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/InstrumentWindow.cpp
@@ -1,677 +1,677 @@
-#include "InstrumentWindow.h"
-#include "InstrumentWindowRenderTab.h"
-#include "InstrumentWindowPickTab.h"
-#include "../MantidUI.h"
-#include "../AlgMonitor.h"
-#include "MantidKernel/ConfigService.h"
-#include "MantidAPI/MatrixWorkspace.h"
-#include "Poco/Path.h"
-
-#include <QVBoxLayout>
-#include <QHBoxLayout>
-#include <QFrame>
-#include <QMenu>
-#include <QMessageBox>
-#include <QFileDialog>
-#include <QString>
-#include <QSplitter>
-#include <QDoubleValidator>
-#include <QRadioButton>
-#include <QGroupBox>
-#include <QGridLayout>
-#include <QComboBox>
-#include <QSettings>
-#include <QFileInfo>
-#include <QColorDialog>
-#include <QLineEdit>
-#include <QCheckBox>
-#include <QImageWriter>
-
-#include <numeric>
-
-using namespace Mantid::API;
-using namespace Mantid::Geometry;
-
-/**
- * Constructor.
- */
-InstrumentWindow::InstrumentWindow(const QString& label, ApplicationWindow *app , const QString& name , Qt::WFlags f ): 
-  MdiSubWindow(label, app, name, f), WorkspaceObserver(), mViewChanged(false),m_blocked(false)
-{
-  m_savedialog_dir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory"));
-
-  setFocusPolicy(Qt::StrongFocus);
-  setFocus();
-  QFrame *frame = new QFrame();
-  QVBoxLayout* mainLayout = new QVBoxLayout;
-  QSplitter* controlPanelLayout = new QSplitter(Qt::Horizontal);
-
-  //Add Tab control panel and Render window
-  mControlsTab = new QTabWidget(this,0);
-  controlPanelLayout->addWidget(mControlsTab);
-  controlPanelLayout->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
-
-  // Create the display widget
-  mInstrumentDisplay = new Instrument3DWidget(this);
-  controlPanelLayout->addWidget(mInstrumentDisplay);
-  mainLayout->addWidget(controlPanelLayout);
-
-  //Set the mouse/keyboard operation info
-  mInteractionInfo = new QLabel();
-  mainLayout->addWidget(mInteractionInfo);
-  connect(mInstrumentDisplay, SIGNAL(actionDetectorHighlighted(const Instrument3DWidget::DetInfo &)),this,SLOT(detectorHighlighted(const Instrument3DWidget::DetInfo &)));
-  connect(mInstrumentDisplay, SIGNAL(detectorsSelected()), this, SLOT(showPickOptions()));
-
-  // Load settings is called after mInstrumentDisplay is created but before m_renderTab
-  loadSettings();
-
-  //Render Controls
-  m_renderTab = new InstrumentWindowRenderTab(this);
-  mControlsTab->addTab( m_renderTab, QString("Render"));
-  
-  // Pick controls
-  m_pickTab = new InstrumentWindowPickTab(this);
-  mControlsTab->addTab( m_pickTab, QString("Pick"));
-
-  // Instrument tree controls
-  QFrame* instrumentTree=createInstrumentTreeTab(mControlsTab);
-  mControlsTab->addTab( instrumentTree, QString("Instrument Tree"));
-
-  connect(mControlsTab,SIGNAL(currentChanged(int)),this,SLOT(tabChanged(int)));
-
-  //Set the main frame to the window
-  frame->setLayout(mainLayout);
-  setWidget(frame);
-
-  // Init actions
-  mInfoAction = new QAction(tr("&Details"), this);
-  connect(mInfoAction,SIGNAL(triggered()),this,SLOT(spectraInfoDialog()));
-
-  mPlotAction = new QAction(tr("&Plot Spectra"), this);
-  connect(mPlotAction,SIGNAL(triggered()),this,SLOT(plotSelectedSpectra()));
-
-  mDetTableAction = new QAction(tr("&Extract Data"), this);
-  connect(mDetTableAction, SIGNAL(triggered()), this, SLOT(showDetectorTable()));
-
-  mGroupDetsAction = new QAction(tr("&Group"), this);
-  connect(mGroupDetsAction, SIGNAL(triggered()), this, SLOT(groupDetectors()));
-
-  mMaskDetsAction = new QAction(tr("&Mask"), this);
-  connect(mMaskDetsAction, SIGNAL(triggered()), this, SLOT(maskDetectors()));
-
-  askOnCloseEvent(app->confirmCloseInstrWindow);
-
-  setAttribute(Qt::WA_DeleteOnClose);
-
-  // Watch for the deletion of the associated workspace
-  observeDelete();
-  observeAfterReplace();
-  observeADSClear();
-
-  connect(app->mantidUI->getAlgMinitor(),SIGNAL(algorithmStarted(void*)),this,SLOT(block()));
-  connect(app->mantidUI->getAlgMinitor(),SIGNAL(allAlgorithmsStopped()),this,SLOT(unblock()));
-
-  const int windowWidth = 600;
-  const int tabsSize = windowWidth / 3;
-  QList<int> sizes;
-  sizes << tabsSize << windowWidth - tabsSize;
-  controlPanelLayout->setSizes(sizes);
-  controlPanelLayout->setStretchFactor(0,0);
-  controlPanelLayout->setStretchFactor(1,1);
-
-  resize(windowWidth,650);
-
-  tabChanged(0);
-}
-
-/**
-  * Connected to QTabWidget::currentChanged signal
-  */
-void InstrumentWindow::tabChanged(int i)
-{
-  QString text;
-  if (i == 1) 
-  {
-    mInstrumentDisplay->setInteractionModePick();
-    text = "Move cursor over instrument to see detector information.";
-  }
-  else
-  {
-    mInstrumentDisplay->setInteractionModeNormal();
-    if (mInstrumentDisplay->getRenderMode() == GL3DWidget::FULL3D)
-    {
-      text = tr("Mouse Button: Left -- Rotation, Middle -- Zoom, Right -- Translate\nKeyboard: NumKeys -- Rotation, PageUp/Down -- Zoom, ArrowKeys -- Translate");
-      if( mInstrumentDisplay->areAxesOn() )
-      {
-        text += "\nAxes: X = Red; Y = Green; Z = Blue";
-      }
-    }
-    else
-    {
-      text = "Left mouse click and drag to zoom in.\n";
-      text += "Right mouse click to zoom out.";
-    }
-  }
-  setInfoText(text);
-
-}
-
-/**
- * Change color map button slot. This provides the file dialog box to select colormap or sets it directly a string is provided
- */
-void InstrumentWindow::changeColormap(const QString &filename)
-{
-  QString fileselection;
-  //Use a file dialog if no parameter is passed
-  if( filename.isEmpty() )
-  {
-    fileselection = QFileDialog::getOpenFileName(this, tr("Pick a Colormap"), 
-						 QFileInfo(mCurrentColorMap).absoluteFilePath(),
-						 tr("Colormaps (*.map *.MAP)"));
-    // User cancelled if filename is still empty
-    if( fileselection.isEmpty() ) return;
-  }
-  else
-  {
-    fileselection = QFileInfo(filename).absoluteFilePath();
-    if( !QFileInfo(fileselection).exists() ) return;
-  }
-  
-  if( fileselection == mCurrentColorMap ) return;
-
-  mCurrentColorMap = fileselection;
-  mInstrumentDisplay->mutableColorMap().loadMap(mCurrentColorMap);
-  if( this->isVisible() )
-  {
-    m_renderTab->setupColorBarScaling();
-    mInstrumentDisplay->updateColorsForNewMap();
-  }
-}
-
-void InstrumentWindow::showPickOptions()
-{
-  QMenu context(mInstrumentDisplay);
-  
-  context.addAction(mInfoAction);
-  context.addAction(mPlotAction);
-  context.addAction(mDetTableAction);
-
-  if( mInstrumentDisplay->getSelectedWorkspaceIndices().size() > 1 )
-  {
-    context.insertSeparator();
-    context.addAction(mGroupDetsAction);
-    context.addAction(mMaskDetsAction);
-  }
-
-  context.exec(QCursor::pos());
-  mInstrumentDisplay->hidePickBox();
-}
-
-/**
- * This is the detector information slot executed when a detector is highlighted by moving mouse in graphics widget.
+#include "InstrumentWindow.h"
+#include "InstrumentWindowRenderTab.h"
+#include "InstrumentWindowPickTab.h"
+#include "../MantidUI.h"
+#include "../AlgMonitor.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidAPI/MatrixWorkspace.h"
+#include "Poco/Path.h"
+
+#include <QVBoxLayout>
+#include <QHBoxLayout>
+#include <QFrame>
+#include <QMenu>
+#include <QMessageBox>
+#include <QFileDialog>
+#include <QString>
+#include <QSplitter>
+#include <QDoubleValidator>
+#include <QRadioButton>
+#include <QGroupBox>
+#include <QGridLayout>
+#include <QComboBox>
+#include <QSettings>
+#include <QFileInfo>
+#include <QColorDialog>
+#include <QLineEdit>
+#include <QCheckBox>
+#include <QImageWriter>
+
+#include <numeric>
+
+using namespace Mantid::API;
+using namespace Mantid::Geometry;
+
+/**
+ * Constructor.
+ */
+InstrumentWindow::InstrumentWindow(const QString& label, ApplicationWindow *app , const QString& name , Qt::WFlags f ): 
+  MdiSubWindow(label, app, name, f), WorkspaceObserver(), mViewChanged(false),m_blocked(false)
+{
+  m_savedialog_dir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory"));
+
+  setFocusPolicy(Qt::StrongFocus);
+  setFocus();
+  QFrame *frame = new QFrame();
+  QVBoxLayout* mainLayout = new QVBoxLayout;
+  QSplitter* controlPanelLayout = new QSplitter(Qt::Horizontal);
+
+  //Add Tab control panel and Render window
+  mControlsTab = new QTabWidget(this,0);
+  controlPanelLayout->addWidget(mControlsTab);
+  controlPanelLayout->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
+
+  // Create the display widget
+  mInstrumentDisplay = new Instrument3DWidget(this);
+  controlPanelLayout->addWidget(mInstrumentDisplay);
+  mainLayout->addWidget(controlPanelLayout);
+
+  //Set the mouse/keyboard operation info
+  mInteractionInfo = new QLabel();
+  mainLayout->addWidget(mInteractionInfo);
+  connect(mInstrumentDisplay, SIGNAL(actionDetectorHighlighted(const Instrument3DWidget::DetInfo &)),this,SLOT(detectorHighlighted(const Instrument3DWidget::DetInfo &)));
+  connect(mInstrumentDisplay, SIGNAL(detectorsSelected()), this, SLOT(showPickOptions()));
+
+  // Load settings is called after mInstrumentDisplay is created but before m_renderTab
+  loadSettings();
+
+  //Render Controls
+  m_renderTab = new InstrumentWindowRenderTab(this);
+  mControlsTab->addTab( m_renderTab, QString("Render"));
+  
+  // Pick controls
+  m_pickTab = new InstrumentWindowPickTab(this);
+  mControlsTab->addTab( m_pickTab, QString("Pick"));
+
+  // Instrument tree controls
+  QFrame* instrumentTree=createInstrumentTreeTab(mControlsTab);
+  mControlsTab->addTab( instrumentTree, QString("Instrument Tree"));
+
+  connect(mControlsTab,SIGNAL(currentChanged(int)),this,SLOT(tabChanged(int)));
+
+  //Set the main frame to the window
+  frame->setLayout(mainLayout);
+  setWidget(frame);
+
+  // Init actions
+  mInfoAction = new QAction(tr("&Details"), this);
+  connect(mInfoAction,SIGNAL(triggered()),this,SLOT(spectraInfoDialog()));
+
+  mPlotAction = new QAction(tr("&Plot Spectra"), this);
+  connect(mPlotAction,SIGNAL(triggered()),this,SLOT(plotSelectedSpectra()));
+
+  mDetTableAction = new QAction(tr("&Extract Data"), this);
+  connect(mDetTableAction, SIGNAL(triggered()), this, SLOT(showDetectorTable()));
+
+  mGroupDetsAction = new QAction(tr("&Group"), this);
+  connect(mGroupDetsAction, SIGNAL(triggered()), this, SLOT(groupDetectors()));
+
+  mMaskDetsAction = new QAction(tr("&Mask"), this);
+  connect(mMaskDetsAction, SIGNAL(triggered()), this, SLOT(maskDetectors()));
+
+  askOnCloseEvent(app->confirmCloseInstrWindow);
+
+  setAttribute(Qt::WA_DeleteOnClose);
+
+  // Watch for the deletion of the associated workspace
+  observeDelete();
+  observeAfterReplace();
+  observeADSClear();
+
+  connect(app->mantidUI->getAlgMinitor(),SIGNAL(algorithmStarted(void*)),this,SLOT(block()));
+  connect(app->mantidUI->getAlgMinitor(),SIGNAL(allAlgorithmsStopped()),this,SLOT(unblock()));
+
+  const int windowWidth = 600;
+  const int tabsSize = windowWidth / 3;
+  QList<int> sizes;
+  sizes << tabsSize << windowWidth - tabsSize;
+  controlPanelLayout->setSizes(sizes);
+  controlPanelLayout->setStretchFactor(0,0);
+  controlPanelLayout->setStretchFactor(1,1);
+
+  resize(windowWidth,650);
+
+  tabChanged(0);
+}
+
+/**
+  * Connected to QTabWidget::currentChanged signal
+  */
+void InstrumentWindow::tabChanged(int i)
+{
+  QString text;
+  if (i == 1) 
+  {
+    mInstrumentDisplay->setInteractionModePick();
+    text = "Move cursor over instrument to see detector information.";
+  }
+  else
+  {
+    mInstrumentDisplay->setInteractionModeNormal();
+    if (mInstrumentDisplay->getRenderMode() == GL3DWidget::FULL3D)
+    {
+      text = tr("Mouse Button: Left -- Rotation, Middle -- Zoom, Right -- Translate\nKeyboard: NumKeys -- Rotation, PageUp/Down -- Zoom, ArrowKeys -- Translate");
+      if( mInstrumentDisplay->areAxesOn() )
+      {
+        text += "\nAxes: X = Red; Y = Green; Z = Blue";
+      }
+    }
+    else
+    {
+      text = "Left mouse click and drag to zoom in.\n";
+      text += "Right mouse click to zoom out.";
+    }
+  }
+  setInfoText(text);
+
+}
+
+/**
+ * Change color map button slot. This provides the file dialog box to select colormap or sets it directly a string is provided
+ */
+void InstrumentWindow::changeColormap(const QString &filename)
+{
+  QString fileselection;
+  //Use a file dialog if no parameter is passed
+  if( filename.isEmpty() )
+  {
+    fileselection = QFileDialog::getOpenFileName(this, tr("Pick a Colormap"), 
+						 QFileInfo(mCurrentColorMap).absoluteFilePath(),
+						 tr("Colormaps (*.map *.MAP)"));
+    // User cancelled if filename is still empty
+    if( fileselection.isEmpty() ) return;
+  }
+  else
+  {
+    fileselection = QFileInfo(filename).absoluteFilePath();
+    if( !QFileInfo(fileselection).exists() ) return;
+  }
+  
+  if( fileselection == mCurrentColorMap ) return;
+
+  mCurrentColorMap = fileselection;
+  mInstrumentDisplay->mutableColorMap().loadMap(mCurrentColorMap);
+  if( this->isVisible() )
+  {
+    m_renderTab->setupColorBarScaling();
+    mInstrumentDisplay->updateColorsForNewMap();
+  }
+}
+
+void InstrumentWindow::showPickOptions()
+{
+  QMenu context(mInstrumentDisplay);
+  
+  context.addAction(mInfoAction);
+  context.addAction(mPlotAction);
+  context.addAction(mDetTableAction);
+
+  if( mInstrumentDisplay->getSelectedWorkspaceIndices().size() > 1 )
+  {
+    context.insertSeparator();
+    context.addAction(mGroupDetsAction);
+    context.addAction(mMaskDetsAction);
+  }
+
+  context.exec(QCursor::pos());
+  mInstrumentDisplay->hidePickBox();
+}
+
+/**
+ * This is the detector information slot executed when a detector is highlighted by moving mouse in graphics widget.
  * @param information :: about the detector that is at the location of the users mouse pointer
- */
-void InstrumentWindow::detectorHighlighted(const Instrument3DWidget::DetInfo & cursorPos)
-{
-  mInteractionInfo->setText(cursorPos.display());
-  m_pickTab->updatePick(cursorPos);
-}
-/**
- * This is slot for the dialog to appear when a detector is picked and the info menu is selected
- */
-void InstrumentWindow::spectraInfoDialog()
-{
-  QString info;
-  const std::vector<int> & det_ids = mInstrumentDisplay->getSelectedDetectorIDs();
-  const std::vector<int> & wksp_indices = mInstrumentDisplay->getSelectedWorkspaceIndices();
-  const int ndets = det_ids.size();
-  if( ndets == 1 )
-  {
-    info = QString("Workspace index: %1\nDetector ID: %2").arg(QString::number(wksp_indices.front()),QString::number(det_ids.front()));
-  }
-  else
-  {
-    info = QString("Index list size: %1\nDetector list size: %2").arg(QString::number(wksp_indices.size()), QString::number(ndets));
-  }
-  QMessageBox::information(this,tr("Detector/Spectrum Information"), info, 
-			   QMessageBox::Ok|QMessageBox::Default, QMessageBox::NoButton, QMessageBox::NoButton);
-}
-
-/**
- *   Sends a signal to plot the selected spectrum.
- */
-void InstrumentWindow::plotSelectedSpectra()
-{
-  std::set<int> indices(mInstrumentDisplay->getSelectedWorkspaceIndices().begin(), mInstrumentDisplay->getSelectedWorkspaceIndices().end());
-  if (indices.count(-1) > 0)
-  {
-    indices.erase(-1);
-  }
-  emit plotSpectra( mInstrumentDisplay->getWorkspaceName(), indices);
-}
-
-/**
- * Show detector table
- */
-void InstrumentWindow::showDetectorTable()
-{
-  emit createDetectorTable(mInstrumentDisplay->getWorkspaceName(), mInstrumentDisplay->getSelectedWorkspaceIndices(), true);
-}
-
-QString InstrumentWindow::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;
-}
-/**
- * Group selected detectors
- */
-void InstrumentWindow::groupDetectors()
-{
-  const std::vector<int> & wksp_indices = mInstrumentDisplay->getSelectedWorkspaceIndices();
-  const std::vector<int> & det_ids = mInstrumentDisplay->getSelectedDetectorIDs();
-  QString inputWS = mInstrumentDisplay->getWorkspaceName();
-  QString outputWS = confirmDetectorOperation("grouped", inputWS, static_cast<int>(det_ids.size()));
-  if( outputWS.isEmpty() ) return;
-  QString param_list = "InputWorkspace=%1;OutputWorkspace=%2;WorkspaceIndexList=%3;KeepUngroupedSpectra=1";
-  emit execMantidAlgorithm("GroupDetectors",
-			   param_list.arg(inputWS, outputWS, asString(wksp_indices))
-			   );
-}
-
-/**
- * Mask selected detectors
- */
-void InstrumentWindow::maskDetectors()
-{
-  const std::vector<int> & wksp_indices = mInstrumentDisplay->getSelectedWorkspaceIndices();
-
-  //Following variable is unused:
-  //const std::vector<int> & det_ids = mInstrumentDisplay->getSelectedDetectorIDs();
-
-  QString inputWS = mInstrumentDisplay->getWorkspaceName();
-  // Masking can only replace the input workspace so no need to ask for confirmation
-  QString param_list = "Workspace=%1;WorkspaceIndexList=%2";
-  QString indices = asString(mInstrumentDisplay->getSelectedWorkspaceIndices());
-  emit execMantidAlgorithm("MaskDetectors",param_list.arg(inputWS, asString(wksp_indices)));
-}
-
-/**
- * Convert a list of integers to a comma separated string of numbers 
- */
-QString InstrumentWindow::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;
-}
-
-
-/**
- * Destructor
- */
-InstrumentWindow::~InstrumentWindow()
-{
-  saveSettings();
-  delete mInstrumentDisplay;
-}
-
-/**
- * This method sets the workspace name for the Instrument
- */
-void InstrumentWindow::setWorkspaceName(std::string wsName)
-{
-  mWorkspaceName = wsName;
-}
-
-void InstrumentWindow::updateWindow()
-{
-  if( mWorkspaceName.empty() ) return;
-
-  bool resultError=false;
-
-  MatrixWorkspace_sptr workspace = boost::dynamic_pointer_cast<MatrixWorkspace>(AnalysisDataService::Instance().retrieve(mWorkspaceName));
-  if( !workspace.get() ) return;
-
-  try
-  {
-    renderInstrument(workspace.get());
-  }
-  catch(...)
-  {
-    mInstrumentDisplay->resetWidget();
-    mInstrumentDisplay->setSlowRendering();
-    resultError = true;
-  }
-  if(resultError)
-  {
-    QMessageBox::critical(this,"Mantid -- Error","Trying Slow Rendering");
-    try
-    {
-      renderInstrument(workspace.get());
-    }
-    catch(std::bad_alloc &)
-    {
-      QMessageBox::critical(this,"Mantid -- Error","not enough memory to display this instrument");
-      mInstrumentDisplay->resetWidget();
-    }
-  }
-
-  connect(mInstrumentTree->selectionModel(),SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
-	  this, SLOT(componentSelected(const QItemSelection&, const QItemSelection&)));
-}
-
-void InstrumentWindow::renderInstrument(Mantid::API::MatrixWorkspace* workspace)
-{
-  mInstrumentDisplay->setWorkspace(QString::fromStdString(mWorkspaceName));
-  // Need to check if the values have already been set for the range
-  if( !mInstrumentDisplay->dataMinValueEdited() )
-  {
-    m_renderTab->setMinValue(mInstrumentDisplay->getDataMinValue(),false);
-  }
-  if( !mInstrumentDisplay->dataMaxValueEdited() )
-  {
-    m_renderTab->setMaxValue(mInstrumentDisplay->getDataMaxValue(),false);
-  }
-  
-  // Setup the colour map details
-  GraphOptions::ScaleType type = m_renderTab->getScaleType();
-  mInstrumentDisplay->mutableColorMap().changeScaleType(type);
-  m_renderTab->setupColorBarScaling();
-  
-  mInstrumentDisplay->resetUnwrappedViews();
-  // Ensure the 3D display is up-to-date
-  mInstrumentDisplay->update();
-  // Populate the instrument tree
-  mInstrumentTree->setInstrument(workspace->getInstrument());
-
-  if ( ! mViewChanged )
-  {
-    // set the default view, the axis that the instrument is be viewed from initially can be set in the instrument definition and there is always a value in the Instrument
-    QString axisName = QString::fromStdString(
-    workspace->getInstrument()->getDefaultAxis());
-    m_renderTab->setAxis(axisName);
-    // this was an automatic view change, only flag that the view changed if the user initiated the change
-    mViewChanged = false;
-  }
-
-}
-
-/// Set a maximum and minimum for the colour map range
-void InstrumentWindow::setColorMapRange(double minValue, double maxValue)
-{
-  setColorMapMinValue(minValue);
-  setColorMapMaxValue(maxValue);
-}
-
-/// Set the minimum value of the colour map
-void InstrumentWindow::setColorMapMinValue(double minValue)
-{
-  m_renderTab->setMinValue(minValue);
-}
-
-/// Set the maximumu value of the colour map
-void InstrumentWindow::setColorMapMaxValue(double maxValue)
-{
-  m_renderTab->setMaxValue(maxValue);
-}
-
-void InstrumentWindow::setDataMappingIntegral(double minValue,double maxValue,bool entireRange)
-{
-  mInstrumentDisplay->setDataMappingIntegral(minValue, maxValue, entireRange);
-}
-
-/**
- * This is the callback for the combo box that selects the view direction
- */
-void InstrumentWindow::setViewDirection(const QString& input)
-{
-	if(input.compare("X+")==0)
-	{
-		mInstrumentDisplay->setViewDirectionXPositive();
-	}
-	else if(input.compare("X-")==0)
-	{
-		mInstrumentDisplay->setViewDirectionXNegative();
-	}
-	else if(input.compare("Y+")==0)
-	{
-		mInstrumentDisplay->setViewDirectionYPositive();
-	}
-	else if(input.compare("Y-")==0)
-	{
-		mInstrumentDisplay->setViewDirectionYNegative();
-	}
-	else if(input.compare("Z+")==0)
-	{
-		mInstrumentDisplay->setViewDirectionZPositive();
-	}
-	else if(input.compare("Z-")==0)
-	{
-		mInstrumentDisplay->setViewDirectionZNegative();
-	}
-
-  mViewChanged = true;
-}
-
-/**
- * For the scripting API
- */
-void InstrumentWindow::selectComponent(const QString & name)
-{
-  QModelIndex component = mInstrumentTree->findComponentByName(name);
-  if( !component.isValid() ) return;
-
-  mInstrumentTree->scrollTo(component, QAbstractItemView::EnsureVisible );
-  mInstrumentTree->selectionModel()->select(component, QItemSelectionModel::Select);
-}
-
-/**
- * Set the scale type programmatically
+ */
+void InstrumentWindow::detectorHighlighted(const Instrument3DWidget::DetInfo & cursorPos)
+{
+  mInteractionInfo->setText(cursorPos.display());
+  m_pickTab->updatePick(cursorPos);
+}
+/**
+ * This is slot for the dialog to appear when a detector is picked and the info menu is selected
+ */
+void InstrumentWindow::spectraInfoDialog()
+{
+  QString info;
+  const std::vector<int> & det_ids = mInstrumentDisplay->getSelectedDetectorIDs();
+  const std::vector<int> & wksp_indices = mInstrumentDisplay->getSelectedWorkspaceIndices();
+  const int ndets = det_ids.size();
+  if( ndets == 1 )
+  {
+    info = QString("Workspace index: %1\nDetector ID: %2").arg(QString::number(wksp_indices.front()),QString::number(det_ids.front()));
+  }
+  else
+  {
+    info = QString("Index list size: %1\nDetector list size: %2").arg(QString::number(wksp_indices.size()), QString::number(ndets));
+  }
+  QMessageBox::information(this,tr("Detector/Spectrum Information"), info, 
+			   QMessageBox::Ok|QMessageBox::Default, QMessageBox::NoButton, QMessageBox::NoButton);
+}
+
+/**
+ *   Sends a signal to plot the selected spectrum.
+ */
+void InstrumentWindow::plotSelectedSpectra()
+{
+  std::set<int> indices(mInstrumentDisplay->getSelectedWorkspaceIndices().begin(), mInstrumentDisplay->getSelectedWorkspaceIndices().end());
+  if (indices.count(-1) > 0)
+  {
+    indices.erase(-1);
+  }
+  emit plotSpectra( mInstrumentDisplay->getWorkspaceName(), indices);
+}
+
+/**
+ * Show detector table
+ */
+void InstrumentWindow::showDetectorTable()
+{
+  emit createDetectorTable(mInstrumentDisplay->getWorkspaceName(), mInstrumentDisplay->getSelectedWorkspaceIndices(), true);
+}
+
+QString InstrumentWindow::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;
+}
+/**
+ * Group selected detectors
+ */
+void InstrumentWindow::groupDetectors()
+{
+  const std::vector<int> & wksp_indices = mInstrumentDisplay->getSelectedWorkspaceIndices();
+  const std::vector<int> & det_ids = mInstrumentDisplay->getSelectedDetectorIDs();
+  QString inputWS = mInstrumentDisplay->getWorkspaceName();
+  QString outputWS = confirmDetectorOperation("grouped", inputWS, static_cast<int>(det_ids.size()));
+  if( outputWS.isEmpty() ) return;
+  QString param_list = "InputWorkspace=%1;OutputWorkspace=%2;WorkspaceIndexList=%3;KeepUngroupedSpectra=1";
+  emit execMantidAlgorithm("GroupDetectors",
+			   param_list.arg(inputWS, outputWS, asString(wksp_indices))
+			   );
+}
+
+/**
+ * Mask selected detectors
+ */
+void InstrumentWindow::maskDetectors()
+{
+  const std::vector<int> & wksp_indices = mInstrumentDisplay->getSelectedWorkspaceIndices();
+
+  //Following variable is unused:
+  //const std::vector<int> & det_ids = mInstrumentDisplay->getSelectedDetectorIDs();
+
+  QString inputWS = mInstrumentDisplay->getWorkspaceName();
+  // Masking can only replace the input workspace so no need to ask for confirmation
+  QString param_list = "Workspace=%1;WorkspaceIndexList=%2";
+  QString indices = asString(mInstrumentDisplay->getSelectedWorkspaceIndices());
+  emit execMantidAlgorithm("MaskDetectors",param_list.arg(inputWS, asString(wksp_indices)));
+}
+
+/**
+ * Convert a list of integers to a comma separated string of numbers 
+ */
+QString InstrumentWindow::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;
+}
+
+
+/**
+ * Destructor
+ */
+InstrumentWindow::~InstrumentWindow()
+{
+  saveSettings();
+  delete mInstrumentDisplay;
+}
+
+/**
+ * This method sets the workspace name for the Instrument
+ */
+void InstrumentWindow::setWorkspaceName(std::string wsName)
+{
+  mWorkspaceName = wsName;
+}
+
+void InstrumentWindow::updateWindow()
+{
+  if( mWorkspaceName.empty() ) return;
+
+  bool resultError=false;
+
+  MatrixWorkspace_sptr workspace = boost::dynamic_pointer_cast<MatrixWorkspace>(AnalysisDataService::Instance().retrieve(mWorkspaceName));
+  if( !workspace.get() ) return;
+
+  try
+  {
+    renderInstrument(workspace.get());
+  }
+  catch(...)
+  {
+    mInstrumentDisplay->resetWidget();
+    mInstrumentDisplay->setSlowRendering();
+    resultError = true;
+  }
+  if(resultError)
+  {
+    QMessageBox::critical(this,"Mantid -- Error","Trying Slow Rendering");
+    try
+    {
+      renderInstrument(workspace.get());
+    }
+    catch(std::bad_alloc &)
+    {
+      QMessageBox::critical(this,"Mantid -- Error","not enough memory to display this instrument");
+      mInstrumentDisplay->resetWidget();
+    }
+  }
+
+  connect(mInstrumentTree->selectionModel(),SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
+	  this, SLOT(componentSelected(const QItemSelection&, const QItemSelection&)));
+}
+
+void InstrumentWindow::renderInstrument(Mantid::API::MatrixWorkspace* workspace)
+{
+  mInstrumentDisplay->setWorkspace(QString::fromStdString(mWorkspaceName));
+  // Need to check if the values have already been set for the range
+  if( !mInstrumentDisplay->dataMinValueEdited() )
+  {
+    m_renderTab->setMinValue(mInstrumentDisplay->getDataMinValue(),false);
+  }
+  if( !mInstrumentDisplay->dataMaxValueEdited() )
+  {
+    m_renderTab->setMaxValue(mInstrumentDisplay->getDataMaxValue(),false);
+  }
+  
+  // Setup the colour map details
+  GraphOptions::ScaleType type = m_renderTab->getScaleType();
+  mInstrumentDisplay->mutableColorMap().changeScaleType(type);
+  m_renderTab->setupColorBarScaling();
+  
+  mInstrumentDisplay->resetUnwrappedViews();
+  // Ensure the 3D display is up-to-date
+  mInstrumentDisplay->update();
+  // Populate the instrument tree
+  mInstrumentTree->setInstrument(workspace->getInstrument());
+
+  if ( ! mViewChanged )
+  {
+    // set the default view, the axis that the instrument is be viewed from initially can be set in the instrument definition and there is always a value in the Instrument
+    QString axisName = QString::fromStdString(
+    workspace->getInstrument()->getDefaultAxis());
+    m_renderTab->setAxis(axisName);
+    // this was an automatic view change, only flag that the view changed if the user initiated the change
+    mViewChanged = false;
+  }
+
+}
+
+/// Set a maximum and minimum for the colour map range
+void InstrumentWindow::setColorMapRange(double minValue, double maxValue)
+{
+  setColorMapMinValue(minValue);
+  setColorMapMaxValue(maxValue);
+}
+
+/// Set the minimum value of the colour map
+void InstrumentWindow::setColorMapMinValue(double minValue)
+{
+  m_renderTab->setMinValue(minValue);
+}
+
+/// Set the maximumu value of the colour map
+void InstrumentWindow::setColorMapMaxValue(double maxValue)
+{
+  m_renderTab->setMaxValue(maxValue);
+}
+
+void InstrumentWindow::setDataMappingIntegral(double minValue,double maxValue,bool entireRange)
+{
+  mInstrumentDisplay->setDataMappingIntegral(minValue, maxValue, entireRange);
+}
+
+/**
+ * This is the callback for the combo box that selects the view direction
+ */
+void InstrumentWindow::setViewDirection(const QString& input)
+{
+	if(input.compare("X+")==0)
+	{
+		mInstrumentDisplay->setViewDirectionXPositive();
+	}
+	else if(input.compare("X-")==0)
+	{
+		mInstrumentDisplay->setViewDirectionXNegative();
+	}
+	else if(input.compare("Y+")==0)
+	{
+		mInstrumentDisplay->setViewDirectionYPositive();
+	}
+	else if(input.compare("Y-")==0)
+	{
+		mInstrumentDisplay->setViewDirectionYNegative();
+	}
+	else if(input.compare("Z+")==0)
+	{
+		mInstrumentDisplay->setViewDirectionZPositive();
+	}
+	else if(input.compare("Z-")==0)
+	{
+		mInstrumentDisplay->setViewDirectionZNegative();
+	}
+
+  mViewChanged = true;
+}
+
+/**
+ * For the scripting API
+ */
+void InstrumentWindow::selectComponent(const QString & name)
+{
+  QModelIndex component = mInstrumentTree->findComponentByName(name);
+  if( !component.isValid() ) return;
+
+  mInstrumentTree->scrollTo(component, QAbstractItemView::EnsureVisible );
+  mInstrumentTree->selectionModel()->select(component, QItemSelectionModel::Select);
+}
+
+/**
+ * Set the scale type programmatically
  * @param type :: The scale choice
- */
-void InstrumentWindow::setScaleType(GraphOptions::ScaleType type)
-{
-  m_renderTab->setScaleType(type);
-}
-
-/// A slot for the mouse selection
-void InstrumentWindow::componentSelected(const QItemSelection & selected, const QItemSelection &)
-{
-  QModelIndexList items = selected.indexes();
-  if( items.isEmpty() ) return;
-
-  if (mInstrumentDisplay->getRenderMode() == GL3DWidget::FULL3D)
-  {
-    double xmax(0.), xmin(0.), ymax(0.), ymin(0.), zmax(0.), zmin(0.);
-    mInstrumentTree->getSelectedBoundingBox(items.first(), xmax, ymax, zmax, xmin, ymin, zmin);
-    V3D pos = mInstrumentTree->getSamplePos();
-    mInstrumentDisplay->setView(pos, xmax, ymax, zmax, xmin, ymin, zmin);
-  }
-  else
-  {
-    mInstrumentTree->sendComponentSelectedSignal(items.first());
-  }
-
-}
-
-/**
- * This method opens a color dialog to pick the background color,
- * and then sets it.
- */
-void InstrumentWindow::pickBackgroundColor()
-{
-	QColor color = QColorDialog::getColor(Qt::green,this);
-	mInstrumentDisplay->setBackgroundColor(color);
-}
-
-void InstrumentWindow::saveImage()
-{
-  QList<QByteArray> formats = QImageWriter::supportedImageFormats();
-  QListIterator<QByteArray> itr(formats);
-  QString filter("");
-  while( itr.hasNext() )
-  {
-    filter += "*." + itr.next();
-    if( itr.hasNext() )
-    {
-      filter += ";;";
-    }
-  }
-  QString selectedFilter = "*.png";
-  QString filename = QFileDialog::getSaveFileName(this, "Save image ...", m_savedialog_dir, filter, &selectedFilter);
-
-  // If its empty, they cancelled the dialog
-  if( filename.isEmpty() ) return;
-  
-  //Save the directory used
-  QFileInfo finfo(filename);
-  m_savedialog_dir = finfo.dir().path();
-
-  QString ext = finfo.completeSuffix();
-  if( ext.isEmpty() )
-  {
-    filename += selectedFilter.section("*", 1);
-    ext = QFileInfo(filename).completeSuffix();
-  }
-  else
-  {
-    QStringList extlist = filter.split(";;");
-    if( !extlist.contains("*." + ext) )
-    {
-      QMessageBox::warning(this, "MantidPlot", "Unsupported file extension, please use one from the supported list.");
-      return;
-    }
-  }
-  
-  mInstrumentDisplay->saveToFile(filename);
-}
-
-/**
- * Update the text display that informs the user of the current mode and details about it
- */
-void InstrumentWindow::setInfoText(const QString& text)
-{
- // if(mInstrumentDisplay->getInteractionMode() == Instrument3DWidget::PickMode)
-	//{
- //   text = tr("Mouse Button: Left -- Rotation, Middle -- Zoom, Right -- Translate\nKeyboard: NumKeys -- Rotation, PageUp/Down -- Zoom, ArrowKeys -- Translate");
- //   if( mInstrumentDisplay->areAxesOn() )
- //   {
- //     text += "\nAxes: X = Red; Y = Green; Z = Blue";
- //   }
- // }
- // else
- // {
- //  text = tr("Use Mouse Left Button to Pick an detector\n Click on 'Normal' button to get into interactive mode");
- // }
-  mInteractionInfo->setText(text);
-}
-
-/**
- * This method loads the setting from QSettings
- */
-void InstrumentWindow::loadSettings()
-{
-  //Load Color
-  QSettings settings;
-  settings.beginGroup("Mantid/InstrumentWindow");
-  
-  // Background colour
-  mInstrumentDisplay->setBackgroundColor(settings.value("BackgroundColor",QColor(0,0,0,1.0)).value<QColor>());
-  
-  //Load Colormap. If the file is invalid the default stored colour map is used
-  mCurrentColorMap = settings.value("ColormapFile", "").toString();
-  // Set values from settings
-  mInstrumentDisplay->mutableColorMap().loadMap(mCurrentColorMap);
-  
-  GraphOptions::ScaleType type = (GraphOptions::ScaleType)settings.value("ScaleType", GraphOptions::Log10).toUInt();
-  mInstrumentDisplay->mutableColorMap().changeScaleType(type);
-
-  settings.endGroup();
-}
-
-/**
- * Save properties of the window a persistent store
- */
-void InstrumentWindow::saveSettings()
-{
-  QSettings settings;
-  settings.beginGroup("Mantid/InstrumentWindow");
-  settings.setValue("BackgroundColor", mInstrumentDisplay->currentBackgroundColor());
-  settings.setValue("ColormapFile", mCurrentColorMap);
-  settings.setValue("ScaleType", mInstrumentDisplay->getColorMap().getScaleType());
-  settings.setValue("ColormapFile", mCurrentColorMap);
-  settings.endGroup();
-}
-
-/// Closes the window if the associated workspace is deleted
-void InstrumentWindow::deleteHandle(const std::string & ws_name, boost::shared_ptr<Mantid::API::Workspace>)
-{
-  if (ws_name == mWorkspaceName)
-  {
-    askOnCloseEvent(false);
-    close();
-  }
-}
-
-void InstrumentWindow::afterReplaceHandle(const std::string& wsName,
-					  const boost::shared_ptr<Mantid::API::Workspace>)
-{
-  //Replace current workspace
-  if (wsName == mWorkspaceName)
-  {
-    updateWindow();
-  }
-}
-
-void InstrumentWindow::clearADSHandle()
-{
-  askOnCloseEvent(false);
-  close();
-}
-
-
-/**
- * This method saves the workspace name associated with the instrument window 
- * and geometry to a string.This is useful for loading/saving the project.
- */
-QString InstrumentWindow::saveToString(const QString& geometry, bool saveAsTemplate)
-{
-  (void) saveAsTemplate;
-	QString s="<instrumentwindow>\n";
-	s+="WorkspaceName\t"+QString::fromStdString(mWorkspaceName)+"\n";
-	s+=geometry;
-	s+="</instrumentwindow>\n";
-	return s;
-
-}
-
+ */
+void InstrumentWindow::setScaleType(GraphOptions::ScaleType type)
+{
+  m_renderTab->setScaleType(type);
+}
+
+/// A slot for the mouse selection
+void InstrumentWindow::componentSelected(const QItemSelection & selected, const QItemSelection &)
+{
+  QModelIndexList items = selected.indexes();
+  if( items.isEmpty() ) return;
+
+  if (mInstrumentDisplay->getRenderMode() == GL3DWidget::FULL3D)
+  {
+    double xmax(0.), xmin(0.), ymax(0.), ymin(0.), zmax(0.), zmin(0.);
+    mInstrumentTree->getSelectedBoundingBox(items.first(), xmax, ymax, zmax, xmin, ymin, zmin);
+    V3D pos = mInstrumentTree->getSamplePos();
+    mInstrumentDisplay->setView(pos, xmax, ymax, zmax, xmin, ymin, zmin);
+  }
+  else
+  {
+    mInstrumentTree->sendComponentSelectedSignal(items.first());
+  }
+
+}
+
+/**
+ * This method opens a color dialog to pick the background color,
+ * and then sets it.
+ */
+void InstrumentWindow::pickBackgroundColor()
+{
+	QColor color = QColorDialog::getColor(Qt::green,this);
+	mInstrumentDisplay->setBackgroundColor(color);
+}
+
+void InstrumentWindow::saveImage()
+{
+  QList<QByteArray> formats = QImageWriter::supportedImageFormats();
+  QListIterator<QByteArray> itr(formats);
+  QString filter("");
+  while( itr.hasNext() )
+  {
+    filter += "*." + itr.next();
+    if( itr.hasNext() )
+    {
+      filter += ";;";
+    }
+  }
+  QString selectedFilter = "*.png";
+  QString filename = QFileDialog::getSaveFileName(this, "Save image ...", m_savedialog_dir, filter, &selectedFilter);
+
+  // If its empty, they cancelled the dialog
+  if( filename.isEmpty() ) return;
+  
+  //Save the directory used
+  QFileInfo finfo(filename);
+  m_savedialog_dir = finfo.dir().path();
+
+  QString ext = finfo.completeSuffix();
+  if( ext.isEmpty() )
+  {
+    filename += selectedFilter.section("*", 1);
+    ext = QFileInfo(filename).completeSuffix();
+  }
+  else
+  {
+    QStringList extlist = filter.split(";;");
+    if( !extlist.contains("*." + ext) )
+    {
+      QMessageBox::warning(this, "MantidPlot", "Unsupported file extension, please use one from the supported list.");
+      return;
+    }
+  }
+  
+  mInstrumentDisplay->saveToFile(filename);
+}
+
+/**
+ * Update the text display that informs the user of the current mode and details about it
+ */
+void InstrumentWindow::setInfoText(const QString& text)
+{
+ // if(mInstrumentDisplay->getInteractionMode() == Instrument3DWidget::PickMode)
+	//{
+ //   text = tr("Mouse Button: Left -- Rotation, Middle -- Zoom, Right -- Translate\nKeyboard: NumKeys -- Rotation, PageUp/Down -- Zoom, ArrowKeys -- Translate");
+ //   if( mInstrumentDisplay->areAxesOn() )
+ //   {
+ //     text += "\nAxes: X = Red; Y = Green; Z = Blue";
+ //   }
+ // }
+ // else
+ // {
+ //  text = tr("Use Mouse Left Button to Pick an detector\n Click on 'Normal' button to get into interactive mode");
+ // }
+  mInteractionInfo->setText(text);
+}
+
+/**
+ * This method loads the setting from QSettings
+ */
+void InstrumentWindow::loadSettings()
+{
+  //Load Color
+  QSettings settings;
+  settings.beginGroup("Mantid/InstrumentWindow");
+  
+  // Background colour
+  mInstrumentDisplay->setBackgroundColor(settings.value("BackgroundColor",QColor(0,0,0,1.0)).value<QColor>());
+  
+  //Load Colormap. If the file is invalid the default stored colour map is used
+  mCurrentColorMap = settings.value("ColormapFile", "").toString();
+  // Set values from settings
+  mInstrumentDisplay->mutableColorMap().loadMap(mCurrentColorMap);
+  
+  GraphOptions::ScaleType type = (GraphOptions::ScaleType)settings.value("ScaleType", GraphOptions::Log10).toUInt();
+  mInstrumentDisplay->mutableColorMap().changeScaleType(type);
+
+  settings.endGroup();
+}
+
+/**
+ * Save properties of the window a persistent store
+ */
+void InstrumentWindow::saveSettings()
+{
+  QSettings settings;
+  settings.beginGroup("Mantid/InstrumentWindow");
+  settings.setValue("BackgroundColor", mInstrumentDisplay->currentBackgroundColor());
+  settings.setValue("ColormapFile", mCurrentColorMap);
+  settings.setValue("ScaleType", mInstrumentDisplay->getColorMap().getScaleType());
+  settings.setValue("ColormapFile", mCurrentColorMap);
+  settings.endGroup();
+}
+
+/// Closes the window if the associated workspace is deleted
+void InstrumentWindow::deleteHandle(const std::string & ws_name, boost::shared_ptr<Mantid::API::Workspace>)
+{
+  if (ws_name == mWorkspaceName)
+  {
+    askOnCloseEvent(false);
+    close();
+  }
+}
+
+void InstrumentWindow::afterReplaceHandle(const std::string& wsName,
+					  const boost::shared_ptr<Mantid::API::Workspace>)
+{
+  //Replace current workspace
+  if (wsName == mWorkspaceName)
+  {
+    updateWindow();
+  }
+}
+
+void InstrumentWindow::clearADSHandle()
+{
+  askOnCloseEvent(false);
+  close();
+}
+
+
+/**
+ * This method saves the workspace name associated with the instrument window 
+ * and geometry to a string.This is useful for loading/saving the project.
+ */
+QString InstrumentWindow::saveToString(const QString& geometry, bool saveAsTemplate)
+{
+  (void) saveAsTemplate;
+	QString s="<instrumentwindow>\n";
+	s+="WorkspaceName\t"+QString::fromStdString(mWorkspaceName)+"\n";
+	s+=geometry;
+	s+="</instrumentwindow>\n";
+	return s;
+
+}
+
 /** 
  * Called just before a show event
  * @param A :: pointer to the QShowEvent object
@@ -680,18 +680,18 @@ void InstrumentWindow::showEvent(QShowEvent* event)
 {
   updateWindow();
 }
-
+
 
 
 QFrame * InstrumentWindow::createInstrumentTreeTab(QTabWidget* ControlsTab)
 {
-  QFrame* instrumentTree=new QFrame(ControlsTab);
-  QVBoxLayout* instrumentTreeLayout=new QVBoxLayout(instrumentTree);
-  //Tree Controls
-  mInstrumentTree = new InstrumentTreeWidget(0);
-  instrumentTreeLayout->addWidget(mInstrumentTree);
-  connect(mInstrumentTree,SIGNAL(componentSelected(Mantid::Geometry::ComponentID)),
-          mInstrumentDisplay,SLOT(componentSelected(Mantid::Geometry::ComponentID)));
+  QFrame* instrumentTree=new QFrame(ControlsTab);
+  QVBoxLayout* instrumentTreeLayout=new QVBoxLayout(instrumentTree);
+  //Tree Controls
+  mInstrumentTree = new InstrumentTreeWidget(0);
+  instrumentTreeLayout->addWidget(mInstrumentTree);
+  connect(mInstrumentTree,SIGNAL(componentSelected(Mantid::Geometry::ComponentID)),
+          mInstrumentDisplay,SLOT(componentSelected(Mantid::Geometry::ComponentID)));
   return instrumentTree;
 }
 
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/MantidColorMap.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/MantidColorMap.cpp
index aab76338d6b6c7d9612baa9728b8df48fcc0fb63..a33ff026ddaa403fcd7df16a2018ab912619586c 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/MantidColorMap.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/MantidColorMap.cpp
@@ -161,45 +161,45 @@ void MantidColorMap::setupDefaultMap()
 
 
 /**
- * Normalize the value to the range[0,1]
- * @param interval :: The data range
- * @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
-{
-  if( interval.isNull() || m_num_colors == 0 ) 
-  {
-    return -1.0;
-  }
-
-  const double width = interval.width();
-  if( width <= 0.0 || value <= interval.minValue() )
-  {
-    return 0.0;
-  }
-  // nan numbers have the property that nan != nan, treat nan as being the maximum
-  if ( value >= interval.maxValue() || value != value )
-  {
-    return 1.0;
-  }
-  double ratio(0.0);
-  if( m_scale_type == GraphOptions::Linear)
-  {
-    ratio = (value - interval.minValue()) / width;
-  }
-  else
-  {
-    // Have to deal with the possibility that a user has entered 0 as a minimum
-    double minValue = interval.minValue();
-    if( minValue < 1e-08 )
-    {
-      minValue = 1.0;
-    }
-    ratio = std::log10(value/minValue)/std::log10(interval.maxValue()/minValue);
-  }
-  return ratio;
-}
+ * Normalize the value to the range[0,1]
+ * @param interval :: The data range
+ * @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
+{
+  if( interval.isNull() || m_num_colors == 0 ) 
+  {
+    return -1.0;
+  }
+
+  const double width = interval.width();
+  if( width <= 0.0 || value <= interval.minValue() )
+  {
+    return 0.0;
+  }
+  // nan numbers have the property that nan != nan, treat nan as being the maximum
+  if ( value >= interval.maxValue() || value != value )
+  {
+    return 1.0;
+  }
+  double ratio(0.0);
+  if( m_scale_type == GraphOptions::Linear)
+  {
+    ratio = (value - interval.minValue()) / width;
+  }
+  else
+  {
+    // Have to deal with the possibility that a user has entered 0 as a minimum
+    double minValue = interval.minValue();
+    if( minValue < 1e-08 )
+    {
+      minValue = 1.0;
+    }
+    ratio = std::log10(value/minValue)/std::log10(interval.maxValue()/minValue);
+  }
+  return ratio;
+}
 
 
 /**
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/MantidObject.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/MantidObject.cpp
index 51a2c53c41f98ebf95293394fc4be770af08ff97..c110c4828942e52137c29b74e0a510742f4ff5e2 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/MantidObject.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/MantidObject.cpp
@@ -1,108 +1,108 @@
-#include "MantidGeometry/V3D.h"
-#include "MantidGeometry/Objects/Object.h"
-#include "MantidKernel/Exception.h"
-#include "MantidObject.h"
-#include "TexObject.h"
-
-/**
- * Constructor
- */
-MantidObject::MantidObject(const boost::shared_ptr<const Mantid::Geometry::Object> obj,bool withDisplayList):GLObject(withDisplayList)
-{
-	Obj=obj;
-	mHighResolution=true;
-	Obj->initDraw();
-}
-
-/** 
- * Destructor
- */
-MantidObject::~MantidObject()
-{
-}
-
-/**
- * implementation to render Object
- */
-void MantidObject::define()
-{
-  if(mHighResolution)
-  {
-    Obj->draw();
-  }
-  else
-  {
-    defineBoundingBox();
-  }
-}
-
-/**
- * @return the Object
- */
-const boost::shared_ptr<const Mantid::Geometry::Object> MantidObject::getObject()
-{
-	return Obj;
-}
-
-
-/**
- * Implementation of the rendering bounding box
- */
-void MantidObject::defineBoundingBox()
-{
-	//Get Object bounding box
-	double xmin,xmax,ymin,ymax,zmin,zmax;
-	xmax=ymax=zmax=1000;
-	xmin=ymin=zmin=-1000;
-	Obj->getBoundingBox(xmax,ymax,zmax,xmin,ymin,zmin);
-	Mantid::Geometry::V3D _bbmin(xmin,ymin,zmin),_bbmax(xmax,ymax,zmax);
-	//draw bounding box
- 	        glBegin(GL_LINE_LOOP);
- 	            glVertex3d(_bbmin[0],_bbmin[1],_bbmin[2]);
- 	            glVertex3d(_bbmin[0],_bbmax[1],_bbmin[2]);
-	            glVertex3d(_bbmax[0],_bbmax[1],_bbmin[2]);
- 	            glVertex3d(_bbmax[0],_bbmin[1],_bbmin[2]);
- 	        glEnd();
- 	        glBegin(GL_LINE_LOOP);
- 	            glVertex3d(_bbmin[0],_bbmin[1],_bbmax[2]);
- 	            glVertex3d(_bbmin[0],_bbmax[1],_bbmax[2]);
- 	            glVertex3d(_bbmax[0],_bbmax[1],_bbmax[2]);
- 	            glVertex3d(_bbmax[0],_bbmin[1],_bbmax[2]);
- 	        glEnd();
- 	         glBegin(GL_LINES);
- 	            glVertex3d(_bbmin[0],_bbmin[1],_bbmin[2]);
- 	            glVertex3d(_bbmin[0],_bbmin[1],_bbmax[2]);
- 	        glEnd();
- 	        glBegin(GL_LINES);
- 	            glVertex3d(_bbmin[0],_bbmax[1],_bbmin[2]);
- 	            glVertex3d(_bbmin[0],_bbmax[1],_bbmax[2]);
- 	        glEnd();
- 	        glBegin(GL_LINES);
- 	            glVertex3d(_bbmax[0],_bbmin[1],_bbmin[2]);
- 	            glVertex3d(_bbmax[0],_bbmin[1],_bbmax[2]);
- 	        glEnd();
- 	        glBegin(GL_LINES);
- 	            glVertex3d(_bbmax[0],_bbmax[1],_bbmin[2]);
- 	            glVertex3d(_bbmax[0],_bbmax[1],_bbmax[2]);
- 	        glEnd();
-}
-
-/**
- * renders the object in high resolution
- */
-void MantidObject::setResolutionToHigh()
-{
-	mHighResolution=true;
-	mChanged=true;
-	construct();
-}
-
-/**
- * renders the object in low resolution
- */
-void MantidObject::setResolutionToLow()
-{
-	mHighResolution=false;
-	mChanged=true;
-	construct();
-}
+#include "MantidGeometry/V3D.h"
+#include "MantidGeometry/Objects/Object.h"
+#include "MantidKernel/Exception.h"
+#include "MantidObject.h"
+#include "TexObject.h"
+
+/**
+ * Constructor
+ */
+MantidObject::MantidObject(const boost::shared_ptr<const Mantid::Geometry::Object> obj,bool withDisplayList):GLObject(withDisplayList)
+{
+	Obj=obj;
+	mHighResolution=true;
+	Obj->initDraw();
+}
+
+/** 
+ * Destructor
+ */
+MantidObject::~MantidObject()
+{
+}
+
+/**
+ * implementation to render Object
+ */
+void MantidObject::define()
+{
+  if(mHighResolution)
+  {
+    Obj->draw();
+  }
+  else
+  {
+    defineBoundingBox();
+  }
+}
+
+/**
+ * @return the Object
+ */
+const boost::shared_ptr<const Mantid::Geometry::Object> MantidObject::getObject()
+{
+	return Obj;
+}
+
+
+/**
+ * Implementation of the rendering bounding box
+ */
+void MantidObject::defineBoundingBox()
+{
+	//Get Object bounding box
+	double xmin,xmax,ymin,ymax,zmin,zmax;
+	xmax=ymax=zmax=1000;
+	xmin=ymin=zmin=-1000;
+	Obj->getBoundingBox(xmax,ymax,zmax,xmin,ymin,zmin);
+	Mantid::Geometry::V3D _bbmin(xmin,ymin,zmin),_bbmax(xmax,ymax,zmax);
+	//draw bounding box
+ 	        glBegin(GL_LINE_LOOP);
+ 	            glVertex3d(_bbmin[0],_bbmin[1],_bbmin[2]);
+ 	            glVertex3d(_bbmin[0],_bbmax[1],_bbmin[2]);
+	            glVertex3d(_bbmax[0],_bbmax[1],_bbmin[2]);
+ 	            glVertex3d(_bbmax[0],_bbmin[1],_bbmin[2]);
+ 	        glEnd();
+ 	        glBegin(GL_LINE_LOOP);
+ 	            glVertex3d(_bbmin[0],_bbmin[1],_bbmax[2]);
+ 	            glVertex3d(_bbmin[0],_bbmax[1],_bbmax[2]);
+ 	            glVertex3d(_bbmax[0],_bbmax[1],_bbmax[2]);
+ 	            glVertex3d(_bbmax[0],_bbmin[1],_bbmax[2]);
+ 	        glEnd();
+ 	         glBegin(GL_LINES);
+ 	            glVertex3d(_bbmin[0],_bbmin[1],_bbmin[2]);
+ 	            glVertex3d(_bbmin[0],_bbmin[1],_bbmax[2]);
+ 	        glEnd();
+ 	        glBegin(GL_LINES);
+ 	            glVertex3d(_bbmin[0],_bbmax[1],_bbmin[2]);
+ 	            glVertex3d(_bbmin[0],_bbmax[1],_bbmax[2]);
+ 	        glEnd();
+ 	        glBegin(GL_LINES);
+ 	            glVertex3d(_bbmax[0],_bbmin[1],_bbmin[2]);
+ 	            glVertex3d(_bbmax[0],_bbmin[1],_bbmax[2]);
+ 	        glEnd();
+ 	        glBegin(GL_LINES);
+ 	            glVertex3d(_bbmax[0],_bbmax[1],_bbmin[2]);
+ 	            glVertex3d(_bbmax[0],_bbmax[1],_bbmax[2]);
+ 	        glEnd();
+}
+
+/**
+ * renders the object in high resolution
+ */
+void MantidObject::setResolutionToHigh()
+{
+	mHighResolution=true;
+	mChanged=true;
+	construct();
+}
+
+/**
+ * renders the object in low resolution
+ */
+void MantidObject::setResolutionToLow()
+{
+	mHighResolution=false;
+	mChanged=true;
+	construct();
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/MantidObject.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/MantidObject.h
index 5351ead7697bc79e6b02b022658486dd7a66aee4..cb0f51d302faab036586faad665157c346aefe60 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/MantidObject.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/MantidObject.h
@@ -1,55 +1,55 @@
-#ifndef MANTIDOBJECT_H_
-#define MANTIDOBJECT_H_
-#include "GLObject.h"
-/**
-  \class  MantidObject
-  \brief  Mantid Objent wrapper class for rendering in OpenGL
-  \author Srikanth Nagella
-  \date   March 2009
-  \version 1.0
-
-   This class has the implementation for rendering OpenGL object and it inherits from the GLObject
-
-  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-namespace Mantid{
-	namespace Geometry{
-		class Object;
-	}
-}
-
-class MantidObject : public GLObject
-{
-protected:
-  boost::shared_ptr<const Mantid::Geometry::Object> Obj; ///< Holder for Object
-  bool mHighResolution;
-public:
-  MantidObject(const boost::shared_ptr<const Mantid::Geometry::Object> obj,bool withDisplayList=true); ///< Default Constructor
-  ~MantidObject();								   ///< Destructor
-  virtual std::string type()const {return "MantidObject";} ///< Type of the GL object
-  void define();  ///< Method that defines ObjComponent geometry. Calls ObjComponent draw method
-  const boost::shared_ptr<const Mantid::Geometry::Object> getObject(); ///< Returns the objcomponent held in this object
-  void defineBoundingBox();
-  void setResolutionToHigh();
-  void setResolutionToLow();
-};
-
-#endif /*GLTRIANGLE_H_*/
-
+#ifndef MANTIDOBJECT_H_
+#define MANTIDOBJECT_H_
+#include "GLObject.h"
+/**
+  \class  MantidObject
+  \brief  Mantid Objent wrapper class for rendering in OpenGL
+  \author Srikanth Nagella
+  \date   March 2009
+  \version 1.0
+
+   This class has the implementation for rendering OpenGL object and it inherits from the GLObject
+
+  Copyright &copy; 2007 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+*/
+namespace Mantid{
+	namespace Geometry{
+		class Object;
+	}
+}
+
+class MantidObject : public GLObject
+{
+protected:
+  boost::shared_ptr<const Mantid::Geometry::Object> Obj; ///< Holder for Object
+  bool mHighResolution;
+public:
+  MantidObject(const boost::shared_ptr<const Mantid::Geometry::Object> obj,bool withDisplayList=true); ///< Default Constructor
+  ~MantidObject();								   ///< Destructor
+  virtual std::string type()const {return "MantidObject";} ///< Type of the GL object
+  void define();  ///< Method that defines ObjComponent geometry. Calls ObjComponent draw method
+  const boost::shared_ptr<const Mantid::Geometry::Object> getObject(); ///< Returns the objcomponent held in this object
+  void defineBoundingBox();
+  void setResolutionToHigh();
+  void setResolutionToLow();
+};
+
+#endif /*GLTRIANGLE_H_*/
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjComponentActor.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjComponentActor.cpp
index af9c142926abf47c62873bb92fa11e120bb3372f..d33140e5c57e5ba73e4cc65c2240672eca9daf1e 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjComponentActor.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjComponentActor.cpp
@@ -1,143 +1,143 @@
-#include "MantidGeometry/V3D.h"
-#include "MantidGeometry/Quat.h"
-#include "MantidGeometry/IObjComponent.h"
-#include "MantidKernel/Exception.h"
-#include "MantidGeometry/IDetector.h"
-#include "ObjComponentActor.h"
-#include "MantidObject.h"
-
-using namespace Mantid;
-using namespace Geometry;
-
-ObjComponentActor::ObjComponentActor(bool withDisplayList)
-  :GLActor(withDisplayList)
-{
-}
-
-
-ObjComponentActor::ObjComponentActor(MantidObject *obj, boost::shared_ptr<Mantid::Geometry::IObjComponent> objComp, bool withDisplayList)
-  : GLActor(withDisplayList)
-{
-	mObjComp=objComp;
-	mObject=obj;
-	this->setName( objComp->getName() );
-}
-
-ObjComponentActor::~ObjComponentActor()
-{
-}
-
-//-------------------------------------------------------------------------------------------------
-/**
- * Concrete implementation of rendering ObjComponent.
- */
-void ObjComponentActor::define()
-{
-	glPushMatrix();
-	// Translation first
-	V3D pos = mObjComp->getPos();
-	if (!(pos.nullVector()))
-	{
-		glTranslated(pos[0],pos[1],pos[2]);
-	}
-	//Rotation
-	Quat rot = mObjComp->getRotation();
-	if (!(rot.isNull()))
-	{
-		double deg,ax0,ax1,ax2;
-		rot.getAngleAxis(deg,ax0,ax1,ax2);
-		glRotated(deg,ax0,ax1,ax2);
-	}
-	//Scale
-	V3D scaleFactor = mObjComp->getScaleFactor();
-	if (!(scaleFactor==V3D(1,1,1)))
-	{
-		glScaled(scaleFactor[0],scaleFactor[1],scaleFactor[2]);
-	}
-
-	//std::cout << "ObjComponentActor::define() called with pos=" << pos << " and rot=" << rot << " and scale=" << scaleFactor << ".\n";
-
-	//If a mantidObject was specified, call ITS draw routine
-	if (mObject)
-	  mObject->draw();
-	else
-	  //Otherwise, use the ObjComponent draw routine. This is what RectangularDetector will use.
-	  mObjComp->draw();
-
-	glPopMatrix();
-}
-
-
-//-------------------------------------------------------------------------------------------------
-/** Append the detector ID of this object to the list, if it is a detector.
- *
- * @param idList :: sequential list of detector IDs.
- */
-void ObjComponentActor::appendObjCompID(std::vector<int>& idList)
-{
-  //check the component type if its detector or not
-  const boost::shared_ptr<Mantid::Geometry::IDetector>  detector = boost::dynamic_pointer_cast<Mantid::Geometry::IDetector>(this->getObjComponent());
-  if( detector != boost::shared_ptr<Mantid::Geometry::IDetector>() )
-  {
-    if( !detector->isMonitor() )
-    {
-      idList.push_back(detector->getID());
-    }
-    else
-    {
-      idList.push_back(-1);
-    }
-  }
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * The colors are set using the iterator of the color list. The order of the detectors
- * in this color list was defined by the calls to appendObjCompID().
- *
- * @param list :: Color list iterator
- * @return the number of detectors
- */
-int ObjComponentActor::setInternalDetectorColors(std::vector<boost::shared_ptr<GLColor> >::iterator & list)
-{
-  const boost::shared_ptr<Mantid::Geometry::IDetector>  detector =
-      boost::dynamic_pointer_cast<Mantid::Geometry::IDetector>(this->getObjComponent());
-  if( detector != boost::shared_ptr<Mantid::Geometry::IDetector>() )
-  {
-    this->setColor((*list));
-    //Increment for the next one
-    list++;
-    return 1;
-  }
-  else
-    return 0;
-}
-
-
-
-//-------------------------------------------------------------------------------------------------
-/**
- * Return the bounding box
- * @param minBound :: min point of the bounding box
- * @param maxBound :: max point of the bounding box
- */
-void ObjComponentActor::getBoundingBox(Mantid::Geometry::V3D& minBound,Mantid::Geometry::V3D& maxBound)
-{
-	double xmin,ymin,zmin,xmax,ymax,zmax;
-	xmin=ymin=zmin=-1000;
-	xmax=ymax=zmax=1000;
-	mObjComp->getBoundingBox(xmax,ymax,zmax,xmin,ymin,zmin);
-	minBound[0]=xmin;minBound[1]=ymin;minBound[2]=zmin;
-	maxBound[0]=xmax;maxBound[1]=ymax;maxBound[2]=zmax;
-}
-
-void ObjComponentActor::detectorCallback(DetectorCallback* callback)const
-{
-  boost::shared_ptr<const Mantid::Geometry::IDetector> det =
-      boost::dynamic_pointer_cast<const Mantid::Geometry::IDetector> (mObjComp);
-  if (det)
-  {
-    callback->callback(det,DetectorCallbackData(*getColor()));
-  }
-}
+#include "MantidGeometry/V3D.h"
+#include "MantidGeometry/Quat.h"
+#include "MantidGeometry/IObjComponent.h"
+#include "MantidKernel/Exception.h"
+#include "MantidGeometry/IDetector.h"
+#include "ObjComponentActor.h"
+#include "MantidObject.h"
+
+using namespace Mantid;
+using namespace Geometry;
+
+ObjComponentActor::ObjComponentActor(bool withDisplayList)
+  :GLActor(withDisplayList)
+{
+}
+
+
+ObjComponentActor::ObjComponentActor(MantidObject *obj, boost::shared_ptr<Mantid::Geometry::IObjComponent> objComp, bool withDisplayList)
+  : GLActor(withDisplayList)
+{
+	mObjComp=objComp;
+	mObject=obj;
+	this->setName( objComp->getName() );
+}
+
+ObjComponentActor::~ObjComponentActor()
+{
+}
+
+//-------------------------------------------------------------------------------------------------
+/**
+ * Concrete implementation of rendering ObjComponent.
+ */
+void ObjComponentActor::define()
+{
+	glPushMatrix();
+	// Translation first
+	V3D pos = mObjComp->getPos();
+	if (!(pos.nullVector()))
+	{
+		glTranslated(pos[0],pos[1],pos[2]);
+	}
+	//Rotation
+	Quat rot = mObjComp->getRotation();
+	if (!(rot.isNull()))
+	{
+		double deg,ax0,ax1,ax2;
+		rot.getAngleAxis(deg,ax0,ax1,ax2);
+		glRotated(deg,ax0,ax1,ax2);
+	}
+	//Scale
+	V3D scaleFactor = mObjComp->getScaleFactor();
+	if (!(scaleFactor==V3D(1,1,1)))
+	{
+		glScaled(scaleFactor[0],scaleFactor[1],scaleFactor[2]);
+	}
+
+	//std::cout << "ObjComponentActor::define() called with pos=" << pos << " and rot=" << rot << " and scale=" << scaleFactor << ".\n";
+
+	//If a mantidObject was specified, call ITS draw routine
+	if (mObject)
+	  mObject->draw();
+	else
+	  //Otherwise, use the ObjComponent draw routine. This is what RectangularDetector will use.
+	  mObjComp->draw();
+
+	glPopMatrix();
+}
+
+
+//-------------------------------------------------------------------------------------------------
+/** Append the detector ID of this object to the list, if it is a detector.
+ *
+ * @param idList :: sequential list of detector IDs.
+ */
+void ObjComponentActor::appendObjCompID(std::vector<int>& idList)
+{
+  //check the component type if its detector or not
+  const boost::shared_ptr<Mantid::Geometry::IDetector>  detector = boost::dynamic_pointer_cast<Mantid::Geometry::IDetector>(this->getObjComponent());
+  if( detector != boost::shared_ptr<Mantid::Geometry::IDetector>() )
+  {
+    if( !detector->isMonitor() )
+    {
+      idList.push_back(detector->getID());
+    }
+    else
+    {
+      idList.push_back(-1);
+    }
+  }
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * The colors are set using the iterator of the color list. The order of the detectors
+ * in this color list was defined by the calls to appendObjCompID().
+ *
+ * @param list :: Color list iterator
+ * @return the number of detectors
+ */
+int ObjComponentActor::setInternalDetectorColors(std::vector<boost::shared_ptr<GLColor> >::iterator & list)
+{
+  const boost::shared_ptr<Mantid::Geometry::IDetector>  detector =
+      boost::dynamic_pointer_cast<Mantid::Geometry::IDetector>(this->getObjComponent());
+  if( detector != boost::shared_ptr<Mantid::Geometry::IDetector>() )
+  {
+    this->setColor((*list));
+    //Increment for the next one
+    list++;
+    return 1;
+  }
+  else
+    return 0;
+}
+
+
+
+//-------------------------------------------------------------------------------------------------
+/**
+ * Return the bounding box
+ * @param minBound :: min point of the bounding box
+ * @param maxBound :: max point of the bounding box
+ */
+void ObjComponentActor::getBoundingBox(Mantid::Geometry::V3D& minBound,Mantid::Geometry::V3D& maxBound)
+{
+	double xmin,ymin,zmin,xmax,ymax,zmax;
+	xmin=ymin=zmin=-1000;
+	xmax=ymax=zmax=1000;
+	mObjComp->getBoundingBox(xmax,ymax,zmax,xmin,ymin,zmin);
+	minBound[0]=xmin;minBound[1]=ymin;minBound[2]=zmin;
+	maxBound[0]=xmax;maxBound[1]=ymax;maxBound[2]=zmax;
+}
+
+void ObjComponentActor::detectorCallback(DetectorCallback* callback)const
+{
+  boost::shared_ptr<const Mantid::Geometry::IDetector> det =
+      boost::dynamic_pointer_cast<const Mantid::Geometry::IDetector> (mObjComp);
+  if (det)
+  {
+    callback->callback(det,DetectorCallbackData(*getColor()));
+  }
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjComponentActor.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjComponentActor.h
index d3dd12840b692ab3cd29e7c8b77fdd4489807196..7d2fa9e96f2b5a46228dc4f3ef355997825e928f 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjComponentActor.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjComponentActor.h
@@ -1,60 +1,60 @@
-#ifndef OBJCOMPONENT_ACTOR_H_
-#define OBJCOMPONENT_ACTOR_H_
-#include "GLActor.h"
-/**
-  \class  ObjComponentActor
-  \brief  ObjComponentActor is an actor class for rendering ObjComponents.
-  \author Srikanth Nagella
-  \date   March 2009
-  \version 1.0
-
-   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
-
-  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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-namespace Mantid{
-	namespace Geometry{
-		class IObjComponent;
-		class V3D;
-	}
-}
-class MantidObject;
-
-class ObjComponentActor : public GLActor
-{
-private:
-  MantidObject *mObject;
-  boost::shared_ptr<Mantid::Geometry::IObjComponent> mObjComp;
-public:
-  ObjComponentActor(bool withDisplayList=false); ///< Default Constructor
-  ObjComponentActor(MantidObject *obj, boost::shared_ptr<Mantid::Geometry::IObjComponent> objComp, bool withDisplayList=false); ///< Default Constructor
-  ~ObjComponentActor();								   ///< Destructor
-  virtual std::string type()const {return "ObjComponentActor";} ///< Type of the GL object
-  virtual void define();  ///< Method that defines ObjComponent geometry. Calls ObjComponent draw method
-  virtual void appendObjCompID(std::vector<int>& idList);
-  virtual int setInternalDetectorColors(std::vector<boost::shared_ptr<GLColor> >::iterator & list);
-  virtual void getBoundingBox(Mantid::Geometry::V3D& minBound,Mantid::Geometry::V3D& maxBound);
-
-  const boost::shared_ptr<Mantid::Geometry::IObjComponent> getObjComponent() const{return mObjComp;}
-  void detectorCallback(DetectorCallback* callback)const;
-};
-
-#endif /*OBJCOMPONENT_ACTOR_H_*/
-
+#ifndef OBJCOMPONENT_ACTOR_H_
+#define OBJCOMPONENT_ACTOR_H_
+#include "GLActor.h"
+/**
+  \class  ObjComponentActor
+  \brief  ObjComponentActor is an actor class for rendering ObjComponents.
+  \author Srikanth Nagella
+  \date   March 2009
+  \version 1.0
+
+   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
+
+  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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+*/
+namespace Mantid{
+	namespace Geometry{
+		class IObjComponent;
+		class V3D;
+	}
+}
+class MantidObject;
+
+class ObjComponentActor : public GLActor
+{
+private:
+  MantidObject *mObject;
+  boost::shared_ptr<Mantid::Geometry::IObjComponent> mObjComp;
+public:
+  ObjComponentActor(bool withDisplayList=false); ///< Default Constructor
+  ObjComponentActor(MantidObject *obj, boost::shared_ptr<Mantid::Geometry::IObjComponent> objComp, bool withDisplayList=false); ///< Default Constructor
+  ~ObjComponentActor();								   ///< Destructor
+  virtual std::string type()const {return "ObjComponentActor";} ///< Type of the GL object
+  virtual void define();  ///< Method that defines ObjComponent geometry. Calls ObjComponent draw method
+  virtual void appendObjCompID(std::vector<int>& idList);
+  virtual int setInternalDetectorColors(std::vector<boost::shared_ptr<GLColor> >::iterator & list);
+  virtual void getBoundingBox(Mantid::Geometry::V3D& minBound,Mantid::Geometry::V3D& maxBound);
+
+  const boost::shared_ptr<Mantid::Geometry::IObjComponent> getObjComponent() const{return mObjComp;}
+  void detectorCallback(DetectorCallback* callback)const;
+};
+
+#endif /*OBJCOMPONENT_ACTOR_H_*/
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/RectangularDetectorActor.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/RectangularDetectorActor.cpp
index 76c5346b2c35c8f9fe7b342dcbd0068240098882..ab6fd10ebf64140f5d6160d8c73977cf59e04af3 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/RectangularDetectorActor.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/RectangularDetectorActor.cpp
@@ -1,367 +1,367 @@
-#include "MantidGeometry/IInstrument.h"
-#include "MantidGeometry/V3D.h"
-#include "MantidGeometry/Objects/Object.h"
-#include "MantidGeometry/Objects/BoundingBox.h"
-#include "MantidGeometry/ICompAssembly.h"
-#include "MantidGeometry/IObjComponent.h"
-#include "MantidGeometry/IDetector.h"
-#include "MantidGeometry/Instrument/RectangularDetector.h"
-#include "MantidKernel/Exception.h"
-#include "MantidObject.h"
-#include "RectangularDetectorActor.h"
-#include "ObjComponentActor.h"
-#include "RectangularDetectorActor.h"
-#include <cfloat>
-using namespace Mantid;
-using namespace Geometry;
-
-static const bool VERBOSE = false;
-
-
-/**
- * Constructor.
- *
- * @param withDisplayList :: true to create a display list
- */
-RectangularDetectorActor::RectangularDetectorActor(boost::shared_ptr<Mantid::Geometry::RectangularDetector> rectDet)
-:
-    ICompAssemblyActor(false), mTextureID(0)
-{
-  mNumberOfDetectors = 0;
-  mDet = rectDet;
-  image_data = NULL;
-  pick_data = NULL;
-
-  if (mDet)
-  {
-    BoundingBox compBox;
-    mDet->getBoundingBox(compBox);
-    mNumberOfDetectors = mDet->nelements();
-    this->AppendBoundingBox(compBox.minPoint(), compBox.maxPoint());
-  }
-
-}
-
-
-
-//-------------------------------------------------------------------------------------------------
-/**
- * Destructor which removes the actors created by this object
- */
-RectangularDetectorActor::~RectangularDetectorActor()
-{
-}
-
-
-//-------------------------------------------------------------------------------------------------
-/**
- * This function is concrete implementation that renders the Child ObjComponents and Child CompAssembly's
- */
-void RectangularDetectorActor::define()
-{
-  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]);
-  }
-
-  // RectangularDetector will use.
-  mDet->draw();
-
-  glPopMatrix();
-}
-
-
-//-------------------------------------------------------------------------------------------------
-/**
- * Concrete implementation of init method of GLObject. this method draws the children
- */
-void RectangularDetectorActor::init()
-{
-  if (VERBOSE) std::cout << "RectangularDetectorActor::init() called for " << mDet->getName() << "\n";
-}
-
-
-//-------------------------------------------------------------------------------------------------
-/**
- * This method redraws the CompAssembly children compassembly actors redraw. this method is used to redraw all the children
- */
-void RectangularDetectorActor::redraw()
-{
-  if (VERBOSE) std::cout << "RectangularDetectorActor::redraw() called for " << mDet->getName() << "\n";
-}
-
-//-------------------------------------------------------------------------------------------------
-/** Append the detector ID of this object to the list, if it is a detector.
- *
- * @param idList :: sequential list of detector IDs.
- */
-void RectangularDetectorActor::appendObjCompID(std::vector<int>& idList)
-{
-  if (mDet)
-  {
-    //Append all the detector IDs of this rectangular detector
-    if (VERBOSE) std::cout << "RectangularDetectorActor::appendObjCompID() called for " << mDet->getName() << "\n";
-    for (int y=0; y < mDet->ypixels(); y++)
-      for (int x=0; x < mDet->xpixels(); x++)
-        idList.push_back( mDet->getAtXY(x,y)->getID() );
-
-  }
-}
-
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * Set the starting color reference for CompAssembly
- * @param rgb :: input color id
- * @return  the number of color ids that are used.
- */
-int RectangularDetectorActor::setStartingReferenceColor(int rgb)
-{
-  if (VERBOSE) std::cout << "RectangularDetectorActor::setStartingReferenceColor() called for " << mDet->getName() << " with rgb = " << rgb << "\n";
-  mColorStartID=rgb;
-  return this->getNumberOfDetectors();
-}
-
-//------------------------------------------------------------------------------------------------
-/**
- * This method searches the child actors for the input rgb color and returns the detector id corresponding to the rgb color. if the
- * detector is not found then returns -1.
- * @param  rgb :: input color id
- * @return the detector id of the input rgb color.if detector id not found then returns -1
- */
-int RectangularDetectorActor::findDetectorIDUsingColor(int rgb)
-{
-  if (VERBOSE) std::cout << "RectangularDetectorActor::findDetectorIDUsingColor() called for " << mDet->getName() << "\n";
-  //The row and column of the detector can be found from the color
-  int diff_rgb = rgb - mColorStartID;
-  int y = diff_rgb / mDet->xpixels();
-  int x = diff_rgb % mDet->xpixels();
-  //And now we return that ID :)
-  return mDet->getAtXY(x,y)->getID();
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * The colors are set using the iterator of the color list. The order of the detectors
- * in this color list was defined by the calls to appendObjCompID().
- *
- * @param list :: Color list iterator
- * @return the number of detectors
- */
-int RectangularDetectorActor::setInternalDetectorColors(std::vector<boost::shared_ptr<GLColor> >::iterator& list)
-{
-  int num = this->genTexture(image_data, list, false);
-  this->uploadTexture(image_data);
-  return num;
-}
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * 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<boost::shared_ptr<GLColor> >::iterator& 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;
-
-  //For using color IDs
-  int rgb = this->mColorStartID;
-
-  //------ 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 (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)
-      char r, g, b;
-
-      if (useDetectorIDs)
-      {
-        //Use the rgb int that is incremented for each detector
-        r=(rgb/65536);
-        g=((rgb%65536)/256);
-        b=((rgb%65536)%256);
-        rgb++;
-      }
-      else
-      {
-        //Get the current color
-        float rf, gf, bf, af;
-        (*list)->get(rf,gf,bf,af);
-        //Convert to bytes
-        r = (char) (255*rf);
-        g = (char) (255*gf);
-        b = (char) (255*bf);
-        //Go to the next color
-        list++;
-      }
-
-        //      //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)
-{
-  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";
-
-}
-
-//
-///** Swaps between the image_data and pick_data in order
-// * to swap the texture between the real one and the pick-color-one.
-// */
-//void RectangularDetectorActor::swapTexture()
-//{
-//  char * temp = pick_data;
-//  pick_data = image_data;
-//  image_data = temp;
-//}
-
-
-
-//------------------------------------------------------------------------------------------------
-/**
- * This method draws the children with the ColorID rather than the children actual color. used in picking the component
- */
-void RectangularDetectorActor::drawUsingColorID()
-{
-  std::vector<boost::shared_ptr<GLColor> >::iterator dummy_iterator;
-  this->genTexture(pick_data, dummy_iterator, true);
-  this->uploadTexture(pick_data);
-
-  //And now draw it with the newly defined texture.
-  this->define();
-
-  //Re-upload the good data from before.
-  this->uploadTexture(image_data);
-}
-
-
-
-
-//-------------------------------------------------------------------------------------------------
-/**
- * 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::Geometry::V3D& minBound,Mantid::Geometry::V3D& maxBound)
-{
-  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::Geometry::V3D& minBound,const Mantid::Geometry::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];
-}
-
+#include "MantidGeometry/IInstrument.h"
+#include "MantidGeometry/V3D.h"
+#include "MantidGeometry/Objects/Object.h"
+#include "MantidGeometry/Objects/BoundingBox.h"
+#include "MantidGeometry/ICompAssembly.h"
+#include "MantidGeometry/IObjComponent.h"
+#include "MantidGeometry/IDetector.h"
+#include "MantidGeometry/Instrument/RectangularDetector.h"
+#include "MantidKernel/Exception.h"
+#include "MantidObject.h"
+#include "RectangularDetectorActor.h"
+#include "ObjComponentActor.h"
+#include "RectangularDetectorActor.h"
+#include <cfloat>
+using namespace Mantid;
+using namespace Geometry;
+
+static const bool VERBOSE = false;
+
+
+/**
+ * Constructor.
+ *
+ * @param withDisplayList :: true to create a display list
+ */
+RectangularDetectorActor::RectangularDetectorActor(boost::shared_ptr<Mantid::Geometry::RectangularDetector> rectDet)
+:
+    ICompAssemblyActor(false), mTextureID(0)
+{
+  mNumberOfDetectors = 0;
+  mDet = rectDet;
+  image_data = NULL;
+  pick_data = NULL;
+
+  if (mDet)
+  {
+    BoundingBox compBox;
+    mDet->getBoundingBox(compBox);
+    mNumberOfDetectors = mDet->nelements();
+    this->AppendBoundingBox(compBox.minPoint(), compBox.maxPoint());
+  }
+
+}
+
+
+
+//-------------------------------------------------------------------------------------------------
+/**
+ * Destructor which removes the actors created by this object
+ */
+RectangularDetectorActor::~RectangularDetectorActor()
+{
+}
+
+
+//-------------------------------------------------------------------------------------------------
+/**
+ * This function is concrete implementation that renders the Child ObjComponents and Child CompAssembly's
+ */
+void RectangularDetectorActor::define()
+{
+  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]);
+  }
+
+  // RectangularDetector will use.
+  mDet->draw();
+
+  glPopMatrix();
+}
+
+
+//-------------------------------------------------------------------------------------------------
+/**
+ * Concrete implementation of init method of GLObject. this method draws the children
+ */
+void RectangularDetectorActor::init()
+{
+  if (VERBOSE) std::cout << "RectangularDetectorActor::init() called for " << mDet->getName() << "\n";
+}
+
+
+//-------------------------------------------------------------------------------------------------
+/**
+ * This method redraws the CompAssembly children compassembly actors redraw. this method is used to redraw all the children
+ */
+void RectangularDetectorActor::redraw()
+{
+  if (VERBOSE) std::cout << "RectangularDetectorActor::redraw() called for " << mDet->getName() << "\n";
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Append the detector ID of this object to the list, if it is a detector.
+ *
+ * @param idList :: sequential list of detector IDs.
+ */
+void RectangularDetectorActor::appendObjCompID(std::vector<int>& idList)
+{
+  if (mDet)
+  {
+    //Append all the detector IDs of this rectangular detector
+    if (VERBOSE) std::cout << "RectangularDetectorActor::appendObjCompID() called for " << mDet->getName() << "\n";
+    for (int y=0; y < mDet->ypixels(); y++)
+      for (int x=0; x < mDet->xpixels(); x++)
+        idList.push_back( mDet->getAtXY(x,y)->getID() );
+
+  }
+}
+
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * Set the starting color reference for CompAssembly
+ * @param rgb :: input color id
+ * @return  the number of color ids that are used.
+ */
+int RectangularDetectorActor::setStartingReferenceColor(int rgb)
+{
+  if (VERBOSE) std::cout << "RectangularDetectorActor::setStartingReferenceColor() called for " << mDet->getName() << " with rgb = " << rgb << "\n";
+  mColorStartID=rgb;
+  return this->getNumberOfDetectors();
+}
+
+//------------------------------------------------------------------------------------------------
+/**
+ * This method searches the child actors for the input rgb color and returns the detector id corresponding to the rgb color. if the
+ * detector is not found then returns -1.
+ * @param  rgb :: input color id
+ * @return the detector id of the input rgb color.if detector id not found then returns -1
+ */
+int RectangularDetectorActor::findDetectorIDUsingColor(int rgb)
+{
+  if (VERBOSE) std::cout << "RectangularDetectorActor::findDetectorIDUsingColor() called for " << mDet->getName() << "\n";
+  //The row and column of the detector can be found from the color
+  int diff_rgb = rgb - mColorStartID;
+  int y = diff_rgb / mDet->xpixels();
+  int x = diff_rgb % mDet->xpixels();
+  //And now we return that ID :)
+  return mDet->getAtXY(x,y)->getID();
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * The colors are set using the iterator of the color list. The order of the detectors
+ * in this color list was defined by the calls to appendObjCompID().
+ *
+ * @param list :: Color list iterator
+ * @return the number of detectors
+ */
+int RectangularDetectorActor::setInternalDetectorColors(std::vector<boost::shared_ptr<GLColor> >::iterator& list)
+{
+  int num = this->genTexture(image_data, list, false);
+  this->uploadTexture(image_data);
+  return num;
+}
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * 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<boost::shared_ptr<GLColor> >::iterator& 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;
+
+  //For using color IDs
+  int rgb = this->mColorStartID;
+
+  //------ 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 (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)
+      char r, g, b;
+
+      if (useDetectorIDs)
+      {
+        //Use the rgb int that is incremented for each detector
+        r=(rgb/65536);
+        g=((rgb%65536)/256);
+        b=((rgb%65536)%256);
+        rgb++;
+      }
+      else
+      {
+        //Get the current color
+        float rf, gf, bf, af;
+        (*list)->get(rf,gf,bf,af);
+        //Convert to bytes
+        r = (char) (255*rf);
+        g = (char) (255*gf);
+        b = (char) (255*bf);
+        //Go to the next color
+        list++;
+      }
+
+        //      //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)
+{
+  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";
+
+}
+
+//
+///** Swaps between the image_data and pick_data in order
+// * to swap the texture between the real one and the pick-color-one.
+// */
+//void RectangularDetectorActor::swapTexture()
+//{
+//  char * temp = pick_data;
+//  pick_data = image_data;
+//  image_data = temp;
+//}
+
+
+
+//------------------------------------------------------------------------------------------------
+/**
+ * This method draws the children with the ColorID rather than the children actual color. used in picking the component
+ */
+void RectangularDetectorActor::drawUsingColorID()
+{
+  std::vector<boost::shared_ptr<GLColor> >::iterator dummy_iterator;
+  this->genTexture(pick_data, dummy_iterator, true);
+  this->uploadTexture(pick_data);
+
+  //And now draw it with the newly defined texture.
+  this->define();
+
+  //Re-upload the good data from before.
+  this->uploadTexture(image_data);
+}
+
+
+
+
+//-------------------------------------------------------------------------------------------------
+/**
+ * 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::Geometry::V3D& minBound,Mantid::Geometry::V3D& maxBound)
+{
+  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::Geometry::V3D& minBound,const Mantid::Geometry::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];
+}
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/RectangularDetectorActor.h b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/RectangularDetectorActor.h
index ded3cb26ff2651fbb4fea441f95f71ee4c1ef563..143741b7ce507fd7860d8a04e4aeee21a2ad0a68 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/RectangularDetectorActor.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/RectangularDetectorActor.h
@@ -1,109 +1,109 @@
-#ifndef RECTANGULAR_DETECTOR_ACTOR__H_
-#define RECTANGULAR_DETECTOR_ACTOR__H_
-#include "GLActor.h"
-#include "ObjComponentActor.h"
-#include "ICompAssemblyActor.h"
-#include "MantidGeometry/IComponent.h"
-#include "MantidGeometry/Instrument/RectangularDetector.h"
-#include "MantidGeometry/V3D.h"
-/**
-  \class  RectangularDetectorActor
-  \brief  This class wraps a RectangularDetector into Actor.
-  \author Janik Zikovsky
-  \date   October 7 2010
-  \version 1.0
-
-  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
-
-  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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-*/
-namespace Mantid
-{
-
-namespace Geometry
-{
-  class ICompAssembly;
-  class Object;
-  class V3D;
-}
-namespace API
-{
-  class IInstrument;
-}
-
-}
-
-class MantidObject;
-class ObjComponentActor;
-
-class RectangularDetectorActor : public ICompAssemblyActor //ObjComponentActor
-{
-public:
-  /// Constructor
-  RectangularDetectorActor(boost::shared_ptr<Mantid::Geometry::RectangularDetector> rectDet);
-  /// Destructor
-  virtual ~RectangularDetectorActor();
-
-private:
-  void AppendBoundingBox(const Mantid::Geometry::V3D& minBound,const Mantid::Geometry::V3D& maxBound);
-
-protected:
-  /// The rectangular detector
-  boost::shared_ptr<Mantid::Geometry::RectangularDetector> mDet;
-
-  void init();
-  void redraw();
-  int findDetectorIDUsingColor(int rgb);
-  virtual void initChilds(bool) {}
-
-public:
-  virtual std::string type()const {return "RectangularDetectorActor";} ///< Type of the GL object
-
-  void define();  ///< Method that defines ObjComponent geometry. Calls ObjComponent draw method
-
-  void appendObjCompID(std::vector<int>& idList);
-  int setInternalDetectorColors(std::vector<boost::shared_ptr<GLColor> >::iterator & list);
-  int genTexture(char * & image_data, std::vector<boost::shared_ptr<GLColor> >::iterator& list, bool useDetectorIDs);
-  void uploadTexture(char * & image_data);
-  void getBoundingBox(Mantid::Geometry::V3D& minBound,Mantid::Geometry::V3D& maxBound);
-
-  virtual int  setStartingReferenceColor(int rgb);
-  virtual void drawUsingColorID();
-
-  virtual MantidObject* getMantidObject(const boost::shared_ptr<const Mantid::Geometry::Object>, bool)
-  {
-    return NULL;
-  }
-
-private:
-  /// Texture ID that holds the texture.
-  unsigned int mTextureID;
-
-  /// Pointer to the array holding the texture color data
-  char * image_data;
-
-  /// Pointer to the array holding the color data for picking the scene
-  char * pick_data;
-
-
-};
-
-#endif /*RECTANGULAR_DETECTOR_ACTOR__H_*/
-
+#ifndef RECTANGULAR_DETECTOR_ACTOR__H_
+#define RECTANGULAR_DETECTOR_ACTOR__H_
+#include "GLActor.h"
+#include "ObjComponentActor.h"
+#include "ICompAssemblyActor.h"
+#include "MantidGeometry/IComponent.h"
+#include "MantidGeometry/Instrument/RectangularDetector.h"
+#include "MantidGeometry/V3D.h"
+/**
+  \class  RectangularDetectorActor
+  \brief  This class wraps a RectangularDetector into Actor.
+  \author Janik Zikovsky
+  \date   October 7 2010
+  \version 1.0
+
+  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
+
+  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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+*/
+namespace Mantid
+{
+
+namespace Geometry
+{
+  class ICompAssembly;
+  class Object;
+  class V3D;
+}
+namespace API
+{
+  class IInstrument;
+}
+
+}
+
+class MantidObject;
+class ObjComponentActor;
+
+class RectangularDetectorActor : public ICompAssemblyActor //ObjComponentActor
+{
+public:
+  /// Constructor
+  RectangularDetectorActor(boost::shared_ptr<Mantid::Geometry::RectangularDetector> rectDet);
+  /// Destructor
+  virtual ~RectangularDetectorActor();
+
+private:
+  void AppendBoundingBox(const Mantid::Geometry::V3D& minBound,const Mantid::Geometry::V3D& maxBound);
+
+protected:
+  /// The rectangular detector
+  boost::shared_ptr<Mantid::Geometry::RectangularDetector> mDet;
+
+  void init();
+  void redraw();
+  int findDetectorIDUsingColor(int rgb);
+  virtual void initChilds(bool) {}
+
+public:
+  virtual std::string type()const {return "RectangularDetectorActor";} ///< Type of the GL object
+
+  void define();  ///< Method that defines ObjComponent geometry. Calls ObjComponent draw method
+
+  void appendObjCompID(std::vector<int>& idList);
+  int setInternalDetectorColors(std::vector<boost::shared_ptr<GLColor> >::iterator & list);
+  int genTexture(char * & image_data, std::vector<boost::shared_ptr<GLColor> >::iterator& list, bool useDetectorIDs);
+  void uploadTexture(char * & image_data);
+  void getBoundingBox(Mantid::Geometry::V3D& minBound,Mantid::Geometry::V3D& maxBound);
+
+  virtual int  setStartingReferenceColor(int rgb);
+  virtual void drawUsingColorID();
+
+  virtual MantidObject* getMantidObject(const boost::shared_ptr<const Mantid::Geometry::Object>, bool)
+  {
+    return NULL;
+  }
+
+private:
+  /// Texture ID that holds the texture.
+  unsigned int mTextureID;
+
+  /// Pointer to the array holding the texture color data
+  char * image_data;
+
+  /// Pointer to the array holding the color data for picking the scene
+  char * pick_data;
+
+
+};
+
+#endif /*RECTANGULAR_DETECTOR_ACTOR__H_*/
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/ManageCustomMenus.cpp b/Code/Mantid/MantidPlot/src/Mantid/ManageCustomMenus.cpp
index bf36ddf8d74d316b3ec8ab38775eb82c92aea8d2..8da1ad82869e92b13ef818cfe67726c93d297a0a 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/ManageCustomMenus.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/ManageCustomMenus.cpp
@@ -1,51 +1,51 @@
-#include "ManageCustomMenus.h"
-#include "../ApplicationWindow.h"
-
-#include "MantidQtAPI/InterfaceManager.h"
-#include "MantidKernel/ConfigService.h"
-
-#include <QtGui>
-/**
-* 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_customInterfacesTree(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.
-*/
-void ManageCustomMenus::initLayout()
-{
-    m_scriptsTree = m_uiForm.twScripts;
-    m_customInterfacesTree = m_uiForm.twCustomInterfaces;
-    m_menusTree = m_uiForm.twMenus;
-
-    m_scriptsTree->setHeaderLabel("Python Scripts");
-    m_customInterfacesTree->setHeaderLabel("Custom Interfaces");
-    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
-    getCustomInterfaceList();
-    populateMenuTree();
-}
-/**
-* Populates the m_menusTree to reflect the currently set custom menus.
-*/
-void ManageCustomMenus::populateMenuTree()
-{
+#include "ManageCustomMenus.h"
+#include "../ApplicationWindow.h"
+
+#include "MantidQtAPI/InterfaceManager.h"
+#include "MantidKernel/ConfigService.h"
+
+#include <QtGui>
+/**
+* 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_customInterfacesTree(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.
+*/
+void ManageCustomMenus::initLayout()
+{
+    m_scriptsTree = m_uiForm.twScripts;
+    m_customInterfacesTree = m_uiForm.twCustomInterfaces;
+    m_menusTree = m_uiForm.twMenus;
+
+    m_scriptsTree->setHeaderLabel("Python Scripts");
+    m_customInterfacesTree->setHeaderLabel("Custom Interfaces");
+    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
+    getCustomInterfaceList();
+    populateMenuTree();
+}
+/**
+* Populates the m_menusTree to reflect the currently set custom menus.
+*/
+void ManageCustomMenus::populateMenuTree()
+{
     m_menusTree->clear();
     m_widgetMap.clear();
 
@@ -69,13 +69,13 @@ void ManageCustomMenus::populateMenuTree()
             menu->addChild(item);
         }
         m_menusTree->addTopLevelItem(menu);    
-    }
-}
-/**
-* Gets the list of Custom Interfaces that have been registered with Mantid.
-*/
-void ManageCustomMenus::getCustomInterfaceList()
-{
+    }
+}
+/**
+* Gets the list of Custom Interfaces that have been registered with Mantid.
+*/
+void ManageCustomMenus::getCustomInterfaceList()
+{
     QStringList user_windows = MantidQt::API::InterfaceManager::Instance().getUserSubWindowKeys();
     QStringListIterator itr(user_windows);
     while( itr.hasNext() )
@@ -86,37 +86,37 @@ void ManageCustomMenus::getCustomInterfaceList()
         item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable );
         m_customInterfacesTree->addTopLevelItem(item);
     }
-}
-/**
-* 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() + m_customInterfacesTree->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;
-}
-/**
-* 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
+}
+/**
+* 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() + m_customInterfacesTree->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;
+}
+/**
+* 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 )
         {
@@ -128,14 +128,14 @@ void ManageCustomMenus::addScriptClicked()
             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()
-{
+        }
+    }
+}
+/**
+* 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.");
@@ -146,32 +146,32 @@ void ManageCustomMenus::remScriptClicked()
         foreach(item, m_scriptsTree->selectedItems())
         {
             delete item;
-        }
-    }
-}
-/**
-* 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.");
-    }
-    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();
+        }
+    }
+}
+/**
+* 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.");
+    }
+    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;
@@ -181,50 +181,50 @@ void ManageCustomMenus::addItemClicked()
             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();
-        }
-    }
-}
-/**
-* 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();
-    }
-}
-/**
-* Adds new top-level menu to the interface.
-*/
-void ManageCustomMenus::addMenuClicked()
-{
+            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();
+        }
+    }
+}
+/**
+* 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();
+    }
+}
+/**
+* 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 )
@@ -242,12 +242,12 @@ void ManageCustomMenus::addMenuClicked()
             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);
-}
+}
+/**
+* Opens web browser to wiki page for this dialog.
+*/
+void ManageCustomMenus::helpClicked()
+{
+    QUrl helpUrl("http://www.mantidproject.org/ManageCustomMenus");
+    QDesktopServices::openUrl(helpUrl);
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/ManageCustomMenus.h b/Code/Mantid/MantidPlot/src/Mantid/ManageCustomMenus.h
index 11f7ec7ec3c24c9534c0775497f15379eae4820a..375cfbda865d4e7e6613eca3ac271be800ac7a1f 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/ManageCustomMenus.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/ManageCustomMenus.h
@@ -1,11 +1,11 @@
-#ifndef MANTID_MANAGE_CUSTOM_MENUS_H
-#define MANTID_MANAGE_CUSTOM_MENUS_H
-
-#include <QDialog>
-#include "ui_ManageCustomMenus.h"
-
-class ApplicationWindow;
-
+#ifndef MANTID_MANAGE_CUSTOM_MENUS_H
+#define MANTID_MANAGE_CUSTOM_MENUS_H
+
+#include <QDialog>
+#include "ui_ManageCustomMenus.h"
+
+class ApplicationWindow;
+
 /** 
 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.
@@ -31,33 +31,33 @@ along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 File change history is stored at: <https://svn.mantidproject.org/mantid/trunk/Code/Mantid>
 Code Documentation is available at: <http://doxygen.mantidproject.org>    
-*/
-class ManageCustomMenus : public QDialog
-{
-	Q_OBJECT
-public:
-	ManageCustomMenus(QWidget *parent = 0);
-private:
-    void initLayout();
-    void populateMenuTree();
-    void getCustomInterfaceList();
-    QList<QTreeWidgetItem*> getCurrentSelection();
-    QTreeWidgetItem* getCurrentMenuSelection();
-private slots:
-    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;
-};
-
+*/
+class ManageCustomMenus : public QDialog
+{
+	Q_OBJECT
+public:
+	ManageCustomMenus(QWidget *parent = 0);
+private:
+    void initLayout();
+    void populateMenuTree();
+    void getCustomInterfaceList();
+    QList<QTreeWidgetItem*> getCurrentSelection();
+    QTreeWidgetItem* getCurrentMenuSelection();
+private slots:
+    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;
+};
+
 #endif /* MANTID_MANAGE_CUSTOM_MENUS_H */
\ No newline at end of file
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidCurve.h b/Code/Mantid/MantidPlot/src/Mantid/MantidCurve.h
index 1c95e4f306c8c5c42a85e408e1699ef4e108bec1..f11aa84dccf9c28547d174c44f66a6c06a21237b 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidCurve.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidCurve.h
@@ -1,232 +1,232 @@
-#ifndef MANTID_CURVE_H
-#define MANTID_CURVE_H
-
-#include "../PlotCurve.h"
-#include "WorkspaceObserver.h"
-#include "boost/shared_ptr.hpp"
-#include "MantidAPI/MatrixWorkspace.h"
-
-
-// Forward definitions
-
-class MantidQwtData;
-class Graph;
-class MantidUI;
-
-/** 
-    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
-
-    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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
-*/
-
-class MantidCurve:public PlotCurve, public WorkspaceObserver
-{
-  Q_OBJECT
-public:
-
-  /// More complex constructor setting some defaults for the curve
-  MantidCurve(const QString& name,const QString& wsName,Graph* g,
-              const QString& type,int index,bool err=false);
-
-  /// More complex constructor setting some defaults for the curve
-  MantidCurve(const QString& wsName,Graph* g,
-              const QString& type,int index,bool err=false);
-
-  /// Copy constructor 
-  MantidCurve(const MantidCurve& c);
-
-  ~MantidCurve();
-
-  PlotCurve* clone()const{return new MantidCurve(*this);}
-
-  /// Curve type. Used in the QtiPlot API.
-  int rtti() const{return Rtti_PlotUserItem;}
-
-  /// Overrides qwt_plot_curve::setData to make sure only data of MantidQwtData type can  be set
-  void setData(const QwtData &data);
-
-  /// Overrides qwt_plot_curve::boundingRect
-  QwtDoubleRect boundingRect() const;
-  /// Invalidates the bounding rect forcing it to be recalculated
-  void invalidateBoundingRect(){m_boundingRect = QwtDoubleRect();}
-
-  /// Return pointer to the data if it of the right type or 0 otherwise
-  MantidQwtData* mantidData();
-  /// Return pointer to the data if it of the right type or 0 otherwise, const version
-  const MantidQwtData* mantidData()const;
-
-  /// Enables/disables drawing of error bars
-  void setErrorBars(bool yes=true,bool drawAll = false){m_drawErrorBars = yes;m_drawAllErrorBars = drawAll;}
-
-  virtual void draw(QPainter *p, 
-    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
-    const QRect &) const;
-
-  /// Overriden virtual method
-  void itemChanged();
-  /// saves the mantidcurve details to project file.
-  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;
-
-private:
-  /// Init the curve
-  void init(boost::shared_ptr<const Mantid::API::MatrixWorkspace> workspace,Graph* g,
-              int index);
-
-  /// Handles delete notification
-  void deleteHandle(const std::string& wsName,const boost::shared_ptr<Mantid::API::Workspace> ws)
-  {
-    (void) ws; //Avoid compiler warning
-    if (wsName == m_wsName.toStdString())
-    {
-      observeDelete(false);
-      emit removeMe(this);
-    }
-  }
-  /// Handles afterReplace notification
-  void afterReplaceHandle(const std::string& wsName,const boost::shared_ptr<Mantid::API::Workspace> ws);
-
-  /// Handle an ADS clear notificiation
-  void clearADSHandle()
-  {
-    emit removeMe(this);
-  }
-
-signals:
-
-  void resetData(const QString&);
-
-private slots:
-
-  void dataReset(const QString&);
-
-  void axisScaleChanged(int axis, bool toLog);
-
-private:
-
-  /// Make the curve name
-  static QString createCurveName(const boost::shared_ptr<const Mantid::API::MatrixWorkspace> ws,
-                                 const QString& wsName,int index);
-  /// Make a name for a copied curve
-  static QString createCopyName(const QString& curveName);
-  bool m_drawErrorBars;///< True for drawing error bars
-  bool m_drawAllErrorBars; ///< if true and m_drawErrorBars is true draw all error bars (no skipping)
-  QString m_wsName;///< Workspace name. If empty the ws isn't in the data service
-  /// workspace index
-  int  m_index;
-  /// The bounding rect used by qwt to set the axes
-  mutable QwtDoubleRect m_boundingRect;
-};
-
-
-//=================================================================================================
-//=================================================================================================
-/**  This class implements QwtData with direct access to a spectrum in a MatrixWorkspace.
- */
-class MantidQwtData: public QObject, public QwtData
-{
-  Q_OBJECT
-public:
-  /// Constructor
-  MantidQwtData(Mantid::API::MatrixWorkspace_const_sptr workspace, int specIndex, const bool logScale);
-
-  /// Copy constructor
-  MantidQwtData(const MantidQwtData& data);
-
-    //! @return Pointer to a copy (virtual copy constructor)
-  virtual QwtData *copy() const {return new MantidQwtData(*this);}
-
-  //! @return Size of the data set
-  virtual size_t size() const;
-
-  /**
-  Return the x value of data point i
-  @param i :: Index
-  @return x X value of data point i
-  */
-  virtual double x(size_t i) const;
-  /**
-  Return the y value of data point i
-  @param i :: Index
-  @return y Y value of data point i
-  */
-  virtual double y(size_t i) const;
-
-  /// Return a new data object of the same type but with a new workspace
-  virtual MantidQwtData* copy(boost::shared_ptr<const Mantid::API::MatrixWorkspace> workspace)const
-  {
-    return new MantidQwtData(workspace,m_spec, m_logScale);
-  }
-  /// Returns the error of the i-th data point
-  double e(size_t i)const;
-  /// Returns the x position of the error bar for the i-th data point (bin)
-  double ex(size_t i)const;
-  /// Number of error bars to plot
-  int esize()const;
-
-  bool isHistogram()const{return m_isHistogram;}
-
-  bool sameWorkspace(boost::shared_ptr<const Mantid::API::MatrixWorkspace> workspace)const;
-
-  /// Inform the data that it is to be plotted on a log y scale
-  void setLogScale(bool on);
-  bool logScale()const{return m_logScale;}
-  void saveLowestPositiveValue(const double v);
-
-private:
-
-  friend class MantidCurve;
-
-  /// Pointer to the Mantid workspace
-  boost::shared_ptr<const Mantid::API::MatrixWorkspace> m_workspace;
-  /// Spectrum index in the workspace
-  int m_spec;
-  /// Copy of the X vector
-  const Mantid::MantidVec m_X;
-
-  /// Copy of the Y vector
-  const Mantid::MantidVec m_Y;
-
-  /// Copy of the E vector
-  const Mantid::MantidVec m_E;
-
-  /// Is the spectrum a histogram?
-  bool m_isHistogram;
-  /// This field can be set true for a histogram worspace. If it's true x(i) returns (X[i]+X[i+1])/2
-  bool m_binCentres;
-  /// Indicates that the data is plotted on a log y scale
-  bool m_logScale;
-  /// lowest positive y value
-  mutable double m_minPositive;
-
-};
-
-
-#endif // MANTID_CURVE_H
+#ifndef MANTID_CURVE_H
+#define MANTID_CURVE_H
+
+#include "../PlotCurve.h"
+#include "WorkspaceObserver.h"
+#include "boost/shared_ptr.hpp"
+#include "MantidAPI/MatrixWorkspace.h"
+
+
+// Forward definitions
+
+class MantidQwtData;
+class Graph;
+class MantidUI;
+
+/** 
+    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
+
+    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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+*/
+
+class MantidCurve:public PlotCurve, public WorkspaceObserver
+{
+  Q_OBJECT
+public:
+
+  /// More complex constructor setting some defaults for the curve
+  MantidCurve(const QString& name,const QString& wsName,Graph* g,
+              const QString& type,int index,bool err=false);
+
+  /// More complex constructor setting some defaults for the curve
+  MantidCurve(const QString& wsName,Graph* g,
+              const QString& type,int index,bool err=false);
+
+  /// Copy constructor 
+  MantidCurve(const MantidCurve& c);
+
+  ~MantidCurve();
+
+  PlotCurve* clone()const{return new MantidCurve(*this);}
+
+  /// Curve type. Used in the QtiPlot API.
+  int rtti() const{return Rtti_PlotUserItem;}
+
+  /// Overrides qwt_plot_curve::setData to make sure only data of MantidQwtData type can  be set
+  void setData(const QwtData &data);
+
+  /// Overrides qwt_plot_curve::boundingRect
+  QwtDoubleRect boundingRect() const;
+  /// Invalidates the bounding rect forcing it to be recalculated
+  void invalidateBoundingRect(){m_boundingRect = QwtDoubleRect();}
+
+  /// Return pointer to the data if it of the right type or 0 otherwise
+  MantidQwtData* mantidData();
+  /// Return pointer to the data if it of the right type or 0 otherwise, const version
+  const MantidQwtData* mantidData()const;
+
+  /// Enables/disables drawing of error bars
+  void setErrorBars(bool yes=true,bool drawAll = false){m_drawErrorBars = yes;m_drawAllErrorBars = drawAll;}
+
+  virtual void draw(QPainter *p, 
+    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
+    const QRect &) const;
+
+  /// Overriden virtual method
+  void itemChanged();
+  /// saves the mantidcurve details to project file.
+  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;
+
+private:
+  /// Init the curve
+  void init(boost::shared_ptr<const Mantid::API::MatrixWorkspace> workspace,Graph* g,
+              int index);
+
+  /// Handles delete notification
+  void deleteHandle(const std::string& wsName,const boost::shared_ptr<Mantid::API::Workspace> ws)
+  {
+    (void) ws; //Avoid compiler warning
+    if (wsName == m_wsName.toStdString())
+    {
+      observeDelete(false);
+      emit removeMe(this);
+    }
+  }
+  /// Handles afterReplace notification
+  void afterReplaceHandle(const std::string& wsName,const boost::shared_ptr<Mantid::API::Workspace> ws);
+
+  /// Handle an ADS clear notificiation
+  void clearADSHandle()
+  {
+    emit removeMe(this);
+  }
+
+signals:
+
+  void resetData(const QString&);
+
+private slots:
+
+  void dataReset(const QString&);
+
+  void axisScaleChanged(int axis, bool toLog);
+
+private:
+
+  /// Make the curve name
+  static QString createCurveName(const boost::shared_ptr<const Mantid::API::MatrixWorkspace> ws,
+                                 const QString& wsName,int index);
+  /// Make a name for a copied curve
+  static QString createCopyName(const QString& curveName);
+  bool m_drawErrorBars;///< True for drawing error bars
+  bool m_drawAllErrorBars; ///< if true and m_drawErrorBars is true draw all error bars (no skipping)
+  QString m_wsName;///< Workspace name. If empty the ws isn't in the data service
+  /// workspace index
+  int  m_index;
+  /// The bounding rect used by qwt to set the axes
+  mutable QwtDoubleRect m_boundingRect;
+};
+
+
+//=================================================================================================
+//=================================================================================================
+/**  This class implements QwtData with direct access to a spectrum in a MatrixWorkspace.
+ */
+class MantidQwtData: public QObject, public QwtData
+{
+  Q_OBJECT
+public:
+  /// Constructor
+  MantidQwtData(Mantid::API::MatrixWorkspace_const_sptr workspace, int specIndex, const bool logScale);
+
+  /// Copy constructor
+  MantidQwtData(const MantidQwtData& data);
+
+    //! @return Pointer to a copy (virtual copy constructor)
+  virtual QwtData *copy() const {return new MantidQwtData(*this);}
+
+  //! @return Size of the data set
+  virtual size_t size() const;
+
+  /**
+  Return the x value of data point i
+  @param i :: Index
+  @return x X value of data point i
+  */
+  virtual double x(size_t i) const;
+  /**
+  Return the y value of data point i
+  @param i :: Index
+  @return y Y value of data point i
+  */
+  virtual double y(size_t i) const;
+
+  /// Return a new data object of the same type but with a new workspace
+  virtual MantidQwtData* copy(boost::shared_ptr<const Mantid::API::MatrixWorkspace> workspace)const
+  {
+    return new MantidQwtData(workspace,m_spec, m_logScale);
+  }
+  /// Returns the error of the i-th data point
+  double e(size_t i)const;
+  /// Returns the x position of the error bar for the i-th data point (bin)
+  double ex(size_t i)const;
+  /// Number of error bars to plot
+  int esize()const;
+
+  bool isHistogram()const{return m_isHistogram;}
+
+  bool sameWorkspace(boost::shared_ptr<const Mantid::API::MatrixWorkspace> workspace)const;
+
+  /// Inform the data that it is to be plotted on a log y scale
+  void setLogScale(bool on);
+  bool logScale()const{return m_logScale;}
+  void saveLowestPositiveValue(const double v);
+
+private:
+
+  friend class MantidCurve;
+
+  /// Pointer to the Mantid workspace
+  boost::shared_ptr<const Mantid::API::MatrixWorkspace> m_workspace;
+  /// Spectrum index in the workspace
+  int m_spec;
+  /// Copy of the X vector
+  const Mantid::MantidVec m_X;
+
+  /// Copy of the Y vector
+  const Mantid::MantidVec m_Y;
+
+  /// Copy of the E vector
+  const Mantid::MantidVec m_E;
+
+  /// Is the spectrum a histogram?
+  bool m_isHistogram;
+  /// This field can be set true for a histogram worspace. If it's true x(i) returns (X[i]+X[i+1])/2
+  bool m_binCentres;
+  /// Indicates that the data is plotted on a log y scale
+  bool m_logScale;
+  /// lowest positive y value
+  mutable double m_minPositive;
+
+};
+
+
+#endif // MANTID_CURVE_H
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp
index 51d13ac4ab6c842563b37c9ac1d4004ba2279d5f..ca282d61949a9d37afaddf5832c06bbfa423b5cc 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.cpp
@@ -648,10 +648,10 @@ void MantidDockWidget::addWorkspaceGroupMenuItems(QMenu *menu) const
  * Add the actions that are appropriate for a MatrixWorspace
  * @param menu :: The menu to store the items
  */
-void MantidDockWidget::addTableWorkspaceMenuItems(QMenu * menu) const
-{
-  menu->addAction(m_showData);
-  menu->addAction(m_showHist);
+void MantidDockWidget::addTableWorkspaceMenuItems(QMenu * menu) const
+{
+  menu->addAction(m_showData);
+  menu->addAction(m_showHist);
 }
 
 void MantidDockWidget::clickedWorkspace(QTreeWidgetItem* item, int)
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.h b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.h
index faf22534bdd4c0ae47af2026b0335d04272a4349..491837e2c447843efd735a6479dc4a6f07c2fd0c 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidDock.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidDock.h
@@ -1,165 +1,165 @@
-#ifndef MANTIDDOCK_H
-#define MANTIDDOCK_H
-
-#include <QDockWidget>
-#include <QTreeWidget>
-#include <QComboBox>
-#include <QPoint>
-#include <QVector>
-#include "MantidAPI/MatrixWorkspace.h"
-#include "MantidAPI/WorkspaceGroup.h"
-#include "MantidAPI/ITableWorkspace.h"
-#include "MantidAPI/IMDEventWorkspace.h"
-
-class MantidUI;
-class ApplicationWindow;
-class MantidTreeWidget;
-class QLabel;
-class QMenu;
-class QPushButton;
-class QTreeWidget;
-class QProgressBar;
-class QVBoxLayout;
-class QHBoxLayout;
-class QSignalMapper;
-
-class MantidDockWidget: public QDockWidget
-{
-  Q_OBJECT
-public:
-  MantidDockWidget(MantidUI *mui, ApplicationWindow *parent);
-  QString getSelectedWorkspaceName() const;
-  Mantid::API::Workspace_sptr getSelectedWorkspace() const;
-
-public slots:
-  void clickedWorkspace(QTreeWidgetItem*, int);
-  void deleteWorkspaces();
-  void renameWorkspace();
-  void populateChildData(QTreeWidgetItem* item);
-
-protected slots:
-  void popupMenu(const QPoint & pos);
-  void workspaceSelected();
-
-private slots:
-  void addTreeEntry(const QString &, Mantid::API::Workspace_sptr);
-  void replaceTreeEntry(const QString &, Mantid::API::Workspace_sptr);
-  void unrollWorkspaceGroup(const QString &,Mantid::API::Workspace_sptr);
-  void removeWorkspaceEntry(const QString &);
-  void treeSelectionChanged();
-  void groupingButtonClick();
-  void plotSpectra();
-  void drawColorFillPlot();
-
-private:
-  void createWorkspaceMenuActions();
-  QString findParentName(const QString & ws_name, Mantid::API::Workspace_sptr workspace);
-  void setItemIcon(QTreeWidgetItem* ws_item,  Mantid::API::Workspace_sptr workspace);
-  QTreeWidgetItem *createEntry(const QString & ws_name, Mantid::API::Workspace_sptr workspace);
-  void updateWorkspaceEntry(const QString & ws_name, Mantid::API::Workspace_sptr workspace);
-  void updateWorkspaceGroupEntry(const QString & ws_name, Mantid::API::WorkspaceGroup_sptr workspace);
-  void populateMDEventWorkspaceData(Mantid::API::IMDEventWorkspace_sptr workspace, QTreeWidgetItem* ws_item);
-  void populateMatrixWorkspaceData(Mantid::API::MatrixWorkspace_sptr workspace, QTreeWidgetItem* ws_item);
-  void populateWorkspaceGroupData(Mantid::API::WorkspaceGroup_sptr workspace, QTreeWidgetItem* ws_item);
-  void populateTableWorkspaceData(Mantid::API::ITableWorkspace_sptr workspace, QTreeWidgetItem* ws_item);
-  void addMatrixWorspaceMenuItems(QMenu *menu, Mantid::API::MatrixWorkspace_const_sptr matrixWS) const;
+#ifndef MANTIDDOCK_H
+#define MANTIDDOCK_H
+
+#include <QDockWidget>
+#include <QTreeWidget>
+#include <QComboBox>
+#include <QPoint>
+#include <QVector>
+#include "MantidAPI/MatrixWorkspace.h"
+#include "MantidAPI/WorkspaceGroup.h"
+#include "MantidAPI/ITableWorkspace.h"
+#include "MantidAPI/IMDEventWorkspace.h"
+
+class MantidUI;
+class ApplicationWindow;
+class MantidTreeWidget;
+class QLabel;
+class QMenu;
+class QPushButton;
+class QTreeWidget;
+class QProgressBar;
+class QVBoxLayout;
+class QHBoxLayout;
+class QSignalMapper;
+
+class MantidDockWidget: public QDockWidget
+{
+  Q_OBJECT
+public:
+  MantidDockWidget(MantidUI *mui, ApplicationWindow *parent);
+  QString getSelectedWorkspaceName() const;
+  Mantid::API::Workspace_sptr getSelectedWorkspace() const;
+
+public slots:
+  void clickedWorkspace(QTreeWidgetItem*, int);
+  void deleteWorkspaces();
+  void renameWorkspace();
+  void populateChildData(QTreeWidgetItem* item);
+
+protected slots:
+  void popupMenu(const QPoint & pos);
+  void workspaceSelected();
+
+private slots:
+  void addTreeEntry(const QString &, Mantid::API::Workspace_sptr);
+  void replaceTreeEntry(const QString &, Mantid::API::Workspace_sptr);
+  void unrollWorkspaceGroup(const QString &,Mantid::API::Workspace_sptr);
+  void removeWorkspaceEntry(const QString &);
+  void treeSelectionChanged();
+  void groupingButtonClick();
+  void plotSpectra();
+  void drawColorFillPlot();
+
+private:
+  void createWorkspaceMenuActions();
+  QString findParentName(const QString & ws_name, Mantid::API::Workspace_sptr workspace);
+  void setItemIcon(QTreeWidgetItem* ws_item,  Mantid::API::Workspace_sptr workspace);
+  QTreeWidgetItem *createEntry(const QString & ws_name, Mantid::API::Workspace_sptr workspace);
+  void updateWorkspaceEntry(const QString & ws_name, Mantid::API::Workspace_sptr workspace);
+  void updateWorkspaceGroupEntry(const QString & ws_name, Mantid::API::WorkspaceGroup_sptr workspace);
+  void populateMDEventWorkspaceData(Mantid::API::IMDEventWorkspace_sptr workspace, QTreeWidgetItem* ws_item);
+  void populateMatrixWorkspaceData(Mantid::API::MatrixWorkspace_sptr workspace, QTreeWidgetItem* ws_item);
+  void populateWorkspaceGroupData(Mantid::API::WorkspaceGroup_sptr workspace, QTreeWidgetItem* ws_item);
+  void populateTableWorkspaceData(Mantid::API::ITableWorkspace_sptr workspace, QTreeWidgetItem* ws_item);
+  void addMatrixWorspaceMenuItems(QMenu *menu, Mantid::API::MatrixWorkspace_const_sptr matrixWS) const;
   void addMDEventWorspaceMenuItems(QMenu *menu, Mantid::API::IMDEventWorkspace_const_sptr mdeventWS) const;
   void addWorkspaceGroupMenuItems(QMenu *menu) const;
-  void addTableWorkspaceMenuItems(QMenu * menu) const;
-  bool isInvisibleWorkspaceOptionSet();
-  
-protected:
-  MantidTreeWidget * m_tree;
-  friend class MantidUI;
-
-private:
-  MantidUI * const m_mantidUI;
-  QSet<QString> m_known_groups;
-
-  QPushButton *m_loadButton;
-  QMenu *m_loadMenu;
-  QPushButton *m_deleteButton;
-  QPushButton *m_groupButton;
-  QSignalMapper *m_loadMapper;
-
-  //Context-menu actions
-  QAction *m_showData, *m_showInst, *m_plotSpec, *m_colorFill, *m_showLogs, *m_showHist, 
-    *m_saveNexus, *m_rename, *m_delete;
-
-  static Mantid::Kernel::Logger& logObject;
-};
-
-
-class MantidTreeWidget:public QTreeWidget
-{
-  Q_OBJECT
-
-public:
-  MantidTreeWidget(QWidget *w, MantidUI *mui);
-  void mousePressEvent (QMouseEvent *e);
-  void mouseMoveEvent(QMouseEvent *e);
-  void mouseDoubleClickEvent(QMouseEvent *e);
-
-  QStringList getSelectedWorkspaceNames() const;
-  QMultiMap<QString,int> chooseSpectrumFromSelected() const;
-  
-private:
-  QPoint m_dragStartPosition;
-  MantidUI *m_mantidUI;
-  static Mantid::Kernel::Logger& logObject;
-};
-
-class FindAlgComboBox:public QComboBox
-{
-    Q_OBJECT
-signals:
-    void enterPressed();
-protected:
-    void keyPressEvent(QKeyEvent *e);
-};
-
-class AlgorithmDockWidget: public QDockWidget
-{
-    Q_OBJECT
-public:
-    AlgorithmDockWidget(MantidUI *mui, ApplicationWindow *w);
-public slots:
-    void update();
-    void findAlgTextChanged(const QString& text);
-    void treeSelectionChanged();
-    void selectionChanged(const QString& algName);
-    void updateProgress(void* alg, const int p, const QString& msg);
-    void algorithmStarted(void* alg);
-    void algorithmFinished(void* alg);
-protected:
-    void showProgressBar();
-    void hideProgressBar();
-
-    QTreeWidget *m_tree;
-    FindAlgComboBox* m_findAlg;
-    QPushButton *m_runningButton;
-    QProgressBar* m_progressBar;
-    QHBoxLayout * m_runningLayout;
-    bool m_treeChanged;
-    bool m_findAlgChanged;
-    QVector<void*> m_algID;
-    friend class MantidUI;
-private:
-    MantidUI *m_mantidUI;
-};
-
-
-class AlgorithmTreeWidget:public QTreeWidget
-{
-    Q_OBJECT
-public:
-    AlgorithmTreeWidget(QWidget *w, MantidUI *mui):QTreeWidget(w),m_mantidUI(mui){}
-    void mousePressEvent (QMouseEvent *e);
-    void mouseMoveEvent(QMouseEvent *e);
-    void mouseDoubleClickEvent(QMouseEvent *e);
-private:
-    QPoint m_dragStartPosition;
-    MantidUI *m_mantidUI;
-};
-
-#endif
+  void addTableWorkspaceMenuItems(QMenu * menu) const;
+  bool isInvisibleWorkspaceOptionSet();
+  
+protected:
+  MantidTreeWidget * m_tree;
+  friend class MantidUI;
+
+private:
+  MantidUI * const m_mantidUI;
+  QSet<QString> m_known_groups;
+
+  QPushButton *m_loadButton;
+  QMenu *m_loadMenu;
+  QPushButton *m_deleteButton;
+  QPushButton *m_groupButton;
+  QSignalMapper *m_loadMapper;
+
+  //Context-menu actions
+  QAction *m_showData, *m_showInst, *m_plotSpec, *m_colorFill, *m_showLogs, *m_showHist, 
+    *m_saveNexus, *m_rename, *m_delete;
+
+  static Mantid::Kernel::Logger& logObject;
+};
+
+
+class MantidTreeWidget:public QTreeWidget
+{
+  Q_OBJECT
+
+public:
+  MantidTreeWidget(QWidget *w, MantidUI *mui);
+  void mousePressEvent (QMouseEvent *e);
+  void mouseMoveEvent(QMouseEvent *e);
+  void mouseDoubleClickEvent(QMouseEvent *e);
+
+  QStringList getSelectedWorkspaceNames() const;
+  QMultiMap<QString,int> chooseSpectrumFromSelected() const;
+  
+private:
+  QPoint m_dragStartPosition;
+  MantidUI *m_mantidUI;
+  static Mantid::Kernel::Logger& logObject;
+};
+
+class FindAlgComboBox:public QComboBox
+{
+    Q_OBJECT
+signals:
+    void enterPressed();
+protected:
+    void keyPressEvent(QKeyEvent *e);
+};
+
+class AlgorithmDockWidget: public QDockWidget
+{
+    Q_OBJECT
+public:
+    AlgorithmDockWidget(MantidUI *mui, ApplicationWindow *w);
+public slots:
+    void update();
+    void findAlgTextChanged(const QString& text);
+    void treeSelectionChanged();
+    void selectionChanged(const QString& algName);
+    void updateProgress(void* alg, const int p, const QString& msg);
+    void algorithmStarted(void* alg);
+    void algorithmFinished(void* alg);
+protected:
+    void showProgressBar();
+    void hideProgressBar();
+
+    QTreeWidget *m_tree;
+    FindAlgComboBox* m_findAlg;
+    QPushButton *m_runningButton;
+    QProgressBar* m_progressBar;
+    QHBoxLayout * m_runningLayout;
+    bool m_treeChanged;
+    bool m_findAlgChanged;
+    QVector<void*> m_algID;
+    friend class MantidUI;
+private:
+    MantidUI *m_mantidUI;
+};
+
+
+class AlgorithmTreeWidget:public QTreeWidget
+{
+    Q_OBJECT
+public:
+    AlgorithmTreeWidget(QWidget *w, MantidUI *mui):QTreeWidget(w),m_mantidUI(mui){}
+    void mousePressEvent (QMouseEvent *e);
+    void mouseMoveEvent(QMouseEvent *e);
+    void mouseDoubleClickEvent(QMouseEvent *e);
+private:
+    QPoint m_dragStartPosition;
+    MantidUI *m_mantidUI;
+};
+
+#endif
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidLog.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidLog.cpp
index 641394547b0e39196873c001aa425c48f9dcbf9b..354412cbff517114f724a136cfac27f7ad523bcf 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidLog.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidLog.cpp
@@ -1,8 +1,8 @@
-#include "MantidLog.h"
-#include "MantidUI.h"
-#include <iostream>
-using namespace std;
-
+#include "MantidLog.h"
+#include "MantidUI.h"
+#include <iostream>
+using namespace std;
+
 void MantidLog::connect(MantidUI* mui)
 {
     if (!s_Instance)
@@ -13,11 +13,11 @@ void MantidLog::connect(MantidUI* mui)
         s_Instance->AbstractMantidLog::connect();
     }
 }
-
-/// Posts message text to QtiPlot Result Log
-void MantidLog::log(const Poco::Message& msg)
-{
-    emit messageReceived(msg);
-}
-
+
+/// Posts message text to QtiPlot Result Log
+void MantidLog::log(const Poco::Message& msg)
+{
+    emit messageReceived(msg);
+}
+
 boost::shared_ptr<MantidLog> MantidLog::s_Instance;
\ No newline at end of file
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.cpp
index 6ef8a56a408ff90637e39432ac41a03d64625340..006be2b3a6599e6874cbd21ec8baca955ebd5818 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.cpp
@@ -1,1511 +1,1511 @@
-#include "MantidMatrix.h"
-#include "MantidKernel/Timer.h"
-#include "MantidUI.h"
-#include "../Graph3D.h"
-#include "../ApplicationWindow.h"
-#include "../Spectrogram.h"
-#include "MantidMatrixDialog.h"
-#include "Preferences.h"
-#include "../pixmaps.h"
-
-#include "MantidAPI/TextAxis.h"
-
-#include <QtGlobal>
-#include <QTextStream>
-#include <QList>
-#include <QEvent>
-#include <QContextMenuEvent>
-#include <QVBoxLayout>
-#include <QMouseEvent>
-#include <QHeaderView>
-#include <QApplication>
-#include <QVarLengthArray>
-#include <QClipboard>
-#include <QShortcut>
-#include <QPrinter>
-#include <QPrintDialog>
-#include <QPainter>
-#include <QLocale>
-#include <QItemDelegate>
-#include <QLabel>
-#include <QStackedWidget>
-#include <QImageWriter>
-#include <QSvgGenerator>
-#include <QFile>
-#include <QUndoStack>
-#include <QCheckBox>
-#include <QTabWidget>
-
-#include <stdlib.h>
-#include <iostream>
-#include <algorithm>
-#include <limits>
-
-using namespace Mantid;
-using namespace Mantid::API;
-using namespace Mantid::Kernel;
-
-//Mantid::Kernel::Logger & MantidMatrix::g_log=Mantid::Kernel::Logger::get("MantidMatrix");
-MantidMatrix::MantidMatrix(Mantid::API::MatrixWorkspace_sptr ws, ApplicationWindow* parent, const QString& label, const QString& name, int start, int end)
-  : MdiSubWindow(label, parent, name, 0),
-    WorkspaceObserver(),
-    y_start(0.0),y_end(0.0),
-    m_histogram(false),
-    m_min(0),m_max(0),
-    m_are_min_max_set(false),
-    m_boundingRect(),
-    m_funct(this),
-    m_selectedRows(),
-    m_selectedCols()
-{
-  m_appWindow = parent;
-  m_strName = name.toStdString();
-  m_workspace = ws;
-  setup(ws,start,end);
-  setWindowTitle(name);
-  setName(name);
-  setIcon( matrixIcon() );
-
-  m_modelY = new MantidMatrixModel(this,ws.get(),m_rows,m_cols,m_startRow,MantidMatrixModel::Y);
-  m_table_viewY = new QTableView();
-  connectTableView(m_table_viewY,m_modelY);
-  setColumnsWidth(0,MantidPreferences::MantidMatrixColumnWidthY());
-  setNumberFormat(0,MantidPreferences::MantidMatrixNumberFormatY(),
-                  MantidPreferences::MantidMatrixNumberPrecisionY());
-
-  m_modelX = new MantidMatrixModel(this,ws.get(),m_rows,m_cols,m_startRow,MantidMatrixModel::X);
-  m_table_viewX = new QTableView();
-  connectTableView(m_table_viewX,m_modelX);
-  setColumnsWidth(1,MantidPreferences::MantidMatrixColumnWidthX());
-  setNumberFormat(1,MantidPreferences::MantidMatrixNumberFormatX(),
-                  MantidPreferences::MantidMatrixNumberPrecisionX());
-
-  m_modelE = new MantidMatrixModel(this,ws.get(),m_rows,m_cols,m_startRow,MantidMatrixModel::E);
-  m_table_viewE = new QTableView();
-  connectTableView(m_table_viewE,m_modelE);
-  setColumnsWidth(2,MantidPreferences::MantidMatrixColumnWidthE());
-  setNumberFormat(2,MantidPreferences::MantidMatrixNumberFormatE(),
-                  MantidPreferences::MantidMatrixNumberPrecisionE());
-
-  m_YTabLabel = QString("Y values");
-  m_XTabLabel = QString("X values");
-  m_ETabLabel = QString("Errors");
-
-  m_tabs = new QTabWidget(this);
-  m_tabs->insertTab(0,m_table_viewY, m_YTabLabel);
-  m_tabs->insertTab(1,m_table_viewX, m_XTabLabel);
-  m_tabs->insertTab(2,m_table_viewE, m_ETabLabel);
-
-  setWidget(m_tabs);
-  //for synchronizing the views
-  //index is zero for the defualt view
-  m_PrevIndex=0;
-  //install event filter on  these objects
-  m_table_viewY->installEventFilter(this);
-  m_table_viewX->installEventFilter(this);
-  m_table_viewE->installEventFilter(this);
-
-  connect(m_tabs,SIGNAL(currentChanged(int)),this,SLOT(viewChanged(int)));
-
-  setGeometry(50, 50, QMIN(5, numCols())*m_table_viewY->horizontalHeader()->sectionSize(0) + 55,
-              (QMIN(10,numRows())+1)*m_table_viewY->verticalHeader()->sectionSize(0)+100);
-
-  observeAfterReplace();
-  observeDelete();
-  observeADSClear();
-
-  connect(this,SIGNAL(needWorkspaceChange(Mantid::API::MatrixWorkspace_sptr)),this,SLOT(changeWorkspace(Mantid::API::MatrixWorkspace_sptr))); 
-  connect(this,SIGNAL(needToClose()),this,SLOT(closeMatrix()));
-
-  connect(this, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(selfClosed(MdiSubWindow*)));
-
-  askOnCloseEvent(false);
-}
-
-MantidMatrix::~MantidMatrix()
-{
-  delete m_modelY;
-  delete m_modelX;
-  delete m_modelE;
-}
-
-bool MantidMatrix::eventFilter(QObject *object, QEvent *e)
-{
-  // if it's context menu on any of the views
-  if (e->type() == QEvent::ContextMenu && (object == m_table_viewY || object == m_table_viewX || object == m_table_viewE)){
-    emit showContextMenu();
-    return true;
-  }
-  return MdiSubWindow::eventFilter(object, e);
-}
-
-/** Called when switching between tabs
- *  @param index :: The index of the new active tab
- */
-void MantidMatrix::viewChanged(int index)
-{
-  // get the previous view and selection model
-  QTableView* prevView=(QTableView*)m_tabs->widget(m_PrevIndex);
-  if(prevView)
-  {
-    QItemSelectionModel *oldSelModel = prevView->selectionModel();
-    QItemSelectionModel *selModel = activeView()->selectionModel();
-    // Copy the selection from the previous tab into the newly-activated one
-    selModel->select(oldSelModel->selection(),QItemSelectionModel::Select);
-    // Clear the selection on the now-hidden tab
-    oldSelModel->clearSelection();
-
-    m_PrevIndex=index;
-    //get the previous tab scrollbar positions
-    int hValue=  prevView->horizontalScrollBar()->value();
-    int vValue = prevView->verticalScrollBar()->value();
-    //to synchronize the views
-    //set  the previous view  scrollbar positions to current view
-    activeView()->horizontalScrollBar()->setValue(hValue);
-    activeView()->verticalScrollBar()->setValue(vValue);
-  }
-
-}
-
-/// Checks if d is not infinity or a NaN
-bool isANumber(volatile const double& d)
-{
-  return d != std::numeric_limits<double>::infinity() && d == d;
-}
-
-void MantidMatrix::setup(Mantid::API::MatrixWorkspace_sptr ws, int start, int end)
-{
-  if (!ws.get())
-  {
-    QMessageBox::critical(0,"WorkspaceMatrixModel error","2D workspace expected.");
-    m_rows = 0;
-    m_cols = 0;
-    m_startRow = 0;
-    m_endRow = 0;
-    return;
-  }
-
-  m_workspace = ws;
-  m_workspaceTotalHist = ws->getNumberHistograms();
-  m_startRow = (start<0 || start>=m_workspaceTotalHist)?0:start;
-  m_endRow   = (end<0 || end>=m_workspaceTotalHist || end < start)? m_workspaceTotalHist - 1 : end;
-  m_rows = m_endRow - m_startRow + 1;
-  m_cols = ws->blocksize();
-  if ( ws->isHistogramData() ) m_histogram = true;
-  connect(this,SIGNAL(needsUpdating()),this,SLOT(repaintAll()));
-
-
-  m_bk_color = QColor(128, 255, 255);
-  m_matrix_icon = getQPixmap("mantid_matrix_xpm");
-  m_column_width = 100;
-
-}
-
-void MantidMatrix::connectTableView(QTableView* view,MantidMatrixModel*model)
-{
-  view->setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding));
-  view->setSelectionMode(QAbstractItemView::ExtendedSelection);
-  view->setModel(model);
-  view->setCornerButtonEnabled(false);
-  view->setFocusPolicy(Qt::StrongFocus);
-
-  QPalette pal = view->palette();
-  pal.setColor(QColorGroup::Base, m_bk_color);
-  view->setPalette(pal);
-
-  // set header properties
-  QHeaderView* hHeader = (QHeaderView*)view->horizontalHeader();
-  hHeader->setMovable(false);
-  hHeader->setResizeMode(QHeaderView::Interactive);
-  hHeader->setDefaultSectionSize(m_column_width);
-
-  view->resizeRowToContents(0);
-  int row_height = view->rowHeight(0);
-
-  QHeaderView* vHeader = (QHeaderView*)view->verticalHeader();
-  vHeader->setDefaultSectionSize(row_height);
-  vHeader->setResizeMode(QHeaderView::Fixed);
-  vHeader->setMovable(false);
-}
-
-double MantidMatrix::cell(int row, int col)
-{
-  return m_modelY->data(row, col);
-}
-
-QString MantidMatrix::text(int row, int col)
-{
-  return QString::number(activeModel()->data(row, col));
-}
-
-/** Sets new column width in a table view(s).
-    @param width :: New column width in pixels. All columns have the same width.
-    @param all :: If true the change will be applied to all three table views.
-*/
-void MantidMatrix::setColumnsWidth(int width, bool all)
-{
-  if (all)
-  {
-    m_table_viewY->horizontalHeader()->setDefaultSectionSize(width);
-    m_table_viewX->horizontalHeader()->setDefaultSectionSize(width);
-    m_table_viewE->horizontalHeader()->setDefaultSectionSize(width);
-
-    int cols = numCols();
-    for(int i=0; i<cols; i++)
-    {
-      m_table_viewY->setColumnWidth(i, width);
-      m_table_viewX->setColumnWidth(i, width);
-      m_table_viewE->setColumnWidth(i, width);
-    }
-    MantidPreferences::MantidMatrixColumnWidth(width);
-  }
-  else
-  {
-    QTableView* table_view = activeView();
-    table_view->horizontalHeader()->setDefaultSectionSize(width);
-    int cols = numCols();
-    for(int i=0; i<cols; i++)
-      table_view->setColumnWidth(i, width);
-    switch (m_tabs->currentIndex())
-    {
-    case 0: MantidPreferences::MantidMatrixColumnWidthY(width);break;
-    case 1: MantidPreferences::MantidMatrixColumnWidthX(width);break;
-    case 2: MantidPreferences::MantidMatrixColumnWidthE(width);break;
-    }
-  }
-
-  emit modifiedWindow(this);
-}
-
-/**  Sets column width to one table view.
-     @param i :: ordinal number of the view. 0 - Y, 1 - X, 2 - Error
-     @param width :: New column width in pixels. All columns have the same width.
-*/
-void MantidMatrix::setColumnsWidth(int i,int width)
-{
-
-  QTableView* table_view;
-  switch(i)
-  {
-  case 0: table_view =  m_table_viewY; MantidPreferences::MantidMatrixColumnWidthY(width); break;
-  case 1: table_view =  m_table_viewX; MantidPreferences::MantidMatrixColumnWidthX(width); break;
-  case 2: table_view =  m_table_viewE; MantidPreferences::MantidMatrixColumnWidthE(width); break;
-  default: table_view = activeView();
-  };
-
-  table_view->horizontalHeader()->setDefaultSectionSize(width);
-  int cols = numCols();
-  for(int i=0; i<cols; i++)
-    table_view->setColumnWidth(i, width);
-
-  emit modifiedWindow(this);
-}
-
-/**  Returns the width of a column.
-     @param i :: ordinal number of the view. 0 - Y, 1 - X, 2 - Error
-     @return The column width in pixels. All columns have the same width.
-*/
-int MantidMatrix::columnsWidth(int i)
-{
-  switch(i)
-  {
-  case 0: return m_table_viewY->columnWidth(0);
-  case 1: return m_table_viewX->columnWidth(0);
-  case 2: return m_table_viewE->columnWidth(0);
-  };
-  return activeView()->columnWidth(0);
-}
-
-/**  Return the pointer to the active table view.
-*/
-QTableView *MantidMatrix::activeView()
-{
-  switch (m_tabs->currentIndex())
-  {
-  case 0: return m_table_viewY;
-  case 1: return m_table_viewX;
-  case 2: return m_table_viewE;
-  }
-  return m_table_viewY;
-}
-
-/**  Returns the pointer to the active model.
-*/
-MantidMatrixModel *MantidMatrix::activeModel()
-{
-  switch (m_tabs->currentIndex())
-  {
-  case 0: return m_modelY;
-  case 1: return m_modelX;
-  case 2: return m_modelE;
-  }
-  return m_modelY;
-}
-
-/**  Copies the current selection in the active table view into the system clipboard.
-*/
-void MantidMatrix::copySelection()
-{
-  QItemSelectionModel *selModel = activeView()->selectionModel();
-  QString s = "";
-  QString eol = applicationWindow()->endOfLine();
-  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())
-      return;
-
-    QItemSelectionRange cur = it.next();
-    int top = cur.top();
-    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++)
-        s += text(i, j) + "\t";
-      s += text(i,right) + eol;
-    }
-  }
-  // Copy text into the clipboard
-  QApplication::clipboard()->setText(s.trimmed());
-}
-
-/**  Returns minimum and maximum values in the matrix.
-     If setRange(...) has not been called it returns the true smalles ang largest Y-values in the matrix,
-     otherwise the values set with setRange(...) are returned. These are needed in plotGraph2D to set
-     the range of the third, colour axis.
-     @param[out] min is set to the minumium value
-     @param[out] max is set to the maximum value
-*/
-void MantidMatrix::range(double *min, double *max)
-{
-  if (!m_are_min_max_set)
-  {
-    //this is here to fill m_min and m_max with numbers that aren't nan
-    m_min = std::numeric_limits<double>::max();
-    m_max = -std::numeric_limits<double>::max();
-
-    if (this->m_workspace)
-    {
-
-      PARALLEL_FOR1(m_workspace)
-      for (int wi=0; wi < m_workspace->getNumberHistograms(); wi++)
-      {
-        double local_min, local_max;
-        const MantidVec & Y = m_workspace->readY(wi);
-
-        local_min = std::numeric_limits<double>::max();
-        local_max = -std::numeric_limits<double>::max();
-
-        for (size_t i=0; i < Y.size(); i++)
-        {
-          double aux = Y[i];
-          if (fabs(aux) == std::numeric_limits<double>::infinity() || aux != aux)
-            continue;
-          if (aux < local_min)
-            local_min = aux;
-          if (aux > local_max)
-            local_max = aux;
-        }
-
-        // Now merge back the local min max
-        PARALLEL_CRITICAL(MantidMatrix_range_max)
-        {
-          if (local_max > m_max)
-            m_max = local_max;
-        }
-        PARALLEL_CRITICAL(MantidMatrix_range_min)
-        {
-          if (local_min < m_min)
-            m_min = local_min;
-        }
-      }
-      m_are_min_max_set = true;
-    }
-
-    // Make up some reasonable values if nothing was found
-    if (m_min == std::numeric_limits<double>::max())
-      m_min = 0;
-    if (m_max == -std::numeric_limits<double>::max())
-      m_max = m_min + 1e6;
-
-//    // ---- VERY SLOW OLD ALGORITHM -----
-//    int rows = numRows();
-//    int cols = numCols();
-//    for(int i=0; i<rows; i++){
-//      for(int j=0; j<cols; j++){
-//        double aux = cell(i, j);
-//        if (fabs(aux) == std::numeric_limits<double>::infinity() || aux != aux)
-//        {
-//          continue;
-//        }
-//        if (aux <= m_min)
-//          m_min = aux;
-//
-//        if (aux >= m_max)
-//          m_max = aux;
-//      }
-//
-//      m_are_min_max_set = true;
-//    }
-
-
-  }
-  *min = m_min;
-  *max = m_max;
-}
-
-
-
-/**  Sets new minimum and maximum Y-values which can be displayed in a 2D graph
-*/
-void MantidMatrix::setRange(double min, double max)
-{
-  m_min = min;
-  m_max = max;
-  m_are_min_max_set = true;
-}
-
-double** MantidMatrix::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++)
-        free(data[j]);
-      free(data);
-
-      QMessageBox::critical(0, tr("MantidPlot") + " - " + tr("Memory Allocation Error"),
-                            tr("Not enough memory, operation aborted!"));
-      return NULL;
-    }
-  }
-  return data;
-}
-
-void MantidMatrix::freeMatrixData(double **data, int rows)
-{
-  for ( int i = 0; i < rows; i++)
-    free(data[i]);
-
-  free(data);
-}
-
-void MantidMatrix::goTo(int row,int col)
-{
-  if(row < 1 || row > numRows())
-    return;
-  if(col < 1 || col > numCols())
-    return;
-
-  activeView()->selectionModel()->select(activeModel()->index(row - 1, col - 1), QItemSelectionModel::ClearAndSelect);
-  activeView()->scrollTo(activeModel()->index(row - 1, col - 1), QAbstractItemView::PositionAtTop);
-}
-
-void MantidMatrix::goToRow(int row)
-{
-  if(row < 1 || row > numRows())
-    return;
-
-  //	activeView()->selectRow(row - 1); //For some reason, this did not highlight the row at all, hence the stupid line below
-  activeView()->selectionModel()->select(QItemSelection(activeModel()->index(row - 1, 0), activeModel()->index(row - 1, numCols() - 1)), QItemSelectionModel::ClearAndSelect);
-
-  activeView()->scrollTo(activeModel()->index(row - 1, 0), QAbstractItemView::PositionAtCenter);
-}
-
-void MantidMatrix::goToColumn(int col)
-{
-  if(col < 1 || col > numCols())
-    return;
-
-  //	activeView()->selectColumn(col - 1); //For some reason, this did not highlight the row at all, hence the stupid line below
-  activeView()->selectionModel()->select(QItemSelection(activeModel()->index(0, col - 1), activeModel()->index(numRows() - 1, col - 1)), QItemSelectionModel::ClearAndSelect);
-  activeView()->scrollTo(activeModel()->index(0, col - 1), QAbstractItemView::PositionAtCenter);
-
-}
-
-double MantidMatrix::dataX(int row, int col) const
-{
-  if (!m_workspace || row >= numRows() || col >= static_cast<int>(m_workspace->readX(row + m_startRow).size())) return 0.;
-  double res = m_workspace->readX(row + m_startRow)[col];
-  return res;
-
-}
-
-double MantidMatrix::dataY(int row, int col) const
-{
-  if (!m_workspace || row >= numRows() || col >= numCols()) return 0.;
-  double res = m_workspace->readY(row + m_startRow)[col];
-  return res;
-
-}
-
-double MantidMatrix::dataE(int row, int col) const
-{
-  if (!m_workspace || row >= numRows() || col >= numCols()) return 0.;
-  double res = m_workspace->readE(row + m_startRow)[col];
-  if (res == 0.) res = 1.;//  quick fix of the fitting problem
-  return res;
-
-}
-
-/////////////////////////////////////////
-
-int MantidMatrix::indexY(double s)const
-{
-  int n = m_rows;
-
-  const Mantid::API::Axis& yAxis = *m_workspace->getAxis(1);
-
-  bool isNumeric = yAxis.isNumeric();
-  
-  if (n == 0) return -1;
-
-  int i0 = m_startRow;
-
-  if (s < yAxis(i0))
-  {
-    if (isNumeric || yAxis(i0) - s > 0.5) return -1;
-    return 0;
-  }
-  else if (s > yAxis(n-1))
-  {
-    if (isNumeric || s - yAxis(n-1) > 0.5) return -1;
-    return n-1;
-  }
-
-  int i = i0, j = n-1, k = n/2;
-  double ss;
-  int it;
-  for(it=0;it<n;it++)
-  {
-    ss = yAxis(k);
-    if (ss == s ) return k;
-    if (abs(i - j) <2)
-    {
-      double ds = fabs(ss-s);
-      double ds1 = fabs(yAxis(j)-s);
-      if (ds1 < ds)
-      {
-        if (isNumeric || ds1 < 0.5) return j;
-        return -1;
-      }
-      if (isNumeric || ds < 0.5) return i;
-      return -1;
-    }
-    if (s > ss) i = k;
-    else
-      j = k;
-    k = i + (j - i)/2;
-  }
-
-  return i;
-}
-
-QString MantidMatrix::workspaceName() const
-{
-  return QString::fromStdString(m_strName);
-}
-
-QwtDoubleRect MantidMatrix::boundingRect()
-{
-  if (m_boundingRect.isNull())
-  {
-    m_spectrogramRows = numRows() > 100 ? numRows() : 100;
-
-    // This is only meaningful if a 2D (or greater) workspace
-    if (m_workspace->axes() > 1)
-    {
-      const Mantid::API::Axis* const ax = m_workspace->getAxis(1);
-      y_start =(*ax)(m_startRow);
-      y_end   =(*ax)(m_endRow);
-    }
-
-    double dy = fabs(y_end - y_start)/(double)(numRows() - 1);
-
-    int i0 = m_startRow;
-    x_start = x_end = 0;
-    while(x_start == x_end && i0 <= m_endRow)
-    {
-      i0++;
-      const Mantid::MantidVec& X = m_workspace->readX(i0);
-      x_start = X[0];
-      if (X.size() != m_workspace->readY(i0).size()) x_end = X[m_workspace->blocksize()];
-      else
-        x_end = X[m_workspace->blocksize()-1];
-      if ( !isANumber(x_start) || !isANumber(x_end))
-      {
-        x_start = x_end = 0;
-      }
-    }
-
-    // if i0 > m_endRow there aren't any plottable rows
-    if (i0 <= m_endRow)
-    {
-      // check if all X vectors are the same
-      bool theSame = true;
-      double dx = 0.;
-      for(int i=i0;i<=m_endRow;++i)
-      {
-        if (m_workspace->readX(i).front() != x_start || m_workspace->readX(i).back() != x_end)
-        {
-          theSame = false;
-          break;
-        }
-      }
-      dx = fabs(x_end - x_start)/(double)(numCols() - 1);
-
-      if ( !theSame )
-      {
-        // Find the smallest bin width and thus the number of columns in a spectrogram
-        // that can be plotted from this matrix
-        double ddx = dx;
-        for(int i=m_startRow+1;i<=m_endRow;++i)
-        {
-          const Mantid::MantidVec& X = m_workspace->readX(i);
-          if (X.front() < x_start)
-          {
-            double xs = X.front();
-            if (!isANumber(xs)) continue;
-            x_start = xs;
-          }
-          if (X.back() > x_end)
-          {
-            double xe = X.back();
-            if (!isANumber(xe)) continue;
-            x_end = xe;
-          }
-          for(int j=1;j<static_cast<int>(X.size());++j)
-          {
-            double d = X[j] - X[j-1];
-            if (ddx == 0 && d < ddx)
-            {
-              ddx = d;
-            }
-          }
-        }
-        m_spectrogramCols = int((x_end - x_start)/ddx);
-        if (m_spectrogramCols < 100) m_spectrogramCols = 100;
-      }
-      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();
-
-    }
-    else
-    {
-      m_spectrogramCols = 0;
-      m_boundingRect = QwtDoubleRect(0, QMIN(y_start, y_end) - 0.5*dy,
-        1, fabs(y_end - y_start) + dy).normalized();
-    }
-  }// Define the spectrogram bounding box
-  return m_boundingRect;
-}
-
-//----------------------------------------------------------------------------
-void MantidMatrixFunction::init()
-{
- if (!m_matrix->workspace()->getAxis(1))
- {
-   throw std::runtime_error("The y-axis is not set");
- }
-
-  double tmp;
-  m_matrix->range(&tmp,&m_outside);
-  m_outside *= 1.1;
-}
-
-double MantidMatrixFunction::operator()(double x, double y)
-{
-  int i = m_matrix->indexY(y);
-  if (i < 0 || i >= m_matrix->numRows())
-  {
-    return m_outside;
-  }
-
-  int j = m_matrix->indexX(i,x);
-
-  if (j >=0 && j < m_matrix->numCols())
-    return m_matrix->dataY(i,j);
-  else
-    return m_outside;
-}
-
-double MantidMatrixFunction::getMinPositiveValue()const
-{
-  double zmin = DBL_MAX;
-  for(int i=0;i<numRows();++i)
-  {
-    for(int j=0;j<numCols();++j)
-    {
-      double tmp = value(i,j);
-      if (tmp > 0 && tmp < zmin)
-      {
-        zmin = tmp;
-      }
-    }
-  }
-  return zmin;
-}
-
-int MantidMatrixFunction::numRows()const
-{
-  return m_matrix->m_rows;
-}
-
-int MantidMatrixFunction::numCols()const
-{
-  return m_matrix->m_cols;
-}
-
-double MantidMatrixFunction::value(int row,int col)const
-{
-  return m_matrix->m_workspace->readY(row + m_matrix->m_startRow)[col];
-}
-
-void MantidMatrixFunction::getRowYRange(int row,double& ymin, double& ymax)const
-{
-  const Mantid::API::Axis& yAxis = *(m_matrix->m_workspace->getAxis(1));
-
-
-  int i = row + m_matrix->m_startRow;
-  double y = yAxis(i);
-
-  int imax = m_matrix->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 = (yAxis(i-1) + y)/2;
-      ymax = 2*y - ymin;
-    }
-  }
-  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_matrix->m_workspace->readX(row + m_matrix->m_startRow);
-  xmin = X[0];
-  xmax = X[X.size()-1];
-}
-
-const Mantid::MantidVec& MantidMatrixFunction::getMantidVec(int row)const
-{
-  return m_matrix->m_workspace->readX(row + m_matrix->m_startRow);
-}
-
-int MantidMatrix::indexX(int row,double s)const
-{
-  int n = m_workspace->blocksize();
-
-  //bool isHistogram = m_workspace->isHistogramData();
-
-  const Mantid::MantidVec& X = m_workspace->readX(row + m_startRow);
-  if (n == 0 || s < X[0] || s > X[n-1]) return -1;
-
-  int i = 0, j = n-1, k = n/2;
-  double ss;
-  int it;
-  for(it=0;it<n;it++)
-  {
-    ss = X[k];
-    if (ss == s ) return k;
-    if (abs(i - j) <2)
-    {
-      double ds = fabs(ss-s);
-      if (fabs(X[j]-s) < ds) return j;
-      return i;
-    }
-    if (s > ss) i = k;
-    else
-      j = k;
-    k = i + (j - i)/2;
-  }
-
-  return i;
-}
-
-//----------------------------------------------------------------------------
-
-Graph3D * MantidMatrix::plotGraph3D(int style)
-{
-  QApplication::setOverrideCursor(Qt::WaitCursor);
-
-  ApplicationWindow* a = applicationWindow();
-  QString labl = a->generateUniqueName(tr("Graph"));
-
-  Graph3D *plot = new Graph3D("", a);
-  plot->resize(500,400);
-  plot->setWindowTitle(labl);
-  plot->setName(labl);
-  plot->setTitle(tr("Workspace ")+name());
-  a->customPlot3D(plot);
-  plot->customPlotStyle(style);
-  int resCol = numCols() / 200;
-  int resRow = numRows() / 200;
-  plot->setResolution( qMax(resCol,resRow) );
-
-  double zMin =  1e300;
-  double zMax = -1e300;
-  for(int i=0;i<numRows();i++)
-    for(int j=0;j<numCols();j++)
-    {
-    if (cell(i,j) < zMin) zMin = cell(i,j);
-    if (cell(i,j) > zMax) zMax = cell(i,j);
-  }
-
-  // Calculate xStart(), xEnd(), yStart(), yEnd()
-  boundingRect();
-  
-  m_funct.init();
-  plot->addFunction("", xStart(), xEnd(), yStart(), yEnd(), zMin, zMax, numCols(), numRows(), static_cast<UserHelperFunction*>(&m_funct));
-
-  const Mantid::API::Axis* ax = m_workspace->getAxis(0);
-  std::string s;
-  if ( ax->unit() ) s = ax->unit()->caption() + " / " + ax->unit()->label();
-  else
-    s = "X Axis";
-  plot->setXAxisLabel(tr(s.c_str()));
-
-  if ( m_workspace->axes() > 1 )
-  {
-    ax = m_workspace->getAxis(1);
-    if (ax->isNumeric())
-    {
-      if ( ax->unit() ) s = ax->unit()->caption() + " / " + ax->unit()->label();
-      else
-        s = "Y Axis";
-      plot->setYAxisLabel(tr(s.c_str()));
-    }
-    else
-      plot->setYAxisLabel(tr("Spectrum"));
-  }
-
-  plot->setZAxisLabel(tr(m_workspace->YUnitLabel().c_str()));
-
-  a->initPlot3D(plot);
-  //plot->askOnCloseEvent(false);
-  QApplication::restoreOverrideCursor();
-
-  return plot;
-}
-
-/** Creates a MultiLayer graph and plots this MantidMatrix as a Spectrogram.
-
-    @param type :: The "curve" type.
-    @return Pointer to the created graph.
-*/
-MultiLayer* MantidMatrix::plotGraph2D(Graph::CurveType type)
-{
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-  ApplicationWindow *a = applicationWindow();
-  MultiLayer* g = a->multilayerPlot(a->generateUniqueName(tr("Graph")));
-  m_plots2D<<g;
-  connect(g, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(dependantClosed(MdiSubWindow*)));
-  //#799 fix for  multiple dialog creation on double clicking/ on right click menu scale on  2d plot
-  //   a->connectMultilayerPlot(g);
-  Graph* plot = g->activeGraph();
-  ProjectData *prjData=0;
-  plotSpectrogram(plot,a,type,false,prjData);
- // g->askOnCloseEvent(false);
-  QApplication::restoreOverrideCursor();
-  return g;
-}
-
-Spectrogram* MantidMatrix::plotSpectrogram(Graph* plot,ApplicationWindow* app,Graph::CurveType type,bool project,ProjectData *prjData)
-{
-  app->setPreferences(plot);
-  plot->setTitle(tr("Workspace ") + name());
-  const Mantid::API::Axis* ax;
-  ax = m_workspace->getAxis(0);
-  std::string s;
-  if (ax->unit().get()) s = ax->unit()->caption() + " / " + ax->unit()->label();
-  else
-    s = "X Axis";
-  plot->setXAxisTitle(tr(s.c_str()));
-  if ( m_workspace->axes() > 1 )
-  {
-    ax = m_workspace->getAxis(1);
-    if (ax->isNumeric())
-    {
-      if ( ax->unit() ) s = ax->unit()->caption() + " / " + ax->unit()->label();
-      else
-        s = "Y Axis";
-      plot->setYAxisTitle(tr(s.c_str()));
-    }
-    else
-      plot->setYAxisTitle(tr("Spectrum"));
-  }
-
-  // Set the range on the thirs, colour axis
-  double minz, maxz;
-  m_funct.init();
-  range(&minz,&maxz);
-  Spectrogram *spgrm = plot->plotSpectrogram(&m_funct, m_spectrogramRows, m_spectrogramCols, boundingRect(), minz, maxz, type);
-  if( spgrm )
-  {
-    spgrm->setDisplayMode(QwtPlotSpectrogram::ImageMode, true);
-    spgrm->setDisplayMode(QwtPlotSpectrogram::ContourMode, false);
-    if(project)
-    {
-      spgrm->mutableColorMap().loadMap(prjData->getColormapFile());
-      spgrm->setCustomColorMap(spgrm->mutableColorMap());
-      spgrm->setIntensityChange(prjData->getIntensity());
-      if(!prjData->getGrayScale())spgrm->setGrayScale();
-      if(prjData->getContourMode())
-      {spgrm->setDisplayMode(QwtPlotSpectrogram::ContourMode, true);
-      spgrm->showContourLineLabels(true);
-      }
-      spgrm->setDefaultContourPen(prjData->getDefaultContourPen());
-      spgrm->setColorMapPen(false);
-      if(prjData->getColorMapPen())spgrm->setColorMapPen(true);
-      ContourLinesEditor* contourEditor=prjData->getContourLinesEditor();
-      if(contourEditor) 
-      {
-        contourEditor->setSpectrogram(spgrm);
-        contourEditor->updateContents();
-        contourEditor->updateContourLevels();
-      }
-    }
-
-  }
-  plot->setAutoScale();
-  return spgrm;
-}
-void MantidMatrix::setSpectrumGraph(MultiLayer *ml, Table* t)
-{
-  MantidUI::setUpSpectrumGraph(ml,name());
-  connect(ml, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(dependantClosed(MdiSubWindow*)));
-  if (t)
-  {
-    m_plots1D[ml] = t;
-    connect(t, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(dependantClosed(MdiSubWindow*)));
-  }
-  else
-    m_plots2D<<ml;
-}
-
-void MantidMatrix::setBinGraph(MultiLayer *ml, Table* t)
-{
-  MantidUI::setUpBinGraph(ml,name(),workspace());
-  connect(ml, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(dependantClosed(MdiSubWindow*)));
-  if (t)
-  {
-    m_plots1D[ml] = t;
-    connect(t, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(dependantClosed(MdiSubWindow*)));
-  }
-  else
-    m_plots2D<<ml;
-}
-
-// Remove all references to the MantidMatrix
-void MantidMatrix::removeWindow()
-{
-  QList<MdiSubWindow *> windows = applicationWindow()->windowsList();
-  foreach(MdiSubWindow *w, windows){
-    //if (w->isA("Graph3D") && ((Graph3D*)w)->userFunction()->hlpFun() == &m_funct)
-    if (w->isA("Graph3D") )//&& ((Graph3D*)w)->userFunction()->hlpFun() == &m_funct)
-    { 	UserFunction* fn=((Graph3D*)w)->userFunction();
-      if(fn)
-      {	if(fn->hlpFun() == &m_funct)((Graph3D*)w)->clearData();
-      }
-
-    }else if (w->isA("Table")){
-    }
-    else if (w->isA("MultiLayer")){
-      QList<Graph *> layers = ((MultiLayer*)w)->layersList();
-      foreach(Graph *g, layers){
-        for (int i=0; i<g->curves(); i++){
-          Spectrogram *sp = (Spectrogram *)g->plotItem(i);
-          if (sp && sp->rtti() == QwtPlotItem::Rtti_PlotSpectrogram && sp->funct() == &m_funct)
-            g->removeCurve(i);
-        }
-      }
-    }
-
-  }
-  //this->closeDependants();
-}
-
-/// Returns a list of the selected rows
-const QList<int>& MantidMatrix::getSelectedRows() const
-{
-  return m_selectedRows;
-}
-
-/**
- * Sets the internal cache of selected rows.
- * @return True if rows are selected, false otherwise
- */
-bool MantidMatrix::setSelectedRows()
-{
-  QTableView *tv = activeView();
-  QItemSelectionModel *selModel = tv->selectionModel();
-  if( !selModel  ) return false;
-
-  m_selectedRows.clear();
-  const QModelIndexList rows = selModel->selectedRows();
-  QModelIndexList::const_iterator it;
-  for ( it = rows.constBegin(); it != rows.constEnd(); ++it)
-  {
-    m_selectedRows.append(it->row()+m_startRow);
-  }
-
-  return (m_selectedRows.empty() ? false : true);
-}
-
-/// Returns a list of the selected columns
-const QList<int>& MantidMatrix::getSelectedColumns() const
-{
-  return m_selectedCols;
-}
-
-/**
- * Sets the internal cache of selected columns.
- * @return True if columns are selected, false otherwise
- */
-bool MantidMatrix::setSelectedColumns()
-{
-  QTableView *tv = activeView();
-  QItemSelectionModel *selModel = tv->selectionModel();
-  if( !selModel ||  !selModel->hasSelection()) return false;
-
-  m_selectedCols.clear();
-  const QModelIndexList cols = selModel->selectedColumns();
-  QModelIndexList::const_iterator it;
-  for ( it = cols.constBegin(); it != cols.constEnd(); ++it)
-  {
-    m_selectedCols.append(it->column());
-  }
-
-  return (m_selectedCols.empty() ? false : true);
-}
-
-void MantidMatrix::dependantClosed(MdiSubWindow* w)
-{
-  if( w->isA("Table") )
-  {
-    QMap<MultiLayer*,Table*>::iterator itr;
-    for( itr = m_plots1D.begin(); itr != m_plots1D.end(); ++itr )
-    {
-      if( itr.value() == (Table*)w )
-      {
-        m_plots1D.erase(itr);
-        break;
-      }
-    }
-  }
-  else if (w->isA("MultiLayer"))
-  {
-    int i = m_plots2D.indexOf((MultiLayer*)w);
-    if (i >= 0)m_plots2D.remove(i);
-    else
-    {QMap<MultiLayer*,Table*>::iterator i = m_plots1D.find((MultiLayer*)w);
-      if (i != m_plots1D.end())
-      {
-        if (i.value() != 0)
-        {
-          i.value()->askOnCloseEvent(false);
-          i.value()->close();
-        }
-        m_plots1D.erase(i);
-      }
-    }
-  }
-}
-
-/**
-     Repaints all 1D and 2D plots attached to this MantidMatrix
-*/
-void MantidMatrix::repaintAll()
-{
-  repaint();
-
-  // Repaint 2D plots
-  QVector<MultiLayer*>::iterator vEnd  = m_plots2D.end();
-  for( QVector<MultiLayer*>::iterator vItr = m_plots2D.begin(); vItr != vEnd; ++vItr )
-  {
-    (*vItr)->activeGraph()->replot();
-  }
-
-  // Updates the 1D plots by modifying the attached tables
-  QMap<MultiLayer*,Table*>::iterator mEnd = m_plots1D.end();
-  for(QMap<MultiLayer*,Table*>::iterator mItr = m_plots1D.begin(); mItr != mEnd;  ++mItr)
-  {
-    Table* t = mItr.value();
-    if ( !t ) continue;
-    int charsToRemove = t->name().size() + 1;
-    int nTableCols(t->numCols());
-    for(int col = 1; col < nTableCols; ++col)
-    {
-      QString colName = t->colName(col).remove(0,charsToRemove);
-      if( colName.isEmpty() ) break;
-      //Need to determine whether the table was created from plotting a spectrum
-      //or a time bin. A spectrum has a Y column name YS and a bin YB
-      QString ident = colName.left(2);
-      colName.remove(0,2); //This now contains the number in the MantidMatrix
-      int matrixNumber = colName.toInt();
-      if( matrixNumber < 0 ) break;
-      bool errs = (ident[0] == QChar('E')) ? true : false;
-      if( ident[1] == QChar('S') )
-      {
-        if( matrixNumber >= numRows() ) break;
-        int endCount = numCols();
-        for(int j = 0; j < endCount; ++j)
-        {
-          if( errs ) t->setCell(j, col, dataE(matrixNumber, j));
-          else t->setCell(j, col, dataY(matrixNumber, j));
-        }
-      }
-      else
-      {
-        if( matrixNumber >= numCols() ) break;
-        int endCount = numRows();
-        for(int j = 0; j < endCount; ++j)
-        {
-          if( errs ) t->setCell(j, col, dataE(j, matrixNumber));
-          else t->setCell(j, col, dataY(j, matrixNumber));
-        }
-      }
-    }
-    t->notifyChanges();
-    Graph *g = mItr.key()->activeGraph();
-    if (g) g->setAutoScale();
-  }
-}
-
-void MantidMatrix::afterReplaceHandle(const std::string& wsName,const boost::shared_ptr<Mantid::API::Workspace> ws)
-{
-  if( wsName != m_strName || !ws.get() ) return;
-
-  Mantid::API::MatrixWorkspace_sptr new_workspace = boost::dynamic_pointer_cast<MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(m_strName));
-  emit needWorkspaceChange( new_workspace ); 
-
-
-}
-
-void MantidMatrix::changeWorkspace(Mantid::API::MatrixWorkspace_sptr ws)
-{
-  if (m_cols != ws->blocksize() ||
-      m_workspaceTotalHist != ws->getNumberHistograms())
-  {
-    closeDependants();
-  }
-
-  // Save selection
-  QItemSelectionModel *oldSelModel = activeView()->selectionModel();
-  QModelIndexList indexList = oldSelModel->selectedIndexes();
-  QModelIndex curIndex = activeView()->currentIndex();
-
-  setup(ws,-1,-1);
-
-  m_modelY = new MantidMatrixModel(this,ws.get(),m_rows,m_cols,m_startRow,MantidMatrixModel::Y);
-  connectTableView(m_table_viewY,m_modelY);
-
-  m_modelX = new MantidMatrixModel(this,ws.get(),m_rows,m_cols,m_startRow,MantidMatrixModel::X);
-  connectTableView(m_table_viewX,m_modelX);
-
-  m_modelE = new MantidMatrixModel(this,ws.get(),m_rows,m_cols,m_startRow,MantidMatrixModel::E);
-  connectTableView(m_table_viewE,m_modelE);
-
-  // Restore selection
-  activeView()->setCurrentIndex(curIndex);
-  if (indexList.size())
-  {
-    QItemSelection sel(indexList.first(),indexList.last());
-    QItemSelectionModel *selModel = activeView()->selectionModel();
-    selModel->select(sel,QItemSelectionModel::Select);
-  }
-
-  invalidateBoundingRect();
-
-  repaintAll();
-
-}
-
-void MantidMatrix::closeDependants()
-{
-  while(m_plots2D.size())
-  {
-    MultiLayer* ml = m_plots2D.front();
-    ml->askOnCloseEvent(false);
-    ml->close();// this calls slot dependantClosed() which removes the pointer from m_plots2D
-  }
-
-  while(m_plots1D.size())
-  {
-    MultiLayer* ml = m_plots1D.begin().key();
-    ml->askOnCloseEvent(false);
-    ml->close();// this calls slot dependantClosed() which removes the pointer from m_plots1D
-  }
-
-}
-
-void MantidMatrix::setNumberFormat(const QChar& f,int prec, bool all)
-{
-  if (all)
-  {
-    modelY()->setFormat(f,prec);
-    modelX()->setFormat(f,prec);
-    modelE()->setFormat(f,prec);
-    MantidPreferences::MantidMatrixNumberFormat(f);
-    MantidPreferences::MantidMatrixNumberPrecision(prec);
-  }
-  else
-  {
-    activeModel()->setFormat(f,prec);
-    switch (m_tabs->currentIndex())
-    {
-    case 0: MantidPreferences::MantidMatrixNumberFormatY(f);
-      MantidPreferences::MantidMatrixNumberPrecisionY(prec);
-      break;
-    case 1: MantidPreferences::MantidMatrixNumberFormatX(f);
-      MantidPreferences::MantidMatrixNumberPrecisionX(prec);
-      break;
-    case 2: MantidPreferences::MantidMatrixNumberFormatE(f);
-      MantidPreferences::MantidMatrixNumberPrecisionE(prec);
-      break;
-    }
-  }
-}
-
-void MantidMatrix::setNumberFormat(int i,const QChar& f,int prec, bool all)
-{
-  (void) all; //Avoid unused warning
-  switch (i)
-  {
-  case 0: m_modelY->setFormat(f,prec);
-    MantidPreferences::MantidMatrixNumberFormatY(f);
-    MantidPreferences::MantidMatrixNumberPrecisionY(prec);
-    break;
-  case 1: m_modelX->setFormat(f,prec);
-    MantidPreferences::MantidMatrixNumberFormatX(f);
-    MantidPreferences::MantidMatrixNumberPrecisionX(prec);
-    break;
-  case 2: m_modelE->setFormat(f,prec);
-    MantidPreferences::MantidMatrixNumberFormatE(f);
-    MantidPreferences::MantidMatrixNumberPrecisionE(prec);
-    break;
-  }
-}
-
-QChar MantidMatrix::numberFormat()
-{
-  return activeModel()->format();
-}
-
-int MantidMatrix::precision()
-{
-  return activeModel()->precision();
-}
-
-
-
-void MantidMatrix::setMatrixProperties()
-{
-  MantidMatrixDialog* dlg = new MantidMatrixDialog(m_appWindow);
-  dlg->setMatrix(this);
-  dlg->exec();
-}
-
-void MantidMatrix::deleteHandle(const std::string& wsName,const boost::shared_ptr<Mantid::API::Workspace> ws)
-{
-  (void) ws; //Avoid unused warning
-  (void) wsName; //Avoid unused warning
-  if (m_workspace.get() == ws.get())
-  {
-    emit needToClose();
-  }
-}
-
-void MantidMatrix::clearADSHandle()
-{
-  emit needToClose();
-}
-
-
-void MantidMatrix::closeMatrix()
-{
-  askOnCloseEvent(false);
-  close();
-}
-
-void MantidMatrix::selfClosed(MdiSubWindow* w)
-{
-  (void) w; //Avoid unused warning
-  closeDependants();
-}
-
-//-------------------------------
-// Python API commands
-//------------------------------
-
-void MantidMatrix::goToTab(const QString & name)
-{
-  if( m_tabs->tabText(m_tabs->currentIndex()) == name ) return;
-
-  if( name == m_YTabLabel )
-  {
-    m_tabs->setCurrentIndex(0);
-  }
-  else if( name == m_XTabLabel )
-  {
-    m_tabs->setCurrentIndex(1);
-  }
-  else if( name == m_ETabLabel )
-  {
-    m_tabs->setCurrentIndex(2);
-  }
-  else return;
-}
-QString MantidMatrix::saveToString(const QString &geometry, bool saveAsTemplate)
-{
-  (void) saveAsTemplate; //Avoid unused warning
-
-  QString s="<mantidmatrix>\n";
-  s+="WorkspaceName\t"+QString::fromStdString(m_strName)+"\n";
-  s+=geometry;
-  s+="</mantidmatrix>\n";
-  return s;
-}
-
-/**  returns the workspace name
-  */
-const std::string & MantidMatrix::getWorkspaceName()
-{return m_strName;
-}
-
-// ----------   MantidMatrixModel   ------------------ //
-
-/**   MantidMatrixModel constructor.
-      @param parent :: Pointer to the parent MantidMatrix
-      @param ws :: Underlying workspace
-      @param rows :: Number of rows in the workspace to be visible via MantidMatrixModel
-      @param cols :: Number of columns (time bins)
-      @param start :: Starting index
-      @param type :: Type of the data to display: Y, X, or E
-  */
-MantidMatrixModel::MantidMatrixModel(QObject *parent,
-                                     Mantid::API::MatrixWorkspace* ws,
-                                     int rows,
-                                     int cols,
-                                     int start,
-                                     Type type):
-QAbstractTableModel(parent),m_type(type),
-m_format('e'),m_prec(6)
-{
-  setup(ws,rows,cols,start);
-}
-
-/// Call this function if the workspace has changed
-void MantidMatrixModel::setup(Mantid::API::MatrixWorkspace* ws,
-                              int rows,
-                              int cols,
-                              int start)
-{
-  m_workspace = ws;
-  m_rows = rows;
-  m_cols = cols;
-  m_startRow = start >= 0? start : 0;
-  if (ws->blocksize() != 0)
-    m_colNumCorr = ws->isHistogramData() ? 1 : 0;
-  else
-    m_colNumCorr = 0;
-}
-
-
-double MantidMatrixModel::data(int row, int col) const
-{
-  double val;
-  if (m_type == X)
-  {
-    val = m_workspace->readX(row + m_startRow)[col];
-  }
-  else if (m_type == Y)
-  {
-    val = m_workspace->readY(row + m_startRow)[col];
-  }
-  else
-  {
-    val = m_workspace->readE(row + m_startRow)[col];
-  }
-  return val;
-}
-
-QVariant MantidMatrixModel::headerData(int section, Qt::Orientation orientation, int role ) const
-{
-  if (role != Qt::DisplayRole) return QVariant();
-  if (orientation == Qt::Vertical && m_workspace->axes() > 1)
-  {
-    Mantid::API::TextAxis* xAxis = dynamic_cast<Mantid::API::TextAxis*>(m_workspace->getAxis(1));
-    if (xAxis)
-    {
-      return QString::fromStdString(xAxis->label(section));
-    }
-  }
-  return section;
-}
-
-Qt::ItemFlags MantidMatrixModel::flags(const QModelIndex & index ) const
-{
-  // MG: For item selection to work correclty in later Qt versions it must be marked as enabled
-  if (index.isValid())
-    return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
-  else
-    return Qt::ItemIsEnabled;
-}
-
-/**
-      @param f :: Number format:  'f' - fixed, 'e' - scientific.
-      @param prec :: New precision (number of digits after the decimal point) with which the data will
-                   be shown in MantidMatrix.
-  */
-void MantidMatrixModel::setFormat(const QChar& f,int prec)
-{
-  QString formats = " ef";
-  if ( formats.indexOf(f) > 0 )
-  {
-    m_format = f.toAscii();
-    m_prec = prec;
-  }
-}
-
-QVariant MantidMatrixModel::data(const QModelIndex &index, int role) const
-{
-  if (role != Qt::DisplayRole) return QVariant();
-  double val = data(index.row(),index.column());
-  return QVariant(m_locale.toString(val,m_format,m_prec));
-}
-
+#include "MantidMatrix.h"
+#include "MantidKernel/Timer.h"
+#include "MantidUI.h"
+#include "../Graph3D.h"
+#include "../ApplicationWindow.h"
+#include "../Spectrogram.h"
+#include "MantidMatrixDialog.h"
+#include "Preferences.h"
+#include "../pixmaps.h"
+
+#include "MantidAPI/TextAxis.h"
+
+#include <QtGlobal>
+#include <QTextStream>
+#include <QList>
+#include <QEvent>
+#include <QContextMenuEvent>
+#include <QVBoxLayout>
+#include <QMouseEvent>
+#include <QHeaderView>
+#include <QApplication>
+#include <QVarLengthArray>
+#include <QClipboard>
+#include <QShortcut>
+#include <QPrinter>
+#include <QPrintDialog>
+#include <QPainter>
+#include <QLocale>
+#include <QItemDelegate>
+#include <QLabel>
+#include <QStackedWidget>
+#include <QImageWriter>
+#include <QSvgGenerator>
+#include <QFile>
+#include <QUndoStack>
+#include <QCheckBox>
+#include <QTabWidget>
+
+#include <stdlib.h>
+#include <iostream>
+#include <algorithm>
+#include <limits>
+
+using namespace Mantid;
+using namespace Mantid::API;
+using namespace Mantid::Kernel;
+
+//Mantid::Kernel::Logger & MantidMatrix::g_log=Mantid::Kernel::Logger::get("MantidMatrix");
+MantidMatrix::MantidMatrix(Mantid::API::MatrixWorkspace_sptr ws, ApplicationWindow* parent, const QString& label, const QString& name, int start, int end)
+  : MdiSubWindow(label, parent, name, 0),
+    WorkspaceObserver(),
+    y_start(0.0),y_end(0.0),
+    m_histogram(false),
+    m_min(0),m_max(0),
+    m_are_min_max_set(false),
+    m_boundingRect(),
+    m_funct(this),
+    m_selectedRows(),
+    m_selectedCols()
+{
+  m_appWindow = parent;
+  m_strName = name.toStdString();
+  m_workspace = ws;
+  setup(ws,start,end);
+  setWindowTitle(name);
+  setName(name);
+  setIcon( matrixIcon() );
+
+  m_modelY = new MantidMatrixModel(this,ws.get(),m_rows,m_cols,m_startRow,MantidMatrixModel::Y);
+  m_table_viewY = new QTableView();
+  connectTableView(m_table_viewY,m_modelY);
+  setColumnsWidth(0,MantidPreferences::MantidMatrixColumnWidthY());
+  setNumberFormat(0,MantidPreferences::MantidMatrixNumberFormatY(),
+                  MantidPreferences::MantidMatrixNumberPrecisionY());
+
+  m_modelX = new MantidMatrixModel(this,ws.get(),m_rows,m_cols,m_startRow,MantidMatrixModel::X);
+  m_table_viewX = new QTableView();
+  connectTableView(m_table_viewX,m_modelX);
+  setColumnsWidth(1,MantidPreferences::MantidMatrixColumnWidthX());
+  setNumberFormat(1,MantidPreferences::MantidMatrixNumberFormatX(),
+                  MantidPreferences::MantidMatrixNumberPrecisionX());
+
+  m_modelE = new MantidMatrixModel(this,ws.get(),m_rows,m_cols,m_startRow,MantidMatrixModel::E);
+  m_table_viewE = new QTableView();
+  connectTableView(m_table_viewE,m_modelE);
+  setColumnsWidth(2,MantidPreferences::MantidMatrixColumnWidthE());
+  setNumberFormat(2,MantidPreferences::MantidMatrixNumberFormatE(),
+                  MantidPreferences::MantidMatrixNumberPrecisionE());
+
+  m_YTabLabel = QString("Y values");
+  m_XTabLabel = QString("X values");
+  m_ETabLabel = QString("Errors");
+
+  m_tabs = new QTabWidget(this);
+  m_tabs->insertTab(0,m_table_viewY, m_YTabLabel);
+  m_tabs->insertTab(1,m_table_viewX, m_XTabLabel);
+  m_tabs->insertTab(2,m_table_viewE, m_ETabLabel);
+
+  setWidget(m_tabs);
+  //for synchronizing the views
+  //index is zero for the defualt view
+  m_PrevIndex=0;
+  //install event filter on  these objects
+  m_table_viewY->installEventFilter(this);
+  m_table_viewX->installEventFilter(this);
+  m_table_viewE->installEventFilter(this);
+
+  connect(m_tabs,SIGNAL(currentChanged(int)),this,SLOT(viewChanged(int)));
+
+  setGeometry(50, 50, QMIN(5, numCols())*m_table_viewY->horizontalHeader()->sectionSize(0) + 55,
+              (QMIN(10,numRows())+1)*m_table_viewY->verticalHeader()->sectionSize(0)+100);
+
+  observeAfterReplace();
+  observeDelete();
+  observeADSClear();
+
+  connect(this,SIGNAL(needWorkspaceChange(Mantid::API::MatrixWorkspace_sptr)),this,SLOT(changeWorkspace(Mantid::API::MatrixWorkspace_sptr))); 
+  connect(this,SIGNAL(needToClose()),this,SLOT(closeMatrix()));
+
+  connect(this, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(selfClosed(MdiSubWindow*)));
+
+  askOnCloseEvent(false);
+}
+
+MantidMatrix::~MantidMatrix()
+{
+  delete m_modelY;
+  delete m_modelX;
+  delete m_modelE;
+}
+
+bool MantidMatrix::eventFilter(QObject *object, QEvent *e)
+{
+  // if it's context menu on any of the views
+  if (e->type() == QEvent::ContextMenu && (object == m_table_viewY || object == m_table_viewX || object == m_table_viewE)){
+    emit showContextMenu();
+    return true;
+  }
+  return MdiSubWindow::eventFilter(object, e);
+}
+
+/** Called when switching between tabs
+ *  @param index :: The index of the new active tab
+ */
+void MantidMatrix::viewChanged(int index)
+{
+  // get the previous view and selection model
+  QTableView* prevView=(QTableView*)m_tabs->widget(m_PrevIndex);
+  if(prevView)
+  {
+    QItemSelectionModel *oldSelModel = prevView->selectionModel();
+    QItemSelectionModel *selModel = activeView()->selectionModel();
+    // Copy the selection from the previous tab into the newly-activated one
+    selModel->select(oldSelModel->selection(),QItemSelectionModel::Select);
+    // Clear the selection on the now-hidden tab
+    oldSelModel->clearSelection();
+
+    m_PrevIndex=index;
+    //get the previous tab scrollbar positions
+    int hValue=  prevView->horizontalScrollBar()->value();
+    int vValue = prevView->verticalScrollBar()->value();
+    //to synchronize the views
+    //set  the previous view  scrollbar positions to current view
+    activeView()->horizontalScrollBar()->setValue(hValue);
+    activeView()->verticalScrollBar()->setValue(vValue);
+  }
+
+}
+
+/// Checks if d is not infinity or a NaN
+bool isANumber(volatile const double& d)
+{
+  return d != std::numeric_limits<double>::infinity() && d == d;
+}
+
+void MantidMatrix::setup(Mantid::API::MatrixWorkspace_sptr ws, int start, int end)
+{
+  if (!ws.get())
+  {
+    QMessageBox::critical(0,"WorkspaceMatrixModel error","2D workspace expected.");
+    m_rows = 0;
+    m_cols = 0;
+    m_startRow = 0;
+    m_endRow = 0;
+    return;
+  }
+
+  m_workspace = ws;
+  m_workspaceTotalHist = ws->getNumberHistograms();
+  m_startRow = (start<0 || start>=m_workspaceTotalHist)?0:start;
+  m_endRow   = (end<0 || end>=m_workspaceTotalHist || end < start)? m_workspaceTotalHist - 1 : end;
+  m_rows = m_endRow - m_startRow + 1;
+  m_cols = ws->blocksize();
+  if ( ws->isHistogramData() ) m_histogram = true;
+  connect(this,SIGNAL(needsUpdating()),this,SLOT(repaintAll()));
+
+
+  m_bk_color = QColor(128, 255, 255);
+  m_matrix_icon = getQPixmap("mantid_matrix_xpm");
+  m_column_width = 100;
+
+}
+
+void MantidMatrix::connectTableView(QTableView* view,MantidMatrixModel*model)
+{
+  view->setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding));
+  view->setSelectionMode(QAbstractItemView::ExtendedSelection);
+  view->setModel(model);
+  view->setCornerButtonEnabled(false);
+  view->setFocusPolicy(Qt::StrongFocus);
+
+  QPalette pal = view->palette();
+  pal.setColor(QColorGroup::Base, m_bk_color);
+  view->setPalette(pal);
+
+  // set header properties
+  QHeaderView* hHeader = (QHeaderView*)view->horizontalHeader();
+  hHeader->setMovable(false);
+  hHeader->setResizeMode(QHeaderView::Interactive);
+  hHeader->setDefaultSectionSize(m_column_width);
+
+  view->resizeRowToContents(0);
+  int row_height = view->rowHeight(0);
+
+  QHeaderView* vHeader = (QHeaderView*)view->verticalHeader();
+  vHeader->setDefaultSectionSize(row_height);
+  vHeader->setResizeMode(QHeaderView::Fixed);
+  vHeader->setMovable(false);
+}
+
+double MantidMatrix::cell(int row, int col)
+{
+  return m_modelY->data(row, col);
+}
+
+QString MantidMatrix::text(int row, int col)
+{
+  return QString::number(activeModel()->data(row, col));
+}
+
+/** Sets new column width in a table view(s).
+    @param width :: New column width in pixels. All columns have the same width.
+    @param all :: If true the change will be applied to all three table views.
+*/
+void MantidMatrix::setColumnsWidth(int width, bool all)
+{
+  if (all)
+  {
+    m_table_viewY->horizontalHeader()->setDefaultSectionSize(width);
+    m_table_viewX->horizontalHeader()->setDefaultSectionSize(width);
+    m_table_viewE->horizontalHeader()->setDefaultSectionSize(width);
+
+    int cols = numCols();
+    for(int i=0; i<cols; i++)
+    {
+      m_table_viewY->setColumnWidth(i, width);
+      m_table_viewX->setColumnWidth(i, width);
+      m_table_viewE->setColumnWidth(i, width);
+    }
+    MantidPreferences::MantidMatrixColumnWidth(width);
+  }
+  else
+  {
+    QTableView* table_view = activeView();
+    table_view->horizontalHeader()->setDefaultSectionSize(width);
+    int cols = numCols();
+    for(int i=0; i<cols; i++)
+      table_view->setColumnWidth(i, width);
+    switch (m_tabs->currentIndex())
+    {
+    case 0: MantidPreferences::MantidMatrixColumnWidthY(width);break;
+    case 1: MantidPreferences::MantidMatrixColumnWidthX(width);break;
+    case 2: MantidPreferences::MantidMatrixColumnWidthE(width);break;
+    }
+  }
+
+  emit modifiedWindow(this);
+}
+
+/**  Sets column width to one table view.
+     @param i :: ordinal number of the view. 0 - Y, 1 - X, 2 - Error
+     @param width :: New column width in pixels. All columns have the same width.
+*/
+void MantidMatrix::setColumnsWidth(int i,int width)
+{
+
+  QTableView* table_view;
+  switch(i)
+  {
+  case 0: table_view =  m_table_viewY; MantidPreferences::MantidMatrixColumnWidthY(width); break;
+  case 1: table_view =  m_table_viewX; MantidPreferences::MantidMatrixColumnWidthX(width); break;
+  case 2: table_view =  m_table_viewE; MantidPreferences::MantidMatrixColumnWidthE(width); break;
+  default: table_view = activeView();
+  };
+
+  table_view->horizontalHeader()->setDefaultSectionSize(width);
+  int cols = numCols();
+  for(int i=0; i<cols; i++)
+    table_view->setColumnWidth(i, width);
+
+  emit modifiedWindow(this);
+}
+
+/**  Returns the width of a column.
+     @param i :: ordinal number of the view. 0 - Y, 1 - X, 2 - Error
+     @return The column width in pixels. All columns have the same width.
+*/
+int MantidMatrix::columnsWidth(int i)
+{
+  switch(i)
+  {
+  case 0: return m_table_viewY->columnWidth(0);
+  case 1: return m_table_viewX->columnWidth(0);
+  case 2: return m_table_viewE->columnWidth(0);
+  };
+  return activeView()->columnWidth(0);
+}
+
+/**  Return the pointer to the active table view.
+*/
+QTableView *MantidMatrix::activeView()
+{
+  switch (m_tabs->currentIndex())
+  {
+  case 0: return m_table_viewY;
+  case 1: return m_table_viewX;
+  case 2: return m_table_viewE;
+  }
+  return m_table_viewY;
+}
+
+/**  Returns the pointer to the active model.
+*/
+MantidMatrixModel *MantidMatrix::activeModel()
+{
+  switch (m_tabs->currentIndex())
+  {
+  case 0: return m_modelY;
+  case 1: return m_modelX;
+  case 2: return m_modelE;
+  }
+  return m_modelY;
+}
+
+/**  Copies the current selection in the active table view into the system clipboard.
+*/
+void MantidMatrix::copySelection()
+{
+  QItemSelectionModel *selModel = activeView()->selectionModel();
+  QString s = "";
+  QString eol = applicationWindow()->endOfLine();
+  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())
+      return;
+
+    QItemSelectionRange cur = it.next();
+    int top = cur.top();
+    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++)
+        s += text(i, j) + "\t";
+      s += text(i,right) + eol;
+    }
+  }
+  // Copy text into the clipboard
+  QApplication::clipboard()->setText(s.trimmed());
+}
+
+/**  Returns minimum and maximum values in the matrix.
+     If setRange(...) has not been called it returns the true smalles ang largest Y-values in the matrix,
+     otherwise the values set with setRange(...) are returned. These are needed in plotGraph2D to set
+     the range of the third, colour axis.
+     @param[out] min is set to the minumium value
+     @param[out] max is set to the maximum value
+*/
+void MantidMatrix::range(double *min, double *max)
+{
+  if (!m_are_min_max_set)
+  {
+    //this is here to fill m_min and m_max with numbers that aren't nan
+    m_min = std::numeric_limits<double>::max();
+    m_max = -std::numeric_limits<double>::max();
+
+    if (this->m_workspace)
+    {
+
+      PARALLEL_FOR1(m_workspace)
+      for (int wi=0; wi < m_workspace->getNumberHistograms(); wi++)
+      {
+        double local_min, local_max;
+        const MantidVec & Y = m_workspace->readY(wi);
+
+        local_min = std::numeric_limits<double>::max();
+        local_max = -std::numeric_limits<double>::max();
+
+        for (size_t i=0; i < Y.size(); i++)
+        {
+          double aux = Y[i];
+          if (fabs(aux) == std::numeric_limits<double>::infinity() || aux != aux)
+            continue;
+          if (aux < local_min)
+            local_min = aux;
+          if (aux > local_max)
+            local_max = aux;
+        }
+
+        // Now merge back the local min max
+        PARALLEL_CRITICAL(MantidMatrix_range_max)
+        {
+          if (local_max > m_max)
+            m_max = local_max;
+        }
+        PARALLEL_CRITICAL(MantidMatrix_range_min)
+        {
+          if (local_min < m_min)
+            m_min = local_min;
+        }
+      }
+      m_are_min_max_set = true;
+    }
+
+    // Make up some reasonable values if nothing was found
+    if (m_min == std::numeric_limits<double>::max())
+      m_min = 0;
+    if (m_max == -std::numeric_limits<double>::max())
+      m_max = m_min + 1e6;
+
+//    // ---- VERY SLOW OLD ALGORITHM -----
+//    int rows = numRows();
+//    int cols = numCols();
+//    for(int i=0; i<rows; i++){
+//      for(int j=0; j<cols; j++){
+//        double aux = cell(i, j);
+//        if (fabs(aux) == std::numeric_limits<double>::infinity() || aux != aux)
+//        {
+//          continue;
+//        }
+//        if (aux <= m_min)
+//          m_min = aux;
+//
+//        if (aux >= m_max)
+//          m_max = aux;
+//      }
+//
+//      m_are_min_max_set = true;
+//    }
+
+
+  }
+  *min = m_min;
+  *max = m_max;
+}
+
+
+
+/**  Sets new minimum and maximum Y-values which can be displayed in a 2D graph
+*/
+void MantidMatrix::setRange(double min, double max)
+{
+  m_min = min;
+  m_max = max;
+  m_are_min_max_set = true;
+}
+
+double** MantidMatrix::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++)
+        free(data[j]);
+      free(data);
+
+      QMessageBox::critical(0, tr("MantidPlot") + " - " + tr("Memory Allocation Error"),
+                            tr("Not enough memory, operation aborted!"));
+      return NULL;
+    }
+  }
+  return data;
+}
+
+void MantidMatrix::freeMatrixData(double **data, int rows)
+{
+  for ( int i = 0; i < rows; i++)
+    free(data[i]);
+
+  free(data);
+}
+
+void MantidMatrix::goTo(int row,int col)
+{
+  if(row < 1 || row > numRows())
+    return;
+  if(col < 1 || col > numCols())
+    return;
+
+  activeView()->selectionModel()->select(activeModel()->index(row - 1, col - 1), QItemSelectionModel::ClearAndSelect);
+  activeView()->scrollTo(activeModel()->index(row - 1, col - 1), QAbstractItemView::PositionAtTop);
+}
+
+void MantidMatrix::goToRow(int row)
+{
+  if(row < 1 || row > numRows())
+    return;
+
+  //	activeView()->selectRow(row - 1); //For some reason, this did not highlight the row at all, hence the stupid line below
+  activeView()->selectionModel()->select(QItemSelection(activeModel()->index(row - 1, 0), activeModel()->index(row - 1, numCols() - 1)), QItemSelectionModel::ClearAndSelect);
+
+  activeView()->scrollTo(activeModel()->index(row - 1, 0), QAbstractItemView::PositionAtCenter);
+}
+
+void MantidMatrix::goToColumn(int col)
+{
+  if(col < 1 || col > numCols())
+    return;
+
+  //	activeView()->selectColumn(col - 1); //For some reason, this did not highlight the row at all, hence the stupid line below
+  activeView()->selectionModel()->select(QItemSelection(activeModel()->index(0, col - 1), activeModel()->index(numRows() - 1, col - 1)), QItemSelectionModel::ClearAndSelect);
+  activeView()->scrollTo(activeModel()->index(0, col - 1), QAbstractItemView::PositionAtCenter);
+
+}
+
+double MantidMatrix::dataX(int row, int col) const
+{
+  if (!m_workspace || row >= numRows() || col >= static_cast<int>(m_workspace->readX(row + m_startRow).size())) return 0.;
+  double res = m_workspace->readX(row + m_startRow)[col];
+  return res;
+
+}
+
+double MantidMatrix::dataY(int row, int col) const
+{
+  if (!m_workspace || row >= numRows() || col >= numCols()) return 0.;
+  double res = m_workspace->readY(row + m_startRow)[col];
+  return res;
+
+}
+
+double MantidMatrix::dataE(int row, int col) const
+{
+  if (!m_workspace || row >= numRows() || col >= numCols()) return 0.;
+  double res = m_workspace->readE(row + m_startRow)[col];
+  if (res == 0.) res = 1.;//  quick fix of the fitting problem
+  return res;
+
+}
+
+/////////////////////////////////////////
+
+int MantidMatrix::indexY(double s)const
+{
+  int n = m_rows;
+
+  const Mantid::API::Axis& yAxis = *m_workspace->getAxis(1);
+
+  bool isNumeric = yAxis.isNumeric();
+  
+  if (n == 0) return -1;
+
+  int i0 = m_startRow;
+
+  if (s < yAxis(i0))
+  {
+    if (isNumeric || yAxis(i0) - s > 0.5) return -1;
+    return 0;
+  }
+  else if (s > yAxis(n-1))
+  {
+    if (isNumeric || s - yAxis(n-1) > 0.5) return -1;
+    return n-1;
+  }
+
+  int i = i0, j = n-1, k = n/2;
+  double ss;
+  int it;
+  for(it=0;it<n;it++)
+  {
+    ss = yAxis(k);
+    if (ss == s ) return k;
+    if (abs(i - j) <2)
+    {
+      double ds = fabs(ss-s);
+      double ds1 = fabs(yAxis(j)-s);
+      if (ds1 < ds)
+      {
+        if (isNumeric || ds1 < 0.5) return j;
+        return -1;
+      }
+      if (isNumeric || ds < 0.5) return i;
+      return -1;
+    }
+    if (s > ss) i = k;
+    else
+      j = k;
+    k = i + (j - i)/2;
+  }
+
+  return i;
+}
+
+QString MantidMatrix::workspaceName() const
+{
+  return QString::fromStdString(m_strName);
+}
+
+QwtDoubleRect MantidMatrix::boundingRect()
+{
+  if (m_boundingRect.isNull())
+  {
+    m_spectrogramRows = numRows() > 100 ? numRows() : 100;
+
+    // This is only meaningful if a 2D (or greater) workspace
+    if (m_workspace->axes() > 1)
+    {
+      const Mantid::API::Axis* const ax = m_workspace->getAxis(1);
+      y_start =(*ax)(m_startRow);
+      y_end   =(*ax)(m_endRow);
+    }
+
+    double dy = fabs(y_end - y_start)/(double)(numRows() - 1);
+
+    int i0 = m_startRow;
+    x_start = x_end = 0;
+    while(x_start == x_end && i0 <= m_endRow)
+    {
+      i0++;
+      const Mantid::MantidVec& X = m_workspace->readX(i0);
+      x_start = X[0];
+      if (X.size() != m_workspace->readY(i0).size()) x_end = X[m_workspace->blocksize()];
+      else
+        x_end = X[m_workspace->blocksize()-1];
+      if ( !isANumber(x_start) || !isANumber(x_end))
+      {
+        x_start = x_end = 0;
+      }
+    }
+
+    // if i0 > m_endRow there aren't any plottable rows
+    if (i0 <= m_endRow)
+    {
+      // check if all X vectors are the same
+      bool theSame = true;
+      double dx = 0.;
+      for(int i=i0;i<=m_endRow;++i)
+      {
+        if (m_workspace->readX(i).front() != x_start || m_workspace->readX(i).back() != x_end)
+        {
+          theSame = false;
+          break;
+        }
+      }
+      dx = fabs(x_end - x_start)/(double)(numCols() - 1);
+
+      if ( !theSame )
+      {
+        // Find the smallest bin width and thus the number of columns in a spectrogram
+        // that can be plotted from this matrix
+        double ddx = dx;
+        for(int i=m_startRow+1;i<=m_endRow;++i)
+        {
+          const Mantid::MantidVec& X = m_workspace->readX(i);
+          if (X.front() < x_start)
+          {
+            double xs = X.front();
+            if (!isANumber(xs)) continue;
+            x_start = xs;
+          }
+          if (X.back() > x_end)
+          {
+            double xe = X.back();
+            if (!isANumber(xe)) continue;
+            x_end = xe;
+          }
+          for(int j=1;j<static_cast<int>(X.size());++j)
+          {
+            double d = X[j] - X[j-1];
+            if (ddx == 0 && d < ddx)
+            {
+              ddx = d;
+            }
+          }
+        }
+        m_spectrogramCols = int((x_end - x_start)/ddx);
+        if (m_spectrogramCols < 100) m_spectrogramCols = 100;
+      }
+      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();
+
+    }
+    else
+    {
+      m_spectrogramCols = 0;
+      m_boundingRect = QwtDoubleRect(0, QMIN(y_start, y_end) - 0.5*dy,
+        1, fabs(y_end - y_start) + dy).normalized();
+    }
+  }// Define the spectrogram bounding box
+  return m_boundingRect;
+}
+
+//----------------------------------------------------------------------------
+void MantidMatrixFunction::init()
+{
+ if (!m_matrix->workspace()->getAxis(1))
+ {
+   throw std::runtime_error("The y-axis is not set");
+ }
+
+  double tmp;
+  m_matrix->range(&tmp,&m_outside);
+  m_outside *= 1.1;
+}
+
+double MantidMatrixFunction::operator()(double x, double y)
+{
+  int i = m_matrix->indexY(y);
+  if (i < 0 || i >= m_matrix->numRows())
+  {
+    return m_outside;
+  }
+
+  int j = m_matrix->indexX(i,x);
+
+  if (j >=0 && j < m_matrix->numCols())
+    return m_matrix->dataY(i,j);
+  else
+    return m_outside;
+}
+
+double MantidMatrixFunction::getMinPositiveValue()const
+{
+  double zmin = DBL_MAX;
+  for(int i=0;i<numRows();++i)
+  {
+    for(int j=0;j<numCols();++j)
+    {
+      double tmp = value(i,j);
+      if (tmp > 0 && tmp < zmin)
+      {
+        zmin = tmp;
+      }
+    }
+  }
+  return zmin;
+}
+
+int MantidMatrixFunction::numRows()const
+{
+  return m_matrix->m_rows;
+}
+
+int MantidMatrixFunction::numCols()const
+{
+  return m_matrix->m_cols;
+}
+
+double MantidMatrixFunction::value(int row,int col)const
+{
+  return m_matrix->m_workspace->readY(row + m_matrix->m_startRow)[col];
+}
+
+void MantidMatrixFunction::getRowYRange(int row,double& ymin, double& ymax)const
+{
+  const Mantid::API::Axis& yAxis = *(m_matrix->m_workspace->getAxis(1));
+
+
+  int i = row + m_matrix->m_startRow;
+  double y = yAxis(i);
+
+  int imax = m_matrix->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 = (yAxis(i-1) + y)/2;
+      ymax = 2*y - ymin;
+    }
+  }
+  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_matrix->m_workspace->readX(row + m_matrix->m_startRow);
+  xmin = X[0];
+  xmax = X[X.size()-1];
+}
+
+const Mantid::MantidVec& MantidMatrixFunction::getMantidVec(int row)const
+{
+  return m_matrix->m_workspace->readX(row + m_matrix->m_startRow);
+}
+
+int MantidMatrix::indexX(int row,double s)const
+{
+  int n = m_workspace->blocksize();
+
+  //bool isHistogram = m_workspace->isHistogramData();
+
+  const Mantid::MantidVec& X = m_workspace->readX(row + m_startRow);
+  if (n == 0 || s < X[0] || s > X[n-1]) return -1;
+
+  int i = 0, j = n-1, k = n/2;
+  double ss;
+  int it;
+  for(it=0;it<n;it++)
+  {
+    ss = X[k];
+    if (ss == s ) return k;
+    if (abs(i - j) <2)
+    {
+      double ds = fabs(ss-s);
+      if (fabs(X[j]-s) < ds) return j;
+      return i;
+    }
+    if (s > ss) i = k;
+    else
+      j = k;
+    k = i + (j - i)/2;
+  }
+
+  return i;
+}
+
+//----------------------------------------------------------------------------
+
+Graph3D * MantidMatrix::plotGraph3D(int style)
+{
+  QApplication::setOverrideCursor(Qt::WaitCursor);
+
+  ApplicationWindow* a = applicationWindow();
+  QString labl = a->generateUniqueName(tr("Graph"));
+
+  Graph3D *plot = new Graph3D("", a);
+  plot->resize(500,400);
+  plot->setWindowTitle(labl);
+  plot->setName(labl);
+  plot->setTitle(tr("Workspace ")+name());
+  a->customPlot3D(plot);
+  plot->customPlotStyle(style);
+  int resCol = numCols() / 200;
+  int resRow = numRows() / 200;
+  plot->setResolution( qMax(resCol,resRow) );
+
+  double zMin =  1e300;
+  double zMax = -1e300;
+  for(int i=0;i<numRows();i++)
+    for(int j=0;j<numCols();j++)
+    {
+    if (cell(i,j) < zMin) zMin = cell(i,j);
+    if (cell(i,j) > zMax) zMax = cell(i,j);
+  }
+
+  // Calculate xStart(), xEnd(), yStart(), yEnd()
+  boundingRect();
+  
+  m_funct.init();
+  plot->addFunction("", xStart(), xEnd(), yStart(), yEnd(), zMin, zMax, numCols(), numRows(), static_cast<UserHelperFunction*>(&m_funct));
+
+  const Mantid::API::Axis* ax = m_workspace->getAxis(0);
+  std::string s;
+  if ( ax->unit() ) s = ax->unit()->caption() + " / " + ax->unit()->label();
+  else
+    s = "X Axis";
+  plot->setXAxisLabel(tr(s.c_str()));
+
+  if ( m_workspace->axes() > 1 )
+  {
+    ax = m_workspace->getAxis(1);
+    if (ax->isNumeric())
+    {
+      if ( ax->unit() ) s = ax->unit()->caption() + " / " + ax->unit()->label();
+      else
+        s = "Y Axis";
+      plot->setYAxisLabel(tr(s.c_str()));
+    }
+    else
+      plot->setYAxisLabel(tr("Spectrum"));
+  }
+
+  plot->setZAxisLabel(tr(m_workspace->YUnitLabel().c_str()));
+
+  a->initPlot3D(plot);
+  //plot->askOnCloseEvent(false);
+  QApplication::restoreOverrideCursor();
+
+  return plot;
+}
+
+/** Creates a MultiLayer graph and plots this MantidMatrix as a Spectrogram.
+
+    @param type :: The "curve" type.
+    @return Pointer to the created graph.
+*/
+MultiLayer* MantidMatrix::plotGraph2D(Graph::CurveType type)
+{
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  ApplicationWindow *a = applicationWindow();
+  MultiLayer* g = a->multilayerPlot(a->generateUniqueName(tr("Graph")));
+  m_plots2D<<g;
+  connect(g, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(dependantClosed(MdiSubWindow*)));
+  //#799 fix for  multiple dialog creation on double clicking/ on right click menu scale on  2d plot
+  //   a->connectMultilayerPlot(g);
+  Graph* plot = g->activeGraph();
+  ProjectData *prjData=0;
+  plotSpectrogram(plot,a,type,false,prjData);
+ // g->askOnCloseEvent(false);
+  QApplication::restoreOverrideCursor();
+  return g;
+}
+
+Spectrogram* MantidMatrix::plotSpectrogram(Graph* plot,ApplicationWindow* app,Graph::CurveType type,bool project,ProjectData *prjData)
+{
+  app->setPreferences(plot);
+  plot->setTitle(tr("Workspace ") + name());
+  const Mantid::API::Axis* ax;
+  ax = m_workspace->getAxis(0);
+  std::string s;
+  if (ax->unit().get()) s = ax->unit()->caption() + " / " + ax->unit()->label();
+  else
+    s = "X Axis";
+  plot->setXAxisTitle(tr(s.c_str()));
+  if ( m_workspace->axes() > 1 )
+  {
+    ax = m_workspace->getAxis(1);
+    if (ax->isNumeric())
+    {
+      if ( ax->unit() ) s = ax->unit()->caption() + " / " + ax->unit()->label();
+      else
+        s = "Y Axis";
+      plot->setYAxisTitle(tr(s.c_str()));
+    }
+    else
+      plot->setYAxisTitle(tr("Spectrum"));
+  }
+
+  // Set the range on the thirs, colour axis
+  double minz, maxz;
+  m_funct.init();
+  range(&minz,&maxz);
+  Spectrogram *spgrm = plot->plotSpectrogram(&m_funct, m_spectrogramRows, m_spectrogramCols, boundingRect(), minz, maxz, type);
+  if( spgrm )
+  {
+    spgrm->setDisplayMode(QwtPlotSpectrogram::ImageMode, true);
+    spgrm->setDisplayMode(QwtPlotSpectrogram::ContourMode, false);
+    if(project)
+    {
+      spgrm->mutableColorMap().loadMap(prjData->getColormapFile());
+      spgrm->setCustomColorMap(spgrm->mutableColorMap());
+      spgrm->setIntensityChange(prjData->getIntensity());
+      if(!prjData->getGrayScale())spgrm->setGrayScale();
+      if(prjData->getContourMode())
+      {spgrm->setDisplayMode(QwtPlotSpectrogram::ContourMode, true);
+      spgrm->showContourLineLabels(true);
+      }
+      spgrm->setDefaultContourPen(prjData->getDefaultContourPen());
+      spgrm->setColorMapPen(false);
+      if(prjData->getColorMapPen())spgrm->setColorMapPen(true);
+      ContourLinesEditor* contourEditor=prjData->getContourLinesEditor();
+      if(contourEditor) 
+      {
+        contourEditor->setSpectrogram(spgrm);
+        contourEditor->updateContents();
+        contourEditor->updateContourLevels();
+      }
+    }
+
+  }
+  plot->setAutoScale();
+  return spgrm;
+}
+void MantidMatrix::setSpectrumGraph(MultiLayer *ml, Table* t)
+{
+  MantidUI::setUpSpectrumGraph(ml,name());
+  connect(ml, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(dependantClosed(MdiSubWindow*)));
+  if (t)
+  {
+    m_plots1D[ml] = t;
+    connect(t, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(dependantClosed(MdiSubWindow*)));
+  }
+  else
+    m_plots2D<<ml;
+}
+
+void MantidMatrix::setBinGraph(MultiLayer *ml, Table* t)
+{
+  MantidUI::setUpBinGraph(ml,name(),workspace());
+  connect(ml, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(dependantClosed(MdiSubWindow*)));
+  if (t)
+  {
+    m_plots1D[ml] = t;
+    connect(t, SIGNAL(closedWindow(MdiSubWindow*)), this, SLOT(dependantClosed(MdiSubWindow*)));
+  }
+  else
+    m_plots2D<<ml;
+}
+
+// Remove all references to the MantidMatrix
+void MantidMatrix::removeWindow()
+{
+  QList<MdiSubWindow *> windows = applicationWindow()->windowsList();
+  foreach(MdiSubWindow *w, windows){
+    //if (w->isA("Graph3D") && ((Graph3D*)w)->userFunction()->hlpFun() == &m_funct)
+    if (w->isA("Graph3D") )//&& ((Graph3D*)w)->userFunction()->hlpFun() == &m_funct)
+    { 	UserFunction* fn=((Graph3D*)w)->userFunction();
+      if(fn)
+      {	if(fn->hlpFun() == &m_funct)((Graph3D*)w)->clearData();
+      }
+
+    }else if (w->isA("Table")){
+    }
+    else if (w->isA("MultiLayer")){
+      QList<Graph *> layers = ((MultiLayer*)w)->layersList();
+      foreach(Graph *g, layers){
+        for (int i=0; i<g->curves(); i++){
+          Spectrogram *sp = (Spectrogram *)g->plotItem(i);
+          if (sp && sp->rtti() == QwtPlotItem::Rtti_PlotSpectrogram && sp->funct() == &m_funct)
+            g->removeCurve(i);
+        }
+      }
+    }
+
+  }
+  //this->closeDependants();
+}
+
+/// Returns a list of the selected rows
+const QList<int>& MantidMatrix::getSelectedRows() const
+{
+  return m_selectedRows;
+}
+
+/**
+ * Sets the internal cache of selected rows.
+ * @return True if rows are selected, false otherwise
+ */
+bool MantidMatrix::setSelectedRows()
+{
+  QTableView *tv = activeView();
+  QItemSelectionModel *selModel = tv->selectionModel();
+  if( !selModel  ) return false;
+
+  m_selectedRows.clear();
+  const QModelIndexList rows = selModel->selectedRows();
+  QModelIndexList::const_iterator it;
+  for ( it = rows.constBegin(); it != rows.constEnd(); ++it)
+  {
+    m_selectedRows.append(it->row()+m_startRow);
+  }
+
+  return (m_selectedRows.empty() ? false : true);
+}
+
+/// Returns a list of the selected columns
+const QList<int>& MantidMatrix::getSelectedColumns() const
+{
+  return m_selectedCols;
+}
+
+/**
+ * Sets the internal cache of selected columns.
+ * @return True if columns are selected, false otherwise
+ */
+bool MantidMatrix::setSelectedColumns()
+{
+  QTableView *tv = activeView();
+  QItemSelectionModel *selModel = tv->selectionModel();
+  if( !selModel ||  !selModel->hasSelection()) return false;
+
+  m_selectedCols.clear();
+  const QModelIndexList cols = selModel->selectedColumns();
+  QModelIndexList::const_iterator it;
+  for ( it = cols.constBegin(); it != cols.constEnd(); ++it)
+  {
+    m_selectedCols.append(it->column());
+  }
+
+  return (m_selectedCols.empty() ? false : true);
+}
+
+void MantidMatrix::dependantClosed(MdiSubWindow* w)
+{
+  if( w->isA("Table") )
+  {
+    QMap<MultiLayer*,Table*>::iterator itr;
+    for( itr = m_plots1D.begin(); itr != m_plots1D.end(); ++itr )
+    {
+      if( itr.value() == (Table*)w )
+      {
+        m_plots1D.erase(itr);
+        break;
+      }
+    }
+  }
+  else if (w->isA("MultiLayer"))
+  {
+    int i = m_plots2D.indexOf((MultiLayer*)w);
+    if (i >= 0)m_plots2D.remove(i);
+    else
+    {QMap<MultiLayer*,Table*>::iterator i = m_plots1D.find((MultiLayer*)w);
+      if (i != m_plots1D.end())
+      {
+        if (i.value() != 0)
+        {
+          i.value()->askOnCloseEvent(false);
+          i.value()->close();
+        }
+        m_plots1D.erase(i);
+      }
+    }
+  }
+}
+
+/**
+     Repaints all 1D and 2D plots attached to this MantidMatrix
+*/
+void MantidMatrix::repaintAll()
+{
+  repaint();
+
+  // Repaint 2D plots
+  QVector<MultiLayer*>::iterator vEnd  = m_plots2D.end();
+  for( QVector<MultiLayer*>::iterator vItr = m_plots2D.begin(); vItr != vEnd; ++vItr )
+  {
+    (*vItr)->activeGraph()->replot();
+  }
+
+  // Updates the 1D plots by modifying the attached tables
+  QMap<MultiLayer*,Table*>::iterator mEnd = m_plots1D.end();
+  for(QMap<MultiLayer*,Table*>::iterator mItr = m_plots1D.begin(); mItr != mEnd;  ++mItr)
+  {
+    Table* t = mItr.value();
+    if ( !t ) continue;
+    int charsToRemove = t->name().size() + 1;
+    int nTableCols(t->numCols());
+    for(int col = 1; col < nTableCols; ++col)
+    {
+      QString colName = t->colName(col).remove(0,charsToRemove);
+      if( colName.isEmpty() ) break;
+      //Need to determine whether the table was created from plotting a spectrum
+      //or a time bin. A spectrum has a Y column name YS and a bin YB
+      QString ident = colName.left(2);
+      colName.remove(0,2); //This now contains the number in the MantidMatrix
+      int matrixNumber = colName.toInt();
+      if( matrixNumber < 0 ) break;
+      bool errs = (ident[0] == QChar('E')) ? true : false;
+      if( ident[1] == QChar('S') )
+      {
+        if( matrixNumber >= numRows() ) break;
+        int endCount = numCols();
+        for(int j = 0; j < endCount; ++j)
+        {
+          if( errs ) t->setCell(j, col, dataE(matrixNumber, j));
+          else t->setCell(j, col, dataY(matrixNumber, j));
+        }
+      }
+      else
+      {
+        if( matrixNumber >= numCols() ) break;
+        int endCount = numRows();
+        for(int j = 0; j < endCount; ++j)
+        {
+          if( errs ) t->setCell(j, col, dataE(j, matrixNumber));
+          else t->setCell(j, col, dataY(j, matrixNumber));
+        }
+      }
+    }
+    t->notifyChanges();
+    Graph *g = mItr.key()->activeGraph();
+    if (g) g->setAutoScale();
+  }
+}
+
+void MantidMatrix::afterReplaceHandle(const std::string& wsName,const boost::shared_ptr<Mantid::API::Workspace> ws)
+{
+  if( wsName != m_strName || !ws.get() ) return;
+
+  Mantid::API::MatrixWorkspace_sptr new_workspace = boost::dynamic_pointer_cast<MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(m_strName));
+  emit needWorkspaceChange( new_workspace ); 
+
+
+}
+
+void MantidMatrix::changeWorkspace(Mantid::API::MatrixWorkspace_sptr ws)
+{
+  if (m_cols != ws->blocksize() ||
+      m_workspaceTotalHist != ws->getNumberHistograms())
+  {
+    closeDependants();
+  }
+
+  // Save selection
+  QItemSelectionModel *oldSelModel = activeView()->selectionModel();
+  QModelIndexList indexList = oldSelModel->selectedIndexes();
+  QModelIndex curIndex = activeView()->currentIndex();
+
+  setup(ws,-1,-1);
+
+  m_modelY = new MantidMatrixModel(this,ws.get(),m_rows,m_cols,m_startRow,MantidMatrixModel::Y);
+  connectTableView(m_table_viewY,m_modelY);
+
+  m_modelX = new MantidMatrixModel(this,ws.get(),m_rows,m_cols,m_startRow,MantidMatrixModel::X);
+  connectTableView(m_table_viewX,m_modelX);
+
+  m_modelE = new MantidMatrixModel(this,ws.get(),m_rows,m_cols,m_startRow,MantidMatrixModel::E);
+  connectTableView(m_table_viewE,m_modelE);
+
+  // Restore selection
+  activeView()->setCurrentIndex(curIndex);
+  if (indexList.size())
+  {
+    QItemSelection sel(indexList.first(),indexList.last());
+    QItemSelectionModel *selModel = activeView()->selectionModel();
+    selModel->select(sel,QItemSelectionModel::Select);
+  }
+
+  invalidateBoundingRect();
+
+  repaintAll();
+
+}
+
+void MantidMatrix::closeDependants()
+{
+  while(m_plots2D.size())
+  {
+    MultiLayer* ml = m_plots2D.front();
+    ml->askOnCloseEvent(false);
+    ml->close();// this calls slot dependantClosed() which removes the pointer from m_plots2D
+  }
+
+  while(m_plots1D.size())
+  {
+    MultiLayer* ml = m_plots1D.begin().key();
+    ml->askOnCloseEvent(false);
+    ml->close();// this calls slot dependantClosed() which removes the pointer from m_plots1D
+  }
+
+}
+
+void MantidMatrix::setNumberFormat(const QChar& f,int prec, bool all)
+{
+  if (all)
+  {
+    modelY()->setFormat(f,prec);
+    modelX()->setFormat(f,prec);
+    modelE()->setFormat(f,prec);
+    MantidPreferences::MantidMatrixNumberFormat(f);
+    MantidPreferences::MantidMatrixNumberPrecision(prec);
+  }
+  else
+  {
+    activeModel()->setFormat(f,prec);
+    switch (m_tabs->currentIndex())
+    {
+    case 0: MantidPreferences::MantidMatrixNumberFormatY(f);
+      MantidPreferences::MantidMatrixNumberPrecisionY(prec);
+      break;
+    case 1: MantidPreferences::MantidMatrixNumberFormatX(f);
+      MantidPreferences::MantidMatrixNumberPrecisionX(prec);
+      break;
+    case 2: MantidPreferences::MantidMatrixNumberFormatE(f);
+      MantidPreferences::MantidMatrixNumberPrecisionE(prec);
+      break;
+    }
+  }
+}
+
+void MantidMatrix::setNumberFormat(int i,const QChar& f,int prec, bool all)
+{
+  (void) all; //Avoid unused warning
+  switch (i)
+  {
+  case 0: m_modelY->setFormat(f,prec);
+    MantidPreferences::MantidMatrixNumberFormatY(f);
+    MantidPreferences::MantidMatrixNumberPrecisionY(prec);
+    break;
+  case 1: m_modelX->setFormat(f,prec);
+    MantidPreferences::MantidMatrixNumberFormatX(f);
+    MantidPreferences::MantidMatrixNumberPrecisionX(prec);
+    break;
+  case 2: m_modelE->setFormat(f,prec);
+    MantidPreferences::MantidMatrixNumberFormatE(f);
+    MantidPreferences::MantidMatrixNumberPrecisionE(prec);
+    break;
+  }
+}
+
+QChar MantidMatrix::numberFormat()
+{
+  return activeModel()->format();
+}
+
+int MantidMatrix::precision()
+{
+  return activeModel()->precision();
+}
+
+
+
+void MantidMatrix::setMatrixProperties()
+{
+  MantidMatrixDialog* dlg = new MantidMatrixDialog(m_appWindow);
+  dlg->setMatrix(this);
+  dlg->exec();
+}
+
+void MantidMatrix::deleteHandle(const std::string& wsName,const boost::shared_ptr<Mantid::API::Workspace> ws)
+{
+  (void) ws; //Avoid unused warning
+  (void) wsName; //Avoid unused warning
+  if (m_workspace.get() == ws.get())
+  {
+    emit needToClose();
+  }
+}
+
+void MantidMatrix::clearADSHandle()
+{
+  emit needToClose();
+}
+
+
+void MantidMatrix::closeMatrix()
+{
+  askOnCloseEvent(false);
+  close();
+}
+
+void MantidMatrix::selfClosed(MdiSubWindow* w)
+{
+  (void) w; //Avoid unused warning
+  closeDependants();
+}
+
+//-------------------------------
+// Python API commands
+//------------------------------
+
+void MantidMatrix::goToTab(const QString & name)
+{
+  if( m_tabs->tabText(m_tabs->currentIndex()) == name ) return;
+
+  if( name == m_YTabLabel )
+  {
+    m_tabs->setCurrentIndex(0);
+  }
+  else if( name == m_XTabLabel )
+  {
+    m_tabs->setCurrentIndex(1);
+  }
+  else if( name == m_ETabLabel )
+  {
+    m_tabs->setCurrentIndex(2);
+  }
+  else return;
+}
+QString MantidMatrix::saveToString(const QString &geometry, bool saveAsTemplate)
+{
+  (void) saveAsTemplate; //Avoid unused warning
+
+  QString s="<mantidmatrix>\n";
+  s+="WorkspaceName\t"+QString::fromStdString(m_strName)+"\n";
+  s+=geometry;
+  s+="</mantidmatrix>\n";
+  return s;
+}
+
+/**  returns the workspace name
+  */
+const std::string & MantidMatrix::getWorkspaceName()
+{return m_strName;
+}
+
+// ----------   MantidMatrixModel   ------------------ //
+
+/**   MantidMatrixModel constructor.
+      @param parent :: Pointer to the parent MantidMatrix
+      @param ws :: Underlying workspace
+      @param rows :: Number of rows in the workspace to be visible via MantidMatrixModel
+      @param cols :: Number of columns (time bins)
+      @param start :: Starting index
+      @param type :: Type of the data to display: Y, X, or E
+  */
+MantidMatrixModel::MantidMatrixModel(QObject *parent,
+                                     Mantid::API::MatrixWorkspace* ws,
+                                     int rows,
+                                     int cols,
+                                     int start,
+                                     Type type):
+QAbstractTableModel(parent),m_type(type),
+m_format('e'),m_prec(6)
+{
+  setup(ws,rows,cols,start);
+}
+
+/// Call this function if the workspace has changed
+void MantidMatrixModel::setup(Mantid::API::MatrixWorkspace* ws,
+                              int rows,
+                              int cols,
+                              int start)
+{
+  m_workspace = ws;
+  m_rows = rows;
+  m_cols = cols;
+  m_startRow = start >= 0? start : 0;
+  if (ws->blocksize() != 0)
+    m_colNumCorr = ws->isHistogramData() ? 1 : 0;
+  else
+    m_colNumCorr = 0;
+}
+
+
+double MantidMatrixModel::data(int row, int col) const
+{
+  double val;
+  if (m_type == X)
+  {
+    val = m_workspace->readX(row + m_startRow)[col];
+  }
+  else if (m_type == Y)
+  {
+    val = m_workspace->readY(row + m_startRow)[col];
+  }
+  else
+  {
+    val = m_workspace->readE(row + m_startRow)[col];
+  }
+  return val;
+}
+
+QVariant MantidMatrixModel::headerData(int section, Qt::Orientation orientation, int role ) const
+{
+  if (role != Qt::DisplayRole) return QVariant();
+  if (orientation == Qt::Vertical && m_workspace->axes() > 1)
+  {
+    Mantid::API::TextAxis* xAxis = dynamic_cast<Mantid::API::TextAxis*>(m_workspace->getAxis(1));
+    if (xAxis)
+    {
+      return QString::fromStdString(xAxis->label(section));
+    }
+  }
+  return section;
+}
+
+Qt::ItemFlags MantidMatrixModel::flags(const QModelIndex & index ) const
+{
+  // MG: For item selection to work correclty in later Qt versions it must be marked as enabled
+  if (index.isValid())
+    return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
+  else
+    return Qt::ItemIsEnabled;
+}
+
+/**
+      @param f :: Number format:  'f' - fixed, 'e' - scientific.
+      @param prec :: New precision (number of digits after the decimal point) with which the data will
+                   be shown in MantidMatrix.
+  */
+void MantidMatrixModel::setFormat(const QChar& f,int prec)
+{
+  QString formats = " ef";
+  if ( formats.indexOf(f) > 0 )
+  {
+    m_format = f.toAscii();
+    m_prec = prec;
+  }
+}
+
+QVariant MantidMatrixModel::data(const QModelIndex &index, int role) const
+{
+  if (role != Qt::DisplayRole) return QVariant();
+  double val = data(index.row(),index.column());
+  return QVariant(m_locale.toString(val,m_format,m_prec));
+}
+
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.h b/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.h
index ac63b7856570ea0236660c390121aa08a858c4a9..50cbcecd45b77e85a1f8fecf9e92ad13d489cb56 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidMatrix.h
@@ -207,8 +207,8 @@ public slots:
 
   //! Returns the bounding rect of the matrix coordinates
   QwtDoubleRect boundingRect();
-  /// Invalidates the bounding rect forcing it to be recalculated
-  void invalidateBoundingRect(){m_boundingRect = QwtDoubleRect();}
+  /// 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);
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidMatrixDialog.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidMatrixDialog.cpp
index 46e99661d7ce791f02d68167150a8f4d34712178..cee6637646789e2b4dec6628f5fce63c466e077e 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidMatrixDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidMatrixDialog.cpp
@@ -1,5 +1,5 @@
 #include "MantidMatrixDialog.h"
-#include "MantidMatrix.h"
+#include "MantidMatrix.h"
 
 #include <QPushButton>
 #include <QLabel>
@@ -78,22 +78,22 @@ void MantidMatrixDialog::showPrecisionBox(int item)
 }
 
 void MantidMatrixDialog::apply()
-{
-    int width = boxColWidth->value();
-    if (d_matrix->columnsWidth() != width){
-        d_matrix->setColumnsWidth(width,false);
-    }
-
-    int prec = boxPrecision->value();
-    QChar format = 'f';
-    QString fmtName = tr("Decimal");
-    if (boxFormat->currentIndex()){
-        format = 'e';
-        fmtName = tr("Scientific");
-    }
-
-   d_matrix->setNumberFormat(format, prec);
-
+{
+    int width = boxColWidth->value();
+    if (d_matrix->columnsWidth() != width){
+        d_matrix->setColumnsWidth(width,false);
+    }
+
+    int prec = boxPrecision->value();
+    QChar format = 'f';
+    QString fmtName = tr("Decimal");
+    if (boxFormat->currentIndex()){
+        format = 'e';
+        fmtName = tr("Scientific");
+    }
+
+   d_matrix->setNumberFormat(format, prec);
+
     double yMin,yMax;
     yMin = editRangeMin->text().toDouble();
     yMax = editRangeMax->text().toDouble();
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp b/Code/Mantid/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp
index a4e91f5b37aef21e1de43c678c5a0225fad50c93..84042afc0479305581dd66b3438b2086c4c4351b 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp
@@ -46,21 +46,21 @@ MantidSampleLogDialog::MantidSampleLogDialog(const QString & wsname, MantidUI* m
   QHBoxLayout *uiLayout = new QHBoxLayout;
   uiLayout->addWidget(m_tree);
 
-  QGroupBox *groupBox = new QGroupBox(tr("Filter log values by"));
-
-  filterNone = new QRadioButton("None");
-  filterStatus = new QRadioButton("Status");
-  filterPeriod = new QRadioButton("Period");
-  filterStatusPeriod = new QRadioButton("Status + Period");
-
-  filterStatusPeriod->setChecked(true);
-
-  QVBoxLayout *vbox = new QVBoxLayout;
-  vbox->addWidget(filterNone);
-  vbox->addWidget(filterStatus);
-  vbox->addWidget(filterPeriod);
-  vbox->addWidget(filterStatusPeriod);
-  //vbox->addStretch(1);
+  QGroupBox *groupBox = new QGroupBox(tr("Filter log values by"));
+
+  filterNone = new QRadioButton("None");
+  filterStatus = new QRadioButton("Status");
+  filterPeriod = new QRadioButton("Period");
+  filterStatusPeriod = new QRadioButton("Status + Period");
+
+  filterStatusPeriod->setChecked(true);
+
+  QVBoxLayout *vbox = new QVBoxLayout;
+  vbox->addWidget(filterNone);
+  vbox->addWidget(filterStatus);
+  vbox->addWidget(filterPeriod);
+  vbox->addWidget(filterStatusPeriod);
+  //vbox->addStretch(1);
   groupBox->setLayout(vbox);
   QHBoxLayout *bottomButtons = new QHBoxLayout;
   
@@ -73,10 +73,10 @@ MantidSampleLogDialog::MantidSampleLogDialog(const QString & wsname, MantidUI* m
   buttonClose->setToolTip("Close dialog");
   bottomButtons->addWidget(buttonClose);
 
-  QVBoxLayout *hbox = new QVBoxLayout;
+  QVBoxLayout *hbox = new QVBoxLayout;
   hbox->addLayout(bottomButtons);
-  hbox->addWidget(groupBox);
-  hbox->addStretch(1);
+  hbox->addWidget(groupBox);
+  hbox->addStretch(1);
      
 
   //Main layout
diff --git a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h
index 10de6d4e144d07932b3b3177c7797c2af08e14a1..b4b43c642e086bebb043aa8fff1b865f8ef4f0cc 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/MantidUI.h
@@ -1,13 +1,13 @@
-#ifndef MANTIDUI_H
-#define MANTIDUI_H
-
+#ifndef MANTIDUI_H
+#define MANTIDUI_H
+
 //----------------------------------
 // Includes
 //----------------------------------
 #include "../ApplicationWindow.h"
 #include "../Graph.h"
 #include "MantidLog.h"
-
+
 #include "MantidAPI/FrameworkManager.h"
 #include "MantidAPI/Algorithm.h"
 #include "MantidAPI/AlgorithmManager.h"
@@ -35,7 +35,7 @@ class MantidDockWidget;
 class AlgorithmDockWidget;
 class AlgorithmMonitor;
 class InstrumentWindow;
-class FitPropertyBrowser;
+class FitPropertyBrowser;
 
 /**
     MantidUI is the extension of QtiPlot's ApplicationWindow which deals with Mantid framework.
@@ -69,42 +69,42 @@ Q_DECLARE_METATYPE(Mantid::API::Workspace_sptr)
 Q_DECLARE_METATYPE(Mantid::API::MatrixWorkspace_sptr)
 Q_DECLARE_METATYPE(std::string)
 
-class MantidUI:public QObject
-{
-
-    Q_OBJECT
-
-public:
-    // Constructor
-    MantidUI(ApplicationWindow *aw);
-
-    // Destructor
-    ~MantidUI();
+class MantidUI:public QObject
+{
+
+    Q_OBJECT
+
+public:
+    // Constructor
+    MantidUI(ApplicationWindow *aw);
+
+    // Destructor
+    ~MantidUI();
 
     //Clear the framework
     void shutdown();
 
     // Save settings to a persistent store
     void saveSettings() const;
-
-    // Initialization
-    void init();
+
+    // Initialization
+    void init();
 
     // Insert relevant items into a menu
     void addMenuItems(QMenu *menu);
-
-    // Pointer to QtiPLot main window
+
+    // Pointer to QtiPLot main window
     ApplicationWindow *appWindow(){return m_appWindow;}
 
     // Release date string formed during scons building
     QString releaseDate();
-
-    // Returns a list of open workspaces
-    QStringList getWorkspaceNames();
-
-    // Returns a list of registered algorithms
-    QStringList getAlgorithmNames();
-
+
+    // Returns a list of open workspaces
+    QStringList getWorkspaceNames();
+
+    // Returns a list of registered algorithms
+    QStringList getAlgorithmNames();
+
     // Create an algorithm using Mantid FrameworkManager
     Mantid::API::IAlgorithm_sptr CreateAlgorithm(const QString& algName);
 
@@ -144,7 +144,7 @@ public:
     MultiLayer *plotSpectrogram(Graph::CurveType type);
 
     /// Create a Table form specified spectra in a MatrixWorkspace
-    Table* createTableFromSpectraList(const QString& tableName, Mantid::API::MatrixWorkspace_sptr workspace, QList<int> indexList, bool errs=true, bool binCentres=false);
+    Table* createTableFromSpectraList(const QString& tableName, Mantid::API::MatrixWorkspace_sptr workspace, QList<int> indexList, bool errs=true, bool binCentres=false);
 
     // Copies selected rows from MantidMatrix to Y and errY columns of a new Table.
     Table* createTableFromSelectedRows(MantidMatrix *m, bool errs = true, bool binCentres=false);
@@ -168,14 +168,14 @@ public:
 
 public slots:
     // Create a 1d graph form specified spectra in a MatrixWorkspace
-    MultiLayer* plotSpectraList(const QString& wsName, const std::set<int>& indexList, bool errs=false);
+    MultiLayer* plotSpectraList(const QString& wsName, const std::set<int>& indexList, bool errs=false);
 
 public:
-    MultiLayer* plotSpectraList(const QMultiMap<QString,int>& toPlot, bool errs=false);
-    /// Draw a color fill plot for each of the listed workspaces
-    void drawColorFillPlots(const QStringList & wsNames, Graph::CurveType curveType = Graph::ColorMap);
-    /// Draw a color fill plot for the named workspace
-    MultiLayer* drawSingleColorFillPlot(const QString & wsName, Graph::CurveType curveType = Graph::ColorMap);
+    MultiLayer* plotSpectraList(const QMultiMap<QString,int>& toPlot, bool errs=false);
+    /// Draw a color fill plot for each of the listed workspaces
+    void drawColorFillPlots(const QStringList & wsNames, Graph::CurveType curveType = Graph::ColorMap);
+    /// Draw a color fill plot for the named workspace
+    MultiLayer* drawSingleColorFillPlot(const QString & wsName, Graph::CurveType curveType = Graph::ColorMap);
 
     // Create a 1d graph form specified spectra in a MatrixWorkspace
     MultiLayer* plotSpectraRange(const QString& wsName, int i0, int i1, bool errs=true);
@@ -187,7 +187,7 @@ public:
     static void setUpBinGraph(MultiLayer* ml, const QString& wsName, Mantid::API::MatrixWorkspace_sptr workspace);
 
     // Copy to a Table Y-values (and Err-values if errs==true) of bins with indeces from i0 to i1 (inclusive) from a workspace
-    Table* createTableFromBins(const QString& wsName, Mantid::API::MatrixWorkspace_sptr workspace, const QList<int>& bins, bool errs=true,int fromRow = -1, int toRow = -1);
+    Table* createTableFromBins(const QString& wsName, Mantid::API::MatrixWorkspace_sptr workspace, const QList<int>& bins, bool errs=true,int fromRow = -1, int toRow = -1);
 
     // Copies selected columns (time bins) in a MantidMatrix to a Table
     Table* createTableFromSelectedColumns(MantidMatrix *m, bool errs);
@@ -215,14 +215,14 @@ public:
   /** ---------------------------------
    * Commands purely for python interaction
    */
-    // The Python API wouldn't accept a multimap as a type so had to resort to this which is still more efficient than
-    // the old merge plots method
-  MultiLayer* pyPlotSpectraList(const QList<QString>& wsnames, const QList<int>& spec_list, bool errs=true); 
+    // The Python API wouldn't accept a multimap as a type so had to resort to this which is still more efficient than
+    // the old merge plots method
+  MultiLayer* pyPlotSpectraList(const QList<QString>& wsnames, const QList<int>& spec_list, bool errs=true); 
   MultiLayer* mergePlots(MultiLayer* g1, MultiLayer* g2);
   MantidMatrix* getMantidMatrix(const QString& wsName);
   MantidMatrix* newMantidMatrix(const QString& name, int start=-1, int end=-1);
-  MultiLayer* plotBin(const QString& wsName, int bin, bool errors = false);
-  bool runAlgorithmAsync_PyCallback(const QString & algName);
+  MultiLayer* plotBin(const QString& wsName, int bin, bool errors = false);
+  bool runAlgorithmAsync_PyCallback(const QString & algName);
   void setIsRunning(bool running);
   bool createPropertyInputDialog(const QString & alg_name, const QString & preset_values,
 				 const QString & optional_msg,  const QString & enabled_names);
@@ -299,7 +299,7 @@ public slots:
     void importWorkspace();
 	// #539: For adding Workspace History display to MantidPlot
 	void showAlgorithmHistory();
-
+
     // Import a workspace wsName
     void importWorkspace(const QString& wsName, bool showDlg = true, bool makeVisible = true);
 
@@ -313,23 +313,23 @@ public slots:
     void createLoadDAEMantidMatrix(const QString&);
 
     // Slots responding to MantidMatrix context menu commands
-    void copyRowToTable();
-    void copyColumnToTable();
-    void copyRowToGraph();
-    void copyColumnToGraph();
-    void copyRowToGraphErr();
-    void copyColumnToGraphErr();
-    void copyDetectorsToTable();
-    void copyValues();
-
-    // Execute selected algorithm
-    void executeAlgorithm();
-    // Execute algorithm given name and version
-    void executeAlgorithm(QString algName, int version = -1);
+    void copyRowToTable();
+    void copyColumnToTable();
+    void copyRowToGraph();
+    void copyColumnToGraph();
+    void copyRowToGraphErr();
+    void copyColumnToGraphErr();
+    void copyDetectorsToTable();
+    void copyValues();
+
+    // Execute selected algorithm
+    void executeAlgorithm();
+    // Execute algorithm given name and version
+    void executeAlgorithm(QString algName, int version = -1);
     //Execute an algorithm with the given parameter list
     void executeAlgorithm(const QString & algName, const QString & paramList);
-    // Find the name of the first input workspace for an algorithm
-    QString findInputWorkspaceProperty(Mantid::API::IAlgorithm_sptr algorithm) const;
+    // Find the name of the first input workspace for an algorithm
+    QString findInputWorkspaceProperty(Mantid::API::IAlgorithm_sptr algorithm) const;
     // Show Qt critical error message box
     void showCritical(const QString&);
     // Show the dialog monitoring currently running algorithms
@@ -370,12 +370,12 @@ public slots:
 	void importStrSeriesLog(const QString &logName, const QString &data);
 	void importNumSeriesLog(const QString &wsName, const QString &logname, int filter);
 
-	// Clear all Mantid related memory
-	void clearAllMemory();
-	void releaseFreeMemory();
-	// Ticket #672
-	void saveNexusWorkspace();
-	QString saveToString(const std::string &workingDir);
+	// Clear all Mantid related memory
+	void clearAllMemory();
+	void releaseFreeMemory();
+	// Ticket #672
+	void saveNexusWorkspace();
+	QString saveToString(const std::string &workingDir);
 
 #ifdef _WIN32
 public:
@@ -385,23 +385,23 @@ public:
 #endif
 
 
-private:
-
+private:
+
 // Create a pointer to the named algorithm and version
     Mantid::API::IAlgorithm_sptr createAlgorithm(const QString& algName, int version);
-    // Execute algorithm asinchronously
-    void executeAlgorithmAsync(Mantid::API::IAlgorithm_sptr alg);
-
-    // Notification handlers and corresponding observers.
+    // Execute algorithm asinchronously
+    void executeAlgorithmAsync(Mantid::API::IAlgorithm_sptr alg);
+
+    // Notification handlers and corresponding observers.
     void handleLoadDAEFinishedNotification(const Poco::AutoPtr<Mantid::API::Algorithm::FinishedNotification>& pNf);
     Poco::NObserver<MantidUI, Mantid::API::Algorithm::FinishedNotification> m_finishedLoadDAEObserver;
-
+
     void handleAddWorkspace(Mantid::API::WorkspaceAddNotification_ptr pNf);
     Poco::NObserver<MantidUI, Mantid::API::WorkspaceAddNotification> m_addObserver;
-
+
     void handleReplaceWorkspace(Mantid::API::WorkspaceAfterReplaceNotification_ptr pNf);
     Poco::NObserver<MantidUI, Mantid::API::WorkspaceAfterReplaceNotification> m_replaceObserver;
-
+
     void handleDeleteWorkspace(Mantid::API::WorkspaceDeleteNotification_ptr pNf);
     Poco::NObserver<MantidUI, Mantid::API::WorkspaceDeleteNotification> m_deleteObserver;
 
@@ -423,11 +423,11 @@ private:
   void handleUnGroupWorkspace(Mantid::API::WorkspaceUnGroupingNotification_ptr pNf);
   Poco::NObserver<MantidUI, Mantid::API::WorkspaceUnGroupingNotification> m_ungroupworkspaceObserver;
 
-	//#678
-    //for savenexus algorithm
-	void executeSaveNexus(QString algName,int version);
-
-    void copyWorkspacestoVector(const QList<QTreeWidgetItem*> &list,std::vector<std::string> &inputWS);
+	//#678
+    //for savenexus algorithm
+	void executeSaveNexus(QString algName,int version);
+
+    void copyWorkspacestoVector(const QList<QTreeWidgetItem*> &list,std::vector<std::string> &inputWS);
 	void PopulateData(Mantid::API::Workspace_sptr ws_ptr,QTreeWidgetItem*  wsid_item);
 
 	/// This method executes LoadRaw/LoadNexus algorithm from ICat interface
@@ -437,37 +437,37 @@ private:
 	 void executeLoadAlgorithm(MantidQt::API::AlgorithmDialog* dlg,Mantid::API::IAlgorithm_sptr alg);
 	
 
-    // Private variables
-
-    ApplicationWindow *m_appWindow;             // QtiPlot main ApplicationWindow
-    MantidDockWidget *m_exploreMantid;          // Dock window for manipulating workspaces
-    AlgorithmDockWidget *m_exploreAlgorithms;   // Dock window for using algorithms
-    FitPropertyBrowser *m_fitFunction;        // Dock window to set fit function properties
-
-    QAction *actionCopyRowToTable;
-    QAction *actionCopyRowToGraph;
-    QAction *actionCopyRowToGraphErr;
-    QAction *actionCopyColumnToTable;
-    QAction *actionCopyColumnToGraph;
-    QAction *actionCopyColumnToGraphErr;
-    QAction *actionToggleMantid;
-    QAction *actionToggleAlgorithms;
-    QAction *actionToggleFitFunction;
-    QAction *actionCopyDetectorsToTable;
-    QAction *actionCopyValues;
-
+    // Private variables
+
+    ApplicationWindow *m_appWindow;             // QtiPlot main ApplicationWindow
+    MantidDockWidget *m_exploreMantid;          // Dock window for manipulating workspaces
+    AlgorithmDockWidget *m_exploreAlgorithms;   // Dock window for using algorithms
+    FitPropertyBrowser *m_fitFunction;        // Dock window to set fit function properties
+
+    QAction *actionCopyRowToTable;
+    QAction *actionCopyRowToGraph;
+    QAction *actionCopyRowToGraphErr;
+    QAction *actionCopyColumnToTable;
+    QAction *actionCopyColumnToGraph;
+    QAction *actionCopyColumnToGraphErr;
+    QAction *actionToggleMantid;
+    QAction *actionToggleAlgorithms;
+    QAction *actionToggleFitFunction;
+    QAction *actionCopyDetectorsToTable;
+    QAction *actionCopyValues;
+
 	  QMenu *mantidMenu;
     QMenu *menuMantidMatrix;             //  MantidMatrix specific menu
-    AlgorithmMonitor *m_algMonitor;      //  Class for monitoring running algorithms
-
-    // Map of <workspace_name,update_interval> pairs. Positive update_intervals mean
-    // UpdateDAE must be launched after LoadDAE for this workspace
-    QMap<std::string,int> m_DAE_map;
-
-    // Stores dependent mdi windows. If the 'key' window closes, all 'value' ones must be closed as well.
-    std::multimap<MdiSubWindow*,MdiSubWindow*> m_mdiDependency;
-
-};
-
+    AlgorithmMonitor *m_algMonitor;      //  Class for monitoring running algorithms
+
+    // Map of <workspace_name,update_interval> pairs. Positive update_intervals mean
+    // UpdateDAE must be launched after LoadDAE for this workspace
+    QMap<std::string,int> m_DAE_map;
+
+    // Stores dependent mdi windows. If the 'key' window closes, all 'value' ones must be closed as well.
+    std::multimap<MdiSubWindow*,MdiSubWindow*> m_mdiDependency;
+
+};
+
 
 #endif
diff --git a/Code/Mantid/MantidPlot/src/Mantid/PeakPickerTool.cpp b/Code/Mantid/MantidPlot/src/Mantid/PeakPickerTool.cpp
index 6dfb3f206931ce52762d24a7c602f51161bf6fcc..aec150ad4cac17960720fbd6495c0ea785b2c991 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/PeakPickerTool.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/PeakPickerTool.cpp
@@ -6,8 +6,8 @@
 #include "PropertyHandler.h"
 
 #include "MantidAPI/CompositeFunction.h"
-#include "MantidAPI/IPeakFunction.h"
-#include "MantidAPI/FunctionFactory.h"
+#include "MantidAPI/IPeakFunction.h"
+#include "MantidAPI/FunctionFactory.h"
 
 #include "qwt_painter.h"
 #include <QPainter>
@@ -15,7 +15,7 @@
 #include <QToolBar>
 #include <QAction>
 #include <QMenu>
-#include <QInputDialog>
+#include <QInputDialog>
 
 #include <iostream>
 
@@ -722,17 +722,17 @@ void PeakPickerTool::prepareContextMenu(QMenu& menu)
  */
 void PeakPickerTool::addPeak()
 {
-  int i = fitBrowser()->registeredPeaks().indexOf(QString::fromStdString(fitBrowser()->defaultPeakType()));
-  bool ok = false;
-  QString fnName = 
-    QInputDialog::getItem(m_mantidUI->appWindow(), "MantidPlot - Fit", "Select peak type", fitBrowser()->registeredPeaks(),i,false,&ok);
-  if (ok)
-  {
-    fitBrowser()->setDefaultPeakType(fnName.toStdString());
-    m_addingPeak = true;
+  int i = fitBrowser()->registeredPeaks().indexOf(QString::fromStdString(fitBrowser()->defaultPeakType()));
+  bool ok = false;
+  QString fnName = 
+    QInputDialog::getItem(m_mantidUI->appWindow(), "MantidPlot - Fit", "Select peak type", fitBrowser()->registeredPeaks(),i,false,&ok);
+  if (ok)
+  {
+    fitBrowser()->setDefaultPeakType(fnName.toStdString());
+    m_addingPeak = true;
     d_graph->plotWidget()->canvas()->setCursor(Qt::CrossCursor);
     setToolTip("Click to add the peak");
-  }
+  }
 }
 
 /**
@@ -773,25 +773,25 @@ void PeakPickerTool::fit()
  */
 void PeakPickerTool::addBackground()
 {
-  bool ok = false;
-  QString fnName = 
-    QInputDialog::getItem(m_mantidUI->appWindow(), 
-         "MantidPlot - Fit", "Select background type", 
-         fitBrowser()->registeredBackgrounds(),
-         fitBrowser()->registeredBackgrounds().indexOf("LinearBackground"),
-         false,&ok);
-  if (ok)
-  {
-    if (fnName == "LinearBackground")
-    {
-      fitBrowser()->setAutoBackgroundName(fnName);
-      fitBrowser()->addAutoBackground();
-    }
-    else
-    {
-      fitBrowser()->addFunction(fnName.toStdString());
-    }
-  }
+  bool ok = false;
+  QString fnName = 
+    QInputDialog::getItem(m_mantidUI->appWindow(), 
+         "MantidPlot - Fit", "Select background type", 
+         fitBrowser()->registeredBackgrounds(),
+         fitBrowser()->registeredBackgrounds().indexOf("LinearBackground"),
+         false,&ok);
+  if (ok)
+  {
+    if (fnName == "LinearBackground")
+    {
+      fitBrowser()->setAutoBackgroundName(fnName);
+      fitBrowser()->addAutoBackground();
+    }
+    else
+    {
+      fitBrowser()->addFunction(fnName.toStdString());
+    }
+  }
 }
 
 /**
@@ -799,16 +799,16 @@ void PeakPickerTool::addBackground()
  */
 void PeakPickerTool::addOther()
 {
-  bool ok = false;
-  QString fnName = 
-    QInputDialog::getItem(m_mantidUI->appWindow(), 
-         "MantidPlot - Fit", "Select function type", 
-         fitBrowser()->registeredOthers(),0,
-         false,&ok);
-  if (ok)
-  {
-    fitBrowser()->addFunction(fnName.toStdString());
-  }
+  bool ok = false;
+  QString fnName = 
+    QInputDialog::getItem(m_mantidUI->appWindow(), 
+         "MantidPlot - Fit", "Select function type", 
+         fitBrowser()->registeredOthers(),0,
+         false,&ok);
+  if (ok)
+  {
+    fitBrowser()->addFunction(fnName.toStdString());
+  }
 }
 
 /**
diff --git a/Code/Mantid/MantidPlot/src/Mantid/Preferences.cpp b/Code/Mantid/MantidPlot/src/Mantid/Preferences.cpp
index 16ed089570daa99e1c3f5db0a91d2e46614bdc45..2077a64664427580a55407a4c22677de06a9abfc 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/Preferences.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/Preferences.cpp
@@ -1,10 +1,10 @@
-#include "Preferences.h"
-#include <QSettings>
-
-//------------------------------------------//
-//           MantidMatrix settings
-//------------------------------------------//
-
+#include "Preferences.h"
+#include <QSettings>
+
+//------------------------------------------//
+//           MantidMatrix settings
+//------------------------------------------//
+
 int MantidPreferences::MantidMatrixColumnWidthY()
 {
     QSettings settings;
diff --git a/Code/Mantid/MantidPlot/src/Mantid/Preferences.h b/Code/Mantid/MantidPlot/src/Mantid/Preferences.h
index 168979cb80e8b7ea85eab9a9c1abc31713f9a316..4fb8bd3ff0033787bf91851b85888430de05ad9a 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/Preferences.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/Preferences.h
@@ -5,34 +5,34 @@
 #include <QMap>
 #include <QList>
 
-/** @class MantidPreferences
-
- Keeps the preferences for some Mantid-related UI settings.
-
- @author Roman Tolchenov, Tessella Support Services plc
- @date 13/02/2009
-
- Copyright &copy; 2007-8 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>.
- Code Documentation is available at: <http://doxygen.mantidproject.org>
- */
-
+/** @class MantidPreferences
+
+ Keeps the preferences for some Mantid-related UI settings.
+
+ @author Roman Tolchenov, Tessella Support Services plc
+ @date 13/02/2009
+
+ Copyright &copy; 2007-8 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>.
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+ */
+
 class MantidPreferences
 {
 public:
diff --git a/Code/Mantid/MantidPlot/src/Mantid/PropertyHandler.cpp b/Code/Mantid/MantidPlot/src/Mantid/PropertyHandler.cpp
index 78053292758e4a6a5a1e8c00fcfab87d4e4ed8c3..6f67a147b827cea4d02cf8b4f7e7083ecccdf60d 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/PropertyHandler.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/PropertyHandler.cpp
@@ -1,1352 +1,1352 @@
-#include "PropertyHandler.h"
-#include "FitPropertyBrowser.h"
-#include "../FunctionCurve.h"
-
-#include "MantidAPI/FunctionFactory.h"
-#include "MantidAPI/IPeakFunction.h"
-#include "MantidAPI/IBackgroundFunction.h"
-#include "MantidAPI/CompositeFunction.h"
-#include "MantidAPI/ParameterTie.h"
-#include "MantidAPI/IConstraint.h"
-#include "MantidAPI/ConstraintFactory.h"
-#include "MantidAPI/AlgorithmManager.h"
-
-#include "qttreepropertybrowser.h"
-#include "qtpropertymanager.h"
-
-#include "../ApplicationWindow.h"
-#include "../Graph.h"
-#include <QMessageBox>
-
-// Visual studio 2010 can't deal with NULL (for a pointer) being passed to the constructor of an std::pair
-// You have to use the c++0x keyword 'nullptr' instead.
-// _MSC_VER=1600 is Visual Studio 2010, so in all other cases I create a define to turn nullptr into NULL
-#if (_MSC_VER!=1600)
-  #ifndef nullptr
-    #define nullptr NULL
-  #endif
-#endif
-
-// Constructor
-PropertyHandler::PropertyHandler(Mantid::API::IFitFunction* fun,
-                Mantid::API::CompositeFunction* parent,
-                FitPropertyBrowser* browser,
-                QtBrowserItem* item)
-                :FitFunctionHandler(fun),m_browser(browser),
-                m_cf(dynamic_cast<Mantid::API::CompositeFunction*>(fun)),
-                m_pf(dynamic_cast<Mantid::API::IPeakFunction*>(fun)),
-                m_if(fun),
-                m_parent(parent),
-                m_type(NULL),
-                m_item(item),
-                m_base(0),
-                m_ci(0),
-                m_curve(NULL)
-{}
-
-/// Destructor
-PropertyHandler::~PropertyHandler()
-{
-}
-
-/// overrides virtual init() which is called from IFitFunction::setHandler(...)
-void PropertyHandler::init()
-{
-  m_browser->m_changeSlotsEnabled = false;
-  if (m_parent == NULL)
-  {// the root composite function
-    m_item = m_browser->m_functionsGroup;
-  }
-  else if (m_item == NULL)
-  {
-    if ( !m_parent->getHandler() )
-    {
-      throw std::runtime_error("Parent function handler does not exist");
-    }
-    //PropertyHandler* ph = parentHandler();
-    QtBrowserItem* pi = parentHandler()->item();
-    // Create group property with function name on it
-    QtProperty* fnProp = m_browser->m_groupManager->addProperty(
-      functionName()
-      );
-    pi->property()->addSubProperty(fnProp);
-    // assign m_item
-    QList<QtBrowserItem *> itList = pi->children();
-    foreach(QtBrowserItem* item,itList)
-    {
-      if (item->property() == fnProp)
-      {
-        m_item = item;
-        break;
-      }
-    }
-    if (m_item == 0) 
-      throw std::runtime_error("Browser item not found");
-
-    if (!m_cf)
-    {
-      m_browser->m_browser->setExpanded(m_item,false);
-    }
-  }
-  else
-  {
-    m_item->property()->setPropertyName(functionName());
-  }
-
-  QtProperty* fnProp = m_item->property();
-
-  // create Type property
-  int itype = m_browser->m_registeredFunctions.indexOf(QString::fromStdString(m_fun->name()));
-  if (!m_type)
-  {
-    m_type = m_browser->m_enumManager->addProperty("Type");
-
-    fnProp->addSubProperty(m_type);
-    if (m_parent)
-    {
-      m_browser->m_enumManager->setEnumNames(m_type, m_browser->m_registeredFunctions);
-    }
-    else
-    {
-      QStringList functionNames;
-      functionNames << QString::fromStdString(m_fun->name());
-      m_browser->m_enumManager->setEnumNames(m_type, functionNames);
-    }
-  }
-  m_browser->m_enumManager->setValue(m_type,itype);
-
-  // create attribute properties
-  initAttributes();
-
-  // create parameter properties
-  initParameters();
-
-  // set handlers for the child functions
-  if (m_cf && m_cf->nFunctions() > 0)
-  {
-    for(int i=0;i<m_cf->nFunctions();i++)
-    {
-      Mantid::API::IFitFunction* f = m_cf->getFunction(i);
-      PropertyHandler* h = new PropertyHandler(f,m_cf,m_browser);
-      f->setHandler(h);
-    }
-  }
-
-  m_browser->m_changeSlotsEnabled = true;
-
-}
-
-/**
- * Attribute visitor to create a QtProperty. Depending on the attribute type
- * the appropriate apply method is used.
- */
-class CreateAttributeProperty: public Mantid::API::IFitFunction::ConstAttributeVisitor<QtProperty*>
-{
-public:
-  CreateAttributeProperty(FitPropertyBrowser* browser,const QString& name)
-    :m_browser(browser),m_name(name){}
-protected:
-  /// Create string property
-  QtProperty* apply(const std::string& str)const
-  {
-    QtProperty* prop = NULL;
-    prop = m_browser->addStringProperty(m_name);
-    m_browser->setStringPropertyValue(prop,QString::fromStdString(str));
-    return prop;
-  }
-  /// Create double property
-  QtProperty* apply(const double& d)const
-  {
-    QtProperty* prop = m_browser->addDoubleProperty(m_name);
-    m_browser->m_doubleManager->setValue(prop,d);
-    return prop;
-  }
-  /// Create int property
-  QtProperty* apply(const int& i)const
-  {
-    QtProperty* prop = m_browser->m_intManager->addProperty(m_name);
-    m_browser->m_intManager->setValue(prop,i);
-    return prop;
-  }
-private:
-  FitPropertyBrowser* m_browser;
-  QString m_name;
-};
-
-void PropertyHandler::initAttributes()
-{
-  std::vector<std::string> attNames = function()->getAttributeNames();
-  for(int i=0;i<m_attributes.size();i++)
-  {
-    m_item->property()->removeSubProperty(m_attributes[i]);
-  }
-  m_attributes.clear();
-  for(size_t i=0;i<attNames.size();i++)
-  {
-    QString aName = QString::fromStdString(attNames[i]);
-    Mantid::API::IFitFunction::Attribute att = function()->getAttribute(attNames[i]);
-    CreateAttributeProperty tmp(m_browser,aName);
-    QtProperty* prop = att.apply(tmp);
-    m_item->property()->addSubProperty(prop);
-    m_attributes << prop;
-  }
-}
-
-void PropertyHandler::initParameters()
-{
-  for(int i=0;i<m_parameters.size();i++)
-  {
-    m_item->property()->removeSubProperty(m_parameters[i]);
-  }
-  m_parameters.clear();
-  for(int i=0;i<function()->nParams();i++)
-  {
-    QString parName = QString::fromStdString(function()->parameterName(i));
-    if (parName.contains('.')) continue;
-    QtProperty* prop = m_browser->addDoubleProperty(parName);
-    m_browser->m_doubleManager->setValue(prop,function()->getParameter(i));
-    m_item->property()->addSubProperty(prop);
-    m_parameters << prop;
-    // add tie property if this parameter has a tie
-    Mantid::API::ParameterTie* tie = m_fun->getTie(i);
-    if (tie)
-    {
-      QStringList qtie = 
-        QString::fromStdString(tie->asString(m_browser->theFunction())).split("=");
-      if (qtie.size() > 1)
-      {
-        QtProperty* tieProp = m_browser->m_stringManager->addProperty("Tie");
-        m_browser->m_stringManager->setValue(tieProp,qtie[1]);
-        prop->addSubProperty(tieProp);
-        m_ties[parName] = tieProp;
-      }
-    }
-    // add constraint properties
-    Mantid::API::IConstraint* c = m_fun->getConstraint(i);
-    if (c)
-    {
-      QStringList qc = QString::fromStdString(c->asString()).split("<");
-      bool lo = false;
-      bool up = false;
-      double loBound, upBound;
-      if (qc.size() == 2)
-      {
-        if (qc[0].contains(parName))
-        {
-          up = true;
-          upBound = qc[1].toDouble();
-        }
-        else
-        {
-          lo = true;
-          loBound = qc[0].toDouble();
-        }
-      }
-      else if (qc.size() == 3)
-      {
-        lo = up = true;
-        loBound = qc[0].toDouble();
-        upBound = qc[2].toDouble();
-      }
-      else
-      {
-        continue;
-      }
-      QtProperty* loProp = NULL;
-      QtProperty* upProp = NULL;
-      if (lo)
-      {
-        loProp = m_browser->addDoubleProperty("LowerBound");
-        m_browser->m_doubleManager->setValue(loProp,loBound);
-        prop->addSubProperty(loProp);
-      }
-      if (up)
-      {
-        upProp = m_browser->addDoubleProperty("UpperBound");
-        m_browser->m_doubleManager->setValue(upProp,upBound);
-        prop->addSubProperty(upProp);
-      }
-      m_constraints.insert(parName,std::pair<QtProperty*,QtProperty*>(loProp,upProp));
-    }
-  }
-}
-
-/**
-  * Add a function to the function handled by this handler.
-  * @param fnName :: A function name or full initialization string
-  *   in the form name=FunctionName,param1=Value,param2=Value,...
-  */
-PropertyHandler* PropertyHandler::addFunction(const std::string& fnName)
-{
-  if (!m_cf) return NULL;
-  m_browser->disableUndo();
-  Mantid::API::IFitFunction* f = 0;
-  // Create new function
-  if (fnName.find("=") == std::string::npos)
-  {// either from name
-    f = Mantid::API::FunctionFactory::Instance().createFunction(fnName);
-  }
-  else
-  {// of from full initialization expression
-    f = Mantid::API::FunctionFactory::Instance().createInitialized(fnName);
-  }
-
-  // turn of the change slots (doubleChanged() etc) to avoid infinite loop
-  m_browser->m_changeSlotsEnabled = false;
-
-  // Check if it's a peak and set its width
-  Mantid::API::IPeakFunction* pf = dynamic_cast<Mantid::API::IPeakFunction*>(f);
-  if (pf)
-  {
-    if (!m_browser->workspaceName().empty() && 
-         m_browser->workspaceIndex() >= 0 &&
-         pf->centre() == 0.)
-    {
-      pf->setCentre( (m_browser->startX() + m_browser->endX())/2 );
-    }
-  }
-
-  Mantid::API::MatrixWorkspace_sptr ws;
-
-  try
-  {
-    ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-      Mantid::API::AnalysisDataService::Instance().retrieve(m_browser->workspaceName()) );
-  }
-  catch(...){}
-
-  int wi = m_browser->workspaceIndex();
-
-  // if it's a LinearBackground estimate its A0 and A1 parameters
-  // from data values at the ends of the fitting interval
-    if (f->name() == "LinearBackground" && !m_browser->workspaceName().empty())
-    {
-      if (ws && wi >= 0 && wi < ws->getNumberHistograms())
-      {
-        const Mantid::MantidVec& X = ws->readX(wi);
-        double istart = 0, iend = 0;
-        for(int i=0; i < static_cast<int>(X.size())-1; ++i)
-        {
-          double x = X[i];
-          if (x < m_browser->startX())
-          {
-            istart = i;
-          }
-          if (x > m_browser->endX())
-          {
-            iend = i;
-            if (iend > 0) iend--;
-            break;
-          }
-        }
-        if (iend > istart)
-        {
-          const Mantid::MantidVec& Y = ws->readY(wi);
-          double p0 = Y[istart];
-          double p1 = Y[iend];
-          double A1 = (p1-p0)/(X[iend]-X[istart]);
-          double A0 = p0 - A1*X[istart];
-          f->setParameter("A0",A0);
-          f->setParameter("A1",A1);
-        }
-      }
-  }
-  if (ws)
-  {
-    m_browser->setWorkspace(f);
-  }
-
-  int nFunctions = m_cf->nFunctions()+1;
-  m_cf->addFunction(f);
-
-  if (m_cf->nFunctions() != nFunctions)
-  {// this may happen
-    m_browser->reset();
-    return NULL;
-  }
-
-  PropertyHandler* h = new PropertyHandler(f,m_cf,m_browser);
-  f->setHandler(h);
-  h->setAttribute("StartX",m_browser->startX());
-  h->setAttribute("EndX",m_browser->endX());
-
-  // enable the change slots
-  m_browser->m_changeSlotsEnabled = true;
-  m_browser->setFitEnabled(true);
-  if (pf)
-  {
-    m_browser->setDefaultPeakType(f->name());
-  }
-  else
-  {
-    m_browser->setDefaultBackgroundType(f->name());
-  }
-  m_browser->setFocus();
-  m_browser->setCurrentFunction(h);
-  return h;
-}
-
-// Removes handled function from its parent function and 
-// properties from the browser
-void PropertyHandler::removeFunction()
-{
-  PropertyHandler* ph = parentHandler();
-  if (ph)
-  {
-    if (this == m_browser->m_autoBackground)
-    {
-      m_browser->m_autoBackground = NULL;
-    }
-    ph->item()->property()->removeSubProperty(m_item->property());
-    Mantid::API::CompositeFunction* cf = ph->cfun();
-    for(int i=0;i<cf->nFunctions();i++)
-    {
-      if (cf->getFunction(i) == function())
-      {
-        removePlot();
-        cf->removeFunction(i);
-        break;
-      }
-    }
-    ph->renameChildren();
-  }
-}
-
-void PropertyHandler::renameChildren()const
-{
-  m_browser->m_changeSlotsEnabled = false;
-  // update tie properties, as the parameter names may change
-  QMap<QString,QtProperty*>::const_iterator it = m_ties.begin();
-  for(;it!=m_ties.end();++it)
-  {
-    QtProperty* prop = it.value();
-    Mantid::API::ParameterTie* tie = 
-      m_fun->getTie(m_fun->parameterIndex(it.key().toStdString()));
-    if (!tie) continue;
-    QStringList qtie = QString::fromStdString(tie->asString()).split("=");
-    if (qtie.size() < 2) continue;
-    m_browser->m_stringManager->setValue(prop,qtie[1]);
-  }
-  if (!m_cf) return;
-  // rename children
-  for(int i=0;i<m_cf->nFunctions();i++)
-  {
-    PropertyHandler* h = getHandler(i);
-    if (!h) continue;
-    QtProperty* nameProp = h->item()->property();
-    nameProp->setPropertyName(h->functionName());
-    h->renameChildren();
-  }
-  m_browser->m_changeSlotsEnabled = true;
-}
-
-/// Creates name for this function to be displayed
-/// in the browser
-QString PropertyHandler::functionName()const
-{
-  QString name = functionPrefix();
-  if (!name.isEmpty())
-  {
-    name += "-";
-  }
-  name += QString::fromStdString(function()->name());
-  return name;
-}
-
-QString PropertyHandler::functionPrefix()const
-{
-  PropertyHandler* ph = parentHandler();
-  if (ph)
-  {
-    int iFun = -1;
-    Mantid::API::CompositeFunction* cf = ph->cfun();
-    for(int i=0;i<cf->nFunctions();i++)
-    {
-      if (cf->getFunction(i) == function())
-      {
-        iFun = i;
-        break;
-      }
-    }
-    QString pref = ph->functionPrefix();
-    if (!pref.isEmpty()) pref += ".";
-    return pref + "f" + QString::number(iFun);
-  }
-  return "";
-}
-
-// Return the parent handler
-PropertyHandler* PropertyHandler::parentHandler()const
-{
-  if (!m_parent) return 0;
-  PropertyHandler* ph = static_cast<PropertyHandler*>(m_parent->getHandler());
-  return ph;
-}
-// Return the child's handler
-PropertyHandler* PropertyHandler::getHandler(int i)const
-{
-  if (!m_cf || i >= m_cf->nFunctions()) return 0;
-  PropertyHandler* ph = static_cast<PropertyHandler*>(m_cf->getFunction(i)->getHandler());
-  return ph;
-}
-/** Returns 'this' if item == m_item and this is a composite function or
-* calls findCompositeFunction recursively with all its children or
-* zero
-*/
-const Mantid::API::CompositeFunction* PropertyHandler::findCompositeFunction(QtBrowserItem* item)const
-{
-  if (!m_cf) return 0;
-  if (item == m_item) return m_cf;
-  for(int i=0;i<m_cf->nFunctions();i++)
-  {
-    const Mantid::API::CompositeFunction* res = getHandler(i)->findCompositeFunction(item);
-    if (res != NULL) return res;
-  }
-  return 0;
-}
-/** Returns 'this' if item == m_item or
-* calls findFunction recursively with all its children or
-* zero
-*/
-const Mantid::API::IFitFunction* PropertyHandler::findFunction(QtBrowserItem* item)const
-{
-  if (item == m_item) return static_cast<const Mantid::API::IFitFunction*>(function());
-  if (!m_cf) return 0;
-  for(int i=0;i<m_cf->nFunctions();i++)
-  {
-    const Mantid::API::IFitFunction* res = getHandler(i)->findFunction(item);
-    if (res != NULL) return res;
-  }
-  return 0;
-}
-
-PropertyHandler* PropertyHandler::findHandler(QtProperty* prop)
-{
-  if (prop == m_item->property()) return this;
-  if (prop == m_type) return this;
-  if (m_attributes.contains(prop)) return this;
-  if (m_parameters.contains(prop)) return this;
-  if (!m_ties.key(prop,"").isEmpty()) return this;
-  QMap<QString,std::pair<QtProperty*,QtProperty*> >::iterator it = m_constraints.begin();
-  for(;it!=m_constraints.end();++it)
-  {
-    if (it.value().first == prop || it.value().second == prop)
-    {
-      return this;
-    }
-  }
-  if (!m_cf) return 0;
-  for(int i=0;i<m_cf->nFunctions();i++)
-  {
-    PropertyHandler* h = getHandler(i)->findHandler(prop);
-    if (h != NULL) return h;
-  }
-  return NULL;
-}
-
-PropertyHandler* PropertyHandler::findHandler(const Mantid::API::IFitFunction* fun)
-{
-  if (fun == function()) return this;
-  if (m_cf)
-  {
-    for(int i=0;i<m_cf->nFunctions();i++)
-    {
-      PropertyHandler* h = getHandler(i)->findHandler(fun);
-      if (h) return h;
-    }
-  }
-  return NULL;
-}
-
-/**
-* Set function parameter value read from a QtProperty
-* @param prop :: The (double) property with the new parameter value
-* @return true if successfull
-*/
-bool PropertyHandler::setParameter(QtProperty* prop)
-{
-  if (m_parameters.contains(prop))
-  {
-    std::string parName = prop->propertyName().toStdString();
-    double parValue = m_browser->m_doubleManager->value(prop);
-    m_fun->setParameter(parName,parValue);
-    m_browser->sendParameterChanged(m_if);
-    return true;
-  }
-  if (m_cf)
-  {
-    for(int i=0;i<m_cf->nFunctions();i++)
-    {
-      bool res = getHandler(i)->setParameter(prop);
-      if (res) return true;
-    }
-  }
-  return false;
-}
-
-/**
- * Visitor setting new attribute value. Depending on the attribute type
- * the appropriate apply method is used.
- */
-class SetAttribute: public Mantid::API::IFitFunction::AttributeVisitor<>
-{
-public:
-  SetAttribute(FitPropertyBrowser* browser,QtProperty* prop)
-    :m_browser(browser),m_prop(prop){}
-protected:
-  /// Create string property
-  void apply(std::string& str)const
-  {
-    QString attName = m_prop->propertyName();
-    str = m_browser->getStringPropertyValue(m_prop).toStdString();
-  }
-  /// Create double property
-  void apply(double& d)const
-  {
-    d = m_browser->m_doubleManager->value(m_prop);
-  }
-  /// Create int property
-  void apply(int& i)const
-  {
-    i = m_browser->m_intManager->value(m_prop);
-  }
-private:
-  FitPropertyBrowser* m_browser;
-  QtProperty* m_prop;
-};
-
-/**
- * Visitor setting new attribute value. Depending on the attribute type
- * the appropriate apply method is used.
- */
-class SetAttributeProperty: public Mantid::API::IFitFunction::ConstAttributeVisitor<>
-{
-public:
-  SetAttributeProperty(FitPropertyBrowser* browser,QtProperty* prop)
-    :m_browser(browser),m_prop(prop){}
-protected:
-  /// Set string property
-  void apply(const std::string& str)const
-  {
-    m_browser->m_changeSlotsEnabled = false;
-    QString attName = m_prop->propertyName();
-    m_browser->setStringPropertyValue(m_prop,QString::fromStdString(str));
-    m_browser->m_changeSlotsEnabled = true;
-  }
-  /// Set double property
-  void apply(const double& d)const
-  {
-    m_browser->m_changeSlotsEnabled = false;
-    m_browser->m_doubleManager->setValue(m_prop,d);
-    m_browser->m_changeSlotsEnabled = true;
-  }
-  /// Set int property
-  void apply(const int& i)const
-  {
-    m_browser->m_changeSlotsEnabled = false;
-    m_browser->m_intManager->setValue(m_prop,i);
-    m_browser->m_changeSlotsEnabled = true;
-  }
-private:
-  FitPropertyBrowser* m_browser;
-  QtProperty* m_prop;
-};
-
-/**
-* Set function attribute value read from a QtProperty
-* @param prop :: The (string) property with the new attribute value
-* @return true if successfull
-*/
-bool PropertyHandler::setAttribute(QtProperty* prop)
-{
-  if (m_attributes.contains(prop))
-  {
-    QString attName = prop->propertyName();
-    try
-    {
-      Mantid::API::IFitFunction::Attribute att = 
-        m_fun->getAttribute(attName.toStdString());
-      SetAttribute tmp(m_browser,prop);
-      att.apply(tmp);
-      m_fun->setAttribute(attName.toStdString(),att);
-      m_browser->compositeFunction()->checkFunction();
-      initParameters();
-      if (this == m_browser->m_autoBackground)
-      {
-        fit();
-      }
-    }
-    catch(std::exception& e)
-    {
-      QMessageBox::critical(m_browser->m_appWindow,"Mantid - Error",e.what());
-      return false;
-    }
-    return true;
-  }
-  if (m_cf)
-  {
-    for(int i=0;i<m_cf->nFunctions();i++)
-    {
-      bool res = getHandler(i)->setAttribute(prop);
-      if (res) return true;
-    }
-  }
-  return false;
-}
-
-void PropertyHandler::setAttribute(const QString& attName, const double& attValue)
-{
-  if (m_fun->hasAttribute(attName.toStdString()))
-  {
-    try
-    {
-      m_fun->setAttribute(attName.toStdString(),Mantid::API::IFitFunction::Attribute(attValue));
-      m_browser->compositeFunction()->checkFunction();
-      foreach(QtProperty* prop,m_attributes)
-      {
-        if (prop->propertyName() == attName)
-        {
-          m_browser->m_changeSlotsEnabled = false;
-          m_browser->m_doubleManager->setValue(prop,attValue);
-          m_browser->m_changeSlotsEnabled = true;
-        }
-      }
-    }
-    catch(...){}
-  }
-  if (cfun())
-  {
-    for(int i=0;i<cfun()->nFunctions();++i)
-    {
-      PropertyHandler* h = getHandler(i);
-      h->setAttribute(attName,attValue);
-    }
-  }
-}
-
-
-
-void PropertyHandler::setAttribute(const QString& attName, const QString& attValue)
-{
-  const std::string name = attName.toStdString();
-  if (m_fun->hasAttribute(name))
-  {
-    Mantid::API::IFitFunction::Attribute att = m_fun->getAttribute(name);
-    att.fromString(attValue.toStdString());
-    m_fun->setAttribute(name,att);
-    m_browser->compositeFunction()->checkFunction();
-    foreach(QtProperty* prop,m_attributes)
-    {
-      if (prop->propertyName() == attName)
-      {
-        SetAttributeProperty tmp(m_browser,prop);
-        att.apply(tmp);
-      }
-    }
-    initParameters();
-  }
-}
-
-/**
-* Update the parameter properties
-*/
-void PropertyHandler::updateParameters()
-{
-  for(int i=0;i<m_parameters.size();i++)
-  {
-    QtProperty* prop = m_parameters[i];
-    std::string parName = prop->propertyName().toStdString();
-    double parValue = function()->getParameter(parName);
-    m_browser->m_doubleManager->setValue(prop,parValue);
-  }
-  if (m_cf)
-  {
-    for(int i=0;i<m_cf->nFunctions();i++)
-    {
-      getHandler(i)->updateParameters();
-    }
-  }
-}
-
-/**
-* Change the type of the function (replace the function)
-* @param prop :: The "Type" property with new value
-* @param fnName :: New function name (type) or full initialization expression
-*/
-Mantid::API::IFitFunction* PropertyHandler::changeType(QtProperty* prop)
-{
-  if (prop == m_type)
-  {
-    if (!m_parent) return m_browser->compositeFunction();// dont replace the root composite function
-
-    // Create new function
-    int i = m_browser->m_enumManager->value(prop);
-    const QString& fnName = m_browser->m_registeredFunctions[i];
-    Mantid::API::IFitFunction* f = NULL;
-    try
-    {
-      f = Mantid::API::FunctionFactory::Instance().
-        createFunction(fnName.toStdString());
-    }
-    catch(std::exception& e)
-    {
-      QMessageBox::critical(NULL,"Mantid - Error","Cannot create function "+fnName+
-        "\n"+e.what());
-      return NULL;
-    }
-
-    // turn of the change slots (doubleChanged() etc) to avoid infinite loop
-    m_browser->m_changeSlotsEnabled = false;
-
-    // Check if it's a peak and set its width
-    Mantid::API::IPeakFunction* pf = dynamic_cast<Mantid::API::IPeakFunction*>(f);
-    if (pf)
-    {
-      if (!m_pf)
-      {
-        if (!m_browser->workspaceName().empty() && m_browser->workspaceIndex() >= 0)
-        {
-          pf->setCentre( (m_browser->startX() + m_browser->endX())/2 );
-        }
-      }
-      else
-      {
-        pf->setCentre(m_pf->centre());
-        pf->setHeight(m_pf->height());
-        pf->setWidth(m_pf->width());
-      }
-    }
-
-    if (pf)
-    {
-      m_browser->setDefaultPeakType(fnName.toStdString());
-    }
-    else
-    {
-      m_browser->setDefaultBackgroundType(fnName.toStdString());
-    }
-
-    QList<QtProperty*> subs = m_item->property()->subProperties();
-    foreach(QtProperty* sub, subs)
-    {
-      m_item->property()->removeSubProperty(sub);
-    }
-
-    m_browser->m_changeSlotsEnabled = true;
-
-    removePlot();
-
-    const Mantid::API::IFitFunction* f_old = static_cast<const Mantid::API::IFitFunction*>(function());
-    PropertyHandler* h = new PropertyHandler(f,m_parent,m_browser,m_item);
-    if (this == m_browser->m_autoBackground)
-    {
-      if (dynamic_cast<Mantid::API::IBackgroundFunction*>(f))
-      {
-        m_browser->m_autoBackground = h;
-        h->fit();
-      }
-      else
-      {
-        m_browser->m_autoBackground = NULL;
-      }
-    }
-    m_parent->replaceFunction(f_old,f);
-    f->setHandler(h);
-    // calculate the baseline
-    if (h->pfun())
-    {
-      h->setCentre(h->centre()); // this sets m_ci
-      h->calcBase();
-    }
-    // at this point this handler does not exist any more. only return is possible
-    return f;
-
-  }
-  else if (m_cf)
-  {
-    for(int i=0;i<m_cf->nFunctions();i++)
-    {
-      Mantid::API::IFitFunction* f = getHandler(i)->changeType(prop);
-      if (f) return f;
-    }
-  }
-  return NULL;
-}
-
-bool PropertyHandler::isParameter(QtProperty* prop)
-{
-  return m_parameters.contains(prop);
-}
-
-QtProperty* PropertyHandler::getParameterProperty(const QString& parName)const
-{
-  foreach(QtProperty* parProp,m_parameters)
-  {
-    if (parProp->propertyName() == parName)
-    {
-      return parProp;
-    }
-  }
-  return NULL;
-}
-
-QtProperty* PropertyHandler::getParameterProperty(QtProperty* prop)const
-{
-  foreach(QtProperty* parProp,m_parameters)
-  {
-    QList<QtProperty*> subs = parProp->subProperties();
-    if (subs.contains(prop))
-    {
-      return parProp;
-    }
-  }
-  return NULL;
-}
-
-void PropertyHandler::addTie(const QString& tieStr)
-{
-  QStringList parts = tieStr.split("=");
-  if (parts.size() != 2) return;
-  std::string name = parts[0].trimmed().toStdString();
-  std::string expr = parts[1].trimmed().toStdString();
-  try
-  {
-    Mantid::API::ParameterTie* tie = 
-      m_browser->compositeFunction()->tie(name,expr);
-    if (tie == NULL) return;
-    QString parName = QString::fromStdString(
-      tie->getFunction()->parameterName(tie->getIndex())
-     );
-    foreach(QtProperty* parProp,m_parameters)
-    {
-      if (parProp->propertyName() == parName)
-      {
-        m_browser->m_changeSlotsEnabled = false;
-        QtProperty* tieProp = m_ties[parName];
-        if (!tieProp)
-        {
-          tieProp = m_browser->m_stringManager->addProperty( "Tie" );
-          m_ties[parName] = tieProp;
-        }
-        m_browser->m_stringManager->setValue(tieProp,QString::fromStdString(expr));
-        m_browser->m_changeSlotsEnabled = true;
-        parProp->addSubProperty(tieProp);
-        return;
-      }
-    }
-  }
-  catch(...){}
-}
-
-void PropertyHandler::fix(const QString& parName)
-{
-  QtProperty* parProp = getParameterProperty(parName);
-  if (!parProp) return;
-  QString parValue = QString::number(m_browser->m_doubleManager->value(parProp));
-  try
-  {
-    m_fun->tie(parName.toStdString(),parValue.toStdString());
-    m_browser->m_changeSlotsEnabled = false;
-    QtProperty* tieProp = m_ties[parName];
-    if (!tieProp)
-    {
-      tieProp = m_browser->m_stringManager->addProperty( "Tie" );
-      m_ties[parName] = tieProp;
-    }
-    m_browser->m_stringManager->setValue(tieProp,parValue);
-    m_browser->m_changeSlotsEnabled = true;
-    parProp->addSubProperty(tieProp);
-    parProp->setEnabled(false);
-    tieProp->setEnabled(false);
-  }
-  catch(...){}
-
-}
-
-/**
- * Remove the tie.
- * @param prop :: The tie property to remove
- */
-void PropertyHandler::removeTie(QtProperty* prop)
-{
-  QString parName = m_ties.key(prop,"");
-  if (parName.isEmpty()) return;
-  
-  QtProperty* parProp = getParameterProperty(parName);
-  if (parProp)
-  {
-    m_browser->m_changeSlotsEnabled = false;
-    m_fun->removeTie(parName.toStdString());
-    parProp->removeSubProperty(prop);
-    m_ties.remove(parName);
-    m_browser->m_changeSlotsEnabled = true;
-    parProp->setEnabled(true);
-  }
-}
-
-/**
- * Remove the tie.
- * @param parName :: The name of the parameter
- */
-void PropertyHandler::removeTie(const QString& parName)
-{
-  QtProperty* prop = m_ties[parName];
-  if (prop) removeTie(prop);
-}
-
-void PropertyHandler::calcBase()
-{
-  if (!m_browser->m_autoBackground) return;
-  Mantid::API::IFunctionMW* fMW = dynamic_cast<Mantid::API::IFunctionMW*>(m_if);
-  if (!fMW) return;
-  Mantid::API::MatrixWorkspace_const_sptr ws = fMW->getMatrixWorkspace();
-  if (ws)
-  {
-    int wi = fMW->getWorkspaceIndex();
-    const Mantid::MantidVec& X = ws->readX(wi);
-    const Mantid::MantidVec& Y = ws->readY(wi);
-    int n = Y.size() - 1;
-    if (m_ci < 0 || m_ci > n || !m_browser->m_autoBackground)
-    {
-      m_base = 0.;
-    }
-    else
-    {
-      double x = X[m_ci];
-      double y = 0;
-      dynamic_cast<const Mantid::API::IFunctionMW*>(m_browser->m_autoBackground->function())->function(&y,&x,1);
-      m_base = y;
-    }
-  }
-  else
-  {
-    m_base = 0.;
-  }
-}
-
-void PropertyHandler::calcBaseAll()
-{
-  if (!m_browser->m_autoBackground) return;
-  if (!m_cf) return;
-  for(int i=0;i<m_cf->nFunctions();++i)
-  {
-    PropertyHandler* h = getHandler(i);
-    if (h->pfun())
-    {
-      h->calcBase();
-    }
-    else if (h->cfun())
-    {
-      h->calcBaseAll();
-    }
-  }
-}
-
-void PropertyHandler::setHeight(const double& h)
-{
-  if (m_pf)
-  {
-    m_pf->setHeight(h - m_base);
-  }
-}
-
-void PropertyHandler::setCentre(const double& c)
-{
-  if (m_pf)
-  {
-    m_pf->setCentre(c);
-    Mantid::API::MatrixWorkspace_const_sptr ws = m_pf->getMatrixWorkspace();
-    if (ws)
-    {
-      int wi = m_pf->getWorkspaceIndex();
-      const Mantid::MantidVec& X = ws->readX(wi);
-      int n = X.size() - 2;
-      if (m_ci < 0) m_ci = 0;
-      if (m_ci > n) m_ci = n;
-      double x = X[m_ci];
-      if (x < c)
-      {
-        for(;m_ci<=n;++m_ci)
-        {
-          x = X[m_ci];
-          if (x > c) break;
-        }
-      }
-      else
-      {
-        for(;m_ci>=0;--m_ci)
-        {
-          x = X[m_ci];
-          if (x < c) break;
-        }
-      }
-    }
-  }
-}
-
-void PropertyHandler::setWidth(const double& w)
-{
-  if (m_pf)
-  {
-    m_pf->setWidth(w);
-  }
-}
-
-double PropertyHandler::height()const
-{
-  if (m_pf)
-  {
-    return m_pf->height();
-  }
-  return 0;
-}
-
-double PropertyHandler::centre()const
-{
-  if (m_pf)
-  {
-    return m_pf->centre();
-  }
-  return (m_browser->endX() + m_browser->startX())/2;
-}
-
-double PropertyHandler::width()const
-{
-  if (m_pf)
-  {
-    return m_pf->width();
-  }
-  return 0;
-}
-
-/**
- * Add constraint to parameter property parProp
- */
-void PropertyHandler::addConstraint(QtProperty* parProp,bool lo,bool up,double loBound,double upBound)
-{
-  QMap<QString,std::pair<QtProperty*,QtProperty*> >::iterator old = 
-    m_constraints.find(parProp->propertyName());
-
-  bool hasLo = false;
-  bool hasUp = false;
-
-  if (old != m_constraints.end())
-  {
-    hasLo = old.value().first != NULL;
-    hasUp = old.value().second != NULL;
-    if (hasLo && !lo)
-    {
-      lo = true;
-      loBound = m_browser->m_doubleManager->value(old.value().first);
-    }
-    if (hasUp && !up)
-    {
-      up = true;
-      upBound = m_browser->m_doubleManager->value(old.value().second);
-    }
-  }
-
-  m_browser->m_changeSlotsEnabled = false;
-  std::pair<QtProperty*,QtProperty*> cnew(nullptr,nullptr);
-  std::ostringstream ostr;
-  if (lo) 
-  {
-    ostr << loBound << "<";
-    if (!hasLo)
-    {
-      cnew.first = m_browser->addDoubleProperty("LowerBound");
-      parProp->addSubProperty(cnew.first);
-    }
-    else
-    {
-      cnew.first = old.value().first;
-    }
-    m_browser->m_doubleManager->setValue(cnew.first,loBound);
-  }
-  ostr << parProp->propertyName().toStdString();
-  if (up)
-  {
-    ostr << "<" << upBound;
-    if (!hasUp)
-    {
-      cnew.second = m_browser->addDoubleProperty("UpperBound");
-      parProp->addSubProperty(cnew.second);
-    }
-    else
-    {
-      cnew.second = old.value().second;
-    }
-    m_browser->m_doubleManager->setValue(cnew.second,upBound);
-  }
-
-  if (old != m_constraints.end())
-  {
-    m_constraints.erase(old);
-  }
-
-  m_constraints.insert(parProp->propertyName(),cnew);
-
-  Mantid::API::IConstraint* c = 
-    Mantid::API::ConstraintFactory::Instance().createInitialized(m_fun,ostr.str());
-  m_fun->addConstraint(c);
-  m_browser->m_changeSlotsEnabled = true;
-}
-
-void PropertyHandler::removeConstraint(QtProperty* parProp)
-{
-  QMap<QString,std::pair<QtProperty*,QtProperty*> >::iterator it = 
-    m_constraints.find(parProp->propertyName());
-
-  if (it != m_constraints.end())
-  {
-    if (it.value().first)
-    {
-      parProp->removeSubProperty(it.value().first);
-    }
-    if (it.value().second)
-    {
-      parProp->removeSubProperty(it.value().second);
-    }
-    m_fun->removeConstraint(parProp->propertyName().toStdString());
-  }
-  m_constraints.clear();
-}
-
-/**
- * Make a list of all peaks in this function
- */
-QList<PropertyHandler*> PropertyHandler::getPeakList()
-{
-  QList<PropertyHandler*> res;
-  if (m_pf)
-  {
-    res << this;
-  }
-  if (m_cf)
-  {
-    for(int i=0;i<m_cf->nFunctions();++i)
-    {
-      PropertyHandler* h = getHandler(i);
-      if ( !h )  continue;
-      if (h->pfun())
-      {
-        res << h;
-      }
-      else if (h->cfun())
-      {
-        res << h->getPeakList();
-      }
-    }
-  }
-  return res;
-}
-
-/**
- * Plot this function on a graph
- * @param g :: The graph to plot on
- */
-void PropertyHandler::plot(Graph* g)const
-{
-  if (!m_curve)
-  {
-    m_curve = new FunctionCurve(
-      m_if,
-      QString::fromStdString(m_browser->m_groupMember),//m_browser->workspaceName()),
-      m_browser->workspaceIndex(),
-      functionName());
-    m_curve->setRange(m_browser->startX(),m_browser->endX());
-    m_curve->loadData();
-    // Graph now owns m_curve. Use m_curve->removeMe() to remove (and delete) from Graph
-    g->insertCurve(m_curve);
-    connect(m_curve,SIGNAL(forgetMe(PlotCurve*)),this,SLOT(plotRemoved(PlotCurve*)));
-    if (this == m_browser->getHandler())
-    {
-      m_browser->m_btnPlotGuess->setText("Remove guess");
-    }
-  }
-}
-
-/**
- * Remove this function curve from its graph
- */
-void PropertyHandler::removePlot()
-{
-  if (m_curve)
-  {
-    m_curve->removeMe();
-    m_curve = NULL;
-    if (this == m_browser->getHandler())
-    {
-      m_browser->m_btnPlotGuess->setText("Plot guess");
-    }
-  }
-}
-
-/**
- * Remove the reference to the function curve as it has been deleted
- */
-void PropertyHandler::plotRemoved(PlotCurve* c)
-{
-  if (c == dynamic_cast<PlotCurve*>(m_curve))
-  {
-    m_curve = NULL;
-  }
-}
-
-/**
- * Replot function curve when parameters have been changed
- */
-void PropertyHandler::replot()const
-{
-  if (m_curve)
-  {
-    QStringList formulas = m_curve->formulas();
-    formulas[1] = QString::fromStdString(*m_fun);
-    m_curve->setFormulas(formulas);
-    m_curve->loadData();
-  }
-}
-
-/**
- * Remove all plots including children's
- */
-void PropertyHandler::removeAllPlots()
-{
-  removePlot();
-  if (m_cf)
-  {
-    for(int i=0;i<m_cf->nFunctions();++i)
-    {
-      getHandler(i)->removeAllPlots();
-    }
-  }
-}
-
-void PropertyHandler::fit()
-{
-  try
-  {
-    if (m_browser->workspaceName().empty()) return;
-
-    Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("Fit");
-    alg->initialize();
-    alg->setPropertyValue("InputWorkspace",m_browser->workspaceName());
-    alg->setProperty("WorkspaceIndex",m_browser->workspaceIndex());
-    alg->setProperty("StartX",m_browser->startX());
-    alg->setProperty("EndX",m_browser->endX());
-    alg->setPropertyValue("Function",*m_fun);
-    alg->execute();
-    std::string fitFun = alg->getPropertyValue("Function");
-    Mantid::API::IFitFunction* f = Mantid::API::FunctionFactory::Instance().createInitialized(fitFun);
-    for(int i=0;i<f->nParams();++i)
-    {
-      m_fun->setParameter(i,f->getParameter(i));
-    }
-    delete f;
-    m_browser->getHandler()->calcBaseAll();
-    updateParameters();
-  }
-  catch(...)
-  {
-  }
-}
+#include "PropertyHandler.h"
+#include "FitPropertyBrowser.h"
+#include "../FunctionCurve.h"
+
+#include "MantidAPI/FunctionFactory.h"
+#include "MantidAPI/IPeakFunction.h"
+#include "MantidAPI/IBackgroundFunction.h"
+#include "MantidAPI/CompositeFunction.h"
+#include "MantidAPI/ParameterTie.h"
+#include "MantidAPI/IConstraint.h"
+#include "MantidAPI/ConstraintFactory.h"
+#include "MantidAPI/AlgorithmManager.h"
+
+#include "qttreepropertybrowser.h"
+#include "qtpropertymanager.h"
+
+#include "../ApplicationWindow.h"
+#include "../Graph.h"
+#include <QMessageBox>
+
+// Visual studio 2010 can't deal with NULL (for a pointer) being passed to the constructor of an std::pair
+// You have to use the c++0x keyword 'nullptr' instead.
+// _MSC_VER=1600 is Visual Studio 2010, so in all other cases I create a define to turn nullptr into NULL
+#if (_MSC_VER!=1600)
+  #ifndef nullptr
+    #define nullptr NULL
+  #endif
+#endif
+
+// Constructor
+PropertyHandler::PropertyHandler(Mantid::API::IFitFunction* fun,
+                Mantid::API::CompositeFunction* parent,
+                FitPropertyBrowser* browser,
+                QtBrowserItem* item)
+                :FitFunctionHandler(fun),m_browser(browser),
+                m_cf(dynamic_cast<Mantid::API::CompositeFunction*>(fun)),
+                m_pf(dynamic_cast<Mantid::API::IPeakFunction*>(fun)),
+                m_if(fun),
+                m_parent(parent),
+                m_type(NULL),
+                m_item(item),
+                m_base(0),
+                m_ci(0),
+                m_curve(NULL)
+{}
+
+/// Destructor
+PropertyHandler::~PropertyHandler()
+{
+}
+
+/// overrides virtual init() which is called from IFitFunction::setHandler(...)
+void PropertyHandler::init()
+{
+  m_browser->m_changeSlotsEnabled = false;
+  if (m_parent == NULL)
+  {// the root composite function
+    m_item = m_browser->m_functionsGroup;
+  }
+  else if (m_item == NULL)
+  {
+    if ( !m_parent->getHandler() )
+    {
+      throw std::runtime_error("Parent function handler does not exist");
+    }
+    //PropertyHandler* ph = parentHandler();
+    QtBrowserItem* pi = parentHandler()->item();
+    // Create group property with function name on it
+    QtProperty* fnProp = m_browser->m_groupManager->addProperty(
+      functionName()
+      );
+    pi->property()->addSubProperty(fnProp);
+    // assign m_item
+    QList<QtBrowserItem *> itList = pi->children();
+    foreach(QtBrowserItem* item,itList)
+    {
+      if (item->property() == fnProp)
+      {
+        m_item = item;
+        break;
+      }
+    }
+    if (m_item == 0) 
+      throw std::runtime_error("Browser item not found");
+
+    if (!m_cf)
+    {
+      m_browser->m_browser->setExpanded(m_item,false);
+    }
+  }
+  else
+  {
+    m_item->property()->setPropertyName(functionName());
+  }
+
+  QtProperty* fnProp = m_item->property();
+
+  // create Type property
+  int itype = m_browser->m_registeredFunctions.indexOf(QString::fromStdString(m_fun->name()));
+  if (!m_type)
+  {
+    m_type = m_browser->m_enumManager->addProperty("Type");
+
+    fnProp->addSubProperty(m_type);
+    if (m_parent)
+    {
+      m_browser->m_enumManager->setEnumNames(m_type, m_browser->m_registeredFunctions);
+    }
+    else
+    {
+      QStringList functionNames;
+      functionNames << QString::fromStdString(m_fun->name());
+      m_browser->m_enumManager->setEnumNames(m_type, functionNames);
+    }
+  }
+  m_browser->m_enumManager->setValue(m_type,itype);
+
+  // create attribute properties
+  initAttributes();
+
+  // create parameter properties
+  initParameters();
+
+  // set handlers for the child functions
+  if (m_cf && m_cf->nFunctions() > 0)
+  {
+    for(int i=0;i<m_cf->nFunctions();i++)
+    {
+      Mantid::API::IFitFunction* f = m_cf->getFunction(i);
+      PropertyHandler* h = new PropertyHandler(f,m_cf,m_browser);
+      f->setHandler(h);
+    }
+  }
+
+  m_browser->m_changeSlotsEnabled = true;
+
+}
+
+/**
+ * Attribute visitor to create a QtProperty. Depending on the attribute type
+ * the appropriate apply method is used.
+ */
+class CreateAttributeProperty: public Mantid::API::IFitFunction::ConstAttributeVisitor<QtProperty*>
+{
+public:
+  CreateAttributeProperty(FitPropertyBrowser* browser,const QString& name)
+    :m_browser(browser),m_name(name){}
+protected:
+  /// Create string property
+  QtProperty* apply(const std::string& str)const
+  {
+    QtProperty* prop = NULL;
+    prop = m_browser->addStringProperty(m_name);
+    m_browser->setStringPropertyValue(prop,QString::fromStdString(str));
+    return prop;
+  }
+  /// Create double property
+  QtProperty* apply(const double& d)const
+  {
+    QtProperty* prop = m_browser->addDoubleProperty(m_name);
+    m_browser->m_doubleManager->setValue(prop,d);
+    return prop;
+  }
+  /// Create int property
+  QtProperty* apply(const int& i)const
+  {
+    QtProperty* prop = m_browser->m_intManager->addProperty(m_name);
+    m_browser->m_intManager->setValue(prop,i);
+    return prop;
+  }
+private:
+  FitPropertyBrowser* m_browser;
+  QString m_name;
+};
+
+void PropertyHandler::initAttributes()
+{
+  std::vector<std::string> attNames = function()->getAttributeNames();
+  for(int i=0;i<m_attributes.size();i++)
+  {
+    m_item->property()->removeSubProperty(m_attributes[i]);
+  }
+  m_attributes.clear();
+  for(size_t i=0;i<attNames.size();i++)
+  {
+    QString aName = QString::fromStdString(attNames[i]);
+    Mantid::API::IFitFunction::Attribute att = function()->getAttribute(attNames[i]);
+    CreateAttributeProperty tmp(m_browser,aName);
+    QtProperty* prop = att.apply(tmp);
+    m_item->property()->addSubProperty(prop);
+    m_attributes << prop;
+  }
+}
+
+void PropertyHandler::initParameters()
+{
+  for(int i=0;i<m_parameters.size();i++)
+  {
+    m_item->property()->removeSubProperty(m_parameters[i]);
+  }
+  m_parameters.clear();
+  for(int i=0;i<function()->nParams();i++)
+  {
+    QString parName = QString::fromStdString(function()->parameterName(i));
+    if (parName.contains('.')) continue;
+    QtProperty* prop = m_browser->addDoubleProperty(parName);
+    m_browser->m_doubleManager->setValue(prop,function()->getParameter(i));
+    m_item->property()->addSubProperty(prop);
+    m_parameters << prop;
+    // add tie property if this parameter has a tie
+    Mantid::API::ParameterTie* tie = m_fun->getTie(i);
+    if (tie)
+    {
+      QStringList qtie = 
+        QString::fromStdString(tie->asString(m_browser->theFunction())).split("=");
+      if (qtie.size() > 1)
+      {
+        QtProperty* tieProp = m_browser->m_stringManager->addProperty("Tie");
+        m_browser->m_stringManager->setValue(tieProp,qtie[1]);
+        prop->addSubProperty(tieProp);
+        m_ties[parName] = tieProp;
+      }
+    }
+    // add constraint properties
+    Mantid::API::IConstraint* c = m_fun->getConstraint(i);
+    if (c)
+    {
+      QStringList qc = QString::fromStdString(c->asString()).split("<");
+      bool lo = false;
+      bool up = false;
+      double loBound, upBound;
+      if (qc.size() == 2)
+      {
+        if (qc[0].contains(parName))
+        {
+          up = true;
+          upBound = qc[1].toDouble();
+        }
+        else
+        {
+          lo = true;
+          loBound = qc[0].toDouble();
+        }
+      }
+      else if (qc.size() == 3)
+      {
+        lo = up = true;
+        loBound = qc[0].toDouble();
+        upBound = qc[2].toDouble();
+      }
+      else
+      {
+        continue;
+      }
+      QtProperty* loProp = NULL;
+      QtProperty* upProp = NULL;
+      if (lo)
+      {
+        loProp = m_browser->addDoubleProperty("LowerBound");
+        m_browser->m_doubleManager->setValue(loProp,loBound);
+        prop->addSubProperty(loProp);
+      }
+      if (up)
+      {
+        upProp = m_browser->addDoubleProperty("UpperBound");
+        m_browser->m_doubleManager->setValue(upProp,upBound);
+        prop->addSubProperty(upProp);
+      }
+      m_constraints.insert(parName,std::pair<QtProperty*,QtProperty*>(loProp,upProp));
+    }
+  }
+}
+
+/**
+  * Add a function to the function handled by this handler.
+  * @param fnName :: A function name or full initialization string
+  *   in the form name=FunctionName,param1=Value,param2=Value,...
+  */
+PropertyHandler* PropertyHandler::addFunction(const std::string& fnName)
+{
+  if (!m_cf) return NULL;
+  m_browser->disableUndo();
+  Mantid::API::IFitFunction* f = 0;
+  // Create new function
+  if (fnName.find("=") == std::string::npos)
+  {// either from name
+    f = Mantid::API::FunctionFactory::Instance().createFunction(fnName);
+  }
+  else
+  {// of from full initialization expression
+    f = Mantid::API::FunctionFactory::Instance().createInitialized(fnName);
+  }
+
+  // turn of the change slots (doubleChanged() etc) to avoid infinite loop
+  m_browser->m_changeSlotsEnabled = false;
+
+  // Check if it's a peak and set its width
+  Mantid::API::IPeakFunction* pf = dynamic_cast<Mantid::API::IPeakFunction*>(f);
+  if (pf)
+  {
+    if (!m_browser->workspaceName().empty() && 
+         m_browser->workspaceIndex() >= 0 &&
+         pf->centre() == 0.)
+    {
+      pf->setCentre( (m_browser->startX() + m_browser->endX())/2 );
+    }
+  }
+
+  Mantid::API::MatrixWorkspace_sptr ws;
+
+  try
+  {
+    ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+      Mantid::API::AnalysisDataService::Instance().retrieve(m_browser->workspaceName()) );
+  }
+  catch(...){}
+
+  int wi = m_browser->workspaceIndex();
+
+  // if it's a LinearBackground estimate its A0 and A1 parameters
+  // from data values at the ends of the fitting interval
+    if (f->name() == "LinearBackground" && !m_browser->workspaceName().empty())
+    {
+      if (ws && wi >= 0 && wi < ws->getNumberHistograms())
+      {
+        const Mantid::MantidVec& X = ws->readX(wi);
+        double istart = 0, iend = 0;
+        for(int i=0; i < static_cast<int>(X.size())-1; ++i)
+        {
+          double x = X[i];
+          if (x < m_browser->startX())
+          {
+            istart = i;
+          }
+          if (x > m_browser->endX())
+          {
+            iend = i;
+            if (iend > 0) iend--;
+            break;
+          }
+        }
+        if (iend > istart)
+        {
+          const Mantid::MantidVec& Y = ws->readY(wi);
+          double p0 = Y[istart];
+          double p1 = Y[iend];
+          double A1 = (p1-p0)/(X[iend]-X[istart]);
+          double A0 = p0 - A1*X[istart];
+          f->setParameter("A0",A0);
+          f->setParameter("A1",A1);
+        }
+      }
+  }
+  if (ws)
+  {
+    m_browser->setWorkspace(f);
+  }
+
+  int nFunctions = m_cf->nFunctions()+1;
+  m_cf->addFunction(f);
+
+  if (m_cf->nFunctions() != nFunctions)
+  {// this may happen
+    m_browser->reset();
+    return NULL;
+  }
+
+  PropertyHandler* h = new PropertyHandler(f,m_cf,m_browser);
+  f->setHandler(h);
+  h->setAttribute("StartX",m_browser->startX());
+  h->setAttribute("EndX",m_browser->endX());
+
+  // enable the change slots
+  m_browser->m_changeSlotsEnabled = true;
+  m_browser->setFitEnabled(true);
+  if (pf)
+  {
+    m_browser->setDefaultPeakType(f->name());
+  }
+  else
+  {
+    m_browser->setDefaultBackgroundType(f->name());
+  }
+  m_browser->setFocus();
+  m_browser->setCurrentFunction(h);
+  return h;
+}
+
+// Removes handled function from its parent function and 
+// properties from the browser
+void PropertyHandler::removeFunction()
+{
+  PropertyHandler* ph = parentHandler();
+  if (ph)
+  {
+    if (this == m_browser->m_autoBackground)
+    {
+      m_browser->m_autoBackground = NULL;
+    }
+    ph->item()->property()->removeSubProperty(m_item->property());
+    Mantid::API::CompositeFunction* cf = ph->cfun();
+    for(int i=0;i<cf->nFunctions();i++)
+    {
+      if (cf->getFunction(i) == function())
+      {
+        removePlot();
+        cf->removeFunction(i);
+        break;
+      }
+    }
+    ph->renameChildren();
+  }
+}
+
+void PropertyHandler::renameChildren()const
+{
+  m_browser->m_changeSlotsEnabled = false;
+  // update tie properties, as the parameter names may change
+  QMap<QString,QtProperty*>::const_iterator it = m_ties.begin();
+  for(;it!=m_ties.end();++it)
+  {
+    QtProperty* prop = it.value();
+    Mantid::API::ParameterTie* tie = 
+      m_fun->getTie(m_fun->parameterIndex(it.key().toStdString()));
+    if (!tie) continue;
+    QStringList qtie = QString::fromStdString(tie->asString()).split("=");
+    if (qtie.size() < 2) continue;
+    m_browser->m_stringManager->setValue(prop,qtie[1]);
+  }
+  if (!m_cf) return;
+  // rename children
+  for(int i=0;i<m_cf->nFunctions();i++)
+  {
+    PropertyHandler* h = getHandler(i);
+    if (!h) continue;
+    QtProperty* nameProp = h->item()->property();
+    nameProp->setPropertyName(h->functionName());
+    h->renameChildren();
+  }
+  m_browser->m_changeSlotsEnabled = true;
+}
+
+/// Creates name for this function to be displayed
+/// in the browser
+QString PropertyHandler::functionName()const
+{
+  QString name = functionPrefix();
+  if (!name.isEmpty())
+  {
+    name += "-";
+  }
+  name += QString::fromStdString(function()->name());
+  return name;
+}
+
+QString PropertyHandler::functionPrefix()const
+{
+  PropertyHandler* ph = parentHandler();
+  if (ph)
+  {
+    int iFun = -1;
+    Mantid::API::CompositeFunction* cf = ph->cfun();
+    for(int i=0;i<cf->nFunctions();i++)
+    {
+      if (cf->getFunction(i) == function())
+      {
+        iFun = i;
+        break;
+      }
+    }
+    QString pref = ph->functionPrefix();
+    if (!pref.isEmpty()) pref += ".";
+    return pref + "f" + QString::number(iFun);
+  }
+  return "";
+}
+
+// Return the parent handler
+PropertyHandler* PropertyHandler::parentHandler()const
+{
+  if (!m_parent) return 0;
+  PropertyHandler* ph = static_cast<PropertyHandler*>(m_parent->getHandler());
+  return ph;
+}
+// Return the child's handler
+PropertyHandler* PropertyHandler::getHandler(int i)const
+{
+  if (!m_cf || i >= m_cf->nFunctions()) return 0;
+  PropertyHandler* ph = static_cast<PropertyHandler*>(m_cf->getFunction(i)->getHandler());
+  return ph;
+}
+/** Returns 'this' if item == m_item and this is a composite function or
+* calls findCompositeFunction recursively with all its children or
+* zero
+*/
+const Mantid::API::CompositeFunction* PropertyHandler::findCompositeFunction(QtBrowserItem* item)const
+{
+  if (!m_cf) return 0;
+  if (item == m_item) return m_cf;
+  for(int i=0;i<m_cf->nFunctions();i++)
+  {
+    const Mantid::API::CompositeFunction* res = getHandler(i)->findCompositeFunction(item);
+    if (res != NULL) return res;
+  }
+  return 0;
+}
+/** Returns 'this' if item == m_item or
+* calls findFunction recursively with all its children or
+* zero
+*/
+const Mantid::API::IFitFunction* PropertyHandler::findFunction(QtBrowserItem* item)const
+{
+  if (item == m_item) return static_cast<const Mantid::API::IFitFunction*>(function());
+  if (!m_cf) return 0;
+  for(int i=0;i<m_cf->nFunctions();i++)
+  {
+    const Mantid::API::IFitFunction* res = getHandler(i)->findFunction(item);
+    if (res != NULL) return res;
+  }
+  return 0;
+}
+
+PropertyHandler* PropertyHandler::findHandler(QtProperty* prop)
+{
+  if (prop == m_item->property()) return this;
+  if (prop == m_type) return this;
+  if (m_attributes.contains(prop)) return this;
+  if (m_parameters.contains(prop)) return this;
+  if (!m_ties.key(prop,"").isEmpty()) return this;
+  QMap<QString,std::pair<QtProperty*,QtProperty*> >::iterator it = m_constraints.begin();
+  for(;it!=m_constraints.end();++it)
+  {
+    if (it.value().first == prop || it.value().second == prop)
+    {
+      return this;
+    }
+  }
+  if (!m_cf) return 0;
+  for(int i=0;i<m_cf->nFunctions();i++)
+  {
+    PropertyHandler* h = getHandler(i)->findHandler(prop);
+    if (h != NULL) return h;
+  }
+  return NULL;
+}
+
+PropertyHandler* PropertyHandler::findHandler(const Mantid::API::IFitFunction* fun)
+{
+  if (fun == function()) return this;
+  if (m_cf)
+  {
+    for(int i=0;i<m_cf->nFunctions();i++)
+    {
+      PropertyHandler* h = getHandler(i)->findHandler(fun);
+      if (h) return h;
+    }
+  }
+  return NULL;
+}
+
+/**
+* Set function parameter value read from a QtProperty
+* @param prop :: The (double) property with the new parameter value
+* @return true if successfull
+*/
+bool PropertyHandler::setParameter(QtProperty* prop)
+{
+  if (m_parameters.contains(prop))
+  {
+    std::string parName = prop->propertyName().toStdString();
+    double parValue = m_browser->m_doubleManager->value(prop);
+    m_fun->setParameter(parName,parValue);
+    m_browser->sendParameterChanged(m_if);
+    return true;
+  }
+  if (m_cf)
+  {
+    for(int i=0;i<m_cf->nFunctions();i++)
+    {
+      bool res = getHandler(i)->setParameter(prop);
+      if (res) return true;
+    }
+  }
+  return false;
+}
+
+/**
+ * Visitor setting new attribute value. Depending on the attribute type
+ * the appropriate apply method is used.
+ */
+class SetAttribute: public Mantid::API::IFitFunction::AttributeVisitor<>
+{
+public:
+  SetAttribute(FitPropertyBrowser* browser,QtProperty* prop)
+    :m_browser(browser),m_prop(prop){}
+protected:
+  /// Create string property
+  void apply(std::string& str)const
+  {
+    QString attName = m_prop->propertyName();
+    str = m_browser->getStringPropertyValue(m_prop).toStdString();
+  }
+  /// Create double property
+  void apply(double& d)const
+  {
+    d = m_browser->m_doubleManager->value(m_prop);
+  }
+  /// Create int property
+  void apply(int& i)const
+  {
+    i = m_browser->m_intManager->value(m_prop);
+  }
+private:
+  FitPropertyBrowser* m_browser;
+  QtProperty* m_prop;
+};
+
+/**
+ * Visitor setting new attribute value. Depending on the attribute type
+ * the appropriate apply method is used.
+ */
+class SetAttributeProperty: public Mantid::API::IFitFunction::ConstAttributeVisitor<>
+{
+public:
+  SetAttributeProperty(FitPropertyBrowser* browser,QtProperty* prop)
+    :m_browser(browser),m_prop(prop){}
+protected:
+  /// Set string property
+  void apply(const std::string& str)const
+  {
+    m_browser->m_changeSlotsEnabled = false;
+    QString attName = m_prop->propertyName();
+    m_browser->setStringPropertyValue(m_prop,QString::fromStdString(str));
+    m_browser->m_changeSlotsEnabled = true;
+  }
+  /// Set double property
+  void apply(const double& d)const
+  {
+    m_browser->m_changeSlotsEnabled = false;
+    m_browser->m_doubleManager->setValue(m_prop,d);
+    m_browser->m_changeSlotsEnabled = true;
+  }
+  /// Set int property
+  void apply(const int& i)const
+  {
+    m_browser->m_changeSlotsEnabled = false;
+    m_browser->m_intManager->setValue(m_prop,i);
+    m_browser->m_changeSlotsEnabled = true;
+  }
+private:
+  FitPropertyBrowser* m_browser;
+  QtProperty* m_prop;
+};
+
+/**
+* Set function attribute value read from a QtProperty
+* @param prop :: The (string) property with the new attribute value
+* @return true if successfull
+*/
+bool PropertyHandler::setAttribute(QtProperty* prop)
+{
+  if (m_attributes.contains(prop))
+  {
+    QString attName = prop->propertyName();
+    try
+    {
+      Mantid::API::IFitFunction::Attribute att = 
+        m_fun->getAttribute(attName.toStdString());
+      SetAttribute tmp(m_browser,prop);
+      att.apply(tmp);
+      m_fun->setAttribute(attName.toStdString(),att);
+      m_browser->compositeFunction()->checkFunction();
+      initParameters();
+      if (this == m_browser->m_autoBackground)
+      {
+        fit();
+      }
+    }
+    catch(std::exception& e)
+    {
+      QMessageBox::critical(m_browser->m_appWindow,"Mantid - Error",e.what());
+      return false;
+    }
+    return true;
+  }
+  if (m_cf)
+  {
+    for(int i=0;i<m_cf->nFunctions();i++)
+    {
+      bool res = getHandler(i)->setAttribute(prop);
+      if (res) return true;
+    }
+  }
+  return false;
+}
+
+void PropertyHandler::setAttribute(const QString& attName, const double& attValue)
+{
+  if (m_fun->hasAttribute(attName.toStdString()))
+  {
+    try
+    {
+      m_fun->setAttribute(attName.toStdString(),Mantid::API::IFitFunction::Attribute(attValue));
+      m_browser->compositeFunction()->checkFunction();
+      foreach(QtProperty* prop,m_attributes)
+      {
+        if (prop->propertyName() == attName)
+        {
+          m_browser->m_changeSlotsEnabled = false;
+          m_browser->m_doubleManager->setValue(prop,attValue);
+          m_browser->m_changeSlotsEnabled = true;
+        }
+      }
+    }
+    catch(...){}
+  }
+  if (cfun())
+  {
+    for(int i=0;i<cfun()->nFunctions();++i)
+    {
+      PropertyHandler* h = getHandler(i);
+      h->setAttribute(attName,attValue);
+    }
+  }
+}
+
+
+
+void PropertyHandler::setAttribute(const QString& attName, const QString& attValue)
+{
+  const std::string name = attName.toStdString();
+  if (m_fun->hasAttribute(name))
+  {
+    Mantid::API::IFitFunction::Attribute att = m_fun->getAttribute(name);
+    att.fromString(attValue.toStdString());
+    m_fun->setAttribute(name,att);
+    m_browser->compositeFunction()->checkFunction();
+    foreach(QtProperty* prop,m_attributes)
+    {
+      if (prop->propertyName() == attName)
+      {
+        SetAttributeProperty tmp(m_browser,prop);
+        att.apply(tmp);
+      }
+    }
+    initParameters();
+  }
+}
+
+/**
+* Update the parameter properties
+*/
+void PropertyHandler::updateParameters()
+{
+  for(int i=0;i<m_parameters.size();i++)
+  {
+    QtProperty* prop = m_parameters[i];
+    std::string parName = prop->propertyName().toStdString();
+    double parValue = function()->getParameter(parName);
+    m_browser->m_doubleManager->setValue(prop,parValue);
+  }
+  if (m_cf)
+  {
+    for(int i=0;i<m_cf->nFunctions();i++)
+    {
+      getHandler(i)->updateParameters();
+    }
+  }
+}
+
+/**
+* Change the type of the function (replace the function)
+* @param prop :: The "Type" property with new value
+* @param fnName :: New function name (type) or full initialization expression
+*/
+Mantid::API::IFitFunction* PropertyHandler::changeType(QtProperty* prop)
+{
+  if (prop == m_type)
+  {
+    if (!m_parent) return m_browser->compositeFunction();// dont replace the root composite function
+
+    // Create new function
+    int i = m_browser->m_enumManager->value(prop);
+    const QString& fnName = m_browser->m_registeredFunctions[i];
+    Mantid::API::IFitFunction* f = NULL;
+    try
+    {
+      f = Mantid::API::FunctionFactory::Instance().
+        createFunction(fnName.toStdString());
+    }
+    catch(std::exception& e)
+    {
+      QMessageBox::critical(NULL,"Mantid - Error","Cannot create function "+fnName+
+        "\n"+e.what());
+      return NULL;
+    }
+
+    // turn of the change slots (doubleChanged() etc) to avoid infinite loop
+    m_browser->m_changeSlotsEnabled = false;
+
+    // Check if it's a peak and set its width
+    Mantid::API::IPeakFunction* pf = dynamic_cast<Mantid::API::IPeakFunction*>(f);
+    if (pf)
+    {
+      if (!m_pf)
+      {
+        if (!m_browser->workspaceName().empty() && m_browser->workspaceIndex() >= 0)
+        {
+          pf->setCentre( (m_browser->startX() + m_browser->endX())/2 );
+        }
+      }
+      else
+      {
+        pf->setCentre(m_pf->centre());
+        pf->setHeight(m_pf->height());
+        pf->setWidth(m_pf->width());
+      }
+    }
+
+    if (pf)
+    {
+      m_browser->setDefaultPeakType(fnName.toStdString());
+    }
+    else
+    {
+      m_browser->setDefaultBackgroundType(fnName.toStdString());
+    }
+
+    QList<QtProperty*> subs = m_item->property()->subProperties();
+    foreach(QtProperty* sub, subs)
+    {
+      m_item->property()->removeSubProperty(sub);
+    }
+
+    m_browser->m_changeSlotsEnabled = true;
+
+    removePlot();
+
+    const Mantid::API::IFitFunction* f_old = static_cast<const Mantid::API::IFitFunction*>(function());
+    PropertyHandler* h = new PropertyHandler(f,m_parent,m_browser,m_item);
+    if (this == m_browser->m_autoBackground)
+    {
+      if (dynamic_cast<Mantid::API::IBackgroundFunction*>(f))
+      {
+        m_browser->m_autoBackground = h;
+        h->fit();
+      }
+      else
+      {
+        m_browser->m_autoBackground = NULL;
+      }
+    }
+    m_parent->replaceFunction(f_old,f);
+    f->setHandler(h);
+    // calculate the baseline
+    if (h->pfun())
+    {
+      h->setCentre(h->centre()); // this sets m_ci
+      h->calcBase();
+    }
+    // at this point this handler does not exist any more. only return is possible
+    return f;
+
+  }
+  else if (m_cf)
+  {
+    for(int i=0;i<m_cf->nFunctions();i++)
+    {
+      Mantid::API::IFitFunction* f = getHandler(i)->changeType(prop);
+      if (f) return f;
+    }
+  }
+  return NULL;
+}
+
+bool PropertyHandler::isParameter(QtProperty* prop)
+{
+  return m_parameters.contains(prop);
+}
+
+QtProperty* PropertyHandler::getParameterProperty(const QString& parName)const
+{
+  foreach(QtProperty* parProp,m_parameters)
+  {
+    if (parProp->propertyName() == parName)
+    {
+      return parProp;
+    }
+  }
+  return NULL;
+}
+
+QtProperty* PropertyHandler::getParameterProperty(QtProperty* prop)const
+{
+  foreach(QtProperty* parProp,m_parameters)
+  {
+    QList<QtProperty*> subs = parProp->subProperties();
+    if (subs.contains(prop))
+    {
+      return parProp;
+    }
+  }
+  return NULL;
+}
+
+void PropertyHandler::addTie(const QString& tieStr)
+{
+  QStringList parts = tieStr.split("=");
+  if (parts.size() != 2) return;
+  std::string name = parts[0].trimmed().toStdString();
+  std::string expr = parts[1].trimmed().toStdString();
+  try
+  {
+    Mantid::API::ParameterTie* tie = 
+      m_browser->compositeFunction()->tie(name,expr);
+    if (tie == NULL) return;
+    QString parName = QString::fromStdString(
+      tie->getFunction()->parameterName(tie->getIndex())
+     );
+    foreach(QtProperty* parProp,m_parameters)
+    {
+      if (parProp->propertyName() == parName)
+      {
+        m_browser->m_changeSlotsEnabled = false;
+        QtProperty* tieProp = m_ties[parName];
+        if (!tieProp)
+        {
+          tieProp = m_browser->m_stringManager->addProperty( "Tie" );
+          m_ties[parName] = tieProp;
+        }
+        m_browser->m_stringManager->setValue(tieProp,QString::fromStdString(expr));
+        m_browser->m_changeSlotsEnabled = true;
+        parProp->addSubProperty(tieProp);
+        return;
+      }
+    }
+  }
+  catch(...){}
+}
+
+void PropertyHandler::fix(const QString& parName)
+{
+  QtProperty* parProp = getParameterProperty(parName);
+  if (!parProp) return;
+  QString parValue = QString::number(m_browser->m_doubleManager->value(parProp));
+  try
+  {
+    m_fun->tie(parName.toStdString(),parValue.toStdString());
+    m_browser->m_changeSlotsEnabled = false;
+    QtProperty* tieProp = m_ties[parName];
+    if (!tieProp)
+    {
+      tieProp = m_browser->m_stringManager->addProperty( "Tie" );
+      m_ties[parName] = tieProp;
+    }
+    m_browser->m_stringManager->setValue(tieProp,parValue);
+    m_browser->m_changeSlotsEnabled = true;
+    parProp->addSubProperty(tieProp);
+    parProp->setEnabled(false);
+    tieProp->setEnabled(false);
+  }
+  catch(...){}
+
+}
+
+/**
+ * Remove the tie.
+ * @param prop :: The tie property to remove
+ */
+void PropertyHandler::removeTie(QtProperty* prop)
+{
+  QString parName = m_ties.key(prop,"");
+  if (parName.isEmpty()) return;
+  
+  QtProperty* parProp = getParameterProperty(parName);
+  if (parProp)
+  {
+    m_browser->m_changeSlotsEnabled = false;
+    m_fun->removeTie(parName.toStdString());
+    parProp->removeSubProperty(prop);
+    m_ties.remove(parName);
+    m_browser->m_changeSlotsEnabled = true;
+    parProp->setEnabled(true);
+  }
+}
+
+/**
+ * Remove the tie.
+ * @param parName :: The name of the parameter
+ */
+void PropertyHandler::removeTie(const QString& parName)
+{
+  QtProperty* prop = m_ties[parName];
+  if (prop) removeTie(prop);
+}
+
+void PropertyHandler::calcBase()
+{
+  if (!m_browser->m_autoBackground) return;
+  Mantid::API::IFunctionMW* fMW = dynamic_cast<Mantid::API::IFunctionMW*>(m_if);
+  if (!fMW) return;
+  Mantid::API::MatrixWorkspace_const_sptr ws = fMW->getMatrixWorkspace();
+  if (ws)
+  {
+    int wi = fMW->getWorkspaceIndex();
+    const Mantid::MantidVec& X = ws->readX(wi);
+    const Mantid::MantidVec& Y = ws->readY(wi);
+    int n = Y.size() - 1;
+    if (m_ci < 0 || m_ci > n || !m_browser->m_autoBackground)
+    {
+      m_base = 0.;
+    }
+    else
+    {
+      double x = X[m_ci];
+      double y = 0;
+      dynamic_cast<const Mantid::API::IFunctionMW*>(m_browser->m_autoBackground->function())->function(&y,&x,1);
+      m_base = y;
+    }
+  }
+  else
+  {
+    m_base = 0.;
+  }
+}
+
+void PropertyHandler::calcBaseAll()
+{
+  if (!m_browser->m_autoBackground) return;
+  if (!m_cf) return;
+  for(int i=0;i<m_cf->nFunctions();++i)
+  {
+    PropertyHandler* h = getHandler(i);
+    if (h->pfun())
+    {
+      h->calcBase();
+    }
+    else if (h->cfun())
+    {
+      h->calcBaseAll();
+    }
+  }
+}
+
+void PropertyHandler::setHeight(const double& h)
+{
+  if (m_pf)
+  {
+    m_pf->setHeight(h - m_base);
+  }
+}
+
+void PropertyHandler::setCentre(const double& c)
+{
+  if (m_pf)
+  {
+    m_pf->setCentre(c);
+    Mantid::API::MatrixWorkspace_const_sptr ws = m_pf->getMatrixWorkspace();
+    if (ws)
+    {
+      int wi = m_pf->getWorkspaceIndex();
+      const Mantid::MantidVec& X = ws->readX(wi);
+      int n = X.size() - 2;
+      if (m_ci < 0) m_ci = 0;
+      if (m_ci > n) m_ci = n;
+      double x = X[m_ci];
+      if (x < c)
+      {
+        for(;m_ci<=n;++m_ci)
+        {
+          x = X[m_ci];
+          if (x > c) break;
+        }
+      }
+      else
+      {
+        for(;m_ci>=0;--m_ci)
+        {
+          x = X[m_ci];
+          if (x < c) break;
+        }
+      }
+    }
+  }
+}
+
+void PropertyHandler::setWidth(const double& w)
+{
+  if (m_pf)
+  {
+    m_pf->setWidth(w);
+  }
+}
+
+double PropertyHandler::height()const
+{
+  if (m_pf)
+  {
+    return m_pf->height();
+  }
+  return 0;
+}
+
+double PropertyHandler::centre()const
+{
+  if (m_pf)
+  {
+    return m_pf->centre();
+  }
+  return (m_browser->endX() + m_browser->startX())/2;
+}
+
+double PropertyHandler::width()const
+{
+  if (m_pf)
+  {
+    return m_pf->width();
+  }
+  return 0;
+}
+
+/**
+ * Add constraint to parameter property parProp
+ */
+void PropertyHandler::addConstraint(QtProperty* parProp,bool lo,bool up,double loBound,double upBound)
+{
+  QMap<QString,std::pair<QtProperty*,QtProperty*> >::iterator old = 
+    m_constraints.find(parProp->propertyName());
+
+  bool hasLo = false;
+  bool hasUp = false;
+
+  if (old != m_constraints.end())
+  {
+    hasLo = old.value().first != NULL;
+    hasUp = old.value().second != NULL;
+    if (hasLo && !lo)
+    {
+      lo = true;
+      loBound = m_browser->m_doubleManager->value(old.value().first);
+    }
+    if (hasUp && !up)
+    {
+      up = true;
+      upBound = m_browser->m_doubleManager->value(old.value().second);
+    }
+  }
+
+  m_browser->m_changeSlotsEnabled = false;
+  std::pair<QtProperty*,QtProperty*> cnew(nullptr,nullptr);
+  std::ostringstream ostr;
+  if (lo) 
+  {
+    ostr << loBound << "<";
+    if (!hasLo)
+    {
+      cnew.first = m_browser->addDoubleProperty("LowerBound");
+      parProp->addSubProperty(cnew.first);
+    }
+    else
+    {
+      cnew.first = old.value().first;
+    }
+    m_browser->m_doubleManager->setValue(cnew.first,loBound);
+  }
+  ostr << parProp->propertyName().toStdString();
+  if (up)
+  {
+    ostr << "<" << upBound;
+    if (!hasUp)
+    {
+      cnew.second = m_browser->addDoubleProperty("UpperBound");
+      parProp->addSubProperty(cnew.second);
+    }
+    else
+    {
+      cnew.second = old.value().second;
+    }
+    m_browser->m_doubleManager->setValue(cnew.second,upBound);
+  }
+
+  if (old != m_constraints.end())
+  {
+    m_constraints.erase(old);
+  }
+
+  m_constraints.insert(parProp->propertyName(),cnew);
+
+  Mantid::API::IConstraint* c = 
+    Mantid::API::ConstraintFactory::Instance().createInitialized(m_fun,ostr.str());
+  m_fun->addConstraint(c);
+  m_browser->m_changeSlotsEnabled = true;
+}
+
+void PropertyHandler::removeConstraint(QtProperty* parProp)
+{
+  QMap<QString,std::pair<QtProperty*,QtProperty*> >::iterator it = 
+    m_constraints.find(parProp->propertyName());
+
+  if (it != m_constraints.end())
+  {
+    if (it.value().first)
+    {
+      parProp->removeSubProperty(it.value().first);
+    }
+    if (it.value().second)
+    {
+      parProp->removeSubProperty(it.value().second);
+    }
+    m_fun->removeConstraint(parProp->propertyName().toStdString());
+  }
+  m_constraints.clear();
+}
+
+/**
+ * Make a list of all peaks in this function
+ */
+QList<PropertyHandler*> PropertyHandler::getPeakList()
+{
+  QList<PropertyHandler*> res;
+  if (m_pf)
+  {
+    res << this;
+  }
+  if (m_cf)
+  {
+    for(int i=0;i<m_cf->nFunctions();++i)
+    {
+      PropertyHandler* h = getHandler(i);
+      if ( !h )  continue;
+      if (h->pfun())
+      {
+        res << h;
+      }
+      else if (h->cfun())
+      {
+        res << h->getPeakList();
+      }
+    }
+  }
+  return res;
+}
+
+/**
+ * Plot this function on a graph
+ * @param g :: The graph to plot on
+ */
+void PropertyHandler::plot(Graph* g)const
+{
+  if (!m_curve)
+  {
+    m_curve = new FunctionCurve(
+      m_if,
+      QString::fromStdString(m_browser->m_groupMember),//m_browser->workspaceName()),
+      m_browser->workspaceIndex(),
+      functionName());
+    m_curve->setRange(m_browser->startX(),m_browser->endX());
+    m_curve->loadData();
+    // Graph now owns m_curve. Use m_curve->removeMe() to remove (and delete) from Graph
+    g->insertCurve(m_curve);
+    connect(m_curve,SIGNAL(forgetMe(PlotCurve*)),this,SLOT(plotRemoved(PlotCurve*)));
+    if (this == m_browser->getHandler())
+    {
+      m_browser->m_btnPlotGuess->setText("Remove guess");
+    }
+  }
+}
+
+/**
+ * Remove this function curve from its graph
+ */
+void PropertyHandler::removePlot()
+{
+  if (m_curve)
+  {
+    m_curve->removeMe();
+    m_curve = NULL;
+    if (this == m_browser->getHandler())
+    {
+      m_browser->m_btnPlotGuess->setText("Plot guess");
+    }
+  }
+}
+
+/**
+ * Remove the reference to the function curve as it has been deleted
+ */
+void PropertyHandler::plotRemoved(PlotCurve* c)
+{
+  if (c == dynamic_cast<PlotCurve*>(m_curve))
+  {
+    m_curve = NULL;
+  }
+}
+
+/**
+ * Replot function curve when parameters have been changed
+ */
+void PropertyHandler::replot()const
+{
+  if (m_curve)
+  {
+    QStringList formulas = m_curve->formulas();
+    formulas[1] = QString::fromStdString(*m_fun);
+    m_curve->setFormulas(formulas);
+    m_curve->loadData();
+  }
+}
+
+/**
+ * Remove all plots including children's
+ */
+void PropertyHandler::removeAllPlots()
+{
+  removePlot();
+  if (m_cf)
+  {
+    for(int i=0;i<m_cf->nFunctions();++i)
+    {
+      getHandler(i)->removeAllPlots();
+    }
+  }
+}
+
+void PropertyHandler::fit()
+{
+  try
+  {
+    if (m_browser->workspaceName().empty()) return;
+
+    Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("Fit");
+    alg->initialize();
+    alg->setPropertyValue("InputWorkspace",m_browser->workspaceName());
+    alg->setProperty("WorkspaceIndex",m_browser->workspaceIndex());
+    alg->setProperty("StartX",m_browser->startX());
+    alg->setProperty("EndX",m_browser->endX());
+    alg->setPropertyValue("Function",*m_fun);
+    alg->execute();
+    std::string fitFun = alg->getPropertyValue("Function");
+    Mantid::API::IFitFunction* f = Mantid::API::FunctionFactory::Instance().createInitialized(fitFun);
+    for(int i=0;i<f->nParams();++i)
+    {
+      m_fun->setParameter(i,f->getParameter(i));
+    }
+    delete f;
+    m_browser->getHandler()->calcBaseAll();
+    updateParameters();
+  }
+  catch(...)
+  {
+  }
+}
diff --git a/Code/Mantid/MantidPlot/src/Mantid/PropertyHandler.h b/Code/Mantid/MantidPlot/src/Mantid/PropertyHandler.h
index 3b588396761fab2166f7fdfa8a769a23a64bd589..683b90ae874b65acc448b4a3cbc11acbbba2acb5 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/PropertyHandler.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/PropertyHandler.h
@@ -1,194 +1,194 @@
-#ifndef PROPERTY_HANDLER_H
-#define PROPERTY_HANDLER_H
-
-#include "MantidAPI/IFitFunction.h"
-
-/* Forward declarations */
-namespace Mantid
-{
-  namespace API
-  {
-    class IPeakFunction;
-    class CompositeFunction;
-  }
-}
-class FitPropertyBrowser;
-class FunctionCurve;
-class PlotCurve;
-class Graph;
-class QtBrowserItem;
-class QtProperty;
-
-/* Qt includes */
-#include <QString>
-#include <QList>
-#include <QMap>
-#include <QObject>
-
-/**
- * Helps display and edit functions in FitPropertyBrowser
- */
-class PropertyHandler:public QObject, public Mantid::API::FitFunctionHandler
-{
-  Q_OBJECT
-public:
-  // Constructor
-  PropertyHandler(Mantid::API::IFitFunction* fun,
-                  Mantid::API::CompositeFunction* parent,
-                  FitPropertyBrowser* browser,
-                  QtBrowserItem* item = NULL);
-
-  /// Destructor
-  ~PropertyHandler();
-
-  /// overrides virtual init() which is called from IFitFunction::setHandler(...)
-  void init();
-
-  void initAttributes();
-  void initParameters();
-
-  PropertyHandler* addFunction(const std::string& fnName);
-  // Removes handled function from its parent function and 
-  // properties from the browser
-  void removeFunction();
-
-  void renameChildren()const;
-
-  /// Creates name for this function to be displayed
-  /// in the browser
-  QString functionName()const;
-
-  QString functionPrefix()const;
-
-  // Return composite function
-  Mantid::API::CompositeFunction* cfun()const{return m_cf;}
-  // Return peak function
-  Mantid::API::IPeakFunction* pfun()const{return m_pf;}
-  // Return the browser item
-  QtBrowserItem* item()const{return m_item;}
-  // Return the parent handler
-  PropertyHandler* parentHandler()const;
-  // Return the child's handler
-  PropertyHandler* getHandler(int i)const;
-  /** Returns 'this' if item == m_item and this is a composite function or
-   * calls findCompositeFunction recursively with all its children or
-   * zero
-   */
-  const Mantid::API::CompositeFunction* findCompositeFunction(QtBrowserItem* item)const;
-  /** Returns 'this' if item == m_item or
-   * calls findFunction recursively with all its children or
-   * zero
-   */
-  const Mantid::API::IFitFunction* findFunction(QtBrowserItem* item)const;
-
-  PropertyHandler* findHandler(QtProperty* prop);
-
-  PropertyHandler* findHandler(const Mantid::API::IFitFunction* 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);
-
-  // Check if it is a parameter property
-  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);
-
-  /**
-   * 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);
-
-  /**
-   * Set function's attribute of any type.
-   * @param attName :: The name of the attribute
-   * @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);
-
-  /**
-   * Update the parameter properties
-   */
-  void updateParameters();
-
-  // Get property for function parameter parName
-  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;
-
-  /**
-   * Change the type of the function (replace the function)
-   * @param prop :: The "Type" property with new value
-   * @param fnName :: New function name (type) or full initialization expression
-   */
-  Mantid::API::IFitFunction* changeType(QtProperty* prop);
-
-  void setHeight(const double& h);
-  void setCentre(const double& c);
-  void setWidth(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
-
-  double height()const;
-  double centre()const;
-  double width()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();
-
-  // Plot the function on a graph
-  void plot(Graph* g)const;
-  bool hasPlot()const{return m_curve != NULL;}
-  void replot()const;
-  void removePlot();
-  void removeAllPlots();
-
-  void fit();
-
-protected slots:
-
-  // 
-  void plotRemoved(PlotCurve*);
-
-private:
-  FitPropertyBrowser* m_browser;
-  Mantid::API::CompositeFunction* m_cf;//< if the function is composite holds pointer to it
-  Mantid::API::IPeakFunction* m_pf;//< if the function is peak holds pointer to it
-  Mantid::API::CompositeFunction* m_parent; //< if the function has parent holds pointer to it
-  Mantid::API::IFitFunction* m_if;//< pointer to IFitFunction
-  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
-  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
-};
-
-#endif /* PROPERTY_HANDLER_H */
+#ifndef PROPERTY_HANDLER_H
+#define PROPERTY_HANDLER_H
+
+#include "MantidAPI/IFitFunction.h"
+
+/* Forward declarations */
+namespace Mantid
+{
+  namespace API
+  {
+    class IPeakFunction;
+    class CompositeFunction;
+  }
+}
+class FitPropertyBrowser;
+class FunctionCurve;
+class PlotCurve;
+class Graph;
+class QtBrowserItem;
+class QtProperty;
+
+/* Qt includes */
+#include <QString>
+#include <QList>
+#include <QMap>
+#include <QObject>
+
+/**
+ * Helps display and edit functions in FitPropertyBrowser
+ */
+class PropertyHandler:public QObject, public Mantid::API::FitFunctionHandler
+{
+  Q_OBJECT
+public:
+  // Constructor
+  PropertyHandler(Mantid::API::IFitFunction* fun,
+                  Mantid::API::CompositeFunction* parent,
+                  FitPropertyBrowser* browser,
+                  QtBrowserItem* item = NULL);
+
+  /// Destructor
+  ~PropertyHandler();
+
+  /// overrides virtual init() which is called from IFitFunction::setHandler(...)
+  void init();
+
+  void initAttributes();
+  void initParameters();
+
+  PropertyHandler* addFunction(const std::string& fnName);
+  // Removes handled function from its parent function and 
+  // properties from the browser
+  void removeFunction();
+
+  void renameChildren()const;
+
+  /// Creates name for this function to be displayed
+  /// in the browser
+  QString functionName()const;
+
+  QString functionPrefix()const;
+
+  // Return composite function
+  Mantid::API::CompositeFunction* cfun()const{return m_cf;}
+  // Return peak function
+  Mantid::API::IPeakFunction* pfun()const{return m_pf;}
+  // Return the browser item
+  QtBrowserItem* item()const{return m_item;}
+  // Return the parent handler
+  PropertyHandler* parentHandler()const;
+  // Return the child's handler
+  PropertyHandler* getHandler(int i)const;
+  /** Returns 'this' if item == m_item and this is a composite function or
+   * calls findCompositeFunction recursively with all its children or
+   * zero
+   */
+  const Mantid::API::CompositeFunction* findCompositeFunction(QtBrowserItem* item)const;
+  /** Returns 'this' if item == m_item or
+   * calls findFunction recursively with all its children or
+   * zero
+   */
+  const Mantid::API::IFitFunction* findFunction(QtBrowserItem* item)const;
+
+  PropertyHandler* findHandler(QtProperty* prop);
+
+  PropertyHandler* findHandler(const Mantid::API::IFitFunction* 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);
+
+  // Check if it is a parameter property
+  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);
+
+  /**
+   * 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);
+
+  /**
+   * Set function's attribute of any type.
+   * @param attName :: The name of the attribute
+   * @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);
+
+  /**
+   * Update the parameter properties
+   */
+  void updateParameters();
+
+  // Get property for function parameter parName
+  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;
+
+  /**
+   * Change the type of the function (replace the function)
+   * @param prop :: The "Type" property with new value
+   * @param fnName :: New function name (type) or full initialization expression
+   */
+  Mantid::API::IFitFunction* changeType(QtProperty* prop);
+
+  void setHeight(const double& h);
+  void setCentre(const double& c);
+  void setWidth(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
+
+  double height()const;
+  double centre()const;
+  double width()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();
+
+  // Plot the function on a graph
+  void plot(Graph* g)const;
+  bool hasPlot()const{return m_curve != NULL;}
+  void replot()const;
+  void removePlot();
+  void removeAllPlots();
+
+  void fit();
+
+protected slots:
+
+  // 
+  void plotRemoved(PlotCurve*);
+
+private:
+  FitPropertyBrowser* m_browser;
+  Mantid::API::CompositeFunction* m_cf;//< if the function is composite holds pointer to it
+  Mantid::API::IPeakFunction* m_pf;//< if the function is peak holds pointer to it
+  Mantid::API::CompositeFunction* m_parent; //< if the function has parent holds pointer to it
+  Mantid::API::IFitFunction* m_if;//< pointer to IFitFunction
+  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
+  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
+};
+
+#endif /* PROPERTY_HANDLER_H */
diff --git a/Code/Mantid/MantidPlot/src/Mantid/RemoveErrorsDialog.cpp b/Code/Mantid/MantidPlot/src/Mantid/RemoveErrorsDialog.cpp
index 55c5d5468538026b4d392ac91b8e37dd89e2a83a..4d8bdb6454fdbcd96cb4aee7c44e148bda533db4 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/RemoveErrorsDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/RemoveErrorsDialog.cpp
@@ -1,25 +1,25 @@
-#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()
-{
-    delete ui;
-}
-
-void RemoveErrorsDialog::setCurveNames(const QStringList& names)
-{
-  ui->nameLabel->addItems(names);
-}
-
-void RemoveErrorsDialog::remove()
-{
-  emit curveName(ui->nameLabel->currentText());
+#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()
+{
+    delete ui;
+}
+
+void RemoveErrorsDialog::setCurveNames(const QStringList& names)
+{
+  ui->nameLabel->addItems(names);
+}
+
+void RemoveErrorsDialog::remove()
+{
+  emit curveName(ui->nameLabel->currentText());
 }
\ No newline at end of file
diff --git a/Code/Mantid/MantidPlot/src/Mantid/RemoveErrorsDialog.h b/Code/Mantid/MantidPlot/src/Mantid/RemoveErrorsDialog.h
index 59b577a42edd62f5e8dcfde1db6ce16d7ce1f863..5c0816bf273aea9db235d0e8dbeef6b72f2863e7 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/RemoveErrorsDialog.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/RemoveErrorsDialog.h
@@ -1,31 +1,31 @@
-#ifndef REMOVEERRORSDIALOG_H
-#define REMOVEERRORSDIALOG_H
-
-#include <QDialog>
-
-namespace Ui {
-    class RemoveErrorsDialog;
-}
-
-class RemoveErrorsDialog : public QDialog {
-    Q_OBJECT
-public:
-    RemoveErrorsDialog(QWidget *parent = 0);
-    ~RemoveErrorsDialog();
-
-    //! Supply the dialog with a curves list
-    void setCurveNames(const QStringList& names);
-
-signals:
-
-    void curveName(const QString&);
-
-protected slots:
-
-  void remove();
-
-private:
-    Ui::RemoveErrorsDialog *ui;
-};
-
-#endif // REMOVEERRORSDIALOG_H
+#ifndef REMOVEERRORSDIALOG_H
+#define REMOVEERRORSDIALOG_H
+
+#include <QDialog>
+
+namespace Ui {
+    class RemoveErrorsDialog;
+}
+
+class RemoveErrorsDialog : public QDialog {
+    Q_OBJECT
+public:
+    RemoveErrorsDialog(QWidget *parent = 0);
+    ~RemoveErrorsDialog();
+
+    //! Supply the dialog with a curves list
+    void setCurveNames(const QStringList& names);
+
+signals:
+
+    void curveName(const QString&);
+
+protected slots:
+
+  void remove();
+
+private:
+    Ui::RemoveErrorsDialog *ui;
+};
+
+#endif // REMOVEERRORSDIALOG_H
diff --git a/Code/Mantid/MantidPlot/src/Mantid/SelectWorkspacesDialog.cpp b/Code/Mantid/MantidPlot/src/Mantid/SelectWorkspacesDialog.cpp
index e2df754f9ce1f3932837d6f61d8ca847281dc86f..ee4286b281671e76f953b745fb244eac713eb808 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/SelectWorkspacesDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/SelectWorkspacesDialog.cpp
@@ -1,16 +1,16 @@
 //---------------------------------------
 // Includes
 //---------------------------------------
-
-#include "SelectWorkspacesDialog.h"
-#include "../ApplicationWindow.h"
-#include "MantidUI.h"
-
-#include <QListWidget>
-#include <QVBoxLayout>
-#include <QPushButton>
-#include <QDialogButtonBox>
-
+
+#include "SelectWorkspacesDialog.h"
+#include "../ApplicationWindow.h"
+#include "MantidUI.h"
+
+#include <QListWidget>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QDialogButtonBox>
+
 //---------------------------------------
 // Public member functions
 //---------------------------------------
@@ -29,8 +29,8 @@ QDialog(appWindow)
   QDialogButtonBox* btnBox = new QDialogButtonBox(Qt::Horizontal);
   btnBox->addButton(okButton,QDialogButtonBox::AcceptRole);
   btnBox->addButton(cancelButton,QDialogButtonBox::RejectRole);
-  connect(btnBox, SIGNAL(accepted()), this, SLOT(accept()));
-  connect(btnBox, SIGNAL(rejected()), this, SLOT(reject()));
+  connect(btnBox, SIGNAL(accepted()), this, SLOT(accept()));
+  connect(btnBox, SIGNAL(rejected()), this, SLOT(reject()));
 
   QVBoxLayout* vLayout = new QVBoxLayout();
   vLayout->addWidget(m_wsList);
diff --git a/Code/Mantid/MantidPlot/src/Mantid/SelectWorkspacesDialog.h b/Code/Mantid/MantidPlot/src/Mantid/SelectWorkspacesDialog.h
index 085eb790dd1ce0d367f7f7abd4ece474588ef64e..bc6bd4e7c11fc48f8f1f922955168688f3adf16d 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/SelectWorkspacesDialog.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/SelectWorkspacesDialog.h
@@ -1,20 +1,20 @@
-#ifndef SELECTWORKSPACESDIALOG_H
-#define SELECTWORKSPACESDIALOG_H
-
-//----------------------------
-//   Includes
-//----------------------------
-
-#include <QDialog>
-#include <QListWidget>
-#include <QStringList>
-
-//----------------------------
-//   Forward declarations
-//----------------------------
-
-class ApplicationWindow;
-
+#ifndef SELECTWORKSPACESDIALOG_H
+#define SELECTWORKSPACESDIALOG_H
+
+//----------------------------
+//   Includes
+//----------------------------
+
+#include <QDialog>
+#include <QListWidget>
+#include <QStringList>
+
+//----------------------------
+//   Forward declarations
+//----------------------------
+
+class ApplicationWindow;
+
 /** 
     This is a dialog for selecting workspaces.
 
@@ -61,5 +61,5 @@ private:
 };
 
 
-
-#endif /* SELECTWORKSPACESDIALOG_H */
+
+#endif /* SELECTWORKSPACESDIALOG_H */
diff --git a/Code/Mantid/MantidPlot/src/Mantid/SequentialFitDialog.cpp b/Code/Mantid/MantidPlot/src/Mantid/SequentialFitDialog.cpp
index 63dfb313273d11b4774b51a474cc89cee2527287..841ace457445750b2fd0791c411e748af0bdecbb 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/SequentialFitDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/SequentialFitDialog.cpp
@@ -1,22 +1,22 @@
 //---------------------------------------
 // Includes
 //---------------------------------------
-
-#include "SequentialFitDialog.h"
-#include "FitPropertyBrowser.h"
-#include "MantidUI.h"
-#include "SelectWorkspacesDialog.h"
-#include "../ApplicationWindow.h"
-
-#include "MantidKernel/TimeSeriesProperty.h"
-#include "MantidKernel/ConfigService.h"
-#include "MantidAPI/CompositeFunction.h"
-
-#include <QInputDialog>
-#include <QFileDialog>
-#include <QMessageBox>
+
+#include "SequentialFitDialog.h"
+#include "FitPropertyBrowser.h"
+#include "MantidUI.h"
+#include "SelectWorkspacesDialog.h"
+#include "../ApplicationWindow.h"
+
+#include "MantidKernel/TimeSeriesProperty.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidAPI/CompositeFunction.h"
+
+#include <QInputDialog>
+#include <QFileDialog>
+#include <QMessageBox>
 #include <QDesktopServices>
-
+
 //---------------------------------------
 // Public member functions
 //---------------------------------------
@@ -85,9 +85,9 @@ bool SequentialFitDialog::addWorkspaces(const QStringList wsNames)
     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)
@@ -118,14 +118,14 @@ bool SequentialFitDialog::addWorkspaces(const QStringList wsNames)
 
 void SequentialFitDialog::addFile()
 {
-  QFileDialog dlg(this);
+  QFileDialog dlg(this);
   dlg.setFileMode(QFileDialog::ExistingFiles);
-  const std::vector<std::string>& searchDirs =
-    Mantid::Kernel::ConfigService::Instance().getDataSearchDirs();
-  QString dir;
-  if ( searchDirs.size() == 0 )
-  {
-    dir = "";
+  const std::vector<std::string>& searchDirs =
+    Mantid::Kernel::ConfigService::Instance().getDataSearchDirs();
+  QString dir;
+  if ( searchDirs.size() == 0 )
+  {
+    dir = "";
   }
   else
   {
@@ -174,132 +174,132 @@ void SequentialFitDialog::removeItem()
 
 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;
-      logNames << QString::fromStdString(logs[i]->name());
-    }
-    int n = ui.cbLogValue->count();
-    // if the ws has no logs - do not include it
-    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
-      QStringList namesToRemove;
-      for(int i=0;i<n;++i)
-      {
-        QString name = ui.cbLogValue->itemText(i);
-        if (!logNames.contains(name))
-        {
-          namesToRemove << name;
-        }
-      }
-      foreach(QString name,namesToRemove)
-      {
-        int i = ui.cbLogValue->findText(name);
-        if (i >= 0)
-        {
-          ui.cbLogValue->removeItem(i);
-        }
-      }
-      if (ui.cbLogValue->count() == 0)
-      {
-        QMessageBox::warning(m_fitBrowser->m_appWindow,"MantidPlot - Warning","The list of the log names is empty:\n"
-          "The selected workspaces do not have common logs");
-        return false;
-      }
-    }
-  }
-  return true;
+  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;
+      logNames << QString::fromStdString(logs[i]->name());
+    }
+    int n = ui.cbLogValue->count();
+    // if the ws has no logs - do not include it
+    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
+      QStringList namesToRemove;
+      for(int i=0;i<n;++i)
+      {
+        QString name = ui.cbLogValue->itemText(i);
+        if (!logNames.contains(name))
+        {
+          namesToRemove << name;
+        }
+      }
+      foreach(QString name,namesToRemove)
+      {
+        int i = ui.cbLogValue->findText(name);
+        if (i >= 0)
+        {
+          ui.cbLogValue->removeItem(i);
+        }
+      }
+      if (ui.cbLogValue->count() == 0)
+      {
+        QMessageBox::warning(m_fitBrowser->m_appWindow,"MantidPlot - Warning","The list of the log names is empty:\n"
+          "The selected workspaces do not have common logs");
+        return false;
+      }
+    }
+  }
+  return true;
 }
 
 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();
-    // check name whether it's a file or workspace in order to decide which number to use:
-    // spectrum (for files) or workspace index (for workspaces)
-    int j = 3;
-    QString prefx;
-    QTableWidgetItem* item = ui.tWorkspaces->item(i,3);
-    bool isFile = !item || item->flags().testFlag(Qt::ItemIsEnabled) == false;
-    if (ui.ckbLogPlot->isChecked())
-    {// plot against logs
-      if (isFile)
-      {
-        j = 2;
-        prefx = "sp";
-      }
-      else
-      {
-        prefx = "i";
-      }
-    }
-    else
-    {// plot against axis values
-      prefx = "v";
-      j = 2;
-    }
-    QString index = ui.tWorkspaces->model()->data(ui.tWorkspaces->model()->index(i,j)).toString();
-    QString parStr = name + "," + prefx + index;
-    if (isFile)
-    {// 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)
-  {
-    funStr = *m_fitBrowser->m_compositeFunction;
-  }
-  else
-  {
-    funStr = *(m_fitBrowser->m_compositeFunction->getFunction(0));
-  }
-
-  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);
-  if (ui.ckbLogPlot->isChecked())
-  {
-    std::string logName = ui.cbLogValue->currentText().toStdString();
-    alg->setPropertyValue("LogValue",logName);
-  }
-  alg->setPropertyValue("Minimizer",m_fitBrowser->minimizer());
-  alg->setPropertyValue("CostFunction",m_fitBrowser->costFunction());
-  if (ui.rbIndividual->isChecked())
-  {
-    alg->setPropertyValue("FitType","Individual");
-  }
-
-  observeFinish(alg);
-  alg->executeAsync();
+  QStringList inputStr;
+  for(int i=0;i<ui.tWorkspaces->rowCount();++i)
+  {
+    QString name = ui.tWorkspaces->model()->data(ui.tWorkspaces->model()->index(i,0)).toString();
+    // check name whether it's a file or workspace in order to decide which number to use:
+    // spectrum (for files) or workspace index (for workspaces)
+    int j = 3;
+    QString prefx;
+    QTableWidgetItem* item = ui.tWorkspaces->item(i,3);
+    bool isFile = !item || item->flags().testFlag(Qt::ItemIsEnabled) == false;
+    if (ui.ckbLogPlot->isChecked())
+    {// plot against logs
+      if (isFile)
+      {
+        j = 2;
+        prefx = "sp";
+      }
+      else
+      {
+        prefx = "i";
+      }
+    }
+    else
+    {// plot against axis values
+      prefx = "v";
+      j = 2;
+    }
+    QString index = ui.tWorkspaces->model()->data(ui.tWorkspaces->model()->index(i,j)).toString();
+    QString parStr = name + "," + prefx + index;
+    if (isFile)
+    {// 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)
+  {
+    funStr = *m_fitBrowser->m_compositeFunction;
+  }
+  else
+  {
+    funStr = *(m_fitBrowser->m_compositeFunction->getFunction(0));
+  }
+
+  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);
+  if (ui.ckbLogPlot->isChecked())
+  {
+    std::string logName = ui.cbLogValue->currentText().toStdString();
+    alg->setPropertyValue("LogValue",logName);
+  }
+  alg->setPropertyValue("Minimizer",m_fitBrowser->minimizer());
+  alg->setPropertyValue("CostFunction",m_fitBrowser->costFunction());
+  if (ui.rbIndividual->isChecked())
+  {
+    alg->setPropertyValue("FitType","Individual");
+  }
+
+  observeFinish(alg);
+  alg->executeAsync();
   QDialog::accept();
 }
 
@@ -319,7 +319,7 @@ void SequentialFitDialog::functionChanged()
   populateParameters();
 }
 
-
+
 void SequentialFitDialog::finishHandle(const Mantid::API::IAlgorithm* alg)
 {
   (void) alg; //Avoid unused warning
@@ -328,35 +328,35 @@ void SequentialFitDialog::finishHandle(const Mantid::API::IAlgorithm* alg)
 
 void SequentialFitDialog::showPlot()
 {
-  std::string wsName = m_fitBrowser->outputName();
-  Mantid::API::ITableWorkspace_sptr ws = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(
-    Mantid::API::AnalysisDataService::Instance().retrieve(wsName) );
-  if (ws)
-  {
-    if ((ws->columnCount() - 1)/2 != m_fitBrowser->compositeFunction()->nParams()) return;
-    Table *t = m_fitBrowser->m_appWindow->mantidUI->importTableWorkspace(QString::fromStdString(wsName));
-    if (!t) return;
-    QString parName;
-    if (m_fitBrowser->compositeFunction()->nFunctions() == 1)
-    {
-      int i = m_fitBrowser->compositeFunction()->parameterIndex(ui.cbParameter->currentText().toStdString());
-      parName = QString::fromStdString(m_fitBrowser->compositeFunction()->getFunction(0)->parameterName(i));
-    }
-    else
-    {
-      parName = ui.cbParameter->currentText();
-    }
-    QStringList colNames;
-    colNames << t->name() + "_" + parName << t->name() + "_" + parName + "_Err";
-    MultiLayer* ml = m_fitBrowser->m_appWindow->multilayerPlot(t,colNames,ui.cbCurveType->currentIndex());
-    Graph* g = ml->activeGraph();
-    if (g)
-    {
-      g->setXAxisTitle(ui.cbLogValue->currentText());
-      g->setYAxisTitle(parName);
-      g->setTitle("");
-    }
-  }
+  std::string wsName = m_fitBrowser->outputName();
+  Mantid::API::ITableWorkspace_sptr ws = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>(
+    Mantid::API::AnalysisDataService::Instance().retrieve(wsName) );
+  if (ws)
+  {
+    if ((ws->columnCount() - 1)/2 != m_fitBrowser->compositeFunction()->nParams()) return;
+    Table *t = m_fitBrowser->m_appWindow->mantidUI->importTableWorkspace(QString::fromStdString(wsName));
+    if (!t) return;
+    QString parName;
+    if (m_fitBrowser->compositeFunction()->nFunctions() == 1)
+    {
+      int i = m_fitBrowser->compositeFunction()->parameterIndex(ui.cbParameter->currentText().toStdString());
+      parName = QString::fromStdString(m_fitBrowser->compositeFunction()->getFunction(0)->parameterName(i));
+    }
+    else
+    {
+      parName = ui.cbParameter->currentText();
+    }
+    QStringList colNames;
+    colNames << t->name() + "_" + parName << t->name() + "_" + parName + "_Err";
+    MultiLayer* ml = m_fitBrowser->m_appWindow->multilayerPlot(t,colNames,ui.cbCurveType->currentIndex());
+    Graph* g = ml->activeGraph();
+    if (g)
+    {
+      g->setXAxisTitle(ui.cbLogValue->currentText());
+      g->setYAxisTitle(parName);
+      g->setTitle("");
+    }
+  }
 }
 
 void SequentialFitDialog::helpClicked()
@@ -379,18 +379,18 @@ void SequentialFitDialog::spectraChanged(int row,int col)
   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
-    {
-      ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-             Mantid::API::AnalysisDataService::Instance().retrieve(name.toStdString())
-           );
-    }
-    catch(...)
-    {// 
-      return;
-    }
-    if (!ws) return;
+    Mantid::API::MatrixWorkspace_sptr ws;
+    try
+    {
+      ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+             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);
@@ -497,18 +497,18 @@ void SequentialFitDialog::plotAgainstLog(bool yes)
     ui.tWorkspaces->horizontalHeaderItem(2)->setData(Qt::DisplayRole,"Range");
     for(int row = 0; row < rowCount(); ++row)
     {
-      Mantid::API::MatrixWorkspace_sptr ws;
-      try
-      {
-        ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
-          Mantid::API::AnalysisDataService::Instance().retrieve(name(row).toStdString())
-          );
-      }
-      catch(...)
-      {// 
-        continue;
-      }
-      if (!ws) continue;
+      Mantid::API::MatrixWorkspace_sptr ws;
+      try
+      {
+        ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
+          Mantid::API::AnalysisDataService::Instance().retrieve(name(row).toStdString())
+          );
+      }
+      catch(...)
+      {// 
+        continue;
+      }
+      if (!ws) continue;
       Mantid::API::Axis* y = ws->getAxis(1);
       setRange(row,(*y)(0),(*y)(y->length()-1));
     }
diff --git a/Code/Mantid/MantidPlot/src/Mantid/SequentialFitDialog.h b/Code/Mantid/MantidPlot/src/Mantid/SequentialFitDialog.h
index 6b022f492177a1ebb035ef0a6eb8ea48364246ba..51001207b0cbd589db97b248b56e085f5237c8e6 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/SequentialFitDialog.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/SequentialFitDialog.h
@@ -1,19 +1,19 @@
-#ifndef SEQUENTIALFITDIALOG_H
-#define SEQUENTIALFITDIALOG_H
-
-//----------------------------
-//   Includes
-//----------------------------
-
-#include "ui_SequentialFitDialog.h"
-#include "MantidAPI/AlgorithmObserver.h"
-
-//----------------------------
-//   Forward declarations
-//----------------------------
-
-class FitPropertyBrowser;
-
+#ifndef SEQUENTIALFITDIALOG_H
+#define SEQUENTIALFITDIALOG_H
+
+//----------------------------
+//   Includes
+//----------------------------
+
+#include "ui_SequentialFitDialog.h"
+#include "MantidAPI/AlgorithmObserver.h"
+
+//----------------------------
+//   Forward declarations
+//----------------------------
+
+class FitPropertyBrowser;
+
 /** 
     This is a dialog for doing sequential fit.
     (Calls algorithm PlotPeakByLogValue)
@@ -101,7 +101,7 @@ private:
   /// Populate parameter combo box with possible parameter names
   void populateParameters();
 
-  /// Called when the fit is finished
+  /// Called when the fit is finished
   void finishHandle(const Mantid::API::IAlgorithm* alg);
 
   /// set spectrum value for workspace/file in row row
@@ -121,5 +121,5 @@ private:
 };
 
 
-
-#endif /* SEQUENTIALFITDIALOG_H */
+
+#endif /* SEQUENTIALFITDIALOG_H */
diff --git a/Code/Mantid/MantidPlot/src/Mantid/UserFitFunctionDialog.cpp b/Code/Mantid/MantidPlot/src/Mantid/UserFitFunctionDialog.cpp
index 13e6e6347297e476d1a5e0579ae729ed485c94e3..e45583bc5597ae7ba6dfccb76c23762ded6fa444 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/UserFitFunctionDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/Mantid/UserFitFunctionDialog.cpp
@@ -1,14 +1,14 @@
 //---------------------------------------
 // Includes
 //---------------------------------------
-
-#include "UserFitFunctionDialog.h"
-#include <muParser.h>
-#include <qcheckbox.h>
-#include <qmessagebox.h>
-#include <qheaderview.h>
-#include <iostream>
-
+
+#include "UserFitFunctionDialog.h"
+#include <muParser.h>
+#include <qcheckbox.h>
+#include <qmessagebox.h>
+#include <qheaderview.h>
+#include <iostream>
+
 //---------------------------------------
 // Public member functions
 //---------------------------------------
diff --git a/Code/Mantid/MantidPlot/src/Mantid/UserFitFunctionDialog.h b/Code/Mantid/MantidPlot/src/Mantid/UserFitFunctionDialog.h
index c42a647b63af8dbcbf71ce33f187f26be0588b26..76ab57ae132d622a77aa535be2502b9c7d5b7610 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/UserFitFunctionDialog.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/UserFitFunctionDialog.h
@@ -1,22 +1,22 @@
-#ifndef USERFITFUNCTIONDIALOG_H
-#define USERFITFUNCTIONDIALOG_H
-
-//----------------------------
-//   Includes
-//----------------------------
-
-#include <qdialog.h>
-#include <qcheckbox.h>
-#include <qlineedit.h>
-#include <boost/shared_ptr.hpp>
-#include "ui_UserFitFunctionDialog.h"
-
-//----------------------------
-//   Forward declarations
-//----------------------------
-
-class MantidUI;
-
+#ifndef USERFITFUNCTIONDIALOG_H
+#define USERFITFUNCTIONDIALOG_H
+
+//----------------------------
+//   Includes
+//----------------------------
+
+#include <qdialog.h>
+#include <qcheckbox.h>
+#include <qlineedit.h>
+#include <boost/shared_ptr.hpp>
+#include "ui_UserFitFunctionDialog.h"
+
+//----------------------------
+//   Forward declarations
+//----------------------------
+
+class MantidUI;
+
 /** 
     This is a dialog for constructing fitting functions.
 
@@ -86,5 +86,5 @@ private:
 };
 
 
-
+
 #endif /* USERFITFUNCTIONDIALOG_H */
\ No newline at end of file
diff --git a/Code/Mantid/MantidPlot/src/Mantid/WorkspaceObserver.h b/Code/Mantid/MantidPlot/src/Mantid/WorkspaceObserver.h
index ed0786d6a53b29c30ec528129ef3a01a5fb85b02..9c3dd0ff6842a759e8c5095b7515e47851915fc8 100644
--- a/Code/Mantid/MantidPlot/src/Mantid/WorkspaceObserver.h
+++ b/Code/Mantid/MantidPlot/src/Mantid/WorkspaceObserver.h
@@ -1,5 +1,5 @@
-#ifndef WORKSPACE_OBSERVER_H
-#define WORKSPACE_OBSERVER_H
+#ifndef WORKSPACE_OBSERVER_H
+#define WORKSPACE_OBSERVER_H
 
 #include "MantidAPI/AnalysisDataService.h"
 #include <Poco/NObserver.h>
@@ -10,9 +10,9 @@
 //------------------------------------------------
 class WorkspaceObserver;
 
-#ifndef IGNORE_WORKSPACE_OBSERVER_ARGUMENT
-#define IGNORE_WORKSPACE_OBSERVER_ARGUMENT(x)
-#endif
+#ifndef IGNORE_WORKSPACE_OBSERVER_ARGUMENT
+#define IGNORE_WORKSPACE_OBSERVER_ARGUMENT(x)
+#endif
 /**
  * A simple callback class so that we avoid multiple inheritance issues with QObject.
  * 
@@ -54,34 +54,34 @@ private:
   WorkspaceObserver *m_observer;
 };
 
-/** @class WorkspaceObserver 
-
- Observes AnalysisDataService notifications: add,replace,delete.
- Hides Poco::Notification API from the user. 
-
- @author Roman Tolchenov, Tessella plc
+/** @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
-
- 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>.
- Code Documentation is available at: <http://doxygen.mantidproject.org>
- */
+
+ Copyright &copy; 2007-8 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>.
+ Code Documentation is available at: <http://doxygen.mantidproject.org>
+ */
 class WorkspaceObserver
 {
 
@@ -154,8 +154,8 @@ protected:
         @param wsName :: The name of the deleted workspace.
         @param ws :: The shared pointer to the workspace to be deleted.
     */
-  virtual void deleteHandle(const std::string& IGNORE_WORKSPACE_OBSERVER_ARGUMENT(wsName),
-                            const boost::shared_ptr<Mantid::API::Workspace> IGNORE_WORKSPACE_OBSERVER_ARGUMENT(ws))
+  virtual void deleteHandle(const std::string& IGNORE_WORKSPACE_OBSERVER_ARGUMENT(wsName),
+                            const boost::shared_ptr<Mantid::API::Workspace> IGNORE_WORKSPACE_OBSERVER_ARGUMENT(ws))
   {
   }
     /** Handler of the AfterReplace notifications. Could be overriden in inherited classes.
@@ -212,4 +212,4 @@ private:
 };
 
 
-#endif
+#endif
diff --git a/Code/Mantid/MantidPlot/src/Matrix.cpp b/Code/Mantid/MantidPlot/src/Matrix.cpp
index bed0dc15d4a93b135020ae47cb1634928e008f74..46b4977088069426ef5286d02f151601d361ada5 100644
--- a/Code/Mantid/MantidPlot/src/Matrix.cpp
+++ b/Code/Mantid/MantidPlot/src/Matrix.cpp
@@ -26,11 +26,11 @@
  *   Boston, MA  02110-1301  USA                                           *
  *                                                                         *
  ***************************************************************************/
-#include "Matrix.h"
+#include "Matrix.h"
 #include "MatrixCommand.h"
-#include "Graph.h"
+#include "Graph.h"
 #include "ApplicationWindow.h"
-#include "muParserScript.h"
+#include "muParserScript.h"
 #include "ScriptingEnv.h"
 #include "pixmaps.h"
 
@@ -52,11 +52,11 @@
 #include <QLocale>
 #include <QItemDelegate>
 #include <QLabel>
-#include <QStackedWidget>
+#include <QStackedWidget>
 #include <QImageWriter>
 #include <QSvgGenerator>
 #include <QFile>
-#include <QUndoStack>
+#include <QUndoStack>
 
 #include <stdlib.h>
 #include <stdio.h>
@@ -70,7 +70,7 @@ Matrix::Matrix(ScriptingEnv *env, const QString& label, ApplicationWindow* paren
   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(label, parent, name, f), Scripted(env)
 {
@@ -78,72 +78,72 @@ Matrix::Matrix(ScriptingEnv *env, int r, int c, const QString& label, Applicatio
   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(label, parent, name, f), Scripted(env)
-{
+
+Matrix::Matrix(ScriptingEnv *env, const QImage& image, const QString& label, ApplicationWindow* parent, const QString& name, Qt::WFlags f)
+: MdiSubWindow(label, parent, name, f), Scripted(env)
+{
   m_bk_color = QColor(255, 255, 128);
   m_matrix_icon = getQPixmap("matrix_xpm");
-  initImage(image);
-}
-
-void Matrix::initGlobals()
-{
-  d_workspace = NULL;
-  d_table_view = NULL;
-  imageLabel = NULL;
-
-  d_header_view_type = ColumnRow;
+  initImage(image);
+}
+
+void Matrix::initGlobals()
+{
+  d_workspace = NULL;
+  d_table_view = NULL;
+  imageLabel = NULL;
+
+  d_header_view_type = ColumnRow;
   d_color_map_type = GrayScale;
-  d_color_map = QwtLinearColorMap(Qt::black, Qt::white);
-  d_column_width = 100;
-
-  formula_str = "";
-  txt_format = 'f';
-  num_precision = 6;
-  x_start = 1.0;
-  x_end = 10.0;
-  y_start = 1.0;
-  y_end = 10.0;
-
-  d_stack = new QStackedWidget();
-  d_stack->setFocusPolicy(Qt::StrongFocus);
-  setWidget(d_stack);
-
-  d_undo_stack = new QUndoStack();
+  d_color_map = QwtLinearColorMap(Qt::black, Qt::white);
+  d_column_width = 100;
+
+  formula_str = "";
+  txt_format = 'f';
+  num_precision = 6;
+  x_start = 1.0;
+  x_end = 10.0;
+  y_start = 1.0;
+  y_end = 10.0;
+
+  d_stack = new QStackedWidget();
+  d_stack->setFocusPolicy(Qt::StrongFocus);
+  setWidget(d_stack);
+
+  d_undo_stack = new QUndoStack();
   d_undo_stack->setUndoLimit(applicationWindow()->matrixUndoStackSize());
-}
-
-void Matrix::initTable(int rows, int cols)
-{
-  initGlobals();
-  d_view_type = TableView;
-
-  d_matrix_model = new MatrixModel(rows, cols, this);
-  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));
-}
-
-void Matrix::initImage(const QImage& image)
-{
-  initGlobals();
-  d_view_type = ImageView;
-
-  d_matrix_model = new MatrixModel(image, this);
-  initImageView();
-
-  int w = image.width();
-  int h = image.height();
+}
+
+void Matrix::initTable(int rows, int cols)
+{
+  initGlobals();
+  d_view_type = TableView;
+
+  d_matrix_model = new MatrixModel(rows, cols, this);
+  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));
+}
+
+void Matrix::initImage(const QImage& image)
+{
+  initGlobals();
+  d_view_type = ImageView;
+
+  d_matrix_model = new MatrixModel(image, this);
+  initImageView();
+
+  int w = image.width();
+  int h = image.height();
   if (w <= 500 && h <= 400){
-    int size = QMAX(w, h);
+    int size = QMAX(w, h);
     imageLabel->resize(size, size);
   } else
     imageLabel->resize(500, 500);
 
-  displayImage(image);
+  displayImage(image);
 }
 
 double Matrix::cell(int row, int col)
@@ -180,25 +180,25 @@ void Matrix::setCoordinates(double xs, double xe, double ys, double ye)
 }
 
 QString Matrix::saveToString(const QString &info, bool saveAsTemplate)
-{
+{
   bool notTemplate = !saveAsTemplate;
-  QString s = "<matrix>\n";
+  QString s = "<matrix>\n";
   if (notTemplate)
     s += QString(objectName()) + "\t";
   s += QString::number(numRows())+"\t";
-  s += QString::number(numCols())+"\t";
+  s += QString::number(numCols())+"\t";
   if (notTemplate)
     s += birthDate() + "\n";
   s += info;
   s += "ColWidth\t" + QString::number(d_column_width)+"\n";
   s += "<formula>\n" + formula_str + "\n</formula>\n";
-  s += "TextFormat\t" + QString(txt_format) + "\t" + QString::number(num_precision) + "\n";
+  s += "TextFormat\t" + QString(txt_format) + "\t" + QString::number(num_precision) + "\n";
   if (notTemplate)
     s += "WindowLabel\t" + windowLabel() + "\t" + QString::number(captionPolicy()) + "\n";
   s += "Coordinates\t" + QString::number(x_start,'g',15) + "\t" +QString::number(x_end,'g',15) + "\t";
   s += QString::number(y_start,'g',15) + "\t" + QString::number(y_end,'g',15) + "\n";
   s += "ViewType\t" + QString::number((int)d_view_type) + "\n";
-  s += "HeaderViewType\t" + QString::number((int)d_header_view_type) + "\n";
+  s += "HeaderViewType\t" + QString::number((int)d_header_view_type) + "\n";
 
   if (d_color_map_type != Custom)
     s += "ColorPolicy\t" + QString::number(d_color_map_type) + "\n";
@@ -217,7 +217,7 @@ QString Matrix::saveToString(const QString &info, bool saveAsTemplate)
     }
     s += "</ColorMap>\n";
   }
-
+
   if (notTemplate)
     s += d_matrix_model->saveToString();
   s +="</matrix>\n";
@@ -225,7 +225,7 @@ QString Matrix::saveToString(const QString &info, bool saveAsTemplate)
 }
 
 QString Matrix::saveAsTemplate(const QString &info)
-{
+{
   return saveToString(info, true);
 }
 
@@ -257,34 +257,34 @@ void Matrix::restore(const QStringList &lst)
   x_start = l[1].toDouble();
   x_end = l[2].toDouble();
   y_start = l[3].toDouble();
-  y_end = l[4].toDouble();
-
-  l = (*i++).split("\t");
-  d_view_type = (Matrix::ViewType)l[1].toInt();
-  l = (*i++).split("\t");
-  d_header_view_type = (Matrix::HeaderViewType)l[1].toInt();
-  l = (*i++).split("\t");
-  d_color_map_type = (Matrix::ColorMapType)l[1].toInt();
-
-  if (lst.contains ("<ColorMap>")){
-    QStringList aux;
-    while (*i != "</ColorMap>"){
-      aux << *i;
-      i++;
-    }
-    setColorMap(aux);
-  }
-
-  if (d_view_type == ImageView){
-    if (d_table_view)
-      delete d_table_view;
-    if (d_select_all_shortcut)
-      delete d_select_all_shortcut;
-    initImageView();
-    d_stack->setCurrentWidget(imageLabel);
-    if (d_color_map_type == Rainbow)
-      setRainbowColorMap();
-  }
+  y_end = l[4].toDouble();
+
+  l = (*i++).split("\t");
+  d_view_type = (Matrix::ViewType)l[1].toInt();
+  l = (*i++).split("\t");
+  d_header_view_type = (Matrix::HeaderViewType)l[1].toInt();
+  l = (*i++).split("\t");
+  d_color_map_type = (Matrix::ColorMapType)l[1].toInt();
+
+  if (lst.contains ("<ColorMap>")){
+    QStringList aux;
+    while (*i != "</ColorMap>"){
+      aux << *i;
+      i++;
+    }
+    setColorMap(aux);
+  }
+
+  if (d_view_type == ImageView){
+    if (d_table_view)
+      delete d_table_view;
+    if (d_select_all_shortcut)
+      delete d_select_all_shortcut;
+    initImageView();
+    d_stack->setCurrentWidget(imageLabel);
+    if (d_color_map_type == Rainbow)
+      setRainbowColorMap();
+  }
   resetView();
 }
 
@@ -311,15 +311,15 @@ void Matrix::setColumnsWidth(int width)
 {
   if (d_column_width == width)
     return;
-
-  d_column_width = width;
+
+  d_column_width = width;
   d_table_view->horizontalHeader()->setDefaultSectionSize(d_column_width);
-
-  if (d_view_type == TableView){
-    int cols = numCols();
-    for(int i=0; i<cols; i++)
-      d_table_view->setColumnWidth(i, width);
-  }
+
+  if (d_view_type == TableView){
+    int cols = numCols();
+    for(int i=0; i<cols; i++)
+      d_table_view->setColumnWidth(i, width);
+  }
 
   emit modifiedWindow(this);
 }
@@ -338,7 +338,7 @@ void Matrix::setDimensions(int rows, int cols)
     return;
 
   double *buffer = d_matrix_model->dataCopy();
-  if (buffer)
+  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()){
@@ -454,7 +454,7 @@ void Matrix::rotate90(bool clockwise)
     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�")));
-}
+}
 
 bool Matrix::canCalculate(bool useMuParser)
 {
@@ -510,8 +510,8 @@ 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){
@@ -524,7 +524,7 @@ bool Matrix::muParserCalculate(int startRow, int endRow, int startCol, int endCo
     emit modifiedWindow(this);
     return true;
   }
-  return false;
+  return false;
 }
 
 bool Matrix::calculate(int startRow, int endRow, int startCol, int endCol, bool forceMuParser)
@@ -547,9 +547,9 @@ bool Matrix::calculate(int startRow, int endRow, int startCol, int endCol, bool
 }
 
 void Matrix::clearSelection()
-{
-  if (d_view_type == ImageView)
-    return;
+{
+  if (d_view_type == ImageView)
+    return;
 
   QItemSelectionModel *selModel = d_table_view->selectionModel();
   if (!selModel || !selModel->hasSelection())
@@ -571,9 +571,9 @@ void Matrix::clearSelection()
 }
 
 void Matrix::copySelection()
-{
-  if (d_view_type == ImageView)
-    return;
+{
+  if (d_view_type == ImageView)
+    return;
 
   QItemSelectionModel *selModel = d_table_view->selectionModel();
   QString s = "";
@@ -603,9 +603,9 @@ void Matrix::copySelection()
 }
 
 void Matrix::pasteSelection()
-{
-  if (d_view_type == ImageView)
-    return;
+{
+  if (d_view_type == ImageView)
+    return;
 
   QString text = QApplication::clipboard()->text();
   if (text.isEmpty())
@@ -657,9 +657,9 @@ void Matrix::pasteSelection()
     QStringList cells = linesList[i].split("\t");
     int size = cells.count();
     for(int j = 0; j<cols; j++){
-      if (j >= size){
+      if (j >= size){
         clipboardBuffer[cell++] = GSL_NAN;
-        continue;
+        continue;
       }
       bool numeric = true;
       double value = locale.toDouble(cells[j], &numeric);
@@ -707,17 +707,17 @@ 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)));
-    emit modifiedWindow(this);
-  } else if (ignoreUndo()){
-    d_matrix_model->removeRows(startRow, count);
-    d_table_view->reset();
-    emit modifiedWindow(this);
+    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)));
+    emit modifiedWindow(this);
+  } else if (ignoreUndo()){
+    d_matrix_model->removeRows(startRow, count);
+    d_table_view->reset();
+    emit modifiedWindow(this);
   }
 }
 
@@ -739,16 +739,16 @@ 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)));
-    emit modifiedWindow(this);
-  } else if (ignoreUndo()){
-    d_matrix_model->removeColumns(startCol, count);
-    d_table_view->reset();
-    emit modifiedWindow(this);
+
+  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()){
+    d_matrix_model->removeColumns(startCol, count);
+    d_table_view->reset();
+    emit modifiedWindow(this);
   }
 }
 
@@ -791,14 +791,14 @@ void Matrix::insertRow()
   QModelIndex index = selModel->currentIndex();
   if (!index.isValid())
     return;
-
-  if (!d_matrix_model->canResize(numRows() + 1, numCols()))
-    return;
+
+  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_table_view->reset();
-  emit modifiedWindow(this);
+  emit modifiedWindow(this);
 }
 
 void Matrix::insertColumn()
@@ -810,14 +810,14 @@ void Matrix::insertColumn()
   QModelIndex index = selModel->currentIndex();
   if (!index.isValid())
     return;
-
-  if (!d_matrix_model->canResize(numRows(), numCols() + 1))
-    return;
+
+  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_table_view->reset();
-  emit modifiedWindow(this);
+  emit modifiedWindow(this);
 }
 
 void Matrix::customEvent(QEvent *e)
@@ -905,11 +905,11 @@ void Matrix::print(const QString& fileName)
     return; // paint on printer
   int dpiy = printer.logicalDpiY();
   const int margin = (int) ( (1/2.54)*dpiy ); // 1 cm margins
-
-  if (d_view_type == ImageView){
-    p.drawImage (printer.pageRect(), d_matrix_model->renderImage());
-    return;
-  }
+
+  if (d_view_type == ImageView){
+    p.drawImage (printer.pageRect(), d_matrix_model->renderImage());
+    return;
+  }
 
   QHeaderView *vHeader = d_table_view->verticalHeader();
 
@@ -982,73 +982,73 @@ void Matrix::print(const QString& fileName)
     }
   }
 }
-
-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!"));
-    return;
-  }
-
-  QPrinter printer;
-  printer.setCreator("MantidPlot");
-  printer.setFullPage(true);
-  if (res)
-    printer.setResolution(res);
-
-  printer.setOutputFileName(fileName);
-  if (fileName.contains(".eps"))
-    printer.setOutputFormat(QPrinter::PostScriptFormat);
-
-  if (color)
-    printer.setColorMode(QPrinter::Color);
-  else
-    printer.setColorMode(QPrinter::GrayScale);
-
-  int cols = numCols();
-  int rows = numRows();
-  QRect rect = QRect(0, 0, cols, rows);
-  if (pageSize == QPrinter::Custom)
-    printer.setPageSize(Graph::minPageSize(printer, rect));
-  else
-    printer.setPageSize(pageSize);
-
-  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 = int(height*aspect);
-      int x = (printer.width()- width)/2;
-      rect = QRect(x, margin, width, height);
-    } else if (aspect >= page_aspect){
-      int margin = (int) ((0.1/2.54)*printer.logicalDpiX()); // 1 mm margins
-      int width = printer.width() - 2*margin;
-      int height = 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;
-    rect = QRect(x_margin, y_margin, width, height);
-  }
-
-  QPainter paint(&printer);
-  paint.drawImage(rect, d_matrix_model->renderImage());
-  paint.end();
-}
+
+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!"));
+    return;
+  }
+
+  QPrinter printer;
+  printer.setCreator("MantidPlot");
+  printer.setFullPage(true);
+  if (res)
+    printer.setResolution(res);
+
+  printer.setOutputFileName(fileName);
+  if (fileName.contains(".eps"))
+    printer.setOutputFormat(QPrinter::PostScriptFormat);
+
+  if (color)
+    printer.setColorMode(QPrinter::Color);
+  else
+    printer.setColorMode(QPrinter::GrayScale);
+
+  int cols = numCols();
+  int rows = numRows();
+  QRect rect = QRect(0, 0, cols, rows);
+  if (pageSize == QPrinter::Custom)
+    printer.setPageSize(Graph::minPageSize(printer, rect));
+  else
+    printer.setPageSize(pageSize);
+
+  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 = int(height*aspect);
+      int x = (printer.width()- width)/2;
+      rect = QRect(x, margin, width, height);
+    } else if (aspect >= page_aspect){
+      int margin = (int) ((0.1/2.54)*printer.logicalDpiX()); // 1 mm margins
+      int width = printer.width() - 2*margin;
+      int height = 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;
+    rect = QRect(x_margin, y_margin, width, height);
+  }
+
+  QPainter paint(&printer);
+  paint.drawImage(rect, d_matrix_model->renderImage());
+  paint.end();
+}
 
 void Matrix::range(double *min, double *max)
 {
@@ -1083,10 +1083,10 @@ double** Matrix::allocateMatrixData(int rows, int columns)
 
   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);
+    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!"));
@@ -1108,23 +1108,23 @@ void Matrix::goToRow(int row)
 {
   if(row < 1 || row > numRows())
     return;
-
-  if (d_view_type == ImageView)
+
+  if (d_view_type == ImageView)
     d_undo_stack->push(new MatrixSetViewCommand(this, d_view_type, TableView, tr("Set Data Mode")));
-  d_table_view->selectRow(row - 1);
+  d_table_view->selectRow(row - 1);
   d_table_view->scrollTo(d_matrix_model->index(row - 1, 0), QAbstractItemView::PositionAtTop);
 }
-
-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_table_view->selectColumn(col - 1);
-  d_table_view->scrollTo(d_matrix_model->index(0, col - 1), QAbstractItemView::PositionAtCenter);
-}
+
+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_table_view->selectColumn(col - 1);
+  d_table_view->scrollTo(d_matrix_model->index(0, col - 1), QAbstractItemView::PositionAtCenter);
+}
 
 void Matrix::moveCell(const QModelIndex& index)
 {
@@ -1138,10 +1138,10 @@ void Matrix::copy(Matrix *m)
 {
   if (!m)
     return;
-
-  MatrixModel *mModel = m->matrixModel();
-  if (!mModel)
-    return;
+
+  MatrixModel *mModel = m->matrixModel();
+  if (!mModel)
+    return;
 
   x_start = m->xStart();
   x_end = m->xEnd();
@@ -1150,36 +1150,36 @@ void Matrix::copy(Matrix *m)
 
   int rows = numRows();
   int cols = numCols();
-
-  txt_format = m->textFormat();
-  num_precision = m->precision();
-
-  double *data = d_matrix_model->dataVector();
-  double *m_data = mModel->dataVector();
+
+  txt_format = m->textFormat();
+  num_precision = m->precision();
+
+  double *data = d_matrix_model->dataVector();
+  double *m_data = mModel->dataVector();
   int size = rows*cols;
   for (int i=0; i<size; i++)
     data[i] = m_data[i];
-
-  d_header_view_type = m->headerViewType();
+
+  d_header_view_type = m->headerViewType();
   d_view_type = m->viewType();
   setColumnsWidth(m->columnsWidth());
-  formula_str = m->formula();
-  d_color_map_type = m->colorMapType();
-  d_color_map = m->colorMap();
-
-  if (d_view_type == ImageView){
-    if (d_table_view)
-      delete d_table_view;
-    if (d_select_all_shortcut)
-      delete d_select_all_shortcut;
-    initImageView();
-    d_stack->setCurrentWidget(imageLabel);
-  }
-  resetView();
-}
-
-void Matrix::displayImage(const QImage& image)
-{
+  formula_str = m->formula();
+  d_color_map_type = m->colorMapType();
+  d_color_map = m->colorMap();
+
+  if (d_view_type == ImageView){
+    if (d_table_view)
+      delete d_table_view;
+    if (d_select_all_shortcut)
+      delete d_select_all_shortcut;
+    initImageView();
+    d_stack->setCurrentWidget(imageLabel);
+  }
+  resetView();
+}
+
+void Matrix::displayImage(const QImage& image)
+{
   if (!imageLabel)
     return;
 
@@ -1187,9 +1187,9 @@ void Matrix::displayImage(const QImage& image)
   im.fill(0);
   QPainter p(&im);
   p.drawImage(0, 0, image.scaled(imageLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
-  p.end();
-  imageLabel->setPixmap(QPixmap::fromImage(im));
-}
+  p.end();
+  imageLabel->setPixmap(QPixmap::fromImage(im));
+}
 
 void Matrix::setViewType(ViewType type, bool renderImage)
 {
@@ -1198,69 +1198,69 @@ void Matrix::setViewType(ViewType type, bool renderImage)
 
   d_view_type = type;
 
-  if (d_view_type == ImageView){
+  if (d_view_type == ImageView){
     delete d_table_view;
-    delete d_select_all_shortcut;
+    delete d_select_all_shortcut;
     initImageView();
     if (renderImage)
-      displayImage(d_matrix_model->renderImage());
-    d_stack->setCurrentWidget(imageLabel);
+      displayImage(d_matrix_model->renderImage());
+    d_stack->setCurrentWidget(imageLabel);
   } else if (d_view_type == TableView){
-    delete imageLabel;
-    initTableView();
+    delete imageLabel;
+    initTableView();
     d_stack->setCurrentWidget(d_table_view);
   }
   emit modifiedWindow(this);
 }
-
-void Matrix::initImageView()
-{
-  imageLabel = new QLabel();
-  imageLabel->setBackgroundRole(QPalette::Base);
-  imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
-  imageLabel->setScaledContents(true);
+
+void Matrix::initImageView()
+{
+  imageLabel = new QLabel();
+  imageLabel->setBackgroundRole(QPalette::Base);
+  imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
+  imageLabel->setScaledContents(true);
   d_stack->addWidget(imageLabel);
-}
-
-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->setModel(d_matrix_model);
-  d_table_view->setEditTriggers(QAbstractItemView::DoubleClicked);
-  d_table_view->setFocusPolicy(Qt::StrongFocus);
-  d_table_view->setFocus();
-
-  QPalette pal = d_table_view->palette();
-  pal.setColor(QColorGroup::Base, m_bk_color);
-  d_table_view->setPalette(pal);
-
-  // set header properties
-  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++)
-    d_table_view->setColumnWidth(i, d_column_width);
-
-  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()));
-}
+}
+
+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->setModel(d_matrix_model);
+  d_table_view->setEditTriggers(QAbstractItemView::DoubleClicked);
+  d_table_view->setFocusPolicy(Qt::StrongFocus);
+  d_table_view->setFocus();
+
+  QPalette pal = d_table_view->palette();
+  pal.setColor(QColorGroup::Base, m_bk_color);
+  d_table_view->setPalette(pal);
+
+  // set header properties
+  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++)
+    d_table_view->setColumnWidth(i, d_column_width);
+
+  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()));
+}
 
 QImage Matrix::image()
 {
   return d_matrix_model->renderImage();
-}
+}
 
 void Matrix::importImage(const QString& fn)
 {
@@ -1268,40 +1268,40 @@ void Matrix::importImage(const QString& 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 + "\""));
-    setWindowLabel(fn);
-    emit modifiedWindow(this);
-  } else if (ignoreUndo()){
-    d_matrix_model->setImage(image);
-    setViewType(ImageView, false);
-    displayImage(image);
-    setWindowLabel(fn);
-    emit modifiedWindow(this);
+  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 + "\""));
+    setWindowLabel(fn);
+    emit modifiedWindow(this);
+  } else if (ignoreUndo()){
+    d_matrix_model->setImage(image);
+    setViewType(ImageView, false);
+    displayImage(image);
+    setWindowLabel(fn);
+    emit modifiedWindow(this);
   }
 }
 
 void Matrix::setGrayScale()
-{
+{
   d_color_map_type = GrayScale;
-  d_color_map = QwtLinearColorMap(Qt::black, Qt::white);
-  if (d_view_type == ImageView)
+  d_color_map = QwtLinearColorMap(Qt::black, Qt::white);
+  if (d_view_type == ImageView)
     displayImage(d_matrix_model->renderImage());
   emit modifiedWindow(this);
 }
 
 void Matrix::setRainbowColorMap()
-{
-  d_color_map_type = Rainbow;
+{
+  d_color_map_type = Rainbow;
 
   d_color_map = QwtLinearColorMap(Qt::blue, Qt::red);
   d_color_map.addColorStop(0.25, Qt::cyan);
   d_color_map.addColorStop(0.5, Qt::green);
-  d_color_map.addColorStop(0.75, Qt::yellow);
-
-  if (d_view_type == ImageView)
+  d_color_map.addColorStop(0.75, Qt::yellow);
+
+  if (d_view_type == ImageView)
     displayImage(d_matrix_model->renderImage());
   emit modifiedWindow(this);
 }
@@ -1350,46 +1350,46 @@ void Matrix::setColorMapType(ColorMapType mapType)
   else if (d_color_map_type == Rainbow)
     setRainbowColorMap();
 }
-
-void Matrix::resetView()
-{
-  if (d_view_type == ImageView)
-    displayImage(d_matrix_model->renderImage());
-  else if (d_view_type == TableView){
-    d_table_view->horizontalHeader()->setDefaultSectionSize(d_column_width);
-    d_table_view->horizontalHeader()->reset();
-    d_table_view->verticalHeader()->reset();
-    d_table_view->reset();
-    QSize size = this->size();
-    this->resize(QSize(size.width() + 1, size.height()));
-    this->resize(size);
-  }
-}
-
-void Matrix::setHeaderViewType(HeaderViewType type)
-{
-  if (d_header_view_type == type)
-    return;
-
-  d_header_view_type = type;
-
-  if (d_view_type == TableView)
+
+void Matrix::resetView()
+{
+  if (d_view_type == ImageView)
+    displayImage(d_matrix_model->renderImage());
+  else if (d_view_type == TableView){
+    d_table_view->horizontalHeader()->setDefaultSectionSize(d_column_width);
+    d_table_view->horizontalHeader()->reset();
+    d_table_view->verticalHeader()->reset();
+    d_table_view->reset();
+    QSize size = this->size();
+    this->resize(QSize(size.width() + 1, size.height()));
+    this->resize(size);
+  }
+}
+
+void Matrix::setHeaderViewType(HeaderViewType type)
+{
+  if (d_header_view_type == type)
+    return;
+
+  d_header_view_type = type;
+
+  if (d_view_type == TableView)
     resetView();
-  emit modifiedWindow(this);
-}
-
-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);
-
+  emit modifiedWindow(this);
+}
+
+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);
+
   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();
+      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){
@@ -1400,64 +1400,64 @@ void Matrix::fft(bool inverse)
   } else if (ignoreUndo()){
     d_matrix_model->fft(inverse);
     emit modifiedWindow(this);
-  }
-}
-
-bool Matrix::exportASCII(const QString& fname, const QString& separator, bool exportSelection)
-{
-  QFile f(fname);
-  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));
-    return false;
-  }
-
-  int rows = numRows();
-  int cols = numCols();
+  }
+}
+
+bool Matrix::exportASCII(const QString& fname, const QString& separator, bool exportSelection)
+{
+  QFile f(fname);
+  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));
+    return false;
+  }
+
+  int rows = numRows();
+  int cols = numCols();
   QTextStream t( &f );
-  QString eol = applicationWindow()->endOfLine();
-  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){
-      int row = index.row();
-      if (row < topRow)
-        topRow = row;
-      if (row > bottomRow)
-        bottomRow = row;
-
-      int col = index.column();
-      if (col < leftCol)
-        leftCol = col;
-      if (col > rightCol)
-        rightCol = col;
-    }
-
-    for (int i = topRow; i <= bottomRow; i++){
-      for (int j = leftCol; j < rightCol; j++){
+  QString eol = applicationWindow()->endOfLine();
+  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){
+      int row = index.row();
+      if (row < topRow)
+        topRow = row;
+      if (row > bottomRow)
+        bottomRow = row;
+
+      int col = index.column();
+      if (col < leftCol)
+        leftCol = col;
+      if (col > rightCol)
+        rightCol = col;
+    }
+
+    for (int i = topRow; i <= bottomRow; i++){
+      for (int j = leftCol; j < rightCol; j++){
         t << d_matrix_model->text(i, j);
-        t << separator;
-      }
+        t << separator;
+      }
       t << d_matrix_model->text(i, rightCol);
-      t << eol;
-    }
-  } else {
-    for (int i=0; i<rows; i++) {
-      for (int j=0; j<cols-1; j++){
+      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);
         t << separator;
-      }
+      }
       t << d_matrix_model->text(i, cols-1);
-      t << eol;
-    }
-  }
-  f.close();
-  return true;
-}
+      t << eol;
+    }
+  }
+  f.close();
+  return true;
+}
 
 void Matrix::importASCII(const QString &fname, const QString &sep, int ignoredLines,
     bool stripSpaces, bool simplifySpaces, const QString& commentString,
@@ -1482,7 +1482,7 @@ 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((ApplicationWindow *)applicationWindow(),
       tr("MantidPlot") + " - " + tr("Warning"), msg, QMessageBox::Yes, QMessageBox::Cancel));
-}
+}
 
 double* Matrix::initWorkspace(int size)
 {
@@ -1495,9 +1495,9 @@ double* Matrix::initWorkspace(int size)
 
   return d_workspace;
 }
-
-Matrix::~Matrix()
-{
-  delete d_undo_stack;
+
+Matrix::~Matrix()
+{
+  delete d_undo_stack;
   delete d_matrix_model;
 }
diff --git a/Code/Mantid/MantidPlot/src/Matrix.h b/Code/Mantid/MantidPlot/src/Matrix.h
index c47bf1ca5e6fec0d1d60cde42bafd61755f7f2a9..c9c4cbe8b327c139f734597909819e7d51581365 100644
--- a/Code/Mantid/MantidPlot/src/Matrix.h
+++ b/Code/Mantid/MantidPlot/src/Matrix.h
@@ -34,7 +34,7 @@
 #define MATRIX_H
 
 #include <QHeaderView>
-#include <QTableView>
+#include <QTableView>
 #include <QPrinter>
 #include <qpixmap.h>
 #include <QMessageBox>
@@ -52,10 +52,10 @@
 // (maximum) initial matrix size
 #define _Matrix_initial_rows_ 10
 #define _Matrix_initial_columns_ 3
-
+
 class QLabel;
-class QStackedWidget;
-class QShortcut;
+class QStackedWidget;
+class QShortcut;
 class QUndoStack;
 
 //! Matrix worksheet class
@@ -81,11 +81,11 @@ public:
    * @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();
+  Matrix(ScriptingEnv *env, const QImage& image, const QString& label, ApplicationWindow* parent, const QString& name = QString(), Qt::WFlags f=0);
+  ~Matrix();
 
   enum Operation{Transpose, Invert, FlipHorizontally, FlipVertically, RotateClockwise,
-    RotateCounterClockwise, FFT, Clear, Calculate, MuParserCalculate, SetImage, ImportAscii};
+    RotateCounterClockwise, FFT, Clear, Calculate, MuParserCalculate, SetImage, ImportAscii};
   enum HeaderViewType{ColumnRow, XY};
   enum ViewType{TableView, ImageView};
   enum ColorMapType{GrayScale, Rainbow, Custom};
@@ -96,21 +96,21 @@ public:
   };
 
   void setViewType(ViewType, bool renderImage = true);
-  ViewType viewType(){return d_view_type;};
-
-  HeaderViewType headerViewType(){return d_header_view_type;};
-  void setHeaderViewType(HeaderViewType type);
+  ViewType viewType(){return d_view_type;};
+
+  HeaderViewType headerViewType(){return d_header_view_type;};
+  void setHeaderViewType(HeaderViewType type);
 
-  QImage image();
-  void displayImage(const QImage& image);
+  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;};
+  MatrixModel * matrixModel(){return d_matrix_model;};
+  QUndoStack *undoStack(){return d_undo_stack;};
 
   QItemSelectionModel * selectionModel(){return d_table_view->selectionModel();};
 
@@ -134,9 +134,9 @@ public:
 
   virtual void flipVertically();
   virtual void flipHorizontally();
-  void rotate90(bool clockwise = true);
-  void fft(bool inverse = false);
-
+  void rotate90(bool clockwise = true);
+  void fft(bool inverse = false);
+
   ColorMapType colorMapType(){return d_color_map_type;};
   void setColorMapType(ColorMapType mapType);
 
@@ -146,7 +146,7 @@ public:
   void setColorMap(const QStringList& lst);
 
   void setGrayScale();
-  void setRainbowColorMap();
+  void setRainbowColorMap();
   //! Calculate the volume integral
   double integrate();
   //! Calculate the determinant of the matrix
@@ -160,16 +160,16 @@ public:
   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,
+      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);
+  void exportPDF(const QString& fileName);
   //! Print the Matrix
   void print();
   //! Print the Matrix to fileName
@@ -283,8 +283,8 @@ public slots:
   void range(double *min, double *max);
 
   //! Scroll to row (row starts with 1)
-  void goToRow(int row);
-  //! Scroll to column (column starts with 1)
+  void goToRow(int row);
+  //! Scroll to column (column starts with 1)
   void goToColumn(int col);
 
   //! Allocate memory for a matrix buffer
@@ -306,17 +306,17 @@ public slots:
   QColor m_bk_color;
 
   //! Initialize the matrix
-  void initTable(int rows, int cols);
-  void initImage(const QImage& image);
-  void initImageView();
+  void initTable(int rows, int cols);
+  void initImage(const QImage& image);
+  void initImageView();
   void initTableView();
-  void initGlobals();
+  void initGlobals();
   bool ignoreUndo();
   QPixmap m_matrix_icon;
-
+
   //private:
-  QStackedWidget *d_stack;
-  //! Pointer to the table view
+  QStackedWidget *d_stack;
+  //! Pointer to the table view
   QTableView *d_table_view;
   //! Used to display the image view
   QLabel *imageLabel;
@@ -330,19 +330,19 @@ public slots:
   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;
-  //! Keeps track of the header view type;
-  HeaderViewType d_header_view_type;
+  ViewType d_view_type;
+  //! Keeps track of the header view type;
+  HeaderViewType d_header_view_type;
   //! The color map used to display images.
   QwtLinearColorMap d_color_map;
-  //! The color map type.
-  ColorMapType d_color_map_type;
-  //! Column width in pixels;
-  int d_column_width;
-  QShortcut *d_select_all_shortcut;
-  //! Undo/Redo commands stack
+  //! The color map type.
+  ColorMapType d_color_map_type;
+  //! Column width in pixels;
+  int d_column_width;
+  QShortcut *d_select_all_shortcut;
+  //! Undo/Redo commands stack
   QUndoStack *d_undo_stack;
   //! Pointer to a data buffer used for matrix operations.
   double *d_workspace;
diff --git a/Code/Mantid/MantidPlot/src/MatrixCommand.cpp b/Code/Mantid/MantidPlot/src/MatrixCommand.cpp
index 05b7f5f8cded8f4fc38f9e1100f68893cc2932d3..ad603f5f3801df7da4966f39f2b9c451f4bb9f07 100644
--- a/Code/Mantid/MantidPlot/src/MatrixCommand.cpp
+++ b/Code/Mantid/MantidPlot/src/MatrixCommand.cpp
@@ -26,750 +26,750 @@
  *   Boston, MA  02110-1301  USA                                           *
  *                                                                         *
  ***************************************************************************/
-
-#include "MatrixCommand.h"
-#include <QApplication>
-#include <gsl/gsl_math.h>
-
-/*************************************************************************/
-/*           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();
-    }
-}
-
-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);
-}
-
-void MatrixSetFormulaCommand::redo()
-{
-    if (!d_matrix)
-        return;
-
-    d_matrix->setFormula(d_new_formula);
-}
-
-void MatrixSetFormulaCommand::undo()
-{
-    if (!d_matrix)
-        return;
-
-    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);
-}
-
-void MatrixSetViewCommand::redo()
-{
-    if (!d_matrix)
-        return;
-
-    d_matrix->setViewType(d_new_view);
-}
-
-void MatrixSetViewCommand::undo()
-{
-    if (!d_matrix)
-        return;
-
-    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);
-}
-
-void MatrixSetHeaderViewCommand::redo()
-{
-    if (!d_matrix)
-        return;
-
-    d_matrix->setHeaderViewType(d_new_view);
-}
-
-void MatrixSetHeaderViewCommand::undo()
-{
-    if (!d_matrix)
-        return;
-
-    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);
-}
-
-void MatrixSetColWidthCommand::redo()
-{
-    if (!d_matrix)
-        return;
-
-    d_matrix->setColumnsWidth(d_new_width);
-}
-
-void MatrixSetColWidthCommand::undo()
-{
-    if (!d_matrix)
-        return;
-
-    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);
-}
-
-void MatrixSetPrecisionCommand::redo()
-{
-    if (!d_matrix)
-        return;
-
-    d_matrix->setNumericFormat(d_new_format, d_new_prec);
-}
-
-void MatrixSetPrecisionCommand::undo()
-{
-    if (!d_matrix)
-        return;
-
-    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);
-}
-
-void MatrixSetCoordinatesCommand::redo()
-{
-    if (!d_matrix)
-        return;
-
-    d_matrix->setCoordinates(d_new_xs, d_new_xe, d_new_ys, d_new_ye);
-}
-
-void MatrixSetCoordinatesCommand::undo()
-{
-    if (!d_matrix)
-        return;
-
-    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);
-
-	d_map_before = QwtLinearColorMap(map_before);
-	d_map_after = QwtLinearColorMap(map_after);
-}
-
-void MatrixSetColorMapCommand::redo()
-{
-    if (!d_matrix)
-        return;
-
-	switch(d_map_type_after){
-		case Matrix::GrayScale:
-			d_matrix->setGrayScale();
-		break;
-
-		case Matrix::Rainbow:
-			d_matrix->setRainbowColorMap();
-		break;
-
-		case Matrix::Custom:
-			d_matrix->setColorMap(d_map_after);
-		break;
-	}
-}
-
-void MatrixSetColorMapCommand::undo()
-{
-    if (!d_matrix)
-        return;
-
-    	switch(d_map_type_before){
-		case Matrix::GrayScale:
-			d_matrix->setGrayScale();
-		break;
-
-		case Matrix::Rainbow:
-			d_matrix->setRainbowColorMap();
-		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);
-}
-
-void MatrixDeleteRowsCommand::redo()
-{
-    if (!d_model)
-        return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    d_model->removeRows(d_start_row, d_count);
-	QApplication::restoreOverrideCursor();
-}
-
-void MatrixDeleteRowsCommand::undo()
-{
-    if (!d_model)
-        return;
-
-	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];
-
-	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);
-}
-
-void MatrixInsertRowCommand::redo()
-{
-    if (!d_model)
-        return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    d_model->insertRows(d_start_row, 1);
-	QApplication::restoreOverrideCursor();
-}
-
-void MatrixInsertRowCommand::undo()
-{
-    if (!d_model)
-        return;
-
-	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);
-}
-
-void MatrixDeleteColsCommand::redo()
-{
-    if (!d_model)
-        return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    d_model->removeColumns(d_start_col, d_count);
-	QApplication::restoreOverrideCursor();
-}
-
-void MatrixDeleteColsCommand::undo()
-{
-    if (!d_model)
-        return;
-
-	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();
-}
-
-/*************************************************************************/
-/*           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);
-}
-
-void MatrixInsertColCommand::redo()
-{
-    if (!d_model)
-        return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    d_model->insertColumns(d_start_col, 1);
-	QApplication::restoreOverrideCursor();
-}
-
-void MatrixInsertColCommand::undo()
-{
-    if (!d_model)
-        return;
-
-	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++;
-		}
-    }
-	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();
-}
-
-/*************************************************************************/
-/*           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)
-{
-}
-
-void MatrixFftCommand::redo()
-{
-    if (!d_model)
-        return;
-
-    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)
-{
-}
-
-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();
-}
-
-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);
-}
-
-/*************************************************************************/
-/*           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)
-{
-}
-
-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);
-}
-
-/*************************************************************************/
-/*           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();
-}
-
-/*************************************************************************/
-/*           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();
+
+#include "MatrixCommand.h"
+#include <QApplication>
+#include <gsl/gsl_math.h>
+
+/*************************************************************************/
+/*           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();
+    }
+}
+
+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);
+}
+
+void MatrixSetFormulaCommand::redo()
+{
+    if (!d_matrix)
+        return;
+
+    d_matrix->setFormula(d_new_formula);
+}
+
+void MatrixSetFormulaCommand::undo()
+{
+    if (!d_matrix)
+        return;
+
+    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);
+}
+
+void MatrixSetViewCommand::redo()
+{
+    if (!d_matrix)
+        return;
+
+    d_matrix->setViewType(d_new_view);
+}
+
+void MatrixSetViewCommand::undo()
+{
+    if (!d_matrix)
+        return;
+
+    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);
+}
+
+void MatrixSetHeaderViewCommand::redo()
+{
+    if (!d_matrix)
+        return;
+
+    d_matrix->setHeaderViewType(d_new_view);
+}
+
+void MatrixSetHeaderViewCommand::undo()
+{
+    if (!d_matrix)
+        return;
+
+    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);
+}
+
+void MatrixSetColWidthCommand::redo()
+{
+    if (!d_matrix)
+        return;
+
+    d_matrix->setColumnsWidth(d_new_width);
+}
+
+void MatrixSetColWidthCommand::undo()
+{
+    if (!d_matrix)
+        return;
+
+    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);
+}
+
+void MatrixSetPrecisionCommand::redo()
+{
+    if (!d_matrix)
+        return;
+
+    d_matrix->setNumericFormat(d_new_format, d_new_prec);
+}
+
+void MatrixSetPrecisionCommand::undo()
+{
+    if (!d_matrix)
+        return;
+
+    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);
+}
+
+void MatrixSetCoordinatesCommand::redo()
+{
+    if (!d_matrix)
+        return;
+
+    d_matrix->setCoordinates(d_new_xs, d_new_xe, d_new_ys, d_new_ye);
+}
+
+void MatrixSetCoordinatesCommand::undo()
+{
+    if (!d_matrix)
+        return;
+
+    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);
+
+	d_map_before = QwtLinearColorMap(map_before);
+	d_map_after = QwtLinearColorMap(map_after);
+}
+
+void MatrixSetColorMapCommand::redo()
+{
+    if (!d_matrix)
+        return;
+
+	switch(d_map_type_after){
+		case Matrix::GrayScale:
+			d_matrix->setGrayScale();
+		break;
+
+		case Matrix::Rainbow:
+			d_matrix->setRainbowColorMap();
+		break;
+
+		case Matrix::Custom:
+			d_matrix->setColorMap(d_map_after);
+		break;
+	}
+}
+
+void MatrixSetColorMapCommand::undo()
+{
+    if (!d_matrix)
+        return;
+
+    	switch(d_map_type_before){
+		case Matrix::GrayScale:
+			d_matrix->setGrayScale();
+		break;
+
+		case Matrix::Rainbow:
+			d_matrix->setRainbowColorMap();
+		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);
+}
+
+void MatrixDeleteRowsCommand::redo()
+{
+    if (!d_model)
+        return;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+    d_model->removeRows(d_start_row, d_count);
+	QApplication::restoreOverrideCursor();
+}
+
+void MatrixDeleteRowsCommand::undo()
+{
+    if (!d_model)
+        return;
+
+	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];
+
+	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);
+}
+
+void MatrixInsertRowCommand::redo()
+{
+    if (!d_model)
+        return;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+    d_model->insertRows(d_start_row, 1);
+	QApplication::restoreOverrideCursor();
+}
+
+void MatrixInsertRowCommand::undo()
+{
+    if (!d_model)
+        return;
+
+	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);
+}
+
+void MatrixDeleteColsCommand::redo()
+{
+    if (!d_model)
+        return;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+    d_model->removeColumns(d_start_col, d_count);
+	QApplication::restoreOverrideCursor();
+}
+
+void MatrixDeleteColsCommand::undo()
+{
+    if (!d_model)
+        return;
+
+	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();
+}
+
+/*************************************************************************/
+/*           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);
+}
+
+void MatrixInsertColCommand::redo()
+{
+    if (!d_model)
+        return;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+    d_model->insertColumns(d_start_col, 1);
+	QApplication::restoreOverrideCursor();
+}
+
+void MatrixInsertColCommand::undo()
+{
+    if (!d_model)
+        return;
+
+	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++;
+		}
+    }
+	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();
+}
+
+/*************************************************************************/
+/*           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)
+{
+}
+
+void MatrixFftCommand::redo()
+{
+    if (!d_model)
+        return;
+
+    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)
+{
+}
+
+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();
+}
+
+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);
+}
+
+/*************************************************************************/
+/*           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)
+{
+}
+
+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);
+}
+
+/*************************************************************************/
+/*           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();
+}
+
+/*************************************************************************/
+/*           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();
 }
diff --git a/Code/Mantid/MantidPlot/src/MatrixCommand.h b/Code/Mantid/MantidPlot/src/MatrixCommand.h
index 83f6e1b1b9b963e1cc01089a7226b9d84a981f2e..2df50a2c261c678021caa156ef40bde592cb745b 100644
--- a/Code/Mantid/MantidPlot/src/MatrixCommand.h
+++ b/Code/Mantid/MantidPlot/src/MatrixCommand.h
@@ -1,11 +1,11 @@
-/***************************************************************************
-    File                 : MatrixCommand.h
-    Project              : QtiPlot
-    --------------------------------------------------------------------
-    Copyright            : (C) 2008 by Ion Vasilief,
-    Email (use @ for *)  : ion_vasilief*yahoo.fr
-    Description          : Matrix undo/redo commands
-
+/***************************************************************************
+    File                 : MatrixCommand.h
+    Project              : QtiPlot
+    --------------------------------------------------------------------
+    Copyright            : (C) 2008 by Ion Vasilief,
+    Email (use @ for *)  : ion_vasilief*yahoo.fr
+    Description          : Matrix undo/redo commands
+
  ***************************************************************************/
 
 /***************************************************************************
@@ -28,274 +28,274 @@
  ***************************************************************************/
 #ifndef MATRIX_COMMAND_H
 #define MATRIX_COMMAND_H
-
-#include "Matrix.h"
-#include "MatrixModel.h"
-#include <QUndoCommand>
-
-//! Matrix commands used by the undo/redo framework
-class MatrixEditCellCommand: public QUndoCommand
-{
-public:
-    MatrixEditCellCommand(MatrixModel *model, const QModelIndex & index, double valBefore,
-                            double valAfter, const QString & text);
-    virtual void redo();
-    virtual void undo();
-
-private:
-    MatrixModel *d_model;
-    QModelIndex d_index;
-    double d_val_before;
-    double d_val_after;
-};
-
-class MatrixSetFormulaCommand: public QUndoCommand
-{
-public:
-    MatrixSetFormulaCommand(Matrix *m, const QString& oldFormula, const QString& newFormula, const QString & text);
-    virtual void redo();
-    virtual void undo();
-
-private:
-    Matrix *d_matrix;
-    QString d_old_formula;
-    QString d_new_formula;
-};
-
-class MatrixSetViewCommand: public QUndoCommand
-{
-public:
-    MatrixSetViewCommand(Matrix *m, Matrix::ViewType oldView, Matrix::ViewType newView, const QString & text);
-    virtual void redo();
-    virtual void undo();
-
-private:
-    Matrix *d_matrix;
-    Matrix::ViewType d_old_view;
-    Matrix::ViewType d_new_view;
-};
-
-class MatrixSetHeaderViewCommand: public QUndoCommand
-{
-public:
-    MatrixSetHeaderViewCommand(Matrix *m, Matrix::HeaderViewType oldView,
-                            Matrix::HeaderViewType newView, const QString & text);
-    virtual void redo();
-    virtual void undo();
-
-private:
-    Matrix *d_matrix;
-    Matrix::HeaderViewType d_old_view;
-    Matrix::HeaderViewType d_new_view;
-};
-
-class MatrixSetColWidthCommand: public QUndoCommand
-{
-public:
-    MatrixSetColWidthCommand(Matrix *m, int oldWidth, int newWidth, const QString & text);
-    virtual void redo();
-    virtual void undo();
-
-private:
-    Matrix *d_matrix;
-    int d_old_width;
-    int d_new_width;
-};
-
-class MatrixSetPrecisionCommand: public QUndoCommand
-{
-public:
-    MatrixSetPrecisionCommand(Matrix *m, const QChar& oldFormat, const QChar& newFormat,
-                    int oldPrec, int newPrec, const QString & text);
-    virtual void redo();
-    virtual void undo();
-
-private:
-    Matrix *d_matrix;
-    QChar d_old_format;
-    QChar d_new_format;
-    int d_old_prec;
-    int d_new_prec;
-};
-
-class MatrixSetCoordinatesCommand: public QUndoCommand
-{
-public:
-    MatrixSetCoordinatesCommand(Matrix *, double, double, double, double,
-                    double, double, double, double, const QString &);
-    virtual void redo();
-    virtual void undo();
-
-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;
-};
-
-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);
-    virtual void redo();
-    virtual void undo();
-
-private:
-    Matrix *d_matrix;
-    Matrix::ColorMapType d_map_type_before, d_map_type_after;
-    QwtLinearColorMap d_map_before, d_map_after;
-};
-
-class MatrixDeleteRowsCommand: public QUndoCommand
-{
-public:
-    MatrixDeleteRowsCommand(MatrixModel *model, int startRow, int count, double* data, const QString& text);
-    ~MatrixDeleteRowsCommand(){free(d_data);};
-    virtual void redo();
-    virtual void undo();
-
-private:
-    MatrixModel *d_model;
-    int d_start_row, d_count;
-	double* d_data;
-};
-
-class MatrixInsertRowCommand: public QUndoCommand
-{
-public:
-    MatrixInsertRowCommand(MatrixModel *model, int startRow, const QString& text);
-    virtual void redo();
-    virtual void undo();
-
-private:
-    MatrixModel *d_model;
-    int d_start_row;
-};
-
-class MatrixDeleteColsCommand: public QUndoCommand
-{
-public:
-    MatrixDeleteColsCommand(MatrixModel *model, int startCol, int count, double* data, const QString& text);
-    ~MatrixDeleteColsCommand(){free(d_data);};
-    virtual void redo();
-    virtual void undo();
-
-private:
-    MatrixModel *d_model;
-    int d_start_col, d_count;
-	double* d_data;
-};
-
-class MatrixInsertColCommand: public QUndoCommand
-{
-public:
-    MatrixInsertColCommand(MatrixModel *model, int startCol, const QString& text);
-    virtual void redo();
-    virtual void undo();
-
-private:
-    MatrixModel *d_model;
-    int d_start_col;
-};
-
-class MatrixSetSizeCommand: public QUndoCommand
-{
-public:
-    MatrixSetSizeCommand(MatrixModel *model, const QSize& oldSize, const QSize& newSize, double *data, const QString& text);
-	~MatrixSetSizeCommand(){free(d_backup);};    
-	virtual void redo();
-    virtual void undo();
-
-private:
-    MatrixModel *d_model;
-    QSize d_old_size, d_new_size;
-	double *d_backup;
-};
-
-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(){free(d_data);};
-    virtual void redo();
-    virtual void undo();
-
-protected:
-	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
-{
-public:
-    MatrixFftCommand(bool inverse, MatrixModel *model, int startRow, int endRow,
-					int startCol, int endCol, double *data, const QString& text);
-    virtual void redo();
-
-private:
-    bool d_inverse;
-};
-
-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);
-    virtual void redo();
-    virtual void undo();
-
-private:
-    QImage d_image;
-	Matrix::ViewType d_old_view;
-};
-
-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);
-    virtual void redo();
-
-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;
-};
-
-class MatrixSymmetryOperation: public QUndoCommand
-{
-public:
-    MatrixSymmetryOperation(MatrixModel *model, Matrix::Operation op, const QString& text);
-    virtual void redo();
-    virtual void undo();
-
-private:
-    MatrixModel *d_model;
-    Matrix::Operation d_operation;
-};
-
-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(){free(d_clipboard_data); free(d_backup_data);};
-    virtual void redo();
-    virtual void undo();
-
-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;
+
+#include "Matrix.h"
+#include "MatrixModel.h"
+#include <QUndoCommand>
+
+//! Matrix commands used by the undo/redo framework
+class MatrixEditCellCommand: public QUndoCommand
+{
+public:
+    MatrixEditCellCommand(MatrixModel *model, const QModelIndex & index, double valBefore,
+                            double valAfter, const QString & text);
+    virtual void redo();
+    virtual void undo();
+
+private:
+    MatrixModel *d_model;
+    QModelIndex d_index;
+    double d_val_before;
+    double d_val_after;
+};
+
+class MatrixSetFormulaCommand: public QUndoCommand
+{
+public:
+    MatrixSetFormulaCommand(Matrix *m, const QString& oldFormula, const QString& newFormula, const QString & text);
+    virtual void redo();
+    virtual void undo();
+
+private:
+    Matrix *d_matrix;
+    QString d_old_formula;
+    QString d_new_formula;
+};
+
+class MatrixSetViewCommand: public QUndoCommand
+{
+public:
+    MatrixSetViewCommand(Matrix *m, Matrix::ViewType oldView, Matrix::ViewType newView, const QString & text);
+    virtual void redo();
+    virtual void undo();
+
+private:
+    Matrix *d_matrix;
+    Matrix::ViewType d_old_view;
+    Matrix::ViewType d_new_view;
+};
+
+class MatrixSetHeaderViewCommand: public QUndoCommand
+{
+public:
+    MatrixSetHeaderViewCommand(Matrix *m, Matrix::HeaderViewType oldView,
+                            Matrix::HeaderViewType newView, const QString & text);
+    virtual void redo();
+    virtual void undo();
+
+private:
+    Matrix *d_matrix;
+    Matrix::HeaderViewType d_old_view;
+    Matrix::HeaderViewType d_new_view;
+};
+
+class MatrixSetColWidthCommand: public QUndoCommand
+{
+public:
+    MatrixSetColWidthCommand(Matrix *m, int oldWidth, int newWidth, const QString & text);
+    virtual void redo();
+    virtual void undo();
+
+private:
+    Matrix *d_matrix;
+    int d_old_width;
+    int d_new_width;
+};
+
+class MatrixSetPrecisionCommand: public QUndoCommand
+{
+public:
+    MatrixSetPrecisionCommand(Matrix *m, const QChar& oldFormat, const QChar& newFormat,
+                    int oldPrec, int newPrec, const QString & text);
+    virtual void redo();
+    virtual void undo();
+
+private:
+    Matrix *d_matrix;
+    QChar d_old_format;
+    QChar d_new_format;
+    int d_old_prec;
+    int d_new_prec;
+};
+
+class MatrixSetCoordinatesCommand: public QUndoCommand
+{
+public:
+    MatrixSetCoordinatesCommand(Matrix *, double, double, double, double,
+                    double, double, double, double, const QString &);
+    virtual void redo();
+    virtual void undo();
+
+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;
+};
+
+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);
+    virtual void redo();
+    virtual void undo();
+
+private:
+    Matrix *d_matrix;
+    Matrix::ColorMapType d_map_type_before, d_map_type_after;
+    QwtLinearColorMap d_map_before, d_map_after;
+};
+
+class MatrixDeleteRowsCommand: public QUndoCommand
+{
+public:
+    MatrixDeleteRowsCommand(MatrixModel *model, int startRow, int count, double* data, const QString& text);
+    ~MatrixDeleteRowsCommand(){free(d_data);};
+    virtual void redo();
+    virtual void undo();
+
+private:
+    MatrixModel *d_model;
+    int d_start_row, d_count;
+	double* d_data;
+};
+
+class MatrixInsertRowCommand: public QUndoCommand
+{
+public:
+    MatrixInsertRowCommand(MatrixModel *model, int startRow, const QString& text);
+    virtual void redo();
+    virtual void undo();
+
+private:
+    MatrixModel *d_model;
+    int d_start_row;
+};
+
+class MatrixDeleteColsCommand: public QUndoCommand
+{
+public:
+    MatrixDeleteColsCommand(MatrixModel *model, int startCol, int count, double* data, const QString& text);
+    ~MatrixDeleteColsCommand(){free(d_data);};
+    virtual void redo();
+    virtual void undo();
+
+private:
+    MatrixModel *d_model;
+    int d_start_col, d_count;
+	double* d_data;
+};
+
+class MatrixInsertColCommand: public QUndoCommand
+{
+public:
+    MatrixInsertColCommand(MatrixModel *model, int startCol, const QString& text);
+    virtual void redo();
+    virtual void undo();
+
+private:
+    MatrixModel *d_model;
+    int d_start_col;
+};
+
+class MatrixSetSizeCommand: public QUndoCommand
+{
+public:
+    MatrixSetSizeCommand(MatrixModel *model, const QSize& oldSize, const QSize& newSize, double *data, const QString& text);
+	~MatrixSetSizeCommand(){free(d_backup);};    
+	virtual void redo();
+    virtual void undo();
+
+private:
+    MatrixModel *d_model;
+    QSize d_old_size, d_new_size;
+	double *d_backup;
+};
+
+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(){free(d_data);};
+    virtual void redo();
+    virtual void undo();
+
+protected:
+	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
+{
+public:
+    MatrixFftCommand(bool inverse, MatrixModel *model, int startRow, int endRow,
+					int startCol, int endCol, double *data, const QString& text);
+    virtual void redo();
+
+private:
+    bool d_inverse;
+};
+
+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);
+    virtual void redo();
+    virtual void undo();
+
+private:
+    QImage d_image;
+	Matrix::ViewType d_old_view;
+};
+
+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);
+    virtual void redo();
+
+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;
+};
+
+class MatrixSymmetryOperation: public QUndoCommand
+{
+public:
+    MatrixSymmetryOperation(MatrixModel *model, Matrix::Operation op, const QString& text);
+    virtual void redo();
+    virtual void undo();
+
+private:
+    MatrixModel *d_model;
+    Matrix::Operation d_operation;
+};
+
+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(){free(d_clipboard_data); free(d_backup_data);};
+    virtual void redo();
+    virtual void undo();
+
+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;
 };
 #endif
diff --git a/Code/Mantid/MantidPlot/src/MatrixDialog.cpp b/Code/Mantid/MantidPlot/src/MatrixDialog.cpp
index 6ad30b4f5ad5efef99f1199cd681c64a34da4ccd..8454d697496aa46c7ed282eac6f5728abc8c3ea5 100644
--- a/Code/Mantid/MantidPlot/src/MatrixDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/MatrixDialog.cpp
@@ -27,7 +27,7 @@
  *                                                                         *
  ***************************************************************************/
 #include "MatrixDialog.h"
-#include "Matrix.h"
+#include "Matrix.h"
 #include "MatrixCommand.h"
 
 #include <QPushButton>
@@ -105,29 +105,29 @@ void MatrixDialog::showPrecisionBox(int item)
 }
 
 void MatrixDialog::apply()
-{
-    int width = boxColWidth->value();
-    if (d_matrix->columnsWidth() != width){
-        d_matrix->undoStack()->push(new MatrixSetColWidthCommand(d_matrix, d_matrix->columnsWidth(),
+{
+    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);
+        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);
     }
 }
 
diff --git a/Code/Mantid/MantidPlot/src/MatrixModel.cpp b/Code/Mantid/MantidPlot/src/MatrixModel.cpp
index 6e3619425965dd03773bdfb0fe2915154941a81b..31f91246fc70ff24fa34a19041ce764623e1991b 100644
--- a/Code/Mantid/MantidPlot/src/MatrixModel.cpp
+++ b/Code/Mantid/MantidPlot/src/MatrixModel.cpp
@@ -1,1025 +1,1025 @@
-/***************************************************************************
-	File                 : MatrixModel.cpp
-	Project              : QtiPlot
---------------------------------------------------------------------
-	Copyright            : (C) 2007 by Ion Vasilief
-	Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : QtiPlot's matrix model
-
- ***************************************************************************/
-
-/***************************************************************************
- *                                                                         *
- *  This program is free software; you can redistribute it and/or modify   *
- *  it under the terms of the GNU General Public License as published by   *
- *  the Free Software Foundation; either version 2 of the License, or      *
- *  (at your option) any later version.                                    *
- *                                                                         *
- *  This program is distributed in the hope that it will be useful,        *
- *  but WITHOUT 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, write to the Free Software           *
- *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
- *   Boston, MA  02110-1301  USA                                           *
- *                                                                         *
- ***************************************************************************/
-#include <QtGui>
-#include <QFile>
-#include <QTextStream>
-
-#include "Matrix.h"
-#include "MatrixModel.h"
-#include "MatrixCommand.h"
-#include "muParserScript.h"
-#include "ScriptingEnv.h"
-#include "analysis/fft2D.h"
-
-#include <gsl/gsl_math.h>
-#include <gsl/gsl_linalg.h>
-#include <gsl/gsl_errno.h>
-
-#include <qwt_color_map.h>
-#include <stdlib.h>
-
-MatrixModel::MatrixModel(QObject *parent)
-     : QAbstractTableModel(parent),
-	 d_matrix((Matrix*)parent)
-{
-	init();
-	
-	if (d_matrix){
-		d_txt_format = d_matrix->textFormat().toAscii();
-		d_num_precision = d_matrix->precision();
-		d_locale = d_matrix->locale();
-	}
-
-	d_rows = 0;
-	d_cols = 0;
-
-}
-
-MatrixModel::MatrixModel(int rows, int cols, QObject *parent)
-     : QAbstractTableModel(parent),
-	 d_matrix((Matrix*)parent)
-{
-	init();
-	
-	if (d_matrix){
-		d_txt_format = d_matrix->textFormat().toAscii();
-		d_num_precision = d_matrix->precision();
-		d_locale = d_matrix->locale();
-	}
-
-	if (canResize(rows, cols)){
-		d_rows = rows;
-		d_cols = cols;
-		int cell = 0;
-		int size = rows*cols;
-		for (int i = 0; i < size; i++)
-            d_data[cell++] = GSL_NAN;
-	}
-}
-
-MatrixModel::MatrixModel(const QImage& image, QObject *parent)
-     : QAbstractTableModel(parent),
-	 d_matrix((Matrix*)parent)
-{
-	init();
-    setImage(image);
-}
-
-void MatrixModel::init()
-{
-	d_txt_format = 'g';
-	d_num_precision = 6;
-	d_locale = QLocale();
-	d_direct_matrix = NULL;
-	d_inv_matrix = NULL;
-	d_inv_perm = NULL;
-	
-	d_rows = 1;
-	d_cols = 1;
-	d_data_block_size = QSize(1, 1);
-	d_data = (double *)malloc(sizeof(double));
-}
-
-void MatrixModel::setImage(const QImage& image)
-{
-	if (!canResize(image.height(), image.width()))
-		return;
-
-    d_rows = image.height();
-    d_cols = image.width();
-	int cell = 0;
-    for (int i=0; i<d_rows; i++ ){
-		for (int j=0; j<d_cols; j++)
-            d_data[cell++] = qGray(image.pixel (j, i));
-    }
-}
-
-Qt::ItemFlags MatrixModel::flags(const QModelIndex & index ) const
-{
-	if (index.isValid())
-		return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
-	else
-		return Qt::ItemIsEnabled;
-}
-
-int MatrixModel::rowCount(const QModelIndex & /* parent */) const
-{
-    return d_rows;
-}
-
-int MatrixModel::columnCount(const QModelIndex & /* parent */) const
-{
-    return d_cols;
-}
-
-void MatrixModel::setRowCount(int rows)
-{
-	if (d_rows == rows)
-		return;
-
-   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-	if (rows > d_rows )
-		insertRows(d_rows, rows - d_rows);
-    else if (rows < d_rows )
-		removeRows(rows, d_rows - rows);
-
-	QApplication::restoreOverrideCursor();
-}
-
-void MatrixModel::setColumnCount(int cols)
-{
-	if (d_cols == cols)
-		return;
-
-   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-	if (cols > d_cols )
-		insertColumns(d_cols, cols - d_cols);
-    else if (cols < d_cols )
-		removeColumns(cols, d_cols - cols);
-
-	QApplication::restoreOverrideCursor();
-}
-
-void MatrixModel::setDimensions(int rows, int cols)
-{
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-	if (rows < d_rows){//first remove rows (faster)
-		removeRows(rows, d_rows - rows);
-		setColumnCount(cols);
-	} else {
-		setColumnCount(cols);
-		if (rows > d_rows )
-			insertRows(d_rows, rows - d_rows);
-	}
-
-	QApplication::restoreOverrideCursor();
-}
-
-double MatrixModel::cell(int row, int col) const
-{
-    int i = d_cols*row + col;
-    double val = d_data[i];
-    if (i < 0 || i>= d_rows*d_cols || gsl_isnan (val))
-        return 0.0;
-
-	return val;
-}
-
-void MatrixModel::setCell(int row, int col, double val)
-{
-	int i = d_cols*row + col;
-    if (i < 0 || i>= d_rows*d_cols)
-		return;
-
-    d_data[i] = val;
-}
-
-QString MatrixModel::text(int row, int col)
-{
-	double val = cell(row,col);
-
-	if (d_matrix){
-		QLocale locale = d_matrix->locale();
-		return locale.toString(val, d_matrix->textFormat().toAscii(), d_matrix->precision());
-	}
-	return d_locale.toString(val, d_txt_format, d_num_precision);
-}
-
-void MatrixModel::setText(int row, int col, const QString& text)
-{
-	int i = d_cols*row + col;
-    if (i < 0 || i>= d_rows*d_cols)
-		return;
-
- 	if (text.isEmpty())
-		d_data[i] = GSL_NAN;
-	else {
-		if (d_matrix)
-			d_data[i] = d_matrix->locale().toDouble(text);
-		else
-			d_data[i] = d_locale.toDouble(text);
-	}
-}
-
-double MatrixModel::data(int row, int col) const
-{
-    int i = d_cols*row + col;
-    if (i < 0 || i>= d_rows*d_cols)
-        return 0.0;
-
-	return d_data[i];
-}
-
-double MatrixModel::x(int col) const
-{
-	if (col < 0 || col >= d_cols)
-        return 0.0;
-
-	double start = d_matrix->xStart();
-	double end = d_matrix->xEnd();
-	if (start < end)
-		return start + col*d_matrix->dx();
-	else
-		return start - col*d_matrix->dx();
-
-	return 0.0;
-}
-
-double MatrixModel::y(int row) const
-{
-	if (row < 0 || row >= d_rows)
-        return 0.0;
-
-	double start = d_matrix->yStart();
-	double end = d_matrix->yEnd();
-	if (start < end)
-		return start + row*d_matrix->dy();
-	else
-		return start - row*d_matrix->dy();
-
-	return 0.0;
-}
-
-QVariant MatrixModel::headerData ( int section, Qt::Orientation orientation, int role) const
-{
-    if (!d_matrix || d_matrix->headerViewType() == Matrix::ColumnRow)
-        return QAbstractItemModel::headerData(section, orientation, role);
-
-    QLocale locale = d_locale;
-	int prec = d_num_precision;
-	char fmt = d_txt_format;
-	if (d_matrix){
-		locale = d_matrix->locale();
-		fmt = d_matrix->textFormat().toAscii();
-		prec = d_matrix->precision();
-	}
-
-    if (role == Qt::DisplayRole || role == Qt::EditRole){
-        if (orientation == Qt::Horizontal){
-            double start = d_matrix->xStart();
-            double end = d_matrix->xEnd();
-            double dx = d_matrix->dx();
-            if (start < end)
-                return QVariant(locale.toString(start + section*dx, fmt, prec));
-            else
-                return QVariant(locale.toString(start - section*dx, fmt, prec));
-        } else if (orientation == Qt::Vertical){
-            double start = d_matrix->yStart();
-            double end = d_matrix->yEnd();
-            double dy = d_matrix->dy();
-            if (start < end)
-                return QVariant(locale.toString(start + section*dy, fmt, prec));
-            else
-                return QVariant(locale.toString(start - section*dy, fmt, prec));
-        }
-    }
-	return QAbstractItemModel::headerData(section, orientation, role);
-}
-
-QVariant MatrixModel::data(const QModelIndex &index, int role) const
-{
-    if (!index.isValid())
-		return QVariant();
-
-    int i = d_cols*index.row() + index.column();
-	double val = d_data[i];
-    if (gsl_isnan (val))
-        return QVariant();
-
-	if (role == Qt::DisplayRole || role == Qt::EditRole){
-		if (d_matrix)
-			return QVariant(d_matrix->locale().toString(val, d_matrix->textFormat().toAscii(), d_matrix->precision()));
-		else
-			return QVariant(d_locale.toString(val, d_txt_format, d_num_precision));
-	} else
-		return QVariant();
-}
-
-bool MatrixModel::setData(const QModelIndex & index, const QVariant & value, int role)
-{
-	if (!index.isValid())
-		return false;
-
-	int i = d_cols*index.row() + index.column();
-	double valBefore = d_data[i];
- 	if(role == Qt::EditRole){
-		if (value.toString().isEmpty())
-			d_data[i] = GSL_NAN;
-		else
-			d_data[i] = value.toDouble();
-	}
-
-	if(index.row() + 1 >= d_rows){
-        insertRows(d_rows, 1);
-		d_matrix->resetView();
-	}
-
-    d_matrix->undoStack()->push(new MatrixEditCellCommand(this, index, valBefore, d_data[i],
-                                tr("Edited cell") + " (" + QString::number(index.row() + 1) + "," +
-                                QString::number(index.column() + 1) + ")"));
-    d_matrix->notifyChanges();
-	d_matrix->moveCell(index);
-	return false;
-}
-
-bool MatrixModel::canResize(int rows, int cols)
-{
-	if (rows <= 0 || cols <= 0 || INT_MAX/rows < cols){ //avoid integer overflow
-		QApplication::restoreOverrideCursor();
-    	QMessageBox::critical(d_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 on your system!"));
-		return false;
-	}
-	
-    if (d_data_block_size.width()*d_data_block_size.height() >= rows*cols)
-		return true;
-
-    double *new_data = (double *)realloc(d_data, rows*cols*sizeof(double));
-    if (new_data){
-        d_data = new_data;
-		d_data_block_size = QSize(rows, cols);
-        return true;
-    }
-
-    QApplication::restoreOverrideCursor();
-    QMessageBox::critical(d_matrix, tr("MantidPlot") + " - " + tr("Memory Allocation Error"),
-    tr("Not enough memory, operation aborted!"));
-    return false;
-}
-
-bool MatrixModel::removeColumns(int column, int count, const QModelIndex & parent)
-{
-	beginRemoveColumns(parent, column, column + count - 1);
-
-    d_cols -= count;
-	d_data_block_size = QSize(d_rows, d_cols);
-
-    int size = d_rows*d_cols;
-    for (int i = column; i < size; i++){
-	    int aux = (i - column)/d_cols + 1;
-        d_data[i] = d_data[i + aux*count];
-	}
-
-    d_data = (double *)realloc (d_data, size*sizeof(double));
-
-	endRemoveColumns();
-	return true;
-}
-
-bool MatrixModel::insertColumns(int column, int count, const QModelIndex & parent)
-{
-    if (!canResize(d_rows, d_cols + count))
-        return false;
-
-	beginInsertColumns(parent, column, column + count - 1);
-
-    int offset = column + count;
-    int oldCell = d_rows*d_cols - 1;
-	d_cols += count;
-    int cell = d_rows*d_cols - 1;
-    for (int i = d_rows - 1; i >= 0; i--){
-        for (int j = d_cols - 1; j >= offset; j--)
-            d_data[cell--] = d_data[oldCell--];
-
-        for (int j = offset - 1; j >= column; j--)
-            d_data[cell--] = GSL_NAN;
-
-        for (int j = column - 1; j >= 0; j--)
-            d_data[cell--] = d_data[oldCell--];
-    }
-
-	endInsertColumns();
-	return true;
-}
-
-bool MatrixModel::insertRows(int row, int count, const QModelIndex & parent)
-{
-    if (!canResize(d_rows + count, d_cols))
-        return false;
-
-	beginInsertRows(parent, row, row + count - 1);
-
-    int oldSize = d_rows*d_cols;
-	d_rows += count;
-
-    int insertedCells = count*d_cols;
-    int startCell = row*d_cols;
-    for (int i = oldSize - 1; i >= startCell; i--)
-        d_data[i + insertedCells] = d_data[i];
-    for (int i = 0; i < insertedCells; i++)
-        d_data[startCell++] = GSL_NAN;
-
-	endInsertRows();
-	return true;
-}
-
-bool MatrixModel::removeRows(int row, int count, const QModelIndex & parent)
-{
-	beginRemoveRows(parent, row, row + count - 1);
-
-    d_rows -= count;
-	d_data_block_size = QSize(d_rows, d_cols);
-
-	int removedCells = count*d_cols;
-	int size = d_rows*d_cols;
-	for (int i = row*d_cols; i < size; i++)
-        d_data[i] = d_data[i + removedCells];
-
-    d_data = (double *)realloc(d_data, size * sizeof(double));
-
-	endRemoveRows();
-	return true;
+/***************************************************************************
+	File                 : MatrixModel.cpp
+	Project              : QtiPlot
+--------------------------------------------------------------------
+	Copyright            : (C) 2007 by Ion Vasilief
+	Email (use @ for *)  : ion_vasilief*yahoo.fr
+	Description          : QtiPlot's matrix model
+
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *  This program is free software; you can redistribute it and/or modify   *
+ *  it under the terms of the GNU General Public License as published by   *
+ *  the Free Software Foundation; either version 2 of the License, or      *
+ *  (at your option) any later version.                                    *
+ *                                                                         *
+ *  This program is distributed in the hope that it will be useful,        *
+ *  but WITHOUT 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, write to the Free Software           *
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
+ *   Boston, MA  02110-1301  USA                                           *
+ *                                                                         *
+ ***************************************************************************/
+#include <QtGui>
+#include <QFile>
+#include <QTextStream>
+
+#include "Matrix.h"
+#include "MatrixModel.h"
+#include "MatrixCommand.h"
+#include "muParserScript.h"
+#include "ScriptingEnv.h"
+#include "analysis/fft2D.h"
+
+#include <gsl/gsl_math.h>
+#include <gsl/gsl_linalg.h>
+#include <gsl/gsl_errno.h>
+
+#include <qwt_color_map.h>
+#include <stdlib.h>
+
+MatrixModel::MatrixModel(QObject *parent)
+     : QAbstractTableModel(parent),
+	 d_matrix((Matrix*)parent)
+{
+	init();
+	
+	if (d_matrix){
+		d_txt_format = d_matrix->textFormat().toAscii();
+		d_num_precision = d_matrix->precision();
+		d_locale = d_matrix->locale();
+	}
+
+	d_rows = 0;
+	d_cols = 0;
+
+}
+
+MatrixModel::MatrixModel(int rows, int cols, QObject *parent)
+     : QAbstractTableModel(parent),
+	 d_matrix((Matrix*)parent)
+{
+	init();
+	
+	if (d_matrix){
+		d_txt_format = d_matrix->textFormat().toAscii();
+		d_num_precision = d_matrix->precision();
+		d_locale = d_matrix->locale();
+	}
+
+	if (canResize(rows, cols)){
+		d_rows = rows;
+		d_cols = cols;
+		int cell = 0;
+		int size = rows*cols;
+		for (int i = 0; i < size; i++)
+            d_data[cell++] = GSL_NAN;
+	}
+}
+
+MatrixModel::MatrixModel(const QImage& image, QObject *parent)
+     : QAbstractTableModel(parent),
+	 d_matrix((Matrix*)parent)
+{
+	init();
+    setImage(image);
 }
-
-QString MatrixModel::saveToString()
-{
-	QString s = "<data>\n";
-	int cols = d_cols - 1;
-	for(int i = 0; i < d_rows; i++){
-		int aux = d_cols*i;
-		bool emptyRow = true;
-		for(int j = 0; j < d_cols; j++){
-			if (gsl_finite(d_data[aux + j])){
-				emptyRow = false;
-				break;
-			}
-		}
-		if (emptyRow)
-			continue;
-
-		s += QString::number(i) + "\t";
-		for(int j = 0; j < cols; j++){
-			double val = d_data[aux + j];
-			if (gsl_finite(val))
-				s += QString::number(val, 'e', 16);
-			s += "\t";
-		}
-		double val = d_data[aux + cols];
-		if (gsl_finite(val))
-			s += QString::number(val, 'e', 16);
-		s += "\n";
-	}
-	return s + "</data>\n";
+
+void MatrixModel::init()
+{
+	d_txt_format = 'g';
+	d_num_precision = 6;
+	d_locale = QLocale();
+	d_direct_matrix = NULL;
+	d_inv_matrix = NULL;
+	d_inv_perm = NULL;
+	
+	d_rows = 1;
+	d_cols = 1;
+	d_data_block_size = QSize(1, 1);
+	d_data = (double *)malloc(sizeof(double));
 }
-
-QImage MatrixModel::renderImage()
-{
-    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-	
-	QImage image(QSize(d_cols, d_rows), QImage::Format_RGB32);
-	QwtLinearColorMap color_map = d_matrix->colorMap();
-
-	double minValue = 0.0, maxValue = 0.0;
-	d_matrix->range(&minValue, &maxValue);
-    const QwtDoubleInterval intensityRange = QwtDoubleInterval (minValue, maxValue);
-    for ( int i = 0; i < d_rows; i++ ){
-    	QRgb *line = (QRgb *)image.scanLine(i);
-		for ( int j = 0; j < d_cols; j++){
-		    double val = cell(i,j);//d_data[i*d_cols + j];
-		    if (gsl_isnan (val))
-                *line++ = color_map.rgb(intensityRange, 0.0);
-			else if(fabs(val) < HUGE_VAL)
-				*line++ = color_map.rgb(intensityRange, val);
-		}
-     }
-     QApplication::restoreOverrideCursor();
-	 return image;
-}
-
-bool MatrixModel::importASCII(const QString &fname, const QString &sep, int ignoredLines,
-    bool stripSpaces, bool simplifySpaces, const QString& commentString, int importAs,
-	const QLocale& locale, int endLineChar, int maxRows)
-{
-	int rows = 0;
-	QString name = MdiSubWindow::parseAsciiFile(fname, commentString, endLineChar, ignoredLines, maxRows, rows);
-	if (name.isEmpty())
-		return false;
-	QFile f(name);
-	if (!f.open(QIODevice::ReadOnly))
-		return false;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-    QTextStream t(&f);
-	QLocale l = d_locale;
-	if (d_matrix)
-		l = d_matrix->locale();
-	bool updateDecimalSeparators = (l != locale) ? true : false;
-
-	QString s = t.readLine();
-	if (simplifySpaces)
-		s = s.simplifyWhiteSpace();
-	else if (stripSpaces)
-		s = s.stripWhiteSpace();
-
-	QStringList line = s.split(sep);
-	int cols = line.size();
-
-	int startRow = 1, startCol = 0;
-	switch(importAs){
-		case Matrix::Overwrite:
-			if (d_cols != cols)
-				setColumnCount(cols);
-			if (d_rows != rows)
-				setRowCount(rows);
-		break;
-		case Matrix::NewColumns:
-			startCol = d_cols;
-			setColumnCount(d_cols + cols);
-			if (d_rows < rows)
-				setRowCount(rows);
-		break;
-		case Matrix::NewRows:
-			startRow = d_rows;
-			if (d_cols < cols)
-				setColumnCount(cols);
-			setRowCount(d_rows + rows);
-		break;
-	}
-
-	for (int j = startCol; j<d_cols; j++){
-		int aux = j - startCol;
-		if (cols > aux){
-			if (updateDecimalSeparators)
-				setCell(0, j, locale.toDouble(line[aux]));
-			else
-				setText(0, j, line[aux]);
-		}
-	}
-
-	qApp->processEvents(QEventLoop::ExcludeUserInput);
-	for (int i = startRow; i<d_rows; i++){
-		s = t.readLine();
-		if (simplifySpaces)
-			s = s.simplifyWhiteSpace();
-		else if (stripSpaces)
-			s = s.stripWhiteSpace();
-		line = s.split(sep);
-		int lc = line.size();
-		if (lc > cols)
-			setColumnCount(d_cols + lc - cols);
-
-		for (int j = startCol; j<d_cols; j++){
-			int aux = j - startCol;
-		    if (lc > aux){
-				if (updateDecimalSeparators)
-					setCell(i, j, locale.toDouble(line[aux]));
-				else
-					setText(i, j, line[aux]);
-			}
-		}
-	}
-    f.remove();	//remove temp file
-	if (d_matrix)
-		d_matrix->resetView();
-	QApplication::restoreOverrideCursor();
-	return true;
-}
-
-void MatrixModel::setNumericFormat(char f, int prec)
-{
-	if (d_txt_format == f && d_num_precision == prec)
-		return;
-
-	d_txt_format = f;
-	d_num_precision = prec;
-}
-
-void MatrixModel::transpose()
-{
-	int size = d_rows*d_cols;
-	double *data = d_matrix->initWorkspace(size);
-	if (!data)
-		return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-	for(int i = 0; i < size; i++)
-		data[i] = d_data[i];
-
-	int old_cols = d_cols;
-	d_cols = d_rows;
-	d_rows = old_cols;
-	int aux = 0;
-	for(int i = 0; i < d_rows; i++){
-		for(int j = 0; j < d_cols; j++)
-			d_data[aux++] = data[j*old_cols + i];
-	}
-	d_matrix->freeWorkspace();
-	QApplication::restoreOverrideCursor();
+
+void MatrixModel::setImage(const QImage& image)
+{
+	if (!canResize(image.height(), image.width()))
+		return;
+
+    d_rows = image.height();
+    d_cols = image.width();
+	int cell = 0;
+    for (int i=0; i<d_rows; i++ ){
+		for (int j=0; j<d_cols; j++)
+            d_data[cell++] = qGray(image.pixel (j, i));
+    }
 }
-
-void MatrixModel::flipVertically()
-{
-	int size = d_rows*d_cols;
-	double *data = d_matrix->initWorkspace(size);
-	if (!data)
-		return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-	for(int i = 0; i < size; i++)
-		data[i] = d_data[i];
-
-	int aux = 0;
-	for(int i = 0; i < d_rows; i++){
-		int row = (d_rows - i - 1)*d_cols;
-		for(int j = 0; j < d_cols; j++)
-			d_data[aux++] = data[row++];
-	}
-	d_matrix->freeWorkspace();
-	QApplication::restoreOverrideCursor();
-}
-
-void MatrixModel::flipHorizontally()
-{
-	int size = d_rows*d_cols;
-	double *data = d_matrix->initWorkspace(size);
-	if (!data)
-		return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-	for(int i = 0; i < size; i++)
-		data[i] = d_data[i];
-
-	int aux = 0;
-	for(int i = 0; i < d_rows; i++){
-		int row = i*d_cols;
-		for(int j = d_cols - 1; j >= 0; j--)
-			d_data[aux++] = data[row + j];
-	}
-	d_matrix->freeWorkspace();
-	QApplication::restoreOverrideCursor();
-}
-
-void MatrixModel::rotate90(bool clockwise)
-{
-	int size = d_rows*d_cols;
-	double *data = d_matrix->initWorkspace(size);
-	if (!data)
-		return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-	for(int i = 0; i < size; i++)
-		data[i] = d_data[i];
-
-    int old_rows = d_rows;
-    int old_cols = d_cols;
-	d_cols = d_rows;
-	d_rows = old_cols;
-	if (clockwise){
-        int cell = 0;
-        int aux = old_rows - 1;
-        for(int i = 0; i < d_rows; i++){
-            for(int j = 0; j < d_cols; j++)
-                d_data[cell++] = data[(aux - j)*old_cols + i];
-        }
-	} else {
-	    int cell = 0;
-	    int aux = old_cols - 1;
-        for(int i = 0; i < d_rows; i++){
-            int k = aux - i;
-            for(int j = 0; j < d_cols; j++)
-                d_data[cell++] = data[j*old_cols + k];
-        }
-	}
-	d_matrix->freeWorkspace();
-	QApplication::restoreOverrideCursor();
+
+Qt::ItemFlags MatrixModel::flags(const QModelIndex & index ) const
+{
+	if (index.isValid())
+		return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
+	else
+		return Qt::ItemIsEnabled;
 }
-
-bool MatrixModel::initWorkspace()
-{
-	gsl_set_error_handler_off();
-
-	if (!d_direct_matrix)
-		d_direct_matrix = gsl_matrix_alloc(d_rows, d_cols);
-	if (!d_inv_matrix)
-		d_inv_matrix = gsl_matrix_alloc(d_rows, d_cols);
-	if (!d_inv_perm)
-    	d_inv_perm = gsl_permutation_alloc(d_cols);
-	if (!d_direct_matrix || !d_inv_matrix || !d_inv_perm){
-		QApplication::restoreOverrideCursor();
-		QMessageBox::critical(d_matrix, tr("MantidPlot") + " - " + tr("Memory Allocation Error"),
-		tr("Not enough memory, operation aborted!"));
-		return false;
-	}
-	return true;
-}
-
-void MatrixModel::invert()
-{
-	initWorkspace();
-	if(!d_direct_matrix || !d_inv_matrix || !d_inv_perm)
-		return;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-	int i, aux = 0;
-	for(i=0; i<d_rows; i++){
-		for(int j=0; j<d_cols; j++)
-			gsl_matrix_set(d_direct_matrix, i, j, d_data[aux++]);
-	}
-
-	gsl_linalg_LU_decomp(d_direct_matrix, d_inv_perm, &i);
-	gsl_linalg_LU_invert(d_direct_matrix, d_inv_perm, d_inv_matrix);
-
-	gsl_matrix_free(d_direct_matrix);
-	d_direct_matrix = NULL;
-	gsl_permutation_free(d_inv_perm);
-	d_inv_perm = NULL;
-
-    aux = 0;
-	for(int i=0; i<d_rows; i++){
-		for(int j=0; j<d_cols; j++)
-			d_data[aux++] = gsl_matrix_get(d_inv_matrix, i, j);
-	}
-	gsl_matrix_free(d_inv_matrix);
-	d_inv_matrix = NULL;
-	QApplication::restoreOverrideCursor();
-}
-
-void MatrixModel::clear(int startRow, int endRow, int startCol, int endCol)
-{
-	if (endRow < 0)
-		endRow = d_rows - 1;
-	if (endCol < 0)
-		endCol = d_cols - 1;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-    for (int i = startRow; i <= endRow; i++){
-        int aux = i*d_cols + startCol;
-        for (int j = startCol; j <= endCol; j++){
-            d_data[aux++] = GSL_NAN;
-        }
-    }
-	QApplication::restoreOverrideCursor();
+
+int MatrixModel::rowCount(const QModelIndex & /* parent */) const
+{
+    return d_rows;
 }
-
-double * MatrixModel::dataCopy(int startRow, int endRow, int startCol, int endCol)
-{
-	if (endRow < 0)
-		endRow = d_rows - 1;
-	if (endCol < 0)
-		endCol = d_cols - 1;
-
-    double *buffer = (double *)malloc((endRow - startRow + 1)*(endCol - startCol + 1) * sizeof (double));
-	if (!buffer)
-		return NULL;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-	int aux = 0;
-    for (int i = startRow; i <= endRow; i++){
-        int row = i*d_cols + startCol;
-       	for (int j = startCol; j <= endCol; j++){
-            buffer[aux++] = d_data[row++];
-        }
-    }
-
-	QApplication::restoreOverrideCursor();
-	return buffer;
-}
-
-bool MatrixModel::muParserCalculate(int startRow, int endRow, int startCol, int endCol)
-{
-	ScriptingEnv *scriptEnv = d_matrix->scriptingEnv();
-    muParserScript *mup = new muParserScript(scriptEnv, d_matrix->formula(), d_matrix, QString("<%1>").arg(d_matrix->objectName()));
-	connect(mup, SIGNAL(error(const QString&,const QString&,int)), scriptEnv, SIGNAL(error(const QString&,const QString&,int)));
-	connect(mup, SIGNAL(print(const QString&)), scriptEnv, SIGNAL(print(const QString&)));
-
-	if (endRow < 0)
-		endRow = d_rows - 1;
-	if (endCol < 0)
-		endCol = d_cols - 1;
-    if (endCol >= d_cols)
-		setColumnCount(endCol + 1);
-	if (endRow >= d_rows)
-        setRowCount(endRow + 1);
-
-	double dx = d_matrix->dx();
-	double dy = d_matrix->dy();
-    double *ri = mup->defineVariable("i");
-    double *rr = mup->defineVariable("row");
-    double *cj = mup->defineVariable("j");
-    double *cc = mup->defineVariable("col");
-    double *x = mup->defineVariable("x");
-    double *y = mup->defineVariable("y");
-
-	if (!mup->compile()){
-		QApplication::restoreOverrideCursor();
-		return false;
-	}
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-	double x_start = d_matrix->xStart();
-	double y_start = d_matrix->yStart();
-    if (mup->codeLines() == 1){
-        for(int row = startRow; row <= endRow; row++){
-            double r = row + 1.0;
-            *ri = r; *rr = r;
-            *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;
-                d_data[aux++] = mup->evalSingleLine();
-            }
-        }
-    } else {
-        QVariant res;
-        for(int row = startRow; row <= endRow; row++){
-            double r = row + 1.0;
-            *ri = r; *rr = r;
-            *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;
-                res = mup->eval();
-                if (res.canConvert(QVariant::Double))
-                     d_data[aux++] = res.toDouble();
-                else
-                    d_data[aux++] = GSL_NAN;
-                qApp->processEvents();
-            }
-		}
-	}
-	QApplication::restoreOverrideCursor();
-	return true;
-}
-
-bool MatrixModel::calculate(int startRow, int endRow, int startCol, int endCol)
-{
-	QString formula = d_matrix->formula();
-	if (formula.isEmpty())
-		return false;
-
-	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-	ScriptingEnv *scriptEnv = d_matrix->scriptingEnv();
-	  Script *script = scriptEnv->newScript(formula, this, QString("<%1>").arg(objectName()), false);
-	connect(script, SIGNAL(error(const QString&,const QString&,int)), scriptEnv, SIGNAL(error(const QString&,const QString&,int)));
-	connect(script, SIGNAL(print(const QString&)), scriptEnv, SIGNAL(print(const QString&)));
-	
-	if (!script->compile()){
-		QApplication::restoreOverrideCursor();
-		return false;
-	}
-
-	if (endRow < 0)
-		endRow = d_rows - 1;
-	if (endCol < 0)
-		endCol = d_cols - 1;
-    if (endCol >= d_cols)
-		setColumnCount(endCol + 1);
-	if (endRow >= d_rows)
-        setRowCount(endRow + 1);
-
-	QVariant res;
-	double dx = d_matrix->dx();
-	double dy = d_matrix->dy();
-	double x_start = d_matrix->xStart();
-	double y_start = d_matrix->yStart();
-	double r = 0.0, c = 0.0;
-	for(int row = startRow; row <= endRow; row++){
-	    r = row + 1.0;
-		script->setDouble(r, "i");
-		script->setDouble(r, "row");
-		script->setDouble(y_start + row*dy, "y");
-		int aux = row*d_cols + startCol;
-		for(int col = startCol; col <= endCol; col++){
-		    c = col + 1.0;
-			script->setDouble(c, "j");
-			script->setDouble(c, "col");
-			script->setDouble(x_start + col*dx, "x");
-			res = script->eval();
-			if (res.canConvert(QVariant::Double))
-				d_data[aux++] = res.toDouble();
-			else {
-				QApplication::restoreOverrideCursor();
-				d_data[aux++] = GSL_NAN;
-				return false;
-			}
-		}
-		qApp->processEvents();
-	}
-
-	QApplication::restoreOverrideCursor();
-	return true;
-}
-
-void MatrixModel::fft(bool inverse)
-{
-	int width = d_cols;
-    int height = d_rows;
-
-    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));
-
-	int cell = 0;
-    for (int i = 0; i < height; i++){
-        for (int j = 0; j < width; j++){
-            x_int_re[i][j] = d_data[cell++];
-            x_int_im[i][j] = 0.0;
-        }
-    }
-
-    if (inverse){
-        double **x_fin_re = Matrix::allocateMatrixData(height, width);
-        double **x_fin_im = Matrix::allocateMatrixData(height, width);
-		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);
-		cell = 0;
-        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];
-                d_data[cell++] = sqrt(re*re + im*im);
-            }
-        }
-        Matrix::freeMatrixData(x_fin_re, height);
-        Matrix::freeMatrixData(x_fin_im, height);
-    } else {
-        fft2d(x_int_re, x_int_im, width, height);
-		cell = 0;
-        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];
-                d_data[cell++] = sqrt(re*re + im*im);
-            }
-        }
-    }
-    Matrix::freeMatrixData(x_int_re, height);
-    Matrix::freeMatrixData(x_int_im, height);
-
-	d_matrix->resetView();
-	QApplication::restoreOverrideCursor();
+
+int MatrixModel::columnCount(const QModelIndex & /* parent */) const
+{
+    return d_cols;
 }
-
-void MatrixModel::pasteData(double *clipboardBuffer, int topRow, int leftCol, int rows, int cols)
-{
-	int newCols = leftCol + cols;
-	if (newCols > d_cols)
-		insertColumns(d_cols, newCols - d_cols);
-	
-	int newRows = topRow + rows;
-	if (newRows > d_rows)
-		insertRows(d_rows, newRows - d_rows);
-		
-	int cell = 0;
-	int bottomRow = newRows - 1;
-	int rightCol = newCols - 1;
-    for (int i = topRow; i <= bottomRow; i++){
-        int row = i*d_cols + leftCol;
-        for (int j = leftCol; j <= rightCol; j++)
-            d_data[row++] = clipboardBuffer[cell++];
-    }
+
+void MatrixModel::setRowCount(int rows)
+{
+	if (d_rows == rows)
+		return;
+
+   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+	if (rows > d_rows )
+		insertRows(d_rows, rows - d_rows);
+    else if (rows < d_rows )
+		removeRows(rows, d_rows - rows);
+
+	QApplication::restoreOverrideCursor();
+}
+
+void MatrixModel::setColumnCount(int cols)
+{
+	if (d_cols == cols)
+		return;
+
+   QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+	if (cols > d_cols )
+		insertColumns(d_cols, cols - d_cols);
+    else if (cols < d_cols )
+		removeColumns(cols, d_cols - cols);
+
+	QApplication::restoreOverrideCursor();
+}
+
+void MatrixModel::setDimensions(int rows, int cols)
+{
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+	if (rows < d_rows){//first remove rows (faster)
+		removeRows(rows, d_rows - rows);
+		setColumnCount(cols);
+	} else {
+		setColumnCount(cols);
+		if (rows > d_rows )
+			insertRows(d_rows, rows - d_rows);
+	}
+
+	QApplication::restoreOverrideCursor();
+}
+
+double MatrixModel::cell(int row, int col) const
+{
+    int i = d_cols*row + col;
+    double val = d_data[i];
+    if (i < 0 || i>= d_rows*d_cols || gsl_isnan (val))
+        return 0.0;
+
+	return val;
+}
+
+void MatrixModel::setCell(int row, int col, double val)
+{
+	int i = d_cols*row + col;
+    if (i < 0 || i>= d_rows*d_cols)
+		return;
+
+    d_data[i] = val;
+}
+
+QString MatrixModel::text(int row, int col)
+{
+	double val = cell(row,col);
+
+	if (d_matrix){
+		QLocale locale = d_matrix->locale();
+		return locale.toString(val, d_matrix->textFormat().toAscii(), d_matrix->precision());
+	}
+	return d_locale.toString(val, d_txt_format, d_num_precision);
+}
+
+void MatrixModel::setText(int row, int col, const QString& text)
+{
+	int i = d_cols*row + col;
+    if (i < 0 || i>= d_rows*d_cols)
+		return;
+
+ 	if (text.isEmpty())
+		d_data[i] = GSL_NAN;
+	else {
+		if (d_matrix)
+			d_data[i] = d_matrix->locale().toDouble(text);
+		else
+			d_data[i] = d_locale.toDouble(text);
+	}
+}
+
+double MatrixModel::data(int row, int col) const
+{
+    int i = d_cols*row + col;
+    if (i < 0 || i>= d_rows*d_cols)
+        return 0.0;
+
+	return d_data[i];
+}
+
+double MatrixModel::x(int col) const
+{
+	if (col < 0 || col >= d_cols)
+        return 0.0;
+
+	double start = d_matrix->xStart();
+	double end = d_matrix->xEnd();
+	if (start < end)
+		return start + col*d_matrix->dx();
+	else
+		return start - col*d_matrix->dx();
+
+	return 0.0;
+}
+
+double MatrixModel::y(int row) const
+{
+	if (row < 0 || row >= d_rows)
+        return 0.0;
+
+	double start = d_matrix->yStart();
+	double end = d_matrix->yEnd();
+	if (start < end)
+		return start + row*d_matrix->dy();
+	else
+		return start - row*d_matrix->dy();
+
+	return 0.0;
+}
+
+QVariant MatrixModel::headerData ( int section, Qt::Orientation orientation, int role) const
+{
+    if (!d_matrix || d_matrix->headerViewType() == Matrix::ColumnRow)
+        return QAbstractItemModel::headerData(section, orientation, role);
+
+    QLocale locale = d_locale;
+	int prec = d_num_precision;
+	char fmt = d_txt_format;
+	if (d_matrix){
+		locale = d_matrix->locale();
+		fmt = d_matrix->textFormat().toAscii();
+		prec = d_matrix->precision();
+	}
+
+    if (role == Qt::DisplayRole || role == Qt::EditRole){
+        if (orientation == Qt::Horizontal){
+            double start = d_matrix->xStart();
+            double end = d_matrix->xEnd();
+            double dx = d_matrix->dx();
+            if (start < end)
+                return QVariant(locale.toString(start + section*dx, fmt, prec));
+            else
+                return QVariant(locale.toString(start - section*dx, fmt, prec));
+        } else if (orientation == Qt::Vertical){
+            double start = d_matrix->yStart();
+            double end = d_matrix->yEnd();
+            double dy = d_matrix->dy();
+            if (start < end)
+                return QVariant(locale.toString(start + section*dy, fmt, prec));
+            else
+                return QVariant(locale.toString(start - section*dy, fmt, prec));
+        }
+    }
+	return QAbstractItemModel::headerData(section, orientation, role);
+}
+
+QVariant MatrixModel::data(const QModelIndex &index, int role) const
+{
+    if (!index.isValid())
+		return QVariant();
+
+    int i = d_cols*index.row() + index.column();
+	double val = d_data[i];
+    if (gsl_isnan (val))
+        return QVariant();
+
+	if (role == Qt::DisplayRole || role == Qt::EditRole){
+		if (d_matrix)
+			return QVariant(d_matrix->locale().toString(val, d_matrix->textFormat().toAscii(), d_matrix->precision()));
+		else
+			return QVariant(d_locale.toString(val, d_txt_format, d_num_precision));
+	} else
+		return QVariant();
+}
+
+bool MatrixModel::setData(const QModelIndex & index, const QVariant & value, int role)
+{
+	if (!index.isValid())
+		return false;
+
+	int i = d_cols*index.row() + index.column();
+	double valBefore = d_data[i];
+ 	if(role == Qt::EditRole){
+		if (value.toString().isEmpty())
+			d_data[i] = GSL_NAN;
+		else
+			d_data[i] = value.toDouble();
+	}
+
+	if(index.row() + 1 >= d_rows){
+        insertRows(d_rows, 1);
+		d_matrix->resetView();
+	}
+
+    d_matrix->undoStack()->push(new MatrixEditCellCommand(this, index, valBefore, d_data[i],
+                                tr("Edited cell") + " (" + QString::number(index.row() + 1) + "," +
+                                QString::number(index.column() + 1) + ")"));
+    d_matrix->notifyChanges();
+	d_matrix->moveCell(index);
+	return false;
+}
+
+bool MatrixModel::canResize(int rows, int cols)
+{
+	if (rows <= 0 || cols <= 0 || INT_MAX/rows < cols){ //avoid integer overflow
+		QApplication::restoreOverrideCursor();
+    	QMessageBox::critical(d_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 on your system!"));
+		return false;
+	}
+	
+    if (d_data_block_size.width()*d_data_block_size.height() >= rows*cols)
+		return true;
+
+    double *new_data = (double *)realloc(d_data, rows*cols*sizeof(double));
+    if (new_data){
+        d_data = new_data;
+		d_data_block_size = QSize(rows, cols);
+        return true;
+    }
+
+    QApplication::restoreOverrideCursor();
+    QMessageBox::critical(d_matrix, tr("MantidPlot") + " - " + tr("Memory Allocation Error"),
+    tr("Not enough memory, operation aborted!"));
+    return false;
+}
+
+bool MatrixModel::removeColumns(int column, int count, const QModelIndex & parent)
+{
+	beginRemoveColumns(parent, column, column + count - 1);
+
+    d_cols -= count;
+	d_data_block_size = QSize(d_rows, d_cols);
+
+    int size = d_rows*d_cols;
+    for (int i = column; i < size; i++){
+	    int aux = (i - column)/d_cols + 1;
+        d_data[i] = d_data[i + aux*count];
+	}
+
+    d_data = (double *)realloc (d_data, size*sizeof(double));
+
+	endRemoveColumns();
+	return true;
+}
+
+bool MatrixModel::insertColumns(int column, int count, const QModelIndex & parent)
+{
+    if (!canResize(d_rows, d_cols + count))
+        return false;
+
+	beginInsertColumns(parent, column, column + count - 1);
+
+    int offset = column + count;
+    int oldCell = d_rows*d_cols - 1;
+	d_cols += count;
+    int cell = d_rows*d_cols - 1;
+    for (int i = d_rows - 1; i >= 0; i--){
+        for (int j = d_cols - 1; j >= offset; j--)
+            d_data[cell--] = d_data[oldCell--];
+
+        for (int j = offset - 1; j >= column; j--)
+            d_data[cell--] = GSL_NAN;
+
+        for (int j = column - 1; j >= 0; j--)
+            d_data[cell--] = d_data[oldCell--];
+    }
+
+	endInsertColumns();
+	return true;
+}
+
+bool MatrixModel::insertRows(int row, int count, const QModelIndex & parent)
+{
+    if (!canResize(d_rows + count, d_cols))
+        return false;
+
+	beginInsertRows(parent, row, row + count - 1);
+
+    int oldSize = d_rows*d_cols;
+	d_rows += count;
+
+    int insertedCells = count*d_cols;
+    int startCell = row*d_cols;
+    for (int i = oldSize - 1; i >= startCell; i--)
+        d_data[i + insertedCells] = d_data[i];
+    for (int i = 0; i < insertedCells; i++)
+        d_data[startCell++] = GSL_NAN;
+
+	endInsertRows();
+	return true;
+}
+
+bool MatrixModel::removeRows(int row, int count, const QModelIndex & parent)
+{
+	beginRemoveRows(parent, row, row + count - 1);
+
+    d_rows -= count;
+	d_data_block_size = QSize(d_rows, d_cols);
+
+	int removedCells = count*d_cols;
+	int size = d_rows*d_cols;
+	for (int i = row*d_cols; i < size; i++)
+        d_data[i] = d_data[i + removedCells];
+
+    d_data = (double *)realloc(d_data, size * sizeof(double));
+
+	endRemoveRows();
+	return true;
+}
+
+QString MatrixModel::saveToString()
+{
+	QString s = "<data>\n";
+	int cols = d_cols - 1;
+	for(int i = 0; i < d_rows; i++){
+		int aux = d_cols*i;
+		bool emptyRow = true;
+		for(int j = 0; j < d_cols; j++){
+			if (gsl_finite(d_data[aux + j])){
+				emptyRow = false;
+				break;
+			}
+		}
+		if (emptyRow)
+			continue;
+
+		s += QString::number(i) + "\t";
+		for(int j = 0; j < cols; j++){
+			double val = d_data[aux + j];
+			if (gsl_finite(val))
+				s += QString::number(val, 'e', 16);
+			s += "\t";
+		}
+		double val = d_data[aux + cols];
+		if (gsl_finite(val))
+			s += QString::number(val, 'e', 16);
+		s += "\n";
+	}
+	return s + "</data>\n";
+}
+
+QImage MatrixModel::renderImage()
+{
+    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+	
+	QImage image(QSize(d_cols, d_rows), QImage::Format_RGB32);
+	QwtLinearColorMap color_map = d_matrix->colorMap();
+
+	double minValue = 0.0, maxValue = 0.0;
+	d_matrix->range(&minValue, &maxValue);
+    const QwtDoubleInterval intensityRange = QwtDoubleInterval (minValue, maxValue);
+    for ( int i = 0; i < d_rows; i++ ){
+    	QRgb *line = (QRgb *)image.scanLine(i);
+		for ( int j = 0; j < d_cols; j++){
+		    double val = cell(i,j);//d_data[i*d_cols + j];
+		    if (gsl_isnan (val))
+                *line++ = color_map.rgb(intensityRange, 0.0);
+			else if(fabs(val) < HUGE_VAL)
+				*line++ = color_map.rgb(intensityRange, val);
+		}
+     }
+     QApplication::restoreOverrideCursor();
+	 return image;
+}
+
+bool MatrixModel::importASCII(const QString &fname, const QString &sep, int ignoredLines,
+    bool stripSpaces, bool simplifySpaces, const QString& commentString, int importAs,
+	const QLocale& locale, int endLineChar, int maxRows)
+{
+	int rows = 0;
+	QString name = MdiSubWindow::parseAsciiFile(fname, commentString, endLineChar, ignoredLines, maxRows, rows);
+	if (name.isEmpty())
+		return false;
+	QFile f(name);
+	if (!f.open(QIODevice::ReadOnly))
+		return false;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+    QTextStream t(&f);
+	QLocale l = d_locale;
+	if (d_matrix)
+		l = d_matrix->locale();
+	bool updateDecimalSeparators = (l != locale) ? true : false;
+
+	QString s = t.readLine();
+	if (simplifySpaces)
+		s = s.simplifyWhiteSpace();
+	else if (stripSpaces)
+		s = s.stripWhiteSpace();
+
+	QStringList line = s.split(sep);
+	int cols = line.size();
+
+	int startRow = 1, startCol = 0;
+	switch(importAs){
+		case Matrix::Overwrite:
+			if (d_cols != cols)
+				setColumnCount(cols);
+			if (d_rows != rows)
+				setRowCount(rows);
+		break;
+		case Matrix::NewColumns:
+			startCol = d_cols;
+			setColumnCount(d_cols + cols);
+			if (d_rows < rows)
+				setRowCount(rows);
+		break;
+		case Matrix::NewRows:
+			startRow = d_rows;
+			if (d_cols < cols)
+				setColumnCount(cols);
+			setRowCount(d_rows + rows);
+		break;
+	}
+
+	for (int j = startCol; j<d_cols; j++){
+		int aux = j - startCol;
+		if (cols > aux){
+			if (updateDecimalSeparators)
+				setCell(0, j, locale.toDouble(line[aux]));
+			else
+				setText(0, j, line[aux]);
+		}
+	}
+
+	qApp->processEvents(QEventLoop::ExcludeUserInput);
+	for (int i = startRow; i<d_rows; i++){
+		s = t.readLine();
+		if (simplifySpaces)
+			s = s.simplifyWhiteSpace();
+		else if (stripSpaces)
+			s = s.stripWhiteSpace();
+		line = s.split(sep);
+		int lc = line.size();
+		if (lc > cols)
+			setColumnCount(d_cols + lc - cols);
+
+		for (int j = startCol; j<d_cols; j++){
+			int aux = j - startCol;
+		    if (lc > aux){
+				if (updateDecimalSeparators)
+					setCell(i, j, locale.toDouble(line[aux]));
+				else
+					setText(i, j, line[aux]);
+			}
+		}
+	}
+    f.remove();	//remove temp file
+	if (d_matrix)
+		d_matrix->resetView();
+	QApplication::restoreOverrideCursor();
+	return true;
+}
+
+void MatrixModel::setNumericFormat(char f, int prec)
+{
+	if (d_txt_format == f && d_num_precision == prec)
+		return;
+
+	d_txt_format = f;
+	d_num_precision = prec;
+}
+
+void MatrixModel::transpose()
+{
+	int size = d_rows*d_cols;
+	double *data = d_matrix->initWorkspace(size);
+	if (!data)
+		return;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+	for(int i = 0; i < size; i++)
+		data[i] = d_data[i];
+
+	int old_cols = d_cols;
+	d_cols = d_rows;
+	d_rows = old_cols;
+	int aux = 0;
+	for(int i = 0; i < d_rows; i++){
+		for(int j = 0; j < d_cols; j++)
+			d_data[aux++] = data[j*old_cols + i];
+	}
+	d_matrix->freeWorkspace();
+	QApplication::restoreOverrideCursor();
+}
+
+void MatrixModel::flipVertically()
+{
+	int size = d_rows*d_cols;
+	double *data = d_matrix->initWorkspace(size);
+	if (!data)
+		return;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+	for(int i = 0; i < size; i++)
+		data[i] = d_data[i];
+
+	int aux = 0;
+	for(int i = 0; i < d_rows; i++){
+		int row = (d_rows - i - 1)*d_cols;
+		for(int j = 0; j < d_cols; j++)
+			d_data[aux++] = data[row++];
+	}
+	d_matrix->freeWorkspace();
+	QApplication::restoreOverrideCursor();
+}
+
+void MatrixModel::flipHorizontally()
+{
+	int size = d_rows*d_cols;
+	double *data = d_matrix->initWorkspace(size);
+	if (!data)
+		return;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+	for(int i = 0; i < size; i++)
+		data[i] = d_data[i];
+
+	int aux = 0;
+	for(int i = 0; i < d_rows; i++){
+		int row = i*d_cols;
+		for(int j = d_cols - 1; j >= 0; j--)
+			d_data[aux++] = data[row + j];
+	}
+	d_matrix->freeWorkspace();
+	QApplication::restoreOverrideCursor();
+}
+
+void MatrixModel::rotate90(bool clockwise)
+{
+	int size = d_rows*d_cols;
+	double *data = d_matrix->initWorkspace(size);
+	if (!data)
+		return;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+	for(int i = 0; i < size; i++)
+		data[i] = d_data[i];
+
+    int old_rows = d_rows;
+    int old_cols = d_cols;
+	d_cols = d_rows;
+	d_rows = old_cols;
+	if (clockwise){
+        int cell = 0;
+        int aux = old_rows - 1;
+        for(int i = 0; i < d_rows; i++){
+            for(int j = 0; j < d_cols; j++)
+                d_data[cell++] = data[(aux - j)*old_cols + i];
+        }
+	} else {
+	    int cell = 0;
+	    int aux = old_cols - 1;
+        for(int i = 0; i < d_rows; i++){
+            int k = aux - i;
+            for(int j = 0; j < d_cols; j++)
+                d_data[cell++] = data[j*old_cols + k];
+        }
+	}
+	d_matrix->freeWorkspace();
+	QApplication::restoreOverrideCursor();
+}
+
+bool MatrixModel::initWorkspace()
+{
+	gsl_set_error_handler_off();
+
+	if (!d_direct_matrix)
+		d_direct_matrix = gsl_matrix_alloc(d_rows, d_cols);
+	if (!d_inv_matrix)
+		d_inv_matrix = gsl_matrix_alloc(d_rows, d_cols);
+	if (!d_inv_perm)
+    	d_inv_perm = gsl_permutation_alloc(d_cols);
+	if (!d_direct_matrix || !d_inv_matrix || !d_inv_perm){
+		QApplication::restoreOverrideCursor();
+		QMessageBox::critical(d_matrix, tr("MantidPlot") + " - " + tr("Memory Allocation Error"),
+		tr("Not enough memory, operation aborted!"));
+		return false;
+	}
+	return true;
+}
+
+void MatrixModel::invert()
+{
+	initWorkspace();
+	if(!d_direct_matrix || !d_inv_matrix || !d_inv_perm)
+		return;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+	int i, aux = 0;
+	for(i=0; i<d_rows; i++){
+		for(int j=0; j<d_cols; j++)
+			gsl_matrix_set(d_direct_matrix, i, j, d_data[aux++]);
+	}
+
+	gsl_linalg_LU_decomp(d_direct_matrix, d_inv_perm, &i);
+	gsl_linalg_LU_invert(d_direct_matrix, d_inv_perm, d_inv_matrix);
+
+	gsl_matrix_free(d_direct_matrix);
+	d_direct_matrix = NULL;
+	gsl_permutation_free(d_inv_perm);
+	d_inv_perm = NULL;
+
+    aux = 0;
+	for(int i=0; i<d_rows; i++){
+		for(int j=0; j<d_cols; j++)
+			d_data[aux++] = gsl_matrix_get(d_inv_matrix, i, j);
+	}
+	gsl_matrix_free(d_inv_matrix);
+	d_inv_matrix = NULL;
+	QApplication::restoreOverrideCursor();
+}
+
+void MatrixModel::clear(int startRow, int endRow, int startCol, int endCol)
+{
+	if (endRow < 0)
+		endRow = d_rows - 1;
+	if (endCol < 0)
+		endCol = d_cols - 1;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+    for (int i = startRow; i <= endRow; i++){
+        int aux = i*d_cols + startCol;
+        for (int j = startCol; j <= endCol; j++){
+            d_data[aux++] = GSL_NAN;
+        }
+    }
+	QApplication::restoreOverrideCursor();
+}
+
+double * MatrixModel::dataCopy(int startRow, int endRow, int startCol, int endCol)
+{
+	if (endRow < 0)
+		endRow = d_rows - 1;
+	if (endCol < 0)
+		endCol = d_cols - 1;
+
+    double *buffer = (double *)malloc((endRow - startRow + 1)*(endCol - startCol + 1) * sizeof (double));
+	if (!buffer)
+		return NULL;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+	int aux = 0;
+    for (int i = startRow; i <= endRow; i++){
+        int row = i*d_cols + startCol;
+       	for (int j = startCol; j <= endCol; j++){
+            buffer[aux++] = d_data[row++];
+        }
+    }
+
+	QApplication::restoreOverrideCursor();
+	return buffer;
+}
+
+bool MatrixModel::muParserCalculate(int startRow, int endRow, int startCol, int endCol)
+{
+	ScriptingEnv *scriptEnv = d_matrix->scriptingEnv();
+    muParserScript *mup = new muParserScript(scriptEnv, d_matrix->formula(), d_matrix, QString("<%1>").arg(d_matrix->objectName()));
+	connect(mup, SIGNAL(error(const QString&,const QString&,int)), scriptEnv, SIGNAL(error(const QString&,const QString&,int)));
+	connect(mup, SIGNAL(print(const QString&)), scriptEnv, SIGNAL(print(const QString&)));
+
+	if (endRow < 0)
+		endRow = d_rows - 1;
+	if (endCol < 0)
+		endCol = d_cols - 1;
+    if (endCol >= d_cols)
+		setColumnCount(endCol + 1);
+	if (endRow >= d_rows)
+        setRowCount(endRow + 1);
+
+	double dx = d_matrix->dx();
+	double dy = d_matrix->dy();
+    double *ri = mup->defineVariable("i");
+    double *rr = mup->defineVariable("row");
+    double *cj = mup->defineVariable("j");
+    double *cc = mup->defineVariable("col");
+    double *x = mup->defineVariable("x");
+    double *y = mup->defineVariable("y");
+
+	if (!mup->compile()){
+		QApplication::restoreOverrideCursor();
+		return false;
+	}
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+	double x_start = d_matrix->xStart();
+	double y_start = d_matrix->yStart();
+    if (mup->codeLines() == 1){
+        for(int row = startRow; row <= endRow; row++){
+            double r = row + 1.0;
+            *ri = r; *rr = r;
+            *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;
+                d_data[aux++] = mup->evalSingleLine();
+            }
+        }
+    } else {
+        QVariant res;
+        for(int row = startRow; row <= endRow; row++){
+            double r = row + 1.0;
+            *ri = r; *rr = r;
+            *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;
+                res = mup->eval();
+                if (res.canConvert(QVariant::Double))
+                     d_data[aux++] = res.toDouble();
+                else
+                    d_data[aux++] = GSL_NAN;
+                qApp->processEvents();
+            }
+		}
+	}
+	QApplication::restoreOverrideCursor();
+	return true;
+}
+
+bool MatrixModel::calculate(int startRow, int endRow, int startCol, int endCol)
+{
+	QString formula = d_matrix->formula();
+	if (formula.isEmpty())
+		return false;
+
+	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+	ScriptingEnv *scriptEnv = d_matrix->scriptingEnv();
+	  Script *script = scriptEnv->newScript(formula, this, QString("<%1>").arg(objectName()), false);
+	connect(script, SIGNAL(error(const QString&,const QString&,int)), scriptEnv, SIGNAL(error(const QString&,const QString&,int)));
+	connect(script, SIGNAL(print(const QString&)), scriptEnv, SIGNAL(print(const QString&)));
+	
+	if (!script->compile()){
+		QApplication::restoreOverrideCursor();
+		return false;
+	}
+
+	if (endRow < 0)
+		endRow = d_rows - 1;
+	if (endCol < 0)
+		endCol = d_cols - 1;
+    if (endCol >= d_cols)
+		setColumnCount(endCol + 1);
+	if (endRow >= d_rows)
+        setRowCount(endRow + 1);
+
+	QVariant res;
+	double dx = d_matrix->dx();
+	double dy = d_matrix->dy();
+	double x_start = d_matrix->xStart();
+	double y_start = d_matrix->yStart();
+	double r = 0.0, c = 0.0;
+	for(int row = startRow; row <= endRow; row++){
+	    r = row + 1.0;
+		script->setDouble(r, "i");
+		script->setDouble(r, "row");
+		script->setDouble(y_start + row*dy, "y");
+		int aux = row*d_cols + startCol;
+		for(int col = startCol; col <= endCol; col++){
+		    c = col + 1.0;
+			script->setDouble(c, "j");
+			script->setDouble(c, "col");
+			script->setDouble(x_start + col*dx, "x");
+			res = script->eval();
+			if (res.canConvert(QVariant::Double))
+				d_data[aux++] = res.toDouble();
+			else {
+				QApplication::restoreOverrideCursor();
+				d_data[aux++] = GSL_NAN;
+				return false;
+			}
+		}
+		qApp->processEvents();
+	}
+
+	QApplication::restoreOverrideCursor();
+	return true;
+}
+
+void MatrixModel::fft(bool inverse)
+{
+	int width = d_cols;
+    int height = d_rows;
+
+    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));
+
+	int cell = 0;
+    for (int i = 0; i < height; i++){
+        for (int j = 0; j < width; j++){
+            x_int_re[i][j] = d_data[cell++];
+            x_int_im[i][j] = 0.0;
+        }
+    }
+
+    if (inverse){
+        double **x_fin_re = Matrix::allocateMatrixData(height, width);
+        double **x_fin_im = Matrix::allocateMatrixData(height, width);
+		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);
+		cell = 0;
+        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];
+                d_data[cell++] = sqrt(re*re + im*im);
+            }
+        }
+        Matrix::freeMatrixData(x_fin_re, height);
+        Matrix::freeMatrixData(x_fin_im, height);
+    } else {
+        fft2d(x_int_re, x_int_im, width, height);
+		cell = 0;
+        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];
+                d_data[cell++] = sqrt(re*re + im*im);
+            }
+        }
+    }
+    Matrix::freeMatrixData(x_int_re, height);
+    Matrix::freeMatrixData(x_int_im, height);
+
+	d_matrix->resetView();
+	QApplication::restoreOverrideCursor();
+}
+
+void MatrixModel::pasteData(double *clipboardBuffer, int topRow, int leftCol, int rows, int cols)
+{
+	int newCols = leftCol + cols;
+	if (newCols > d_cols)
+		insertColumns(d_cols, newCols - d_cols);
+	
+	int newRows = topRow + rows;
+	if (newRows > d_rows)
+		insertRows(d_rows, newRows - d_rows);
+		
+	int cell = 0;
+	int bottomRow = newRows - 1;
+	int rightCol = newCols - 1;
+    for (int i = topRow; i <= bottomRow; i++){
+        int row = i*d_cols + leftCol;
+        for (int j = leftCol; j <= rightCol; j++)
+            d_data[row++] = clipboardBuffer[cell++];
+    }
 }
 
 
diff --git a/Code/Mantid/MantidPlot/src/MatrixModel.h b/Code/Mantid/MantidPlot/src/MatrixModel.h
index 7742e098488aae9c58659eb02af733a89e7afd9f..8ebd82806a1059d25cca7efeec2b11b1c0e010dd 100644
--- a/Code/Mantid/MantidPlot/src/MatrixModel.h
+++ b/Code/Mantid/MantidPlot/src/MatrixModel.h
@@ -1,138 +1,138 @@
-/***************************************************************************
-	File                 : MatrixModel.h
-	Project              : QtiPlot
---------------------------------------------------------------------
-	Copyright            : (C) 2007 by Ion Vasilief
-	Email (use @ for *)  : ion_vasilief*yahoo.fr
-	Description          : QtiPlot's matrix model
-
- ***************************************************************************/
-
-/***************************************************************************
- *                                                                         *
- *  This program is free software; you can redistribute it and/or modify   *
- *  it under the terms of the GNU General Public License as published by   *
- *  the Free Software Foundation; either version 2 of the License, or      *
- *  (at your option) any later version.                                    *
- *                                                                         *
- *  This program is distributed in the hope that it will be useful,        *
- *  but WITHOUT 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, write to the Free Software           *
- *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
- *   Boston, MA  02110-1301  USA                                           *
- *                                                                         *
- ***************************************************************************/
-
-#ifndef MATRIXMODEL_H
-#define MATRIXMODEL_H
-
-#include <QAbstractTableModel>
-#include <QVector>
-#include <QLocale>
-#include <QSize>
-#include <QMessageBox>
-
-#include <gsl/gsl_matrix.h>
-#include <gsl/gsl_permutation.h>
-
-class Matrix;
-
-class MatrixModel : public QAbstractTableModel
-{
-    Q_OBJECT
-
-protected:
-    MatrixModel(QObject *parent);
-
-public:
-    MatrixModel(int rows = 32, int cols = 32, QObject *parent = 0);
-    MatrixModel(const QImage& image, QObject *parent);
-    ~MatrixModel();
-
-    Matrix *matrix(){return d_matrix;};
-
-	Qt::ItemFlags flags( const QModelIndex & index ) const;
-
-    virtual bool canResize(int rows, int cols);
-	virtual void setDimensions(int rows, int cols);
-
-    virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
-	virtual void setRowCount(int rows);
-
-    virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
-	virtual void setColumnCount(int cols);
-
-	virtual bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex());
-	virtual bool insertRows(int row, int count, const QModelIndex & parent = QModelIndex());
-
-	virtual bool removeColumns(int column, int count, const QModelIndex & parent = QModelIndex());
-	virtual bool insertColumns(int column, int count, const QModelIndex & parent = QModelIndex());
-
-	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 QString text(int row, int col);
-	virtual void setText(int row, int col, const QString&);
-
-	virtual QString saveToString();
-	virtual QImage renderImage();
-
-	virtual double data(int row, int col) const;
-    virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
-	virtual bool setData(const QModelIndex & index, const QVariant & value, int role);
-
-    virtual double* dataVector(){return d_data;};
-    virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
-
-	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;
-};
-
+/***************************************************************************
+	File                 : MatrixModel.h
+	Project              : QtiPlot
+--------------------------------------------------------------------
+	Copyright            : (C) 2007 by Ion Vasilief
+	Email (use @ for *)  : ion_vasilief*yahoo.fr
+	Description          : QtiPlot's matrix model
+
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *  This program is free software; you can redistribute it and/or modify   *
+ *  it under the terms of the GNU General Public License as published by   *
+ *  the Free Software Foundation; either version 2 of the License, or      *
+ *  (at your option) any later version.                                    *
+ *                                                                         *
+ *  This program is distributed in the hope that it will be useful,        *
+ *  but WITHOUT 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, write to the Free Software           *
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
+ *   Boston, MA  02110-1301  USA                                           *
+ *                                                                         *
+ ***************************************************************************/
+
+#ifndef MATRIXMODEL_H
+#define MATRIXMODEL_H
+
+#include <QAbstractTableModel>
+#include <QVector>
+#include <QLocale>
+#include <QSize>
+#include <QMessageBox>
+
+#include <gsl/gsl_matrix.h>
+#include <gsl/gsl_permutation.h>
+
+class Matrix;
+
+class MatrixModel : public QAbstractTableModel
+{
+    Q_OBJECT
+
+protected:
+    MatrixModel(QObject *parent);
+
+public:
+    MatrixModel(int rows = 32, int cols = 32, QObject *parent = 0);
+    MatrixModel(const QImage& image, QObject *parent);
+    ~MatrixModel();
+
+    Matrix *matrix(){return d_matrix;};
+
+	Qt::ItemFlags flags( const QModelIndex & index ) const;
+
+    virtual bool canResize(int rows, int cols);
+	virtual void setDimensions(int rows, int cols);
+
+    virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
+	virtual void setRowCount(int rows);
+
+    virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
+	virtual void setColumnCount(int cols);
+
+	virtual bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex());
+	virtual bool insertRows(int row, int count, const QModelIndex & parent = QModelIndex());
+
+	virtual bool removeColumns(int column, int count, const QModelIndex & parent = QModelIndex());
+	virtual bool insertColumns(int column, int count, const QModelIndex & parent = QModelIndex());
+
+	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 QString text(int row, int col);
+	virtual void setText(int row, int col, const QString&);
+
+	virtual QString saveToString();
+	virtual QImage renderImage();
+
+	virtual double data(int row, int col) const;
+    virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
+	virtual bool setData(const QModelIndex & index, const QVariant & value, int role);
+
+    virtual double* dataVector(){return d_data;};
+    virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
+
+	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;
+};
+
 #endif
diff --git a/Code/Mantid/MantidPlot/src/MatrixSizeDialog.cpp b/Code/Mantid/MantidPlot/src/MatrixSizeDialog.cpp
index 503c506eedd6ff65969dca7803fbd1b33cc07122..5e92f9af27affb17edc87ee6c4eb22f0667398b1 100644
--- a/Code/Mantid/MantidPlot/src/MatrixSizeDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/MatrixSizeDialog.cpp
@@ -26,9 +26,9 @@
  *   Boston, MA  02110-1301  USA                                           *
  *                                                                         *
  ***************************************************************************/
-#include "MatrixSizeDialog.h"
+#include "MatrixSizeDialog.h"
 #include "MatrixCommand.h"
-#include "DoubleSpinBox.h"
+#include "DoubleSpinBox.h"
 
 #include <QPushButton>
 #include <QLabel>
@@ -38,7 +38,7 @@
 #include <QLayout>
 
 MatrixSizeDialog::MatrixSizeDialog( Matrix *m, QWidget* parent, Qt::WFlags fl )
-    : QDialog( parent, fl ),
+    : QDialog( parent, fl ),
     d_matrix(m)
 {
     setWindowTitle(tr("MantidPlot - Matrix Dimensions"));
@@ -60,23 +60,23 @@ MatrixSizeDialog::MatrixSizeDialog( Matrix *m, QWidget* parent, Qt::WFlags fl )
 	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 );
-
+	centerLayout->addWidget( new QLabel(tr( "First" )), 1, 0 );
+
 	QLocale locale = m->locale();
-    boxXStart = new DoubleSpinBox();
-    boxXStart->setLocale(locale);
-    centerLayout->addWidget( boxXStart, 1, 1 );
+    boxXStart = new DoubleSpinBox();
+    boxXStart->setLocale(locale);
+    centerLayout->addWidget( boxXStart, 1, 1 );
 
-    boxYStart = new DoubleSpinBox();
+    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 );
+    boxXEnd = new DoubleSpinBox();
+    boxXEnd->setLocale(locale);
+    centerLayout->addWidget( boxXEnd, 2, 1 );
 
-    boxYEnd = new DoubleSpinBox();
+    boxYEnd = new DoubleSpinBox();
     boxYEnd->setLocale(locale);
 	centerLayout->addWidget( boxYEnd, 2, 2 );
 	centerLayout->setRowStretch(3, 1);
@@ -95,14 +95,14 @@ MatrixSizeDialog::MatrixSizeDialog( Matrix *m, QWidget* parent, Qt::WFlags fl )
     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());
+
+    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() ));
diff --git a/Code/Mantid/MantidPlot/src/MatrixSizeDialog.h b/Code/Mantid/MantidPlot/src/MatrixSizeDialog.h
index 4dc24cc3d68521b37b6b0e5e31464b1f5eaf7809..cd3094591f55f6883aa4abe0baf837c6325c123d 100644
--- a/Code/Mantid/MantidPlot/src/MatrixSizeDialog.h
+++ b/Code/Mantid/MantidPlot/src/MatrixSizeDialog.h
@@ -28,14 +28,14 @@
  ***************************************************************************/
 #ifndef MATRIXSIZEDIALOG_H
 #define MATRIXSIZEDIALOG_H
-
+
 #include "Matrix.h"
 #include <QDialog>
 
 class QGroupBox;
 class QPushButton;
 class QSpinBox;
-class DoubleSpinBox;
+class DoubleSpinBox;
 
 //! Matrix dimensions dialog
 class MatrixSizeDialog : public QDialog
@@ -61,7 +61,7 @@ private:
 	QPushButton* buttonCancel;
     QGroupBox* groupBox1, *groupBox2;
 	QSpinBox *boxCols, *boxRows;
-	DoubleSpinBox *boxXStart, *boxYStart, *boxXEnd, *boxYEnd;
+	DoubleSpinBox *boxXStart, *boxYStart, *boxXEnd, *boxYEnd;
 	Matrix *d_matrix;
 };
 
diff --git a/Code/Mantid/MantidPlot/src/MatrixValuesDialog.cpp b/Code/Mantid/MantidPlot/src/MatrixValuesDialog.cpp
index a61e918dc9235f297e7cb43778156661d324eba6..f51f49c88c987c99f49f98cdfc2424da55d868f7 100644
--- a/Code/Mantid/MantidPlot/src/MatrixValuesDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/MatrixValuesDialog.cpp
@@ -30,7 +30,7 @@
  *                                                                         *
  ***************************************************************************/
 #include "MatrixValuesDialog.h"
-#include "MatrixCommand.h"
+#include "MatrixCommand.h"
 
 #include <QLayout>
 #include <QSpinBox>
@@ -179,10 +179,10 @@ void MatrixValuesDialog::setMatrix(Matrix* m)
 	matrix = m;
 	commands->setText(m->formula());
 	commands->setContext(m);
-
-    endCol->setValue(m->numCols());
-    endRow->setValue(m->numRows());
-
+
+    endCol->setValue(m->numCols());
+    endRow->setValue(m->numRows());
+
     if (m->viewType() == Matrix::TableView){
         QItemSelectionModel *selModel = m->selectionModel();
         if (selModel->hasSelection()){
diff --git a/Code/Mantid/MantidPlot/src/MdiSubWindow.h b/Code/Mantid/MantidPlot/src/MdiSubWindow.h
index fa88812aefe5b0c5b11d50dc10581aa6ec60db07..1081595aa8f3b7db23a835a50facc0445be71713 100644
--- a/Code/Mantid/MantidPlot/src/MdiSubWindow.h
+++ b/Code/Mantid/MantidPlot/src/MdiSubWindow.h
@@ -34,7 +34,7 @@
 class QEvent;
 class QCloseEvent;
 class QString;
-class Folder;
+class Folder;
 class ApplicationWindow;
 
 /**
@@ -71,9 +71,9 @@ public:
 		Both = 2 //!< caption = "name - label"
 	};
 	enum Status{Hidden = -1, Normal = 0, Minimized = 1, Maximized = 2};
-
-    //! Returns a pointer to the parent application
-    ApplicationWindow *applicationWindow(){return d_app;};
+
+    //! Returns a pointer to the parent application
+    ApplicationWindow *applicationWindow(){return d_app;};
 
 	//! Return the window label
 	QString windowLabel(){return QString(d_label);};
@@ -142,8 +142,8 @@ public:
 	void setNormal();
 	void setMinimized();
 	void setMaximized();
-
-    //! Returns the size the window had before a change state event to minimized.
+
+    //! Returns the size the window had before a change state event to minimized.
     QSize minRestoreSize(){return d_min_restore_size;};
 
 	//! Static function used as a workaround for ASCII files having end line char != '\n'.
@@ -152,15 +152,15 @@ public:
 	 * 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);
-
-	void setconfirmcloseFlag(bool closeflag){d_confirm_close=closeflag;}
-
+	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;}
+
 public slots:
 	//! 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(){};
 
 signals:
 	//! Emitted when the window was closed
@@ -171,8 +171,8 @@ signals:
 	void resizedWindow(MdiSubWindow *);
 	//! Emitted when the window status changed
 	void statusChanged(MdiSubWindow *);
-	//! Show the context menu
-	void showContextMenu();
+	//! Show the context menu
+	void showContextMenu();
 	
 protected:
 	//! Catches status changes
@@ -183,7 +183,7 @@ private:
 	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();
+	void updateCaption();
 	//!Pointer to the application window
     ApplicationWindow *d_app;
 	//!Pointer to the parent folder of the window
@@ -203,8 +203,8 @@ private:
 	//! Toggle on/off: Ask the user "delete, hide, or cancel?" on a close event
 	bool d_confirm_close;
 	//! The creation date
-	QString d_birthdate;
-    //! Stores the size the window had before a change state event to minimized.
+	QString d_birthdate;
+    //! Stores the size the window had before a change state event to minimized.
 	QSize d_min_restore_size;
 };
 
diff --git a/Code/Mantid/MantidPlot/src/MultiPeakFit.cpp b/Code/Mantid/MantidPlot/src/MultiPeakFit.cpp
index d96541ca320897a14fb38d32e484f19375b51995..a382e3c55ff44adc03c4a0727b6305c55160df1d 100644
--- a/Code/Mantid/MantidPlot/src/MultiPeakFit.cpp
+++ b/Code/Mantid/MantidPlot/src/MultiPeakFit.cpp
@@ -139,7 +139,7 @@ QString MultiPeakFit::generateFormula(int peaks, PeakProfile profile)
 			case Lorentz:
 				return "y0+2*A/PI*w/(4*(x-xc)^2+w^2)";
 				break;
-		}
+		}
 	}
 
 	QString formula = "y0+";
@@ -205,10 +205,10 @@ void MultiPeakFit::guessInitialValues()
 }
 
 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]);
+{
+	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]);
 	}
 }
 
@@ -260,19 +260,19 @@ void MultiPeakFit::generateFitCurve()
 
 	if (d_gen_function){
 		double step = (d_x[d_n-1] - d_x[0])/(d_points-1);
-		for (i = 0; i<d_points; i++){
+		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
+			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();
+
+        customizeFitResults();
 
 		if (d_graphics_display){
 			if (!d_output_graph)
@@ -290,7 +290,7 @@ void MultiPeakFit::generateFitCurve()
 
 				insertPeakFunctionCurve(X.data(), Y.data(), i);//insertPeakFunctionCurve(X, Y, i);
 				}
-			}
+			}
 			d_output_graph->replot();
 		}
 	} else {
@@ -332,8 +332,8 @@ void MultiPeakFit::generateFitCurve()
 			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){
@@ -377,17 +377,17 @@ double MultiPeakFit::eval(double *par, double x)
 
 	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);
-}
+
+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)
 {
@@ -550,17 +550,17 @@ void GaussAmpFit::calculateFitCurveData(double *X, double *Y)
 	double a = d_results[1];
 	double xc = d_results[2];
 	double w2 = d_results[3]*d_results[3];
-	if (d_gen_function){
+	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++){
+		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++){
+		for (int i=0; i<d_points; i++){
 		    double x = d_x[i];
 			X[i] = x;
 			double diff = x - xc;
@@ -568,12 +568,12 @@ void GaussAmpFit::calculateFitCurveData(double *X, double *Y)
 		}
 	}
 }
-
-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];
-}
+
+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()
 {
diff --git a/Code/Mantid/MantidPlot/src/MultiPeakFit.h b/Code/Mantid/MantidPlot/src/MultiPeakFit.h
index 562a36573637b4ca0d14a61c1ba9437daa4a4ce3..cd945cc81b7cda27e9ae2efb131bfc087f8c96f7 100644
--- a/Code/Mantid/MantidPlot/src/MultiPeakFit.h
+++ b/Code/Mantid/MantidPlot/src/MultiPeakFit.h
@@ -54,7 +54,7 @@ class MultiPeakFit : public Fit
 		//! Used by the GaussFit and LorentzFit derived classes to calculate initial values for the parameters
 		void guessInitialValues();
 
-		virtual double eval(double *par, double x);
+		virtual double eval(double *par, double x);
 		double evalPeak(double *par, double x, int peak);
 
 	private:
@@ -119,7 +119,7 @@ class GaussAmpFit : public Fit
 		GaussAmpFit(ApplicationWindow *parent, Table *t, const QString& xCol, const QString& yCol, int startRow = 0, int endRow = -1);
 
 		void guessInitialValues();
-        double eval(double *par, double x);
+        double eval(double *par, double x);
 
 	private:
 		void init();
diff --git a/Code/Mantid/MantidPlot/src/MultiPeakFitTool.cpp b/Code/Mantid/MantidPlot/src/MultiPeakFitTool.cpp
index 394fce65e9167dc087b5633720b019d3046553e3..703c2cc3357be07ba19f37b02dec17c0b82f0556 100644
--- a/Code/Mantid/MantidPlot/src/MultiPeakFitTool.cpp
+++ b/Code/Mantid/MantidPlot/src/MultiPeakFitTool.cpp
@@ -28,12 +28,12 @@
  *   Boston, MA  02110-1301  USA                                           *
  *                                                                         *
  ***************************************************************************/
-#include "MultiPeakFitTool.h"
+#include "MultiPeakFitTool.h"
 #include "RangeSelectorTool.h"
 #include "ApplicationWindow.h"
 #include "DataPickerTool.h"
-#include "Plot.h"
-#include "cursors.h"
+#include "Plot.h"
+#include "cursors.h"
 
 #include <qwt_plot_curve.h>
 #include <QApplication>
@@ -55,11 +55,11 @@ MultiPeakFitTool::MultiPeakFitTool(Graph *graph, ApplicationWindow *app, MultiPe
 
 	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));
+	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();
+	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!"));
 }
@@ -115,24 +115,24 @@ void MultiPeakFitTool::finalize()
 		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 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++){
+		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->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();
@@ -145,9 +145,9 @@ void MultiPeakFitTool::finalize()
 		d_graph->plotWidget()->removeMarker(mrks[n-i-1]);
 
 	d_graph->plotWidget()->replot();
-    if (d_graph->activeTool() && d_graph->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector){
-        ((RangeSelectorTool *)d_graph->activeTool())->setEnabled();
-    } else
-        d_graph->plotWidget()->canvas()->unsetCursor();
+    if (d_graph->activeTool() && d_graph->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector){
+        ((RangeSelectorTool *)d_graph->activeTool())->setEnabled();
+    } else
+        d_graph->plotWidget()->canvas()->unsetCursor();
     delete this;
 }
diff --git a/Code/Mantid/MantidPlot/src/NonLinearFit.cpp b/Code/Mantid/MantidPlot/src/NonLinearFit.cpp
index 586d86f689eae9aa63b3653bf6f90af134bfebf9..a395ed0bda84810f83ae20f19a032e3b3419a820 100644
--- a/Code/Mantid/MantidPlot/src/NonLinearFit.cpp
+++ b/Code/Mantid/MantidPlot/src/NonLinearFit.cpp
@@ -60,7 +60,7 @@ NonLinearFit::NonLinearFit(ApplicationWindow *parent, Table *t, const QString& x
 }
 
 void NonLinearFit::init()
-{
+{
     if (objectName().isEmpty())
         setObjectName(tr("NonLinear"));
 	d_formula = QString::null;
@@ -68,7 +68,7 @@ void NonLinearFit::init()
 	d_df = user_df;
 	d_fdf = user_fdf;
 	d_fsimplex = user_d;
-	d_explanation = tr("Non-linear Fit");
+	d_explanation = tr("Non-linear Fit");
     d_fit_type = User;
 }
 
@@ -150,26 +150,26 @@ void NonLinearFit::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++){
+		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++) {
+		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].ascii(), &par[i]);
-	parser.DefineVar("x", &x);
-	parser.SetExpr(d_formula.ascii());
-    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].ascii(), &par[i]);
+	parser.DefineVar("x", &x);
+	parser.SetExpr(d_formula.ascii());
+    return parser.Eval();
 }
diff --git a/Code/Mantid/MantidPlot/src/NonLinearFit.h b/Code/Mantid/MantidPlot/src/NonLinearFit.h
index ec8b8625ac36af4852e26056a32411eaf8bea845..e1712201e2c277b1a0fb32091dc8b04c5c325ede 100644
--- a/Code/Mantid/MantidPlot/src/NonLinearFit.h
+++ b/Code/Mantid/MantidPlot/src/NonLinearFit.h
@@ -40,14 +40,14 @@ class NonLinearFit : public Fit
 		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);
+
+        double eval(double *par, double x);
 
 		virtual void setParametersList(const QStringList& lst);
-		virtual void setFormula(const QString& s);
+		virtual void setFormula(const QString& s);
 
 	private:
 		void calculateFitCurveData(double *X, double *Y);
-		void init();
+		void init();
 };
 #endif
diff --git a/Code/Mantid/MantidPlot/src/Plot.cpp b/Code/Mantid/MantidPlot/src/Plot.cpp
index 4aa40366a52c0f378d148c29bb17f2d2ec36504d..4c3c7037246faeb64cfce441b8c599a7e87dc8aa 100644
--- a/Code/Mantid/MantidPlot/src/Plot.cpp
+++ b/Code/Mantid/MantidPlot/src/Plot.cpp
@@ -32,7 +32,7 @@
 #include "Grid.h"
 #include "ScaleDraw.h"
 #include "Spectrogram.h"
-#include "PlotCurve.h"
+#include "PlotCurve.h"
 #include "LegendWidget.h"
 #include "plot2D/ScaleEngine.h"
 
@@ -45,7 +45,7 @@
 #include <qwt_text_label.h>
 
 #include <QPainter>
-#include <QMessageBox>
+#include <QMessageBox>
 
 Detacher::Detacher(QwtPlotItem *plotItem) : m_plotItem(plotItem)
 {
@@ -142,7 +142,7 @@ void Plot::printFrame(QPainter *painter, const QRect &rect) const
 	painter->save();
 
 	int lw = lineWidth();
-	if (lw){
+	if (lw){
 		QColor color = palette().color(QPalette::Active, QPalette::Foreground);
 		painter->setPen (QPen(color, lw, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin));
 	} else
@@ -167,8 +167,8 @@ void Plot::printCanvas(QPainter *painter, const QRect &canvasRect,
 
     QwtPainter::fillRect(painter, rect, canvasBackground());
 	painter->setClipping(true);
-	QwtPainter::setClipRect(painter, rect);
-
+	QwtPainter::setClipRect(painter, rect);
+
     drawItems(painter, canvasRect, map, pfilter);
     painter->restore();
 
@@ -191,15 +191,15 @@ void Plot::printCanvas(QPainter *painter, const QRect &canvasRect,
 
 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();
+{
+    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))
@@ -207,24 +207,24 @@ void Plot::drawItems (QPainter *painter, const QRect &rect,
 
 		ScaleEngine *sc_engine = (ScaleEngine *)axisScaleEngine(i);
 		/*const QwtScaleEngine *qwtsc_engine=axisScaleEngine(i);
-		const ScaleEngine *sc_engine =dynamic_cast<const ScaleEngine*>(qwtsc_engine);
-		if(sc_engine!=NULL)
-		{	*/
+		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());
+			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)
+		}
+		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);
 		//}
 	}
@@ -243,7 +243,7 @@ void Plot::drawItems (QPainter *painter, const QRect &rect,
 		bool maj = (majorTicksType == ScaleDraw::In || majorTicksType == ScaleDraw::Both);
 
 		if (min || maj)
-			drawInwardTicks(painter, rect, map[i], i, min, maj);
+			drawInwardTicks(painter, rect, map[i], i, min, maj);
 	}
 }
 
@@ -270,7 +270,7 @@ void Plot::drawInwardTicks(QPainter *painter, const QRect &rect,
 
 	const QwtValueList majTickList = scDiv->ticks(QwtScaleDiv::MajorTick);
 	int majTicks = (int)majTickList.count();
-
+
 	int j, x, y, low,high;
 	switch (axis)
 	{
@@ -383,54 +383,54 @@ void Plot::drawInwardTicks(QPainter *painter, const QRect &rect,
 	}
 	painter->restore();
 }
-
-void Plot::drawBreak(QPainter *painter, const QRect &rect, const QwtScaleMap &map, int axis) const
-{	
-    ScaleEngine *sc_engine = (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());
+
+void Plot::drawBreak(QPainter *painter, const QRect &rect, const QwtScaleMap &map, int axis) const
+{	
+    ScaleEngine *sc_engine = (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:
+		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:
+			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;
-
+			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();
-	//}
-}
+			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();
+	//}
+}
 
 void Plot::setAxesLinewidth(int width)
 {
@@ -471,7 +471,7 @@ void Plot::setTickLength (int minLength, int majLength)
 
 	majTickLength = majLength;
 	minTickLength = minLength;
-}
+}
 
 QwtPlotCurve* Plot::curve(int index)
 {
@@ -498,15 +498,15 @@ int Plot::closestCurve(int xpos, int ypos, int &dist, int &point)
 
 		if(item->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
 		{
-      PlotCurve *c = (PlotCurve *)item;
-      DataCurve *dc = dynamic_cast<DataCurve *>(item);
-      if (!dc) continue;
-      if (c->type() != Graph::Function && dc->hasLabels() &&
-        dc->selectedLabels(QPoint(xpos, ypos))){
-          dist = 0;
-          return iter.key();
-      } else
-        dc->setLabelsSelected(false);
+      PlotCurve *c = (PlotCurve *)item;
+      DataCurve *dc = dynamic_cast<DataCurve *>(item);
+      if (!dc) continue;
+      if (c->type() != Graph::Function && dc->hasLabels() &&
+        dc->selectedLabels(QPoint(xpos, ypos))){
+          dist = 0;
+          return iter.key();
+      } else
+        dc->setLabelsSelected(false);
 
 			for (int i=0; i<c->dataSize(); i++)
 			{
@@ -702,203 +702,203 @@ 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::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).
-
-  @param painter :: Painter
-  @param plotRect :: Bounding rectangle
-  @param pfilter :: Print filter
-*/
-void Plot::print(QPainter *painter, const QRect &plotRect,
-        const QwtPlotPrintFilter &pfilter)
-{
-    int axisId;
-
-    if ( painter == 0 || !painter->isActive() ||
-            !plotRect.isValid() || size().isNull() )
-       return;
-
-    QwtText t = title();
-	printFrame(painter, plotRect);
-
-    painter->save();
-
-    // All paint operations need to be scaled according to
-    // the paint device metrics.
-
-    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 ...
-
-    pfilter.apply((QwtPlot *)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.
-
-        for (axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){
-            QwtScaleWidget *scaleWidget = (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 *)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);
-    }
-
-   // The canvas maps are already scaled.
-    QwtPainter::setMetricsMap(painter->device(), painter->device());
-    printCanvas(painter, canvasRect, map, pfilter);
-    QwtPainter::resetMetricsMap();
-
-
-  
-   canvasRect = plotLayout()->canvasRect();
-
-
-    for ( axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){
-        QwtScaleWidget *scaleWidget = (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);
-    }
-
-    
-
-    ((QwtPlot *)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 = (QwtScaleWidget *)axisWidget(axisId);
-            if ( scaleWidget  )
-                scaleWidget->setMargin(baseLineDists[axisId]);
-        }
-    }
-
-    pfilter.reset((QwtPlot *)this);
-    painter->restore();
-    setTitle(t);//hack used to avoid bug in Qwt::printTitle(): the title attributes are overwritten
+
+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::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).
+
+  @param painter :: Painter
+  @param plotRect :: Bounding rectangle
+  @param pfilter :: Print filter
+*/
+void Plot::print(QPainter *painter, const QRect &plotRect,
+        const QwtPlotPrintFilter &pfilter)
+{
+    int axisId;
+
+    if ( painter == 0 || !painter->isActive() ||
+            !plotRect.isValid() || size().isNull() )
+       return;
+
+    QwtText t = title();
+	printFrame(painter, plotRect);
+
+    painter->save();
+
+    // All paint operations need to be scaled according to
+    // the paint device metrics.
+
+    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 ...
+
+    pfilter.apply((QwtPlot *)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.
+
+        for (axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){
+            QwtScaleWidget *scaleWidget = (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 *)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);
+    }
+
+   // The canvas maps are already scaled.
+    QwtPainter::setMetricsMap(painter->device(), painter->device());
+    printCanvas(painter, canvasRect, map, pfilter);
+    QwtPainter::resetMetricsMap();
+
+
+  
+   canvasRect = plotLayout()->canvasRect();
+
+
+    for ( axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){
+        QwtScaleWidget *scaleWidget = (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);
+    }
+
+    
+
+    ((QwtPlot *)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 = (QwtScaleWidget *)axisWidget(axisId);
+            if ( scaleWidget  )
+                scaleWidget->setMargin(baseLineDists[axisId]);
+        }
+    }
+
+    pfilter.reset((QwtPlot *)this);
+    painter->restore();
+    setTitle(t);//hack used to avoid bug in Qwt::printTitle(): the title attributes are overwritten
 }
diff --git a/Code/Mantid/MantidPlot/src/Plot.h b/Code/Mantid/MantidPlot/src/Plot.h
index d5ab594e3ab28aba87e58b1f82d26d54173a696c..ec185e16e9ce3ab65897702c7ae17cbb7d4a68c8 100644
--- a/Code/Mantid/MantidPlot/src/Plot.h
+++ b/Code/Mantid/MantidPlot/src/Plot.h
@@ -94,24 +94,24 @@ public:
 	int axisLabelPrecision(int axis);
 
 	QColor frameColor();
-	const QColor & paletteBackgroundColor() const;
+	const QColor & paletteBackgroundColor() const;
 
     void print(QPainter *, const QRect &rect, const QwtPlotPrintFilter & = QwtPlotPrintFilter());
 	void updateLayout();
-
-    void updateCurveLabels();
 
-protected:
-    void showEvent (QShowEvent * event);
-    void printFrame(QPainter *painter, const QRect &rect) const;
+    void updateCurveLabels();
+
+protected:
+    void showEvent (QShowEvent * event);
+    void printFrame(QPainter *painter, const QRect &rect) const;
 	void printCanvas(QPainter *painter, const QRect &canvasRect,
    			 const QwtScaleMap map[axisCnt], const QwtPlotPrintFilter &pfilter) const;
 	virtual void drawItems (QPainter *painter, const QRect &rect,
 			const QwtScaleMap map[axisCnt], const QwtPlotPrintFilter &pfilter) 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;
+							const QwtScaleMap&map, int axis, bool min, bool maj) const;
+    void drawBreak(QPainter *painter, const QRect &rect, const QwtScaleMap &map, int axis) const;
 
 	Grid *d_grid;
 	QMap<int, QwtPlotItem*> d_curves;
diff --git a/Code/Mantid/MantidPlot/src/Plot3DDialog.cpp b/Code/Mantid/MantidPlot/src/Plot3DDialog.cpp
index d90e167e2f8c0f05c4e6732423aeee511f3a88b5..cad60e6fc8d9c9945cb2a2aa972a9fc9c6dd72c1 100644
--- a/Code/Mantid/MantidPlot/src/Plot3DDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/Plot3DDialog.cpp
@@ -31,7 +31,7 @@
 #include "MyParser.h"
 #include "SymbolDialog.h"
 #include "ApplicationWindow.h"
-#include "ColorButton.h"
+#include "ColorButton.h"
 #include "TextFormatButtons.h"
 
 #include <QListWidget>
@@ -198,15 +198,15 @@ void Plot3DDialog::initAxesPage()
 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);
+    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();
@@ -231,18 +231,18 @@ void Plot3DDialog::initTitlePage()
 
 void Plot3DDialog::initColorsPage()
 {
-    QGridLayout* vl1 = new QGridLayout();
-    btnFromColor = new ColorButton();
-    QLabel *maxLabel = new QLabel(tr( "&Max" ));
-    maxLabel->setBuddy(btnFromColor);
+    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);
+    vl1->addWidget(btnFromColor, 0, 1);
 
-	btnToColor = new ColorButton();
-	QLabel *minLabel = new QLabel(tr( "M&in" ));
-	minLabel->setBuddy(btnToColor);
+	btnToColor = new ColorButton();
+	QLabel *minLabel = new QLabel(tr( "M&in" ));
+	minLabel->setBuddy(btnToColor);
     vl1->addWidget(minLabel, 1, 0);
-    vl1->addWidget(btnToColor, 1, 1);
+    vl1->addWidget(btnToColor, 1, 1);
 
 	btnColorMap = new QPushButton(tr( "Color Ma&p" ));
     vl1->addWidget(btnColorMap, 2, 1);
@@ -251,16 +251,16 @@ void Plot3DDialog::initColorsPage()
     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);
+    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(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);
@@ -268,28 +268,28 @@ void Plot3DDialog::initColorsPage()
     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);
+    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(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);
+    gl1->addWidget(btnLabels, 1, 1);
 
-	btnNumbers = new ColorButton();
-	QLabel *numbersLabel = new QLabel(tr( "&Numbers" ));
-    numbersLabel->setBuddy(btnNumbers);
+	btnNumbers = new ColorButton();
+	QLabel *numbersLabel = new QLabel(tr( "&Numbers" ));
+    numbersLabel->setBuddy(btnNumbers);
 	gl1->addWidget(numbersLabel, 2, 0);
-    gl1->addWidget(btnNumbers, 2, 1);
+    gl1->addWidget(btnNumbers, 2, 1);
 
-	btnGrid = new ColorButton();
-	QLabel *gridLabel = new QLabel(tr( "&Grid" ));
-	gridLabel->setBuddy(btnGrid);
+	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);
@@ -907,7 +907,7 @@ void Plot3DDialog::showGeneralTab()
 
 void Plot3DDialog::showTitleTab()
 {
-	generalDialog->setCurrentWidget (title);
+	generalDialog->setCurrentWidget (title);
 }
 
 void Plot3DDialog::showAxisTab()
diff --git a/Code/Mantid/MantidPlot/src/Plot3DDialog.h b/Code/Mantid/MantidPlot/src/Plot3DDialog.h
index 4b4fdb648b2f71e554410b439728ee3bbf41b63c..fa9274858df749f1953cdd1ba077c2d1059ec5a5 100644
--- a/Code/Mantid/MantidPlot/src/Plot3DDialog.h
+++ b/Code/Mantid/MantidPlot/src/Plot3DDialog.h
@@ -45,7 +45,7 @@ class QWidget;
 class QStringList;
 class QStackedWidget;
 class QDoubleSpinBox;
-class ColorButton;
+class ColorButton;
 class TextFormatButtons;
 
 using namespace Qwt3D;
@@ -103,7 +103,7 @@ private:
     QPushButton* buttonApply;
     QPushButton* buttonOk;
     QPushButton* buttonCancel;
-	QPushButton *btnTitleFont, *btnLabelFont;
+	QPushButton *btnTitleFont, *btnLabelFont;
     QPushButton *btnNumbersFont, *btnTable, *btnColorMap;
 	ColorButton *btnBackground, *btnMesh, *btnAxes, *btnTitleColor, *btnLabels;
 	ColorButton *btnFromColor, *btnToColor, *btnNumbers, *btnGrid;
diff --git a/Code/Mantid/MantidPlot/src/PlotCurve.cpp b/Code/Mantid/MantidPlot/src/PlotCurve.cpp
index e273753275c95a2dd717c07327b8bd9fa190dc74..be82d8f45ec6b12c3d8edf0fe6153758225e9470 100644
--- a/Code/Mantid/MantidPlot/src/PlotCurve.cpp
+++ b/Code/Mantid/MantidPlot/src/PlotCurve.cpp
@@ -29,7 +29,7 @@
 #include "PlotCurve.h"
 #include "ScaleDraw.h"
 #include "SymbolBox.h"
-#include "PatternBox.h"
+#include "PatternBox.h"
 #include "plot2D/ScaleEngine.h"
 #include <QDateTime>
 #include <QMessageBox>
@@ -174,14 +174,14 @@ DataCurve::DataCurve(Table *t, const QString& xColName, const QString& name, int
 	d_table(t),
 	d_x_column(xColName),
 	d_start_row(startRow),
-	d_end_row(endRow),
+	d_end_row(endRow),
 	d_labels_column(QString()),
 	d_labels_color(Qt::black),
 	d_labels_font(QFont()),
 	d_labels_angle(0.0),
 	d_white_out_labels(false),
-	d_labels_align(Qt::AlignHCenter),
-	d_labels_x_offset(0),
+	d_labels_align(Qt::AlignHCenter),
+	d_labels_x_offset(0),
 	d_labels_y_offset(50),
 	d_selected_label(NULL)
 {
@@ -194,14 +194,14 @@ DataCurve::DataCurve(const DataCurve& c):
       d_table(c.d_table),
       d_x_column(c.d_x_column),
       d_start_row(c.d_start_row),
-      d_end_row(c.d_end_row),
+      d_end_row(c.d_end_row),
       d_labels_column(c.d_labels_column),
       d_labels_color(c.d_labels_color),
       d_labels_font(c.d_labels_font),
       d_labels_angle(c.d_labels_angle),
       d_white_out_labels(c.d_white_out_labels),
-      d_labels_align(c.d_labels_align),
-      d_labels_x_offset(c.d_labels_x_offset),
+      d_labels_align(c.d_labels_align),
+      d_labels_x_offset(c.d_labels_x_offset),
       d_labels_y_offset(c.d_labels_y_offset),
       d_selected_label(c.d_selected_label)
 {
@@ -259,25 +259,25 @@ void DataCurve::updateColumnNames(const QString& oldName, const QString& newName
         QStringList lst = s.split("_", QString::SkipEmptyParts);
         if (lst[0] == oldName)
             setTitle(newName + "_" + lst[1]);
-
+
         if (!d_x_column.isEmpty()){
             lst = d_x_column.split("_", QString::SkipEmptyParts);
             if (lst[0] == oldName)
-                d_x_column = newName + "_" + lst[1];
+                d_x_column = newName + "_" + lst[1];
         }
-    } else {
+    } else {
         if (title().text() == oldName)
             setTitle(newName);
         if (d_x_column == oldName)
-            d_x_column = newName;
+            d_x_column = newName;
     }
 }
 
 bool DataCurve::updateData(Table *t, const QString& colName)
 {
-	if (d_table != t ||
-       (colName != title().text() &&
-       colName != d_x_column &&
+	if (d_table != t ||
+       (colName != title().text() &&
+       colName != d_x_column &&
        colName != d_labels_column))
         return false;
 
@@ -286,7 +286,7 @@ bool DataCurve::updateData(Table *t, const QString& colName)
 }
 
 void DataCurve::loadData()
-{
+{
     Plot *plot = (Plot *)this->plot();
 	Graph *g = (Graph *)plot->parent();
 	if (!g)
@@ -383,26 +383,26 @@ void DataCurve::loadData()
 				g->setLabelsTextFormat(QwtPlot::yLeft, ScaleDraw::Text, d_x_column, xLabels);
 			else
                 g->setLabelsTextFormat(QwtPlot::xBottom, ScaleDraw::Text, d_x_column, xLabels);
-		} else if (xColType == Table::Time || xColType == Table::Date){
-			int axis = QwtPlot::xBottom;
-			if (d_type == Graph::HorizontalBars)
-                axis = QwtPlot::yLeft;
-            ScaleDraw *old_sd = (ScaleDraw *)plot->axisScaleDraw(axis);
-            ScaleDraw *sd = new ScaleDraw(plot, old_sd);
-            if (xColType == Table::Date)
-                sd->setDateTimeOrigin(date0);
-            else
-                sd->setDateTimeOrigin(QDateTime(QDate::currentDate(), time0));
+		} else if (xColType == Table::Time || xColType == Table::Date){
+			int axis = QwtPlot::xBottom;
+			if (d_type == Graph::HorizontalBars)
+                axis = QwtPlot::yLeft;
+            ScaleDraw *old_sd = (ScaleDraw *)plot->axisScaleDraw(axis);
+            ScaleDraw *sd = new ScaleDraw(plot, old_sd);
+            if (xColType == Table::Date)
+                sd->setDateTimeOrigin(date0);
+            else
+                sd->setDateTimeOrigin(QDateTime(QDate::currentDate(), time0));
             plot->setAxisScaleDraw(axis, sd);
 		}
 
 		if (yColType == Table::Text)
             g->setLabelsTextFormat(QwtPlot::yLeft, ScaleDraw::Text, title().text(), yLabels);
 	}
-
-    if (!d_labels_list.isEmpty()){
-        ((Graph*)plot->parent())->updatePlot();
-        loadLabels();
+
+    if (!d_labels_list.isEmpty()){
+        ((Graph*)plot->parent())->updatePlot();
+        loadLabels();
     }
 }
 
@@ -499,69 +499,69 @@ void DataCurve::setLabelsColumnName(const QString& name)
 	d_labels_column = name;
     loadLabels();
 }
-
-void DataCurve::loadLabels()
+
+void DataCurve::loadLabels()
 {
 	if (!validCurveType())
 		return;
-
-    clearLabels();
-
-    int xcol = d_table->colIndex(d_x_column);
-    int ycol = d_table->colIndex(title().text());
-    int labelsCol = d_table->colIndex(d_labels_column);
-    int cols = d_table->numCols();
-	if (xcol < 0 || ycol < 0 || labelsCol < 0 ||
-        xcol >= cols || ycol >= cols || labelsCol >= cols)
-		return;
-
-	QwtPlot *d_plot = plot();
-	if (!d_plot)
-		return;
-
-    int index = 0;
-	for (int i = d_start_row; i <= d_end_row; i++){
-		if (d_table->text(i, xcol).isEmpty() ||
-            d_table->text(i, ycol).isEmpty())
-            continue;
-
-		PlotMarker *m = new PlotMarker(index, d_labels_angle);
-
-		QwtText t = QwtText(d_table->text(i, labelsCol));
-		t.setColor(d_labels_color);
-		t.setFont(d_labels_font);
-		if (d_white_out_labels)
-			t.setBackgroundBrush(QBrush(Qt::white));
-        else
-            t.setBackgroundBrush(QBrush(Qt::transparent));
-		m->setLabel(t);
-
-        int x_axis = xAxis();
-        int y_axis = yAxis();
-		m->setAxis(x_axis, y_axis);
-
-		QSize size = t.textSize();
-        int dx = int(d_labels_x_offset*0.01*size.height());
-        int dy = -int((d_labels_y_offset*0.01 + 0.5)*size.height());
-        int x2 = d_plot->transform(x_axis, x(index)) + dx;
-        int y2 = d_plot->transform(y_axis, y(index)) + dy;
-        switch(d_labels_align){
-            case Qt::AlignLeft:
-            break;
-            case Qt::AlignHCenter:
-                x2 -= size.width()/2;
-            break;
-            case Qt::AlignRight:
-                x2 -= size.width();
-            break;
-        }
-        m->setXValue(d_plot->invTransform(x_axis, x2));
-        m->setYValue(d_plot->invTransform(y_axis, y2));
-		m->attach(d_plot);
-		d_labels_list << m;
-		index++;
-	}
-}
+
+    clearLabels();
+
+    int xcol = d_table->colIndex(d_x_column);
+    int ycol = d_table->colIndex(title().text());
+    int labelsCol = d_table->colIndex(d_labels_column);
+    int cols = d_table->numCols();
+	if (xcol < 0 || ycol < 0 || labelsCol < 0 ||
+        xcol >= cols || ycol >= cols || labelsCol >= cols)
+		return;
+
+	QwtPlot *d_plot = plot();
+	if (!d_plot)
+		return;
+
+    int index = 0;
+	for (int i = d_start_row; i <= d_end_row; i++){
+		if (d_table->text(i, xcol).isEmpty() ||
+            d_table->text(i, ycol).isEmpty())
+            continue;
+
+		PlotMarker *m = new PlotMarker(index, d_labels_angle);
+
+		QwtText t = QwtText(d_table->text(i, labelsCol));
+		t.setColor(d_labels_color);
+		t.setFont(d_labels_font);
+		if (d_white_out_labels)
+			t.setBackgroundBrush(QBrush(Qt::white));
+        else
+            t.setBackgroundBrush(QBrush(Qt::transparent));
+		m->setLabel(t);
+
+        int x_axis = xAxis();
+        int y_axis = yAxis();
+		m->setAxis(x_axis, y_axis);
+
+		QSize size = t.textSize();
+        int dx = int(d_labels_x_offset*0.01*size.height());
+        int dy = -int((d_labels_y_offset*0.01 + 0.5)*size.height());
+        int x2 = d_plot->transform(x_axis, x(index)) + dx;
+        int y2 = d_plot->transform(y_axis, y(index)) + dy;
+        switch(d_labels_align){
+            case Qt::AlignLeft:
+            break;
+            case Qt::AlignHCenter:
+                x2 -= size.width()/2;
+            break;
+            case Qt::AlignRight:
+                x2 -= size.width();
+            break;
+        }
+        m->setXValue(d_plot->invTransform(x_axis, x2));
+        m->setYValue(d_plot->invTransform(y_axis, y2));
+		m->attach(d_plot);
+		d_labels_list << m;
+		index++;
+	}
+}
 
 void DataCurve::clearLabels()
 {
@@ -571,192 +571,192 @@ void DataCurve::clearLabels()
 	foreach(PlotMarker *m, d_labels_list){
 		m->detach();
 		delete m;
-	}
+	}
 	d_labels_list.clear();
 }
-
-void DataCurve::setLabelsFont(const QFont& font)
+
+void DataCurve::setLabelsFont(const QFont& font)
 {
 	if (!validCurveType())
 		return;
-
-     if (font == d_labels_font)
-        return;
-
-    d_labels_font = font;
-
-    foreach(PlotMarker *m, d_labels_list){
-		QwtText t = m->label();
-		t.setFont(font);
-		m->setLabel(t);
-	}
-	updateLabelsPosition();
-}
-
-void DataCurve::setLabelsColor(const QColor& c)
+
+     if (font == d_labels_font)
+        return;
+
+    d_labels_font = font;
+
+    foreach(PlotMarker *m, d_labels_list){
+		QwtText t = m->label();
+		t.setFont(font);
+		m->setLabel(t);
+	}
+	updateLabelsPosition();
+}
+
+void DataCurve::setLabelsColor(const QColor& c)
 {
 	if (!validCurveType())
 		return;
-
-    if (c == d_labels_color)
-        return;
-
-    d_labels_color = c;
-
-    foreach(PlotMarker *m, d_labels_list){
-		QwtText t = m->label();
-		t.setColor(c);
-		m->setLabel(t);
-	}
-}
-
-void DataCurve::setLabelsAlignment(int flags)
+
+    if (c == d_labels_color)
+        return;
+
+    d_labels_color = c;
+
+    foreach(PlotMarker *m, d_labels_list){
+		QwtText t = m->label();
+		t.setColor(c);
+		m->setLabel(t);
+	}
+}
+
+void DataCurve::setLabelsAlignment(int flags)
 {
 	if (!validCurveType())
 		return;
-
-    if (flags == d_labels_align)
-        return;
-
-    d_labels_align = flags;
-    updateLabelsPosition();
-}
-
-void DataCurve::updateLabelsPosition()
+
+    if (flags == d_labels_align)
+        return;
+
+    d_labels_align = flags;
+    updateLabelsPosition();
+}
+
+void DataCurve::updateLabelsPosition()
 {
 	if (!validCurveType())
 		return;
-
-    QwtPlot *d_plot = plot();
-    if (!d_plot)
-        return;
-
-    foreach(PlotMarker *m, d_labels_list){
-        int index = m->index();
-        QSize size = m->label().textSize();
-        int x_axis = xAxis();
-        int y_axis = yAxis();
-        int dx = int(d_labels_x_offset*0.01*size.height());
-        int dy = -int((d_labels_y_offset*0.01 + 0.5)*size.height());
-        int x2 = d_plot->transform(x_axis, x(index)) + dx;
-        int y2 = d_plot->transform(y_axis, y(index)) + dy;
-        switch(d_labels_align){
-            case Qt::AlignLeft:
-            break;
-            case Qt::AlignHCenter:
-                x2 -= size.width()/2;
-            break;
-            case Qt::AlignRight:
-                x2 -= size.width();
-            break;
-        }
-        m->setXValue(d_plot->invTransform(x_axis, x2));
-        m->setYValue(d_plot->invTransform(y_axis, y2));
-	}
-}
-
-void DataCurve::setLabelsOffset(int x, int y)
+
+    QwtPlot *d_plot = plot();
+    if (!d_plot)
+        return;
+
+    foreach(PlotMarker *m, d_labels_list){
+        int index = m->index();
+        QSize size = m->label().textSize();
+        int x_axis = xAxis();
+        int y_axis = yAxis();
+        int dx = int(d_labels_x_offset*0.01*size.height());
+        int dy = -int((d_labels_y_offset*0.01 + 0.5)*size.height());
+        int x2 = d_plot->transform(x_axis, x(index)) + dx;
+        int y2 = d_plot->transform(y_axis, y(index)) + dy;
+        switch(d_labels_align){
+            case Qt::AlignLeft:
+            break;
+            case Qt::AlignHCenter:
+                x2 -= size.width()/2;
+            break;
+            case Qt::AlignRight:
+                x2 -= size.width();
+            break;
+        }
+        m->setXValue(d_plot->invTransform(x_axis, x2));
+        m->setYValue(d_plot->invTransform(y_axis, y2));
+	}
+}
+
+void DataCurve::setLabelsOffset(int x, int y)
 {
 	if (!validCurveType())
 		return;
-
-    if (x == d_labels_x_offset && y == d_labels_y_offset)
-        return;
-
-    d_labels_x_offset = x;
-    d_labels_y_offset = y;
-    updateLabelsPosition();
-}
-
-void DataCurve::setLabelsRotation(double angle)
+
+    if (x == d_labels_x_offset && y == d_labels_y_offset)
+        return;
+
+    d_labels_x_offset = x;
+    d_labels_y_offset = y;
+    updateLabelsPosition();
+}
+
+void DataCurve::setLabelsRotation(double angle)
 {
 	if (!validCurveType())
 		return;
-
-    if (angle == d_labels_angle)
-        return;
-
-    d_labels_angle = angle;
-
-    foreach(PlotMarker *m, d_labels_list)
-		m->setAngle(angle);
-}
-
-void DataCurve::setLabelsWhiteOut(bool whiteOut)
+
+    if (angle == d_labels_angle)
+        return;
+
+    d_labels_angle = angle;
+
+    foreach(PlotMarker *m, d_labels_list)
+		m->setAngle(angle);
+}
+
+void DataCurve::setLabelsWhiteOut(bool whiteOut)
 {
 	if (!validCurveType())
 		return;
-
-    if (whiteOut == d_white_out_labels)
-        return;
-
-    d_white_out_labels = whiteOut;
-
-    foreach(PlotMarker *m, d_labels_list){
-		QwtText t = m->label();
-		if (whiteOut)
-			t.setBackgroundBrush(QBrush(Qt::white));
-        else
-            t.setBackgroundBrush(QBrush(Qt::transparent));
-		m->setLabel(t);
-	}
-}
-
-void DataCurve::clone(DataCurve* c)
+
+    if (whiteOut == d_white_out_labels)
+        return;
+
+    d_white_out_labels = whiteOut;
+
+    foreach(PlotMarker *m, d_labels_list){
+		QwtText t = m->label();
+		if (whiteOut)
+			t.setBackgroundBrush(QBrush(Qt::white));
+        else
+            t.setBackgroundBrush(QBrush(Qt::transparent));
+		m->setLabel(t);
+	}
+}
+
+void DataCurve::clone(DataCurve* c)
 {
 	if (!validCurveType())
 		return;
-
-    d_labels_color = c->labelsColor();
-    d_labels_font = c->labelsFont();
-	d_labels_angle = c->labelsRotation();
-	d_white_out_labels = c->labelsWhiteOut();
-	d_labels_align = c->labelsAlignment();
-	d_labels_x_offset = c->labelsXOffset();
-	d_labels_y_offset = c->labelsYOffset();
-
-    if (!c->labelsColumnName().isEmpty()){
-        plot()->replot();
-        setLabelsColumnName(c->labelsColumnName());
-    }
-}
-
-QString DataCurve::saveToString()
+
+    d_labels_color = c->labelsColor();
+    d_labels_font = c->labelsFont();
+	d_labels_angle = c->labelsRotation();
+	d_white_out_labels = c->labelsWhiteOut();
+	d_labels_align = c->labelsAlignment();
+	d_labels_x_offset = c->labelsXOffset();
+	d_labels_y_offset = c->labelsYOffset();
+
+    if (!c->labelsColumnName().isEmpty()){
+        plot()->replot();
+        setLabelsColumnName(c->labelsColumnName());
+    }
+}
+
+QString DataCurve::saveToString()
 {
 	if (!validCurveType())
 		return QString();
-
-    if (d_labels_list.isEmpty() || type() == Graph::Function || type() == Graph::Box)
-        return QString();
-
-    QString s = "<CurveLabels>\n";
-    s += "\t<column>" + d_labels_column + "</column>\n";
-    s += "\t<color>" + d_labels_color.name() + "</color>\n";
-    s += "\t<whiteOut>" + QString::number(d_white_out_labels) + "</whiteOut>\n";
-    s += "\t<font>" + d_labels_font.family() + "\t";
-    s += QString::number(d_labels_font.pointSize()) + "\t";
-    s += QString::number(d_labels_font.bold()) + "\t";
-    s += QString::number(d_labels_font.italic()) + "\t";
-    s += QString::number(d_labels_font.underline()) + "</font>\n";
-    s += "\t<angle>" + QString::number(d_labels_angle) + "</angle>\n";
-    s += "\t<justify>" + QString::number(d_labels_align) + "</justify>\n";
-    if (d_labels_x_offset != 0.0)
-        s += "\t<xoffset>" + QString::number(d_labels_x_offset) + "</xoffset>\n";
-    if (d_labels_y_offset != 0.0)
-        s += "\t<yoffset>" + QString::number(d_labels_y_offset) + "</yoffset>\n";
-    return s + "</CurveLabels>\n";
-}
-
-bool DataCurve::selectedLabels(const QPoint& pos)
+
+    if (d_labels_list.isEmpty() || type() == Graph::Function || type() == Graph::Box)
+        return QString();
+
+    QString s = "<CurveLabels>\n";
+    s += "\t<column>" + d_labels_column + "</column>\n";
+    s += "\t<color>" + d_labels_color.name() + "</color>\n";
+    s += "\t<whiteOut>" + QString::number(d_white_out_labels) + "</whiteOut>\n";
+    s += "\t<font>" + d_labels_font.family() + "\t";
+    s += QString::number(d_labels_font.pointSize()) + "\t";
+    s += QString::number(d_labels_font.bold()) + "\t";
+    s += QString::number(d_labels_font.italic()) + "\t";
+    s += QString::number(d_labels_font.underline()) + "</font>\n";
+    s += "\t<angle>" + QString::number(d_labels_angle) + "</angle>\n";
+    s += "\t<justify>" + QString::number(d_labels_align) + "</justify>\n";
+    if (d_labels_x_offset != 0.0)
+        s += "\t<xoffset>" + QString::number(d_labels_x_offset) + "</xoffset>\n";
+    if (d_labels_y_offset != 0.0)
+        s += "\t<yoffset>" + QString::number(d_labels_y_offset) + "</yoffset>\n";
+    return s + "</CurveLabels>\n";
+}
+
+bool DataCurve::selectedLabels(const QPoint& pos)
 {
   if (!validCurveType())
     return false;
-
-  QwtPlot *d_plot = plot();
-  if (!d_plot)
-    return false;
 
-
+  QwtPlot *d_plot = plot();
+  if (!d_plot)
+    return false;
+
+
   bool selected = false;
   d_selected_label = NULL;
   foreach(PlotMarker *m, d_labels_list){
@@ -768,52 +768,52 @@ bool DataCurve::selectedLabels(const QPoint& pos)
       d_click_pos_y = d_plot->invTransform(yAxis(), pos.y());
       setLabelsSelected();
       return true;
-    }
-  }
-  return selected;
-}
-
-bool DataCurve::hasSelectedLabels()const
+    }
+  }
+  return selected;
+}
+
+bool DataCurve::hasSelectedLabels()const
 {
 	if (!validCurveType())
 		return false;
-
-    if (d_labels_list.isEmpty())
-        return false;
-
-    foreach(PlotMarker *m, d_labels_list){
-        if (m->label().backgroundPen() == QPen(Qt::blue))
-            return true;
-        else
-            return false;
-    }
-    return false;
-}
-
-void DataCurve::setLabelsSelected(bool on)
+
+    if (d_labels_list.isEmpty())
+        return false;
+
+    foreach(PlotMarker *m, d_labels_list){
+        if (m->label().backgroundPen() == QPen(Qt::blue))
+            return true;
+        else
+            return false;
+    }
+    return false;
+}
+
+void DataCurve::setLabelsSelected(bool on)
 {
 	if (!validCurveType())
 		return;
-
-    foreach(PlotMarker *m, d_labels_list){
-		QwtText t = m->label();
-		if(t.text().isEmpty())
-            continue;
-
-        if (on){
-            t.setBackgroundPen(QPen(Qt::blue));
-        } else
-            t.setBackgroundPen(QPen(Qt::NoPen));
-        m->setLabel(t);
-    }
-    if (on){
-        Graph *g = (Graph *)plot()->parent();
-        g->selectTitle(false);
-        g->deselectMarker();
-        g->notifyFontChange(d_labels_font);
-    }
-    plot()->replot();
-}
+
+    foreach(PlotMarker *m, d_labels_list){
+		QwtText t = m->label();
+		if(t.text().isEmpty())
+            continue;
+
+        if (on){
+            t.setBackgroundPen(QPen(Qt::blue));
+        } else
+            t.setBackgroundPen(QPen(Qt::NoPen));
+        m->setLabel(t);
+    }
+    if (on){
+        Graph *g = (Graph *)plot()->parent();
+        g->selectTitle(false);
+        g->deselectMarker();
+        g->notifyFontChange(d_labels_font);
+    }
+    plot()->replot();
+}
 
 bool DataCurve::validCurveType()const
 {
@@ -832,27 +832,27 @@ void DataCurve::moveLabels(const QPoint& pos)
 		return;
 	if (!d_selected_label || d_labels_list.isEmpty())
 		return;
-
-    QwtPlot *d_plot = plot();
-    if (!d_plot)
-        return;
-
+
+    QwtPlot *d_plot = plot();
+    if (!d_plot)
+        return;
+
     d_plot->replot();
     int d_x = pos.x() - d_plot->transform(xAxis(), d_click_pos_x);
 	int d_y = pos.y() - d_plot->transform(yAxis(), d_click_pos_y);
 
 	int height = d_selected_label->label().textSize().height();
 	d_labels_x_offset += int(d_x*100.0/(double)height);
-    d_labels_y_offset -= int(d_y*100.0/(double)height);
+    d_labels_y_offset -= int(d_y*100.0/(double)height);
 
 	updateLabelsPosition();
-	d_plot->replot();
-
-    ((Graph *)d_plot->parent())->notifyChanges();
+	d_plot->replot();
+
+    ((Graph *)d_plot->parent())->notifyChanges();
 
 	d_click_pos_x = d_plot->invTransform(xAxis(), pos.x());
 	d_click_pos_y = d_plot->invTransform(yAxis(), pos.y());
-}
+}
 
 PlotCurve* DataCurve::clone()const
 {
@@ -862,7 +862,7 @@ PlotCurve* DataCurve::clone()const
 PlotMarker::PlotMarker(int index, double angle):QwtPlotMarker(),
 	d_index(index),
 	d_angle(angle),
-	d_label_x_offset(0.0),
+	d_label_x_offset(0.0),
 	d_label_y_offset(0.0)
 {}
 
diff --git a/Code/Mantid/MantidPlot/src/PlotCurve.h b/Code/Mantid/MantidPlot/src/PlotCurve.h
index 7a4d37b8c04b4b83a68dfcb9698a2fb72bf8727b..7184b05747211b8efcfc02ca5ed29fc6b06343c5 100644
--- a/Code/Mantid/MantidPlot/src/PlotCurve.h
+++ b/Code/Mantid/MantidPlot/src/PlotCurve.h
@@ -83,11 +83,11 @@ class DataCurve: public PlotCurve
 public:
 	DataCurve(Table *t, const QString& xColName, const QString& name, int startRow = 0, int endRow = -1);
   DataCurve(const DataCurve& c);
-    void clone(DataCurve* c);
-
-    PlotCurve* clone()const;
-
-    QString saveToString();
+    void clone(DataCurve* c);
+
+    PlotCurve* clone()const;
+
+    QString saveToString();
 
 	QString xColumnName(){return d_x_column;};
 	void setXColumnName(const QString& name){d_x_column = name;};
@@ -95,25 +95,25 @@ public:
 	bool hasLabels()const{return !d_labels_list.isEmpty();};
 	QString labelsColumnName()const{return d_labels_column;};
 	void setLabelsColumnName(const QString& name);
-
-    int labelsAlignment()const{return d_labels_align;};
-    void setLabelsAlignment(int flags);
-
-    int labelsXOffset()const{return d_labels_x_offset;};
-    int labelsYOffset()const{return d_labels_y_offset;};
-    void setLabelsOffset(int x, int y);
-
-    double labelsRotation()const{return d_labels_angle;};
-    void setLabelsRotation(double angle);
-
-    QFont labelsFont()const{return d_labels_font;};
-    void setLabelsFont(const QFont& font);
-
-    QColor labelsColor()const{return d_labels_color;};
-    void setLabelsColor(const QColor& c);
-
-    bool labelsWhiteOut()const{return d_white_out_labels;};
-    void setLabelsWhiteOut(bool whiteOut = true);
+
+    int labelsAlignment()const{return d_labels_align;};
+    void setLabelsAlignment(int flags);
+
+    int labelsXOffset()const{return d_labels_x_offset;};
+    int labelsYOffset()const{return d_labels_y_offset;};
+    void setLabelsOffset(int x, int y);
+
+    double labelsRotation()const{return d_labels_angle;};
+    void setLabelsRotation(double angle);
+
+    QFont labelsFont()const{return d_labels_font;};
+    void setLabelsFont(const QFont& font);
+
+    QColor labelsColor()const{return d_labels_color;};
+    void setLabelsColor(const QColor& c);
+
+    bool labelsWhiteOut()const{return d_white_out_labels;};
+    void setLabelsWhiteOut(bool whiteOut = true);
 
 	Table* table()const{return d_table;};
 
@@ -158,18 +158,18 @@ public:
 	//! Clears the list of attached text labels.
 	void clearLabels();
 
-	void setVisible(bool on);
-
-	bool selectedLabels(const QPoint& pos);
-	bool hasSelectedLabels()const;
+	void setVisible(bool on);
+
+	bool selectedLabels(const QPoint& pos);
+	bool hasSelectedLabels()const;
 	void setLabelsSelected(bool on = true);
 
 	void moveLabels(const QPoint& pos);
-    void updateLabelsPosition();
+    void updateLabelsPosition();
 
 protected:
-	bool validCurveType()const;
-    void loadLabels();
+	bool validCurveType()const;
+    void loadLabels();
 
 	//! List of the error bar curves associated to this curve.
 	QList <DataCurve *> d_error_bars;
@@ -221,8 +221,8 @@ protected:
 
 	int d_index;
 	double d_angle;
-	double d_label_x_offset;
-	//! y coordinate offset
+	double d_label_x_offset;
+	//! y coordinate offset
 	double d_label_y_offset;
 };
 #endif
diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp
index b1a5c9b73f46bde76961191846af1d6302abf909..8786fa61bd88d553bd3f67002d71597bc616567c 100644
--- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp
@@ -43,7 +43,7 @@
 #include "QwtPieCurve.h"
 #include "ColorMapEditor.h"
 #include "pixmaps.h"
-#include "DoubleSpinBox.h"
+#include "DoubleSpinBox.h"
 #include "Folder.h"
 #include "ContourLinesEditor.h"
 #include "PenStyleBox.h"
@@ -106,13 +106,13 @@ PlotDialog::PlotDialog(bool showExtended, QWidget* parent, Qt::WFlags fl )
 	initBoxPage();
 	initPercentilePage();
 	initSpectrogramPage();
-	initPiePage();
-	initPieGeometryPage();
+	initPiePage();
+	initPieGeometryPage();
 	initPieLabelsPage();
 	initLayerPage();
 	initLayerGeometryPage();
 	initFontsPage();
-	initPrintPage();
+	initPrintPage();
 	initLabelsPage();
 	initContourLinesPage();
 
@@ -177,129 +177,129 @@ void PlotDialog::showAll(bool all)
 		btnMore->setText("&<<");
 	}
 }
-void PlotDialog::initContourLinesPage()
-{
-	ApplicationWindow *app = (ApplicationWindow *)parent();
-	QLocale locale = QLocale();
-	if (app)
-		locale = app->locale();
-
-  	contourLinesPage = new QWidget();
-
-  	levelsGroupBox = new QGroupBox(tr("&Show Contour Lines"));
-  	levelsGroupBox->setCheckable(true);
-  	QHBoxLayout *hl0 = new QHBoxLayout();
-
-	QGroupBox *gb1 = new QGroupBox(tr("Set Equidistant Levels"));
-    QGridLayout *hl1 = new QGridLayout(gb1);
-
-	hl1->addWidget(new QLabel(tr("Levels")), 0, 0);
-  	levelsBox = new QSpinBox();
-  	levelsBox->setRange(2, 1000);
-	hl1->addWidget(levelsBox, 0, 1);
-
-    hl1->addWidget(new QLabel(tr("Start")), 1, 0);
-  	firstContourLineBox = new DoubleSpinBox();
-  	firstContourLineBox->setLocale(locale);
-	firstContourLineBox->setDecimals(6);
-	hl1->addWidget(firstContourLineBox, 1, 1);
-
-    hl1->addWidget(new QLabel(tr("Step")), 2, 0);
-    contourLinesDistanceBox = new DoubleSpinBox();
-    contourLinesDistanceBox->setLocale(locale);
-	contourLinesDistanceBox->setDecimals(6);
-	hl1->addWidget(contourLinesDistanceBox, 2, 1);
-
-	btnSetEquidistantLevels = new QPushButton(tr("Set &Levels"));
-	connect(btnSetEquidistantLevels, SIGNAL(clicked()), this, SLOT(setEquidistantLevels()));
-	hl1->addWidget(btnSetEquidistantLevels, 3, 1);
-
-	hl1->setColumnStretch(1, 10);
-	hl1->setRowStretch(4, 1);
-
-	contourLinesEditor = new ContourLinesEditor(app->locale());
-	hl0->addWidget(contourLinesEditor);
-	hl0->addWidget(gb1);
-
-	QGroupBox *penGroupBox = new QGroupBox(tr("Pen"));
-	QHBoxLayout *hl2 = new QHBoxLayout(penGroupBox);
-
-    QVBoxLayout *vl1 = new QVBoxLayout;
-  	autoContourBox = new QRadioButton(tr("Use &Color Map"));
-  	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)));
-    vl1->addWidget(defaultContourBox);
-
-    customPenBtn = new QRadioButton(tr("Use &Table Custom Pen"));
-  	connect(customPenBtn, SIGNAL(toggled(bool)), this, SLOT(showCustomPenColumn(bool)));
-    vl1->addWidget(customPenBtn);
-
-	hl2->addLayout(vl1);
-
-  	defaultPenBox = new QGroupBox();
-    QGridLayout *gl1 = new QGridLayout(defaultPenBox);
-    gl1->addWidget(new QLabel(tr( "Color" )), 0, 0);
-
-  	levelsColorBox = new ColorButton(defaultPenBox);
-    gl1->addWidget(levelsColorBox, 0, 1);
-
-    gl1->addWidget(new QLabel(tr( "Width" )), 1, 0);
-  	contourWidthBox = new DoubleSpinBox('f');
-	contourWidthBox->setLocale(locale);
-	contourWidthBox->setSingleStep(0.1);
-    contourWidthBox->setRange(0, 100);
-    gl1->addWidget(contourWidthBox, 1, 1);
-
-    gl1->addWidget(new QLabel(tr( "Style" )), 2, 0);
-  	//penContourStyle = new PenStyleBox();
-	boxContourStyle = new PenStyleBox();
-    //gl1->addWidget((QWidget*)penContourStyle, 2, 1);
-	gl1->addWidget(boxContourStyle, 2, 1);
-    hl2->addWidget(defaultPenBox);
-
-	QVBoxLayout *vl0 = new QVBoxLayout(levelsGroupBox);
-	vl0->addLayout(hl0);
-	vl0->addWidget(penGroupBox);
-	vl0->addStretch();
-
-  	QVBoxLayout* vl2 = new QVBoxLayout(contourLinesPage);
-  	vl2->addWidget(levelsGroupBox);
-
-  	privateTabWidget->insertTab(contourLinesPage, tr("Contour Lines"));
-	//privateTabWidget->addTab(layerGeometryPage, tr("Contour Lines"));
-}
-void PlotDialog::setEquidistantLevels()
-{	
-	QTreeWidgetItem *it = listBox->currentItem();
-    if (!it)
-        return;
-
-	CurveTreeItem *item = (CurveTreeItem *)it;
-    QwtPlotItem *plotItem = (QwtPlotItem *)item->plotItem();
-    if (!plotItem)
-        return;
-
-	Spectrogram *sp = (Spectrogram *)plotItem;
-	if (!sp || sp->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
-		return;
-	
-
-	QwtValueList levels;
-	double firstVal = firstContourLineBox->value();
-	for (int i = 0; i < levelsBox->value(); i++)
-		levels << firstVal + i*contourLinesDistanceBox->value();
-	sp->setContourLevels(levels);
-	sp->plot()->replot();
-	contourLinesEditor->updateContents();
-}
-void PlotDialog::showCustomPenColumn(bool on)
-{
-  	contourLinesEditor->showPenColumn(on);
-  	if (on)
-		defaultPenBox->hide();
+void PlotDialog::initContourLinesPage()
+{
+	ApplicationWindow *app = (ApplicationWindow *)parent();
+	QLocale locale = QLocale();
+	if (app)
+		locale = app->locale();
+
+  	contourLinesPage = new QWidget();
+
+  	levelsGroupBox = new QGroupBox(tr("&Show Contour Lines"));
+  	levelsGroupBox->setCheckable(true);
+  	QHBoxLayout *hl0 = new QHBoxLayout();
+
+	QGroupBox *gb1 = new QGroupBox(tr("Set Equidistant Levels"));
+    QGridLayout *hl1 = new QGridLayout(gb1);
+
+	hl1->addWidget(new QLabel(tr("Levels")), 0, 0);
+  	levelsBox = new QSpinBox();
+  	levelsBox->setRange(2, 1000);
+	hl1->addWidget(levelsBox, 0, 1);
+
+    hl1->addWidget(new QLabel(tr("Start")), 1, 0);
+  	firstContourLineBox = new DoubleSpinBox();
+  	firstContourLineBox->setLocale(locale);
+	firstContourLineBox->setDecimals(6);
+	hl1->addWidget(firstContourLineBox, 1, 1);
+
+    hl1->addWidget(new QLabel(tr("Step")), 2, 0);
+    contourLinesDistanceBox = new DoubleSpinBox();
+    contourLinesDistanceBox->setLocale(locale);
+	contourLinesDistanceBox->setDecimals(6);
+	hl1->addWidget(contourLinesDistanceBox, 2, 1);
+
+	btnSetEquidistantLevels = new QPushButton(tr("Set &Levels"));
+	connect(btnSetEquidistantLevels, SIGNAL(clicked()), this, SLOT(setEquidistantLevels()));
+	hl1->addWidget(btnSetEquidistantLevels, 3, 1);
+
+	hl1->setColumnStretch(1, 10);
+	hl1->setRowStretch(4, 1);
+
+	contourLinesEditor = new ContourLinesEditor(app->locale());
+	hl0->addWidget(contourLinesEditor);
+	hl0->addWidget(gb1);
+
+	QGroupBox *penGroupBox = new QGroupBox(tr("Pen"));
+	QHBoxLayout *hl2 = new QHBoxLayout(penGroupBox);
+
+    QVBoxLayout *vl1 = new QVBoxLayout;
+  	autoContourBox = new QRadioButton(tr("Use &Color Map"));
+  	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)));
+    vl1->addWidget(defaultContourBox);
+
+    customPenBtn = new QRadioButton(tr("Use &Table Custom Pen"));
+  	connect(customPenBtn, SIGNAL(toggled(bool)), this, SLOT(showCustomPenColumn(bool)));
+    vl1->addWidget(customPenBtn);
+
+	hl2->addLayout(vl1);
+
+  	defaultPenBox = new QGroupBox();
+    QGridLayout *gl1 = new QGridLayout(defaultPenBox);
+    gl1->addWidget(new QLabel(tr( "Color" )), 0, 0);
+
+  	levelsColorBox = new ColorButton(defaultPenBox);
+    gl1->addWidget(levelsColorBox, 0, 1);
+
+    gl1->addWidget(new QLabel(tr( "Width" )), 1, 0);
+  	contourWidthBox = new DoubleSpinBox('f');
+	contourWidthBox->setLocale(locale);
+	contourWidthBox->setSingleStep(0.1);
+    contourWidthBox->setRange(0, 100);
+    gl1->addWidget(contourWidthBox, 1, 1);
+
+    gl1->addWidget(new QLabel(tr( "Style" )), 2, 0);
+  	//penContourStyle = new PenStyleBox();
+	boxContourStyle = new PenStyleBox();
+    //gl1->addWidget((QWidget*)penContourStyle, 2, 1);
+	gl1->addWidget(boxContourStyle, 2, 1);
+    hl2->addWidget(defaultPenBox);
+
+	QVBoxLayout *vl0 = new QVBoxLayout(levelsGroupBox);
+	vl0->addLayout(hl0);
+	vl0->addWidget(penGroupBox);
+	vl0->addStretch();
+
+  	QVBoxLayout* vl2 = new QVBoxLayout(contourLinesPage);
+  	vl2->addWidget(levelsGroupBox);
+
+  	privateTabWidget->insertTab(contourLinesPage, tr("Contour Lines"));
+	//privateTabWidget->addTab(layerGeometryPage, tr("Contour Lines"));
+}
+void PlotDialog::setEquidistantLevels()
+{	
+	QTreeWidgetItem *it = listBox->currentItem();
+    if (!it)
+        return;
+
+	CurveTreeItem *item = (CurveTreeItem *)it;
+    QwtPlotItem *plotItem = (QwtPlotItem *)item->plotItem();
+    if (!plotItem)
+        return;
+
+	Spectrogram *sp = (Spectrogram *)plotItem;
+	if (!sp || sp->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
+		return;
+	
+
+	QwtValueList levels;
+	double firstVal = firstContourLineBox->value();
+	for (int i = 0; i < levelsBox->value(); i++)
+		levels << firstVal + i*contourLinesDistanceBox->value();
+	sp->setContourLevels(levels);
+	sp->plot()->replot();
+	contourLinesEditor->updateContents();
+}
+void PlotDialog::showCustomPenColumn(bool on)
+{
+  	contourLinesEditor->showPenColumn(on);
+  	if (on)
+		defaultPenBox->hide();
 }
 
 void PlotDialog::showPlotAssociations(QTreeWidgetItem *item, int)
@@ -367,9 +367,9 @@ void PlotDialog::editCurve()
 }
 
 void PlotDialog::changePlotType(int plotType)
-{
-    if (boxPlotType->count() == 1)
-		return;
+{
+    if (boxPlotType->count() == 1)
+		return;
 
     CurveTreeItem *item = (CurveTreeItem *)listBox->currentItem();
     if (!item)
@@ -608,7 +608,7 @@ void PlotDialog::initPiePage()
 
 	gl1->addWidget(new QLabel(tr( "Width")), 2, 0);
 	boxPieLineWidth = new DoubleSpinBox('f');
-	boxPieLineWidth->setSingleStep(0.1);
+	boxPieLineWidth->setSingleStep(0.1);
 	boxPieLineWidth->setMinimum(0.0);
 	boxPieLineWidth->setLocale(((ApplicationWindow *)this->parent())->locale());
 	gl1->addWidget(boxPieLineWidth, 2, 1);
@@ -638,109 +638,109 @@ void PlotDialog::initPiePage()
 
 	privateTabWidget->addTab(piePage, tr( "Pattern" ) );
 }
-
-void PlotDialog::initPieGeometryPage()
-{
-    pieGeometryPage = new QWidget();
+
+void PlotDialog::initPieGeometryPage()
+{
+    pieGeometryPage = new QWidget();
 
 	QLocale locale = ((ApplicationWindow *)this->parent())->locale();
 
 	QGroupBox *gb3 = new QGroupBox(tr( "3D View" ));
 	QGridLayout *gl3 = new QGridLayout(gb3);
 	gl3->addWidget(new QLabel( tr( "View Angle (deg)" )), 0, 0);
-	boxPieViewAngle = new DoubleSpinBox('f');
-	boxPieViewAngle->setWrapping(true);
+	boxPieViewAngle = new DoubleSpinBox('f');
+	boxPieViewAngle->setWrapping(true);
 	boxPieViewAngle->setRange(0.0, 90.0);
 	boxPieViewAngle->setLocale(locale);
 	gl3->addWidget(boxPieViewAngle, 0, 1);
 
     gl3->addWidget(new QLabel( tr( "Thickness (% of radius)" )), 1, 0);
 	boxPieThickness = new DoubleSpinBox('f');
-	boxPieThickness->setLocale(locale);
+	boxPieThickness->setLocale(locale);
 	boxPieThickness->setRange(0.0, 300.0);
 	gl3->addWidget(boxPieThickness, 1, 1);
 	gl3->setRowStretch(2, 1);
 
 	QGroupBox *gb1 = new QGroupBox(tr( "Rotation" ));
-	QGridLayout *gl1 = new QGridLayout(gb1);
-	gl1->addWidget(new QLabel( tr( "Starting Azimuth (deg)" )), 0, 0);
-	boxPieStartAzimuth = new DoubleSpinBox('f');
-	boxPieStartAzimuth->setRange(0.0, 360.0);
-	boxPieStartAzimuth->setWrapping(true);
-	boxPieStartAzimuth->setSingleStep(10.0);
-	boxPieStartAzimuth->setLocale(locale);
-	gl1->addWidget(boxPieStartAzimuth, 0, 1);
-
-    boxPieConterClockwise = new QCheckBox(tr("Counter cloc&kwise"));
-	gl1->addWidget(boxPieConterClockwise, 1, 0);
+	QGridLayout *gl1 = new QGridLayout(gb1);
+	gl1->addWidget(new QLabel( tr( "Starting Azimuth (deg)" )), 0, 0);
+	boxPieStartAzimuth = new DoubleSpinBox('f');
+	boxPieStartAzimuth->setRange(0.0, 360.0);
+	boxPieStartAzimuth->setWrapping(true);
+	boxPieStartAzimuth->setSingleStep(10.0);
+	boxPieStartAzimuth->setLocale(locale);
+	gl1->addWidget(boxPieStartAzimuth, 0, 1);
+
+    boxPieConterClockwise = new QCheckBox(tr("Counter cloc&kwise"));
+	gl1->addWidget(boxPieConterClockwise, 1, 0);
 	gl1->setRowStretch(2, 1);
 
-	QGroupBox *gb2 = new QGroupBox(tr( "Radius/Center" ));
-	QGridLayout *gl2 = new QGridLayout(gb2);
-	gl2->addWidget(new QLabel( tr( "Radius (% of frame)" )), 0, 0);
-	boxRadius = new QSpinBox();
-	boxRadius->setRange(0, 300);
-	boxRadius->setSingleStep(5);
-	gl2->addWidget(boxRadius, 0, 1);
-    gl2->addWidget(new QLabel( tr( "Horizontal Offset (% of frame)" )), 1, 0);
-    boxPieOffset = new QSpinBox();
-	boxPieOffset->setRange(-100, 100);
-	gl2->addWidget(boxPieOffset, 1, 1);
-	gl2->setRowStretch(2, 1);
-
+	QGroupBox *gb2 = new QGroupBox(tr( "Radius/Center" ));
+	QGridLayout *gl2 = new QGridLayout(gb2);
+	gl2->addWidget(new QLabel( tr( "Radius (% of frame)" )), 0, 0);
+	boxRadius = new QSpinBox();
+	boxRadius->setRange(0, 300);
+	boxRadius->setSingleStep(5);
+	gl2->addWidget(boxRadius, 0, 1);
+    gl2->addWidget(new QLabel( tr( "Horizontal Offset (% of frame)" )), 1, 0);
+    boxPieOffset = new QSpinBox();
+	boxPieOffset->setRange(-100, 100);
+	gl2->addWidget(boxPieOffset, 1, 1);
+	gl2->setRowStretch(2, 1);
+
 	QVBoxLayout* vl = new QVBoxLayout(pieGeometryPage);
-	vl->addWidget(gb3);
-	vl->addWidget(gb1);
-	vl->addWidget(gb2);
-
-	privateTabWidget->addTab(pieGeometryPage, tr( "Pie Geometry" ) );
-
-    connect(boxPieConterClockwise, SIGNAL(toggled(bool)), this, SLOT(acceptParams()));
-    connect(boxPieViewAngle, SIGNAL(valueChanged(double)), this, SLOT(acceptParams()));
-    connect(boxPieThickness, SIGNAL(valueChanged(double)), this, SLOT(acceptParams()));
-    connect(boxPieStartAzimuth, SIGNAL(valueChanged(double)), this, SLOT(acceptParams()));
-    connect(boxRadius, SIGNAL(valueChanged(int)), this, SLOT(acceptParams()));
-    connect(boxPieOffset, SIGNAL(valueChanged(int)), this, SLOT(acceptParams()));
-}
-
-void PlotDialog::initPieLabelsPage()
-{
-	pieLabelsPage = new QWidget();
-
-    pieAutoLabelsBox = new QGroupBox(tr("Automatic &Format"));
-	pieAutoLabelsBox->setCheckable(true);
-
-	QGridLayout *gl1 = new QGridLayout(pieAutoLabelsBox);
-	boxPieValues = new QCheckBox(tr("&Values"));
-	gl1->addWidget(boxPieValues, 0, 0);
-
-	boxPiePercentages = new QCheckBox(tr("&Percentages"));
+	vl->addWidget(gb3);
+	vl->addWidget(gb1);
+	vl->addWidget(gb2);
+
+	privateTabWidget->addTab(pieGeometryPage, tr( "Pie Geometry" ) );
+
+    connect(boxPieConterClockwise, SIGNAL(toggled(bool)), this, SLOT(acceptParams()));
+    connect(boxPieViewAngle, SIGNAL(valueChanged(double)), this, SLOT(acceptParams()));
+    connect(boxPieThickness, SIGNAL(valueChanged(double)), this, SLOT(acceptParams()));
+    connect(boxPieStartAzimuth, SIGNAL(valueChanged(double)), this, SLOT(acceptParams()));
+    connect(boxRadius, SIGNAL(valueChanged(int)), this, SLOT(acceptParams()));
+    connect(boxPieOffset, SIGNAL(valueChanged(int)), this, SLOT(acceptParams()));
+}
+
+void PlotDialog::initPieLabelsPage()
+{
+	pieLabelsPage = new QWidget();
+
+    pieAutoLabelsBox = new QGroupBox(tr("Automatic &Format"));
+	pieAutoLabelsBox->setCheckable(true);
+
+	QGridLayout *gl1 = new QGridLayout(pieAutoLabelsBox);
+	boxPieValues = new QCheckBox(tr("&Values"));
+	gl1->addWidget(boxPieValues, 0, 0);
+
+	boxPiePercentages = new QCheckBox(tr("&Percentages"));
 	gl1->addWidget(boxPiePercentages, 1, 0);
 
 	boxPieCategories = new QCheckBox(tr("Categories/&Rows"));
 	gl1->addWidget(boxPieCategories, 2, 0);
-
-	gl1->setRowStretch(3, 1);
-
-    boxPieWedge = new QGroupBox(tr( "Associate Position with &Wedge" ));
-	boxPieWedge->setCheckable(true);
-
-	QGridLayout *gl2 = new QGridLayout(boxPieWedge);
-	gl2->addWidget(new QLabel( tr( "Dist. from Pie Edge" )), 0, 0);
-	boxPieEdgeDist = new DoubleSpinBox('f');
-	boxPieEdgeDist->setRange(-100, 100);
-	boxPieEdgeDist->setLocale(((ApplicationWindow *)this->parent())->locale());
-	gl2->addWidget(boxPieEdgeDist, 0, 1);
-	gl2->setRowStretch(1, 1);
-
-	QVBoxLayout* vl = new QVBoxLayout(pieLabelsPage);
-	vl->addWidget(pieAutoLabelsBox);
-	vl->addWidget(boxPieWedge);
-
-	privateTabWidget->addTab(pieLabelsPage, tr( "Labels" ) );
-
-    connect(boxPieEdgeDist, SIGNAL(valueChanged(double)), this, SLOT(acceptParams()));
-}
+
+	gl1->setRowStretch(3, 1);
+
+    boxPieWedge = new QGroupBox(tr( "Associate Position with &Wedge" ));
+	boxPieWedge->setCheckable(true);
+
+	QGridLayout *gl2 = new QGridLayout(boxPieWedge);
+	gl2->addWidget(new QLabel( tr( "Dist. from Pie Edge" )), 0, 0);
+	boxPieEdgeDist = new DoubleSpinBox('f');
+	boxPieEdgeDist->setRange(-100, 100);
+	boxPieEdgeDist->setLocale(((ApplicationWindow *)this->parent())->locale());
+	gl2->addWidget(boxPieEdgeDist, 0, 1);
+	gl2->setRowStretch(1, 1);
+
+	QVBoxLayout* vl = new QVBoxLayout(pieLabelsPage);
+	vl->addWidget(pieAutoLabelsBox);
+	vl->addWidget(boxPieWedge);
+
+	privateTabWidget->addTab(pieLabelsPage, tr( "Labels" ) );
+
+    connect(boxPieEdgeDist, SIGNAL(valueChanged(double)), this, SLOT(acceptParams()));
+}
 
 void PlotDialog::initPrintPage()
 {
@@ -757,69 +757,69 @@ void PlotDialog::initPrintPage()
 	hlayout->addWidget(gb);
 	privateTabWidget->addTab(printPage, tr( "Print" ) );
 }
-
-void PlotDialog::initLabelsPage()
-{
-    labelsGroupBox = new QGroupBox(tr("&Show"));
-    labelsGroupBox->setCheckable (true);
-
-    QGridLayout *gl = new QGridLayout(labelsGroupBox);
-	labelsColumnLbl = new QLabel(tr( "Column" ));
-	gl->addWidget(labelsColumnLbl, 0, 0);
-    boxLabelsColumn = new QComboBox();
-    gl->addWidget(boxLabelsColumn, 0, 1);
-	  
-    gl->addWidget(new QLabel(tr( "Color" )), 1, 0);
-    boxLabelsColor = new ColorBox();
-    gl->addWidget(boxLabelsColor, 1, 1);
-    boxLabelsWhiteOut = new QCheckBox(tr("White O&ut"));
-    gl->addWidget(boxLabelsWhiteOut, 1, 2);
-
-  	justifyLabelsLbl = new QLabel(tr( "Justify" ));
-    gl->addWidget(justifyLabelsLbl, 2, 0);
-    boxLabelsAlign = new QComboBox();
-    boxLabelsAlign->addItem( tr( "Center" ) );
-    boxLabelsAlign->addItem( tr( "Left" ) );
-    boxLabelsAlign->addItem( tr( "Right" ) );
-    gl->addWidget(boxLabelsAlign, 2, 1);
-
-    gl->addWidget(new QLabel(tr( "Rotate (deg)" )), 3, 0);
-    boxLabelsAngle = new DoubleSpinBox('f');
-    boxLabelsAngle->setDecimals(1);
-    boxLabelsAngle->setLocale(((ApplicationWindow *)parent())->locale());
-    boxLabelsAngle->setRange(0, 180);
-    gl->addWidget(boxLabelsAngle, 3, 1);
-
-    gl->addWidget(new QLabel(tr("X Offset (font height %)")), 4, 0);
-    boxLabelsXOffset = new QSpinBox();
-    boxLabelsXOffset->setRange(-INT_MAX, INT_MAX);
-    boxLabelsXOffset->setSingleStep(10);
-    gl->addWidget(boxLabelsXOffset, 4, 1);
-	
-    gl->addWidget(new QLabel(tr("Y Offset (font height %)")), 5, 0);
-    boxLabelsYOffset = new QSpinBox();
-    boxLabelsYOffset->setRange(-INT_MAX, INT_MAX);
-    boxLabelsYOffset->setSingleStep(10);
-    gl->addWidget(boxLabelsYOffset, 5, 1);
-    gl->setRowStretch (6, 1);
-    gl->setColumnStretch (3, 1);
-
-	labelsPage = new QWidget();
-	QHBoxLayout* hlayout = new QHBoxLayout(labelsPage);
-	hlayout->addWidget(labelsGroupBox);
-	privateTabWidget->addTab(labelsPage, tr("Labels"));
-	//privateTabWidget->setTabEnabled(3,true);
-
-    connect(labelsGroupBox, SIGNAL(toggled(bool)), this, SLOT(acceptParams()));
-    connect(boxLabelsColumn, SIGNAL(activated(int)), this, SLOT(acceptParams()));
-    connect(boxLabelsAlign, SIGNAL(activated(int)), this, SLOT(acceptParams()));
-    connect(boxLabelsWhiteOut, SIGNAL(toggled(bool)), this, SLOT(acceptParams()));
-    connect(boxLabelsColor, SIGNAL(activated(int)), this, SLOT(acceptParams()));
-    connect(boxLabelsXOffset, SIGNAL(valueChanged(int)), this, SLOT(acceptParams()));
-    connect(boxLabelsYOffset, SIGNAL(valueChanged(int)), this, SLOT(acceptParams()));
-    connect(boxLabelsAngle, SIGNAL(valueChanged(double)), this, SLOT(acceptParams()));
-    //connect(btnLabelsFont, SIGNAL(clicked()), this, SLOT(chooseLabelsFont()));
-}
+
+void PlotDialog::initLabelsPage()
+{
+    labelsGroupBox = new QGroupBox(tr("&Show"));
+    labelsGroupBox->setCheckable (true);
+
+    QGridLayout *gl = new QGridLayout(labelsGroupBox);
+	labelsColumnLbl = new QLabel(tr( "Column" ));
+	gl->addWidget(labelsColumnLbl, 0, 0);
+    boxLabelsColumn = new QComboBox();
+    gl->addWidget(boxLabelsColumn, 0, 1);
+	  
+    gl->addWidget(new QLabel(tr( "Color" )), 1, 0);
+    boxLabelsColor = new ColorBox();
+    gl->addWidget(boxLabelsColor, 1, 1);
+    boxLabelsWhiteOut = new QCheckBox(tr("White O&ut"));
+    gl->addWidget(boxLabelsWhiteOut, 1, 2);
+
+  	justifyLabelsLbl = new QLabel(tr( "Justify" ));
+    gl->addWidget(justifyLabelsLbl, 2, 0);
+    boxLabelsAlign = new QComboBox();
+    boxLabelsAlign->addItem( tr( "Center" ) );
+    boxLabelsAlign->addItem( tr( "Left" ) );
+    boxLabelsAlign->addItem( tr( "Right" ) );
+    gl->addWidget(boxLabelsAlign, 2, 1);
+
+    gl->addWidget(new QLabel(tr( "Rotate (deg)" )), 3, 0);
+    boxLabelsAngle = new DoubleSpinBox('f');
+    boxLabelsAngle->setDecimals(1);
+    boxLabelsAngle->setLocale(((ApplicationWindow *)parent())->locale());
+    boxLabelsAngle->setRange(0, 180);
+    gl->addWidget(boxLabelsAngle, 3, 1);
+
+    gl->addWidget(new QLabel(tr("X Offset (font height %)")), 4, 0);
+    boxLabelsXOffset = new QSpinBox();
+    boxLabelsXOffset->setRange(-INT_MAX, INT_MAX);
+    boxLabelsXOffset->setSingleStep(10);
+    gl->addWidget(boxLabelsXOffset, 4, 1);
+	
+    gl->addWidget(new QLabel(tr("Y Offset (font height %)")), 5, 0);
+    boxLabelsYOffset = new QSpinBox();
+    boxLabelsYOffset->setRange(-INT_MAX, INT_MAX);
+    boxLabelsYOffset->setSingleStep(10);
+    gl->addWidget(boxLabelsYOffset, 5, 1);
+    gl->setRowStretch (6, 1);
+    gl->setColumnStretch (3, 1);
+
+	labelsPage = new QWidget();
+	QHBoxLayout* hlayout = new QHBoxLayout(labelsPage);
+	hlayout->addWidget(labelsGroupBox);
+	privateTabWidget->addTab(labelsPage, tr("Labels"));
+	//privateTabWidget->setTabEnabled(3,true);
+
+    connect(labelsGroupBox, SIGNAL(toggled(bool)), this, SLOT(acceptParams()));
+    connect(boxLabelsColumn, SIGNAL(activated(int)), this, SLOT(acceptParams()));
+    connect(boxLabelsAlign, SIGNAL(activated(int)), this, SLOT(acceptParams()));
+    connect(boxLabelsWhiteOut, SIGNAL(toggled(bool)), this, SLOT(acceptParams()));
+    connect(boxLabelsColor, SIGNAL(activated(int)), this, SLOT(acceptParams()));
+    connect(boxLabelsXOffset, SIGNAL(valueChanged(int)), this, SLOT(acceptParams()));
+    connect(boxLabelsYOffset, SIGNAL(valueChanged(int)), this, SLOT(acceptParams()));
+    connect(boxLabelsAngle, SIGNAL(valueChanged(double)), this, SLOT(acceptParams()));
+    //connect(btnLabelsFont, SIGNAL(clicked()), this, SLOT(chooseLabelsFont()));
+}
 
 void PlotDialog::initAxesPage()
 {
@@ -1424,8 +1424,8 @@ void PlotDialog::setMultiLayer(MultiLayer *ml)
     listBox->addTopLevelItem(item);
     listBox->setCurrentItem(item);
 
-    QList<Graph *> layers = ml->layersList();
-    int i = 0;
+    QList<Graph *> layers = ml->layersList();
+    int i = 0;
     foreach(Graph *g, layers){
         LayerItem *layer = new LayerItem(g, item, tr("Layer") + QString::number(++i));
         item->addChild(layer);
@@ -1675,7 +1675,7 @@ void PlotDialog::updateTabWindow(QTreeWidgetItem *currentItem, QTreeWidgetItem *
            ((CurveTreeItem *)previousItem)->plotItemType() != curveItem->plotItemType()||forceClearTabs)
         {
 	         clearTabWidget();
-            int plot_type = setPlotType(curveItem);
+            int plot_type = setPlotType(curveItem);
 			if (plot_type >= 0)
 				insertTabs(plot_type);
             if (!curvePlotTypeBox->isVisible())
@@ -1712,8 +1712,8 @@ void PlotDialog::insertTabs(int plot_type)
 {
     if (plot_type == Graph::Pie)
 	{
-		privateTabWidget->addTab (piePage, tr("Pattern"));
-		privateTabWidget->addTab (pieGeometryPage, tr("Pie Geometry"));
+		privateTabWidget->addTab (piePage, tr("Pattern"));
+		privateTabWidget->addTab (pieGeometryPage, tr("Pie Geometry"));
 		privateTabWidget->addTab (pieLabelsPage, tr("Labels"));
 		privateTabWidget->showPage(piePage);
 		return;
@@ -1774,25 +1774,25 @@ void PlotDialog::insertTabs(int plot_type)
 		privateTabWidget->addTab (linePage, tr("Pattern"));
 		privateTabWidget->addTab (boxPage, tr("Box/Whiskers"));
 		privateTabWidget->addTab (percentilePage, tr("Percentile"));
-		privateTabWidget->showPage(linePage);
+		privateTabWidget->showPage(linePage);
 		return;
 	}
 	else if (plot_type == Graph::ColorMap || plot_type == Graph::GrayScale || plot_type == Graph::Contour)
   	{
   		privateTabWidget->addTab(spectrogramPage, tr("Colors"));
 		privateTabWidget->addTab(contourLinesPage, tr("Contour Lines"));
-  	    privateTabWidget->showPage(spectrogramPage);
-		privateTabWidget->addTab(labelsPage, tr("Labels"));
+  	    privateTabWidget->showPage(spectrogramPage);
+		privateTabWidget->addTab(labelsPage, tr("Labels"));
   	    return;
-  	}
-
-  	QTreeWidgetItem *item = listBox->currentItem();
-    if (!item || item->type() != CurveTreeItem::PlotCurveTreeItem)
-        return;
-
-    const DataCurve *c = dynamic_cast<const DataCurve *>(((CurveTreeItem *)item)->plotItem() );
-    if (!c) return;
-    if (c && c->type() != Graph::Function){
+  	}
+
+  	QTreeWidgetItem *item = listBox->currentItem();
+    if (!item || item->type() != CurveTreeItem::PlotCurveTreeItem)
+        return;
+
+    const DataCurve *c = dynamic_cast<const DataCurve *>(((CurveTreeItem *)item)->plotItem() );
+    if (!c) return;
+    if (c && c->type() != Graph::Function){
         privateTabWidget->addTab (labelsPage, tr("Labels"));
 		if (c->hasSelectedLabels())
 			privateTabWidget->showPage(labelsPage);
@@ -1800,7 +1800,7 @@ void PlotDialog::insertTabs(int plot_type)
 }
 
 void PlotDialog::clearTabWidget()
-{
+{
     privateTabWidget->removeTab(privateTabWidget->indexOf(labelsPage));
     privateTabWidget->removeTab(privateTabWidget->indexOf(axesPage));
 	privateTabWidget->removeTab(privateTabWidget->indexOf(linePage));
@@ -1812,7 +1812,7 @@ void PlotDialog::clearTabWidget()
 	privateTabWidget->removeTab(privateTabWidget->indexOf(boxPage));
 	privateTabWidget->removeTab(privateTabWidget->indexOf(percentilePage));
 	privateTabWidget->removeTab(privateTabWidget->indexOf(spectrogramPage));
-    privateTabWidget->removeTab(privateTabWidget->indexOf(piePage));
+    privateTabWidget->removeTab(privateTabWidget->indexOf(piePage));
     privateTabWidget->removeTab(privateTabWidget->indexOf(pieGeometryPage));
     privateTabWidget->removeTab(privateTabWidget->indexOf(pieLabelsPage));
 	privateTabWidget->removeTab(privateTabWidget->indexOf(layerPage));
@@ -1948,14 +1948,14 @@ void PlotDialog::setActiveLayer(LayerItem *item)
 
 	aspect_ratio = (double)p->size().width()/(double)p->size().height();
 }
-void PlotDialog::updateContourLevelsDisplay(Spectrogram *sp)
-{
-	QwtValueList levels = sp->contourLevels();
-	levelsBox->setValue(levels.size());
-	if (levels.size() >= 1)
-		firstContourLineBox->setValue(levels[0]);
-	if (levels.size() >= 2)
-		contourLinesDistanceBox->setValue(fabs(levels[1] - levels[0]));
+void PlotDialog::updateContourLevelsDisplay(Spectrogram *sp)
+{
+	QwtValueList levels = sp->contourLevels();
+	levelsBox->setValue(levels.size());
+	if (levels.size() >= 1)
+		firstContourLineBox->setValue(levels[0]);
+	if (levels.size() >= 2)
+		contourLinesDistanceBox->setValue(fabs(levels[1] - levels[0]));
 }
 void PlotDialog::setActiveCurve(CurveTreeItem *item)
 {
@@ -2002,34 +2002,34 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
             boxContourStyle->setCurrentIndex(sp->defaultContourPen().style() - 1);
 	     else
             boxContourStyle->setCurrentIndex(0);
-		contourLinesEditor->setSpectrogram(sp);
+		contourLinesEditor->setSpectrogram(sp);
 		updateContourLevelsDisplay(sp);
 
         axisScaleBox->setChecked(sp->hasColorScale());
         colorScaleBox->setCurrentItem((int)sp->colorScaleAxis());
         colorScaleWidthBox->setValue(sp->colorBarWidth());
-		
-        //labels page
-
-        showAllLabelControls(false);
-
-        labelsGroupBox->blockSignals(true);
-        labelsGroupBox->setEnabled(sp->testDisplayMode(QwtPlotSpectrogram::ContourMode));
-		labelsGroupBox->setChecked(sp->hasLabels() && sp->testDisplayMode(QwtPlotSpectrogram::ContourMode));
-		boxLabelsColor->setColor(sp->labelsColor());
-		boxLabelsAngle->setValue(sp->labelsRotation());
-
-		boxLabelsXOffset->blockSignals(true);
-		boxLabelsXOffset->setValue(qRound(sp->labelsXOffset()));
-		boxLabelsXOffset->blockSignals(false);
-
-		boxLabelsYOffset->blockSignals(true);
-		boxLabelsYOffset->setValue(qRound(sp->labelsYOffset()));
-		boxLabelsYOffset->blockSignals(false);
-		boxLabelsWhiteOut->setChecked(sp->labelsWhiteOut());
-		labelsGroupBox->blockSignals(false);
-
-		if (sp->hasSelectedLabels())
+		
+        //labels page
+
+        showAllLabelControls(false);
+
+        labelsGroupBox->blockSignals(true);
+        labelsGroupBox->setEnabled(sp->testDisplayMode(QwtPlotSpectrogram::ContourMode));
+		labelsGroupBox->setChecked(sp->hasLabels() && sp->testDisplayMode(QwtPlotSpectrogram::ContourMode));
+		boxLabelsColor->setColor(sp->labelsColor());
+		boxLabelsAngle->setValue(sp->labelsRotation());
+
+		boxLabelsXOffset->blockSignals(true);
+		boxLabelsXOffset->setValue(qRound(sp->labelsXOffset()));
+		boxLabelsXOffset->blockSignals(false);
+
+		boxLabelsYOffset->blockSignals(true);
+		boxLabelsYOffset->setValue(qRound(sp->labelsYOffset()));
+		boxLabelsYOffset->blockSignals(false);
+		boxLabelsWhiteOut->setChecked(sp->labelsWhiteOut());
+		labelsGroupBox->blockSignals(false);
+
+		if (sp->hasSelectedLabels())
 			privateTabWidget->showPage(labelsPage);
 	      return;
     }
@@ -2044,38 +2044,38 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
     if (curveType == Graph::Pie){
         QwtPieCurve *pie = (QwtPieCurve*)i;
         boxPiePattern->setPattern(pie->pattern());
-        boxPieLineWidth->setValue(pie->pen().widthF());
-        boxPieLineColor->setColor(pie->pen().color());
-        setPiePenStyle(pie->pen().style());
-        boxFirstColor->setCurrentIndex(pie->firstColor());
-
+        boxPieLineWidth->setValue(pie->pen().widthF());
+        boxPieLineColor->setColor(pie->pen().color());
+        setPiePenStyle(pie->pen().style());
+        boxFirstColor->setCurrentIndex(pie->firstColor());
+
         boxPieViewAngle->blockSignals(true);
-		boxPieViewAngle->setValue(pie->viewAngle());
-		boxPieViewAngle->blockSignals(false);
+		boxPieViewAngle->setValue(pie->viewAngle());
+		boxPieViewAngle->blockSignals(false);
 		boxPieThickness->blockSignals(true);
-		boxPieThickness->setValue(pie->thickness());
-		boxPieThickness->blockSignals(false);
+		boxPieThickness->setValue(pie->thickness());
+		boxPieThickness->blockSignals(false);
 		boxPieStartAzimuth->blockSignals(true);
-		boxPieStartAzimuth->setValue(pie->startAzimuth());
+		boxPieStartAzimuth->setValue(pie->startAzimuth());
 		boxPieStartAzimuth->blockSignals(false);
 		boxPieConterClockwise->blockSignals(true);
 		boxPieConterClockwise->setChecked(pie->counterClockwise());
-		boxPieConterClockwise->blockSignals(false);
-		boxRadius->blockSignals(true);
-        boxRadius->setValue(pie->radius());
-        boxRadius->blockSignals(false);
-        boxPieOffset->blockSignals(true);
-        boxPieOffset->setValue((int)pie->horizontalOffset());
-        boxPieOffset->blockSignals(false);
-
-		pieAutoLabelsBox->setChecked(pie->labelsAutoFormat());
-		boxPieValues->setChecked(pie->labelsValuesFormat());
+		boxPieConterClockwise->blockSignals(false);
+		boxRadius->blockSignals(true);
+        boxRadius->setValue(pie->radius());
+        boxRadius->blockSignals(false);
+        boxPieOffset->blockSignals(true);
+        boxPieOffset->setValue((int)pie->horizontalOffset());
+        boxPieOffset->blockSignals(false);
+
+		pieAutoLabelsBox->setChecked(pie->labelsAutoFormat());
+		boxPieValues->setChecked(pie->labelsValuesFormat());
 		boxPiePercentages->setChecked(pie->labelsPercentagesFormat());
-		boxPieCategories->setChecked(pie->labelCategories());
-		boxPieEdgeDist->blockSignals(true);
-		boxPieEdgeDist->setValue(pie->labelsEdgeDistance());
-		boxPieEdgeDist->blockSignals(false);
-		boxPieWedge->setChecked(pie->fixedLabelsPosition());
+		boxPieCategories->setChecked(pie->labelCategories());
+		boxPieEdgeDist->blockSignals(true);
+		boxPieEdgeDist->setValue(pie->labelsEdgeDistance());
+		boxPieEdgeDist->blockSignals(false);
+		boxPieWedge->setChecked(pie->fixedLabelsPosition());
         return;
     }
 
@@ -2107,10 +2107,10 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
     boxFillSymbol->setChecked(s.brush() != Qt::NoBrush);
     boxFillColor->setEnabled(s.brush() != Qt::NoBrush);
     boxFillColor->setColor(s.brush().color());
-
-    if (c->type() == Graph::Function)
-        return;
-
+
+    if (c->type() == Graph::Function)
+        return;
+
     if (curveType == Graph::VerticalBars || curveType == Graph::HorizontalBars ||
 				curveType == Graph::Histogram){//spacing page
         QwtBarCurve *b = (QwtBarCurve*)i;
@@ -2206,57 +2206,57 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item)
                 boxWhiskersCoef->setValue((int)b->whiskersRange());
         }
 		return;
-    }
-
+    }
+
     const DataCurve *dc = dynamic_cast<const DataCurve *>(i);
     if (!dc) return;
 	if (!dc->table()){
 		privateTabWidget->removeTab(privateTabWidget->indexOf(labelsPage));
 		return;
-	}
-    labelsGroupBox->blockSignals(true);
-    labelsGroupBox->setChecked(dc->hasLabels());
-
-    QStringList cols = dc->table()->columnsList();
-    boxLabelsColumn->blockSignals(true);
-    boxLabelsColumn->clear();
-    boxLabelsColumn->addItems(cols);
-    int labelsColIndex = cols.indexOf(dc->labelsColumnName());
-    if (labelsColIndex >= 0)
-        boxLabelsColumn->setCurrentIndex(labelsColIndex);
-    boxLabelsColumn->blockSignals(false);
-
-    boxLabelsAngle->setValue(dc->labelsRotation());
-    boxLabelsColor->setColor(dc->labelsColor());
-    boxLabelsXOffset->setValue(dc->labelsXOffset());
-    boxLabelsYOffset->setValue(dc->labelsYOffset());
-    boxLabelsWhiteOut->setChecked(dc->labelsWhiteOut());
-    switch(dc->labelsAlignment()){
-		case Qt::AlignHCenter:
-			boxLabelsAlign->setCurrentIndex(0);
-			break;
-		case Qt::AlignLeft:
-			boxLabelsAlign->setCurrentIndex(1);
-			break;
-		case Qt::AlignRight:
-			boxLabelsAlign->setCurrentIndex(2);
-			break;
-	}
+	}
+    labelsGroupBox->blockSignals(true);
+    labelsGroupBox->setChecked(dc->hasLabels());
+
+    QStringList cols = dc->table()->columnsList();
+    boxLabelsColumn->blockSignals(true);
+    boxLabelsColumn->clear();
+    boxLabelsColumn->addItems(cols);
+    int labelsColIndex = cols.indexOf(dc->labelsColumnName());
+    if (labelsColIndex >= 0)
+        boxLabelsColumn->setCurrentIndex(labelsColIndex);
+    boxLabelsColumn->blockSignals(false);
+
+    boxLabelsAngle->setValue(dc->labelsRotation());
+    boxLabelsColor->setColor(dc->labelsColor());
+    boxLabelsXOffset->setValue(dc->labelsXOffset());
+    boxLabelsYOffset->setValue(dc->labelsYOffset());
+    boxLabelsWhiteOut->setChecked(dc->labelsWhiteOut());
+    switch(dc->labelsAlignment()){
+		case Qt::AlignHCenter:
+			boxLabelsAlign->setCurrentIndex(0);
+			break;
+		case Qt::AlignLeft:
+			boxLabelsAlign->setCurrentIndex(1);
+			break;
+		case Qt::AlignRight:
+			boxLabelsAlign->setCurrentIndex(2);
+			break;
+	}
 	labelsGroupBox->blockSignals(false);
 }
-void PlotDialog::showAllLabelControls(bool show)
-{
-	if (show){
-		boxLabelsColumn->show();
-		boxLabelsAlign->show();
-		justifyLabelsLbl->show();
-		labelsColumnLbl->show();
-	} else {
-		boxLabelsColumn->hide();
-		boxLabelsAlign->hide();
-		justifyLabelsLbl->hide();
-		labelsColumnLbl->hide();
-	}
+void PlotDialog::showAllLabelControls(bool show)
+{
+	if (show){
+		boxLabelsColumn->show();
+		boxLabelsAlign->show();
+		justifyLabelsLbl->show();
+		labelsColumnLbl->show();
+	} else {
+		boxLabelsColumn->hide();
+		boxLabelsAlign->hide();
+		justifyLabelsLbl->hide();
+		labelsColumnLbl->hide();
+	}
 }
 void PlotDialog::updateEndPointColumns(const QString& text)
 {
@@ -2293,7 +2293,7 @@ bool PlotDialog::acceptParams()
 		if (!boxAll->isChecked())
 			return true;
 
-		QList<Graph *> layers = d_ml->layersList();
+		QList<Graph *> layers = d_ml->layersList();
         foreach(Graph *g, layers){
             g->setFrame(boxBorderWidth->value(), boxBorderColor->color());
             g->setMargin(boxMargin->value());
@@ -2375,28 +2375,28 @@ bool PlotDialog::acceptParams()
   	   //Update axes page
   	   boxXAxis->setCurrentItem(sp->xAxis()-2);
   	   boxYAxis->setCurrentItem(sp->yAxis());
-  	}else if (privateTabWidget->currentPage() == contourLinesPage){
-		
-		Spectrogram *sp = (Spectrogram *)plotItem;
-	  	    if (!sp || sp->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
-		{
-	 	    	return false;
-		}
-		if (defaultContourBox->isChecked()){ 
-			QPen pen = QPen(levelsColorBox->color(), contourWidthBox->value(),Graph::getPenStyle(boxContourStyle->currentIndex()));
-		   	pen.setCosmetic(true);
-  	    	sp->setDefaultContourPen(pen);
-			sp->setColorMapPen(false);
-		} else if (customPenBtn->isChecked())
-				contourLinesEditor->updateContourPens();
-		else
-			sp->setColorMapPen();
-
-		contourLinesEditor->updateContourLevels();
-		sp->setDisplayMode(QwtPlotSpectrogram::ContourMode, levelsGroupBox->isChecked());
-		labelsGroupBox->setChecked(levelsGroupBox->isChecked());
-		labelsGroupBox->setEnabled(levelsGroupBox->isChecked());
-		sp->showContourLineLabels(levelsGroupBox->isChecked());
+  	}else if (privateTabWidget->currentPage() == contourLinesPage){
+		
+		Spectrogram *sp = (Spectrogram *)plotItem;
+	  	    if (!sp || sp->rtti() != QwtPlotItem::Rtti_PlotSpectrogram)
+		{
+	 	    	return false;
+		}
+		if (defaultContourBox->isChecked()){ 
+			QPen pen = QPen(levelsColorBox->color(), contourWidthBox->value(),Graph::getPenStyle(boxContourStyle->currentIndex()));
+		   	pen.setCosmetic(true);
+  	    	sp->setDefaultContourPen(pen);
+			sp->setColorMapPen(false);
+		} else if (customPenBtn->isChecked())
+				contourLinesEditor->updateContourPens();
+		else
+			sp->setColorMapPen();
+
+		contourLinesEditor->updateContourLevels();
+		sp->setDisplayMode(QwtPlotSpectrogram::ContourMode, levelsGroupBox->isChecked());
+		labelsGroupBox->setChecked(levelsGroupBox->isChecked());
+		labelsGroupBox->setEnabled(levelsGroupBox->isChecked());
+		sp->showContourLineLabels(levelsGroupBox->isChecked());
   	} 
 	else if (privateTabWidget->currentPage() == linePage){
 		int index = item->plotItemIndex();
@@ -2484,23 +2484,23 @@ bool PlotDialog::acceptParams()
                     Graph::getPenStyle(boxPieLineStyle->currentIndex())));
         pie->setBrushStyle(boxPiePattern->getSelectedPattern());
         pie->setFirstColor(boxFirstColor->currentIndex());
-	} else if (privateTabWidget->currentPage() == pieGeometryPage){
+	} else if (privateTabWidget->currentPage() == pieGeometryPage){
 		QwtPieCurve *pie = (QwtPieCurve*)plotItem;
 		pie->setViewAngle(boxPieViewAngle->value());
-		pie->setThickness(boxPieThickness->value());
-		pie->setRadius(boxRadius->value());
-        pie->setHorizontalOffset(boxPieOffset->value());
-        pie->setStartAzimuth(boxPieStartAzimuth->value());
-		pie->setCounterClockwise(boxPieConterClockwise->isChecked());
-	} else if (privateTabWidget->currentPage() == pieLabelsPage){
-		QwtPieCurve *pie = (QwtPieCurve*)plotItem;
-		pie->setLabelsAutoFormat(pieAutoLabelsBox->isChecked());
-        pie->setLabelValuesFormat(boxPieValues->isChecked());
+		pie->setThickness(boxPieThickness->value());
+		pie->setRadius(boxRadius->value());
+        pie->setHorizontalOffset(boxPieOffset->value());
+        pie->setStartAzimuth(boxPieStartAzimuth->value());
+		pie->setCounterClockwise(boxPieConterClockwise->isChecked());
+	} else if (privateTabWidget->currentPage() == pieLabelsPage){
+		QwtPieCurve *pie = (QwtPieCurve*)plotItem;
+		pie->setLabelsAutoFormat(pieAutoLabelsBox->isChecked());
+        pie->setLabelValuesFormat(boxPieValues->isChecked());
         pie->setLabelPercentagesFormat(boxPiePercentages->isChecked());
-		pie->setLabelCategories(boxPieCategories->isChecked());
-        pie->setFixedLabelsPosition(boxPieWedge->isChecked());
-        pie->setLabelsEdgeDistance(boxPieEdgeDist->value());
-        graph->replot();
+		pie->setLabelCategories(boxPieCategories->isChecked());
+        pie->setFixedLabelsPosition(boxPieWedge->isChecked());
+        pie->setLabelsEdgeDistance(boxPieEdgeDist->value());
+        graph->replot();
 	} else if (privateTabWidget->currentPage() == percentilePage){
 		BoxCurve *b = (BoxCurve*)plotItem;
 		if (b){
@@ -2533,47 +2533,47 @@ bool PlotDialog::acceptParams()
 			else
 				b->setWhiskersRange(boxWhiskersRange->currentIndex(), (double)boxWhiskersCoef->value());
 		}
-	} else if (privateTabWidget->currentPage() == labelsPage){
-	
-		Spectrogram *sp = (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());
-			
-		} else {
-			DataCurve *c = dynamic_cast<DataCurve *>(plotItem);
-      if (!c) return false;
-		
-			QString text = item->text(0);
-			QStringList t = text.split(": ", QString::SkipEmptyParts);
-			QString table = t[0];
-			QStringList cols = t[1].split(",", QString::SkipEmptyParts);
-
-			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
-					cols[4] = boxLabelsColumn->currentText().remove(table + "_") + "(L)";
-				else
-					cols << boxLabelsColumn->currentText().remove(table + "_") + "(L)";
-				item->setText(0, table + ": " + cols.join(","));
-			} else {
-				c->setLabelsColumnName(QString());
-				cols.pop_back();
-				item->setText(0, table + ": " + cols.join(","));
-			}
-
-			c->setLabelsRotation(boxLabelsAngle->value());
-			c->setLabelsWhiteOut(boxLabelsWhiteOut->isChecked());
-			c->setLabelsOffset(boxLabelsXOffset->value(), boxLabelsYOffset->value());
-			c->setLabelsColor(boxLabelsColor->color());
-			c->setLabelsAlignment(labelsAlignment());
-		}
+	} else if (privateTabWidget->currentPage() == labelsPage){
+	
+		Spectrogram *sp = (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());
+			
+		} else {
+			DataCurve *c = dynamic_cast<DataCurve *>(plotItem);
+      if (!c) return false;
+		
+			QString text = item->text(0);
+			QStringList t = text.split(": ", QString::SkipEmptyParts);
+			QString table = t[0];
+			QStringList cols = t[1].split(",", QString::SkipEmptyParts);
+
+			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
+					cols[4] = boxLabelsColumn->currentText().remove(table + "_") + "(L)";
+				else
+					cols << boxLabelsColumn->currentText().remove(table + "_") + "(L)";
+				item->setText(0, table + ": " + cols.join(","));
+			} else {
+				c->setLabelsColumnName(QString());
+				cols.pop_back();
+				item->setText(0, table + ": " + cols.join(","));
+			}
+
+			c->setLabelsRotation(boxLabelsAngle->value());
+			c->setLabelsWhiteOut(boxLabelsWhiteOut->isChecked());
+			c->setLabelsOffset(boxLabelsXOffset->value(), boxLabelsYOffset->value());
+			c->setLabelsColor(boxLabelsColor->color());
+			c->setLabelsAlignment(labelsAlignment());
+		}
 	}
     
 	graph->replot();
@@ -2848,37 +2848,37 @@ void PlotDialog::showSelectColorMapButton(bool )
 /**
      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
-	// instead of Spectrogram::loadSettings()
-	//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
-	mCurrentColorMap = settings.value("ColormapFile", "").toString();
-	settings.endGroup();
-
-  QString fileselection;
-  //Use a file dialog if no parameter is passed
-  if( filename.isEmpty() )
-  {
-    fileselection = QFileDialog::getOpenFileName(this, tr("Pick a Colormap"), 
-						 QFileInfo(mCurrentColorMap).absoluteFilePath(),
-						 tr("Colormaps (*.map *.MAP)"));
-    // User cancelled if filename is still empty
-    if( fileselection.isEmpty() ) return;
-  }
-  else
-  {
-    fileselection = QFileInfo(filename).absoluteFilePath();
-    if( !QFileInfo(fileselection).exists() ) return;
-  }
-  
-  if( fileselection == mCurrentColorMap ) return;
-
-  mCurrentColorMap = fileselection;
+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
+	QSettings settings;
+	settings.beginGroup("Mantid/2DPlotSpectrogram");
+	//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() )
+  {
+    fileselection = QFileDialog::getOpenFileName(this, tr("Pick a Colormap"), 
+						 QFileInfo(mCurrentColorMap).absoluteFilePath(),
+						 tr("Colormaps (*.map *.MAP)"));
+    // User cancelled if filename is still empty
+    if( fileselection.isEmpty() ) return;
+  }
+  else
+  {
+    fileselection = QFileInfo(filename).absoluteFilePath();
+    if( !QFileInfo(fileselection).exists() ) return;
+  }
+  
+  if( fileselection == mCurrentColorMap ) return;
+
+  mCurrentColorMap = fileselection;
 }
 
 void PlotDialog::showDefaultContourLinesBox(bool)
@@ -2903,11 +2903,11 @@ void PlotDialog::updateTreeWidgetItem(QTreeWidgetItem *item)
 void PlotDialog::updateBackgroundTransparency(int alpha)
 {
 	boxBackgroundColor->setEnabled(alpha);
-    QColor c = boxBackgroundColor->color();
-    c.setAlpha(boxBackgroundTransparency->value());
+    QColor c = boxBackgroundColor->color();
+    c.setAlpha(boxBackgroundTransparency->value());
 
 	if (boxAll->isChecked()){
-		QList<Graph *> layers = d_ml->layersList();
+		QList<Graph *> layers = d_ml->layersList();
         foreach(Graph *g, layers)
             g->setBackgroundColor(c);
 	} else {
@@ -2923,12 +2923,12 @@ void PlotDialog::updateBackgroundTransparency(int alpha)
 void PlotDialog::updateCanvasTransparency(int alpha)
 {
     boxCanvasColor->setEnabled(alpha);
-    QColor c = boxCanvasColor->color();
-    c.setAlpha(boxCanvasTransparency->value());
+    QColor c = boxCanvasColor->color();
+    c.setAlpha(boxCanvasTransparency->value());
 
 	if (boxAll->isChecked()){
-		QList<Graph *> layers = d_ml->layersList();
-        foreach(Graph *g, layers)
+		QList<Graph *> layers = d_ml->layersList();
+        foreach(Graph *g, layers)
             g->setCanvasBackground(c);
 	} else {
 		LayerItem *item = (LayerItem *)listBox->currentItem();
@@ -2942,11 +2942,11 @@ void PlotDialog::updateCanvasTransparency(int alpha)
 
 void PlotDialog::pickCanvasColor()
 {
-	QColor c = boxCanvasColor->color();
-    c.setAlpha(boxCanvasTransparency->value());
+	QColor c = boxCanvasColor->color();
+    c.setAlpha(boxCanvasTransparency->value());
 
 	if (boxAll->isChecked()){
-		QList<Graph *> layers = d_ml->layersList();
+		QList<Graph *> layers = d_ml->layersList();
         foreach(Graph *g, layers){
             g->setCanvasBackground(c);
             g->replot();
@@ -2965,12 +2965,12 @@ void PlotDialog::pickCanvasColor()
 
 void PlotDialog::pickBackgroundColor()
 {
-	QColor c = boxBackgroundColor->color();
-    c.setAlpha(boxBackgroundTransparency->value());
+	QColor c = boxBackgroundColor->color();
+    c.setAlpha(boxBackgroundTransparency->value());
 
 	if (boxAll->isChecked()){
-		QList<Graph *> layers = d_ml->layersList();
-        foreach(Graph *g, layers){
+		QList<Graph *> layers = d_ml->layersList();
+        foreach(Graph *g, layers){
             g->setBackgroundColor(c);
             g->replot();
 		}
@@ -2989,8 +2989,8 @@ void PlotDialog::pickBackgroundColor()
 void PlotDialog::pickBorderColor()
 {
 	if (boxAll->isChecked()){
-		QList<Graph *> layers = d_ml->layersList();
-        foreach(Graph *g, layers)
+		QList<Graph *> layers = d_ml->layersList();
+        foreach(Graph *g, layers)
             g->setFrame(boxBorderWidth->value(), boxBorderColor->color());
 	} else {
 		LayerItem *item = (LayerItem *)listBox->currentItem();
@@ -3010,8 +3010,8 @@ void PlotDialog::updateAntialiasing(bool on)
 
 	if (boxAll->isChecked())
 	{
-		QList<Graph *> layers = d_ml->layersList();
-        foreach(Graph *g, layers)
+		QList<Graph *> layers = d_ml->layersList();
+        foreach(Graph *g, layers)
             g->setAntialiasing(on);
 	}
 	else
@@ -3032,7 +3032,7 @@ void PlotDialog::updateBorder(int width)
 
 	if (boxAll->isChecked())
 	{
-		QList<Graph *> layers = d_ml->layersList();
+		QList<Graph *> layers = d_ml->layersList();
         foreach(Graph *g, layers)
             g->setFrame(width, boxBorderColor->color());
 	}
@@ -3055,7 +3055,7 @@ void PlotDialog::changeMargin(int width)
 
     if (boxAll->isChecked())
     {
-        QList<Graph *> layers = d_ml->layersList();
+        QList<Graph *> layers = d_ml->layersList();
         foreach(Graph *g, layers)
             g->setMargin(width);
     }
@@ -3150,48 +3150,48 @@ void PlotDialog::closeEvent(QCloseEvent* e)
 
 	e->accept();
 }
-
-void PlotDialog::chooseLabelsFont()
-{
-  QTreeWidgetItem *item = listBox->currentItem();
-  if (!item || item->type() != CurveTreeItem::PlotCurveTreeItem)
-    return;
-
-  QwtPlotItem *i = ((CurveTreeItem *)item)->plotItem();
-  Graph *graph = ((CurveTreeItem *)item)->graph();
-  if (!i || !graph)
-    return;
-
-  DataCurve *c = dynamic_cast<DataCurve *>(i);
-  if (!c) return;
-  bool okF;
-  QFont fnt = QFontDialog::getFont(&okF, c->labelsFont(), this);
-  if (okF && fnt != c->labelsFont()){
-    c->setLabelsFont(fnt);
-    graph->replot();
-    graph->notifyChanges();
-  }
-}
-
-int PlotDialog::labelsAlignment()
-{
-	int align = -1;
-	switch (boxLabelsAlign->currentIndex())
-	{
-		case 0:
-			align = Qt::AlignHCenter;
-			break;
-
-		case 1:
-			align = Qt::AlignLeft;
-			break;
-
-		case 2:
-			align = Qt::AlignRight;
-			break;
-	}
-	return align;
-}
+
+void PlotDialog::chooseLabelsFont()
+{
+  QTreeWidgetItem *item = listBox->currentItem();
+  if (!item || item->type() != CurveTreeItem::PlotCurveTreeItem)
+    return;
+
+  QwtPlotItem *i = ((CurveTreeItem *)item)->plotItem();
+  Graph *graph = ((CurveTreeItem *)item)->graph();
+  if (!i || !graph)
+    return;
+
+  DataCurve *c = dynamic_cast<DataCurve *>(i);
+  if (!c) return;
+  bool okF;
+  QFont fnt = QFontDialog::getFont(&okF, c->labelsFont(), this);
+  if (okF && fnt != c->labelsFont()){
+    c->setLabelsFont(fnt);
+    graph->replot();
+    graph->notifyChanges();
+  }
+}
+
+int PlotDialog::labelsAlignment()
+{
+	int align = -1;
+	switch (boxLabelsAlign->currentIndex())
+	{
+		case 0:
+			align = Qt::AlignHCenter;
+			break;
+
+		case 1:
+			align = Qt::AlignLeft;
+			break;
+
+		case 2:
+			align = Qt::AlignRight;
+			break;
+	}
+	return align;
+}
 
 /*****************************************************************************
  *
diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.h b/Code/Mantid/MantidPlot/src/PlotDialog.h
index e25ffe30899b2c30737e2332679b5fec39d14454..5a8c709d40ff18304600a37973c6bcba7406d4e8 100644
--- a/Code/Mantid/MantidPlot/src/PlotDialog.h
+++ b/Code/Mantid/MantidPlot/src/PlotDialog.h
@@ -59,7 +59,7 @@ class ColorButton;
 class MultiLayer;
 class SymbolBox;
 class ColorMapEditor;
-class QwtPlotItem;
+class QwtPlotItem;
 class DoubleSpinBox;
 class PenStyleBox;
 class ContourLinesEditor;
@@ -145,11 +145,11 @@ protected slots:
   void setAxesLabelsFont();
   void setAxesNumbersFont();
   void setLegendsFont();
-  void editCurve();
-  void chooseLabelsFont();
-  void showCustomPenColumn(bool on);
+  void editCurve();
+  void chooseLabelsFont();
+  void showCustomPenColumn(bool on);
 
-private:
+private:
   int labelsAlignment();
   void closeEvent(QCloseEvent* e);
 
@@ -167,10 +167,10 @@ private:
   void initLayerPage();
   void initLayerGeometryPage();
   void initFontsPage();
-  void initPiePage();
-  void initPieGeometryPage();
+  void initPiePage();
+  void initPieGeometryPage();
   void initPieLabelsPage();
-  void initPrintPage();
+  void initPrintPage();
   void initLabelsPage();
   void initContourLinesPage();
   void contextMenuEvent(QContextMenuEvent *e);
@@ -255,22 +255,22 @@ private:
   QRadioButton *defaultScaleBox, *grayScaleBox, *customScaleBox, *defaultContourBox, *autoContourBox;
 
   SymbolBox *boxMaxStyle, *boxMinStyle, *boxMeanStyle, *box99Style, *box1Style;
-  QDoubleSpinBox *whiskerCnt, *boxCnt;
-  //!Labels page
-  QGroupBox *labelsGroupBox;
-  DoubleSpinBox *boxLabelsAngle;
-  QSpinBox *boxLabelsXOffset, *boxLabelsYOffset;
-  QCheckBox *boxLabelsWhiteOut;
-  QPushButton *btnLabelsFont,*btnSetEquidistantLevels;
-  QComboBox *boxLabelsAlign, *boxLabelsColumn;
-  ColorBox* boxLabelsColor;
+  QDoubleSpinBox *whiskerCnt, *boxCnt;
+  //!Labels page
+  QGroupBox *labelsGroupBox;
+  DoubleSpinBox *boxLabelsAngle;
+  QSpinBox *boxLabelsXOffset, *boxLabelsYOffset;
+  QCheckBox *boxLabelsWhiteOut;
+  QPushButton *btnLabelsFont,*btnSetEquidistantLevels;
+  QComboBox *boxLabelsAlign, *boxLabelsColumn;
+  ColorBox* boxLabelsColor;
   QWidget *labelsPage;
-
+
   QGroupBox *pieAutoLabelsBox, *boxPieWedge;
   DoubleSpinBox *boxPieStartAzimuth, *boxPieEdgeDist, *boxPieViewAngle, *boxPieThickness,*firstContourLineBox,*contourLinesDistanceBox;
-  QCheckBox *boxPieConterClockwise, *boxPieValues, *boxPiePercentages, *boxPieCategories;
-  QWidget *pieLabelsPage;
-  QSpinBox *boxPieOffset;
+  QCheckBox *boxPieConterClockwise, *boxPieValues, *boxPiePercentages, *boxPieCategories;
+  QWidget *pieLabelsPage;
+  QSpinBox *boxPieOffset;
   QWidget *pieGeometryPage;
   ContourLinesEditor *contourLinesEditor;
   QRadioButton *customPenBtn;
diff --git a/Code/Mantid/MantidPlot/src/PluginFit.cpp b/Code/Mantid/MantidPlot/src/PluginFit.cpp
index 14fa8dad119219bb51fc457ca1b19c47f143e2d9..988b6760191ac7b554a87b8ed861a806c960746c 100644
--- a/Code/Mantid/MantidPlot/src/PluginFit.cpp
+++ b/Code/Mantid/MantidPlot/src/PluginFit.cpp
@@ -60,7 +60,7 @@ PluginFit::PluginFit(ApplicationWindow *parent, Table *t, const QString& xCol, c
 
 void PluginFit::init()
 {
-	d_explanation = tr("Plugin Fit");
+	d_explanation = tr("Plugin Fit");
     d_fit_type = Plugin;
 }
 
@@ -140,13 +140,13 @@ void PluginFit::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++){
+		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++) {
+		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/Code/Mantid/MantidPlot/src/PluginFit.h b/Code/Mantid/MantidPlot/src/PluginFit.h
index 4900388411fda147a6400aab1c7915fff593d841..8212e4abda137d5d75fd94c586abff7ed48f6468 100644
--- a/Code/Mantid/MantidPlot/src/PluginFit.h
+++ b/Code/Mantid/MantidPlot/src/PluginFit.h
@@ -42,7 +42,7 @@ class PluginFit : public Fit
 		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){return f_eval(x, par);};
+        double eval(double *par, double x){return f_eval(x, par);};
 
 	private:
 		void init();
diff --git a/Code/Mantid/MantidPlot/src/PolynomialFit.cpp b/Code/Mantid/MantidPlot/src/PolynomialFit.cpp
index de57301bb6a0e5fb83c5f036c070adf8542de14c..222b000d7ab11ea11ce86d01d90797c8041534de 100644
--- a/Code/Mantid/MantidPlot/src/PolynomialFit.cpp
+++ b/Code/Mantid/MantidPlot/src/PolynomialFit.cpp
@@ -115,7 +115,7 @@ 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++){
+		for (int i=0; i<d_points; i++){
 		    double x = X0+i*step;
 			X[i] = x;
 			double 	yi = 0.0;
@@ -124,7 +124,7 @@ void PolynomialFit::calculateFitCurveData(double *X, double *Y)
 			Y[i] = yi;
 		}
 	} else {
-		for (int i=0; i<d_points; i++) {
+		for (int i=0; i<d_points; i++) {
 		    double x = d_x[i];
 			X[i] = x;
 			double 	yi = 0.0;
@@ -250,9 +250,9 @@ void LinearFit::init()
 
 	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);
+
+    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";
@@ -299,13 +299,13 @@ 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++){
+		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++) {
+		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;
diff --git a/Code/Mantid/MantidPlot/src/PythonScript.cpp b/Code/Mantid/MantidPlot/src/PythonScript.cpp
index 4143302ebe92094a76726ec880af8624bc7c3491..7fcf059a54d1b2dc9b9933d0d48a770a1e6b5834 100644
--- a/Code/Mantid/MantidPlot/src/PythonScript.cpp
+++ b/Code/Mantid/MantidPlot/src/PythonScript.cpp
@@ -262,13 +262,13 @@ QVariant PythonScript::eval()
   
   Py_DECREF(pyret);
   if (PyErr_Occurred()){
-    if (PyErr_ExceptionMatches(PyExc_ValueError) ||
-	PyErr_ExceptionMatches(PyExc_ZeroDivisionError)){
-      PyErr_Clear(); // silently ignore errors
-      return  QVariant("");
-	} else {
-      emit_error(constructErrorMsg(), 0);
-	return QVariant();
+    if (PyErr_ExceptionMatches(PyExc_ValueError) ||
+	PyErr_ExceptionMatches(PyExc_ZeroDivisionError)){
+      PyErr_Clear(); // silently ignore errors
+      return  QVariant("");
+	} else {
+      emit_error(constructErrorMsg(), 0);
+	return QVariant();
 	  }
   } else
     return qret;
diff --git a/Code/Mantid/MantidPlot/src/QwtBarCurve.cpp b/Code/Mantid/MantidPlot/src/QwtBarCurve.cpp
index ed8673c7b62d2d3e235cbdc8ac5bed1185a28b3b..0d6f4031870e6635eff729610529e1433cc49a32 100644
--- a/Code/Mantid/MantidPlot/src/QwtBarCurve.cpp
+++ b/Code/Mantid/MantidPlot/src/QwtBarCurve.cpp
@@ -37,8 +37,8 @@ bar_gap=0;
 bar_style=style;
 
 setPen(QPen(Qt::black, 1, Qt::SolidLine));
-setBrush(QBrush(Qt::red));
-setStyle(QwtPlotCurve::UserCurve);
+setBrush(QBrush(Qt::red));
+setStyle(QwtPlotCurve::UserCurve);
 
 if (bar_style == Vertical)
 	setType(Graph::VerticalBars);
diff --git a/Code/Mantid/MantidPlot/src/QwtErrorPlotCurve.cpp b/Code/Mantid/MantidPlot/src/QwtErrorPlotCurve.cpp
index 2aad070f5fcdf62bf9fc45c26f9064a7a5ed0b95..dc8179f6d3d70947742f2f8cb60eda8100fb4337 100644
--- a/Code/Mantid/MantidPlot/src/QwtErrorPlotCurve.cpp
+++ b/Code/Mantid/MantidPlot/src/QwtErrorPlotCurve.cpp
@@ -43,7 +43,7 @@ QwtErrorPlotCurve::QwtErrorPlotCurve(int orientation, Table *t, const QString& n
 	plus = true;
 	minus = true;
 	through = false;
-	setType(Graph::ErrorBars);
+	setType(Graph::ErrorBars);
     setStyle(QwtPlotCurve::UserCurve);
 }
 
@@ -56,7 +56,7 @@ QwtErrorPlotCurve::QwtErrorPlotCurve(Table *t, const QString& name):
 	plus = true;
 	minus = true;
 	through = false;
-	setType(Graph::ErrorBars);
+	setType(Graph::ErrorBars);
     setStyle(QwtPlotCurve::UserCurve);
 }
 
diff --git a/Code/Mantid/MantidPlot/src/QwtHistogram.cpp b/Code/Mantid/MantidPlot/src/QwtHistogram.cpp
index f65e696ed76d852c6d875d20334cd0c8a9e35af7..165beb32aafd78d3d9ee0e0635a0f1c6ea749930 100644
--- a/Code/Mantid/MantidPlot/src/QwtHistogram.cpp
+++ b/Code/Mantid/MantidPlot/src/QwtHistogram.cpp
@@ -26,40 +26,40 @@
  *   Boston, MA  02110-1301  USA                                           *
  *                                                                         *
  ***************************************************************************/
-#include "QwtHistogram.h"
-#include "Matrix.h"
+#include "QwtHistogram.h"
+#include "Matrix.h"
 #include "MatrixModel.h"
-#include <QPainter>
+#include <QPainter>
 #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_matrix = 0;
-    setType(Graph::Histogram);
-    setStyle(QwtPlotCurve::UserCurve);
+{
+    d_matrix = 0;
+    setType(Graph::Histogram);
+    setStyle(QwtPlotCurve::UserCurve);
+}
+
+QwtHistogram::QwtHistogram(Matrix *m):
+    QwtBarCurve(QwtBarCurve::Vertical, NULL, "matrix", m->objectName(), 0, 0)
+{
+    if (m){
+        d_autoBin = true;
+        d_matrix = m;
+        setType(Graph::Histogram);
+        setStyle(QwtPlotCurve::UserCurve);
+    }
 }
-
-QwtHistogram::QwtHistogram(Matrix *m):
-    QwtBarCurve(QwtBarCurve::Vertical, NULL, "matrix", m->objectName(), 0, 0)
-{
-    if (m){
-        d_autoBin = true;
-        d_matrix = m;
-        setType(Graph::Histogram);
-        setStyle(QwtPlotCurve::UserCurve);
-    }
-}
 
 void QwtHistogram::copy(QwtHistogram *h)
 {
 	QwtBarCurve::copy((const QwtBarCurve *)h);
-
+
 	d_autoBin = h->d_autoBin;
 	d_bin_size = h->d_bin_size;
 	d_begin = h->d_begin;
-	d_end = h->d_end;
+	d_end = h->d_end;
 }
 
 void QwtHistogram::draw(QPainter *painter,
@@ -97,7 +97,7 @@ QwtDoubleRect QwtHistogram::boundingRect() const
 	rect.setRight(rect.right()+x(dataSize()-1));
 	rect.setTop(0);
 	rect.setBottom(1.2*rect.bottom());
-	return rect;
+	return rect;
 }
 
 void QwtHistogram::setBinning(bool autoBin, double size, double begin, double end)
@@ -109,11 +109,11 @@ void QwtHistogram::setBinning(bool autoBin, double size, double begin, double en
 }
 
 void QwtHistogram::loadData()
-{
-    if (d_matrix){
-        loadDataFromMatrix();
-        return;
-    }
+{
+    if (d_matrix){
+        loadDataFromMatrix();
+        return;
+    }
 
     int r = abs(d_end_row - d_start_row) + 1;
 	QVarLengthArray<double> Y(r);
@@ -195,68 +195,68 @@ void QwtHistogram::loadData()
 
 	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 = (int)(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 = 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 = (int)(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 = 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)
 {
diff --git a/Code/Mantid/MantidPlot/src/QwtHistogram.h b/Code/Mantid/MantidPlot/src/QwtHistogram.h
index 3a08ae7708c9c46b00b61b4109d04a20cebfab0c..4bb88b7d0f4a2b8b119302ee9278e36559bb5f8d 100644
--- a/Code/Mantid/MantidPlot/src/QwtHistogram.h
+++ b/Code/Mantid/MantidPlot/src/QwtHistogram.h
@@ -27,15 +27,15 @@
  *                                                                         *
  ***************************************************************************/
 #include "QwtBarCurve.h"
-
-class Matrix;
+
+class Matrix;
 
 //! Histogram class
 class QwtHistogram: public QwtBarCurve
 {
 public:
 	QwtHistogram(Table *t, const QString& xColName, const QString& name, int startRow, int endRow);
-    QwtHistogram(Matrix *m);
+    QwtHistogram(Matrix *m);
 
 	void copy(QwtHistogram *h);
 
@@ -47,7 +47,7 @@ public:
 	double end(){return d_end;};
 	double binSize(){return d_bin_size;};
 
-    void loadData();
+    void loadData();
     void initData(double* Y, int size);
 
     double mean(){return d_mean;};
@@ -60,9 +60,9 @@ public:
 private:
 	void draw(QPainter *painter,const QwtScaleMap &xMap,
 		const QwtScaleMap &yMap, int from, int to) const;
-
-    void loadDataFromMatrix();
-    Matrix *d_matrix;
+
+    void loadDataFromMatrix();
+    Matrix *d_matrix;
 
 	bool d_autoBin;
 	double d_bin_size, d_begin, d_end;
diff --git a/Code/Mantid/MantidPlot/src/QwtPieCurve.cpp b/Code/Mantid/MantidPlot/src/QwtPieCurve.cpp
index 7592446e0463ff2d23f8b21b1a864018e63a6012..cbf713aaf030601301199077a0d2ab68d6fd7820 100644
--- a/Code/Mantid/MantidPlot/src/QwtPieCurve.cpp
+++ b/Code/Mantid/MantidPlot/src/QwtPieCurve.cpp
@@ -47,135 +47,135 @@ QwtPieCurve::QwtPieCurve(Table *t, const QString& name, int startRow, int endRow
 	d_counter_clockwise(false),
 	d_auto_labeling(true),
 	d_values(false),
-	d_percentages(true),
+	d_percentages(true),
 	d_categories(false),
 	d_fixed_labels_pos(true)
 {
-	setPen(QPen(QColor(Qt::black), 1, Qt::SolidLine));
+	setPen(QPen(QColor(Qt::black), 1, Qt::SolidLine));
 	setBrush(QBrush(Qt::SolidPattern));
     setStyle(QwtPlotCurve::UserCurve);
-	setType(Graph::Pie);
+	setType(Graph::Pie);
 	d_table_rows = QVarLengthArray<int>(0);
 }
-
-void QwtPieCurve::clone(QwtPieCurve* c)
-{
-    if (!c)
-        return;
-
-    d_pie_ray = c->radius();
-	d_first_color = c->firstColor();
-	d_start_azimuth = c->startAzimuth();
-	d_view_angle = c->viewAngle();
-	d_thickness = c->thickness();
-	d_horizontal_offset = c->horizontalOffset();
-	d_edge_dist = c->labelsEdgeDistance();
-	d_counter_clockwise = c->counterClockwise();
-	d_auto_labeling = c->labelsAutoFormat();
-	d_values = c->labelsValuesFormat();
-	d_percentages = c->labelsPercentagesFormat();
-	d_categories = c->labelCategories();
-	d_fixed_labels_pos = c->fixedLabelsPosition();
-
-	d_table_rows = c->d_table_rows;
-}
+
+void QwtPieCurve::clone(QwtPieCurve* c)
+{
+    if (!c)
+        return;
+
+    d_pie_ray = c->radius();
+	d_first_color = c->firstColor();
+	d_start_azimuth = c->startAzimuth();
+	d_view_angle = c->viewAngle();
+	d_thickness = c->thickness();
+	d_horizontal_offset = c->horizontalOffset();
+	d_edge_dist = c->labelsEdgeDistance();
+	d_counter_clockwise = c->counterClockwise();
+	d_auto_labeling = c->labelsAutoFormat();
+	d_values = c->labelsValuesFormat();
+	d_percentages = c->labelsPercentagesFormat();
+	d_categories = c->labelCategories();
+	d_fixed_labels_pos = c->fixedLabelsPosition();
+
+	d_table_rows = c->d_table_rows;
+}
 
 void QwtPieCurve::draw(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const
-{
+{
     int size = dataSize();
 	if ( !painter ||  size <= 0 )
 		return;
 
 	if (to < 0)
 		to = size - 1;
-
+
     if (size > 1)
-        drawSlices(painter, xMap, yMap, from, to);
-    else
+        drawSlices(painter, xMap, yMap, from, to);
+    else
         drawDisk(painter, xMap, yMap);
 }
-
-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);
-
-	QRectF pieRect;
-	pieRect.setX(x_center - ray_x);
-	pieRect.setY(y_center - ray_y);
-	pieRect.setWidth(2*ray_x);
-	pieRect.setHeight(2*ray_y);
-
-	QRectF pieRect2 = pieRect;
-    pieRect2.translate(0, thick);
-
-    painter->save();
-
-    painter->setPen(QwtPlotCurve::pen());
-    painter->setBrush(QBrush(color(0), QwtPlotCurve::brush().style()));
-
-    QPointF start(x_center + ray_x, y_center);
-    QPainterPath path(start);
-    path.lineTo(start.x(), start.y() + thick);
-    path.arcTo(pieRect2, 0, -180.0);
-    QPointF aux = path.currentPosition();
-    path.lineTo(aux.x(), aux.y() - thick);
-    path.arcTo(pieRect, -180.0, 180.0);
-    painter->drawPath(path);
-
-    painter->drawEllipse(pieRect);
-
-    if (d_texts_list.size() > 0){
-        PieLabel* l = d_texts_list[0];
-        if (l){
-            QString s;
-            if (d_auto_labeling){
-				if (d_categories)
-					s += QString::number(d_table_rows[0]) + "\n";
-
-                if (d_values && d_percentages)
-                    s += ((Plot *)plot())->locale().toString(y(0), 'g', 4) + " (100%)";
-                else if (d_values)
-                    s += ((Plot *)plot())->locale().toString(y(0), 'g', 4);
-                else if (d_percentages)
-                    s += "100%";
-                l->setText(s);
-				if (l->isHidden())
-					l->show();
-            } else
-				l->setText(l->customText());
-
-            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);
-                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);
-                l->setOriginCoord(dx, dy);
-            }
-        }
-    }
-    painter->restore();
-}
+
+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);
+
+	QRectF pieRect;
+	pieRect.setX(x_center - ray_x);
+	pieRect.setY(y_center - ray_y);
+	pieRect.setWidth(2*ray_x);
+	pieRect.setHeight(2*ray_y);
+
+	QRectF pieRect2 = pieRect;
+    pieRect2.translate(0, thick);
+
+    painter->save();
+
+    painter->setPen(QwtPlotCurve::pen());
+    painter->setBrush(QBrush(color(0), QwtPlotCurve::brush().style()));
+
+    QPointF start(x_center + ray_x, y_center);
+    QPainterPath path(start);
+    path.lineTo(start.x(), start.y() + thick);
+    path.arcTo(pieRect2, 0, -180.0);
+    QPointF aux = path.currentPosition();
+    path.lineTo(aux.x(), aux.y() - thick);
+    path.arcTo(pieRect, -180.0, 180.0);
+    painter->drawPath(path);
+
+    painter->drawEllipse(pieRect);
+
+    if (d_texts_list.size() > 0){
+        PieLabel* l = d_texts_list[0];
+        if (l){
+            QString s;
+            if (d_auto_labeling){
+				if (d_categories)
+					s += QString::number(d_table_rows[0]) + "\n";
+
+                if (d_values && d_percentages)
+                    s += ((Plot *)plot())->locale().toString(y(0), 'g', 4) + " (100%)";
+                else if (d_values)
+                    s += ((Plot *)plot())->locale().toString(y(0), 'g', 4);
+                else if (d_percentages)
+                    s += "100%";
+                l->setText(s);
+				if (l->isHidden())
+					l->show();
+            } else
+				l->setText(l->customText());
+
+            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);
+                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);
+                l->setOriginCoord(dx, dy);
+            }
+        }
+    }
+    painter->restore();
+}
 
 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_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 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);
@@ -190,28 +190,28 @@ void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap, const Q
 	QRectF pieRect2 = pieRect;
     pieRect2.translate(0, thick);
 
-	double sum = 0.0;
-	for (int i = from; i <= to; i++)
-		sum += y(i);
-
-	const int sign = d_counter_clockwise ? 1 : -1;
-
-	const int size = dataSize();
-    double *start_angle = new double[size];
-    double *end_angle = new double[size];
+	double sum = 0.0;
+	for (int i = from; i <= to; i++)
+		sum += y(i);
+
+	const int sign = d_counter_clockwise ? 1 : -1;
+
+	const int size = dataSize();
+    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++){
+	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;
-		if (end >= 360)
-            end -= 360;
-        else if (end < 0)
-            end += 360;
-
-		end_angle[i] = end;
-		aux_angle = end;
+		start_angle[i] = aux_angle;
+
+		double end = aux_angle + a;
+		if (end >= 360)
+            end -= 360;
+        else if (end < 0)
+            end += 360;
+
+		end_angle[i] = end;
+		aux_angle = end;
 	}
 
 	int angle = (int)(5760 * d_start_azimuth/360.0);
@@ -219,8 +219,8 @@ void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap, const Q
 		angle = (int)(5760 * (1 - d_start_azimuth/360.0));
 
 	painter->save();
-
-	QLocale locale = ((Plot *)plot())->locale();
+
+	QLocale locale = ((Plot *)plot())->locale();
 	for (int i = from; i <= to; i++){
 		const double yi = y(i);
 		const double q = yi/sum;
@@ -229,71 +229,71 @@ void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap, const Q
 		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){
-		    start_3D_view_angle = end_angle[i];
-            end_3D_view_angle = start_angle[i];
+		double end_3D_view_angle = end_angle[i];
+		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)){
-                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){
-		    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){
-            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));
-			QPainterPath path(start);
-			path.lineTo(start.x(), start.y() + thick);
-			path.arcTo(pieRect2, -start_3D_view_angle, -deg);
-        	QPointF aux = path.currentPosition();
-        	path.lineTo(aux.x(), aux.y() - thick);
-        	path.arcTo(pieRect, -end_3D_view_angle, deg);
-        	painter->drawPath(path);
-        } else {
-            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));
-                QPainterPath path(start);
-                path.lineTo(start.x(), start.y() + thick);
-
-                deg = 180 - start_3D_view_angle;
-                path.arcTo(pieRect2, -start_3D_view_angle, -deg);
-                QPointF aux = path.currentPosition();
-                path.lineTo(aux.x(), aux.y() - thick);
-                path.arcTo(pieRect, -180, deg);
-                painter->drawPath(path);
-
-                path.moveTo(QPointF(x_center + ray_x, y_center));
-                aux = path.currentPosition();
-                path.lineTo(aux.x(), aux.y() + thick);
-                path.arcTo(pieRect2, 0, -end_3D_view_angle);
-                aux = path.currentPosition();
-                path.lineTo(aux.x(), aux.y() - thick);
-                path.arcTo(pieRect, -end_3D_view_angle, end_3D_view_angle);
-                painter->drawPath(path);
-            }
-        }
+
+        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)){
+                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){
+		    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){
+            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));
+			QPainterPath path(start);
+			path.lineTo(start.x(), start.y() + thick);
+			path.arcTo(pieRect2, -start_3D_view_angle, -deg);
+        	QPointF aux = path.currentPosition();
+        	path.lineTo(aux.x(), aux.y() - thick);
+        	path.arcTo(pieRect, -end_3D_view_angle, deg);
+        	painter->drawPath(path);
+        } else {
+            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));
+                QPainterPath path(start);
+                path.lineTo(start.x(), start.y() + thick);
+
+                deg = 180 - start_3D_view_angle;
+                path.arcTo(pieRect2, -start_3D_view_angle, -deg);
+                QPointF aux = path.currentPosition();
+                path.lineTo(aux.x(), aux.y() - thick);
+                path.arcTo(pieRect, -180, deg);
+                painter->drawPath(path);
+
+                path.moveTo(QPointF(x_center + ray_x, y_center));
+                aux = path.currentPosition();
+                path.lineTo(aux.x(), aux.y() + thick);
+                path.arcTo(pieRect2, 0, -end_3D_view_angle);
+                aux = path.currentPosition();
+                path.lineTo(aux.x(), aux.y() - thick);
+                path.arcTo(pieRect, -end_3D_view_angle, end_3D_view_angle);
+                painter->drawPath(path);
+            }
+        }
 
 		painter->drawPie(pieRect, sign*angle, sign*value);
 		angle += value;
@@ -302,45 +302,45 @@ void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap, const Q
 			continue;
 
 		PieLabel* l = d_texts_list[i];
-		if (l){
+		if (l){
 			QString s;
-			if (d_auto_labeling){
-				if (d_categories)
+			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) + "%)";
 				else if (d_values)
 					s += locale.toString(yi, 'g', 4);
 				else if (d_percentages)
-					s += locale.toString(q*100, 'g', 4) + "%";
-                l->setText(s);
-				if (l->isHidden())
-					l->show();
+					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 (a_deg > 360)
-                    a_deg -= 360.0;
-                double a_rad = a_deg*M_PI/180.0;
+				l->setText(l->customText());
+
+            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 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)
+                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);
-                l->setOriginCoord(dx, dy);
+                l->setOriginCoord(dx, dy);
             }
 		}
 	}
-	painter->restore();
-	delete [] start_angle;
+	painter->restore();
+	delete [] start_angle;
 	delete [] end_angle;
 }
 
@@ -360,11 +360,11 @@ void QwtPieCurve::setBrushStyle(const Qt::BrushStyle& style)
 }
 
 void QwtPieCurve::loadData()
-{
-	Plot *d_plot = (Plot *)plot();
+{
+	Plot *d_plot = (Plot *)plot();
 	QLocale locale = d_plot->locale();
-	QVarLengthArray<double> X(abs(d_end_row - d_start_row) + 1);
-	d_table_rows.resize(abs(d_end_row - d_start_row) + 1);
+	QVarLengthArray<double> X(abs(d_end_row - d_start_row) + 1);
+	d_table_rows.resize(abs(d_end_row - d_start_row) + 1);
 
 	int size = 0;
 	int ycol = d_table->colIndex(title().text());
@@ -373,102 +373,102 @@ void QwtPieCurve::loadData()
 		bool valid_data = true;
 		if (!xval.isEmpty()){
             X[size] = locale.toDouble(xval, &valid_data);
-            if (valid_data){
+            if (valid_data){
 				d_table_rows[size] = i + 1;
-                size++;
+                size++;
 			}
 		}
 	}
-	X.resize(size);
+	X.resize(size);
 	d_table_rows.resize(size);
-	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)
-		return;
-
-	//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();
+	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)
+		return;
+
+	//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)
+{
+	if (!l)
+		return;
+
+	if (clone){
+		PieLabel *newLabel = new PieLabel((Plot *)plot(), this);
+		newLabel->clone(l);
+		newLabel->setCustomText(l->customText());
+		d_texts_list << newLabel;
+	} else {
+		l->setPieCurve(this);
+		d_texts_list << l;
 	}
 }
-
-void QwtPieCurve::addLabel(PieLabel *l, bool clone)
-{
-	if (!l)
-		return;
-
-	if (clone){
-		PieLabel *newLabel = new PieLabel((Plot *)plot(), this);
-		newLabel->clone(l);
-		newLabel->setCustomText(l->customText());
-		d_texts_list << newLabel;
-	} else {
-		l->setPieCurve(this);
-		d_texts_list << l;
-	}
-}
-
-void QwtPieCurve::removeLabel(PieLabel *l)
-{
-	if (!l)
-		return;
-
-	int index = d_texts_list.indexOf(l);
-	if (index < 0 || index >= d_texts_list.size())
-		return;
-
-	PieLabel *newLabel = new PieLabel((Plot *)plot(), this);
-	newLabel->clone(l);
-	newLabel->setCustomText(l->customText());
-	newLabel->hide();
-
-	d_texts_list.removeAt(index);
-	d_texts_list.insert(index, newLabel);
-}
+
+void QwtPieCurve::removeLabel(PieLabel *l)
+{
+	if (!l)
+		return;
+
+	int index = d_texts_list.indexOf(l);
+	if (index < 0 || index >= d_texts_list.size())
+		return;
+
+	PieLabel *newLabel = new PieLabel((Plot *)plot(), this);
+	newLabel->clone(l);
+	newLabel->setCustomText(l->customText());
+	newLabel->hide();
+
+	d_texts_list.removeAt(index);
+	d_texts_list.insert(index, newLabel);
+}
 
 void QwtPieCurve::initLabels()
 {
-	int size = abs(d_end_row - d_start_row) + 1;
+	int size = abs(d_end_row - d_start_row) + 1;
 	int dataPoints = dataSize();
 	double sum = 0.0;
 	for (int i = 0; i < dataPoints; i++)
 		sum += y(i);
-
+
     Plot *d_plot = (Plot *)plot();
 	QLocale locale = d_plot->locale();
 	for (int i = 0; i <size; i++ ){
 		PieLabel* l = new PieLabel(d_plot, this);
-		d_texts_list << l;
+		d_texts_list << l;
 		if (i < dataPoints)
-            l->setText(locale.toString(y(i)/sum*100, 'g', 4) + "%");
-		else
+            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)
+{
+	setBackgroundColor(QColor(255, 255, 255, 0));
+	setFrameStyle(0);
 }
-
-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()
-{
-	if (d_custom_text.isEmpty())
-		return text();
-
-	return d_custom_text;
+
+QString PieLabel::customText()
+{
+	if (d_custom_text.isEmpty())
+		return text();
+
+	return d_custom_text;
 }
-
-void PieLabel::closeEvent(QCloseEvent* e)
-{
-	if(d_pie_curve)
-		d_pie_curve->removeLabel(this);
-	e->accept();
+
+void PieLabel::closeEvent(QCloseEvent* e)
+{
+	if(d_pie_curve)
+		d_pie_curve->removeLabel(this);
+	e->accept();
 }
diff --git a/Code/Mantid/MantidPlot/src/QwtPieCurve.h b/Code/Mantid/MantidPlot/src/QwtPieCurve.h
index dd31591753cba4bb23c784a153e50aaba0a215cf..6f0a41e7fd72157e48b01c7853976d4bdac8529a 100644
--- a/Code/Mantid/MantidPlot/src/QwtPieCurve.h
+++ b/Code/Mantid/MantidPlot/src/QwtPieCurve.h
@@ -37,40 +37,40 @@ class QwtPieCurve: public DataCurve
 {
 public:
 	QwtPieCurve(Table *t, const QString& name, int startRow, int endRow);
-    void clone(QwtPieCurve* c);
-
-    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 horizontalOffset(){return d_horizontal_offset;};
-    void setHorizontalOffset(double d){d_horizontal_offset = d;};
+    void clone(QwtPieCurve* c);
+
+    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 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;};
 
 	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;};
-
-    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 labelsPercentagesFormat(){return d_percentages;};
-    void setLabelPercentagesFormat(bool on){d_percentages = on;};
+
+    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 labelsValuesFormat(){return d_values;};
+    void setLabelValuesFormat(bool on){d_values = 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 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;
 
@@ -96,9 +96,9 @@ private:
 		const QwtScaleMap &yMap, int from, int to) const;
 	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;
+	void drawDisk(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap) const;
 
-	int d_pie_ray;
+	int d_pie_ray;
 	int d_first_color;
 	double d_start_azimuth;
 	double d_view_angle;
diff --git a/Code/Mantid/MantidPlot/src/RangeSelectorTool.cpp b/Code/Mantid/MantidPlot/src/RangeSelectorTool.cpp
index e55d0bbdb43cd84fbf2b25ed6e1b97f9c9df1eae..4754d797035c8ad5c09d137d59b507a69feb8efa 100644
--- a/Code/Mantid/MantidPlot/src/RangeSelectorTool.cpp
+++ b/Code/Mantid/MantidPlot/src/RangeSelectorTool.cpp
@@ -58,7 +58,7 @@ RangeSelectorTool::RangeSelectorTool(Graph *graph, const QObject *status_target,
 				tr("All the curves on this plot are empty!"));
 		return;
 	}
-
+
     d_enabled = true;
 	d_visible = true;
 	d_active_point = 0;
@@ -398,10 +398,10 @@ void RangeSelectorTool::setCurveRange()
         d_graph->notifyChanges();
     }
 }
-
-void RangeSelectorTool::setEnabled(bool on)
-{
-    d_enabled = on;
-    if (on)
-        d_graph->plotWidget()->canvas()->setCursor(QCursor(getQPixmap("vizor_xpm"), -1, -1));
+
+void RangeSelectorTool::setEnabled(bool on)
+{
+    d_enabled = on;
+    if (on)
+        d_graph->plotWidget()->canvas()->setCursor(QCursor(getQPixmap("vizor_xpm"), -1, -1));
 }
diff --git a/Code/Mantid/MantidPlot/src/RangeSelectorTool.h b/Code/Mantid/MantidPlot/src/RangeSelectorTool.h
index f55c7e7cf05dd03840c68ef171c0a11ec5659c40..e3060d35e81f2006f558b9b3606dfddd696646a9 100644
--- a/Code/Mantid/MantidPlot/src/RangeSelectorTool.h
+++ b/Code/Mantid/MantidPlot/src/RangeSelectorTool.h
@@ -74,7 +74,7 @@ class RangeSelectorTool : public QwtPlotPicker, public PlotToolInterface
 
 	public slots:
 		virtual void pointSelected(const QPoint &point);
-        void setCurveRange();
+        void setCurveRange();
         void setEnabled(bool on = true);
 
 	signals:
@@ -94,7 +94,7 @@ class RangeSelectorTool : public QwtPlotPicker, public PlotToolInterface
 	private:
 		QwtPlotMarker d_active_marker, d_inactive_marker;
 		int d_active_point, d_inactive_point;
-		QwtPlotCurve *d_selected_curve;
+		QwtPlotCurve *d_selected_curve;
 		bool d_enabled;
 		bool d_visible;
 };
diff --git a/Code/Mantid/MantidPlot/src/ScaleDraw.cpp b/Code/Mantid/MantidPlot/src/ScaleDraw.cpp
index 70bedb772d0d63a55376b7e5801e286a411c9e62..9b8b17fd8b18b6ef4408c684c0319f67b2120b5f 100644
--- a/Code/Mantid/MantidPlot/src/ScaleDraw.cpp
+++ b/Code/Mantid/MantidPlot/src/ScaleDraw.cpp
@@ -29,14 +29,14 @@
 #include "ScaleDraw.h"
 #include "MyParser.h"
 #include "plot2D/ScaleEngine.h"
-#include "Graph.h"
+#include "Graph.h"
 
 #include <QDateTime>
-#include <QPainter>
-#include <QMatrix>
+#include <QPainter>
+#include <QMatrix>
 
 #include <qwt_painter.h>
-#include <qwt_text.h>
+#include <qwt_text.h>
 
 /*****************************************************************************
  *
@@ -52,7 +52,7 @@ ScaleDraw::ScaleDraw(Plot *plot, const QString& formula):
     d_prec(4),
 	d_formula(formula),
 	d_majTicks(Out),
-	d_minTicks(Out),
+	d_minTicks(Out),
 	d_selected(false),
 	d_name_format(ShortName),
 	d_date_time_origin(QDateTime::currentDateTime()),
@@ -75,32 +75,32 @@ ScaleDraw::ScaleDraw(Plot *plot, const QStringList& labels, const QString& forma
 	d_format_info(format),
 	d_text_labels(labels)
 {}
-
-ScaleDraw::ScaleDraw(Plot *plot, ScaleDraw* sd):
-	d_plot(plot)
-{
-	d_type = sd->d_type;
-	d_numeric_format = sd->d_numeric_format;
-	d_fmt = sd->d_fmt;
-    d_prec = sd->d_prec;
-	d_formula = sd->d_formula;
-	d_majTicks = sd->d_majTicks;
-	d_minTicks = sd->d_minTicks;
-	d_selected = sd->d_selected;
-	d_name_format = sd->d_name_format;
-	d_date_time_origin = sd->d_date_time_origin;
-	d_format_info = sd->d_format_info;
-	d_text_labels = sd->d_text_labels;
-
-	setLabelAlignment(sd->labelAlignment());
-	setLabelRotation(sd->labelRotation());
-}
-
-QwtText ScaleDraw::label(double value) const
+
+ScaleDraw::ScaleDraw(Plot *plot, ScaleDraw* sd):
+	d_plot(plot)
+{
+	d_type = sd->d_type;
+	d_numeric_format = sd->d_numeric_format;
+	d_fmt = sd->d_fmt;
+    d_prec = sd->d_prec;
+	d_formula = sd->d_formula;
+	d_majTicks = sd->d_majTicks;
+	d_minTicks = sd->d_minTicks;
+	d_selected = sd->d_selected;
+	d_name_format = sd->d_name_format;
+	d_date_time_origin = sd->d_date_time_origin;
+	d_format_info = sd->d_format_info;
+	d_text_labels = sd->d_text_labels;
+
+	setLabelAlignment(sd->labelAlignment());
+	setLabelRotation(sd->labelRotation());
+}
+
+QwtText ScaleDraw::label(double value) const
 {
 	switch (d_type){
-		case Numeric:
-		{
+		case Numeric:
+		{
             QLocale locale = ((Graph *)d_plot->parent())->multiLayer()->locale();
 			if (d_numeric_format == Superscripts){
 				QString txt = locale.toString(transformValue(value), 'e', d_prec);
@@ -125,9 +125,9 @@ QwtText ScaleDraw::label(double value) const
 					return QwtText("10<sup>" + s + "</sup>");
 				else
 					return QwtText(list[0] + "x10<sup>" + s + "</sup>");
-			} else
-				return QwtText(locale.toString(transformValue(value), d_fmt, d_prec));
-		break;
+			} else
+				return QwtText(locale.toString(transformValue(value), d_fmt, d_prec));
+		break;
 		}
 
 		case Day:
@@ -182,7 +182,7 @@ QwtText ScaleDraw::label(double value) const
 			return QwtText(d_date_time_origin.time().addMSecs((int)value).toString(d_format_info));
 		break;
 
-		case Date:
+		case Date:
             return QwtText(d_date_time_origin.addSecs((int)value).toString(d_format_info));
 		break;
 
@@ -192,58 +192,58 @@ QwtText ScaleDraw::label(double value) const
 			const QwtScaleDiv scDiv = scaleDiv();
 			if (!scDiv.contains (value))
 				return QwtText();
-
+
 			QwtValueList ticks = scDiv.ticks (QwtScaleDiv::MajorTick);
 
 			double break_offset = 0;
-			ScaleEngine *se = (ScaleEngine *)d_plot->axisScaleEngine(axis());
+			ScaleEngine *se = (ScaleEngine *)d_plot->axisScaleEngine(axis());
 			/*QwtScaleEngine *qwtsc_engine=d_plot->axisScaleEngine(axis());
-			ScaleEngine *se =dynamic_cast<ScaleEngine*>(qwtsc_engine);
-			if(se!=NULL)
-			{*/
-				bool inverted = se->testAttribute(QwtScaleEngine::Inverted);
-				if(se->hasBreak()){
-					double lb = se->axisBreakLeft();
+			ScaleEngine *se =dynamic_cast<ScaleEngine*>(qwtsc_engine);
+			if(se!=NULL)
+			{*/
+				bool inverted = se->testAttribute(QwtScaleEngine::Inverted);
+				if(se->hasBreak()){
+					double lb = se->axisBreakLeft();
 					double rb = se->axisBreakRight();
 					if(inverted){
 						if (value <= lb){
-							int n_ticks = (int)ticks.count() - 1;
+							int n_ticks = (int)ticks.count() - 1;
 							double val0 = ticks[0];
 							double val1 = ticks[n_ticks];
-							for (int i = 1; i < n_ticks; i++){
-								double aux = ticks[i];
-								if(aux >= rb && val0 > aux){
+							for (int i = 1; i < n_ticks; i++){
+								double aux = ticks[i];
+								if(aux >= rb && val0 > aux){
 									val0 = aux;
-									continue;
+									continue;
 								}
 								if(aux <= lb && val1 < aux)
 									val1 = aux;
 							}
 							break_offset = fabs(val1 - val0);
 						}
-					} else {
-						if (value >= rb){
-							double val0 = ticks[0];
-							for (int i = 1; i < (int)ticks.count(); i++){
-								double val = ticks[i];
-								if(val0 <= lb && val >= rb){
-									break_offset = fabs(val - val0);
-									break;
-								}
-								val0 = val;
-							}
-						}
-					}
-				}
-
+					} else {
+						if (value >= rb){
+							double val0 = ticks[0];
+							for (int i = 1; i < (int)ticks.count(); i++){
+								double val = ticks[i];
+								if(val0 <= lb && val >= rb){
+									break_offset = fabs(val - val0);
+									break;
+								}
+								val0 = val;
+							}
+						}
+					}
+				}
+
 				double step = ticks[1] - ticks[0];
-				int index = int(ticks[0] + step*ticks.indexOf(value) - 1);
+				int index = int(ticks[0] + step*ticks.indexOf(value) - 1);
 				int offset = abs((int)floor(break_offset/step));
-				if (offset)
-					offset--;
-				if (step > 0)
-					index += offset;
-				else
+				if (offset)
+					offset--;
+				if (step > 0)
+					index += offset;
+				else
 					index -= offset;
 				if (index >= 0 && index < (int)d_text_labels.count())
 					return QwtText(d_text_labels[index]);
@@ -253,17 +253,17 @@ QwtText ScaleDraw::label(double value) const
 		break;
 		}
 	}
-	return QwtText();
-}
-
-void ScaleDraw::drawLabel(QPainter *painter, double value) const
-{
-    if (!d_plot)
-        return;
-    ScaleEngine *sc_engine = (ScaleEngine *)d_plot->axisScaleEngine(axis());
+	return QwtText();
+}
+
+void ScaleDraw::drawLabel(QPainter *painter, double value) const
+{
+    if (!d_plot)
+        return;
+    ScaleEngine *sc_engine = (ScaleEngine *)d_plot->axisScaleEngine(axis());
 	/*QwtScaleEngine *qwtsc_engine=d_plot->axisScaleEngine(axis());
-    ScaleEngine *sc_engine =dynamic_cast< ScaleEngine*>(qwtsc_engine);
-	if(sc_engine!=NULL)
+    ScaleEngine *sc_engine =dynamic_cast< ScaleEngine*>(qwtsc_engine);
+	if(sc_engine!=NULL)
 	{*/	
 		if (sc_engine->hasBreak()){
 			bool invertedScale = sc_engine->testAttribute(QwtScaleEngine::Inverted);
@@ -271,31 +271,31 @@ void ScaleDraw::drawLabel(QPainter *painter, double value) const
 				return;
 			if (!invertedScale && sc_engine->axisBreakLeft() == value)
 				return;
-		}
-	//}
-
-		QwtText lbl = tickLabel(painter->font(), value);
-		if (lbl.isEmpty())
-			return;
-
-		const QPoint pos = labelPosition(value);
-
-		QSize labelSize = lbl.textSize(painter->font());
-		if ( labelSize.height() % 2 )
-			labelSize.setHeight(labelSize.height() + 1);
-
-		const QMatrix m = labelMatrix(pos, labelSize);
-
-		painter->save();
-		painter->setMatrix(m, true);
-		if (d_selected)
-			lbl.setBackgroundPen(QPen(Qt::blue));
-		else
-			lbl.setBackgroundPen(QPen(Qt::NoPen));
-
-		lbl.draw(painter, QRect(QPoint(0, 0), labelSize));
-		painter->restore();
-}
+		}
+	//}
+
+		QwtText lbl = tickLabel(painter->font(), value);
+		if (lbl.isEmpty())
+			return;
+
+		const QPoint pos = labelPosition(value);
+
+		QSize labelSize = lbl.textSize(painter->font());
+		if ( labelSize.height() % 2 )
+			labelSize.setHeight(labelSize.height() + 1);
+
+		const QMatrix m = labelMatrix(pos, labelSize);
+
+		painter->save();
+		painter->setMatrix(m, true);
+		if (d_selected)
+			lbl.setBackgroundPen(QPen(Qt::blue));
+		else
+			lbl.setBackgroundPen(QPen(Qt::NoPen));
+
+		lbl.draw(painter, QRect(QPoint(0, 0), labelSize));
+		painter->restore();
+}
 
 double ScaleDraw::transformValue(double value) const
 {
@@ -310,7 +310,7 @@ double ScaleDraw::transformValue(double value) const
 
 			parser.SetExpr(d_formula.ascii());
 			lbl=parser.Eval();
-        }
+        }
         catch(mu::ParserError &){
 			return 0;
         }
@@ -320,8 +320,8 @@ double ScaleDraw::transformValue(double value) const
 }
 
 void ScaleDraw::setNumericFormat(NumericFormat format)
-{
-    d_type = Numeric;
+{
+    d_type = Numeric;
 
 	if (d_numeric_format == format)
 		return;
@@ -385,7 +385,7 @@ void ScaleDraw::drawTick(QPainter *p, double value, int len) const
 {
 	ScaleEngine *sc_engine = (ScaleEngine *)d_plot->axisScaleEngine(axis());
 	/*QwtScaleEngine *qwtsc_engine=d_plot->axisScaleEngine(axis());
-    ScaleEngine *sc_engine =dynamic_cast< ScaleEngine*>(qwtsc_engine);
+    ScaleEngine *sc_engine =dynamic_cast< ScaleEngine*>(qwtsc_engine);
 	if(sc_engine!=NULL)
 	{*/
 		if (sc_engine->hasBreak()){
@@ -425,8 +425,8 @@ void ScaleDraw::draw(QPainter *painter, const QPalette& palette) const
 	drawBreak(painter);
 	QwtScaleDraw::draw(painter, palette);
 }
-
-void ScaleDraw::drawBreak(QPainter *painter) const
+
+void ScaleDraw::drawBreak(QPainter *painter) const
 {
 	ScaleEngine *sc_engine = (ScaleEngine *)d_plot->axisScaleEngine(axis());
 	/*const QwtScaleEngine * qwtsc_engine=d_plot->axisScaleEngine(axis());
@@ -435,33 +435,33 @@ void ScaleDraw::drawBreak(QPainter *painter) const
 	{*/
 		if (!sc_engine->hasBreak() || !sc_engine->hasBreakDecoration())
 			return;
-
-		painter->save();
-		painter->setRenderHint(QPainter::Antialiasing);
-
-		int len = majTickLength();
-
-		QwtScaleMap scaleMap = map();
-		const QwtMetricsMap metricsMap = QwtPainter::metricsMap();
-		QPoint pos = this->pos();
-
-		if ( !metricsMap.isIdentity() ){
-			QwtPainter::resetMetricsMap();
-			pos = metricsMap.layoutToDevice(pos);
-
-			if ( orientation() == Qt::Vertical ){
-				scaleMap.setPaintInterval(
-					metricsMap.layoutToDeviceY((int)scaleMap.p1()),
-					metricsMap.layoutToDeviceY((int)scaleMap.p2()));
-				len = metricsMap.layoutToDeviceX(len);
-			} else {
-				scaleMap.setPaintInterval(
-					metricsMap.layoutToDeviceX((int)scaleMap.p1()),
-					metricsMap.layoutToDeviceX((int)scaleMap.p2()));
-				len = metricsMap.layoutToDeviceY(len);
-			}
-		}
-
+
+		painter->save();
+		painter->setRenderHint(QPainter::Antialiasing);
+
+		int len = majTickLength();
+
+		QwtScaleMap scaleMap = map();
+		const QwtMetricsMap metricsMap = QwtPainter::metricsMap();
+		QPoint pos = this->pos();
+
+		if ( !metricsMap.isIdentity() ){
+			QwtPainter::resetMetricsMap();
+			pos = metricsMap.layoutToDevice(pos);
+
+			if ( orientation() == Qt::Vertical ){
+				scaleMap.setPaintInterval(
+					metricsMap.layoutToDeviceY((int)scaleMap.p1()),
+					metricsMap.layoutToDeviceY((int)scaleMap.p2()));
+				len = metricsMap.layoutToDeviceX(len);
+			} else {
+				scaleMap.setPaintInterval(
+					metricsMap.layoutToDeviceX((int)scaleMap.p1()),
+					metricsMap.layoutToDeviceX((int)scaleMap.p2()));
+				len = metricsMap.layoutToDeviceY(len);
+			}
+		}
+
 		int lval = scaleMap.transform(sc_engine->axisBreakLeft());
 		int rval = scaleMap.transform(sc_engine->axisBreakRight());
 		switch(alignment()){
@@ -482,75 +482,75 @@ void ScaleDraw::drawBreak(QPainter *painter) const
 			QwtPainter::drawLine(painter, rval, pos.y(), rval + len, pos.y() - len);
 			break;
 		}
-
-		QwtPainter::setMetricsMap(metricsMap); // restore metrics map
-		painter->restore();
-	//}
-}
-
-void ScaleDraw::drawBackbone(QPainter *painter) const
-{
-    ScaleEngine *sc_engine = (ScaleEngine *)d_plot->axisScaleEngine(axis());
+
+		QwtPainter::setMetricsMap(metricsMap); // restore metrics map
+		painter->restore();
+	//}
+}
+
+void ScaleDraw::drawBackbone(QPainter *painter) const
+{
+    ScaleEngine *sc_engine = (ScaleEngine *)d_plot->axisScaleEngine(axis());
 	/*QwtScaleEngine *qwtsc_engine=d_plot->axisScaleEngine(axis());
-	ScaleEngine *sc_engine =dynamic_cast<ScaleEngine*>(qwtsc_engine);
-	if(sc_engine!=NULL)
-	{*/
-		if (!sc_engine->hasBreak()){
-			const int len = length();
-			const int bw = painter->pen().width();
-			const int bw2 = bw / 2;
-			QPoint pos = this->pos();
-			switch(alignment()){
-			case LeftScale:
-				QwtPainter::drawLine(painter, pos.x() - bw2,
-					pos.y(), pos.x() - bw2, pos.y() + len );
-				break;
-			case RightScale:
-				QwtPainter::drawLine(painter, pos.x() + bw2,
-					pos.y(), pos.x() + bw2, pos.y() + len);
-				break;
-			case TopScale:
-				QwtPainter::drawLine(painter, pos.x(), pos.y() - bw2,
-					pos.x() + len, pos.y() - bw2);
-				break;
-			case BottomScale:
-				QwtPainter::drawLine(painter, pos.x(), pos.y() + bw2,
-					pos.x() + len, pos.y() + bw2);
-				break;
-			}
-			return;
-		}
-
-		QwtScaleMap scaleMap = map();
-		const QwtMetricsMap metricsMap = QwtPainter::metricsMap();
-		QPoint pos = this->pos();
-
-		if ( !metricsMap.isIdentity() ){
-			QwtPainter::resetMetricsMap();
-			pos = metricsMap.layoutToDevice(pos);
-
-			if ( orientation() == Qt::Vertical ){
-				scaleMap.setPaintInterval(
-					metricsMap.layoutToDeviceY((int)scaleMap.p1()),
-					metricsMap.layoutToDeviceY((int)scaleMap.p2()));
-			} else {
-				scaleMap.setPaintInterval(
-					metricsMap.layoutToDeviceX((int)scaleMap.p1()),
-					metricsMap.layoutToDeviceX((int)scaleMap.p2()));
-			}
-		}
+	ScaleEngine *sc_engine =dynamic_cast<ScaleEngine*>(qwtsc_engine);
+	if(sc_engine!=NULL)
+	{*/
+		if (!sc_engine->hasBreak()){
+			const int len = length();
+			const int bw = painter->pen().width();
+			const int bw2 = bw / 2;
+			QPoint pos = this->pos();
+			switch(alignment()){
+			case LeftScale:
+				QwtPainter::drawLine(painter, pos.x() - bw2,
+					pos.y(), pos.x() - bw2, pos.y() + len );
+				break;
+			case RightScale:
+				QwtPainter::drawLine(painter, pos.x() + bw2,
+					pos.y(), pos.x() + bw2, pos.y() + len);
+				break;
+			case TopScale:
+				QwtPainter::drawLine(painter, pos.x(), pos.y() - bw2,
+					pos.x() + len, pos.y() - bw2);
+				break;
+			case BottomScale:
+				QwtPainter::drawLine(painter, pos.x(), pos.y() + bw2,
+					pos.x() + len, pos.y() + bw2);
+				break;
+			}
+			return;
+		}
+
+		QwtScaleMap scaleMap = map();
+		const QwtMetricsMap metricsMap = QwtPainter::metricsMap();
+		QPoint pos = this->pos();
+
+		if ( !metricsMap.isIdentity() ){
+			QwtPainter::resetMetricsMap();
+			pos = metricsMap.layoutToDevice(pos);
+
+			if ( orientation() == Qt::Vertical ){
+				scaleMap.setPaintInterval(
+					metricsMap.layoutToDeviceY((int)scaleMap.p1()),
+					metricsMap.layoutToDeviceY((int)scaleMap.p2()));
+			} else {
+				scaleMap.setPaintInterval(
+					metricsMap.layoutToDeviceX((int)scaleMap.p1()),
+					metricsMap.layoutToDeviceX((int)scaleMap.p2()));
+			}
+		}
 
 		const int start = scaleMap.transform(sc_engine->axisBreakLeft());
-		const int end = scaleMap.transform(sc_engine->axisBreakRight());
+		const int end = scaleMap.transform(sc_engine->axisBreakRight());
 		int lb = start, rb = end;
 		if (sc_engine->testAttribute(QwtScaleEngine::Inverted)){
 			lb = end;
 			rb = start;
 		}
 
-		const int bw = painter->pen().width();
+		const int bw = painter->pen().width();
 		const int bw2 = bw / 2;
-		const int len = length() - 1;
+		const int len = length() - 1;
 		int aux;
 		switch(alignment())
 		{
@@ -574,9 +574,9 @@ void ScaleDraw::drawBackbone(QPainter *painter) const
 			QwtPainter::drawLine(painter, pos.x(), aux, lb - bw, aux);
 			QwtPainter::drawLine(painter, rb, aux, pos.x() + len, aux);
 			break;
-		}
-	//}
-}
+		}
+	//}
+}
 
 void ScaleDraw::setDayFormat(NameFormat format)
 {
@@ -603,13 +603,13 @@ void ScaleDraw::setDateFormat(const QDateTime& d, const QString& format)
 	d_format_info = format;
 	d_date_time_origin = d;
 }
-
-QString ScaleDraw::formatString()
-{
-    if (d_type == Time)
-        return d_date_time_origin.time().toString() + ";" + d_format_info;
-    else if (d_type == Date)
-        return d_date_time_origin.toString(Qt::ISODate) + ";" + d_format_info;
-
-    return d_format_info;
+
+QString ScaleDraw::formatString()
+{
+    if (d_type == Time)
+        return d_date_time_origin.time().toString() + ";" + d_format_info;
+    else if (d_type == Date)
+        return d_date_time_origin.toString(Qt::ISODate) + ";" + d_format_info;
+
+    return d_format_info;
 }
diff --git a/Code/Mantid/MantidPlot/src/ScaleDraw.h b/Code/Mantid/MantidPlot/src/ScaleDraw.h
index 83a7727eebe740bb67bf39e0fed260e06402dbac..52b0aad330445e8dda55075edf09e1ca0b490efa 100644
--- a/Code/Mantid/MantidPlot/src/ScaleDraw.h
+++ b/Code/Mantid/MantidPlot/src/ScaleDraw.h
@@ -44,14 +44,14 @@ public:
 	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.
+
+    //! 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);
-
-    QString formatString();
-    QString format(){return d_format_info;};
+
+    QString formatString();
+    QString format(){return d_format_info;};
 
 	QString formula() {return d_formula;};
 	void setFormula(const QString& formula) {d_formula = formula;};
@@ -66,8 +66,8 @@ public:
 	void setMajorTicksStyle(TicksStyle type){d_majTicks = type;};
 
 	int minorTicksStyle(){return d_minTicks;};
-	void setMinorTicksStyle(TicksStyle type){d_minTicks = type;};
-
+	void setMinorTicksStyle(TicksStyle type){d_minTicks = type;};
+
 	void setSelected(bool select = true){d_selected = select;};
 
 	int axis() const;
@@ -83,20 +83,20 @@ public:
 	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;};
+	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;};
+
+	QStringList labelsList(){return d_text_labels;};
 
-	QStringList labelsList(){return d_text_labels;};
-
 	NameFormat nameFormat(){return d_name_format;};
 
 protected:
-	virtual void draw (QPainter *, const QPalette &) const;
+	virtual void draw (QPainter *, const QPalette &) const;
     virtual void drawLabel(QPainter *painter, double value) const;
-	virtual void drawTick(QPainter *p, double value, int len) const;
-	virtual void drawBackbone(QPainter *painter) const;
+	virtual void drawTick(QPainter *p, double value, int len) const;
+	virtual void drawBackbone(QPainter *painter) const;
 	void drawBreak(QPainter *) const;
 
 private:
@@ -122,9 +122,9 @@ private:
 	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
+	//! 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
diff --git a/Code/Mantid/MantidPlot/src/ScalePicker.cpp b/Code/Mantid/MantidPlot/src/ScalePicker.cpp
index 33943ed24e61581469bae233b68911b47232142d..45443ad6f3484e210fd2bafc1889615b7a4c832f 100644
--- a/Code/Mantid/MantidPlot/src/ScalePicker.cpp
+++ b/Code/Mantid/MantidPlot/src/ScalePicker.cpp
@@ -26,9 +26,9 @@
  *   Boston, MA  02110-1301  USA                                           *
  *                                                                         *
  ***************************************************************************/
-#include "ScalePicker.h"
+#include "ScalePicker.h"
 #include "ScaleDraw.h"
-#include "Graph.h"
+#include "Graph.h"
 
 #include <qwt_plot.h>
 #include <qwt_scale_widget.h>
@@ -65,13 +65,13 @@ bool ScalePicker::eventFilter(QObject *object, QEvent *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))
+			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);
@@ -202,31 +202,31 @@ QRect ScalePicker::titleRect(const QwtScaleWidget *scale) const
     }
 	return rect;
 }
-
-void ScalePicker::selectTitle(QwtScaleWidget *scale, bool select)
-{
-    if (!scale)
-        return;
-
-    if (d_title_selected == select && d_selected_axis == scale)
-        return;
-
-    Graph *g = (Graph *)plot()->parent();
+
+void ScalePicker::selectTitle(QwtScaleWidget *scale, bool select)
+{
+    if (!scale)
+        return;
+
+    if (d_title_selected == select && d_selected_axis == scale)
+        return;
+
+    Graph *g = (Graph *)plot()->parent();
     g->deselect();
-
-    d_title_selected = select;
+
+    d_title_selected = select;
     d_selected_axis = scale;
-	d_labels_selected = false;
-
-    QwtText title = scale->title();
-    if (select){
+	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));
-
-    scale->setTitle(title);
-}
+		g->notifyFontChange(title.font());
+    } else
+        title.setBackgroundPen(QPen(Qt::NoPen));
+
+    scale->setTitle(title);
+}
 
 void ScalePicker::selectLabels(QwtScaleWidget *scale, bool select)
 {
@@ -249,8 +249,8 @@ void ScalePicker::selectLabels(QwtScaleWidget *scale, bool select)
 	sc_draw->setSelected(select);
 	scale->repaint();
 }
-
-void ScalePicker::deselect()
+
+void ScalePicker::deselect()
 {
 	if (!d_selected_axis)
 		return;
@@ -264,7 +264,7 @@ void ScalePicker::deselect()
 
 	ScaleDraw *sc_draw = (ScaleDraw *)d_selected_axis->scaleDraw();
 	sc_draw->setSelected(false);
-
+
     d_selected_axis->repaint();
 	d_selected_axis = NULL;
 }
diff --git a/Code/Mantid/MantidPlot/src/ScalePicker.h b/Code/Mantid/MantidPlot/src/ScalePicker.h
index 12118118b320bdc36333b803df58d45b913c9ef3..fcf5d0865ecd8afefea9c9925d96389a1b68a1eb 100644
--- a/Code/Mantid/MantidPlot/src/ScalePicker.h
+++ b/Code/Mantid/MantidPlot/src/ScalePicker.h
@@ -64,7 +64,7 @@ public:
 
 	void deselect();
 	
-	bool titleSelected(){return d_title_selected;};
+	bool titleSelected(){return d_title_selected;};
     void selectTitle(QwtScaleWidget *scale, bool select = true);
 	
 	bool labelsSelected(){return d_labels_selected;};
@@ -75,7 +75,7 @@ public:
 	 */
 	QwtScaleWidget* selectedAxis(){return d_selected_axis;};
 	//! Returns a pointer to the active axis in the plot layer.
-	QwtScaleWidget* currentAxis(){return d_current_axis;};
+	QwtScaleWidget* currentAxis(){return d_current_axis;};
 
 signals:
 	//! Emitted when the user clicks on one of the monitored axes.
@@ -97,14 +97,14 @@ signals:
 	 */
 	void axisTitleDblClicked();
 	
-private:
+private:
     bool eventFilter(QObject *, QEvent *);
 
 	void mouseDblClicked(const QwtScaleWidget *, const QPoint &);
 	void mouseClicked(const QwtScaleWidget *scale, const QPoint &pos) ;
-	void mouseRightClicked(const QwtScaleWidget *scale, const QPoint &pos);
-
+	void mouseRightClicked(const QwtScaleWidget *scale, const QPoint &pos);
+
 	bool d_title_selected;
-	bool d_labels_selected;
+	bool d_labels_selected;
 	QwtScaleWidget *d_selected_axis, *d_current_axis;
 };
diff --git a/Code/Mantid/MantidPlot/src/ScreenPickerTool.cpp b/Code/Mantid/MantidPlot/src/ScreenPickerTool.cpp
index 9b00f493d78f501ab7cfcc3fc53ae246fb9553b9..19740f9ec22cc4599cc03cd514a4a785a5e56faa 100644
--- a/Code/Mantid/MantidPlot/src/ScreenPickerTool.cpp
+++ b/Code/Mantid/MantidPlot/src/ScreenPickerTool.cpp
@@ -82,17 +82,17 @@ bool ScreenPickerTool::eventFilter(QObject *obj, QEvent *event)
 				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());
+					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 selected(d_selection_marker.value());
+						QString info;
                         emit statusText(info.sprintf("x=%g; y=%g", pos.x(), pos.y()));
-						return true;
+						return true;
 					}
 					default:
 						break;
@@ -116,9 +116,9 @@ void DrawPointTool::appendPoint(const QwtDoublePoint &pos)
 {
 	if (!d_app)
 		return;
-
-    QString info;
-	emit statusText(info.sprintf("x=%g; y=%g", pos.x(), pos.y()));
+
+    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, "");
@@ -148,36 +148,36 @@ void DrawPointTool::appendPoint(const QwtDoublePoint &pos)
 	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/Code/Mantid/MantidPlot/src/ScreenPickerTool.h b/Code/Mantid/MantidPlot/src/ScreenPickerTool.h
index 05944db83fbe82bc78e55c8048d88b873fe2c5b7..b1c4bfbef262f45cba1ac0eb29cdeccf85c2c01d 100644
--- a/Code/Mantid/MantidPlot/src/ScreenPickerTool.h
+++ b/Code/Mantid/MantidPlot/src/ScreenPickerTool.h
@@ -57,7 +57,7 @@ class ScreenPickerTool : public QwtPlotPicker, public PlotToolInterface
 		 * You don't have to connect to this signal if you alreay specified a reciever during initialization.
 		 */
 		void statusText(const QString&);
-	protected:
+	protected:
         virtual bool eventFilter(QObject *obj, QEvent *event);
 		virtual void append(const QPoint &point);
 		QwtPlotMarker d_selection_marker;
@@ -72,7 +72,7 @@ class DrawPointTool : public ScreenPickerTool
 	public:
 		DrawPointTool(ApplicationWindow *app, Graph *graph, const QObject *status_target=NULL, const char *status_slot="");
 
-	protected:
+	protected:
         virtual bool eventFilter(QObject *obj, QEvent *event);
 		void appendPoint(const QwtDoublePoint &point);
 		DataCurve *d_curve;
diff --git a/Code/Mantid/MantidPlot/src/ScriptManagerWidget.cpp b/Code/Mantid/MantidPlot/src/ScriptManagerWidget.cpp
index 5e8e3b55eeba04d753612108b0657707cbcecc3f..5d228c0743538a6e18ae9d330de7164b51e385ba 100644
--- a/Code/Mantid/MantidPlot/src/ScriptManagerWidget.cpp
+++ b/Code/Mantid/MantidPlot/src/ScriptManagerWidget.cpp
@@ -571,9 +571,9 @@ bool ScriptManagerWidget::runScriptCode(const QString & code, const int line_off
   }
   runner->setCode(code);
   QString filename = "<input>";
-  if( editor && !editor->fileName().isEmpty() )
-  {
-    filename = editor->fileName();
+  if( editor && !editor->fileName().isEmpty() )
+  {
+    filename = editor->fileName();
   }
   runner->setName(filename);
   emit ScriptIsActive(true);
@@ -1196,15 +1196,15 @@ void ScriptManagerWidget::openRecentScript(int index)
 * @param index :: The index of the selected script
 */
 void ScriptManagerWidget::updateRecentScriptList()
-{
-  if (m_recentScriptList.isEmpty())
-    return;
-
-  while ((int)m_recentScriptList.size() > MaxRecentScripts)
-    m_recentScriptList.pop_back();
-
-  m_recent_scripts->clear();
-  for (int i = 0; i<m_recentScriptList.size(); i++ )
+{
+  if (m_recentScriptList.isEmpty())
+    return;
+
+  while ((int)m_recentScriptList.size() > MaxRecentScripts)
+    m_recentScriptList.pop_back();
+
+  m_recent_scripts->clear();
+  for (int i = 0; i<m_recentScriptList.size(); i++ )
     m_recent_scripts->insertItem("&" + QString::number(i+1) + " " + m_recentScriptList[i]);
 
 }
diff --git a/Code/Mantid/MantidPlot/src/SelectionMoveResizer.cpp b/Code/Mantid/MantidPlot/src/SelectionMoveResizer.cpp
index ad0510ead47bc0892ab5792e68899b9638f0e1c5..317623376cccb28dd8ac452efae85960423ffbf2 100644
--- a/Code/Mantid/MantidPlot/src/SelectionMoveResizer.cpp
+++ b/Code/Mantid/MantidPlot/src/SelectionMoveResizer.cpp
@@ -73,7 +73,7 @@ void SelectionMoveResizer::init()
 	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);
@@ -307,15 +307,15 @@ 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());
+		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();
+            i->setFont(f);
+            i->repaint();
             ((Graph *)i->parent()->parent())->notifyFontChange(f);
-		}
-	}
+		}
+	}
 
 	foreach(ArrowMarker *i, d_line_markers) {
 		QPoint p1 = i->startPoint();
@@ -336,7 +336,7 @@ void SelectionMoveResizer::operateOnTargets()
 	}
 
 	foreach(QWidget *i, d_widgets)
-		i->setGeometry(operateOn(i->geometry()));
+		i->setGeometry(operateOn(i->geometry()));
 
 	recalcBoundingRect();
 
diff --git a/Code/Mantid/MantidPlot/src/SetColValuesDialog.cpp b/Code/Mantid/MantidPlot/src/SetColValuesDialog.cpp
index 1338eef21ce5bf9fc0076efc164a94902e3c3c09..f033e26f76e2f31abe28c0b85f318a10e02bd94c 100644
--- a/Code/Mantid/MantidPlot/src/SetColValuesDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/SetColValuesDialog.cpp
@@ -175,9 +175,9 @@ void SetColValuesDialog::nextColumn()
 }
 
 void SetColValuesDialog::updateColumn(int sc)
-{
-    if (sc < 0 || sc > table->numCols() - 1)
-        return;
+{
+    if (sc < 0 || sc > table->numCols() - 1)
+        return;
 
 	if (sc == 0)
 		buttonPrev->setEnabled(false);
diff --git a/Code/Mantid/MantidPlot/src/SigmoidalFit.cpp b/Code/Mantid/MantidPlot/src/SigmoidalFit.cpp
index 9836a8a906b1192249858323bd006925563f805b..76432ce82281f1f0606752eacc9086eaf61852ca 100644
--- a/Code/Mantid/MantidPlot/src/SigmoidalFit.cpp
+++ b/Code/Mantid/MantidPlot/src/SigmoidalFit.cpp
@@ -68,7 +68,7 @@ void SigmoidalFit::init()
 	d_explanation = tr("Boltzmann (Sigmoidal) Fit");
 	d_formula = "A2+(A1-A2)/(1+exp((x-x0)/dx))";
 	d_p = 4;
-    initWorkspace(d_p);
+    initWorkspace(d_p);
 }
 
 void SigmoidalFit::calculateFitCurveData(double *X, double *Y)
@@ -80,20 +80,20 @@ void SigmoidalFit::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);
+		double step = (d_x[d_n-1]-X0)/(d_points-1);
         for (int i=0; i<d_points; i++){
-			double x = X0+i*step;
+			double x = X0+i*step;
         	X[i] = x;
-        	Y[i] = (a1 - a2)/(1 + exp((x - x0)/p)) + a2;
+        	Y[i] = (a1 - a2)/(1 + exp((x - x0)/p)) + a2;
 		}
-	} else {
+	} else {
         for (int i=0; i<d_points; i++){
-			double x = d_x[i];
+			double x = d_x[i];
         	X[i] = x;
-        	Y[i] = (a1 - a2)/(1 + exp((x - x0)/p)) + a2;
+        	Y[i] = (a1 - a2)/(1 + exp((x - x0)/p)) + a2;
 		}
 	}
-}
+}
 
 void SigmoidalFit::guessInitialValues()
 {
diff --git a/Code/Mantid/MantidPlot/src/SigmoidalFit.h b/Code/Mantid/MantidPlot/src/SigmoidalFit.h
index f97a65cb4f7262d4f25b5cc77a7a7a3fcc91f309..06dfa8c2470d0b8cd262081fa05cd983b7f04862 100644
--- a/Code/Mantid/MantidPlot/src/SigmoidalFit.h
+++ b/Code/Mantid/MantidPlot/src/SigmoidalFit.h
@@ -40,16 +40,16 @@ class SigmoidalFit : public Fit
 		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){return (par[0]-par[1])/(1+exp((x-par[2])/par[3]))+par[1];};
 
-		void guessInitialValues();
+        double eval(double *par, double x){return (par[0]-par[1])/(1+exp((x-par[2])/par[3]))+par[1];};
+
+		void guessInitialValues();
 		void setLogistic(bool on = true);
 
 	private:
 		void init();
-		void calculateFitCurveData(double *X, double *Y);
-
+		void calculateFitCurveData(double *X, double *Y);
+
 		bool d_logistic;
 };
 
diff --git a/Code/Mantid/MantidPlot/src/Spectrogram.cpp b/Code/Mantid/MantidPlot/src/Spectrogram.cpp
index a88909851be7adc653bb47869aedc0fe8a2a63e8..5bf9878148c48d8e802c8133313d6c77499d9d86 100644
--- a/Code/Mantid/MantidPlot/src/Spectrogram.cpp
+++ b/Code/Mantid/MantidPlot/src/Spectrogram.cpp
@@ -33,9 +33,9 @@
 #include <qwt_scale_widget.h>
 #include <QColor>
 #include <qwt_painter.h>
-#include "qwt_scale_engine.h"
+#include "qwt_scale_engine.h"
 #include <QPainter>
-#include <qwt_symbol.h>
+#include <qwt_symbol.h>
 
 
 #include <iostream>
@@ -98,13 +98,13 @@ Spectrogram::Spectrogram(UserHelperFunction *f,int nrows, int ncols,QwtDoubleRec
  	d_funct(f),
  	color_axis(QwtPlot::yRight),
  	color_map_policy(Default),
- 	d_show_labels(true),
- 	d_white_out_labels(false),
- 	d_labels_angle(0.0),
+ 	d_show_labels(true),
+ 	d_white_out_labels(false),
+ 	d_labels_angle(0.0),
  	d_selected_label(NULL),
   d_labels_color(Qt::black),
- 	d_labels_x_offset(0), 	d_labels_y_offset(0),
- 	d_labels_align(Qt::AlignHCenter),
+ 	d_labels_x_offset(0), 	d_labels_y_offset(0),
+ 	d_labels_align(Qt::AlignHCenter),
  	d_labels_font(QFont()),
  	mColorMap(),
  	m_nRows(nrows),
@@ -129,10 +129,10 @@ Spectrogram::~Spectrogram()
 }
 
 
-void Spectrogram::setContourLevels (const QwtValueList & levels)
-{
-  QwtPlotSpectrogram::setContourLevels(levels);
-  createLabels();
+void Spectrogram::setContourLevels (const QwtValueList & levels)
+{
+  QwtPlotSpectrogram::setContourLevels(levels);
+  createLabels();
 }
 
 void Spectrogram::updateData(Matrix *m)
@@ -346,140 +346,140 @@ QwtLinearColorMap Spectrogram::defaultColorMap()
   colorMap.addColorStop(0.75, Qt::yellow);
   return colorMap;
 }
-void Spectrogram::setColorMapPen(bool on)
-{
-  if (d_color_map_pen == on)
-    return;
-
-  d_color_map_pen = on;
-  if (on) {
-    setDefaultContourPen(Qt::NoPen);
-    d_pen_list.clear();
-  }
-}
-/**
-for creating contour line labels
- */
-void Spectrogram::createLabels()
-{
-  foreach(QwtPlotMarker *m, d_labels_list){
-    m->detach();
-    delete m;
-  }
-  d_labels_list.clear();
-  QwtValueList levels = contourLevels();
-  const int numLevels = levels.size();
-  for (int l = 0; l < numLevels; l++){
-    PlotMarker *m = new PlotMarker(l, d_labels_angle);
-    QwtText t = QwtText(QString::number(levels[l]));
-    t.setColor(d_labels_color);
-    t.setFont(d_labels_font);
-
-    if (d_white_out_labels)
-      t.setBackgroundBrush(QBrush(Qt::white));
-    else
-      t.setBackgroundBrush(QBrush(Qt::transparent));
-    m->setLabel(t);
-
-    int x_axis = xAxis();
-    int y_axis = yAxis();
-    m->setAxis(x_axis, y_axis);
-
-    QwtPlot *d_plot = plot();
-    if (!d_plot)
-      return;
-    if (d_plot && d_show_labels)
-    {	m->attach(d_plot);
-    }
-    d_labels_list << m;
-  }
-}
-void Spectrogram::showContourLineLabels(bool show)
-{
-  if (show == d_show_labels)
-  {
-    return;
-  }
-  d_show_labels = show;
-  QwtPlot *d_plot = plot();
-  if (!d_plot)
-    return;
-  foreach(PlotMarker *m, d_labels_list){
-    if (d_show_labels)
-    {	m->attach(d_plot);
-    }
-    else
-      m->detach();
-  }
-}
-bool Spectrogram::hasSelectedLabels()
-{
-  /*if (d_labels_list.isEmpty())
-        return false;
-
-    foreach(PlotMarker *m, d_labels_list){
-        if (m->label().backgroundPen() == QPen(Qt::blue))
-            return true;
-        else
-            return false;
-    }
-    return false;*/
-
-  if (d_selected_label)
-    return true;
-  return false;
-}
-void Spectrogram::selectLabel(bool on)
-{
-  QwtPlot *d_plot = plot();
-  if (!d_plot)
-    return;
-  if (on){
-    //d_plot->deselect();
-    //d_plot->notifyFontChange(d_labels_font);
-  }
-
-  foreach(PlotMarker *m, d_labels_list){
-    QwtText t = m->label();
-    if(t.text().isEmpty())
-      return;
-
-    if (d_selected_label && m == d_selected_label && on)
-      t.setBackgroundPen(QPen(Qt::blue));
-    else
-      t.setBackgroundPen(QPen(Qt::NoPen));
-
-    m->setLabel(t);
-  }
-  d_plot->replot();
-}
-
-
-bool Spectrogram::selectedLabels(const QPoint& pos)
-{
-  d_selected_label = NULL;
-  QwtPlot *d_plot = plot();
-  if (!d_plot)
-    return false;
-
-  /*if (d_plot->hasActiveTool())
-		return false;*/
-  foreach(PlotMarker *m, d_labels_list){
-    int x = d_plot->transform(xAxis(), m->xValue());
-    int y = d_plot->transform(yAxis(), m->yValue());
-
-    QMatrix wm;
-    wm.translate(x, y);
-    wm.rotate(-d_labels_angle);
-    if (wm.mapToPolygon(QRect(QPoint(0, 0), m->label().textSize())).containsPoint(pos, Qt::OddEvenFill)){
-      d_selected_label = m;
-      d_click_pos_x = d_plot->invTransform(xAxis(), pos.x());
-      d_click_pos_y = d_plot->invTransform(yAxis(), pos.y());
-      selectLabel(true);
-      return true;
-    }
-  }
-  return false;
+void Spectrogram::setColorMapPen(bool on)
+{
+  if (d_color_map_pen == on)
+    return;
+
+  d_color_map_pen = on;
+  if (on) {
+    setDefaultContourPen(Qt::NoPen);
+    d_pen_list.clear();
+  }
+}
+/**
+for creating contour line labels
+ */
+void Spectrogram::createLabels()
+{
+  foreach(QwtPlotMarker *m, d_labels_list){
+    m->detach();
+    delete m;
+  }
+  d_labels_list.clear();
+  QwtValueList levels = contourLevels();
+  const int numLevels = levels.size();
+  for (int l = 0; l < numLevels; l++){
+    PlotMarker *m = new PlotMarker(l, d_labels_angle);
+    QwtText t = QwtText(QString::number(levels[l]));
+    t.setColor(d_labels_color);
+    t.setFont(d_labels_font);
+
+    if (d_white_out_labels)
+      t.setBackgroundBrush(QBrush(Qt::white));
+    else
+      t.setBackgroundBrush(QBrush(Qt::transparent));
+    m->setLabel(t);
+
+    int x_axis = xAxis();
+    int y_axis = yAxis();
+    m->setAxis(x_axis, y_axis);
+
+    QwtPlot *d_plot = plot();
+    if (!d_plot)
+      return;
+    if (d_plot && d_show_labels)
+    {	m->attach(d_plot);
+    }
+    d_labels_list << m;
+  }
+}
+void Spectrogram::showContourLineLabels(bool show)
+{
+  if (show == d_show_labels)
+  {
+    return;
+  }
+  d_show_labels = show;
+  QwtPlot *d_plot = plot();
+  if (!d_plot)
+    return;
+  foreach(PlotMarker *m, d_labels_list){
+    if (d_show_labels)
+    {	m->attach(d_plot);
+    }
+    else
+      m->detach();
+  }
+}
+bool Spectrogram::hasSelectedLabels()
+{
+  /*if (d_labels_list.isEmpty())
+        return false;
+
+    foreach(PlotMarker *m, d_labels_list){
+        if (m->label().backgroundPen() == QPen(Qt::blue))
+            return true;
+        else
+            return false;
+    }
+    return false;*/
+
+  if (d_selected_label)
+    return true;
+  return false;
+}
+void Spectrogram::selectLabel(bool on)
+{
+  QwtPlot *d_plot = plot();
+  if (!d_plot)
+    return;
+  if (on){
+    //d_plot->deselect();
+    //d_plot->notifyFontChange(d_labels_font);
+  }
+
+  foreach(PlotMarker *m, d_labels_list){
+    QwtText t = m->label();
+    if(t.text().isEmpty())
+      return;
+
+    if (d_selected_label && m == d_selected_label && on)
+      t.setBackgroundPen(QPen(Qt::blue));
+    else
+      t.setBackgroundPen(QPen(Qt::NoPen));
+
+    m->setLabel(t);
+  }
+  d_plot->replot();
+}
+
+
+bool Spectrogram::selectedLabels(const QPoint& pos)
+{
+  d_selected_label = NULL;
+  QwtPlot *d_plot = plot();
+  if (!d_plot)
+    return false;
+
+  /*if (d_plot->hasActiveTool())
+		return false;*/
+  foreach(PlotMarker *m, d_labels_list){
+    int x = d_plot->transform(xAxis(), m->xValue());
+    int y = d_plot->transform(yAxis(), m->yValue());
+
+    QMatrix wm;
+    wm.translate(x, y);
+    wm.rotate(-d_labels_angle);
+    if (wm.mapToPolygon(QRect(QPoint(0, 0), m->label().textSize())).containsPoint(pos, Qt::OddEvenFill)){
+      d_selected_label = m;
+      d_click_pos_x = d_plot->invTransform(xAxis(), pos.x());
+      d_click_pos_y = d_plot->invTransform(yAxis(), pos.y());
+      selectLabel(true);
+      return true;
+    }
+  }
+  return false;
 }
 
 QString Spectrogram::saveToString()
@@ -538,60 +538,60 @@ QString Spectrogram::saveToString()
   s+="\t<IntensityChanged>"+QString::number(isIntensityChanged())+"</IntensityChanged>\n";
   return s+"</spectrogram>\n";
 }
-/**
- * Returns a reference to the constant colormap
- */
-const MantidColorMap & Spectrogram::getColorMap() const
-{
-
-  return mColorMap;
-
-}
-void Spectrogram::setMantidColorMap(const MantidColorMap &map)
-{
-  setColorMap(map);
-}
-/**
- * Returns a reference to the colormap
- */
-MantidColorMap & Spectrogram::mutableColorMap()
-{
-  return mColorMap;
-}
-/**
- * Save properties of the window a persistent store
- */
-void Spectrogram::saveSettings()
-{
-  QSettings settings;
-  settings.beginGroup("Mantid/2DPlotSpectrogram");
-  //settings.setValue("BackgroundColor", mInstrumentDisplay->currentBackgroundColor());
-  settings.setValue("ColormapFile", mCurrentColorMap);
-  settings.setValue("ScaleType",getColorMap().getScaleType());
-  settings.endGroup();
-}
-/**
- * This method loads the setting from QSettings
- */
-void Spectrogram::loadSettings()
-{
-  //Load Color
-  QSettings settings;
-  settings.beginGroup("Mantid/2DPlotSpectrogram");
-
-  //Load Colormap. If the file is invalid the default stored colour map is used
-  mCurrentColorMap = settings.value("ColormapFile", "").toString();
-  // Set values from settings
-  mutableColorMap().loadMap(mCurrentColorMap);
-
-  GraphOptions::ScaleType type = (GraphOptions::ScaleType)settings.value("ScaleType", GraphOptions::Log10).toUInt();
-
-  mutableColorMap().changeScaleType(type);
-
-  settings.endGroup();
-}
-/**
- * This method saves the selectcolrmap file name to membervaraible
+/**
+ * Returns a reference to the constant colormap
+ */
+const MantidColorMap & Spectrogram::getColorMap() const
+{
+
+  return mColorMap;
+
+}
+void Spectrogram::setMantidColorMap(const MantidColorMap &map)
+{
+  setColorMap(map);
+}
+/**
+ * Returns a reference to the colormap
+ */
+MantidColorMap & Spectrogram::mutableColorMap()
+{
+  return mColorMap;
+}
+/**
+ * Save properties of the window a persistent store
+ */
+void Spectrogram::saveSettings()
+{
+  QSettings settings;
+  settings.beginGroup("Mantid/2DPlotSpectrogram");
+  //settings.setValue("BackgroundColor", mInstrumentDisplay->currentBackgroundColor());
+  settings.setValue("ColormapFile", mCurrentColorMap);
+  settings.setValue("ScaleType",getColorMap().getScaleType());
+  settings.endGroup();
+}
+/**
+ * This method loads the setting from QSettings
+ */
+void Spectrogram::loadSettings()
+{
+  //Load Color
+  QSettings settings;
+  settings.beginGroup("Mantid/2DPlotSpectrogram");
+
+  //Load Colormap. If the file is invalid the default stored colour map is used
+  mCurrentColorMap = settings.value("ColormapFile", "").toString();
+  // Set values from settings
+  mutableColorMap().loadMap(mCurrentColorMap);
+
+  GraphOptions::ScaleType type = (GraphOptions::ScaleType)settings.value("ScaleType", GraphOptions::Log10).toUInt();
+
+  mutableColorMap().changeScaleType(type);
+
+  settings.endGroup();
+}
+/**
+ * This method saves the selectcolrmap file name to membervaraible
  */
 void Spectrogram::setColorMapFileName(QString colormapName)
 {
@@ -609,11 +609,11 @@ double Spectrogram::getMinPositiveValue()const
   return d ? d->getMinPositiveValue() : 1e-10;
 }
 
-void Spectrogram::setContourPenList(QList<QPen> lst)
-{
-  d_pen_list = lst;
-  setDefaultContourPen(Qt::NoPen);
-  d_color_map_pen = false;
+void Spectrogram::setContourPenList(QList<QPen> lst)
+{
+  d_pen_list = lst;
+  setDefaultContourPen(Qt::NoPen);
+  d_color_map_pen = false;
 }
 
 double MatrixData::value(double x, double y) const
@@ -630,185 +630,185 @@ double MatrixData::value(double x, double y) const
     return 0.0;
 }
 
-double MatrixData::getMinPositiveValue()const
-{
-  double zmin = DBL_MAX;
-  for(int i=0;i<n_rows;++i)
-  {
-    for(int j=0;i<n_cols;++j)
-    {
-      double tmp = d_m[i][j];
-      if (tmp > 0 && tmp < zmin)
-      {
-        zmin = tmp;
-      }
-    }
-  }
-  return zmin;
-}
-
-void Spectrogram::setLabelsRotation(double angle)
-{
-  if (angle == d_labels_angle)
-    return;
-
-  d_labels_angle = angle;
-
-  foreach(PlotMarker *m, d_labels_list)
-  m->setAngle(angle);
-}
-
-void Spectrogram::setLabelsOffset(double x, double y)
-{
-  if (x == d_labels_x_offset && y == d_labels_y_offset)
-    return;
-
-  d_labels_x_offset = x;
-  d_labels_y_offset = y;
-}
-
-void Spectrogram::setLabelOffset(int index, double x, double y)
-{
-  if (index < 0 || index >= d_labels_list.size())
-    return;
-
-  PlotMarker *m = d_labels_list[index];
-  if (!m)
-    return;
-
-  m->setLabelOffset(x, y);
-}
-
-void Spectrogram::setLabelsWhiteOut(bool whiteOut)
-{
-  if (whiteOut == d_white_out_labels)
-    return;
-
-  d_white_out_labels = whiteOut;
-
-  foreach(QwtPlotMarker *m, d_labels_list){
-    QwtText t = m->label();
-    if (whiteOut)
-      t.setBackgroundBrush(QBrush(Qt::white));
-    else
-      t.setBackgroundBrush(QBrush(Qt::transparent));
-    m->setLabel(t);
-  }
-}
-void Spectrogram::drawContourLines (QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QwtRasterData::ContourLines &contourLines) const
-{
-
-  //QwtPlotSpectrogram::drawContourLines(p, xMap, yMap, contourLines);
-  QwtValueList levels = contourLevels();
-  const int numLevels = (int)levels.size();
-  for (int l = 0; l < numLevels; l++){
-    const double level = levels[l];
-
-    QPen pen = defaultContourPen();
-    if ( pen.style() == Qt::NoPen )
-      pen = contourPen(level);
-
-    if ( pen.style() == Qt::NoPen )
-      continue;
-
-    p->setPen(pen);
-
-    const QPolygonF &lines = contourLines[level];
-    for ( int i = 0; i < (int)lines.size(); i += 2 ){
-      const QPointF p1( xMap.xTransform(lines[i].x()),
-          yMap.transform(lines[i].y()) );
-      const QPointF p2( xMap.xTransform(lines[i + 1].x()),
-          yMap.transform(lines[i + 1].y()) );
-
-      p->drawLine(p1, p2);
-    }
-  }
-
-  if (d_show_labels)
-    updateLabels(p, xMap, yMap, contourLines);
-}
-
-void Spectrogram::updateLabels(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
-    const QwtRasterData::ContourLines &contourLines) const
+double MatrixData::getMinPositiveValue()const
+{
+  double zmin = DBL_MAX;
+  for(int i=0;i<n_rows;++i)
+  {
+    for(int j=0;i<n_cols;++j)
+    {
+      double tmp = d_m[i][j];
+      if (tmp > 0 && tmp < zmin)
+      {
+        zmin = tmp;
+      }
+    }
+  }
+  return zmin;
+}
+
+void Spectrogram::setLabelsRotation(double angle)
+{
+  if (angle == d_labels_angle)
+    return;
+
+  d_labels_angle = angle;
+
+  foreach(PlotMarker *m, d_labels_list)
+  m->setAngle(angle);
+}
+
+void Spectrogram::setLabelsOffset(double x, double y)
+{
+  if (x == d_labels_x_offset && y == d_labels_y_offset)
+    return;
+
+  d_labels_x_offset = x;
+  d_labels_y_offset = y;
+}
+
+void Spectrogram::setLabelOffset(int index, double x, double y)
+{
+  if (index < 0 || index >= d_labels_list.size())
+    return;
+
+  PlotMarker *m = d_labels_list[index];
+  if (!m)
+    return;
+
+  m->setLabelOffset(x, y);
+}
+
+void Spectrogram::setLabelsWhiteOut(bool whiteOut)
+{
+  if (whiteOut == d_white_out_labels)
+    return;
+
+  d_white_out_labels = whiteOut;
+
+  foreach(QwtPlotMarker *m, d_labels_list){
+    QwtText t = m->label();
+    if (whiteOut)
+      t.setBackgroundBrush(QBrush(Qt::white));
+    else
+      t.setBackgroundBrush(QBrush(Qt::transparent));
+    m->setLabel(t);
+  }
+}
+void Spectrogram::drawContourLines (QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QwtRasterData::ContourLines &contourLines) const
+{
+
+  //QwtPlotSpectrogram::drawContourLines(p, xMap, yMap, contourLines);
+  QwtValueList levels = contourLevels();
+  const int numLevels = (int)levels.size();
+  for (int l = 0; l < numLevels; l++){
+    const double level = levels[l];
+
+    QPen pen = defaultContourPen();
+    if ( pen.style() == Qt::NoPen )
+      pen = contourPen(level);
+
+    if ( pen.style() == Qt::NoPen )
+      continue;
+
+    p->setPen(pen);
+
+    const QPolygonF &lines = contourLines[level];
+    for ( int i = 0; i < (int)lines.size(); i += 2 ){
+      const QPointF p1( xMap.xTransform(lines[i].x()),
+          yMap.transform(lines[i].y()) );
+      const QPointF p2( xMap.xTransform(lines[i + 1].x()),
+          yMap.transform(lines[i + 1].y()) );
+
+      p->drawLine(p1, p2);
+    }
+  }
+
+  if (d_show_labels)
+    updateLabels(p, xMap, yMap, contourLines);
+}
+
+void Spectrogram::updateLabels(QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap,
+    const QwtRasterData::ContourLines &contourLines) const
 {
   (void) p; //Avoid compiler warning
   (void) xMap; //Avoid compiler warning
   (void) yMap; //Avoid compiler warning
-
-  QwtPlot *d_plot = plot();
-  if (!d_plot)
-    return;
-
-  QwtValueList levels = contourLevels();
-  const int numLevels = levels.size();
-  int x_axis = xAxis();
-  int y_axis = yAxis();
-  for (int l = 0; l < numLevels; l++){
-    const double level = levels[l];
-    const QPolygonF &lines = contourLines[level];
-    int i = (int)lines.size()/2;
-
-    PlotMarker *mrk = d_labels_list[l];
-    if (!mrk)
-      return;
-    QSize size = mrk->label().textSize();
-    int dx =int((d_labels_x_offset )*0.01*size.height()); //int((d_labels_x_offset + mrk->xLabelOffset())*0.01*size.height());
-    int dy = -int(((d_labels_y_offset )*0.01 + 0.5)*size.height());
-
-    double x = lines[i].x();
-    double y = lines[i].y();
-    int x2 = d_plot->transform(x_axis, x) + dx;
-    int y2 = d_plot->transform(y_axis, y) + dy;
-
-    mrk->setValue(d_plot->invTransform(x_axis, x2),
-        d_plot->invTransform(y_axis, y2));
-  }
-
-}
-/**
-     for setting the lables color on contour lines
- */
-void Spectrogram::setLabelsColor(const QColor& c)
-{
-  if (c == d_labels_color)
-    return;
-
-  d_labels_color = c;
-
-  foreach(QwtPlotMarker *m, d_labels_list){
-    QwtText t = m->label();
-    t.setColor(c);
-    m->setLabel(t);
-  }
-}
-/**
-changes the intensity of the colors
- */
-void Spectrogram::changeIntensity( double start,double end)
-{
-  setData(FunctionData(d_funct,m_nRows,m_nColumns,boundingRect(),start,end));
-}
-/**
- sets the flag for intensity changes
- */
-void Spectrogram::setIntensityChange(bool on)
-{
-  m_bIntensityChanged=on;
-}
-/**
-returns true if intensity(minz and maxz) changed
- */
-bool Spectrogram::isIntensityChanged()
-{ return m_bIntensityChanged;
-}
-
-#include "Mantid/MantidMatrix.h"
-
-/**
- * Override QwtPlotSpectrogram::renderImage to draw ragged spectrograms. It is almost
- * a copy of QwtPlotSpectrogram::renderImage except that pixels of the image that are 
- * outside the boundaries of the histograms are set to a special colour (white).
- */
+
+  QwtPlot *d_plot = plot();
+  if (!d_plot)
+    return;
+
+  QwtValueList levels = contourLevels();
+  const int numLevels = levels.size();
+  int x_axis = xAxis();
+  int y_axis = yAxis();
+  for (int l = 0; l < numLevels; l++){
+    const double level = levels[l];
+    const QPolygonF &lines = contourLines[level];
+    int i = (int)lines.size()/2;
+
+    PlotMarker *mrk = d_labels_list[l];
+    if (!mrk)
+      return;
+    QSize size = mrk->label().textSize();
+    int dx =int((d_labels_x_offset )*0.01*size.height()); //int((d_labels_x_offset + mrk->xLabelOffset())*0.01*size.height());
+    int dy = -int(((d_labels_y_offset )*0.01 + 0.5)*size.height());
+
+    double x = lines[i].x();
+    double y = lines[i].y();
+    int x2 = d_plot->transform(x_axis, x) + dx;
+    int y2 = d_plot->transform(y_axis, y) + dy;
+
+    mrk->setValue(d_plot->invTransform(x_axis, x2),
+        d_plot->invTransform(y_axis, y2));
+  }
+
+}
+/**
+     for setting the lables color on contour lines
+ */
+void Spectrogram::setLabelsColor(const QColor& c)
+{
+  if (c == d_labels_color)
+    return;
+
+  d_labels_color = c;
+
+  foreach(QwtPlotMarker *m, d_labels_list){
+    QwtText t = m->label();
+    t.setColor(c);
+    m->setLabel(t);
+  }
+}
+/**
+changes the intensity of the colors
+ */
+void Spectrogram::changeIntensity( double start,double end)
+{
+  setData(FunctionData(d_funct,m_nRows,m_nColumns,boundingRect(),start,end));
+}
+/**
+ sets the flag for intensity changes
+ */
+void Spectrogram::setIntensityChange(bool on)
+{
+  m_bIntensityChanged=on;
+}
+/**
+returns true if intensity(minz and maxz) changed
+ */
+bool Spectrogram::isIntensityChanged()
+{ return m_bIntensityChanged;
+}
+
+#include "Mantid/MantidMatrix.h"
+
+/**
+ * Override QwtPlotSpectrogram::renderImage to draw ragged spectrograms. It is almost
+ * a copy of QwtPlotSpectrogram::renderImage except that pixels of the image that are 
+ * outside the boundaries of the histograms are set to a special colour (white).
+ */
 QImage Spectrogram::renderImage(
     const QwtScaleMap &xMap, const QwtScaleMap &yMap, 
     const QwtDoubleRect &area) const
diff --git a/Code/Mantid/MantidPlot/src/Spectrogram.h b/Code/Mantid/MantidPlot/src/Spectrogram.h
index 454f64e2dc0de0bd7e2b819a2765b54ea22ffe76..1e96053591ffebf07146c46d3894e5dd577ffbd3 100644
--- a/Code/Mantid/MantidPlot/src/Spectrogram.h
+++ b/Code/Mantid/MantidPlot/src/Spectrogram.h
@@ -50,13 +50,13 @@
 
 class MatrixData;
 class PlotMarker;
-namespace Mantid
-{
-namespace API
-{
-class IInstrument;
-class MatrixWorkspace;
-}
+namespace Mantid
+{
+namespace API
+{
+class IInstrument;
+class MatrixWorkspace;
+}
 }
 class Spectrogram: public QwtPlotSpectrogram
 {
@@ -106,48 +106,48 @@ public:
   double getMinPositiveValue()const;
   void setContourPenList(QList<QPen> lst);
   QList<QPen> contourPenList(){return d_pen_list;};
-  //! Flag telling if we use the color map to calculate the pen (QwtPlotSpectrogram::contourPen()).
+  //! Flag telling if we use the color map to calculate the pen (QwtPlotSpectrogram::contourPen()).
   bool d_color_map_pen;
   bool useColorMapPen(){return d_color_map_pen;};
   void setColorMapPen(bool on = true);
   void showContourLineLabels(bool show = true);
   bool hasLabels(){return d_show_labels;};
   QList <PlotMarker *> labelsList(){return d_labels_list;};
-  const MantidColorMap & getColorMap() const;
+  const MantidColorMap & getColorMap() const;
   MantidColorMap & mutableColorMap();
   void saveSettings();
   void loadSettings();
   void setColorMapFileName(QString colormapName);
   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);
-  //	void setLabelOffset(int index, double x, double y);
-
-  void updateForNewMaxData(const double new_max);
-  void updateForNewMinData(const double new_min);
-  void recount();
-  void setCustomColorMap(const QwtColorMap &map);
-
-  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;};
-  void selectLabel(bool on);
-  /// change intensity of the colors
-  void changeIntensity( double start,double end);
-  ///sets a boolan flag for intensity changes
-  void setIntensityChange(bool on);
-  /// returns boolan flag intensity change
-  bool isIntensityChanged();
+  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);
+  //	void setLabelOffset(int index, double x, double y);
+
+  void updateForNewMaxData(const double new_max);
+  void updateForNewMinData(const double new_min);
+  void recount();
+  void setCustomColorMap(const QwtColorMap &map);
+
+  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;};
+  void selectLabel(bool on);
+  /// change intensity of the colors
+  void changeIntensity( double start,double end);
+  ///sets a boolan flag for intensity changes
+  void setIntensityChange(bool on);
+  /// returns boolan flag intensity change
+  bool isIntensityChanged();
 
 protected:
-  virtual void drawContourLines (QPainter *p, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QwtRasterData::ContourLines &lines) const;
+  virtual void drawContourLines (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();
 
@@ -164,32 +164,32 @@ protected:
   QwtLinearColorMap color_map;
 
   QList<QPen> d_pen_list;
-  //! Flag telling if we display the labels
+  //! Flag telling if we display the labels
   bool d_show_labels;
-  //! Flag telling if we paint a white background for the labels
-  bool d_white_out_labels;
+  //! Flag telling if we paint a white background for the labels
+  bool d_white_out_labels;
   double d_labels_angle;
-  //! List of the text labels associated to this spectrogram.
+  //! 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.
+  //! 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
+  //! Labels color
   QColor d_labels_color;
   double d_labels_x_offset, d_labels_y_offset;
   int d_labels_align;
-  //! Labels font
+  //! Labels font
   QFont d_labels_font;
-  //! Pointer to the parent plot
+  //! Pointer to the parent plot
   //Graph *d_graph;
   MantidColorMap mColorMap;
   QString mCurrentColorMap;
 
   int m_nRows;
   int m_nColumns;
-  /// Store a value between 0->255 for each of the integrated spectra.
+  /// Store a value between 0->255 for each of the integrated spectra.
   std::vector<unsigned char> mScaledValues;
   boost::shared_ptr<Mantid::API::MatrixWorkspace> mWorkspaceSptr;
   /// boolean flag to indicate intensity changed
@@ -228,7 +228,7 @@ public:
     x_start = d_matrix->xStart();
     dx = d_matrix->dx();
     y_start = d_matrix->yStart();
-    dy = d_matrix->dy();
+    dy = d_matrix->dy();
   }
 
   ~MatrixData()
diff --git a/Code/Mantid/MantidPlot/src/SurfaceDialog.cpp b/Code/Mantid/MantidPlot/src/SurfaceDialog.cpp
index f294d979485eb07296bbf1b65caeb845b66a4e31..c0c4ffbe2cc2e0482397481fcfcfe75f77dea33d 100644
--- a/Code/Mantid/MantidPlot/src/SurfaceDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/SurfaceDialog.cpp
@@ -41,9 +41,9 @@
 #include <QComboBox>
 #include <QCheckBox>
 #include <QSpinBox>
-#include <QStackedWidget>
+#include <QStackedWidget>
 #include <QCompleter>
-#include <QApplication>
+#include <QApplication>
 
 SurfaceDialog::SurfaceDialog( QWidget* parent, Qt::WFlags fl )
     : QDialog( parent, fl )
@@ -83,10 +83,10 @@ SurfaceDialog::SurfaceDialog( QWidget* parent, Qt::WFlags fl )
 
 	ApplicationWindow *app = (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));
+		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;
@@ -263,15 +263,15 @@ void SurfaceDialog::initParametricSurfacePage()
 }
 
 void SurfaceDialog::clearList()
-{
-    ApplicationWindow *app = (ApplicationWindow *)this->parent();
-
-    if (app && boxType->currentIndex()){
-        app->d_param_surface_func.clear();
+{
+    ApplicationWindow *app = (ApplicationWindow *)this->parent();
+
+    if (app && boxType->currentIndex()){
+        app->d_param_surface_func.clear();
     }else{
         boxFunction->clear();
         if (app)
-            app->clearSurfaceFunctionsList();
+            app->clearSurfaceFunctionsList();
     }
 }
 
@@ -313,8 +313,8 @@ void SurfaceDialog::acceptParametricSurface()
 	double u = 1.0, v = 1.0;
 	parser.DefineVar("u", &u);
 	parser.DefineVar("v", &v);
-
-    int list_size = 15;
+
+    int list_size = 15;
     QString x_formula = boxX->text();
 	try {
 		parser.SetExpr(x_formula.ascii());
@@ -324,12 +324,12 @@ void SurfaceDialog::acceptParametricSurface()
 		boxX->setFocus();
 		return;
 	}
-
-    app->d_param_surface_func.remove(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();
-
+
+    app->d_param_surface_func.remove(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.ascii());
@@ -338,13 +338,13 @@ void SurfaceDialog::acceptParametricSurface()
 		QMessageBox::critical(app, tr("MantidPlot - Y Formula Error"), QString::fromStdString(e.GetMsg()));
 		boxY->setFocus();
 		return;
-	}
-
-    app->d_param_surface_func.remove(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.remove(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.ascii());
@@ -354,11 +354,11 @@ void SurfaceDialog::acceptParametricSurface()
 		boxZ->setFocus();
 		return;
 	}
-
-    app->d_param_surface_func.remove(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();
+
+    app->d_param_surface_func.remove(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().lower();
 	QString uto = boxUTo->text().lower();
@@ -404,7 +404,7 @@ void SurfaceDialog::acceptParametricSurface()
 		boxVTo->setFocus();
 		return;
 	}
-
+
     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
 	if (!d_graph)
 		app->plotParametricSurface(x_formula, y_formula, z_formula,
@@ -414,7 +414,7 @@ void SurfaceDialog::acceptParametricSurface()
 		d_graph->addParametricSurface(x_formula, y_formula, z_formula,
 							   ul, ur, vl, vr, boxColumns->value(), boxRows->value(),
 							   boxUPeriodic->isChecked(), boxVPeriodic->isChecked());
-    QApplication::restoreOverrideCursor();
+    QApplication::restoreOverrideCursor();
 	close();
 }
 
@@ -534,7 +534,7 @@ catch(mu::ParserError &e)
 	error=true;
 	}
 
-if (!error){
+if (!error){
     QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
 	if (!d_graph){
 		app->plotSurface(boxFunction->currentText(),fromX, toX, fromY, toY, fromZ, toZ,
@@ -543,7 +543,7 @@ if (!error){
 		d_graph->addFunction(boxFunction->currentText(),fromX, toX, fromY, toY, fromZ, toZ,
 					 boxFuncColumns->value(), boxFuncRows->value());
 
-	app->updateSurfaceFuncList(boxFunction->currentText());
+	app->updateSurfaceFuncList(boxFunction->currentText());
     QApplication::restoreOverrideCursor();
 	close();
 	}
@@ -557,7 +557,7 @@ void SurfaceDialog::setParametricSurface(Graph3D *g)
 	d_graph = g;
 	UserParametricSurface *s = d_graph->parametricSurface();
 
-	boxType->setCurrentIndex(1);
+	boxType->setCurrentIndex(1);
 	optionStack->setCurrentIndex(1);
 
 	boxX->setText(s->xFormula());
diff --git a/Code/Mantid/MantidPlot/src/SymbolDialog.cpp b/Code/Mantid/MantidPlot/src/SymbolDialog.cpp
index 195f26ee666bb04cba657dba387b6b26f3b428e5..28fcf9522c7b76ca04e217a660baecb44a0f4303 100644
--- a/Code/Mantid/MantidPlot/src/SymbolDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/SymbolDialog.cpp
@@ -36,7 +36,7 @@
 
 SymbolDialog::SymbolDialog(CharSet charSet, QWidget* parent, Qt::WFlags fl )
 : QDialog( parent, fl )
-{
+{
     setAttribute(Qt::WA_DeleteOnClose);
 	setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
 	setSizeGripEnabled( false );
@@ -58,7 +58,7 @@ 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 );
 
diff --git a/Code/Mantid/MantidPlot/src/Table.cpp b/Code/Mantid/MantidPlot/src/Table.cpp
index 77eb4cdbe698fadd7c0070d034491194024b6e13..bcaf2c08a59576ac7685d38dd22ae0a1e4f9ccaa 100644
--- a/Code/Mantid/MantidPlot/src/Table.cpp
+++ b/Code/Mantid/MantidPlot/src/Table.cpp
@@ -32,7 +32,7 @@
 #include "Table.h"
 #include "SortDialog.h"
 #include "ImportASCIIDialog.h"
-#include "muParserScript.h"
+#include "muParserScript.h"
 #include "ApplicationWindow.h"
 
 #include <QMessageBox>
@@ -80,8 +80,8 @@ void Table::init(int rows, int cols)
   d_table->setCurrentCell(-1, -1);
 
   connect(d_table->verticalHeader(), SIGNAL(indexChange(int, int, int)),
-      this, SLOT(notifyChanges()));
-  connect(d_table->horizontalHeader(), SIGNAL(indexChange(int, int, int)),
+      this, SLOT(notifyChanges()));
+  connect(d_table->horizontalHeader(), SIGNAL(indexChange(int, int, int)),
       this, SLOT(moveColumn(int, int, int)));
 
   setFocusPolicy(Qt::StrongFocus);
@@ -93,7 +93,7 @@ void Table::init(int rows, int cols)
     col_format << "0/16";
     comments << "";
     col_label << QString::number(i+1);
-    col_plot_type << Y;
+    col_plot_type << Y;
   }
 
   Q3Header* head=(Q3Header*)d_table->horizontalHeader();
@@ -124,7 +124,7 @@ void Table::init(int rows, int cols)
 
   connect(d_table, SIGNAL(valueChanged(int, int)), this, SLOT(cellEdited(int, int)));
 
-  setAutoUpdateValues(applicationWindow()->autoUpdateTableValues());
+  setAutoUpdateValues(applicationWindow()->autoUpdateTableValues());
 }
 
 void Table::setAutoUpdateValues(bool on)
@@ -284,11 +284,11 @@ void Table::print(const QString& fileName)
 }
 
 void Table::cellEdited(int row, int col)
-{
+{
   QString text = d_table->text(row,col).remove(QRegExp("\\s"));
   if (columnType(col) != Numeric || text.isEmpty()){
     emit modifiedData(this, colName(col));
-    emit modifiedWindow(this);
+    emit modifiedWindow(this);
     return;
   }
 
@@ -353,40 +353,40 @@ int Table::colY(int col)
 
 void Table::setPlotDesignation(PlotDesignation pd, bool rightColumns)
 {
-  if (rightColumns){
-    int cols = d_table->numCols();
-    for (int i = selectedCol; i<cols; i++){
-      col_plot_type[i] = pd;
-      if (pd == Label)
-        colTypes[i] = Text;
-      else if (pd != None)
-        colTypes[i] = Numeric;
-    }
-  } else {
+  if (rightColumns){
+    int cols = d_table->numCols();
+    for (int i = selectedCol; i<cols; i++){
+      col_plot_type[i] = pd;
+      if (pd == Label)
+        colTypes[i] = Text;
+      else if (pd != None)
+        colTypes[i] = Numeric;
+    }
+  } else {
     QStringList list = selectedColumns();
-    for (int i=0; i<(int) list.count(); i++){
+    for (int i=0; i<(int) list.count(); i++){
       int col = colIndex(list[i]);
-      col_plot_type[col] = pd;
-      if (pd == Label)
-        colTypes[col] = Text;
-      else if (pd != None)
-        colTypes[col] = Numeric;
-    }
+      col_plot_type[col] = pd;
+      if (pd == Label)
+        colTypes[col] = Text;
+      else if (pd != None)
+        colTypes[col] = Numeric;
+    }
   }
 
   setHeaderColType();
   emit modifiedWindow(this);
 }
-
-void Table::setColPlotDesignation(int col, PlotDesignation pd)
-{
-  if (col < 0 || col >= d_table->numCols() || col_plot_type[col] == pd)
-    return;
-
-  col_plot_type[col] = pd;
-  if (pd == Label)
-    colTypes[col] = Text;
-}
+
+void Table::setColPlotDesignation(int col, PlotDesignation pd)
+{
+  if (col < 0 || col >= d_table->numCols() || col_plot_type[col] == pd)
+    return;
+
+  col_plot_type[col] = pd;
+  if (pd == Label)
+    colTypes[col] = Text;
+}
 
 void Table::columnNumericFormat(int col, int *f, int *precision)
 {
@@ -512,83 +512,83 @@ bool Table::calculate()
     if (!calculate(col, sel.topRow(), sel.bottomRow()))
       success = false;
   return success;
-}
-
-bool Table::muParserCalculate(int col, int startRow, int endRow, bool notifyChanges)
-{
-  if (startRow < 0)
-    startRow = 0;
-  if (endRow >= numRows())
-    resizeRows(endRow + 1);
-
-  QString cmd = commands[col];
-  if (cmd.isEmpty() || colTypes[col] != Numeric){
-    for (int i = startRow; i <= endRow; i++)
-      d_table->setText(i, col, cmd);
-    if (notifyChanges)
-      emit modifiedData(this, colName(col));
-    emit modifiedWindow(this);
-    return true;
-  }
-
-  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
-  muParserScript *mup = new muParserScript(scriptingEnv(), cmd, this,  QString("<%1>").arg(colName(col)));
-  connect(mup, SIGNAL(error(const QString&,const QString&,int)), scriptingEnv(), SIGNAL(error(const QString&,const QString&,int)));
-  connect(mup, SIGNAL(print(const QString&)), scriptingEnv(), SIGNAL(print(const QString&)));
-
-  double *r = mup->defineVariable("i");
-  mup->defineVariable("j", (double)col);
-  mup->defineVariable("sr", startRow + 1.0);
-  mup->defineVariable("er", endRow + 1.0);
-
-  if (!mup->compile()){
-    QApplication::restoreOverrideCursor();
-    return false;
-  }
-
-  QLocale loc = locale();
-  int prec;
-  char f;
-  columnNumericFormat(col, &f, &prec);
-
-  if (mup->codeLines() == 1){
-    for (int i = startRow; i <= endRow; i++){
-      *r = i + 1.0;
-      d_table->setText(i, col, mup->evalSingleLineToString(loc, f, prec));
-    }
-  } else {
-    QVariant ret;
-    for (int i = startRow; i <= endRow; i++){
-      *r = i + 1.0;
-      ret = mup->eval();
-      if(ret.type() == QVariant::Double) {
-        d_table->setText(i, col, loc.toString(ret.toDouble(), f, prec));
-      } else if(ret.canConvert(QVariant::String))
-        d_table->setText(i, col, ret.toString());
-      else {
-        QApplication::restoreOverrideCursor();
-        return false;
-      }
-    }
-  }
-  if (notifyChanges)
-    emit modifiedData(this, colName(col));
-  emit modifiedWindow(this);
-  QApplication::restoreOverrideCursor();
-  return true;
-}
-
+}
+
+bool Table::muParserCalculate(int col, int startRow, int endRow, bool notifyChanges)
+{
+  if (startRow < 0)
+    startRow = 0;
+  if (endRow >= numRows())
+    resizeRows(endRow + 1);
+
+  QString cmd = commands[col];
+  if (cmd.isEmpty() || colTypes[col] != Numeric){
+    for (int i = startRow; i <= endRow; i++)
+      d_table->setText(i, col, cmd);
+    if (notifyChanges)
+      emit modifiedData(this, colName(col));
+    emit modifiedWindow(this);
+    return true;
+  }
+
+  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+  muParserScript *mup = new muParserScript(scriptingEnv(), cmd, this,  QString("<%1>").arg(colName(col)));
+  connect(mup, SIGNAL(error(const QString&,const QString&,int)), scriptingEnv(), SIGNAL(error(const QString&,const QString&,int)));
+  connect(mup, SIGNAL(print(const QString&)), scriptingEnv(), SIGNAL(print(const QString&)));
+
+  double *r = mup->defineVariable("i");
+  mup->defineVariable("j", (double)col);
+  mup->defineVariable("sr", startRow + 1.0);
+  mup->defineVariable("er", endRow + 1.0);
+
+  if (!mup->compile()){
+    QApplication::restoreOverrideCursor();
+    return false;
+  }
+
+  QLocale loc = locale();
+  int prec;
+  char f;
+  columnNumericFormat(col, &f, &prec);
+
+  if (mup->codeLines() == 1){
+    for (int i = startRow; i <= endRow; i++){
+      *r = i + 1.0;
+      d_table->setText(i, col, mup->evalSingleLineToString(loc, f, prec));
+    }
+  } else {
+    QVariant ret;
+    for (int i = startRow; i <= endRow; i++){
+      *r = i + 1.0;
+      ret = mup->eval();
+      if(ret.type() == QVariant::Double) {
+        d_table->setText(i, col, loc.toString(ret.toDouble(), f, prec));
+      } else if(ret.canConvert(QVariant::String))
+        d_table->setText(i, col, ret.toString());
+      else {
+        QApplication::restoreOverrideCursor();
+        return false;
+      }
+    }
+  }
+  if (notifyChanges)
+    emit modifiedData(this, colName(col));
+  emit modifiedWindow(this);
+  QApplication::restoreOverrideCursor();
+  return true;
+}
+
 bool Table::calculate(int col, int startRow, int endRow, bool forceMuParser, bool notifyChanges)
 {
   if (col < 0 || col >= d_table->numCols())
     return false;
-
-  if (d_table->isColumnReadOnly(col)){
-    QMessageBox::warning(this, tr("MantidPlot - Error"),
-        tr("Column '%1' is read only!").arg(col_label[col]));
-    return false;
-  }
+
+  if (d_table->isColumnReadOnly(col)){
+    QMessageBox::warning(this, tr("MantidPlot - Error"),
+        tr("Column '%1' is read only!").arg(col_label[col]));
+    return false;
+  }
 
   if (QString(scriptingEnv()->name()) == "muParser" || forceMuParser)
     return muParserCalculate(col, startRow, endRow, notifyChanges);
@@ -601,9 +601,9 @@ bool Table::calculate(int col, int startRow, int endRow, bool forceMuParser, boo
   QString cmd = commands[col];
   if (cmd.isEmpty() || colTypes[col] != Numeric){
     for (int i=startRow; i<=endRow; i++)
-      d_table->setText(i, col, cmd);
-    if (notifyChanges)
-      emit modifiedData(this, colName(col));
+      d_table->setText(i, col, cmd);
+    if (notifyChanges)
+      emit modifiedData(this, colName(col));
     emit modifiedWindow(this);
     return true;
   }
@@ -618,11 +618,11 @@ bool Table::calculate(int col, int startRow, int endRow, bool forceMuParser, boo
     QApplication::restoreOverrideCursor();
     return false;
   }
-
-  QLocale loc = locale();
-  int prec;
-  char f;
-  columnNumericFormat(col, &f, &prec);
+
+  QLocale loc = locale();
+  int prec;
+  char f;
+  columnNumericFormat(col, &f, &prec);
 
   colscript->setDouble(col + 1.0, "j");
   colscript->setDouble(startRow + 1.0, "sr");
@@ -639,32 +639,32 @@ bool Table::calculate(int col, int startRow, int endRow, bool forceMuParser, boo
       QApplication::restoreOverrideCursor();
       return false;
     }
-  }
+  }
   if (notifyChanges)
     emit modifiedData(this, colName(col));
   emit modifiedWindow(this);
   QApplication::restoreOverrideCursor();
   return true;
 }
-
-void Table::updateValues(Table* t, const QString& columnName)
-{
-  if (!t || t != this)
-    return;
-
-  QString colLabel = columnName;
-  colLabel.remove(this->objectName()).remove("_");
-
-  int cols = numCols();
-  int endRow = numRows() - 1;
-  for (int i = 0; i < cols; i++){
-    QString cmd = commands[i];
-    if (cmd.isEmpty() || colTypes[i] != Numeric || !cmd.contains("\"" + colLabel + "\""))
-      continue;
-
-    calculate(i, 0, endRow, false, false);
-  }
-}
+
+void Table::updateValues(Table* t, const QString& columnName)
+{
+  if (!t || t != this)
+    return;
+
+  QString colLabel = columnName;
+  colLabel.remove(this->objectName()).remove("_");
+
+  int cols = numCols();
+  int endRow = numRows() - 1;
+  for (int i = 0; i < cols; i++){
+    QString cmd = commands[i];
+    if (cmd.isEmpty() || colTypes[i] != Numeric || !cmd.contains("\"" + colLabel + "\""))
+      continue;
+
+    calculate(i, 0, endRow, false, false);
+  }
+}
 
 Q3TableSelection Table::getSelection()
 {
@@ -707,15 +707,15 @@ QString Table::saveComments()
 
 QString Table::saveToString(const QString& geometry, bool saveAsTemplate)
 {
-  QString s = "<table>";
-  if (saveAsTemplate){
-    s += "\t" + QString::number(d_table->numRows()) + "\t";
-    s += QString::number(d_table->numCols()) + "\n";
-  } else {
-    s += "\n" + QString(objectName()) + "\t";
-    s += QString::number(d_table->numRows()) + "\t";
-    s += QString::number(d_table->numCols()) + "\t";
-    s += birthDate() + "\n";
+  QString s = "<table>";
+  if (saveAsTemplate){
+    s += "\t" + QString::number(d_table->numRows()) + "\t";
+    s += QString::number(d_table->numCols()) + "\n";
+  } else {
+    s += "\n" + QString(objectName()) + "\t";
+    s += QString::number(d_table->numRows()) + "\t";
+    s += QString::number(d_table->numCols()) + "\t";
+    s += birthDate() + "\n";
   }
   s += geometry;
   s += saveHeader();
@@ -724,18 +724,18 @@ QString Table::saveToString(const QString& geometry, bool saveAsTemplate)
   s += saveColumnTypes();
   s += saveReadOnlyInfo();
   s += saveHiddenColumnsInfo();
-  s += saveComments();
+  s += saveComments();
   if (!saveAsTemplate){
     s += "WindowLabel\t" + windowLabel() + "\t" + QString::number(captionPolicy()) + "\n";
-    s += saveText();
+    s += saveText();
   }
   return s += "</table>\n";
 }
-
-QString Table::saveAsTemplate(const QString& geometryInfo)
-{
-  return saveToString(geometryInfo, true);
-}
+
+QString Table::saveAsTemplate(const QString& geometryInfo)
+{
+  return saveToString(geometryInfo, true);
+}
 
 QString Table::saveHeader()
 {
@@ -829,58 +829,58 @@ void Table::setColumnWidth(int col, int width)
   d_table->setColumnWidth (col, width);
   emit modifiedWindow(this);
 }
-
-QString Table::colName(int col)
-{//returns the table name + horizontal header text
-  if (col<0 || col >= col_label.count())
-    return QString();
-
-  return QString(this->objectName())+"_"+col_label[col];
-}
-
-void Table::setColName(int col, const QString& text, bool enumerateRight)
-{
-  if (text.isEmpty() || col<0 || col >= d_table->numCols())
-    return;
-
-  if (col_label[col] == text && !enumerateRight)
-    return;
-
-  QString caption = objectName();
-  QString oldLabel = col_label[col];
-  int cols = col + 1;
-  if (enumerateRight)
-    cols = (int)d_table->numCols();
-
-  int n = 1;
-  for (int i = col; i<cols; i++){
-    QString newLabel = text;
-    if (enumerateRight)
-      newLabel += QString::number(n);
-
-    if (col_label.contains(newLabel) > 0){
-      QMessageBox::critical(0,tr("MantidPlot - Error"),
-          tr("There is already a column called : <b>"+newLabel+"</b> in table <b>"+caption+"</b>!<p>Please choose another name!"));
-      return;
-    }
-    n++;
-  }
-
-  n = 1;
-  caption += "_";
-  for (int i = col; i<cols; i++){
-    QString newLabel = text;
-    if (enumerateRight)
-      newLabel += QString::number(n);
+
+QString Table::colName(int col)
+{//returns the table name + horizontal header text
+  if (col<0 || col >= col_label.count())
+    return QString();
+
+  return QString(this->objectName())+"_"+col_label[col];
+}
+
+void Table::setColName(int col, const QString& text, bool enumerateRight)
+{
+  if (text.isEmpty() || col<0 || col >= d_table->numCols())
+    return;
+
+  if (col_label[col] == text && !enumerateRight)
+    return;
+
+  QString caption = objectName();
+  QString oldLabel = col_label[col];
+  int cols = col + 1;
+  if (enumerateRight)
+    cols = (int)d_table->numCols();
+
+  int n = 1;
+  for (int i = col; i<cols; i++){
+    QString newLabel = text;
+    if (enumerateRight)
+      newLabel += QString::number(n);
+
+    if (col_label.contains(newLabel) > 0){
+      QMessageBox::critical(0,tr("MantidPlot - Error"),
+          tr("There is already a column called : <b>"+newLabel+"</b> in table <b>"+caption+"</b>!<p>Please choose another name!"));
+      return;
+    }
+    n++;
+  }
+
+  n = 1;
+  caption += "_";
+  for (int i = col; i<cols; i++){
+    QString newLabel = text;
+    if (enumerateRight)
+      newLabel += QString::number(n);
 
     commands.replaceInStrings("\"" + col_label[i] + "\"", "\"" + newLabel + "\"");
-    emit changedColHeader(caption + col_label[i], caption + newLabel);
-    col_label[i] = newLabel;
-    n++;
-  }
-
-  setHeaderColType();
-  emit modifiedWindow(this);
+    emit changedColHeader(caption + col_label[i], caption + newLabel);
+    col_label[i] = newLabel;
+    n++;
+  }
+
+  setHeaderColType();
+  emit modifiedWindow(this);
 }
 
 QStringList Table::selectedColumns()
@@ -1034,7 +1034,7 @@ void Table::insertCols(int start, int count)
     comments.insert(j, QString());
     col_label.insert(j, QString::number(max + i));
     colTypes.insert(j, Numeric);
-    col_plot_type.insert(j, Y);
+    col_plot_type.insert(j, Y);
   }
   setHeaderColType();
   emit modifiedWindow(this);
@@ -1089,7 +1089,7 @@ void Table::addCol(PlotDesignation pd)
   colTypes << Numeric;
   col_format << "0/" + QString::number(d_numeric_precision);
   col_label << QString::number(max+1);
-  col_plot_type << pd;
+  col_plot_type << pd;
 
   setHeaderColType();
   emit modifiedWindow(this);
@@ -1113,7 +1113,7 @@ void Table::addColumns(int c)
     colTypes<<Numeric;
     col_format<<"0/" + QString::number(d_numeric_precision);
     col_label<< QString::number(max+i);
-    col_plot_type << Y;
+    col_plot_type << Y;
   }
 }
 
@@ -1148,11 +1148,11 @@ void Table::clearCell(int row, int col)
 
 void Table::deleteSelectedRows()
 {
-  Q3TableSelection sel = d_table->selection(0);
+  Q3TableSelection sel = d_table->selection(0);
   deleteRows(sel.topRow() + 1, sel.bottomRow() + 1);
 }
-
-void Table::deleteRows(int startRow, int endRow)
+
+void Table::deleteRows(int startRow, int endRow)
 {
   for(int i=0; i<d_table->numCols(); i++){
     if (d_table->isColumnReadOnly(i)){
@@ -1161,25 +1161,25 @@ void Table::deleteRows(int startRow, int endRow)
       return;
     }
   }
-
-  int start = QMIN(startRow, endRow);
-  int end = QMAX(startRow, endRow);
-
-  start--;
-  end--;
-  if (start < 0)
-    start = 0;
-  if (end >= d_table->numRows())
-    end = d_table->numRows() - 1;
-
-  int rows = abs(end - start) + 1;
-  Q3MemArray<int> rowsToDelete(rows);
-  for (int i=0; i<rows; i++)
-    rowsToDelete[i] = start + i;
-
-  d_table->removeRows(rowsToDelete);
-  notifyChanges();
-}
+
+  int start = QMIN(startRow, endRow);
+  int end = QMAX(startRow, endRow);
+
+  start--;
+  end--;
+  if (start < 0)
+    start = 0;
+  if (end >= d_table->numRows())
+    end = d_table->numRows() - 1;
+
+  int rows = abs(end - start) + 1;
+  Q3MemArray<int> rowsToDelete(rows);
+  for (int i=0; i<rows; i++)
+    rowsToDelete[i] = start + i;
+
+  d_table->removeRows(rowsToDelete);
+  notifyChanges();
+}
 
 void Table::cutSelection()
 {
@@ -1484,9 +1484,9 @@ void Table::normalize()
 
 void Table::normalizeCol(int col)
 {
-  if (col<0) col = selectedCol;
-  if (d_table->isColumnReadOnly(col) || colTypes[col] == Table::Text)
-    return;
+  if (col<0) col = selectedCol;
+  if (d_table->isColumnReadOnly(col) || colTypes[col] == Table::Text)
+    return;
 
   int rows = d_table->numRows();
   gsl_vector *data = gsl_vector_alloc(rows);
@@ -1590,9 +1590,9 @@ void Table::sortColumns(const QStringList&s, int type, int order, const QString&
     for(int i=0;i<cols;i++){// Since we have the permutation index, sort all the columns
       int col=colIndex(s[i]);
       if (col >= 0)
-      {
-        if (d_table->isColumnReadOnly(col))
-          continue;
+      {
+        if (d_table->isColumnReadOnly(col))
+          continue;
 
         if (columnType(col) == Text){
           for (int j=0; j<non_empty_cells; j++)
@@ -1628,9 +1628,9 @@ void Table::sortColumn(int col, int order)
 {
   if (col < 0)
     col = d_table->currentColumn();
-
-  if (d_table->isColumnReadOnly(col))
-    return;
+
+  if (d_table->isColumnReadOnly(col))
+    return;
 
   int rows=d_table->numRows();
   int non_empty_cells = 0;
@@ -1734,11 +1734,11 @@ QString Table::saveText()
   for (int i=0; i<rows; i++){
     if (!isEmptyRow(i)){
       text += QString::number(i) + "\t";
-      for (int j=0; j<cols; j++){
+      for (int j=0; j<cols; j++){
         if (colTypes[j] == Numeric && !d_table->text(i, j).isEmpty())
           text += QString::number(cell(i, j), 'e', 14) + "\t";
         else
-          text += d_table->text(i, j) + "\t";
+          text += d_table->text(i, j) + "\t";
       }
       if (colTypes[cols] == Numeric && !d_table->text(i, cols).isEmpty())
         text += QString::number(cell(i, cols), 'e', 14) + "\n";
@@ -1963,7 +1963,7 @@ bool Table::setDateFormat(const QString& format, int col, bool updateCells)
 
         if (d_saved_cells){
           d = QDateTime(QDate::fromJulianDay((int)d_saved_cells[col][i] + 1));
-          double msecs = (d_saved_cells[col][i] - floor(d_saved_cells[col][i]))*864e5;
+          double msecs = (d_saved_cells[col][i] - floor(d_saved_cells[col][i]))*864e5;
           d.setTime(d.time().addMSecs(qRound(msecs)));
           if (d.isValid())
             d_table->setText(i, col, d.toString(format));
@@ -2112,9 +2112,9 @@ void Table::setRandomValues()
   int rows=d_table->numRows();
   for (int j=0; j<(int) list.count(); j++){
     QString name=list[j];
-    selectedCol=colIndex(name);
-    if (d_table->isColumnReadOnly(selectedCol))
-      continue;
+    selectedCol=colIndex(name);
+    if (d_table->isColumnReadOnly(selectedCol))
+      continue;
 
     int prec;
     char f;
@@ -2269,9 +2269,9 @@ void Table::setAscValues()
   for (int j=0; j<(int) list.count(); j++){
     QString name = list[j];
     selectedCol = colIndex(name);
-
-    if (d_table->isColumnReadOnly(selectedCol))
-      continue;
+
+    if (d_table->isColumnReadOnly(selectedCol))
+      continue;
 
     if (columnType(selectedCol) != Numeric){
       colTypes[selectedCol] = Numeric;
@@ -2309,10 +2309,10 @@ bool Table::noYColumn()
       return false;
   }
   return notSet;
-}
+}
 
-void Table::importASCII(const QString &fname, const QString &sep, int ignoredLines, bool renameCols,
-    bool stripSpaces, bool simplifySpaces, bool importComments, const QString& commentString,
+void Table::importASCII(const QString &fname, const QString &sep, int ignoredLines, bool renameCols,
+    bool stripSpaces, bool simplifySpaces, bool importComments, const QString& commentString,
     bool readOnly, ImportMode importAs, int endLine, int maxRows)
 {
   int rows;
@@ -2321,8 +2321,8 @@ void Table::importASCII(const QString &fname, const QString &sep, int ignoredLin
     return;
 
   QFile f(name);
-  if (f.open(QIODevice::ReadOnly)){
-    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+  if (f.open(QIODevice::ReadOnly)){
+    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
 
     QTextStream t(&f);
     QString s = t.readLine();//read first line
@@ -2340,21 +2340,21 @@ void Table::importASCII(const QString &fname, const QString &sep, int ignoredLin
       locale().toDouble(line[i], &allNumbers);
       if (!allNumbers)
         break;
-    }
-    if (renameCols && !allNumbers){
-      rows--;
-      if (importComments)
-        rows--;
-    }
-
-    QStringList oldHeader;
-    int startRow = 0, startCol = 0;
-    int c = d_table->numCols();
+    }
+    if (renameCols && !allNumbers){
+      rows--;
+      if (importComments)
+        rows--;
+    }
+
+    QStringList oldHeader;
+    int startRow = 0, startCol = 0;
+    int c = d_table->numCols();
     int r = d_table->numRows();
     switch(importAs){
     case Overwrite:
       if (d_table->numRows() != rows)
-        d_table->setNumRows(rows);
+        d_table->setNumRows(rows);
 
       oldHeader = col_label;
       if (c != cols){
@@ -2369,29 +2369,29 @@ void Table::importASCII(const QString &fname, const QString &sep, int ignoredLin
             col_format.removeLast();
             col_label.removeLast();
             colTypes.removeLast();
-            col_plot_type.removeLast();
+            col_plot_type.removeLast();
           }
         }
       }
       break;
-    case NewColumns:
-      startCol = c;
-      addColumns(cols);
-      if (r < rows)
-        d_table->setNumRows(rows);
+    case NewColumns:
+      startCol = c;
+      addColumns(cols);
+      if (r < rows)
+        d_table->setNumRows(rows);
       break;
-    case NewRows:
-      startRow = r;
-      if (c < cols)
-        addColumns(cols - c);
-      d_table->setNumRows(r + rows);
+    case NewRows:
+      startRow = r;
+      if (c < cols)
+        addColumns(cols - c);
+      d_table->setNumRows(r + rows);
       break;
     }
 
-    if (renameCols && !allNumbers){//use first line to set the table header
-      for (int i = 0; i<cols; i++){
-        int aux = i + startCol;
-        col_label[aux] = QString::null;
+    if (renameCols && !allNumbers){//use first line to set the table header
+      for (int i = 0; i<cols; i++){
+        int aux = i + startCol;
+        col_label[aux] = QString::null;
         if (!importComments)
           comments[aux] = line[i];
         s = line[i].replace("-","_").remove(QRegExp("\\W")).replace("_","-");
@@ -2402,75 +2402,75 @@ void Table::importASCII(const QString &fname, const QString &sep, int ignoredLin
           s += QString::number(n);
         }
         col_label[aux] = s;
-      }
-
-      if (importComments){//import comments
-        s = t.readLine();//read 2nd line
-        if (simplifySpaces)
-          s = s.simplifyWhiteSpace();
-        else if (stripSpaces)
-          s = s.stripWhiteSpace();
-        line = s.split(sep, QString::SkipEmptyParts);
-        for (int i=0; i<line.size(); i++)
-          comments[startCol + i] = line[i];
-        qApp->processEvents(QEventLoop::ExcludeUserInput);
-      }
-    } else if (rows > 0){//put values in the first line of the table
-      for (int i = 0; i<cols; i++)
-        d_table->setText(startRow, startCol + i, line[i]);
-      startRow++;
-    }
+      }
+
+      if (importComments){//import comments
+        s = t.readLine();//read 2nd line
+        if (simplifySpaces)
+          s = s.simplifyWhiteSpace();
+        else if (stripSpaces)
+          s = s.stripWhiteSpace();
+        line = s.split(sep, QString::SkipEmptyParts);
+        for (int i=0; i<line.size(); i++)
+          comments[startCol + i] = line[i];
+        qApp->processEvents(QEventLoop::ExcludeUserInput);
+      }
+    } else if (rows > 0){//put values in the first line of the table
+      for (int i = 0; i<cols; i++)
+        d_table->setText(startRow, startCol + i, line[i]);
+      startRow++;
+    }
 
     d_table->blockSignals(true);
-    setHeaderColType();
-
-    int steps = rows/100 + 1;
-    QProgressDialog progress((QWidget *)applicationWindow());
-    progress.setWindowTitle(tr("MantidPlot") + " - " + tr("Reading file..."));
-    progress.setLabelText(fname);
-    progress.setActiveWindow();
-    progress.setAutoClose(true);
-    progress.setAutoReset(true);
-    progress.setRange(0, steps);
-
-    QApplication::restoreOverrideCursor();
-
-    int l = 0;
-    int row = startRow;
-    rows = d_table->numRows();
-    while (!t.atEnd() && row < rows){
-      if (progress.wasCanceled()){
-        f.close();
-        return;
-      }
-      s = t.readLine();
-      if (simplifySpaces)
-        s = s.simplifyWhiteSpace();
-      else if (stripSpaces)
-        s = s.stripWhiteSpace();
-      line = s.split(sep);
-      int lc = line.size();
-      if (lc > cols) {
-        addColumns(lc - cols);
-        cols = lc;
-      }
-      for (int j=0; j<cols && j<lc; j++)
-        d_table->setText(row, startCol + j, line[j]);
-
-      l++;
-      row++;
-      if (l%100 == 0)
-        progress.setValue(l/100);
-      qApp->processEvents();
-    }
+    setHeaderColType();
+
+    int steps = rows/100 + 1;
+    QProgressDialog progress((QWidget *)applicationWindow());
+    progress.setWindowTitle(tr("MantidPlot") + " - " + tr("Reading file..."));
+    progress.setLabelText(fname);
+    progress.setActiveWindow();
+    progress.setAutoClose(true);
+    progress.setAutoReset(true);
+    progress.setRange(0, steps);
+
+    QApplication::restoreOverrideCursor();
+
+    int l = 0;
+    int row = startRow;
+    rows = d_table->numRows();
+    while (!t.atEnd() && row < rows){
+      if (progress.wasCanceled()){
+        f.close();
+        return;
+      }
+      s = t.readLine();
+      if (simplifySpaces)
+        s = s.simplifyWhiteSpace();
+      else if (stripSpaces)
+        s = s.stripWhiteSpace();
+      line = s.split(sep);
+      int lc = line.size();
+      if (lc > cols) {
+        addColumns(lc - cols);
+        cols = lc;
+      }
+      for (int j=0; j<cols && j<lc; j++)
+        d_table->setText(row, startCol + j, line[j]);
+
+      l++;
+      row++;
+      if (l%100 == 0)
+        progress.setValue(l/100);
+      qApp->processEvents();
+    }
 
     d_table->blockSignals(false);
     f.remove();
-
-    if (readOnly){
-      for (int i = 0; i<cols; i++)
-        d_table->setColumnReadOnly(startCol + i, true);
-    }
+
+    if (readOnly){
+      for (int i = 0; i<cols; i++)
+        d_table->setColumnReadOnly(startCol + i, true);
+    }
 
     if (importAs == Overwrite || importAs == NewRows){
       if (cols > c)
@@ -2562,19 +2562,19 @@ bool Table::exportASCII(const QString& fname, const QString& separator,
       }
     }
   }// finished writting labels
-
-  if (exportComments){
-    if (exportSelection){
-      for (int i=0; i<aux; i++)
+
+  if (exportComments){
+    if (exportSelection){
+      for (int i=0; i<aux; i++)
         text += comments[sCols[i]] + separator;
-      if (aux >= 0)
-        text += comments[sCols[aux]] + eol;
-    } else {
-      for (int i=0; i<cols-1; i++)
-        text += comments[i] + separator;
-      text += comments[cols-1] + eol;
-    }
-  }
+      if (aux >= 0)
+        text += comments[sCols[aux]] + eol;
+    } else {
+      for (int i=0; i<cols-1; i++)
+        text += comments[i] + separator;
+      text += comments[cols-1] + eol;
+    }
+  }
 
   if (exportSelection){
     for (int i=topRow; i<=bottomRow; i++){
@@ -2664,14 +2664,14 @@ bool Table::eventFilter(QObject *object, QEvent *e)
       d_table->setCurrentCell (row, 0);
       setActiveWindow();
     }
-  } else if (e->type() == QEvent::ContextMenu && object == (QObject*)d_table){
-    const QContextMenuEvent *ce = (const QContextMenuEvent *)e;
-    QRect r = d_table->horizontalHeader()->sectionRect(d_table->numCols()-1);
-    setFocus();
-    if (ce->pos().x() > r.right() + d_table->verticalHeader()->width())
-      emit showContextMenu(false);
-    else if (d_table->numCols() > 0 && d_table->numRows() > 0)
-      emit showContextMenu(true);
+  } else if (e->type() == QEvent::ContextMenu && object == (QObject*)d_table){
+    const QContextMenuEvent *ce = (const QContextMenuEvent *)e;
+    QRect r = d_table->horizontalHeader()->sectionRect(d_table->numCols()-1);
+    setFocus();
+    if (ce->pos().x() > r.right() + d_table->verticalHeader()->width())
+      emit showContextMenu(false);
+    else if (d_table->numCols() > 0 && d_table->numRows() > 0)
+      emit showContextMenu(true);
   }
 
   return MdiSubWindow::eventFilter(object, e);
@@ -3075,14 +3075,14 @@ void Table::goToRow(int row)
   d_table->ensureCellVisible ( row-1, 0 );
   d_table->selectRow(row-1);
 }
-
-void Table::goToColumn(int col)
-{
-  if( (col < 1) || (col > numCols()) ) return;
-
-  d_table->ensureCellVisible (0, col - 1);
-  d_table->selectColumn(col - 1);
-}
+
+void Table::goToColumn(int col)
+{
+  if( (col < 1) || (col > numCols()) ) return;
+
+  d_table->ensureCellVisible (0, col - 1);
+  d_table->selectColumn(col - 1);
+}
 
 void Table::setColumnHeader(int index, const QString& label)
 {
@@ -3155,58 +3155,58 @@ void Table::updateDecimalSeparators()
 
   freeMemory();
 }
-
-bool Table::isReadOnlyColumn(int col)
-{
-  if (col < 0 || col >= d_table->numCols())
-    return false;
-
-  return d_table->isColumnReadOnly(col);
-}
-
-void Table::setReadOnlyColumn(int col, bool on)
-{
-  if (col < 0 || col >= d_table->numCols())
-    return;
-
-  d_table->setColumnReadOnly(col, on);
-}
-
-void Table::moveColumn(int, int fromIndex, int toIndex)
-{
-  int to = toIndex;
-  if (fromIndex < toIndex)
-    to = toIndex - 1;
-
-  col_label.move(fromIndex, to);
-  comments.move(fromIndex, to);
-  commands.move(fromIndex, to);
-  colTypes.move(fromIndex, to);
-  col_format.move(fromIndex, to);
-  col_plot_type.move(fromIndex, to);
-  setHeaderColType();
-}
-
-void Table::swapColumns(int col1, int col2)
-{
-  if (col1 < 0 || col1 >= d_table->numCols() || col2 < 0 || col2 >= d_table->numCols())
-    return;
-
-  int width1 = d_table->columnWidth(col1);
-  int width2 = d_table->columnWidth(col2);
-
-  d_table->swapColumns(col1, col2);
-  col_label.swap (col1, col2);
-  comments.swap (col1, col2);
-  commands.swap (col1, col2);
-  colTypes.swap (col1, col2);
-  col_format.swap (col1, col2);
-  col_plot_type.swap (col1, col2);
-
-  d_table->setColumnWidth(col1, width2);
-  d_table->setColumnWidth(col2, width1);
-  setHeaderColType();
-}
+
+bool Table::isReadOnlyColumn(int col)
+{
+  if (col < 0 || col >= d_table->numCols())
+    return false;
+
+  return d_table->isColumnReadOnly(col);
+}
+
+void Table::setReadOnlyColumn(int col, bool on)
+{
+  if (col < 0 || col >= d_table->numCols())
+    return;
+
+  d_table->setColumnReadOnly(col, on);
+}
+
+void Table::moveColumn(int, int fromIndex, int toIndex)
+{
+  int to = toIndex;
+  if (fromIndex < toIndex)
+    to = toIndex - 1;
+
+  col_label.move(fromIndex, to);
+  comments.move(fromIndex, to);
+  commands.move(fromIndex, to);
+  colTypes.move(fromIndex, to);
+  col_format.move(fromIndex, to);
+  col_plot_type.move(fromIndex, to);
+  setHeaderColType();
+}
+
+void Table::swapColumns(int col1, int col2)
+{
+  if (col1 < 0 || col1 >= d_table->numCols() || col2 < 0 || col2 >= d_table->numCols())
+    return;
+
+  int width1 = d_table->columnWidth(col1);
+  int width2 = d_table->columnWidth(col2);
+
+  d_table->swapColumns(col1, col2);
+  col_label.swap (col1, col2);
+  comments.swap (col1, col2);
+  commands.swap (col1, col2);
+  colTypes.swap (col1, col2);
+  col_format.swap (col1, col2);
+  col_plot_type.swap (col1, col2);
+
+  d_table->setColumnWidth(col1, width2);
+  d_table->setColumnWidth(col2, width1);
+  setHeaderColType();
+}
 
 void Table::moveColumnBy(int cols)
 {
diff --git a/Code/Mantid/MantidPlot/src/Table.h b/Code/Mantid/MantidPlot/src/Table.h
index ba2235fcb92ae64a7577e05df657a5b1fe0c36d1..691573eb1680f1dfc8fdaee0e9c316d2090c9149 100644
--- a/Code/Mantid/MantidPlot/src/Table.h
+++ b/Code/Mantid/MantidPlot/src/Table.h
@@ -100,7 +100,7 @@ public slots:
 	QString text(int row, int col);
 	QStringList columnsList();
 	QStringList colNames(){return col_label;}
-	QString colName(int col);
+	QString colName(int col);
     void setColName(int col, const QString& text, bool enumerateRight = false);
 	QString colLabel(int col){return col_label[col];};
 	int colIndex(const QString& name);
@@ -142,14 +142,14 @@ public slots:
 	void insertCol();
 	void insertCols(int start, int count);
 	void addCol(PlotDesignation pd = Y);
-	void addColumns(int c);
-	void moveColumn(int, int, int);
+	void addColumns(int c);
+	void moveColumn(int, int, int);
 	void swapColumns(int, int);
 	void moveColumnBy(int cols);
 	void hideSelectedColumns();
 	void showAllColumns();
 	void hideColumn(int col, bool = true);
-	bool isColumnHidden(int col){return d_table->isColumnHidden(col);};
+	bool isColumnHidden(int col){return d_table->isColumnHidden(col);};
 	//@}
 
 	//! \name Sorting
@@ -216,13 +216,13 @@ public slots:
 	//! Compute specified cells from column formula (optimized for muParser).
 	bool muParserCalculate(int col, int startRow, int endRow, bool notifyChanges = true);
 	//! Compute selected cells from column formulae; use current cell if there's no selection.
-	bool calculate();
-	//! Recalculates values in all columns with formulas containing @param columnName
+	bool calculate();
+	//! Recalculates values in all columns with formulas containing @param columnName
 	void updateValues(Table*, const QString& columnName);
 
 	//! \name Row Operations
 	//@{
-	void deleteSelectedRows();
+	void deleteSelectedRows();
 	void deleteRows(int startRow, int endRow);
 	void insertRow();
 	void insertRow(int row);//Mantid
@@ -262,8 +262,8 @@ public slots:
 	bool isRowSelected(int row, bool full=false) { return d_table->isRowSelected(row, full); }
 	bool isColumnSelected(int col, bool full=false) { return d_table->isColumnSelected(col, full); }
 	//! Scroll to row (row starts with 1)
-	void goToRow(int row);
-	//! Scroll to column (column starts with 1)
+	void goToRow(int row);
+	//! Scroll to column (column starts with 1)
 	void goToColumn(int col);
 
 	void columnNumericFormat(int col, char *f, int *precision);
@@ -278,8 +278,8 @@ public slots:
     void saveToMemory(double **cells){d_saved_cells = cells;};
 	void saveToMemory();
 	void freeMemory();
-
-    bool isReadOnlyColumn(int col);
+
+    bool isReadOnlyColumn(int col);
     void setReadOnlyColumn(int col, bool on = true);
 
 	QString columnFormat(int col){return col_format[col];};
@@ -293,10 +293,10 @@ public slots:
 	void setMonthFormat(const QString& format, int col, bool updateCells = true);
 	void setDayFormat(const QString& format, int col, bool updateCells = true);
 
-	bool exportASCII(const QString& fname, const QString& separator, bool withLabels = false,
+	bool exportASCII(const QString& fname, const QString& separator, bool withLabels = false,
                      bool exportComments = false, bool exportSelection = false);
-	void importASCII(const QString &fname, const QString &sep, int ignoredLines, bool renameCols,
-                    bool stripSpaces, bool simplifySpaces, bool importComments,
+	void importASCII(const QString &fname, const QString &sep, int ignoredLines, bool renameCols,
+                    bool stripSpaces, bool simplifySpaces, bool importComments,
                     const QString& commentString, bool readOnly = false,
 					ImportMode importAs = Overwrite, int endLine = 0, int maxRows = -1);
 
@@ -371,7 +371,7 @@ private:
 	bool d_show_comments;
 	QString specifications, newSpecifications;
 	QStringList commands, col_format, comments, col_label;
-	QList<int> colTypes, col_plot_type;
+	QList<int> colTypes, col_plot_type;
 	int selectedCol;
 	int d_numeric_precision;
 	double **d_saved_cells;
diff --git a/Code/Mantid/MantidPlot/src/TableDialog.cpp b/Code/Mantid/MantidPlot/src/TableDialog.cpp
index 7f6d9c0001f12c8b4554352ce3c7d941170e3f76..0bbb24856cce643071432879539ca88090435503 100644
--- a/Code/Mantid/MantidPlot/src/TableDialog.cpp
+++ b/Code/Mantid/MantidPlot/src/TableDialog.cpp
@@ -130,12 +130,12 @@ TableDialog::TableDialog(Table *t, QWidget* parent, Qt::WFlags fl )
 	labelNumeric = new QLabel(tr( "Precision:" ));
 	gl1->addWidget(labelNumeric, 3, 0);
 
-    precisionBox = new QSpinBox();
+    precisionBox = new QSpinBox();
     precisionBox->setRange(0, 13);
     gl1->addWidget(precisionBox, 3, 1);
-
-    boxReadOnly = new QCheckBox(tr("&Read-only" ));
-    gl1->addWidget(boxReadOnly, 4, 0);
+
+    boxReadOnly = new QCheckBox(tr("&Read-only" ));
+    gl1->addWidget(boxReadOnly, 4, 0);
 
 	boxHideColumn = new QCheckBox(tr("&Hidden" ));
     gl1->addWidget(boxHideColumn, 4, 1);
@@ -235,26 +235,26 @@ void TableDialog::updateColumn(int sc)
 
     d_table->setSelectedCol(sc);
     d_table->table()->clearSelection();
-    d_table->table()->selectColumn(sc);
+    d_table->table()->selectColumn(sc);
     int pd = d_table->colPlotDesignation(sc);
-    columnsBox->setCurrentIndex(pd);
-    displayBox->setEnabled(pd != Table::Label);
+    columnsBox->setCurrentIndex(pd);
+    displayBox->setEnabled(pd != Table::Label);
 
     QString colLabel = d_table->colLabel(sc);
-    colName->setText(colLabel);
+    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
+	else
 		colWidth->setValue(d_table->columnWidth(sc));
 
     d_table->saveToMemory();
@@ -307,24 +307,24 @@ void TableDialog::apply()
     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->text().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++){
+
+    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 {
+		}
+    } else {
         d_table->setReadOnlyColumn(sc, boxReadOnly->isChecked());
 		d_table->hideColumn(sc, boxHideColumn->isChecked());
-	}
+	}
 
     int format = formatBox->currentIndex();
     int colType = displayBox->currentIndex();
@@ -373,13 +373,13 @@ ce->accept();
 }
 
 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
+{
+    d_table->setPlotDesignation((Table::PlotDesignation)i, applyToRightCols->isChecked());
+    if (i == Table::Label){
+        displayBox->setCurrentIndex(1);
+		updateDisplay(1);
+		displayBox->setEnabled(false);
+    } else
         displayBox->setEnabled(true);
 }
 
@@ -436,24 +436,24 @@ void TableDialog::updateDisplay(int item)
 
 		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("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;
 
@@ -495,7 +495,7 @@ void TableDialog::updateDisplay(int item)
 		}
 		break;
 		}
-	}
+	}
 }
 
 void TableDialog::setDateTimeFormat(int type, const QString& format, bool allRightColumns)
diff --git a/Code/Mantid/MantidPlot/src/TextEditor.cpp b/Code/Mantid/MantidPlot/src/TextEditor.cpp
index 234b8aa274e92b08b276488eb4ae638bf2c792c3..ca1006f84b0a9bcc2136604df91d835b92657287 100644
--- a/Code/Mantid/MantidPlot/src/TextEditor.cpp
+++ b/Code/Mantid/MantidPlot/src/TextEditor.cpp
@@ -40,21 +40,21 @@ TextEditor::TextEditor(Graph *g): QTextEdit(g)
 {
 	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);
+	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());
-		text = ((LegendWidget*)d_target)->text();
-		d_target->hide();
+		text = ((LegendWidget*)d_target)->text();
+		d_target->hide();
 	} else if (g->titleSelected()){
 		d_target = g->plotWidget()->titleLabel();
 		QwtText t = g->plotWidget()->title();
@@ -74,14 +74,14 @@ TextEditor::TextEditor(Graph *g): QTextEdit(g)
 			resize(rect.size());
 			move(QPoint(d_target->x() + rect.x(), d_target->y() + rect.y()));
 		} else {
-			resize(QSize(rect.height(), rect.width()));
+			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));
+                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);
 		}
 	}
@@ -95,14 +95,14 @@ TextEditor::TextEditor(Graph *g): QTextEdit(g)
 }
 
 void TextEditor::closeEvent(QCloseEvent *e)
-{
+{
     Graph *g = (Graph *)parent();
 	QString s = QString();
 	if (d_target->isA("LegendWidget")){
 		s = text();
-		((LegendWidget*)d_target)->setText(s);
+		((LegendWidget*)d_target)->setText(s);
         d_target->show();
-		g->setSelectedText(NULL);
+		g->setSelectedText(NULL);
 	} else if (d_target->isA("PieLabel")){
 		s = text();
 		((PieLabel*)d_target)->setCustomText(s);
@@ -127,24 +127,24 @@ void TextEditor::closeEvent(QCloseEvent *e)
 
 	if (d_initial_text != s)
 		g->notifyChanges();
-
+
     d_target->repaint();
 	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::addSymbol(const QString& letter)
-{
-	textCursor().insertText(letter);
+
+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);
 }
diff --git a/Code/Mantid/MantidPlot/src/TextEditor.h b/Code/Mantid/MantidPlot/src/TextEditor.h
index 629550076e10c854c23e9d0b0f32096fd6ef3c7b..8d6d0b0e8a36f482e4de194c0d4d74d9d9dcdebe 100644
--- a/Code/Mantid/MantidPlot/src/TextEditor.h
+++ b/Code/Mantid/MantidPlot/src/TextEditor.h
@@ -31,8 +31,8 @@
 #define TEXTEDITOR_H
 
 #include <QTextEdit>
-
-class Graph;
+
+class Graph;
 
 class TextEditor: public QTextEdit
 {
@@ -40,15 +40,15 @@ class TextEditor: public QTextEdit
 
 public:
     TextEditor(Graph *g);
-    void formatText(const QString & prefix, const QString & postfix);
-
-public slots:
-    void addSymbol(const QString & letter);
+    void formatText(const QString & prefix, const QString & postfix);
+
+public slots:
+    void addSymbol(const QString & letter);
 
 private:
 	void closeEvent(QCloseEvent *e);
 	QString d_initial_text;
-	QWidget *d_target;
+	QWidget *d_target;
 };
 
 #endif
diff --git a/Code/Mantid/MantidPlot/src/TitlePicker.cpp b/Code/Mantid/MantidPlot/src/TitlePicker.cpp
index 33e6aa7aa6c1348e8db271cc46e69f4ab58ca620..5de95cc2a678890ff271fde990cda487b51609e1 100644
--- a/Code/Mantid/MantidPlot/src/TitlePicker.cpp
+++ b/Code/Mantid/MantidPlot/src/TitlePicker.cpp
@@ -32,11 +32,11 @@
 #include <qwt_text_label.h>
 
 #include <QMouseEvent>
-#include <QPen>
+#include <QPen>
 
 TitlePicker::TitlePicker(QwtPlot *plot):
 	QObject(plot)
-{
+{
     d_selected = false;
 	title = (QwtTextLabel *)plot->titleLabel();
 	title->setFocusPolicy(Qt::StrongFocus);
@@ -56,14 +56,14 @@ bool TitlePicker::eventFilter(QObject *object, QEvent *e)
     }
 
 	 if ( object->inherits("QwtTextLabel") &&  e->type() == QEvent::MouseButtonPress ){
-		 const QMouseEvent *me = (const QMouseEvent *)e;
+		 const QMouseEvent *me = (const QMouseEvent *)e;
 
 		 emit clicked();
 
 		 if (me->button() == Qt::RightButton)
-			emit showTitleMenu();
-         else if (me->button() == Qt::LeftButton)
-		 	setSelected();
+			emit showTitleMenu();
+         else if (me->button() == Qt::LeftButton)
+		 	setSelected();
 
 		 return !(me->modifiers() & Qt::ShiftModifier);
     }
@@ -80,19 +80,19 @@ bool TitlePicker::eventFilter(QObject *object, QEvent *e)
 
     return QObject::eventFilter(object, e);
 }
-
-void TitlePicker::setSelected(bool select)
-{
-    if (!title || d_selected == select)
-        return;
-
-    d_selected = select;
-
-    QwtText text = title->text();
-    if (select)
-        text.setBackgroundPen(QPen(Qt::blue));
-    else
-        text.setBackgroundPen(QPen(Qt::NoPen));
-
-    ((QwtPlot *)parent())->setTitle(text);
+
+void TitlePicker::setSelected(bool select)
+{
+    if (!title || d_selected == select)
+        return;
+
+    d_selected = select;
+
+    QwtText text = title->text();
+    if (select)
+        text.setBackgroundPen(QPen(Qt::blue));
+    else
+        text.setBackgroundPen(QPen(Qt::NoPen));
+
+    ((QwtPlot *)parent())->setTitle(text);
 }
diff --git a/Code/Mantid/MantidPlot/src/TitlePicker.h b/Code/Mantid/MantidPlot/src/TitlePicker.h
index 360b311caa2d89297c4713a1193f72d36a3b665e..a0927e88711573c1c65a289cf8ca5f17f45a7df3 100644
--- a/Code/Mantid/MantidPlot/src/TitlePicker.h
+++ b/Code/Mantid/MantidPlot/src/TitlePicker.h
@@ -36,7 +36,7 @@ class TitlePicker: public QObject
     Q_OBJECT
 
 public:
-    TitlePicker(QwtPlot *plot);
+    TitlePicker(QwtPlot *plot);
     void setSelected(bool select = true);
 	bool selected(){return d_selected;};
 
@@ -48,6 +48,6 @@ signals:
 
 private:
 	bool eventFilter(QObject *, QEvent *);
-	QwtTextLabel *title;
+	QwtTextLabel *title;
 	bool d_selected;
 };
diff --git a/Code/Mantid/MantidPlot/src/UserFunction.h b/Code/Mantid/MantidPlot/src/UserFunction.h
index 7ac30532f5e9db7cb9c355ad3bba2e5e6ed7ee23..f435704b985ec6a0ee5891a4ee971059b8a8ebc6 100644
--- a/Code/Mantid/MantidPlot/src/UserFunction.h
+++ b/Code/Mantid/MantidPlot/src/UserFunction.h
@@ -1,10 +1,10 @@
-#ifndef USERFUNCTION_H
-#define USERFUNCTION_H
+#ifndef USERFUNCTION_H
+#define USERFUNCTION_H
 
 #include <qwt3d_function.h>
 #include <QString>
-using namespace Qwt3D;
-
+using namespace Qwt3D;
+
 class UserHelperFunction
 {
 public:
@@ -13,7 +13,7 @@ public:
     virtual double getMinPositiveValue()const = 0;
 };
 
-
+
 //! Class for user defined surfaces
 class UserFunction : public Function
 {
@@ -35,4 +35,4 @@ private:
       UserHelperFunction* m_hlpFun;//Mantid
 };
 
-#endif
+#endif
diff --git a/Code/Mantid/MantidPlot/src/VectorCurve.cpp b/Code/Mantid/MantidPlot/src/VectorCurve.cpp
index df10e5748b5a2b5fea1f210ee096fb03e3a95d0b..f0294d7faec5b8d83631cfd981d63573f12fd9c4 100644
--- a/Code/Mantid/MantidPlot/src/VectorCurve.cpp
+++ b/Code/Mantid/MantidPlot/src/VectorCurve.cpp
@@ -47,7 +47,7 @@ VectorCurve::VectorCurve(VectorStyle style, Table *t, const QString& xColName, c
 	if (style == XYXY)
 		setType(Graph::VectXYXY);
 	else if (style == XYAM)
-		setType(Graph::VectXYAM);
+		setType(Graph::VectXYAM);
 }
 
 void VectorCurve::copy(const VectorCurve *vc)
@@ -312,11 +312,11 @@ QString VectorCurve::plotAssociation()
     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)";
-
+        base += "(X)," + d_end_y_m + "(Y)";
+
+    if (!d_labels_column.isEmpty())
+        base += "," + d_labels_column + "(L)";
+
 	return base;
 }
 
diff --git a/Code/Mantid/MantidPlot/src/analysis/fft2D.cpp b/Code/Mantid/MantidPlot/src/analysis/fft2D.cpp
index 422f9ea96afe50a8f731867af8690175bba20cfa..9b78525d6674b6a9af27078cd2bae6104cad3809 100644
--- a/Code/Mantid/MantidPlot/src/analysis/fft2D.cpp
+++ b/Code/Mantid/MantidPlot/src/analysis/fft2D.cpp
@@ -1,31 +1,31 @@
-/***************************************************************************
-    File                 : fft2D.cpp
-    Project              : QtiPlot
-    --------------------------------------------------------------------
-    Copyright            : (C) 2007 by Ion Vasilief
-    Email (use @ for *)  : ion_vasilief*yahoo.fr
-    Description          : FFT for matrices
-
- ***************************************************************************/
-
-/***************************************************************************
- *                                                                         *
- *  This program is free software; you can redistribute it and/or modify   *
- *  it under the terms of the GNU General Public License as published by   *
- *  the Free Software Foundation; either version 2 of the License, or      *
- *  (at your option) any later version.                                    *
- *                                                                         *
- *  This program is distributed in the hope that it will be useful,        *
- *  but WITHOUT 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, write to the Free Software           *
- *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
- *   Boston, MA  02110-1301  USA                                           *
- *                                                                         *
- ***************************************************************************/
+/***************************************************************************
+    File                 : fft2D.cpp
+    Project              : QtiPlot
+    --------------------------------------------------------------------
+    Copyright            : (C) 2007 by Ion Vasilief
+    Email (use @ for *)  : ion_vasilief*yahoo.fr
+    Description          : FFT for matrices
+
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *  This program is free software; you can redistribute it and/or modify   *
+ *  it under the terms of the GNU General Public License as published by   *
+ *  the Free Software Foundation; either version 2 of the License, or      *
+ *  (at your option) any later version.                                    *
+ *                                                                         *
+ *  This program is distributed in the hope that it will be useful,        *
+ *  but WITHOUT 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, write to the Free Software           *
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
+ *   Boston, MA  02110-1301  USA                                           *
+ *                                                                         *
+ ***************************************************************************/
 #include "fft2D.h"
 #include "../Matrix.h"
 #define _USE_MATH_DEFINES
@@ -93,14 +93,14 @@ void fft_inv(double* x_int_re, double* x_int_im, int taille)
 
 void fft2d(double **xtre, double **xtim, int width, int height)
 {
-    double **xint_re = Matrix::allocateMatrixData(height, width);
-    if (!xint_re)
+    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;
-    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++){
@@ -135,14 +135,14 @@ 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)
 {
-    double **xint_re = Matrix::allocateMatrixData(height, width);
-    if (!xint_re)
+    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;
-    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++){
diff --git a/Code/Mantid/MantidPlot/src/analysis/fft2D.h b/Code/Mantid/MantidPlot/src/analysis/fft2D.h
index 1b7b18961fe09a4dd6c384b0c90b28c91cca6d8b..ba01593482fde9cf3ef311de84a121c74506ac99 100644
--- a/Code/Mantid/MantidPlot/src/analysis/fft2D.h
+++ b/Code/Mantid/MantidPlot/src/analysis/fft2D.h
@@ -1,32 +1,32 @@
-/***************************************************************************
-    File                 : fft2D.h
-    Project              : QtiPlot
-    --------------------------------------------------------------------
-    Copyright            : (C) 2007 by Ion Vasilief
-    Email (use @ for *)  : ion_vasilief*yahoo.fr
-    Description          : FFT for matrices
-
- ***************************************************************************/
-
-/***************************************************************************
- *                                                                         *
- *  This program is free software; you can redistribute it and/or modify   *
- *  it under the terms of the GNU General Public License as published by   *
- *  the Free Software Foundation; either version 2 of the License, or      *
- *  (at your option) any later version.                                    *
- *                                                                         *
- *  This program is distributed in the hope that it will be useful,        *
- *  but WITHOUT 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, write to the Free Software           *
- *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
- *   Boston, MA  02110-1301  USA                                           *
- *                                                                         *
- ***************************************************************************/
-
+/***************************************************************************
+    File                 : fft2D.h
+    Project              : QtiPlot
+    --------------------------------------------------------------------
+    Copyright            : (C) 2007 by Ion Vasilief
+    Email (use @ for *)  : ion_vasilief*yahoo.fr
+    Description          : FFT for matrices
+
+ ***************************************************************************/
+
+/***************************************************************************
+ *                                                                         *
+ *  This program is free software; you can redistribute it and/or modify   *
+ *  it under the terms of the GNU General Public License as published by   *
+ *  the Free Software Foundation; either version 2 of the License, or      *
+ *  (at your option) any later version.                                    *
+ *                                                                         *
+ *  This program is distributed in the hope that it will be useful,        *
+ *  but WITHOUT 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, write to the Free Software           *
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
+ *   Boston, MA  02110-1301  USA                                           *
+ *                                                                         *
+ ***************************************************************************/
+
 #ifndef FOURIER_H
 #define FOURIER_H
 
diff --git a/Code/Mantid/MantidPlot/src/fit_gsl.cpp b/Code/Mantid/MantidPlot/src/fit_gsl.cpp
index a815b271f0f72c49e8b2d57ce20e6578a2bdc821..badfc677a1b6b58f086d3fac63084c9968295233 100644
--- a/Code/Mantid/MantidPlot/src/fit_gsl.cpp
+++ b/Code/Mantid/MantidPlot/src/fit_gsl.cpp
@@ -1,711 +1,711 @@
-#include <math.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <stddef.h>
-#include <qmessagebox.h>
-#include <gsl/gsl_blas.h>
-#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 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;
-    }
-    double t;
-    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]);
-        }
-        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);
-    size_t i,j;
-    double val=0,t;
-    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]);
-        }
-        t = (M_2_PI*res + offset - Y[i])/sigma[i];
-        val += t*t;
-    }
-    delete[] a;
-    delete[] xc;
-    delete[] w;
-    return GSL_SUCCESS;
-}
-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].ascii(), &parameters[i]);
-        }
-        parser.SetExpr(function);
-        for (int j = 0; j < (int)n; j++) {
-            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].ascii(), &parameters[i]);
-        }
-        parser.SetExpr(function);
-        for (int j = 0; j < (int)n; j++) {
-            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].ascii(), &param[k]);
-        }
-        parser.SetExpr(function);
-        for (int i = 0; i<(int)n; i++) {
-            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;
-
-    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;
-}
-
-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;
-}
-
-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;
-}
-
-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;
+#include <math.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <stddef.h>
+#include <qmessagebox.h>
+#include <gsl/gsl_blas.h>
+#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 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;
+    }
+    double t;
+    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]);
+        }
+        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);
+    size_t i,j;
+    double val=0,t;
+    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]);
+        }
+        t = (M_2_PI*res + offset - Y[i])/sigma[i];
+        val += t*t;
+    }
+    delete[] a;
+    delete[] xc;
+    delete[] w;
+    return GSL_SUCCESS;
+}
+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].ascii(), &parameters[i]);
+        }
+        parser.SetExpr(function);
+        for (int j = 0; j < (int)n; j++) {
+            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].ascii(), &parameters[i]);
+        }
+        parser.SetExpr(function);
+        for (int j = 0; j < (int)n; j++) {
+            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].ascii(), &param[k]);
+        }
+        parser.SetExpr(function);
+        for (int i = 0; i<(int)n; i++) {
+            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;
+
+    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;
+}
+
+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;
+}
+
+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;
+}
+
+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/Code/Mantid/MantidPlot/src/fit_gsl.h b/Code/Mantid/MantidPlot/src/fit_gsl.h
index 8761e3fbbcf73480694c98b551a067d8d62010af..9dda60de976fb63281fb3df71b1ea0fbd0455a1c 100644
--- a/Code/Mantid/MantidPlot/src/fit_gsl.h
+++ b/Code/Mantid/MantidPlot/src/fit_gsl.h
@@ -33,11 +33,11 @@ int boltzmann_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matri
 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 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);
diff --git a/Code/Mantid/MantidPlot/src/importOPJ.h b/Code/Mantid/MantidPlot/src/importOPJ.h
index 0c6c34844e60dfed6f302ddad7d47f6b72abf9cc..ebd326af0f14bfcef4eee11af0a22c72177b72b6 100644
--- a/Code/Mantid/MantidPlot/src/importOPJ.h
+++ b/Code/Mantid/MantidPlot/src/importOPJ.h
@@ -44,7 +44,7 @@ public:
 	bool importNotes(const OPJFile& opj);
 	int error(){return parse_error;};
 
-private:
+private:
     int arrowAngle(double length, double width){return ceil(45*atan(0.5*width/length)/atan(1.0));};
 	int translateOrigin2QtiplotLineStyle(int linestyle);
 	QString parseOriginText(const QString &str);
diff --git a/Code/Mantid/MantidPlot/src/main.cpp b/Code/Mantid/MantidPlot/src/main.cpp
index 6cb5c0821cd228d62d2c7a02f93288c02a1d2341..50343a1c8585144d2d799b6a52551a00fc328b72 100644
--- a/Code/Mantid/MantidPlot/src/main.cpp
+++ b/Code/Mantid/MantidPlot/src/main.cpp
@@ -180,7 +180,7 @@ int main( int argc, char ** argv )
       ApplicationWindow *mw = new ApplicationWindow(factorySettings);
       mw->restoreApplicationGeometry();
       mw->parseCommandLineArguments(args);
-      t.wait();
+      t.wait();
       splash.finish(mw);
     }
     app.connect( &app, SIGNAL(lastWindowClosed()), &app, SLOT(quit()) );
diff --git a/Code/Mantid/MantidPlot/src/muParserScript.cpp b/Code/Mantid/MantidPlot/src/muParserScript.cpp
index cb8def80709fc16af1db473166362dbab9c82eaf..b53675941c30f065a47b90fbeb0c7d1bb5ff8356 100644
--- a/Code/Mantid/MantidPlot/src/muParserScript.cpp
+++ b/Code/Mantid/MantidPlot/src/muParserScript.cpp
@@ -34,10 +34,10 @@
 #include "Folder.h"
 
 #include <QStringList>
-#include <QApplication>
-#include <QMessageBox>
-
-#include <gsl/gsl_math.h>
+#include <QApplication>
+#include <QMessageBox>
+
+#include <gsl/gsl_math.h>
 
 using namespace mu;
 
@@ -70,14 +70,14 @@ muParserScript::muParserScript(ScriptingEnv *env, const QString &code, QObject *
   } else if (Context->isA("Matrix"))
 	  parser.DefineFun("cell", mu_cell);
 
-  rparser = parser;
-  if (Context->isA("Table") || Context->isA("Matrix")){
+  rparser = parser;
+  if (Context->isA("Table") || Context->isA("Matrix")){
     if (code.count("\n") > 0){//only autodetect new variables for a script which has min 2 lines
 		if (d_warn_multiline_code){
-        	QApplication::restoreOverrideCursor();
-        	QString mess = tr("Multiline expressions take much more time to evaluate! Do you want to continue anyways?");
-        	if (QMessageBox::Yes == QMessageBox::warning((QWidget *)Context, tr("MantidPlot") + " - " + tr("Warning"), mess,
-                           QMessageBox::Yes, QMessageBox::Cancel)){
+        	QApplication::restoreOverrideCursor();
+        	QString mess = tr("Multiline expressions take much more time to evaluate! Do you want to continue anyways?");
+        	if (QMessageBox::Yes == QMessageBox::warning((QWidget *)Context, tr("MantidPlot") + " - " + tr("Warning"), mess,
+                           QMessageBox::Yes, QMessageBox::Cancel)){
            		parser.SetVarFactory(mu_addVariable);
             	rparser.SetVarFactory(mu_addVariableR);
 			}
@@ -85,10 +85,10 @@ muParserScript::muParserScript(ScriptingEnv *env, const QString &code, QObject *
             parser.SetVarFactory(mu_addVariable);
             rparser.SetVarFactory(mu_addVariableR);
 		}
-	}
-  } else {
-      parser.SetVarFactory(mu_addVariable);
-      rparser.SetVarFactory(mu_addVariableR);
+	}
+  } else {
+      parser.SetVarFactory(mu_addVariable);
+      rparser.SetVarFactory(mu_addVariableR);
   }
 }
 
@@ -97,7 +97,7 @@ double muParserScript::col(const QString &arg)
 	if (!Context->isA("Table"))
 		throw Parser::exception_type(tr("col() works only on tables!").ascii());
 	QStringList items;
-	QString item = "";
+	QString item = "";
 
 	for (int i=0; i < arg.size(); i++) {
 		if (arg[i] == '"') {
@@ -115,7 +115,7 @@ double muParserScript::col(const QString &arg)
 		} else
 			item += arg[i];
 	}
-	items << item;
+	items << item;
 
 	Table *table = (Table*) Context;
 	int col, row;
@@ -131,7 +131,7 @@ double muParserScript::col(const QString &arg)
 			local_parser.SetExpr(items[0].ascii());
 			col = qRound(local_parser.Eval()) - 1;
 		}
-	}
+	}
 
 	if (items.count() == 2)
 	{
@@ -267,31 +267,31 @@ double *muParserScript::addVariableR(const char *name)
 	rvariables.insert(name, valptr);
 	return valptr;
 }
-
-double* muParserScript::defineVariable(const char *name, double val)
-{
-  double *valptr = variables[name];
-  if (!valptr)
-  {
-    valptr = new double;
-    if (!valptr)
-    {
-      emit_error(tr("Out of memory"), 0);
-      return 0;
-    }
-    try {
-      parser.DefineVar(name, valptr);
-      rparser.DefineVar(name, valptr);
-      variables.insert(name, valptr);
-    } catch (mu::ParserError &e) {
-      delete valptr;
-      emit_error(QString(e.GetMsg().c_str()), 0);
-      return valptr;
-    }
-  }
-  *valptr = val;
-  return valptr;
-}
+
+double* muParserScript::defineVariable(const char *name, double val)
+{
+  double *valptr = variables[name];
+  if (!valptr)
+  {
+    valptr = new double;
+    if (!valptr)
+    {
+      emit_error(tr("Out of memory"), 0);
+      return 0;
+    }
+    try {
+      parser.DefineVar(name, valptr);
+      rparser.DefineVar(name, valptr);
+      variables.insert(name, valptr);
+    } catch (mu::ParserError &e) {
+      delete valptr;
+      emit_error(QString(e.GetMsg().c_str()), 0);
+      return valptr;
+    }
+  }
+  *valptr = val;
+  return valptr;
+}
 
 bool muParserScript::setDouble(double val, const char *name)
 {
@@ -304,7 +304,7 @@ bool muParserScript::setDouble(double val, const char *name)
       emit_error(tr("Out of memory"),0);
       return false;
     }
-    try {
+    try {
       parser.DefineVar(name, valptr);
       rparser.DefineVar(name, valptr);
       variables.insert(name, valptr);
@@ -316,12 +316,12 @@ bool muParserScript::setDouble(double val, const char *name)
   }
   *valptr = val;
   return  true;
-}
+}
 
 bool muParserScript::setInt(int val, const char *name)
 {
   return setDouble((double) val, name);
-}
+}
 
 bool muParserScript::setQObject(QObject*, const char*)
 {
@@ -411,52 +411,52 @@ bool muParserScript::compile(bool)
 	muCodeLine = muCodeLine.stripWhiteSpace();
 	if (!muCodeLine.isEmpty())
 		muCode += muCodeLine;
-	compiled = Script::isCompiled;
-
-	if (muCode.size() == 1){		
-	    current = this;
-        parser.SetExpr(muCode[0].ascii());
-        try {
-			parser.Eval();
-		} catch (EmptySourceError *e) {
-		    QApplication::restoreOverrideCursor();
-            return false;
-        } catch (mu::ParserError &e) {
-            if (e.GetCode() != ecVAL_EXPECTED){
-                QApplication::restoreOverrideCursor();
-                emit_error(e.GetMsg().c_str(), 0);
-                return false;
-            }
-        }
+	compiled = Script::isCompiled;
+
+	if (muCode.size() == 1){		
+	    current = this;
+        parser.SetExpr(muCode[0].ascii());
+        try {
+			parser.Eval();
+		} catch (EmptySourceError *e) {
+		    QApplication::restoreOverrideCursor();
+            return false;
+        } catch (mu::ParserError &e) {
+            if (e.GetCode() != ecVAL_EXPECTED){
+                QApplication::restoreOverrideCursor();
+                emit_error(e.GetMsg().c_str(), 0);
+                return false;
+            }
+        }
 	}
 	return true;
-}
-
-QString muParserScript::evalSingleLineToString(const QLocale& locale, char f, int prec)
-{
-    double val = 0.0;
-    try {
-        val = parser.Eval();
-    } catch (EmptySourceError *e) {
-        return "";
-    } catch (ParserError &e) {
-		return "";
-	}
-    return locale.toString(val, f, prec);
-}
-
-double muParserScript::evalSingleLine()
-{
-    double val = 0.0;
-    try {
-        val = parser.Eval();
+}
+
+QString muParserScript::evalSingleLineToString(const QLocale& locale, char f, int prec)
+{
+    double val = 0.0;
+    try {
+        val = parser.Eval();
     } catch (EmptySourceError *e) {
-        return GSL_NAN;
+        return "";
     } catch (ParserError &e) {
-		return GSL_NAN;
-	}
-    return val;
-}
+		return "";
+	}
+    return locale.toString(val, f, prec);
+}
+
+double muParserScript::evalSingleLine()
+{
+    double val = 0.0;
+    try {
+        val = parser.Eval();
+    } catch (EmptySourceError *e) {
+        return GSL_NAN;
+    } catch (ParserError &e) {
+		return GSL_NAN;
+	}
+    return val;
+}
 
 muParserScript *muParserScript::current = NULL;
 
diff --git a/Code/Mantid/MantidPlot/src/muParserScript.h b/Code/Mantid/MantidPlot/src/muParserScript.h
index 6cb0fa7bafe750509ef7a1faca56738b181408f6..7b5fc3f99c3c3751d11128db68ccea721cd2c27a 100644
--- a/Code/Mantid/MantidPlot/src/muParserScript.h
+++ b/Code/Mantid/MantidPlot/src/muParserScript.h
@@ -49,15 +49,15 @@ class muParserScript: public Script
 
   public slots:
     bool compile(bool asFunction=true);
-    QVariant eval();
-    double evalSingleLine();
+    QVariant eval();
+    double evalSingleLine();
     QString evalSingleLineToString(const QLocale& locale, char f, int prec);
     bool exec();
     bool setQObject(QObject *val, const char *name);
     bool setInt(int val, const char* name);
-    bool setDouble(double val, const char* name);
-    double* defineVariable(const char *name, double val = 0.0);
-    int codeLines(){return muCode.size();};
+    bool setDouble(double val, const char* name);
+    double* defineVariable(const char *name, double val = 0.0);
+    int codeLines(){return muCode.size();};
 
   private:
     double col(const QString &arg);
@@ -77,9 +77,9 @@ class muParserScript: public Script
 
     mu::Parser parser, rparser;
     Q3AsciiDict<double> variables, rvariables;
-    QStringList muCode;
+    QStringList muCode;
 	//! Flag telling is the parser should warn users on multiline code input
-	bool d_warn_multiline_code;
+	bool d_warn_multiline_code;
 
   public:
     static muParserScript *current;
diff --git a/Code/Mantid/MantidPlot/src/nrutil.cpp b/Code/Mantid/MantidPlot/src/nrutil.cpp
index a9e795410493d6de66e4ed3c847004a3a3f08914..63ef340d01eb61ccf10ca1991ac249c917987de2 100644
--- a/Code/Mantid/MantidPlot/src/nrutil.cpp
+++ b/Code/Mantid/MantidPlot/src/nrutil.cpp
@@ -91,7 +91,7 @@ return 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)  {
 /*-------------------------------------------------------------------------------------------
diff --git a/Code/Mantid/MantidPlot/src/pixmaps.h b/Code/Mantid/MantidPlot/src/pixmaps.h
index f236f54878034dc7a02995216062e87bf38dfd17..43a033c6cd478d2ec0021b10f594ab290f4247fc 100644
--- a/Code/Mantid/MantidPlot/src/pixmaps.h
+++ b/Code/Mantid/MantidPlot/src/pixmaps.h
@@ -34,5 +34,5 @@
 
 /** Function that returns a QPixmap given a string name. */
 QPixmap getQPixmap(const std::string name);
-
+
 #endif
diff --git a/Code/Mantid/MantidPlot/src/plot2D/ScaleEngine.cpp b/Code/Mantid/MantidPlot/src/plot2D/ScaleEngine.cpp
index 0fe44eb674c87869406c4d30cc04a453d233138c..eac174970c5d87fcceeeaf0e949199d175f08c58 100644
--- a/Code/Mantid/MantidPlot/src/plot2D/ScaleEngine.cpp
+++ b/Code/Mantid/MantidPlot/src/plot2D/ScaleEngine.cpp
@@ -30,71 +30,71 @@
 #include "ScaleEngine.h"
 
 QwtScaleTransformation* ScaleEngine::transformation() const
-{
+{
 	return new ScaleTransformation(this);
-}
-
-double ScaleTransformation::invXForm(double p, double p1, double p2, double s1, double s2) const
-{
-    if (!d_engine->hasBreak()){
-        QwtScaleTransformation *tr = new QwtScaleTransformation (d_engine->type());
-        double res = tr->invXForm(p, p1, p2, s1, s2);
-        delete tr;
-        return res;
-    }
-	
-    const int d_break_space = d_engine->breakWidth();
-	const double lb = d_engine->axisBreakLeft();
-    const double rb = d_engine->axisBreakRight();
-	const double pm = p1 + (p2 - p1)*(double)d_engine->breakPosition()/100.0;
-	double pml, pmr;
-	if (p2 > p1){
-		pml = pm - d_break_space;
-		pmr = pm + d_break_space;
-	} else {
-		pml = pm + d_break_space;
-		pmr = pm - d_break_space;
-	}
-
-	if (p > pml && p < pmr)
-		return pm;
-	
-	bool invertedScale = d_engine->testAttribute(QwtScaleEngine::Inverted);
-	QwtScaleTransformation::Type d_type = d_engine->type();
-
-	if (invertedScale){
-		if ((p2 > p1 && p <= pml) || (p2 < p1 && p >= pml)){
-			if (d_engine->log10ScaleAfterBreak())
-				return s1*exp((p - p1)/(pml - p1)*log(rb/s1));
-            else 
-				return s1 + (rb - s1)/(pml - p1)*(p - p1);
-		}
-		
-		if ((p2 > p1 && p >= pmr) || (p2 < p1 && p <= pmr)){
-			if (d_type == QwtScaleTransformation::Log10)
-				return lb * exp((p - pmr)/(p2 - pmr)*log(s2/lb));
-			else if (d_type == QwtScaleTransformation::Linear)
-				return lb + (p - pmr)/(p2 - pmr)*(s2 - lb);
-		}
-
-	}
-
-    if ((p2 > p1 && p <= pml) || (p2 < p1 && p >= pml)){
-        if (d_type == QwtScaleTransformation::Linear)
-            return s1 + (lb - s1)*(p - p1)/(pml - p1);
-        else if (d_type == QwtScaleTransformation::Log10)
-            return s1 * exp((p - p1)/(pml - p1)*log(lb/s1));
-    }
-
-	if ((p2 > p1 && p >= pmr) || (p2 < p1 && p <= pmr)){
-	    if (d_engine->log10ScaleAfterBreak())
-            return rb * exp((p - pmr)/(p2 - pmr)*log(s2/rb));
-	    else
-            return rb + (p - pmr)*(s2 - rb)/(p2 - pmr);
-	}
-
-	return DBL_MAX; // something invalid
-}
+}
+
+double ScaleTransformation::invXForm(double p, double p1, double p2, double s1, double s2) const
+{
+    if (!d_engine->hasBreak()){
+        QwtScaleTransformation *tr = new QwtScaleTransformation (d_engine->type());
+        double res = tr->invXForm(p, p1, p2, s1, s2);
+        delete tr;
+        return res;
+    }
+	
+    const int d_break_space = d_engine->breakWidth();
+	const double lb = d_engine->axisBreakLeft();
+    const double rb = d_engine->axisBreakRight();
+	const double pm = p1 + (p2 - p1)*(double)d_engine->breakPosition()/100.0;
+	double pml, pmr;
+	if (p2 > p1){
+		pml = pm - d_break_space;
+		pmr = pm + d_break_space;
+	} else {
+		pml = pm + d_break_space;
+		pmr = pm - d_break_space;
+	}
+
+	if (p > pml && p < pmr)
+		return pm;
+	
+	bool invertedScale = d_engine->testAttribute(QwtScaleEngine::Inverted);
+	QwtScaleTransformation::Type d_type = d_engine->type();
+
+	if (invertedScale){
+		if ((p2 > p1 && p <= pml) || (p2 < p1 && p >= pml)){
+			if (d_engine->log10ScaleAfterBreak())
+				return s1*exp((p - p1)/(pml - p1)*log(rb/s1));
+            else 
+				return s1 + (rb - s1)/(pml - p1)*(p - p1);
+		}
+		
+		if ((p2 > p1 && p >= pmr) || (p2 < p1 && p <= pmr)){
+			if (d_type == QwtScaleTransformation::Log10)
+				return lb * exp((p - pmr)/(p2 - pmr)*log(s2/lb));
+			else if (d_type == QwtScaleTransformation::Linear)
+				return lb + (p - pmr)/(p2 - pmr)*(s2 - lb);
+		}
+
+	}
+
+    if ((p2 > p1 && p <= pml) || (p2 < p1 && p >= pml)){
+        if (d_type == QwtScaleTransformation::Linear)
+            return s1 + (lb - s1)*(p - p1)/(pml - p1);
+        else if (d_type == QwtScaleTransformation::Log10)
+            return s1 * exp((p - p1)/(pml - p1)*log(lb/s1));
+    }
+
+	if ((p2 > p1 && p >= pmr) || (p2 < p1 && p <= pmr)){
+	    if (d_engine->log10ScaleAfterBreak())
+            return rb * exp((p - pmr)/(p2 - pmr)*log(s2/rb));
+	    else
+            return rb + (p - pmr)*(s2 - rb)/(p2 - pmr);
+	}
+
+	return DBL_MAX; // something invalid
+}
 
 double ScaleTransformation::xForm(double s, double s1, double s2, double p1, double p2) const
 {
@@ -103,11 +103,11 @@ double ScaleTransformation::xForm(double s, double s1, double s2, double p1, dou
 		double res = tr->xForm(s, s1, s2, p1, p2);
 		delete tr;
 		return res;
-	}
-
-    const int d_break_space = d_engine->breakWidth();
-	const double lb = d_engine->axisBreakLeft();
-    const double rb = d_engine->axisBreakRight();
+	}
+
+    const int d_break_space = d_engine->breakWidth();
+	const double lb = d_engine->axisBreakLeft();
+    const double rb = d_engine->axisBreakRight();
 	const double pm = p1 + (p2 - p1)*(double)d_engine->breakPosition()/100.0;
 	double pml, pmr;
 	if (p2 > p1){
@@ -116,45 +116,45 @@ double ScaleTransformation::xForm(double s, double s1, double s2, double p1, dou
 	} else {
 		pml = pm + d_break_space;
 		pmr = pm - d_break_space;
-	}
-
-	if (s > lb && s < rb)
-		return pm;
-
-	bool invertedScale = d_engine->testAttribute(QwtScaleEngine::Inverted);
-	QwtScaleTransformation::Type d_type = d_engine->type();
-
-	if (invertedScale){
-		if (s <= lb){
-			if (d_type == QwtScaleTransformation::Linear)
-				return pmr + (lb - s)/(lb - s2)*(p2 - pmr);
-			else if (d_type == QwtScaleTransformation::Log10){
-				return pmr + log(lb/s)/log(lb/s2)*(p2 - pmr);
-			}
-		}
-		
-		if (s >= rb){
-			if (d_engine->log10ScaleAfterBreak())
-				return p1 + log(s1/s)/log(s1/rb)*(pml - p1);
-			else
-				return p1 + (s1 - s)/(s1 - rb)*(pml - p1);
-		}
-
-	}
-
-    if (s <= lb){
+	}
+
+	if (s > lb && s < rb)
+		return pm;
+
+	bool invertedScale = d_engine->testAttribute(QwtScaleEngine::Inverted);
+	QwtScaleTransformation::Type d_type = d_engine->type();
+
+	if (invertedScale){
+		if (s <= lb){
+			if (d_type == QwtScaleTransformation::Linear)
+				return pmr + (lb - s)/(lb - s2)*(p2 - pmr);
+			else if (d_type == QwtScaleTransformation::Log10){
+				return pmr + log(lb/s)/log(lb/s2)*(p2 - pmr);
+			}
+		}
+		
+		if (s >= rb){
+			if (d_engine->log10ScaleAfterBreak())
+				return p1 + log(s1/s)/log(s1/rb)*(pml - p1);
+			else
+				return p1 + (s1 - s)/(s1 - rb)*(pml - p1);
+		}
+
+	}
+
+    if (s <= lb){
         if (d_type == QwtScaleTransformation::Linear)
-            return p1 + (s - s1)/(lb - s1)*(pml - p1);
-        else if (d_type == QwtScaleTransformation::Log10)
-            return p1 + log(s/s1)/log(lb/s1)*(pml - p1);
+            return p1 + (s - s1)/(lb - s1)*(pml - p1);
+        else if (d_type == QwtScaleTransformation::Log10)
+            return p1 + log(s/s1)/log(lb/s1)*(pml - p1);
     }
 
-	if (s >= rb){
-	    if (d_engine->log10ScaleAfterBreak())
-            return pmr + log(s/rb)/log(s2/rb)*(p2 - pmr);
+	if (s >= rb){
+	    if (d_engine->log10ScaleAfterBreak())
+            return pmr + log(s/rb)/log(s2/rb)*(p2 - pmr);
 	    else
-            return pmr + (s - rb)/(s2 - rb)*(p2 - pmr);
-	}
+            return pmr + (s - rb)/(s2 - rb)*(p2 - pmr);
+	}
 
 	return DBL_MAX; // something invalid
 }
@@ -163,202 +163,202 @@ QwtScaleTransformation *ScaleTransformation::copy() const
 {
     return new ScaleTransformation(d_engine);
 }
-
-/*****************************************************************************
- *
- * Class ScaleEngine
- *
- *****************************************************************************/
-
-ScaleEngine::ScaleEngine(QwtScaleTransformation::Type type,double left_break, double right_break): QwtScaleEngine(),
-d_type(type),
-d_break_left(left_break),
-d_break_right(right_break),
-d_break_pos(50),
-d_step_before(0.0),
-d_step_after(0.0),
-d_minor_ticks_before(1),
-d_minor_ticks_after(1),
-d_log10_scale_after(false),
+
+/*****************************************************************************
+ *
+ * Class ScaleEngine
+ *
+ *****************************************************************************/
+
+ScaleEngine::ScaleEngine(QwtScaleTransformation::Type type,double left_break, double right_break): QwtScaleEngine(),
+d_type(type),
+d_break_left(left_break),
+d_break_right(right_break),
+d_break_pos(50),
+d_step_before(0.0),
+d_step_after(0.0),
+d_minor_ticks_before(1),
+d_minor_ticks_after(1),
+d_log10_scale_after(false),
 d_break_width(4),
-d_break_decoration(true)
-{}
-
-bool ScaleEngine::hasBreak() const
-{
-return (d_break_left == d_break_right || (d_break_left == -DBL_MAX && d_break_right == DBL_MAX))?false:true;
-}
-
-double ScaleEngine::axisBreakLeft() const
-{
-    return d_break_left;
-}
-
-double ScaleEngine::axisBreakRight() const
-{
-    return d_break_right;
-}
-
-int ScaleEngine::breakWidth() const
-{
-    return d_break_width;
-}
-
-int ScaleEngine::breakPosition() const
-{
-    return d_break_pos;
-}
-
-double ScaleEngine::stepBeforeBreak() const
-{
-    return d_step_before;
-}
-
-double ScaleEngine::stepAfterBreak() const
-{
-    return d_step_after;
-}
-
-QwtScaleTransformation::Type ScaleEngine::type() const
-{
-    return d_type;
-}
-
-int ScaleEngine::minTicksBeforeBreak() const
-{
-    return d_minor_ticks_before;
-}
-
-int ScaleEngine::minTicksAfterBreak() const
-{
-    return d_minor_ticks_after;
-}
-
-bool ScaleEngine::log10ScaleAfterBreak() const
-{
-    return d_log10_scale_after;
-}
+d_break_decoration(true)
+{}
+
+bool ScaleEngine::hasBreak() const
+{
+return (d_break_left == d_break_right || (d_break_left == -DBL_MAX && d_break_right == DBL_MAX))?false:true;
+}
+
+double ScaleEngine::axisBreakLeft() const
+{
+    return d_break_left;
+}
+
+double ScaleEngine::axisBreakRight() const
+{
+    return d_break_right;
+}
+
+int ScaleEngine::breakWidth() const
+{
+    return d_break_width;
+}
+
+int ScaleEngine::breakPosition() const
+{
+    return d_break_pos;
+}
+
+double ScaleEngine::stepBeforeBreak() const
+{
+    return d_step_before;
+}
+
+double ScaleEngine::stepAfterBreak() const
+{
+    return d_step_after;
+}
+
+QwtScaleTransformation::Type ScaleEngine::type() const
+{
+    return d_type;
+}
+
+int ScaleEngine::minTicksBeforeBreak() const
+{
+    return d_minor_ticks_before;
+}
+
+int ScaleEngine::minTicksAfterBreak() const
+{
+    return d_minor_ticks_after;
+}
+
+bool ScaleEngine::log10ScaleAfterBreak() const
+{
+    return d_log10_scale_after;
+}
 
 bool ScaleEngine::hasBreakDecoration() const
 {
 	return d_break_decoration;
 }
-
-void ScaleEngine::clone(const ScaleEngine *engine)
-{
-    d_type = engine->type();
-	d_break_left = engine->axisBreakLeft();
-	d_break_right = engine->axisBreakRight();
-    d_break_pos = engine->breakPosition();
-	d_step_before = engine->stepBeforeBreak();
-	d_step_after = engine->stepAfterBreak();
-	d_minor_ticks_before = engine->minTicksBeforeBreak();
-	d_minor_ticks_after = engine->minTicksAfterBreak();
-    d_log10_scale_after = engine->log10ScaleAfterBreak();
+
+void ScaleEngine::clone(const ScaleEngine *engine)
+{
+    d_type = engine->type();
+	d_break_left = engine->axisBreakLeft();
+	d_break_right = engine->axisBreakRight();
+    d_break_pos = engine->breakPosition();
+	d_step_before = engine->stepBeforeBreak();
+	d_step_after = engine->stepAfterBreak();
+	d_minor_ticks_before = engine->minTicksBeforeBreak();
+	d_minor_ticks_after = engine->minTicksAfterBreak();
+    d_log10_scale_after = engine->log10ScaleAfterBreak();
     d_break_width = engine->breakWidth();
-	d_break_decoration = engine->hasBreakDecoration();
-	setAttributes(engine->attributes());
-    setMargins(engine->loMargin(), engine->hiMargin());
-}
+	d_break_decoration = engine->hasBreakDecoration();
+	setAttributes(engine->attributes());
+    setMargins(engine->loMargin(), engine->hiMargin());
+}
 
 QwtScaleDiv ScaleEngine::divideScale(double x1, double x2, int maxMajSteps,
 		int maxMinSteps, double stepSize) const
 {
 	QwtScaleEngine *engine;
-	if (!hasBreak()){
-        if (d_type == QwtScaleTransformation::Log10)
-            engine = new QwtLog10ScaleEngine();
-        else
+	if (!hasBreak()){
+        if (d_type == QwtScaleTransformation::Log10)
+            engine = new QwtLog10ScaleEngine();
+        else
             engine = new QwtLinearScaleEngine();
 		QwtScaleDiv div = engine->divideScale(x1, x2, maxMajSteps, maxMinSteps, stepSize);
 		delete engine;
 		return div;
-	}
-
-    double lb = d_break_left;
-    double rb = d_break_right;
-	double step1 = d_step_before;
-	double step2 = d_step_after;
-    if (x1 > x2){
-        lb = d_break_right;
-        rb = d_break_left;
-		step1 = d_step_after;
-		step2 = d_step_before;
-        if (d_log10_scale_after)
-            engine = new QwtLog10ScaleEngine();
-        else
-            engine = new QwtLinearScaleEngine();
-    } else if (d_type == QwtScaleTransformation::Log10)
-        engine = new QwtLog10ScaleEngine();
-      else
-        engine = new QwtLinearScaleEngine();
-
-    int max_min_intervals = d_minor_ticks_before;
-	if (d_minor_ticks_before == 1)
-		max_min_intervals = 3;
-	if (d_minor_ticks_before > 1)
-		max_min_intervals = d_minor_ticks_before + 1;
-
+	}
+
+    double lb = d_break_left;
+    double rb = d_break_right;
+	double step1 = d_step_before;
+	double step2 = d_step_after;
+    if (x1 > x2){
+        lb = d_break_right;
+        rb = d_break_left;
+		step1 = d_step_after;
+		step2 = d_step_before;
+        if (d_log10_scale_after)
+            engine = new QwtLog10ScaleEngine();
+        else
+            engine = new QwtLinearScaleEngine();
+    } else if (d_type == QwtScaleTransformation::Log10)
+        engine = new QwtLog10ScaleEngine();
+      else
+        engine = new QwtLinearScaleEngine();
+
+    int max_min_intervals = d_minor_ticks_before;
+	if (d_minor_ticks_before == 1)
+		max_min_intervals = 3;
+	if (d_minor_ticks_before > 1)
+		max_min_intervals = d_minor_ticks_before + 1;
+
 	QwtScaleDiv div1 = engine->divideScale(x1, lb, maxMajSteps/2, max_min_intervals, step1);
-
-    max_min_intervals = d_minor_ticks_after;
-	if (d_minor_ticks_after == 1)
-		max_min_intervals = 3;
-	if (d_minor_ticks_after > 1)
-		max_min_intervals = d_minor_ticks_after + 1;
-
-    delete engine;
-    if (testAttribute(QwtScaleEngine::Inverted)){
-        if (d_type == QwtScaleTransformation::Log10)
-            engine = new QwtLog10ScaleEngine();
-        else
-            engine = new QwtLinearScaleEngine();
-    } else if (d_log10_scale_after)
-            engine = new QwtLog10ScaleEngine();
-      else
-            engine = new QwtLinearScaleEngine();
-
-    QwtScaleDiv div2 = engine->divideScale(rb, x2, maxMajSteps/2, max_min_intervals, step2);
+
+    max_min_intervals = d_minor_ticks_after;
+	if (d_minor_ticks_after == 1)
+		max_min_intervals = 3;
+	if (d_minor_ticks_after > 1)
+		max_min_intervals = d_minor_ticks_after + 1;
+
+    delete engine;
+    if (testAttribute(QwtScaleEngine::Inverted)){
+        if (d_type == QwtScaleTransformation::Log10)
+            engine = new QwtLog10ScaleEngine();
+        else
+            engine = new QwtLinearScaleEngine();
+    } else if (d_log10_scale_after)
+            engine = new QwtLog10ScaleEngine();
+      else
+            engine = new QwtLinearScaleEngine();
+
+    QwtScaleDiv div2 = engine->divideScale(rb, x2, maxMajSteps/2, max_min_intervals, step2);
 
     QwtValueList ticks[QwtScaleDiv::NTickTypes];
     ticks[QwtScaleDiv::MinorTick] = div1.ticks(QwtScaleDiv::MinorTick) + div2.ticks(QwtScaleDiv::MinorTick);
     ticks[QwtScaleDiv::MediumTick] = div1.ticks(QwtScaleDiv::MediumTick) + div2.ticks(QwtScaleDiv::MediumTick);
     ticks[QwtScaleDiv::MajorTick] = div1.ticks(QwtScaleDiv::MajorTick) + div2.ticks(QwtScaleDiv::MajorTick);
 
-	delete engine;
+	delete engine;
 	return QwtScaleDiv(x1, x2, ticks);
 }
 
 void ScaleEngine::autoScale (int maxNumSteps, double &x1, double &x2, double &stepSize) const
-{
-	if (!hasBreak() || testAttribute(QwtScaleEngine::Inverted)){
+{
+	if (!hasBreak() || testAttribute(QwtScaleEngine::Inverted)){
+		QwtScaleEngine *engine;
+		if (d_type == QwtScaleTransformation::Log10)
+			engine = new QwtLog10ScaleEngine();
+		else
+			engine = new QwtLinearScaleEngine();
+		
+		engine->setAttributes(attributes());
+    	engine->setReference(reference());
+    	engine->setMargins(loMargin(), hiMargin());
+		engine->autoScale(maxNumSteps, x1, x2, stepSize);
+		delete engine;
+	} else {
 		QwtScaleEngine *engine;
 		if (d_type == QwtScaleTransformation::Log10)
-			engine = new QwtLog10ScaleEngine();
+			engine = new QwtLog10ScaleEngine();
 		else
-			engine = new QwtLinearScaleEngine();
-		
-		engine->setAttributes(attributes());
-    	engine->setReference(reference());
-    	engine->setMargins(loMargin(), hiMargin());
-		engine->autoScale(maxNumSteps, x1, x2, stepSize);
-		delete engine;
-	} else {
-		QwtScaleEngine *engine;
-		if (d_type == QwtScaleTransformation::Log10)
-			engine = new QwtLog10ScaleEngine();
-		else
-			engine = new QwtLinearScaleEngine();
-		
-		engine->setAttributes(attributes());
-		double breakLeft = d_break_left;
-		engine->autoScale(maxNumSteps, x1, breakLeft, stepSize);
-		delete engine;
-		
-		engine = new QwtLinearScaleEngine();
-		engine->setAttributes(attributes());
-		double breakRight = d_break_right;
-		engine->autoScale(maxNumSteps, breakRight, x2, stepSize);
-		delete engine;
-	}
+			engine = new QwtLinearScaleEngine();
+		
+		engine->setAttributes(attributes());
+		double breakLeft = d_break_left;
+		engine->autoScale(maxNumSteps, x1, breakLeft, stepSize);
+		delete engine;
+		
+		engine = new QwtLinearScaleEngine();
+		engine->setAttributes(attributes());
+		double breakRight = d_break_right;
+		engine->autoScale(maxNumSteps, breakRight, x2, stepSize);
+		delete engine;
+	}
 }
diff --git a/Code/Mantid/MantidPlot/src/plot2D/ScaleEngine.h b/Code/Mantid/MantidPlot/src/plot2D/ScaleEngine.h
index aa665ff249f5f3d8be88034eca2f8ba5f82f5633..52abe83ed145d564a80123edf1456efe507629fe 100644
--- a/Code/Mantid/MantidPlot/src/plot2D/ScaleEngine.h
+++ b/Code/Mantid/MantidPlot/src/plot2D/ScaleEngine.h
@@ -45,33 +45,33 @@ public:
 
     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 breakPosition() const;
-	void setBreakPosition(int pos){d_break_pos = pos;};
-
-    double stepBeforeBreak() const;
-    void setStepBeforeBreak(double step){d_step_before = 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 minTicksAfterBreak() const;
-    void setMinTicksAfterBreak(int ticks){d_minor_ticks_after = ticks;};
-
-    bool log10ScaleAfterBreak() const;
-    void setLog10ScaleAfterBreak(bool on){d_log10_scale_after = on;};
+	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 breakPosition() const;
+	void setBreakPosition(int pos){d_break_pos = pos;};
+
+    double stepBeforeBreak() const;
+    void setStepBeforeBreak(double step){d_step_before = 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 minTicksAfterBreak() const;
+    void setMinTicksAfterBreak(int ticks){d_minor_ticks_after = ticks;};
+
+    bool log10ScaleAfterBreak() const;
+    void setLog10ScaleAfterBreak(bool on){d_log10_scale_after = on;};
 
 	QwtScaleTransformation::Type type() const;
 	void setType(QwtScaleTransformation::Type type){d_type = type;};
 
-	bool hasBreak() const;
+	bool hasBreak() const;
 	void clone(const ScaleEngine *engine);
 
 	bool hasBreakDecoration() const;
@@ -79,16 +79,16 @@ public:
 
 private:
 	QwtScaleTransformation::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
+	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;
@@ -98,11 +98,11 @@ class ScaleTransformation: public QwtScaleTransformation
 {
 public:
 	ScaleTransformation(const ScaleEngine *engine):QwtScaleTransformation(Other), d_engine(engine){};
-	virtual double xForm(double x, double, double, double p1, double p2) const;
+	virtual double xForm(double x, double, double, double p1, double p2) const;
 	virtual double invXForm(double x, double s1, double s2, double p1, double p2) const;
 	QwtScaleTransformation* copy() const;
 
-private:
+private:
     //! The scale engine that generates the transformation
 	const ScaleEngine* d_engine;
 };
diff --git a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/FileDialogHandler.h b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/FileDialogHandler.h
index 6b4bfebbe9ea03fc88a9a8bbaf433a4ada8f368e..5f70fa78141f1152a107a062cb8a683d12d012e5 100644
--- a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/FileDialogHandler.h
+++ b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/FileDialogHandler.h
@@ -11,7 +11,7 @@ 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
+    Copyright &copy; 2009-2010 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
     @date 17/09/2010
 
     This file is part of Mantid.
diff --git a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/ManageUserDirectories.h b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/ManageUserDirectories.h
index eb93570cae11cf6e0c8c2695de08a3930b9ba146..4180dd0bcc06468b5fff6ae3f221b1b0acc65e2b 100644
--- a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/ManageUserDirectories.h
+++ b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/ManageUserDirectories.h
@@ -1,51 +1,51 @@
-#ifndef MANTIDQT_MANAGE_USER_DIRECTORIES_H
-#define MANTIDQT_MANAGE_USER_DIRECTORIES_H
-
-#include <QDialog>
-#include "ui_ManageUserDirectories.h"
-#include "DllOption.h"
-
-namespace MantidQt
-{
-namespace API
-{
-
-class EXPORT_OPT_MANTIDQT_API ManageUserDirectories : public QDialog
-{
-	Q_OBJECT
-public:
-	ManageUserDirectories(QWidget *parent = 0);
-	~ManageUserDirectories();
-
-  static void openUserDirsDialog(QWidget * parent);
-
-private:
-  virtual void initLayout();
-  void loadProperties();
-  void saveProperties();
-
-private slots:
-  void helpClicked();
-  void cancelClicked();
-  void confirmClicked();
-
-  void addDataDirPath();
-  void addDataDirBrowse();
-  void remDataDir();
-  void moveUp();
-  void moveDown();
-  void selectSaveDir();
-
-private:
-	Ui::ManageUserDirectories m_uiForm;
-  QString m_userPropFile;
-	QString m_saveDir;
-	QStringList m_dataDirs;
-
-
-};
-
-} // namespace API
-} // namespace MantidQt
-
-#endif /* MANTIDQT_MANAGE_USER_DIRECTORIES_H */
+#ifndef MANTIDQT_MANAGE_USER_DIRECTORIES_H
+#define MANTIDQT_MANAGE_USER_DIRECTORIES_H
+
+#include <QDialog>
+#include "ui_ManageUserDirectories.h"
+#include "DllOption.h"
+
+namespace MantidQt
+{
+namespace API
+{
+
+class EXPORT_OPT_MANTIDQT_API ManageUserDirectories : public QDialog
+{
+	Q_OBJECT
+public:
+	ManageUserDirectories(QWidget *parent = 0);
+	~ManageUserDirectories();
+
+  static void openUserDirsDialog(QWidget * parent);
+
+private:
+  virtual void initLayout();
+  void loadProperties();
+  void saveProperties();
+
+private slots:
+  void helpClicked();
+  void cancelClicked();
+  void confirmClicked();
+
+  void addDataDirPath();
+  void addDataDirBrowse();
+  void remDataDir();
+  void moveUp();
+  void moveDown();
+  void selectSaveDir();
+
+private:
+	Ui::ManageUserDirectories m_uiForm;
+  QString m_userPropFile;
+	QString m_saveDir;
+	QStringList m_dataDirs;
+
+
+};
+
+} // namespace API
+} // namespace MantidQt
+
+#endif /* MANTIDQT_MANAGE_USER_DIRECTORIES_H */
diff --git a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MantidWidget.h b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MantidWidget.h
index d285a03ffc81c5ddea5bd29accfd9b825931629a..c1e202a11c9e4864a4bad52a58d24a5fcfd45388 100644
--- a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MantidWidget.h
+++ b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/MantidWidget.h
@@ -1,75 +1,75 @@
-#ifndef MANTIDQTAPI_MANTIDWIDGET_H_
-#define MANTIDQTAPI_MANTIDWIDGET_H_
-
-#include "DllOption.h"
-#include "MantidQtAPI/PythonRunner.h"
-#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.
-
-    @author Martyn Gigg, Tessella Support Services plc
-    @date 18/03/2009
-
-    Copyright &copy; 2009 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
-    Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-    class EXPORT_OPT_MANTIDQT_API MantidWidget : public QWidget
-    {
-    Q_OBJECT
-
-    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);
-
-    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;
-    };
-  }
-}
-
-#endif //MANTIDQTAPI_MANTIDWIDGET_H_
+#ifndef MANTIDQTAPI_MANTIDWIDGET_H_
+#define MANTIDQTAPI_MANTIDWIDGET_H_
+
+#include "DllOption.h"
+#include "MantidQtAPI/PythonRunner.h"
+#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.
+
+    @author Martyn Gigg, Tessella Support Services plc
+    @date 18/03/2009
+
+    Copyright &copy; 2009 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+    Code Documentation is available at: <http://doxygen.mantidproject.org>    
+    */
+    class EXPORT_OPT_MANTIDQT_API MantidWidget : public QWidget
+    {
+    Q_OBJECT
+
+    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);
+
+    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;
+    };
+  }
+}
+
+#endif //MANTIDQTAPI_MANTIDWIDGET_H_
diff --git a/Code/Mantid/MantidQt/API/src/ManageUserDirectories.cpp b/Code/Mantid/MantidQt/API/src/ManageUserDirectories.cpp
index 9e6e8ee6643b1417975c5a69c30c2a99437c9029..d296df05a42168e59ffb2e872e81112382c32034 100644
--- a/Code/Mantid/MantidQt/API/src/ManageUserDirectories.cpp
+++ b/Code/Mantid/MantidQt/API/src/ManageUserDirectories.cpp
@@ -1,189 +1,189 @@
-#include "MantidQtAPI/ManageUserDirectories.h"
-#include "MantidKernel/ConfigService.h"
-#include <QtGui>
-
-using namespace MantidQt::API;
-
-ManageUserDirectories::ManageUserDirectories(QWidget *parent) : QDialog(parent)
-{
-  setAttribute(Qt::WA_DeleteOnClose);
-	m_uiForm.setupUi(this);
-  initLayout();
-}
-
-ManageUserDirectories::~ManageUserDirectories() {}
-
-void ManageUserDirectories::initLayout()
-{
-  loadProperties();
-
-  // Make Connections
-  connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(helpClicked()));
-  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(addDataDirPath()));
-  connect(m_uiForm.pbBrowseToDir, SIGNAL(clicked()), this, SLOT(addDataDirBrowse()));
-  connect(m_uiForm.pbRemDir, SIGNAL(clicked()), this, SLOT(remDataDir()));
-  connect(m_uiForm.pbMoveUp, SIGNAL(clicked()), this, SLOT(moveUp()));
-  connect(m_uiForm.pbMoveDown, SIGNAL(clicked()), this, SLOT(moveDown()));
-  
-  connect(m_uiForm.pbSaveBrowse, SIGNAL(clicked()), this, SLOT(selectSaveDir()));
-}
-
-void ManageUserDirectories::loadProperties()
-{
-  m_userPropFile = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getUserFilename()).trimmed();
-
-  // get data search directories and populate the list widget (lwDataSearchDirs)
-  QString dataDirs = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("datasearch.directories")).trimmed();
-  m_dataDirs = dataDirs.split(";",QString::SkipEmptyParts);
-  m_uiForm.lwDataSearchDirs->clear();
-  m_uiForm.lwDataSearchDirs->addItems(m_dataDirs);
-
-  // set flag of whether to search the data archive
-  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
-  m_saveDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory")).trimmed();
-  m_uiForm.leDefaultSave->setText(m_saveDir);
-}
-void ManageUserDirectories::saveProperties()
-{
-  QString newSearchArchive;
-  QString newDataDirs;
-  QString newSaveDir;
-
-  if ( m_uiForm.ckSearchArchive->isChecked() )
-    newSearchArchive = "On";
-  else
-    newSearchArchive = "Off";
-
-  QStringList dataDirs;
-  for ( int i = 0; i < m_uiForm.lwDataSearchDirs->count() ; i++ )
-    dataDirs.append(m_uiForm.lwDataSearchDirs->item(i)->text());
-
-  newDataDirs = dataDirs.join(";");
-  newDataDirs.replace('\\', '/');
-
-  newSaveDir = m_uiForm.leDefaultSave->text();
-  newSaveDir.replace('\\', '/');
-
-  Mantid::Kernel::ConfigServiceImpl& config = Mantid::Kernel::ConfigService::Instance();
-
-  config.setString("datasearch.searcharchive", newSearchArchive.toStdString());
-  config.setString("datasearch.directories", newDataDirs.toStdString());
-  config.setString("defaultsave.directory", newSaveDir.toStdString());
-  config.saveConfig(m_userPropFile.toStdString());
-}
-
-// SLOTS
-void ManageUserDirectories::helpClicked()
-{
-  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/ManageUserDirectories"));
-}
-void ManageUserDirectories::cancelClicked()
-{
-  this->close();
-}
-void ManageUserDirectories::confirmClicked()
-{
-  saveProperties();
-  this->close();
-}
-
-void ManageUserDirectories::addDataDirPath()
-{
-  QString path = m_uiForm.leDirectoryPath->text();
-
-  if ( path != "" )
-  {
-    m_uiForm.lwDataSearchDirs->addItem(path);
-  }
-
-}
-
-void ManageUserDirectories::addDataDirBrowse()
-{
-  QSettings settings;
-  QString lastDirectory = settings.value("ManageUserSettings/last_directory", "").toString();
-
-  QString newDir = QFileDialog::getExistingDirectory(this,
-    tr("Select New Data Directory"),
-    lastDirectory,
-    QFileDialog::ShowDirsOnly );
-
-  if ( newDir != "" )
-  {
-    settings.setValue("ManageUserSettings/last_directory", newDir);
-    m_uiForm.lwDataSearchDirs->addItem(newDir);
-  }
-
-}
-void ManageUserDirectories::remDataDir()
-{
-  QList<QListWidgetItem*> selected = m_uiForm.lwDataSearchDirs->selectedItems();
-  for ( int i = 0; i < selected.size(); i++ )
-  {
-    delete selected[i];
-  }
-}
-void ManageUserDirectories::moveUp()
-{
-  QList<QListWidgetItem*> selected = m_uiForm.lwDataSearchDirs->selectedItems();
-  for ( int i = 0; i < selected.size(); i++ )
-  {
-    int index = m_uiForm.lwDataSearchDirs->row(selected[i]);
-    if ( index != 0 )
-    {
-      QListWidgetItem* move = m_uiForm.lwDataSearchDirs->takeItem(index);
-      m_uiForm.lwDataSearchDirs->insertItem(index-1, move);
-    }
-    m_uiForm.lwDataSearchDirs->setCurrentItem(selected[i]);
-  }
-}
-void ManageUserDirectories::moveDown()
-{
-  int count = m_uiForm.lwDataSearchDirs->count();
-  QList<QListWidgetItem*> selected = m_uiForm.lwDataSearchDirs->selectedItems();
-  for ( int i = 0; i < selected.size(); i++ )
-  {
-    int index = m_uiForm.lwDataSearchDirs->row(selected[i]);
-    if ( index != ( count - 1 ) )
-    {
-      QListWidgetItem* move = m_uiForm.lwDataSearchDirs->takeItem(index);
-      m_uiForm.lwDataSearchDirs->insertItem(index+1, move);
-    }
-    m_uiForm.lwDataSearchDirs->setCurrentItem(selected[i]);
-  }
-}
-void ManageUserDirectories::selectSaveDir()
-{
-  QSettings settings;
-  QString lastDirectory = settings.value("ManageUserSettings/last_directory", "").toString();
-
-  QString newDir = QFileDialog::getExistingDirectory(this,
-    tr("Select New Default Save Directory"),
-    lastDirectory,
-    QFileDialog::ShowDirsOnly );
-
-  if ( newDir != "" )
-  {
-    settings.setValue("ManageUserSettings/last_directory", newDir);
-    m_uiForm.leDefaultSave->setText(newDir);
-  }
-
-}
-/** Opens a manage directories dialog and gives it focus
-*  @param the :: parent window, probably the window that called it
-*/
-void ManageUserDirectories::openUserDirsDialog(QWidget * parent)
-{
-  ManageUserDirectories *ad = new ManageUserDirectories(parent);
-  ad->show();
-  ad->setFocus();
-}
+#include "MantidQtAPI/ManageUserDirectories.h"
+#include "MantidKernel/ConfigService.h"
+#include <QtGui>
+
+using namespace MantidQt::API;
+
+ManageUserDirectories::ManageUserDirectories(QWidget *parent) : QDialog(parent)
+{
+  setAttribute(Qt::WA_DeleteOnClose);
+	m_uiForm.setupUi(this);
+  initLayout();
+}
+
+ManageUserDirectories::~ManageUserDirectories() {}
+
+void ManageUserDirectories::initLayout()
+{
+  loadProperties();
+
+  // Make Connections
+  connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(helpClicked()));
+  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(addDataDirPath()));
+  connect(m_uiForm.pbBrowseToDir, SIGNAL(clicked()), this, SLOT(addDataDirBrowse()));
+  connect(m_uiForm.pbRemDir, SIGNAL(clicked()), this, SLOT(remDataDir()));
+  connect(m_uiForm.pbMoveUp, SIGNAL(clicked()), this, SLOT(moveUp()));
+  connect(m_uiForm.pbMoveDown, SIGNAL(clicked()), this, SLOT(moveDown()));
+  
+  connect(m_uiForm.pbSaveBrowse, SIGNAL(clicked()), this, SLOT(selectSaveDir()));
+}
+
+void ManageUserDirectories::loadProperties()
+{
+  m_userPropFile = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getUserFilename()).trimmed();
+
+  // get data search directories and populate the list widget (lwDataSearchDirs)
+  QString dataDirs = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("datasearch.directories")).trimmed();
+  m_dataDirs = dataDirs.split(";",QString::SkipEmptyParts);
+  m_uiForm.lwDataSearchDirs->clear();
+  m_uiForm.lwDataSearchDirs->addItems(m_dataDirs);
+
+  // set flag of whether to search the data archive
+  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
+  m_saveDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory")).trimmed();
+  m_uiForm.leDefaultSave->setText(m_saveDir);
+}
+void ManageUserDirectories::saveProperties()
+{
+  QString newSearchArchive;
+  QString newDataDirs;
+  QString newSaveDir;
+
+  if ( m_uiForm.ckSearchArchive->isChecked() )
+    newSearchArchive = "On";
+  else
+    newSearchArchive = "Off";
+
+  QStringList dataDirs;
+  for ( int i = 0; i < m_uiForm.lwDataSearchDirs->count() ; i++ )
+    dataDirs.append(m_uiForm.lwDataSearchDirs->item(i)->text());
+
+  newDataDirs = dataDirs.join(";");
+  newDataDirs.replace('\\', '/');
+
+  newSaveDir = m_uiForm.leDefaultSave->text();
+  newSaveDir.replace('\\', '/');
+
+  Mantid::Kernel::ConfigServiceImpl& config = Mantid::Kernel::ConfigService::Instance();
+
+  config.setString("datasearch.searcharchive", newSearchArchive.toStdString());
+  config.setString("datasearch.directories", newDataDirs.toStdString());
+  config.setString("defaultsave.directory", newSaveDir.toStdString());
+  config.saveConfig(m_userPropFile.toStdString());
+}
+
+// SLOTS
+void ManageUserDirectories::helpClicked()
+{
+  QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/ManageUserDirectories"));
+}
+void ManageUserDirectories::cancelClicked()
+{
+  this->close();
+}
+void ManageUserDirectories::confirmClicked()
+{
+  saveProperties();
+  this->close();
+}
+
+void ManageUserDirectories::addDataDirPath()
+{
+  QString path = m_uiForm.leDirectoryPath->text();
+
+  if ( path != "" )
+  {
+    m_uiForm.lwDataSearchDirs->addItem(path);
+  }
+
+}
+
+void ManageUserDirectories::addDataDirBrowse()
+{
+  QSettings settings;
+  QString lastDirectory = settings.value("ManageUserSettings/last_directory", "").toString();
+
+  QString newDir = QFileDialog::getExistingDirectory(this,
+    tr("Select New Data Directory"),
+    lastDirectory,
+    QFileDialog::ShowDirsOnly );
+
+  if ( newDir != "" )
+  {
+    settings.setValue("ManageUserSettings/last_directory", newDir);
+    m_uiForm.lwDataSearchDirs->addItem(newDir);
+  }
+
+}
+void ManageUserDirectories::remDataDir()
+{
+  QList<QListWidgetItem*> selected = m_uiForm.lwDataSearchDirs->selectedItems();
+  for ( int i = 0; i < selected.size(); i++ )
+  {
+    delete selected[i];
+  }
+}
+void ManageUserDirectories::moveUp()
+{
+  QList<QListWidgetItem*> selected = m_uiForm.lwDataSearchDirs->selectedItems();
+  for ( int i = 0; i < selected.size(); i++ )
+  {
+    int index = m_uiForm.lwDataSearchDirs->row(selected[i]);
+    if ( index != 0 )
+    {
+      QListWidgetItem* move = m_uiForm.lwDataSearchDirs->takeItem(index);
+      m_uiForm.lwDataSearchDirs->insertItem(index-1, move);
+    }
+    m_uiForm.lwDataSearchDirs->setCurrentItem(selected[i]);
+  }
+}
+void ManageUserDirectories::moveDown()
+{
+  int count = m_uiForm.lwDataSearchDirs->count();
+  QList<QListWidgetItem*> selected = m_uiForm.lwDataSearchDirs->selectedItems();
+  for ( int i = 0; i < selected.size(); i++ )
+  {
+    int index = m_uiForm.lwDataSearchDirs->row(selected[i]);
+    if ( index != ( count - 1 ) )
+    {
+      QListWidgetItem* move = m_uiForm.lwDataSearchDirs->takeItem(index);
+      m_uiForm.lwDataSearchDirs->insertItem(index+1, move);
+    }
+    m_uiForm.lwDataSearchDirs->setCurrentItem(selected[i]);
+  }
+}
+void ManageUserDirectories::selectSaveDir()
+{
+  QSettings settings;
+  QString lastDirectory = settings.value("ManageUserSettings/last_directory", "").toString();
+
+  QString newDir = QFileDialog::getExistingDirectory(this,
+    tr("Select New Default Save Directory"),
+    lastDirectory,
+    QFileDialog::ShowDirsOnly );
+
+  if ( newDir != "" )
+  {
+    settings.setValue("ManageUserSettings/last_directory", newDir);
+    m_uiForm.leDefaultSave->setText(newDir);
+  }
+
+}
+/** Opens a manage directories dialog and gives it focus
+*  @param the :: parent window, probably the window that called it
+*/
+void ManageUserDirectories::openUserDirsDialog(QWidget * parent)
+{
+  ManageUserDirectories *ad = new ManageUserDirectories(parent);
+  ad->show();
+  ad->setFocus();
+}
diff --git a/Code/Mantid/MantidQt/API/src/MantidWidget.cpp b/Code/Mantid/MantidQt/API/src/MantidWidget.cpp
index 67c12b7bfec94caaa7a3755db08dede5919ca33a..b4c1eeb126480327a6dddafb996c63c95411640e 100644
--- a/Code/Mantid/MantidQt/API/src/MantidWidget.cpp
+++ b/Code/Mantid/MantidQt/API/src/MantidWidget.cpp
@@ -1,25 +1,25 @@
-#include "MantidQtAPI/MantidWidget.h"
-#include "MantidKernel/Exception.h"
-
-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&)),
-    this, SIGNAL(runAsPythonScript(const QString&)));
-}
-
-/** 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
-*  @return output from Python print statements unless no_output is false
-*/
-QString MantidWidget::runPythonCode(const QString & code, bool no_output)
-{
-  return m_pyRunner.runPythonCode(code, no_output);
-}
+#include "MantidQtAPI/MantidWidget.h"
+#include "MantidKernel/Exception.h"
+
+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&)),
+    this, SIGNAL(runAsPythonScript(const QString&)));
+}
+
+/** 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
+*  @return output from Python print statements unless no_output is false
+*/
+QString MantidWidget::runPythonCode(const QString & code, bool no_output)
+{
+  return m_pyRunner.runPythonCode(code, no_output);
+}
diff --git a/Code/Mantid/MantidQt/CustomDialogs/src/MantidGLWidget.cpp b/Code/Mantid/MantidQt/CustomDialogs/src/MantidGLWidget.cpp
index 2a7f8708998df01d42a88328b7c36c30862d7732..bef8bc0b13db13633b2a9d68dead68f5af2535ed 100644
--- a/Code/Mantid/MantidQt/CustomDialogs/src/MantidGLWidget.cpp
+++ b/Code/Mantid/MantidQt/CustomDialogs/src/MantidGLWidget.cpp
@@ -176,10 +176,10 @@ void MantidGLWidget::paintGL()
  */
 void MantidGLWidget::resizeGL(int width, int height)
 {
-  glViewport(0, 0, (GLsizei)width, (GLsizei)height);
-  if( height == 0 ) height = 1;
-
-  GLdouble aspect_ratio = (GLdouble)width/(GLdouble)height;
+  glViewport(0, 0, (GLsizei)width, (GLsizei)height);
+  if( height == 0 ) height = 1;
+
+  GLdouble aspect_ratio = (GLdouble)width/(GLdouble)height;
   setOrthoProjectionMatrix(aspect_ratio);
 }
 
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Background.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Background.h
index 5938794caa85df38c45d6722a40f3954623dffd3..3ec93c55baf6f4db0e80f8e4457662ef499e0bac 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Background.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Background.h
@@ -1,53 +1,53 @@
-#ifndef MANTIDQTCUSTOMINTERFACES_BACKGROUND_H_
-#define MANTIDQTCUSTOMINTERFACES_BACKGROUND_H_
-
-#include "MantidQtAPI/MantidDialog.h"
-#include <QCheckBox>
-#include <QLineEdit>
-#include <QPair>
-
-//--------------------------------------------------------
-// Forward declarations
-//--------------------------------------------------------
-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*);
-      void closeEvent(QCloseEvent*);
-      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_
+#ifndef MANTIDQTCUSTOMINTERFACES_BACKGROUND_H_
+#define MANTIDQTCUSTOMINTERFACES_BACKGROUND_H_
+
+#include "MantidQtAPI/MantidDialog.h"
+#include <QCheckBox>
+#include <QLineEdit>
+#include <QPair>
+
+//--------------------------------------------------------
+// Forward declarations
+//--------------------------------------------------------
+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*);
+      void closeEvent(QCloseEvent*);
+      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/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/ConvertToEnergy.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/ConvertToEnergy.h
index 457548524b29a9d51bcfad293f4365d51cc615fb..26069de707b99f622c41afab129a8b8e7ad1e707 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/ConvertToEnergy.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/ConvertToEnergy.h
@@ -1,23 +1,23 @@
-#ifndef MANTIDQTCUSTOMINTERFACES_CONVERTTOENERGY_H_
-#define MANTIDQTCUSTOMINTERFACES_CONVERTTOENERGY_H_
-
-//----------------------
-// Includes
-//----------------------
-#include "ui_ConvertToEnergy.h"
-#include "MantidQtAPI/UserSubWindow.h"
-
-
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    //-------------------------------------------
-    // Forward declarations
-    //-------------------------------------------
-    class Homer;
-    class Indirect;
-
+#ifndef MANTIDQTCUSTOMINTERFACES_CONVERTTOENERGY_H_
+#define MANTIDQTCUSTOMINTERFACES_CONVERTTOENERGY_H_
+
+//----------------------
+// Includes
+//----------------------
+#include "ui_ConvertToEnergy.h"
+#include "MantidQtAPI/UserSubWindow.h"
+
+
+namespace MantidQt
+{
+  namespace CustomInterfaces
+  {
+    //-------------------------------------------
+    // Forward declarations
+    //-------------------------------------------
+    class Homer;
+    class Indirect;
+
     /** 
     This class defines the ConvertToEnergy interface. It handles the overall instrument settings
     and sets up the appropriate interface depending on the deltaE mode of the instrument. The deltaE
@@ -45,69 +45,69 @@ namespace MantidQt
 
     File change history is stored at: <https://svn.mantidproject.org/mantid/trunk/Code/Mantid>
     Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-
-    class ConvertToEnergy : 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
-      ConvertToEnergy(QWidget *parent = 0);
-      ///Destructor
-      ~ConvertToEnergy();
-      /// Interface name
-      static std::string name() { return "ConvertToEnergy"; }
-      /// Aliases for this interface
-      static std::set<std::string> aliases()
-      { 
-        std::set<std::string> aliasList;
-        aliasList.insert("Homer");
-        return aliasList;
-      }
-
-    private slots:
-      void helpClicked();
-      void runClicked();
-
-    private: // private functions (and slots)
-      /// Initialize the layout
-      virtual void initLayout();
-      virtual void initLocalPython();
-      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);
-      /// Change the user interface to show the relevant sections for the instrument type.
-      void changeInterface(DeltaEMode desired);
-    private slots:
-      void userSelectInstrument(const QString& name);
-      void openDirectoryDialog();
-
-    private: // member variables
-      /// The .ui form generated by Qt Designer
-      Ui::ConvertToEnergy m_uiForm;
-      /// Direct Instruments interface object
-      Homer *m_directInstruments;
-      /// Indirect Instruments interface object
-      Indirect *m_indirectInstruments;
-      /// 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;
-
-    };
-
-  }
-}
-
-#endif //MANTIDQTCUSTOMINTERFACES_CONVERTTOENERGY_H_
+    */
+
+    class ConvertToEnergy : 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
+      ConvertToEnergy(QWidget *parent = 0);
+      ///Destructor
+      ~ConvertToEnergy();
+      /// Interface name
+      static std::string name() { return "ConvertToEnergy"; }
+      /// Aliases for this interface
+      static std::set<std::string> aliases()
+      { 
+        std::set<std::string> aliasList;
+        aliasList.insert("Homer");
+        return aliasList;
+      }
+
+    private slots:
+      void helpClicked();
+      void runClicked();
+
+    private: // private functions (and slots)
+      /// Initialize the layout
+      virtual void initLayout();
+      virtual void initLocalPython();
+      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);
+      /// Change the user interface to show the relevant sections for the instrument type.
+      void changeInterface(DeltaEMode desired);
+    private slots:
+      void userSelectInstrument(const QString& name);
+      void openDirectoryDialog();
+
+    private: // member variables
+      /// The .ui form generated by Qt Designer
+      Ui::ConvertToEnergy m_uiForm;
+      /// Direct Instruments interface object
+      Homer *m_directInstruments;
+      /// Indirect Instruments interface object
+      Indirect *m_indirectInstruments;
+      /// 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;
+
+    };
+
+  }
+}
+
+#endif //MANTIDQTCUSTOMINTERFACES_CONVERTTOENERGY_H_
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Homer.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Homer.h
index b083bd405057b6e255a34ab21bc437e6dba118a4..7995fa6cdd737d9e7ed784fd305df5eb17141812 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Homer.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Homer.h
@@ -34,32 +34,32 @@ namespace MantidQt
     //-----------------------------------------------------
     class Background;
 
-    /** 
-    This class implements the ConvertToEnergy 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
-
-    This file is part of Mantid.
-
+    /** 
+    This class implements the ConvertToEnergy 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
+
+    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://svn.mantidproject.org/mantid/trunk/Code/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://svn.mantidproject.org/mantid/trunk/Code/Mantid>
+    Code Documentation is available at: <http://doxygen.mantidproject.org>    
     */
     class Homer : public MantidQt::API::UserSubWindow
     {
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect.h
index 1394f5148ec41d7c42452805f4d769b54638cb97..f10568763ac9291477445339144b1b6659747493 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect.h
@@ -1,27 +1,27 @@
-#ifndef MANTIDQTCUSTOMINTERFACES_INDIRECT_H_
-#define MANTIDQTCUSTOMINTERFACES_INDIRECT_H_
-
-#include "MantidQtAPI/UserSubWindow.h"
-#include "ui_ConvertToEnergy.h"
-
-#include <qwt_plot.h>
-#include <qwt_plot_curve.h>
-
-#include "qttreepropertybrowser.h"
-#include "qtpropertymanager.h"
-#include "qteditorfactory.h"
-
-#include "MantidQtMantidWidgets/RangeSelector.h"
-
-//-----------------------------------------------------
-// Forward declarations
-//-----------------------------------------------------
-
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    /// Forward Declarations
+#ifndef MANTIDQTCUSTOMINTERFACES_INDIRECT_H_
+#define MANTIDQTCUSTOMINTERFACES_INDIRECT_H_
+
+#include "MantidQtAPI/UserSubWindow.h"
+#include "ui_ConvertToEnergy.h"
+
+#include <qwt_plot.h>
+#include <qwt_plot_curve.h>
+
+#include "qttreepropertybrowser.h"
+#include "qtpropertymanager.h"
+#include "qteditorfactory.h"
+
+#include "MantidQtMantidWidgets/RangeSelector.h"
+
+//-----------------------------------------------------
+// Forward declarations
+//-----------------------------------------------------
+
+namespace MantidQt
+{
+  namespace CustomInterfaces
+  {
+    /// Forward Declarations
     class Background;
 
     /** 
@@ -49,129 +49,129 @@ namespace MantidQt
 
     File change history is stored at: <https://svn.mantidproject.org/mantid/trunk/Code/Mantid>
     Code Documentation is available at: <http://doxygen.mantidproject.org>    
-    */
-
-    class Indirect : public MantidQt::API::UserSubWindow
-    {
-      Q_OBJECT
-
-    public:
-      /// explicit constructor, not to allow any implicit conversion of types
-      explicit Indirect(QWidget *parent, Ui::ConvertToEnergy & uiForm);
-      /// Initialize the layout
-      virtual void initLayout();
-      /// run Python-based initialisation commands
-      virtual void initLocalPython();
-      /// open the wiki page for this interface in a web browser
-      void helpClicked();
-      /// perform whatever operations needed for analysis
-      void runClicked();
-      void runConvertToEnergy(bool tryToSave=true);
-      /// gather necessary information from Instument Definition Files
-      virtual void setIDFValues(const QString & prefix);
-
-    private:
-      virtual void closeEvent(QCloseEvent* close);
-      void handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf); ///< handle POCO event
-      void clearReflectionInfo(); ///< clear various line edit boxes
-      QString createMapFile(const QString& groupType); ///< create the mapping file with which to group results
-      QString savePyCode(); ///< create python code as string to save files
-      void createRESfile(const QString& file); ///< create a RES file for use in Fury
-      bool validateInput(); ///< validate input of "Energy Transfer" tab
-      bool validateCalib(); ///< validate input of "Calibration" tab
-      bool validateSofQw(); ///< validate input of "S(Q, w)" tab
-      bool validateSlice(); ///< validate input of "Slice" tab
-      bool isDirty(); ///< state whether interface has had any changes
-      void isDirty(bool state); ///< signify changes to interface
-      bool isDirtyRebin(); ///< state whether post-rebin interface has had any changes
-      void isDirtyRebin(bool state); ///< set value for above
-      void loadSettings();
-      void saveSettings();
-
-      void setupCalibration(); ///< set up the miniplots on calibration tab
-      void setupSlice(); ///< setup the slice miniplot section
-
-    private slots:
-      void refreshWSlist();
-      void analyserSelected(int index); ///< set up cbReflection based on Analyser selection
-      void reflectionSelected(int index); ///< set up parameter file values based on reflection
-      void mappingOptionSelected(const QString& groupType); ///< change ui to display appropriate options
-      void tabChanged(int index); ///< handles enabling/disabling the "Run" button
-      void backgroundClicked(); ///< handles showing and hiding m_backgroundDialog
-      void backgroundRemoval(); ///< handles data from BG
-      void plotRaw(); ///< plot raw data from instrument
-      void rebinCheck(bool state); ///< handle checking/unchecking of "Do Not Rebin"
-      void detailedBalanceCheck(bool state); ///< handle checking/unchecking of "Detailed Balance"
-      void resCheck(bool state); ///< handles checking/unchecking of "Create RES File" checkbox
-      void rebinData(); ///< rebin transformed data
-      void useCalib(bool state); ///< whether to use calib file
-      void calibCreate(); ///< create calibration file
-      void setasDirty(); ///< sets m_isDirty(true)
-      void setasDirtyRebin(); ///< sets m_isDirtyRebin(true)
-      void calibFileChanged(const QString & calib); ///< sets m_uiForm.ckUseCalib to appropriate value
-
-      void calPlotRaw();
-      void calPlotEnergy();
-      void calMinChanged(double);
-      void calMaxChanged(double);
-      void calUpdateRS(QtProperty*, double);
-
-      void sOfQwClicked(); ///< S(Q,w) tab run button clicked
-      void sOfQwRebinE(bool state);
-      void sOfQwInputType(const QString& input);
-      void sOfQwPlotInput();
-
-      void sliceRun();
-      void slicePlotRaw();
-      void sliceTwoRanges(QtProperty*, bool);
-      void sliceCalib(bool state);
-      void sliceMinChanged(double val);
-      void sliceMaxChanged(double val);
-      void sliceUpdateRS(QtProperty*, double);
-
-    private:
-      Ui::ConvertToEnergy m_uiForm; ///< user interface form object
-      Background *m_backgroundDialog; ///< background removal dialog
-      Poco::NObserver<Indirect, Mantid::Kernel::ConfigValChangeNotification> m_changeObserver; ///< Poco observer for changes in user directory settings
-      QString m_dataDir; ///< default data search directory
-      QString m_saveDir; ///< default data save directory
-      QString m_settingsGroup;
-      bool m_bgRemoval; ///< whether user has set values for BG removal
-      bool m_isDirty; ///< whether pre-rebin options have changed
-      bool m_isDirtyRebin; ///< whether rebin/post-rebin options have changed
-
-      /* Validators */
-      QIntValidator *m_valInt; ///< validator for int inputs
-      QDoubleValidator *m_valDbl; ///< validator for double inputs
-
-      // CALIBRATION MINIPLOTS (prefix: 'm_calCal' (calibration) and 'm_calRes' (resolution))
-      QwtPlot* m_calCalPlot;
-      QwtPlot* m_calResPlot;
-      MantidWidgets::RangeSelector* m_calCalR1;
-      MantidWidgets::RangeSelector* m_calCalR2;
-      MantidWidgets::RangeSelector* m_calResR1;
-      MantidWidgets::RangeSelector* m_calResR2;
-      QwtPlotCurve* m_calCalCurve;
-      QwtPlotCurve* m_calResCurve;
-      QtTreePropertyBrowser* m_calCalTree;
-      QtTreePropertyBrowser* m_calResTree;
-      QMap<QString, QtProperty*> m_calCalProp;
-      QMap<QString, QtProperty*> m_calResProp;
-      QtDoublePropertyManager* m_calDblMng;
-      QtGroupPropertyManager* m_calGrpMng;
-
-      // SLICE MINIPLOT (prefix: 'm_slt')
-      QwtPlot* m_sltPlot;
-      MantidWidgets::RangeSelector* m_sltR1;
-      MantidWidgets::RangeSelector* m_sltR2;
-      QwtPlotCurve* m_sltDataCurve;
-      QtTreePropertyBrowser* m_sltTree;
-      QMap<QString, QtProperty*> m_sltProp;
-      QtDoublePropertyManager* m_sltDblMng;
-      QtBoolPropertyManager* m_sltBlnMng;
-      QtGroupPropertyManager* m_sltGrpMng;
-    };
-  }
-}
-
+    */
+
+    class Indirect : public MantidQt::API::UserSubWindow
+    {
+      Q_OBJECT
+
+    public:
+      /// explicit constructor, not to allow any implicit conversion of types
+      explicit Indirect(QWidget *parent, Ui::ConvertToEnergy & uiForm);
+      /// Initialize the layout
+      virtual void initLayout();
+      /// run Python-based initialisation commands
+      virtual void initLocalPython();
+      /// open the wiki page for this interface in a web browser
+      void helpClicked();
+      /// perform whatever operations needed for analysis
+      void runClicked();
+      void runConvertToEnergy(bool tryToSave=true);
+      /// gather necessary information from Instument Definition Files
+      virtual void setIDFValues(const QString & prefix);
+
+    private:
+      virtual void closeEvent(QCloseEvent* close);
+      void handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf); ///< handle POCO event
+      void clearReflectionInfo(); ///< clear various line edit boxes
+      QString createMapFile(const QString& groupType); ///< create the mapping file with which to group results
+      QString savePyCode(); ///< create python code as string to save files
+      void createRESfile(const QString& file); ///< create a RES file for use in Fury
+      bool validateInput(); ///< validate input of "Energy Transfer" tab
+      bool validateCalib(); ///< validate input of "Calibration" tab
+      bool validateSofQw(); ///< validate input of "S(Q, w)" tab
+      bool validateSlice(); ///< validate input of "Slice" tab
+      bool isDirty(); ///< state whether interface has had any changes
+      void isDirty(bool state); ///< signify changes to interface
+      bool isDirtyRebin(); ///< state whether post-rebin interface has had any changes
+      void isDirtyRebin(bool state); ///< set value for above
+      void loadSettings();
+      void saveSettings();
+
+      void setupCalibration(); ///< set up the miniplots on calibration tab
+      void setupSlice(); ///< setup the slice miniplot section
+
+    private slots:
+      void refreshWSlist();
+      void analyserSelected(int index); ///< set up cbReflection based on Analyser selection
+      void reflectionSelected(int index); ///< set up parameter file values based on reflection
+      void mappingOptionSelected(const QString& groupType); ///< change ui to display appropriate options
+      void tabChanged(int index); ///< handles enabling/disabling the "Run" button
+      void backgroundClicked(); ///< handles showing and hiding m_backgroundDialog
+      void backgroundRemoval(); ///< handles data from BG
+      void plotRaw(); ///< plot raw data from instrument
+      void rebinCheck(bool state); ///< handle checking/unchecking of "Do Not Rebin"
+      void detailedBalanceCheck(bool state); ///< handle checking/unchecking of "Detailed Balance"
+      void resCheck(bool state); ///< handles checking/unchecking of "Create RES File" checkbox
+      void rebinData(); ///< rebin transformed data
+      void useCalib(bool state); ///< whether to use calib file
+      void calibCreate(); ///< create calibration file
+      void setasDirty(); ///< sets m_isDirty(true)
+      void setasDirtyRebin(); ///< sets m_isDirtyRebin(true)
+      void calibFileChanged(const QString & calib); ///< sets m_uiForm.ckUseCalib to appropriate value
+
+      void calPlotRaw();
+      void calPlotEnergy();
+      void calMinChanged(double);
+      void calMaxChanged(double);
+      void calUpdateRS(QtProperty*, double);
+
+      void sOfQwClicked(); ///< S(Q,w) tab run button clicked
+      void sOfQwRebinE(bool state);
+      void sOfQwInputType(const QString& input);
+      void sOfQwPlotInput();
+
+      void sliceRun();
+      void slicePlotRaw();
+      void sliceTwoRanges(QtProperty*, bool);
+      void sliceCalib(bool state);
+      void sliceMinChanged(double val);
+      void sliceMaxChanged(double val);
+      void sliceUpdateRS(QtProperty*, double);
+
+    private:
+      Ui::ConvertToEnergy m_uiForm; ///< user interface form object
+      Background *m_backgroundDialog; ///< background removal dialog
+      Poco::NObserver<Indirect, Mantid::Kernel::ConfigValChangeNotification> m_changeObserver; ///< Poco observer for changes in user directory settings
+      QString m_dataDir; ///< default data search directory
+      QString m_saveDir; ///< default data save directory
+      QString m_settingsGroup;
+      bool m_bgRemoval; ///< whether user has set values for BG removal
+      bool m_isDirty; ///< whether pre-rebin options have changed
+      bool m_isDirtyRebin; ///< whether rebin/post-rebin options have changed
+
+      /* Validators */
+      QIntValidator *m_valInt; ///< validator for int inputs
+      QDoubleValidator *m_valDbl; ///< validator for double inputs
+
+      // CALIBRATION MINIPLOTS (prefix: 'm_calCal' (calibration) and 'm_calRes' (resolution))
+      QwtPlot* m_calCalPlot;
+      QwtPlot* m_calResPlot;
+      MantidWidgets::RangeSelector* m_calCalR1;
+      MantidWidgets::RangeSelector* m_calCalR2;
+      MantidWidgets::RangeSelector* m_calResR1;
+      MantidWidgets::RangeSelector* m_calResR2;
+      QwtPlotCurve* m_calCalCurve;
+      QwtPlotCurve* m_calResCurve;
+      QtTreePropertyBrowser* m_calCalTree;
+      QtTreePropertyBrowser* m_calResTree;
+      QMap<QString, QtProperty*> m_calCalProp;
+      QMap<QString, QtProperty*> m_calResProp;
+      QtDoublePropertyManager* m_calDblMng;
+      QtGroupPropertyManager* m_calGrpMng;
+
+      // SLICE MINIPLOT (prefix: 'm_slt')
+      QwtPlot* m_sltPlot;
+      MantidWidgets::RangeSelector* m_sltR1;
+      MantidWidgets::RangeSelector* m_sltR2;
+      QwtPlotCurve* m_sltDataCurve;
+      QtTreePropertyBrowser* m_sltTree;
+      QMap<QString, QtProperty*> m_sltProp;
+      QtDoublePropertyManager* m_sltDblMng;
+      QtBoolPropertyManager* m_sltBlnMng;
+      QtGroupPropertyManager* m_sltGrpMng;
+    };
+  }
+}
+
 #endif // MANTIDQTCUSTOMINTERFACES_INDIRECT_H_
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IndirectDataAnalysis.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IndirectDataAnalysis.h
index 6561d8e9a73a7988a3331dbfde18ab932aca371f..ac2be0ed0b410f5bc10fbe178939f006c91ab70b 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IndirectDataAnalysis.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IndirectDataAnalysis.h
@@ -1,253 +1,253 @@
-#ifndef MANTIDQTCUSTOMINTERFACES_INDIRECTANALYSIS_H_
-#define MANTIDQTCUSTOMINTERFACES_INDIRECTANALYSIS_H_
-
-//----------------------
-// Includes
-//----------------------
-#include "ui_IndirectDataAnalysis.h"
-#include "MantidQtAPI/UserSubWindow.h"
-
-#include <Poco/NObserver.h>
-#include "MantidKernel/ConfigService.h"
-
-//----------------------
-// Forward Declarations
-//----------------------
-namespace Mantid
-{
-  namespace API
-  {
-    class MatrixWorkspace;
-    class IFitFunction;
-    class CompositeFunctionMW;
-  }
-}
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    class RangeSelector;
-  }
-}
-class QwtPlot;
-class QwtPlotCurve;
-class QIntValidator;
-class QDoubleValidator;
-class DoubleEditorFactory;
-class QtCheckBoxFactory;
-class QtProperty;
-class QtBoolPropertyManager;
-class QtDoublePropertyManager;
-class QtGroupPropertyManager;
-class QtStringPropertyManager;
-class QtTreePropertyBrowser;
-//----------------------
-//       End Of
-// Forward Declarations
-//----------------------
-
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    class IndirectDataAnalysis : public MantidQt::API::UserSubWindow
-    {
-      Q_OBJECT
-
-    public:
-      /// The name of the interface as registered into the factory
-      static std::string name() { return "Indirect Data Analysis"; }
-      /// Default Constructor
-      IndirectDataAnalysis(QWidget *parent = 0);
-
-    private:
-      /// Initialize the layout
-      virtual void initLayout();
-      /// init python-dependent sections
-      virtual void initLocalPython();
-
-      void loadSettings();
-
-      // Tab-specific setup stages (mainly miniplots)
-      void setupElwin();
-      void setupMsd();
-      void setupFury();
-      void setupFuryFit();
-      void setupConFit();
-      void setupAbsorptionF2Py();
-      void setupAbsCor();
-
-      // Validation of user inputs
-      bool validateElwin();
-      bool validateMsd();
-      bool validateFury();
-      bool validateAbsorption();
-      bool validateAbsorptionF2Py();
-
-      // Run processes
-      void elwinRun();
-      void msdRun();
-      void furyRun();
-      void furyfitRun();
-      void confitRun();
-      void absorptionRun();
-
-      Mantid::API::CompositeFunctionMW* furyfitCreateFunction(bool tie=false);
-      Mantid::API::IFitFunction* furyfitCreateUserFunction(const QString & name, bool tie=false);
-      Mantid::API::CompositeFunctionMW* confitCreateFunction(bool tie=false);
-      QtProperty* createLorentzian(const QString &);
-      QtProperty* createExponential(const QString &);
-      QtProperty* createStretchedExp(const QString &);
-
-      void populateFunction(Mantid::API::IFitFunction*, Mantid::API::IFitFunction*, QtProperty*, int, const bool tie=false);
-      QwtPlotCurve* plotMiniplot(QwtPlot* plot, QwtPlotCurve* curve, std::string workspace, int index);
-      
-      virtual void closeEvent(QCloseEvent*);
-
-      void handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf); ///< handle POCO event
-
-    private slots:
-      void run();
-      
-      // context menu on fitting property browser
-      void fitContextMenu(const QPoint &);
-      void fixItem();
-      void unFixItem();
-
-      // ElasticWindow
-      void elwinPlotInput();
-      void elwinTwoRanges(QtProperty*, bool);
-      void elwinMinChanged(double val);
-      void elwinMaxChanged(double val);
-      void elwinUpdateRS(QtProperty* prop, double val);
-
-      // MSD Fit
-      void msdPlotInput();
-      void msdMinChanged(double val);
-      void msdMaxChanged(double val);
-      void msdUpdateRS(QtProperty* prop, double val);
-
-      // Fourier Transform
-      void furyResType(const QString& type);
-      void furyPlotInput();
-      void furyMinChanged(double val);
-      void furyMaxChanged(double val);
-      void furyUpdateRS(QtProperty* prop, double val);
-
-      // Fourier Transform Fit
-      void furyfitTypeSelection(int index);
-      void furyfitPlotInput();
-      void furyfitXMinSelected(double val);
-      void furyfitXMaxSelected(double val);
-      void furyfitBackgroundSelected(double val);
-      void furyfitRangePropChanged(QtProperty*, double);
-      void furyfitSequential();
-      void furyfitPlotGuess(QtProperty*);
-
-      // Convolution Fit
-      void confitTypeSelection(int index);
-      void confitBgTypeSelection(int index);
-      void confitPlotInput();
-      void confitPlotGuess(QtProperty*);
-      void confitSequential();
-      void confitMinChanged(double);
-      void confitMaxChanged(double);
-      void confitBackgLevel(double);
-      void confitUpdateRS(QtProperty*, double);
-      void confitCheckBoxUpdate(QtProperty*, bool);
-      void confitHwhmChanged(double);
-      void confitHwhmUpdateRS(double);
-
-      // Absorption (Basic)
-      // (nothing for this)
-
-      // Absorption (F2PY)
-      void absf2pRun();
-      void absf2pShape(int index);
-      void absf2pUseCanChecked(bool value);
-      void absf2pTCSync();
-
-      // abscor (PolynomialCorrection based)
-      void abscorRun();
-      
-      // Common Elements
-      void openDirectoryDialog();
-      void help();
-      
-    private:
-      Ui::IndirectDataAnalysis m_uiForm;
-      int m_nDec;
-      QIntValidator* m_valInt;
-      QDoubleValidator* m_valDbl;
-            
-      QtStringPropertyManager* m_stringManager;
-      // Editor Factories
-      DoubleEditorFactory* m_dblEdFac;
-      QtCheckBoxFactory* m_blnEdFac;
-      
-      // ELASTICWINDOW MINIPLOT (prefix: 'm_elw')
-      QwtPlot* m_elwPlot;
-      MantidWidgets::RangeSelector* m_elwR1;
-      MantidWidgets::RangeSelector* m_elwR2;
-      QwtPlotCurve* m_elwDataCurve;
-      QtTreePropertyBrowser* m_elwTree;
-      QMap<QString, QtProperty*> m_elwProp;
-      QtDoublePropertyManager* m_elwDblMng;
-      QtBoolPropertyManager* m_elwBlnMng;
-      QtGroupPropertyManager* m_elwGrpMng;
-
-      // MSD Fit MiniPlot (prefix: 'm_msd')
-      QwtPlot* m_msdPlot;
-      MantidWidgets::RangeSelector* m_msdRange;
-      QwtPlotCurve* m_msdDataCurve;
-      QtTreePropertyBrowser* m_msdTree;
-      QMap<QString, QtProperty*> m_msdProp;
-      QtDoublePropertyManager* m_msdDblMng;
-
-      // Fury Miniplot
-      QwtPlot* m_furPlot;
-      MantidWidgets::RangeSelector* m_furRange;
-      QwtPlotCurve* m_furCurve;
-      QtTreePropertyBrowser* m_furTree;
-      QMap<QString, QtProperty*> m_furProp;
-      QtDoublePropertyManager* m_furDblMng;
-      bool m_furyResFileType;
-
-      // Fury Fit Member Variables (prefix 'm_ff')
-      QtTreePropertyBrowser* m_ffTree; ///< FuryFit Property Browser
-      QtGroupPropertyManager* m_groupManager;
-      QtDoublePropertyManager* m_ffDblMng;
-      QtDoublePropertyManager* m_ffRangeManager; ///< StartX and EndX for FuryFit
-      QMap<QString, QtProperty*> m_ffProp;
-      QwtPlot* m_ffPlot;
-      QwtPlotCurve* m_ffDataCurve;
-      QwtPlotCurve* m_ffFitCurve;
-      MantidQt::MantidWidgets::RangeSelector* m_ffRangeS;
-      MantidQt::MantidWidgets::RangeSelector* m_ffBackRangeS;
-      boost::shared_ptr<const Mantid::API::MatrixWorkspace> m_ffInputWS;
-      boost::shared_ptr<const Mantid::API::MatrixWorkspace> m_ffOutputWS;
-      std::string m_ffInputWSName;
-      QString m_furyfitTies;
-
-      // Confit (prefix: 'm_cf')
-      QtTreePropertyBrowser* m_cfTree;
-      QwtPlot* m_cfPlot;
-      QMap<QString, QtProperty*> m_cfProp;
-      MantidWidgets::RangeSelector* m_cfRangeS;
-      MantidWidgets::RangeSelector* m_cfBackgS;
-      MantidWidgets::RangeSelector* m_cfHwhmRange;
-      QtGroupPropertyManager* m_cfGrpMng;
-      QtDoublePropertyManager* m_cfDblMng;
-      QtBoolPropertyManager* m_cfBlnMng;
-      QwtPlotCurve* m_cfDataCurve;
-      QwtPlotCurve* m_cfCalcCurve;
-      boost::shared_ptr<const Mantid::API::MatrixWorkspace> m_cfInputWS;
-      std::string m_cfInputWSName;
-
-      /// Change Observer for ConfigService (monitors user directories)
-      Poco::NObserver<IndirectDataAnalysis, Mantid::Kernel::ConfigValChangeNotification> m_changeObserver;
-
-    };
-  }
-}
-#endif /* MANTIDQTCUSTOMINTERFACES_INDIRECTANALYSIS_H_ */
+#ifndef MANTIDQTCUSTOMINTERFACES_INDIRECTANALYSIS_H_
+#define MANTIDQTCUSTOMINTERFACES_INDIRECTANALYSIS_H_
+
+//----------------------
+// Includes
+//----------------------
+#include "ui_IndirectDataAnalysis.h"
+#include "MantidQtAPI/UserSubWindow.h"
+
+#include <Poco/NObserver.h>
+#include "MantidKernel/ConfigService.h"
+
+//----------------------
+// Forward Declarations
+//----------------------
+namespace Mantid
+{
+  namespace API
+  {
+    class MatrixWorkspace;
+    class IFitFunction;
+    class CompositeFunctionMW;
+  }
+}
+namespace MantidQt
+{
+  namespace MantidWidgets
+  {
+    class RangeSelector;
+  }
+}
+class QwtPlot;
+class QwtPlotCurve;
+class QIntValidator;
+class QDoubleValidator;
+class DoubleEditorFactory;
+class QtCheckBoxFactory;
+class QtProperty;
+class QtBoolPropertyManager;
+class QtDoublePropertyManager;
+class QtGroupPropertyManager;
+class QtStringPropertyManager;
+class QtTreePropertyBrowser;
+//----------------------
+//       End Of
+// Forward Declarations
+//----------------------
+
+namespace MantidQt
+{
+  namespace CustomInterfaces
+  {
+    class IndirectDataAnalysis : public MantidQt::API::UserSubWindow
+    {
+      Q_OBJECT
+
+    public:
+      /// The name of the interface as registered into the factory
+      static std::string name() { return "Indirect Data Analysis"; }
+      /// Default Constructor
+      IndirectDataAnalysis(QWidget *parent = 0);
+
+    private:
+      /// Initialize the layout
+      virtual void initLayout();
+      /// init python-dependent sections
+      virtual void initLocalPython();
+
+      void loadSettings();
+
+      // Tab-specific setup stages (mainly miniplots)
+      void setupElwin();
+      void setupMsd();
+      void setupFury();
+      void setupFuryFit();
+      void setupConFit();
+      void setupAbsorptionF2Py();
+      void setupAbsCor();
+
+      // Validation of user inputs
+      bool validateElwin();
+      bool validateMsd();
+      bool validateFury();
+      bool validateAbsorption();
+      bool validateAbsorptionF2Py();
+
+      // Run processes
+      void elwinRun();
+      void msdRun();
+      void furyRun();
+      void furyfitRun();
+      void confitRun();
+      void absorptionRun();
+
+      Mantid::API::CompositeFunctionMW* furyfitCreateFunction(bool tie=false);
+      Mantid::API::IFitFunction* furyfitCreateUserFunction(const QString & name, bool tie=false);
+      Mantid::API::CompositeFunctionMW* confitCreateFunction(bool tie=false);
+      QtProperty* createLorentzian(const QString &);
+      QtProperty* createExponential(const QString &);
+      QtProperty* createStretchedExp(const QString &);
+
+      void populateFunction(Mantid::API::IFitFunction*, Mantid::API::IFitFunction*, QtProperty*, int, const bool tie=false);
+      QwtPlotCurve* plotMiniplot(QwtPlot* plot, QwtPlotCurve* curve, std::string workspace, int index);
+      
+      virtual void closeEvent(QCloseEvent*);
+
+      void handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf); ///< handle POCO event
+
+    private slots:
+      void run();
+      
+      // context menu on fitting property browser
+      void fitContextMenu(const QPoint &);
+      void fixItem();
+      void unFixItem();
+
+      // ElasticWindow
+      void elwinPlotInput();
+      void elwinTwoRanges(QtProperty*, bool);
+      void elwinMinChanged(double val);
+      void elwinMaxChanged(double val);
+      void elwinUpdateRS(QtProperty* prop, double val);
+
+      // MSD Fit
+      void msdPlotInput();
+      void msdMinChanged(double val);
+      void msdMaxChanged(double val);
+      void msdUpdateRS(QtProperty* prop, double val);
+
+      // Fourier Transform
+      void furyResType(const QString& type);
+      void furyPlotInput();
+      void furyMinChanged(double val);
+      void furyMaxChanged(double val);
+      void furyUpdateRS(QtProperty* prop, double val);
+
+      // Fourier Transform Fit
+      void furyfitTypeSelection(int index);
+      void furyfitPlotInput();
+      void furyfitXMinSelected(double val);
+      void furyfitXMaxSelected(double val);
+      void furyfitBackgroundSelected(double val);
+      void furyfitRangePropChanged(QtProperty*, double);
+      void furyfitSequential();
+      void furyfitPlotGuess(QtProperty*);
+
+      // Convolution Fit
+      void confitTypeSelection(int index);
+      void confitBgTypeSelection(int index);
+      void confitPlotInput();
+      void confitPlotGuess(QtProperty*);
+      void confitSequential();
+      void confitMinChanged(double);
+      void confitMaxChanged(double);
+      void confitBackgLevel(double);
+      void confitUpdateRS(QtProperty*, double);
+      void confitCheckBoxUpdate(QtProperty*, bool);
+      void confitHwhmChanged(double);
+      void confitHwhmUpdateRS(double);
+
+      // Absorption (Basic)
+      // (nothing for this)
+
+      // Absorption (F2PY)
+      void absf2pRun();
+      void absf2pShape(int index);
+      void absf2pUseCanChecked(bool value);
+      void absf2pTCSync();
+
+      // abscor (PolynomialCorrection based)
+      void abscorRun();
+      
+      // Common Elements
+      void openDirectoryDialog();
+      void help();
+      
+    private:
+      Ui::IndirectDataAnalysis m_uiForm;
+      int m_nDec;
+      QIntValidator* m_valInt;
+      QDoubleValidator* m_valDbl;
+            
+      QtStringPropertyManager* m_stringManager;
+      // Editor Factories
+      DoubleEditorFactory* m_dblEdFac;
+      QtCheckBoxFactory* m_blnEdFac;
+      
+      // ELASTICWINDOW MINIPLOT (prefix: 'm_elw')
+      QwtPlot* m_elwPlot;
+      MantidWidgets::RangeSelector* m_elwR1;
+      MantidWidgets::RangeSelector* m_elwR2;
+      QwtPlotCurve* m_elwDataCurve;
+      QtTreePropertyBrowser* m_elwTree;
+      QMap<QString, QtProperty*> m_elwProp;
+      QtDoublePropertyManager* m_elwDblMng;
+      QtBoolPropertyManager* m_elwBlnMng;
+      QtGroupPropertyManager* m_elwGrpMng;
+
+      // MSD Fit MiniPlot (prefix: 'm_msd')
+      QwtPlot* m_msdPlot;
+      MantidWidgets::RangeSelector* m_msdRange;
+      QwtPlotCurve* m_msdDataCurve;
+      QtTreePropertyBrowser* m_msdTree;
+      QMap<QString, QtProperty*> m_msdProp;
+      QtDoublePropertyManager* m_msdDblMng;
+
+      // Fury Miniplot
+      QwtPlot* m_furPlot;
+      MantidWidgets::RangeSelector* m_furRange;
+      QwtPlotCurve* m_furCurve;
+      QtTreePropertyBrowser* m_furTree;
+      QMap<QString, QtProperty*> m_furProp;
+      QtDoublePropertyManager* m_furDblMng;
+      bool m_furyResFileType;
+
+      // Fury Fit Member Variables (prefix 'm_ff')
+      QtTreePropertyBrowser* m_ffTree; ///< FuryFit Property Browser
+      QtGroupPropertyManager* m_groupManager;
+      QtDoublePropertyManager* m_ffDblMng;
+      QtDoublePropertyManager* m_ffRangeManager; ///< StartX and EndX for FuryFit
+      QMap<QString, QtProperty*> m_ffProp;
+      QwtPlot* m_ffPlot;
+      QwtPlotCurve* m_ffDataCurve;
+      QwtPlotCurve* m_ffFitCurve;
+      MantidQt::MantidWidgets::RangeSelector* m_ffRangeS;
+      MantidQt::MantidWidgets::RangeSelector* m_ffBackRangeS;
+      boost::shared_ptr<const Mantid::API::MatrixWorkspace> m_ffInputWS;
+      boost::shared_ptr<const Mantid::API::MatrixWorkspace> m_ffOutputWS;
+      std::string m_ffInputWSName;
+      QString m_furyfitTies;
+
+      // Confit (prefix: 'm_cf')
+      QtTreePropertyBrowser* m_cfTree;
+      QwtPlot* m_cfPlot;
+      QMap<QString, QtProperty*> m_cfProp;
+      MantidWidgets::RangeSelector* m_cfRangeS;
+      MantidWidgets::RangeSelector* m_cfBackgS;
+      MantidWidgets::RangeSelector* m_cfHwhmRange;
+      QtGroupPropertyManager* m_cfGrpMng;
+      QtDoublePropertyManager* m_cfDblMng;
+      QtBoolPropertyManager* m_cfBlnMng;
+      QwtPlotCurve* m_cfDataCurve;
+      QwtPlotCurve* m_cfCalcCurve;
+      boost::shared_ptr<const Mantid::API::MatrixWorkspace> m_cfInputWS;
+      std::string m_cfInputWSName;
+
+      /// Change Observer for ConfigService (monitors user directories)
+      Poco::NObserver<IndirectDataAnalysis, Mantid::Kernel::ConfigValChangeNotification> m_changeObserver;
+
+    };
+  }
+}
+#endif /* MANTIDQTCUSTOMINTERFACES_INDIRECTANALYSIS_H_ */
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IndirectDiffractionReduction.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IndirectDiffractionReduction.h
index 171cebf839c976cfca8e404a8b01d598f538e54d..59542cf8e9256c32229edaa68167b3e6ace4a37e 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IndirectDiffractionReduction.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/IndirectDiffractionReduction.h
@@ -1,58 +1,58 @@
-#ifndef MANTIDQTCUSTOMINTERFACES_INDIRECTDIFFRACTIONREDUCTION_H_
-#define MANTIDQTCUSTOMINTERFACES_INDIRECTDIFFRACTIONREDUCTION_H_
-
-//----------------------
-// Includes
-//----------------------
-#include "ui_IndirectDiffractionReduction.h"
-#include "MantidQtAPI/UserSubWindow.h"
-
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-class IndirectDiffractionReduction : public MantidQt::API::UserSubWindow
-{
-  Q_OBJECT
-
-public:
-  /// The name of the interface as registered into the factory
-  static std::string name() { return "Indirect Diffraction"; }
-
-public:
-  /// Default Constructor
-  IndirectDiffractionReduction(QWidget *parent = 0);
-
-public slots:
-  void demonRun();
-  
-  void instrumentSelected(int);
-  void reflectionSelected(int);
-
-  void correctionSelected(int);
-  void groupingSelected(const QString & selected);
-
-  void openDirectoryDialog();
-  void help();
-
-private:
-  /// Initialize the layout
-  virtual void initLayout();
-  void initLocalPython();
-  void loadSettings();
-
-  bool validateDemon();
-  QString grouping();
-
-private:
-  /// The form generated using Qt Designer
-  Ui::IndirectDiffractionReduction m_uiForm;
-  /// Whether to do "real" diffraction stuff (AlignDetectors, etc)
-  bool m_realDiffraction;
-
-};
-
-}
-}
-
-#endif //MANTIDQTCUSTOMINTERFACES_INDIRECTDIFFRACTIONREDUCTION_H_
+#ifndef MANTIDQTCUSTOMINTERFACES_INDIRECTDIFFRACTIONREDUCTION_H_
+#define MANTIDQTCUSTOMINTERFACES_INDIRECTDIFFRACTIONREDUCTION_H_
+
+//----------------------
+// Includes
+//----------------------
+#include "ui_IndirectDiffractionReduction.h"
+#include "MantidQtAPI/UserSubWindow.h"
+
+namespace MantidQt
+{
+namespace CustomInterfaces
+{
+class IndirectDiffractionReduction : public MantidQt::API::UserSubWindow
+{
+  Q_OBJECT
+
+public:
+  /// The name of the interface as registered into the factory
+  static std::string name() { return "Indirect Diffraction"; }
+
+public:
+  /// Default Constructor
+  IndirectDiffractionReduction(QWidget *parent = 0);
+
+public slots:
+  void demonRun();
+  
+  void instrumentSelected(int);
+  void reflectionSelected(int);
+
+  void correctionSelected(int);
+  void groupingSelected(const QString & selected);
+
+  void openDirectoryDialog();
+  void help();
+
+private:
+  /// Initialize the layout
+  virtual void initLayout();
+  void initLocalPython();
+  void loadSettings();
+
+  bool validateDemon();
+  QString grouping();
+
+private:
+  /// The form generated using Qt Designer
+  Ui::IndirectDiffractionReduction m_uiForm;
+  /// Whether to do "real" diffraction stuff (AlignDetectors, etc)
+  bool m_realDiffraction;
+
+};
+
+}
+}
+
+#endif //MANTIDQTCUSTOMINTERFACES_INDIRECTDIFFRACTIONREDUCTION_H_
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.h
index a2eb3ac54b9ae9cfad4a29ed8a1131ca885291f8..bf1131eb0e2aa9271d9b35d4ad3487fb3a6bddcc 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.h
@@ -15,7 +15,7 @@
 #include <QStringList>
 #include "Poco/NObserver.h"
 #include "MantidAPI/AnalysisDataService.h"
-#include "MantidAPI/MatrixWorkspace.h"
+#include "MantidAPI/MatrixWorkspace.h"
 #include "MantidKernel/ConfigService.h"
 
 namespace Mantid
@@ -84,8 +84,8 @@ signals:
 
 private:
   ///Mode enumeration
-  enum RunMode { SingleMode = 0, BatchMode };
-
+  enum RunMode { SingleMode = 0, BatchMode };
+
   /// mask type
   enum MaskType{ DefaultMask=0,TimeMask=1,PixelMask=2};
 
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/ConvertToEnergy.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/ConvertToEnergy.cpp
index 02acf42b7ba3adb7d0d75a34ce4e41043f365354..d2b6b258d2ee2a2065c9c60b2f15c1e917ac5252 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/ConvertToEnergy.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/ConvertToEnergy.cpp
@@ -1,391 +1,391 @@
-//----------------------
-// Includes
-//----------------------
-#include "MantidQtCustomInterfaces/ConvertToEnergy.h"
-#include "MantidQtCustomInterfaces/Homer.h" // user interface for Direct instruments
-#include "MantidQtCustomInterfaces/Indirect.h" // user interface for Indirect instruments
-
-#include "MantidQtAPI/ManageUserDirectories.h"
-
-#include "MantidKernel/ConfigService.h"
-#include "MantidAPI/AnalysisDataService.h"
-
-#include <QMessageBox>
-#include <QDir>
-
-#include <QDesktopServices>
-#include <QUrl>
-
-//Add this class to the list of specialised dialogs in this namespace
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    DECLARE_SUBWINDOW(ConvertToEnergy);
-  }
-}
-
-using namespace MantidQt::CustomInterfaces;
-
-//----------------------
-// Public member functions
-//----------------------
-
-/**
- * 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.
- */
-ConvertToEnergy::ConvertToEnergy(QWidget *parent) :
-  UserSubWindow(parent), m_directInstruments(NULL), m_indirectInstruments(NULL), 
-  m_curInterfaceSetup(""), m_curEmodeType(ConvertToEnergy::Undefined), m_settingsGroup("CustomInterfaces/ConvertToEnergy")
-{
-}
-
-/**
- * Destructor
- */
-ConvertToEnergy::~ConvertToEnergy()
-{
-  saveSettings();
-}
-
-/**
- * On user clicking the "help" button on the interface, directs their request to the relevant
- * interface's helpClicked() function.
- */
-void ConvertToEnergy::helpClicked()
-{
-  switch ( m_curEmodeType )
-  {
-  case Direct:
-    m_directInstruments->helpClicked();
-    break;
-  case InDirect:
-    m_indirectInstruments->helpClicked();
-    break;
-  default:
-    QDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/") +
-				   "ConvertToEnergy"));
-  }
-}
-
-/**
- * This is the function called when the "Run" button is clicked. It will call the relevent function
- * in the subclass.
- */
-void ConvertToEnergy::runClicked()
-{
-  switch ( m_curEmodeType )
-  {
-  case Direct:
-    m_directInstruments->runClicked();
-    break;
-  case InDirect:
-    m_indirectInstruments->runClicked();
-    break;
-  case Undefined:
-  default:
-    showInformationBox("This interface is not configured to use the instrument you have selected.\nPlease check your instrument selection.");
-  }
-}
-
-/**
- * Sets up Qt UI file and connects signals, slots. 
- */
-void ConvertToEnergy::initLayout()
-{
-  m_uiForm.setupUi(this);
-  m_curInterfaceSetup = "";
-  m_curEmodeType = Undefined;
-
-  // Assume we get a incompatiable instrument to start with
-  m_uiForm.pbRun->setEnabled(false);
-
-  // 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&)));
-
-  // 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()));
-
-}
-
-/**
- * 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 ConvertToEnergy::initLocalPython()
-{
-  // select starting instrument
-  readSettings();
-
-  if ( m_curInterfaceSetup == "" )
-  {
-    userSelectInstrument(m_uiForm.cbInst->currentText());
-  }
-}
-
-/**
- * Read settings from the persistent store
- */
-void ConvertToEnergy::readSettings()
-{
-  QSettings settings;
-  settings.beginGroup(m_settingsGroup);
-  QString instrName = settings.value("instrument-name", "").toString();
-  settings.endGroup();
-
-  setDefaultInstrument(instrName);
-}
-
-/**
- * Save settings to a persistent storage
- */
-void ConvertToEnergy::saveSettings()
-{
-  QSettings settings;
-  settings.beginGroup(m_settingsGroup);
-  QString instrName;
-  if( m_curEmodeType == Undefined )
-  {
-    instrName = "";
-  }
-  else
-  {
-    instrName = m_uiForm.cbInst->currentText();
-  }
-
-  settings.setValue("instrument-name", instrName);
-  settings.endGroup();
-}
-
-/**
- * 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 ConvertToEnergy::setDefaultInstrument(const QString & name)
-{
-  if( name.isEmpty() ) return;
-
-  int index = m_uiForm.cbInst->findText(name);
-  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).
- * @param name :: name of the instrument from the QComboBox
- */
-void ConvertToEnergy::instrumentSelectChanged(const QString& name)
-{
-  QString defFile = getIDFPath(name);
-
-  if ( defFile == "" )
-  {
-    m_curEmodeType = Undefined;
-    return;
-  }
-
-  DeltaEMode desired = instrumentDeltaEMode(defFile);
-
-  if ( desired == Undefined )
-  {
-    m_curEmodeType = Undefined;
-    QMessageBox::warning(this, "MantidPlot", "Selected instrument (" + name + ") does not have a parameter to signify it's deltaE-mode");
-    m_uiForm.cbInst->blockSignals(true);
-    m_uiForm.cbInst->setCurrentIndex(m_uiForm.cbInst->findText(m_curInterfaceSetup));
-    m_uiForm.cbInst->blockSignals(false);
-    return;
-  }
-
-  DeltaEMode current;
-
-  if ( m_curInterfaceSetup == "" )
-  {
-    current = Undefined;
-  }
-  else
-  {
-    current = DeltaEMode(m_uiForm.swInstrument->currentIndex());
-  }
-
-  if ( desired != current || m_curInterfaceSetup != name )
-  {
-    changeInterface(desired);
-  }
-
-  m_curInterfaceSetup = name;
-  m_curEmodeType = desired;
-  m_uiForm.pbRun->setEnabled(true);
-}
-
-/**
- * Gets the path to the selected instrument's Instrument Definition File (IDF), if the instrument has a parameter file.
- * @param prefix :: the instrument's name from the QComboBox
- * @return A string containing the path to the IDF, or an empty string if no parameter file exists.
- */
-QString ConvertToEnergy::getIDFPath(const QString& prefix)
-{
-  QString paramfile_dir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("parameterDefinition.directory"));
-  QDir paramdir(paramfile_dir);
-  paramdir.setFilter(QDir::Files);
-  QStringList filters;
-  filters << prefix + "*_Parameters.xml";
-  paramdir.setNameFilters(filters);
-
-  QStringList entries = paramdir.entryList();
-  QString defFilePrefix;
-
-  if( entries.isEmpty() )
-  {
-    QMessageBox::warning(this, "MantidPlot", "Selected instrument (" + prefix + ") does not have a parameter file.\nCannot run analysis");
-    m_uiForm.cbInst->blockSignals(true);
-    m_uiForm.cbInst->setCurrentIndex(m_uiForm.cbInst->findText(m_curInterfaceSetup));
-    m_uiForm.cbInst->blockSignals(false);
-    return "";
-  }
-  else
-  {
-    defFilePrefix = entries[(entries.count()-1)];
-    defFilePrefix.chop(15); // cut "_Parameters.xml" off the string
-  }
-
-  QString defFile = paramdir.filePath(defFilePrefix + "_Definition.xml");
-  return defFile;
-}
-
-/**
- * Runs a Python script to discover whether the selected instrument is direct or indirect.
- * @param defFile :: path to instrument definition file.
- * @return 'Undefined' deltaE-mode not found, otherwise the relevant value ('Direct' or 'InDirect')
- */
-ConvertToEnergy::DeltaEMode ConvertToEnergy::instrumentDeltaEMode(const QString& defFile)
-{
-  QString pyInput =
-    "from mantidsimple import *\n"
-    "import sys\n"
-    "ws_name = '__empty_%2'\n"
-    "if not mtd.workspaceExists(ws_name):\n"
-    "  LoadEmptyInstrument(r'%1', ws_name)\n"
-    "instrument = mtd[ws_name].getInstrument()\n"
-    "try:\n"
-    "    print instrument.getStringParameter('deltaE-mode')[0]\n"
-    "except IndexError, message:\n" // the above line will raise an IndexError in Python
-    "    print ''\n"; // if the instrument doesn't have this parameter.
-
-  pyInput = pyInput.arg(defFile,m_uiForm.cbInst->currentText());
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-
-  if ( pyOutput == "direct" )
-  {
-    return Direct;
-  }
-  else if ( pyOutput == "indirect" )
-  {
-    return InDirect;
-  }
-  else
-  {
-    return Undefined;
-  }
-}
-
-/**
- * Makes the changes necessary for switching between Direct and Indirect interfaces.
- * @param desired :: The interface format that is to be changed to.
- */
-void ConvertToEnergy::changeInterface(DeltaEMode desired)
-{
-  QString curInstPrefix = m_uiForm.cbInst->itemData(m_uiForm.cbInst->currentIndex()).toString();;
-  switch ( desired )
-  {
-  case Direct:
-    m_uiForm.tabWidget->removeTab(m_uiForm.tabWidget->indexOf(m_uiForm.tabCalibration));
-    m_uiForm.tabWidget->removeTab(m_uiForm.tabWidget->indexOf(m_uiForm.tabSofQW));
-    m_uiForm.tabWidget->removeTab(m_uiForm.tabWidget->indexOf(m_uiForm.tabTimeSlice));
-    m_uiForm.tabWidget->addTab(m_uiForm.tabDiagnoseDetectors, "Diagnose Detectors");
-    m_uiForm.tabWidget->addTab(m_uiForm.tabAbsoluteUnits, "Absolute Units");
-    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&)),
-	      this, SIGNAL(runAsPythonScript(const QString&)));
-      m_directInstruments->initializeLocalPython();
-    }
-    m_directInstruments->setIDFValues(curInstPrefix);
-    break;
-  case InDirect:
-    m_uiForm.tabWidget->removeTab(m_uiForm.tabWidget->indexOf(m_uiForm.tabDiagnoseDetectors));
-    m_uiForm.tabWidget->removeTab(m_uiForm.tabWidget->indexOf(m_uiForm.tabAbsoluteUnits));
-    m_uiForm.tabWidget->addTab(m_uiForm.tabCalibration, "Calibration");
-    m_uiForm.tabWidget->addTab(m_uiForm.tabTimeSlice, "Diagnostics");
-    m_uiForm.tabWidget->addTab(m_uiForm.tabSofQW, "S(Q, w)");
-    if ( m_indirectInstruments == NULL )
-    {
-      m_indirectInstruments = new Indirect(qobject_cast<QWidget*>(this->parent()), m_uiForm);
-      m_indirectInstruments->initLayout();
-      connect(m_indirectInstruments, SIGNAL(runAsPythonScript(const QString&)),
-	      this, SIGNAL(runAsPythonScript(const QString&)));
-      m_indirectInstruments->initializeLocalPython();
-    }
-    m_indirectInstruments->setIDFValues(curInstPrefix);
-    break;
-  default:
-    QMessageBox::information(this, "MantidPlot", "Undefined interface type detected.");
-    return;
-  }
-  m_uiForm.swInstrument->setCurrentIndex(desired);
-  m_uiForm.swInputFiles->setCurrentIndex(desired);
-  m_uiForm.swAnalysis->setCurrentIndex(desired);
-  m_uiForm.swConvertToEnergy->setCurrentIndex(desired);
-  m_uiForm.swRebin->setCurrentIndex(desired);
-  m_uiForm.swSave->setCurrentIndex(desired);
-}
-
-/**
- * If the instrument selection has changed, calls instrumentSelectChanged
- * @param prefix :: instrument name from QComboBox object
- */
-void ConvertToEnergy::userSelectInstrument(const QString& prefix) 
-{
-  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) )
-    {
-      dataStore.remove(ws_name);
-    }
-
-    m_uiForm.pbRun->setEnabled(false);
-    m_uiForm.cbInst->setEnabled(false);
-    instrumentSelectChanged(prefix);
-    m_uiForm.pbRun->setEnabled(true);
-    m_uiForm.cbInst->setEnabled(true);
-  }
-  if( m_curEmodeType != InDirect )
-  {
-    m_uiForm.pbRun->setEnabled(true);
-  }
-}
-
-void ConvertToEnergy::openDirectoryDialog()
-{
-  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
-  ad->show();
-  ad->setFocus();
-}
+//----------------------
+// Includes
+//----------------------
+#include "MantidQtCustomInterfaces/ConvertToEnergy.h"
+#include "MantidQtCustomInterfaces/Homer.h" // user interface for Direct instruments
+#include "MantidQtCustomInterfaces/Indirect.h" // user interface for Indirect instruments
+
+#include "MantidQtAPI/ManageUserDirectories.h"
+
+#include "MantidKernel/ConfigService.h"
+#include "MantidAPI/AnalysisDataService.h"
+
+#include <QMessageBox>
+#include <QDir>
+
+#include <QDesktopServices>
+#include <QUrl>
+
+//Add this class to the list of specialised dialogs in this namespace
+namespace MantidQt
+{
+  namespace CustomInterfaces
+  {
+    DECLARE_SUBWINDOW(ConvertToEnergy);
+  }
+}
+
+using namespace MantidQt::CustomInterfaces;
+
+//----------------------
+// Public member functions
+//----------------------
+
+/**
+ * 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.
+ */
+ConvertToEnergy::ConvertToEnergy(QWidget *parent) :
+  UserSubWindow(parent), m_directInstruments(NULL), m_indirectInstruments(NULL), 
+  m_curInterfaceSetup(""), m_curEmodeType(ConvertToEnergy::Undefined), m_settingsGroup("CustomInterfaces/ConvertToEnergy")
+{
+}
+
+/**
+ * Destructor
+ */
+ConvertToEnergy::~ConvertToEnergy()
+{
+  saveSettings();
+}
+
+/**
+ * On user clicking the "help" button on the interface, directs their request to the relevant
+ * interface's helpClicked() function.
+ */
+void ConvertToEnergy::helpClicked()
+{
+  switch ( m_curEmodeType )
+  {
+  case Direct:
+    m_directInstruments->helpClicked();
+    break;
+  case InDirect:
+    m_indirectInstruments->helpClicked();
+    break;
+  default:
+    QDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/") +
+				   "ConvertToEnergy"));
+  }
+}
+
+/**
+ * This is the function called when the "Run" button is clicked. It will call the relevent function
+ * in the subclass.
+ */
+void ConvertToEnergy::runClicked()
+{
+  switch ( m_curEmodeType )
+  {
+  case Direct:
+    m_directInstruments->runClicked();
+    break;
+  case InDirect:
+    m_indirectInstruments->runClicked();
+    break;
+  case Undefined:
+  default:
+    showInformationBox("This interface is not configured to use the instrument you have selected.\nPlease check your instrument selection.");
+  }
+}
+
+/**
+ * Sets up Qt UI file and connects signals, slots. 
+ */
+void ConvertToEnergy::initLayout()
+{
+  m_uiForm.setupUi(this);
+  m_curInterfaceSetup = "";
+  m_curEmodeType = Undefined;
+
+  // Assume we get a incompatiable instrument to start with
+  m_uiForm.pbRun->setEnabled(false);
+
+  // 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&)));
+
+  // 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()));
+
+}
+
+/**
+ * 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 ConvertToEnergy::initLocalPython()
+{
+  // select starting instrument
+  readSettings();
+
+  if ( m_curInterfaceSetup == "" )
+  {
+    userSelectInstrument(m_uiForm.cbInst->currentText());
+  }
+}
+
+/**
+ * Read settings from the persistent store
+ */
+void ConvertToEnergy::readSettings()
+{
+  QSettings settings;
+  settings.beginGroup(m_settingsGroup);
+  QString instrName = settings.value("instrument-name", "").toString();
+  settings.endGroup();
+
+  setDefaultInstrument(instrName);
+}
+
+/**
+ * Save settings to a persistent storage
+ */
+void ConvertToEnergy::saveSettings()
+{
+  QSettings settings;
+  settings.beginGroup(m_settingsGroup);
+  QString instrName;
+  if( m_curEmodeType == Undefined )
+  {
+    instrName = "";
+  }
+  else
+  {
+    instrName = m_uiForm.cbInst->currentText();
+  }
+
+  settings.setValue("instrument-name", instrName);
+  settings.endGroup();
+}
+
+/**
+ * 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 ConvertToEnergy::setDefaultInstrument(const QString & name)
+{
+  if( name.isEmpty() ) return;
+
+  int index = m_uiForm.cbInst->findText(name);
+  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).
+ * @param name :: name of the instrument from the QComboBox
+ */
+void ConvertToEnergy::instrumentSelectChanged(const QString& name)
+{
+  QString defFile = getIDFPath(name);
+
+  if ( defFile == "" )
+  {
+    m_curEmodeType = Undefined;
+    return;
+  }
+
+  DeltaEMode desired = instrumentDeltaEMode(defFile);
+
+  if ( desired == Undefined )
+  {
+    m_curEmodeType = Undefined;
+    QMessageBox::warning(this, "MantidPlot", "Selected instrument (" + name + ") does not have a parameter to signify it's deltaE-mode");
+    m_uiForm.cbInst->blockSignals(true);
+    m_uiForm.cbInst->setCurrentIndex(m_uiForm.cbInst->findText(m_curInterfaceSetup));
+    m_uiForm.cbInst->blockSignals(false);
+    return;
+  }
+
+  DeltaEMode current;
+
+  if ( m_curInterfaceSetup == "" )
+  {
+    current = Undefined;
+  }
+  else
+  {
+    current = DeltaEMode(m_uiForm.swInstrument->currentIndex());
+  }
+
+  if ( desired != current || m_curInterfaceSetup != name )
+  {
+    changeInterface(desired);
+  }
+
+  m_curInterfaceSetup = name;
+  m_curEmodeType = desired;
+  m_uiForm.pbRun->setEnabled(true);
+}
+
+/**
+ * Gets the path to the selected instrument's Instrument Definition File (IDF), if the instrument has a parameter file.
+ * @param prefix :: the instrument's name from the QComboBox
+ * @return A string containing the path to the IDF, or an empty string if no parameter file exists.
+ */
+QString ConvertToEnergy::getIDFPath(const QString& prefix)
+{
+  QString paramfile_dir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("parameterDefinition.directory"));
+  QDir paramdir(paramfile_dir);
+  paramdir.setFilter(QDir::Files);
+  QStringList filters;
+  filters << prefix + "*_Parameters.xml";
+  paramdir.setNameFilters(filters);
+
+  QStringList entries = paramdir.entryList();
+  QString defFilePrefix;
+
+  if( entries.isEmpty() )
+  {
+    QMessageBox::warning(this, "MantidPlot", "Selected instrument (" + prefix + ") does not have a parameter file.\nCannot run analysis");
+    m_uiForm.cbInst->blockSignals(true);
+    m_uiForm.cbInst->setCurrentIndex(m_uiForm.cbInst->findText(m_curInterfaceSetup));
+    m_uiForm.cbInst->blockSignals(false);
+    return "";
+  }
+  else
+  {
+    defFilePrefix = entries[(entries.count()-1)];
+    defFilePrefix.chop(15); // cut "_Parameters.xml" off the string
+  }
+
+  QString defFile = paramdir.filePath(defFilePrefix + "_Definition.xml");
+  return defFile;
+}
+
+/**
+ * Runs a Python script to discover whether the selected instrument is direct or indirect.
+ * @param defFile :: path to instrument definition file.
+ * @return 'Undefined' deltaE-mode not found, otherwise the relevant value ('Direct' or 'InDirect')
+ */
+ConvertToEnergy::DeltaEMode ConvertToEnergy::instrumentDeltaEMode(const QString& defFile)
+{
+  QString pyInput =
+    "from mantidsimple import *\n"
+    "import sys\n"
+    "ws_name = '__empty_%2'\n"
+    "if not mtd.workspaceExists(ws_name):\n"
+    "  LoadEmptyInstrument(r'%1', ws_name)\n"
+    "instrument = mtd[ws_name].getInstrument()\n"
+    "try:\n"
+    "    print instrument.getStringParameter('deltaE-mode')[0]\n"
+    "except IndexError, message:\n" // the above line will raise an IndexError in Python
+    "    print ''\n"; // if the instrument doesn't have this parameter.
+
+  pyInput = pyInput.arg(defFile,m_uiForm.cbInst->currentText());
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+
+  if ( pyOutput == "direct" )
+  {
+    return Direct;
+  }
+  else if ( pyOutput == "indirect" )
+  {
+    return InDirect;
+  }
+  else
+  {
+    return Undefined;
+  }
+}
+
+/**
+ * Makes the changes necessary for switching between Direct and Indirect interfaces.
+ * @param desired :: The interface format that is to be changed to.
+ */
+void ConvertToEnergy::changeInterface(DeltaEMode desired)
+{
+  QString curInstPrefix = m_uiForm.cbInst->itemData(m_uiForm.cbInst->currentIndex()).toString();;
+  switch ( desired )
+  {
+  case Direct:
+    m_uiForm.tabWidget->removeTab(m_uiForm.tabWidget->indexOf(m_uiForm.tabCalibration));
+    m_uiForm.tabWidget->removeTab(m_uiForm.tabWidget->indexOf(m_uiForm.tabSofQW));
+    m_uiForm.tabWidget->removeTab(m_uiForm.tabWidget->indexOf(m_uiForm.tabTimeSlice));
+    m_uiForm.tabWidget->addTab(m_uiForm.tabDiagnoseDetectors, "Diagnose Detectors");
+    m_uiForm.tabWidget->addTab(m_uiForm.tabAbsoluteUnits, "Absolute Units");
+    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&)),
+	      this, SIGNAL(runAsPythonScript(const QString&)));
+      m_directInstruments->initializeLocalPython();
+    }
+    m_directInstruments->setIDFValues(curInstPrefix);
+    break;
+  case InDirect:
+    m_uiForm.tabWidget->removeTab(m_uiForm.tabWidget->indexOf(m_uiForm.tabDiagnoseDetectors));
+    m_uiForm.tabWidget->removeTab(m_uiForm.tabWidget->indexOf(m_uiForm.tabAbsoluteUnits));
+    m_uiForm.tabWidget->addTab(m_uiForm.tabCalibration, "Calibration");
+    m_uiForm.tabWidget->addTab(m_uiForm.tabTimeSlice, "Diagnostics");
+    m_uiForm.tabWidget->addTab(m_uiForm.tabSofQW, "S(Q, w)");
+    if ( m_indirectInstruments == NULL )
+    {
+      m_indirectInstruments = new Indirect(qobject_cast<QWidget*>(this->parent()), m_uiForm);
+      m_indirectInstruments->initLayout();
+      connect(m_indirectInstruments, SIGNAL(runAsPythonScript(const QString&)),
+	      this, SIGNAL(runAsPythonScript(const QString&)));
+      m_indirectInstruments->initializeLocalPython();
+    }
+    m_indirectInstruments->setIDFValues(curInstPrefix);
+    break;
+  default:
+    QMessageBox::information(this, "MantidPlot", "Undefined interface type detected.");
+    return;
+  }
+  m_uiForm.swInstrument->setCurrentIndex(desired);
+  m_uiForm.swInputFiles->setCurrentIndex(desired);
+  m_uiForm.swAnalysis->setCurrentIndex(desired);
+  m_uiForm.swConvertToEnergy->setCurrentIndex(desired);
+  m_uiForm.swRebin->setCurrentIndex(desired);
+  m_uiForm.swSave->setCurrentIndex(desired);
+}
+
+/**
+ * If the instrument selection has changed, calls instrumentSelectChanged
+ * @param prefix :: instrument name from QComboBox object
+ */
+void ConvertToEnergy::userSelectInstrument(const QString& prefix) 
+{
+  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) )
+    {
+      dataStore.remove(ws_name);
+    }
+
+    m_uiForm.pbRun->setEnabled(false);
+    m_uiForm.cbInst->setEnabled(false);
+    instrumentSelectChanged(prefix);
+    m_uiForm.pbRun->setEnabled(true);
+    m_uiForm.cbInst->setEnabled(true);
+  }
+  if( m_curEmodeType != InDirect )
+  {
+    m_uiForm.pbRun->setEnabled(true);
+  }
+}
+
+void ConvertToEnergy::openDirectoryDialog()
+{
+  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
+  ad->show();
+  ad->setFocus();
+}
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect.cpp
index fcf5e26f82b2c5ad060b7cc1caf61f6c14fe21b4..d5dfb3c24b0c7c288dd95821fc05bb0874763643 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect.cpp
@@ -1,1852 +1,1852 @@
-#include "MantidQtCustomInterfaces/Indirect.h"
-
-#include "MantidQtCustomInterfaces/Background.h"
-
-#include "MantidKernel/ConfigService.h"
-#include "MantidAPI/AnalysisDataService.h"
-#include "MantidAPI/MatrixWorkspace.h"
-
-#include <Poco/NObserver.h>
-
-#include <QUrl>
-#include <QDesktopServices>
-#include <QDir>
-#include <QFileDialog>
-#include <QInputDialog>
-#include <QLineEdit>
-
-#include "qttreepropertybrowser.h"
-#include "qtpropertymanager.h"
-#include "qteditorfactory.h"
-#include "DoubleEditorFactory.h"
-#include <QtCheckBoxFactory>
-
-using namespace MantidQt::CustomInterfaces;
-
-/**
-* This is the constructor for the Indirect Instruments Interface.
-* It is used primarily to ensure sane values for member variables.
-*/
-Indirect::Indirect(QWidget *parent, Ui::ConvertToEnergy & uiForm) : 
-UserSubWindow(parent), m_uiForm(uiForm), m_backgroundDialog(NULL), m_isDirty(true),
-  m_isDirtyRebin(true), m_bgRemoval(false), m_valInt(NULL), m_valDbl(NULL), 
-  m_changeObserver(*this, &Indirect::handleDirectoryChange),
-  // Null pointers - Calibration Tab
-  m_calCalPlot(NULL), m_calResPlot(NULL),
-  m_calCalR1(NULL), m_calCalR2(NULL), m_calResR1(NULL),
-  m_calCalCurve(NULL), m_calResCurve(NULL),
-  // Null pointers - Diagnostics Tab
-  m_sltPlot(NULL), m_sltR1(NULL), m_sltR2(NULL), m_sltDataCurve(NULL)
-
-{
-  // Constructor
-}
-/**
-* This function performs any one-time actions needed when the Inelastic interface
-* is first selected, such as connecting signals to slots.
-*/
-void Indirect::initLayout()
-{
-  Mantid::Kernel::ConfigService::Instance().addObserver(m_changeObserver);
-
-  m_settingsGroup = "CustomInterfaces/ConvertToEnergy/Indirect/";
-
-  setupCalibration(); // setup the calibration miniplots
-  setupSlice(); // setup the slice miniplot
-
-  // "Energy Transfer" tab
-  connect(m_uiForm.cbAnalyser, SIGNAL(activated(int)), this, SLOT(analyserSelected(int)));
-  connect(m_uiForm.cbReflection, SIGNAL(activated(int)), this, SLOT(reflectionSelected(int)));
-  connect(m_uiForm.cbMappingOptions, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(mappingOptionSelected(const QString&)));
-  connect(m_uiForm.pbBack_2, SIGNAL(clicked()), this, SLOT(backgroundClicked()));
-  connect(m_uiForm.pbPlotRaw, SIGNAL(clicked()), this, SLOT(plotRaw()));
-  connect(m_uiForm.rebin_pbRebin, SIGNAL(clicked()), this, SLOT(rebinData()));
-  connect(m_uiForm.rebin_ckDNR, SIGNAL(toggled(bool)), this, SLOT(rebinCheck(bool)));
-  connect(m_uiForm.ckDetailedBalance, SIGNAL(toggled(bool)), this, SLOT(detailedBalanceCheck(bool)));
-
-  connect(m_uiForm.ind_runFiles, SIGNAL(fileEditingFinished()), this, SLOT(setasDirty()));
-  connect(m_uiForm.ind_calibFile, SIGNAL(fileEditingFinished()), this, SLOT(setasDirty()));
-  connect(m_uiForm.ind_calibFile, SIGNAL(fileTextChanged(const QString &)), this, SLOT(calibFileChanged(const QString &)));
-  connect(m_uiForm.leSpectraMin, SIGNAL(editingFinished()), this, SLOT(setasDirty()));
-  connect(m_uiForm.leSpectraMax, SIGNAL(editingFinished()), this, SLOT(setasDirty()));
-  connect(m_uiForm.ckSumFiles, SIGNAL(pressed()), this, SLOT(setasDirty()));
-  connect(m_uiForm.ckUseCalib, SIGNAL(toggled(bool)), this, SLOT(useCalib(bool)));
-  connect(m_uiForm.ckCleanUp, SIGNAL(pressed()), this, SLOT(setasDirtyRebin()));
-
-  connect(m_uiForm.rebin_leELow, SIGNAL(editingFinished()), this, SLOT(setasDirtyRebin()));
-  connect(m_uiForm.rebin_leEWidth, SIGNAL(editingFinished()), this, SLOT(setasDirtyRebin()));
-  connect(m_uiForm.rebin_leEHigh, SIGNAL(editingFinished()), this, SLOT(setasDirtyRebin()));
-  connect(m_uiForm.leDetailedBalance, SIGNAL(editingFinished()), this, SLOT(setasDirtyRebin()));
-  connect(m_uiForm.ind_mapFile, SIGNAL(fileEditingFinished()), this, SLOT(setasDirtyRebin()));
-
-  connect(m_uiForm.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int)));
-
-  // "Calibration" tab
-  connect(m_uiForm.cal_pbPlot, SIGNAL(clicked()), this, SLOT(calPlotRaw()));
-  connect(m_uiForm.cal_pbPlotEnergy, SIGNAL(clicked()), this, SLOT(calPlotEnergy()));
-  connect(m_uiForm.cal_ckRES, SIGNAL(toggled(bool)), this, SLOT(resCheck(bool)));
-
-  // "SofQW" tab
-  connect(m_uiForm.sqw_ckRebinE, SIGNAL(toggled(bool)), this, SLOT(sOfQwRebinE(bool)));
-  connect(m_uiForm.sqw_cbInput, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(sOfQwInputType(const QString&)));
-  connect(m_uiForm.sqw_pbRefresh, SIGNAL(clicked()), this, SLOT(refreshWSlist()));
-  connect(m_uiForm.sqw_pbPlotInput, SIGNAL(clicked()), this, SLOT(sOfQwPlotInput()));
-
-  // "Slice" tab
-  connect(m_uiForm.slice_pbPlotRaw, SIGNAL(clicked()), this, SLOT(slicePlotRaw()));
-  connect(m_uiForm.slice_ckUseCalib, SIGNAL(toggled(bool)), this, SLOT(sliceCalib(bool)));
-
-  // create validators
-  m_valInt = new QIntValidator(this);
-  m_valDbl = new QDoubleValidator(this);
-
-  // apply validators
-  m_uiForm.leNoGroups->setValidator(m_valInt);
-  m_uiForm.leDetailedBalance->setValidator(m_valInt);
-  m_uiForm.leSpectraMin->setValidator(m_valInt);
-  m_uiForm.leSpectraMax->setValidator(m_valInt);
-  m_uiForm.rebin_leELow->setValidator(m_valDbl);
-  m_uiForm.rebin_leEWidth->setValidator(m_valDbl);
-  m_uiForm.rebin_leEHigh->setValidator(m_valDbl);
-  
-  m_uiForm.sqw_leELow->setValidator(m_valDbl);
-  m_uiForm.sqw_leEWidth->setValidator(m_valDbl);
-  m_uiForm.sqw_leEHigh->setValidator(m_valDbl);
-  m_uiForm.sqw_leQLow->setValidator(m_valDbl);
-  m_uiForm.sqw_leQWidth->setValidator(m_valDbl);
-  m_uiForm.sqw_leQHigh->setValidator(m_valDbl);
-
-  // set default values for save formats
-  m_uiForm.save_ckSPE->setChecked(false);
-  m_uiForm.save_ckNexus->setChecked(true);
-
-  loadSettings();
-
-  refreshWSlist();
-}
-/**
-* This function will hold any Python-dependent setup actions for the interface.
-*/
-void Indirect::initLocalPython()
-{
-  // Nothing to do here at the moment.
-}
-/**
-* This function opens a web browser window to the Mantid Project wiki page for this
-* interface ("Inelastic" subsection of ConvertToEnergy).
-*/
-void Indirect::helpClicked()
-{
-  QString tabName = m_uiForm.tabWidget->tabText(m_uiForm.tabWidget->currentIndex());
-  QString url = "http://www.mantidproject.org/Indirect:";
-  if ( tabName == "Energy Transfer" )
-    url += "EnergyTransfer";
-  else if ( tabName == "Calibration" )
-    url += "Calibration";
-  else if ( tabName == "Diagnostics" )
-    url += "Diagnostics";
-  else if ( tabName == "S(Q, w)" )
-    url += "SofQW";
-  QDesktopServices::openUrl(QUrl(url));
-}
-/**
-* This function will control the actions needed for the Indirect interface when the
-* "Run" button is clicked by the user.
-* @param tryToSave :: whether to try and save the output. Generally true, false when user has clicked on the "Rebin" button instead of "Run"
-*/
-void Indirect::runClicked()
-{
-  QString tabName = m_uiForm.tabWidget->tabText(m_uiForm.tabWidget->currentIndex());
-
-  if ( tabName == "Energy Transfer" )
-  {
-    runConvertToEnergy();
-  }
-  else if ( tabName == "Calibration" )
-  {
-    calibCreate();
-  }
-  else if ( tabName == "Diagnostics" )
-  {
-    sliceRun();
-  }
-  else if ( tabName == "S(Q, w)" )
-  {
-    sOfQwClicked();
-  }
-}
-
-void Indirect::runConvertToEnergy(bool tryToSave)
-{
-  if ( ! validateInput() )
-  {
-    showInformationBox("Please check the input highlighted in red.");
-    return;
-  }
-  QString grouping = createMapFile(m_uiForm.cbMappingOptions->currentText());
-  if ( grouping == "" )
-  {
-    return;
-  }
-
-  QString pyInput = "from mantidsimple import *\n"
-    "import IndirectEnergyConversion as ind\n";
-
-  if ( m_uiForm.ckVerbose->isChecked() ) pyInput += "verbose = True\n";
-  else pyInput += "verbose = False\n";
-
-  pyInput += "first = " +m_uiForm.leSpectraMin->text()+ "\n"
-    "last = " +m_uiForm.leSpectraMax->text()+ "\n"
-    "instrument = '" + m_uiForm.cbInst->currentText()+"'\n"
-    "analyser = '"+m_uiForm.cbAnalyser->currentText()+"'\n"
-    "reflection = '"+m_uiForm.cbReflection->currentText()+"'\n";
-  
-  QStringList runFiles_list = m_uiForm.ind_runFiles->getFilenames();
-  QString runFiles = runFiles_list.join("', r'");
-
-  pyInput += "rawfiles = [r'"+runFiles+"']\n"
-    "Sum = ";
-  if ( m_uiForm.ckSumFiles->isChecked() )
-  {
-    pyInput += "True\n";
-  }
-  else
-  {
-    pyInput += "False\n";
-  }
-
-  if ( m_bgRemoval )
-  {
-    QPair<double,double> bgRange = m_backgroundDialog->getRange();
-    QString startTOF, endTOF;
-    startTOF.setNum(bgRange.first, 'e');
-    endTOF.setNum(bgRange.second, 'e');
-    pyInput += "bgRemove = ["+startTOF+", "+endTOF+"]\n";
-  }
-  else
-  {
-    pyInput += "bgRemove = [0, 0]\n";
-  }
-
-  if ( m_uiForm.ckUseCalib->isChecked() )
-  {
-    QString calib = m_uiForm.ind_calibFile->getFirstFilename();
-    pyInput += "calib = r'"+calib+"'\n";
-  }
-  else
-  {
-    pyInput += "calib = ''\n";
-  }
-
-  if ( ! m_uiForm.rebin_ckDNR->isChecked() )
-  { 
-    QString rebinParam = m_uiForm.rebin_leELow->text() + ","
-      + m_uiForm.rebin_leEWidth->text() + ","
-      + m_uiForm.rebin_leEHigh->text();
-    pyInput += "rebinParam = '"+rebinParam+"'\n";
-  }
-  else
-  {
-    pyInput += "rebinParam = ''\n";
-  }
-
-  if ( m_uiForm.ckDetailedBalance->isChecked() )
-    pyInput += "tempK = "+m_uiForm.leDetailedBalance->text()+"\n";
-  else
-    pyInput += "tempK = -1\n";
-
-  pyInput += "mapfile = r'"+grouping+"'\n";
-
-  if (tryToSave)
-  {
-    pyInput += savePyCode();
-  }
-  else
-  {
-    pyInput += "fileFormats = []\n";
-  }
-
-  if ( m_uiForm.ckCleanUp->isChecked() )
-  {
-    pyInput += "clean = False\n";
-  }
-  else
-  {
-    pyInput += "clean = True\n";
-  }
-
-  if ( isDirty() )
-  {
-    pyInput += "ws_list = ind.convert_to_energy(rawfiles, mapfile, first, last,"
-      "instrument, analyser, reflection,"
-      "SumFiles=Sum, bgremove=bgRemove, tempK=tempK, calib=calib, rebinParam=rebinParam,"
-      "saveFormats=fileFormats, CleanUp=clean, Verbose=verbose)\n";
-  }
-  else if ( isDirtyRebin() )
-  {
-    pyInput += "ws_list = ind.cte_rebin(mapfile, tempK, rebinParam, analyser, reflection,"
-      "fileFormats, CleanUp=clean, Verbose=verbose)\n";
-  }
-  else if ( tryToSave ) // where all we want to do is save and/or plot output
-  {
-    pyInput +=
-      "import re\n"
-      "wslist = mantid.getWorkspaceNames()\n"
-      "save_ws = re.compile(r'_'+ana+ref+'_red')\n"
-      "ws_list = []\n"
-      "for workspace in wslist:\n"
-      "   if save_ws.search(workspace):\n"
-      "      ws_list.append(workspace)\n"
-      "ind.saveItems(ws_list, fileFormats, Verbose=verbose)\n";
-  }
-
-  // Plot Output Handling
-  switch ( m_uiForm.ind_cbPlotOutput->currentIndex() )
-  {
-  case 0: // "None"
-    break;
-  case 1: // "Spectra"
-    {
-      // Plot a spectra of the first result workspace
-      pyInput += 
-        "if ( len(ws_list) > 0 ):\n"
-        "  nSpec = mtd[ws_list[0]].getNumberHistograms()\n"
-        "  plotSpectrum(ws_list[0], range(0, nSpec))\n";
-    }
-    break;
-  case 2: // "Contour"
-    {
-      // Plot a 2D Contour Lines of the first result workspace
-      pyInput += 
-        "if ( len(ws_list) > 0 ):\n"
-        "  ws = importMatrixWorkspace(ws_list[0])\n"
-        "  ws.plotGraph2D()\n";
-    }
-    break;
-  }
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-
-  if ( pyOutput != "" )
-  {
-    if ( pyOutput == "No intermediate workspaces were found. Run with 'Keep Intermediate Workspaces' checked." )
-    {
-      isDirty(true);
-      runConvertToEnergy(tryToSave=tryToSave);
-    }
-    else
-    {
-      showInformationBox("The following error occurred:\n" + pyOutput + "\n\nAnalysis did not complete.");
-    }
-  }
-  else
-  {
-    isDirty(false);
-    isDirtyRebin(false);
-  }
-
-}
-/**
-* This function holds any steps that must be performed on the selection of an instrument,
-* for example loading values from the Instrument Definition File (IDF).
-* @param prefix :: The selected instruments prefix in Mantid.
-*/
-void Indirect::setIDFValues(const QString & prefix)
-{
-  // empty ComboBoxes, LineEdits,etc of previous values
-  m_uiForm.cbAnalyser->clear();
-  m_uiForm.cbReflection->clear();
-  clearReflectionInfo();
-
-  rebinCheck(m_uiForm.rebin_ckDNR->isChecked());
-  detailedBalanceCheck(m_uiForm.ckDetailedBalance->isChecked());
-  resCheck(m_uiForm.cal_ckRES->isChecked());
-
-  // Get list of analysers and populate cbAnalyser
-  QString pyInput = 
-    "from IndirectEnergyConversion import getInstrumentDetails\n"
-    "result = getInstrumentDetails('" + m_uiForm.cbInst->currentText() + "')\n"
-    "print result\n";
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-
-  if ( pyOutput == "" )
-  {
-    showInformationBox("Could not get list of analysers from Instrument Parameter file.");
-  }
-  else
-  {
-    QStringList analysers = pyOutput.split("\n", QString::SkipEmptyParts);
-
-    for (int i = 0; i< analysers.count(); i++ )
-    {
-      QString text; // holds Text field of combo box (name of analyser)
-
-      if ( text != "diffraction" ) // do not put diffraction into the analyser list
-      {
-
-        QVariant data; // holds Data field of combo box (list of reflections)
-
-        QStringList analyser = analysers[i].split("-", QString::SkipEmptyParts);
-
-        text = analyser[0];
-
-        if ( analyser.count() > 1 )
-        {
-          QStringList reflections = analyser[1].split(",", QString::SkipEmptyParts);
-          data = QVariant(reflections);
-          m_uiForm.cbAnalyser->addItem(text, data);
-        }
-        else
-        {
-          m_uiForm.cbAnalyser->addItem(text);
-        }
-      }
-    }
-
-    analyserSelected(m_uiForm.cbAnalyser->currentIndex());
-  }
-}
-
-void Indirect::closeEvent(QCloseEvent* close)
-{
-  (void) close;
-  //saveSettings();
-  Mantid::Kernel::ConfigService::Instance().removeObserver(m_changeObserver);
-}
-
-void Indirect::handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf)
-{
-  std::string key = pNf->key();
-  std::string preValue = pNf->preValue();
-  std::string curValue = pNf->curValue();
-
-  if ( key == "datasearch.directories" || key == "defaultsave.directory" )
-  {
-    loadSettings();
-  }
-}
-/**
-* This function clears the values of the QLineEdit objec  ts used to hold Reflection-specific
-* information.
-*/
-void Indirect::clearReflectionInfo()
-{
-  m_uiForm.leSpectraMin->clear();
-  m_uiForm.leSpectraMax->clear();
-  m_uiForm.leEfixed->clear();
-  
-  isDirty(true);
-}
-/**
-* This function creates the mapping/grouping file for the data analysis.
-* @param groupType :: Type of grouping (All, Group, Indiviual)
-* @return path to mapping file, or an empty string if file could not be created.
-*/
-QString Indirect::createMapFile(const QString& groupType)
-{
-  QString groupFile, ngroup, nspec;
-  QString ndet = "( "+m_uiForm.leSpectraMax->text()+" - "+m_uiForm.leSpectraMin->text()+") + 1";
-
-  if ( groupType == "File" )
-  {
-    groupFile = m_uiForm.ind_mapFile->getFirstFilename();
-    if ( groupFile == "" )
-    {
-      showInformationBox("You must enter a path to the .map file.");
-    }
-    return groupFile;
-  }
-  else if ( groupType == "Groups" )
-  {
-    ngroup = m_uiForm.leNoGroups->text();
-    nspec = "( " +ndet+ " ) / " +ngroup;
-  }
-  else if ( groupType == "All" )
-  {
-    return "All";
-  }
-  else if ( groupType == "Individual" )
-  {
-    return "Individual";
-  }
-
-  groupFile = m_uiForm.cbInst->itemData(m_uiForm.cbInst->currentIndex()).toString().toLower();
-  groupFile += "_" + m_uiForm.cbAnalyser->currentText() + m_uiForm.cbReflection->currentText();
-  groupFile += "_" + groupType + ".map";	
-
-  QString pyInput =
-    "import IndirectEnergyConversion as ind\n"
-    "mapfile = ind.createMappingFile('"+groupFile+"', %1, %2, %3)\n"
-    "print mapfile\n";
-  pyInput = pyInput.arg(ngroup);
-  pyInput = pyInput.arg(nspec);
-  pyInput = pyInput.arg(m_uiForm.leSpectraMin->text());
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-
-  return pyOutput;
-}
-/**
-* This function creates the Python script necessary to set the variables used for saving data
-* in the main convert_to_energy script.
-* @return python code as a string
-*/
-QString Indirect::savePyCode()
-{
-  QStringList fileFormats;
-  QString fileFormatList;
-
-  if ( m_uiForm.save_ckNexus->isChecked() )
-    fileFormats << "nxs";
-  if ( m_uiForm.save_ckSPE->isChecked() )
-    fileFormats << "spe";
-  if ( m_uiForm.save_ckNxSPE->isChecked() )
-    fileFormats << "nxspe";
-
-  if ( fileFormats.size() != 0 )
-    fileFormatList = "[ '" + fileFormats.join("', '") + "']";
-  else
-    fileFormatList = "[]";
-
-  QString pyInput =
-    "# Save File Parameters\n"
-    "fileFormats = " + fileFormatList + "\n";
-
-  return pyInput;
-}
-/**
-* This function is called after calib has run and creates a RES file for use in later analysis (Fury,etc)
-* @param file :: the input file (WBV run.raw)
-*/
-void Indirect::createRESfile(const QString& file)
-{
-  QString pyInput =
-    "from IndirectEnergyConversion import resolution\n"
-    "iconOpt = { 'first': " +QString::number(m_calDblMng->value(m_calResProp["SpecMin"]))+
-    ", 'last': " +QString::number(m_calDblMng->value(m_calResProp["SpecMax"]))+"}\n"
-
-    "instrument = '" + m_uiForm.cbInst->currentText() + "'\n"
-    "analyser = '" + m_uiForm.cbAnalyser->currentText() + "'\n"
-    "reflection = '" + m_uiForm.cbReflection->currentText() + "'\n";
-
-  if ( m_uiForm.cal_ckPlotResult->isChecked() ) { pyInput +=	"plot = True\n"; }
-  else { pyInput += "plot = False\n"; }
-
-  QString rebinParam = QString::number(m_calDblMng->value(m_calResProp["ELow"])) + "," +
-    QString::number(m_calDblMng->value(m_calResProp["EWidth"])) + "," +
-    QString::number(m_calDblMng->value(m_calResProp["EHigh"]));
-
-  QString background = "[ " +QString::number(m_calDblMng->value(m_calResProp["Start"]))+ ", " +QString::number(m_calDblMng->value(m_calResProp["End"]))+"]";
-
-  pyInput +=
-    "background = " + background + "\n"
-    "rebinParam = '" + rebinParam + "'\n"
-    "file = " + file + "\n"
-    "resolution(file, iconOpt, rebinParam, background, instrument, analyser, reflection, plotOpt = plot)\n";
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-
-  if ( pyOutput != "" )
-  {
-    showInformationBox("Unable to create RES file: \n" + pyOutput);
-  }
-}
-/**
-* This function validates the input for the Convert To Energy process, highlighting invalid items.
-* @return true if input is ok, false otherwise
-*/
-bool Indirect::validateInput()
-{
-  bool valid = true;
-  // run files input
-  if ( ! m_uiForm.ind_runFiles->isValid() )
-  {
-    valid = false;
-  }
-
-  // calib file input
-
-  if ( m_uiForm.ckUseCalib->isChecked() && !m_uiForm.ind_calibFile->isValid() )
-  {
-    valid = false;
-  }
-
-  // mapping selection
-  if (
-    ( m_uiForm.cbMappingOptions->currentText() == "Groups" && m_uiForm.leNoGroups->text() == "" ) 
-    ||
-    ( m_uiForm.cbMappingOptions->currentText() == "File" && ! m_uiForm.ind_mapFile->isValid() )
-    )
-  {
-    valid = false;
-    m_uiForm.valNoGroups->setText("*");
-  }
-  else
-  {
-    m_uiForm.valNoGroups->setText("");
-  }
-
-  // detailed balance
-  if ( m_uiForm.ckDetailedBalance->isChecked() && m_uiForm.leDetailedBalance->text() == "" )
-  {
-    valid = false;
-    m_uiForm.valDetailedBalance->setText("*");
-  }
-  else
-  {
-    m_uiForm.valDetailedBalance->setText("");
-  }
-
-  // SpectraMin/SpectraMax
-  if (
-    m_uiForm.leSpectraMin->text() == ""
-    ||
-    m_uiForm.leSpectraMax->text() == ""
-    ||
-    (
-    m_uiForm.leSpectraMin->text().toDouble() > m_uiForm.leSpectraMax->text().toDouble()
-    )
-    )
-  {
-    valid = false;
-    m_uiForm.valSpectraMin->setText("*");
-    m_uiForm.valSpectraMax->setText("*");
-  }
-  else
-  {
-    m_uiForm.valSpectraMin->setText("");
-    m_uiForm.valSpectraMax->setText("");
-  }
-
-  if ( ! m_uiForm.rebin_ckDNR->isChecked() )
-  {
-    //
-    if ( m_uiForm.rebin_leELow->text() == "" )
-    {
-      valid = false;
-      m_uiForm.valELow->setText("*");
-    }
-    else
-    {
-      m_uiForm.valELow->setText("");
-    }
-
-    if ( m_uiForm.rebin_leEWidth->text() == "" )
-    {
-      valid = false;
-      m_uiForm.valEWidth->setText("*");
-    }
-    else
-    {
-      m_uiForm.valEWidth->setText("");
-    }
-
-    if ( m_uiForm.rebin_leEHigh->text() == "" )
-    {
-      valid = false;
-      m_uiForm.valEHigh->setText("*");
-    }
-    else
-    {
-      m_uiForm.valEHigh->setText("");
-    }
-
-    if ( m_uiForm.rebin_leELow->text().toDouble() > m_uiForm.rebin_leEHigh->text().toDouble() )
-    {
-      valid = false;
-      m_uiForm.valELow->setText("*");
-      m_uiForm.valEHigh->setText("*");
-    }
-
-  }
-  else
-  {
-    m_uiForm.valELow->setText("");
-    m_uiForm.valEWidth->setText("");
-    m_uiForm.valEHigh->setText("");
-  }
-
-
-  return valid;
-}
-/**
-* Validates user input on the calibration tab.
-*/
-bool Indirect::validateCalib()
-{
-  bool valid = true;
-
-  // run number
-  if ( ! m_uiForm.cal_leRunNo->isValid() )
-  {
-    valid = false;
-  }
-
-  if ( m_uiForm.cal_ckRES->isChecked() )
-  {
-    if ( m_calDblMng->value(m_calResProp["Start"]) > m_calDblMng->value(m_calResProp["End"]) )
-    {
-      valid = false;
-    }
-
-    if ( m_calDblMng->value(m_calResProp["ELow"]) > m_calDblMng->value(m_calResProp["EHigh"]) )
-    {
-      valid = false;
-    }
-
-  }
-
-  return valid;
-}
-
-bool Indirect::validateSofQw()
-{
-  bool valid = true;
-
-  if ( m_uiForm.sqw_cbInput->currentText() == "File" )
-  {
-    if ( ! m_uiForm.sqw_inputFile->isValid() )
-    {
-      valid = false;
-    }
-  }
-  else
-  {
-    if ( m_uiForm.sqw_cbWorkspace->currentText().isEmpty() )
-    {
-      valid = false;
-      m_uiForm.sqw_valWorkspace->setText("*");
-    }
-    else
-    {
-      m_uiForm.sqw_valWorkspace->setText(" ");
-    }
-  }
-
-  if ( m_uiForm.sqw_ckRebinE->isChecked() )
-  {
-    if ( m_uiForm.sqw_leELow->text() == "" )
-    {
-      valid = false;
-      m_uiForm.sqw_valELow->setText("*");
-    }
-    else
-    {
-      m_uiForm.sqw_valELow->setText(" ");
-    }
-
-    if ( m_uiForm.sqw_leEWidth->text() == "" )
-    {
-      valid = false;
-      m_uiForm.sqw_valEWidth->setText("*");
-    }
-    else
-    {
-      m_uiForm.sqw_valEWidth->setText(" ");
-    }
-    if ( m_uiForm.sqw_leEHigh->text() == "" )
-    {
-      valid = false;
-      m_uiForm.sqw_valEHigh->setText("*");
-    }
-    else
-    {
-      m_uiForm.sqw_valEHigh->setText(" ");
-    }
-  }
-
-  if ( m_uiForm.sqw_leQLow->text() == "" )
-  {
-    valid = false;
-    m_uiForm.sqw_valQLow->setText("*");
-  }
-  else
-  {
-    m_uiForm.sqw_valQLow->setText(" ");
-  }
-
-  if ( m_uiForm.sqw_leQWidth->text() == "" )
-  {
-    valid = false;
-    m_uiForm.sqw_valQWidth->setText("*");
-  }
-  else
-  {
-    m_uiForm.sqw_valQWidth->setText(" ");
-  }
-  if ( m_uiForm.sqw_leQHigh->text() == "" )
-  {
-    valid = false;
-    m_uiForm.sqw_valQHigh->setText("*");
-  }
-  else
-  {
-    m_uiForm.sqw_valQHigh->setText(" ");
-  }
-  return valid;
-}
-
-bool Indirect::validateSlice()
-{
-  bool valid = true;
-
-  if ( ! m_uiForm.slice_inputFile->isValid() )
-  {
-    valid = false;
-  }
-
-  return valid;
-}
-/**
-* Used to check whether any changes have been made by the user to the interface.
-* @return boolean m_isDirty
-*/
-bool Indirect::isDirty()
-{
-  return m_isDirty;
-}
-/**
-* Used to set value of m_isDirty, called from each function that signifies a change in the user interface.
-* Will be set to false in functions that use the input.
-* @param state :: whether to set the value to true or false.
-*/
-void Indirect::isDirty(bool state)
-{
-  m_isDirty = state;
-}
-/**
-* Used to check whether any changes have been made by the user to the interface.
-* @return boolean m_isDirtyRebin
-*/
-bool Indirect::isDirtyRebin()
-{
-  return m_isDirtyRebin;
-}
-/**
-* Used to set value of m_isDirtyRebin, called from each function that signifies a change in the user interface.
-* Will be set to false in functions that use the input.
-* @param state :: whether to set the value to true or false.
-*/
-void Indirect::isDirtyRebin(bool state)
-{
-  m_isDirtyRebin = state;
-}
-
-void Indirect::loadSettings()
-{
-  
-  // set values of m_dataDir and m_saveDir
-  m_dataDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("datasearch.directories"));
-  m_dataDir = m_dataDir.split(";", QString::SkipEmptyParts)[0];
-  m_saveDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory"));
-
-
-  QSettings settings;
-  // Load settings for MWRunFile widgets
-  settings.beginGroup(m_settingsGroup + "DataFiles");
-  settings.setValue("last_directory", m_dataDir);
-  m_uiForm.ind_runFiles->readSettings(settings.group());
-  m_uiForm.cal_leRunNo->readSettings(settings.group());
-  m_uiForm.slice_inputFile->readSettings(settings.group());
-  settings.endGroup();
-
-  settings.beginGroup(m_settingsGroup + "ProcessedFiles");
-  settings.setValue("last_directory", m_saveDir);
-  m_uiForm.ind_calibFile->readSettings(settings.group());
-  m_uiForm.ind_mapFile->readSettings(settings.group());
-  m_uiForm.slice_calibFile->readSettings(settings.group());
-  m_uiForm.sqw_inputFile->readSettings(settings.group());
-  settings.endGroup();
-
-  // And for instrument/analyser/reflection
-}
-
-void Indirect::saveSettings()
-{
-  // The only settings that we want to keep are the instrument / analyser / reflection ones
-  // Instrument is handled in ConvertToEnergy class
-}
-
-void Indirect::setupCalibration()
-{
-  int noDec = 6;
-  // General
-  m_calDblMng = new QtDoublePropertyManager();
-  m_calGrpMng = new QtGroupPropertyManager();
-
-  /* Calib */
-  m_calCalTree = new QtTreePropertyBrowser();
-  m_uiForm.cal_treeCal->addWidget(m_calCalTree);
-
-  DoubleEditorFactory *doubleEditorFactory = new DoubleEditorFactory();
-  m_calCalTree->setFactoryForManager(m_calDblMng, doubleEditorFactory);
-
-  m_calCalProp["PeakMin"] = m_calDblMng->addProperty("Peak Min");
-  m_calCalProp["PeakMax"] = m_calDblMng->addProperty("Peak Max");
-  m_calCalProp["BackMin"] = m_calDblMng->addProperty("Back Min");
-  m_calCalProp["BackMax"] = m_calDblMng->addProperty("Back Max");
-
-  m_calCalTree->addProperty(m_calCalProp["PeakMin"]);
-  m_calCalTree->addProperty(m_calCalProp["PeakMax"]);
-  m_calCalTree->addProperty(m_calCalProp["BackMin"]);
-  m_calCalTree->addProperty(m_calCalProp["BackMax"]);
-
-  m_calCalPlot = new QwtPlot(this);
-  m_calCalPlot->setAxisFont(QwtPlot::xBottom, this->font());
-  m_calCalPlot->setAxisFont(QwtPlot::yLeft, this->font());
-  m_uiForm.cal_plotCal->addWidget(m_calCalPlot);
-  m_calCalPlot->setCanvasBackground(Qt::white);
-
-  // R1 = Peak, R2 = Background
-  m_calCalR1 = new MantidWidgets::RangeSelector(m_calCalPlot);
-  connect(m_calCalR1, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double)));
-  connect(m_calCalR1, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double)));
-  m_calCalR2 = new MantidWidgets::RangeSelector(m_calCalPlot);
-  m_calCalR2->setColour(Qt::darkGreen); // dark green to signify background range
-  connect(m_calCalR2, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double)));
-  connect(m_calCalR2, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double)));
-
-  // Res
-  m_calResTree = new QtTreePropertyBrowser();
-  m_uiForm.cal_treeRes->addWidget(m_calResTree);
-
-  m_calResTree->setFactoryForManager(m_calDblMng, doubleEditorFactory);
-
-  // Res - Spectra Selection
-  m_calResProp["SpecMin"] = m_calDblMng->addProperty("Spectra Min");
-  m_calResProp["SpecMax"] = m_calDblMng->addProperty("Spectra Max");
-  m_calResTree->addProperty(m_calResProp["SpecMin"]);
-  m_calDblMng->setDecimals(m_calResProp["SpecMin"], 0);
-  m_calResTree->addProperty(m_calResProp["SpecMax"]);
-  m_calDblMng->setDecimals(m_calResProp["SpecMax"], 0);
-
-  // Res - Background Properties
-  QtProperty* resBG = m_calGrpMng->addProperty("Background");
-  m_calResProp["Start"] = m_calDblMng->addProperty("Start");
-  m_calResProp["End"] = m_calDblMng->addProperty("End");
-  resBG->addSubProperty(m_calResProp["Start"]);
-  resBG->addSubProperty(m_calResProp["End"]);
-  m_calResTree->addProperty(resBG);
-
-  // Res - rebinning
-  QtProperty* resRB = m_calGrpMng->addProperty("Rebinning");
-  m_calResProp["ELow"] = m_calDblMng->addProperty("Low");
-  m_calDblMng->setDecimals(m_calResProp["ELow"], noDec);
-  m_calDblMng->setValue(m_calResProp["ELow"], -0.2);
-  m_calResProp["EWidth"] = m_calDblMng->addProperty("Width");
-  m_calDblMng->setDecimals(m_calResProp["EWidth"], noDec);
-  m_calDblMng->setValue(m_calResProp["EWidth"], 0.002);
-  m_calResProp["EHigh"] = m_calDblMng->addProperty("High");
-  m_calDblMng->setDecimals(m_calResProp["EHigh"], noDec);
-  m_calDblMng->setValue(m_calResProp["EHigh"], 0.2);
-  resRB->addSubProperty(m_calResProp["ELow"]);
-  resRB->addSubProperty(m_calResProp["EWidth"]);
-  resRB->addSubProperty(m_calResProp["EHigh"]);
-  m_calResTree->addProperty(resRB);
-
-  m_calResPlot = new QwtPlot(this);
-  m_calResPlot->setAxisFont(QwtPlot::xBottom, this->font());
-  m_calResPlot->setAxisFont(QwtPlot::yLeft, this->font());
-  m_uiForm.cal_plotRes->addWidget(m_calResPlot);
-  m_calResPlot->setCanvasBackground(Qt::white);
-
-  // Create ResR2 first so ResR1 is drawn above it.
-  m_calResR2 = new MantidWidgets::RangeSelector(m_calResPlot, 
-    MantidQt::MantidWidgets::RangeSelector::XMINMAX, true, true);
-  m_calResR2->setColour(Qt::darkGreen);
-  m_calResR1 = new MantidWidgets::RangeSelector(m_calResPlot);
-
-  connect(m_calResR1, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double)));
-  connect(m_calResR1, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double)));
-  connect(m_calResR1, SIGNAL(rangeChanged(double, double)), m_calResR2, SLOT(setRange(double, double)));
-  connect(m_calDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(calUpdateRS(QtProperty*, double)));
-  connect(m_calDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(calUpdateRS(QtProperty*, double)));
-  connect(m_calDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(calUpdateRS(QtProperty*, double)));
-}
-
-void Indirect::setupSlice()
-{
-  // Property Tree
-  m_sltTree = new QtTreePropertyBrowser();
-  m_uiForm.slice_properties->addWidget(m_sltTree);
-
-  // Create Manager Objects
-  m_sltDblMng = new QtDoublePropertyManager();
-  m_sltBlnMng = new QtBoolPropertyManager();
-  m_sltGrpMng = new QtGroupPropertyManager();
-
-  // Editor Factories
-  DoubleEditorFactory *doubleEditorFactory = new DoubleEditorFactory();
-  QtCheckBoxFactory *checkboxFactory = new QtCheckBoxFactory();
-  m_sltTree->setFactoryForManager(m_sltDblMng, doubleEditorFactory);
-  m_sltTree->setFactoryForManager(m_sltBlnMng, checkboxFactory);
-
-  // Create Properties
-  m_sltProp["SpecMin"] = m_sltDblMng->addProperty("Spectra Min");
-  m_sltProp["SpecMax"] = m_sltDblMng->addProperty("Spectra Max");
-  m_sltDblMng->setDecimals(m_sltProp["SpecMin"], 0);
-  m_sltDblMng->setDecimals(m_sltProp["SpecMax"], 0);
-
-  m_sltProp["R1S"] = m_sltDblMng->addProperty("Start");
-  m_sltProp["R1E"] = m_sltDblMng->addProperty("End");
-  m_sltProp["R2S"] = m_sltDblMng->addProperty("Start");
-  m_sltProp["R2E"] = m_sltDblMng->addProperty("End");
-
-  m_sltProp["UseTwoRanges"] = m_sltBlnMng->addProperty("Use Two Ranges");
-
-  m_sltProp["Range1"] = m_sltGrpMng->addProperty("Range One");
-  m_sltProp["Range1"]->addSubProperty(m_sltProp["R1S"]);
-  m_sltProp["Range1"]->addSubProperty(m_sltProp["R1E"]);
-  m_sltProp["Range2"] = m_sltGrpMng->addProperty("Range Two");
-  m_sltProp["Range2"]->addSubProperty(m_sltProp["R2S"]);
-  m_sltProp["Range2"]->addSubProperty(m_sltProp["R2E"]);
-
-  m_sltTree->addProperty(m_sltProp["SpecMin"]);
-  m_sltTree->addProperty(m_sltProp["SpecMax"]);
-  m_sltTree->addProperty(m_sltProp["Range1"]);
-  m_sltTree->addProperty(m_sltProp["UseTwoRanges"]);
-  m_sltTree->addProperty(m_sltProp["Range2"]);
-
-  // Create Slice Plot Widget for Range Selection
-  m_sltPlot = new QwtPlot(this);
-  m_sltPlot->setAxisFont(QwtPlot::xBottom, this->font());
-  m_sltPlot->setAxisFont(QwtPlot::yLeft, this->font());
-  m_uiForm.slice_plot->addWidget(m_sltPlot);
-  m_sltPlot->setCanvasBackground(Qt::white);
-  // We always want one range selector... the second one can be controlled from
-  // within the sliceTwoRanges(bool state) function
-  m_sltR1 = new MantidWidgets::RangeSelector(m_sltPlot);
-  connect(m_sltR1, SIGNAL(minValueChanged(double)), this, SLOT(sliceMinChanged(double)));
-  connect(m_sltR1, SIGNAL(maxValueChanged(double)), this, SLOT(sliceMaxChanged(double)));
-
-  // second range
-  // create the second range
-  m_sltR2 = new MantidWidgets::RangeSelector(m_sltPlot);
-  m_sltR2->setColour(Qt::darkGreen); // dark green for background
-  connect(m_sltR1, SIGNAL(rangeChanged(double, double)), m_sltR2, SLOT(setRange(double, double)));
-  connect(m_sltR2, SIGNAL(minValueChanged(double)), this, SLOT(sliceMinChanged(double)));
-  connect(m_sltR2, SIGNAL(maxValueChanged(double)), this, SLOT(sliceMaxChanged(double)));
-  m_sltR2->setRange(m_sltR1->getRange());
-
-  // Refresh the plot window
-  m_sltPlot->replot();
-
-  connect(m_sltDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(sliceUpdateRS(QtProperty*, double)));
-  connect(m_sltBlnMng, SIGNAL(valueChanged(QtProperty*, bool)), this, SLOT(sliceTwoRanges(QtProperty*, bool)));
-
-  sliceTwoRanges(0, false); // set default value
-}
-
-void Indirect::refreshWSlist()
-{
-  m_uiForm.sqw_cbWorkspace->clear();
-  std::set<std::string> workspaceList = Mantid::API::AnalysisDataService::Instance().getObjectNames();
-  if ( ! workspaceList.empty() )
-  {
-    std::set<std::string>::const_iterator wsIt;
-    for ( wsIt=workspaceList.begin(); wsIt != workspaceList.end(); ++wsIt )
-    {
-      m_uiForm.sqw_cbWorkspace->addItem(QString::fromStdString(*wsIt));
-    }
-  }
-}
-/**
-* This function is called when the user selects an analyser from the cbAnalyser QComboBox
-* object. It's main purpose is to initialise the values for the Reflection ComboBox.
-* @param index :: Index of the value selected in the combo box.
-*/
-void Indirect::analyserSelected(int index)
-{
-  // populate Reflection combobox with correct values for Analyser selected.
-  m_uiForm.cbReflection->clear();
-  clearReflectionInfo();
-
-
-  QVariant currentData = m_uiForm.cbAnalyser->itemData(index);
-  if ( currentData == QVariant::Invalid )
-  {
-    m_uiForm.lbReflection->setEnabled(false);
-    m_uiForm.cbReflection->setEnabled(false);
-    return;
-  }
-  else
-  {
-    m_uiForm.lbReflection->setEnabled(true);
-    m_uiForm.cbReflection->setEnabled(true);
-    QStringList reflections = currentData.toStringList();
-    for ( int i = 0; i < reflections.count(); i++ )
-    {
-      m_uiForm.cbReflection->addItem(reflections[i]);
-    }
-  }
-
-  reflectionSelected(m_uiForm.cbReflection->currentIndex());
-}
-/**
-* This function is called when the user selects a reflection from the cbReflection QComboBox
-* object.
-* @param index :: Index of the value selected in the combo box.
-*/
-void Indirect::reflectionSelected(int index)
-{
-  // first, clear values in assosciated boxes:
-  clearReflectionInfo();
-
-  QString pyInput =
-    "from IndirectEnergyConversion import getReflectionDetails\n"
-    "instrument = '" + m_uiForm.cbInst->currentText() + "'\n"
-    "analyser = '" + m_uiForm.cbAnalyser->currentText() + "'\n"
-    "reflection = '" + m_uiForm.cbReflection->currentText() + "'\n"
-    "print getReflectionDetails(instrument, analyser, reflection)\n";
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-
-  QStringList values = pyOutput.split("\n", QString::SkipEmptyParts);
-
-  if ( values.count() < 3 )
-  {
-    showInformationBox("Could not gather necessary data from parameter file.");
-    return;
-  }
-  else
-  {
-    QString analysisType = values[0];
-    m_uiForm.leSpectraMin->setText(values[1]);
-    m_uiForm.leSpectraMax->setText(values[2]);
-    m_calDblMng->setValue(m_calResProp["SpecMin"], values[1].toDouble());
-    m_calDblMng->setValue(m_calResProp["SpecMax"], values[2].toDouble());
-    m_sltDblMng->setValue(m_sltProp["SpecMin"], values[1].toDouble());
-    m_sltDblMng->setValue(m_sltProp["SpecMax"], values[2].toDouble());
-    
-    if ( values.count() >= 8 )
-    {
-      m_uiForm.leEfixed->setText(values[3]);
-      
-      m_calDblMng->setValue(m_calCalProp["PeakMin"], values[4].toDouble());
-      m_calDblMng->setValue(m_calCalProp["PeakMax"], values[5].toDouble());
-      m_calDblMng->setValue(m_calCalProp["BackMin"], values[6].toDouble());
-      m_calDblMng->setValue(m_calCalProp["BackMax"], values[7].toDouble());
-
-      m_sltDblMng->setValue(m_sltProp["R1S"], values[4].toDouble());
-      m_sltDblMng->setValue(m_sltProp["R1E"], values[5].toDouble());
-      m_sltDblMng->setValue(m_sltProp["R2S"], values[6].toDouble());
-      m_sltDblMng->setValue(m_sltProp["R2E"], values[7].toDouble());
-    }
-    else
-    {
-      m_uiForm.leEfixed->clear();
-    }
-    // Default rebinning parameters can be set in instrument parameter file
-    if ( values.count() == 9 )
-    {
-      QStringList rbp = values[8].split(",", QString::SkipEmptyParts);
-      m_uiForm.rebin_ckDNR->setChecked(false);
-      m_uiForm.rebin_leELow->setText(rbp[0]);
-      m_uiForm.rebin_leEWidth->setText(rbp[1]);
-      m_uiForm.rebin_leEHigh->setText(rbp[2]);
-    }
-    else
-    {
-      m_uiForm.rebin_ckDNR->setChecked(true);
-      m_uiForm.rebin_leELow->setText("");
-      m_uiForm.rebin_leEWidth->setText("");
-      m_uiForm.rebin_leEHigh->setText("");
-    }
-  }
-
-  // clear validation markers
-  validateInput();
-  validateCalib();
-  validateSlice();
-}
-/**
-* This function runs when the user makes a selection on the cbMappingOptions QComboBox.
-* @param groupType :: Value of selection made by user.
-*/
-void Indirect::mappingOptionSelected(const QString& groupType)
-{
-  if ( groupType == "File" )
-  {
-    m_uiForm.swMapping->setCurrentIndex(0);
-  }
-  else if ( groupType == "All" )
-  {
-    m_uiForm.swMapping->setCurrentIndex(2);
-  }
-  else if ( groupType == "Individual" )
-  {
-    m_uiForm.swMapping->setCurrentIndex(2);
-  }
-  else if ( groupType == "Groups" )
-  {
-    m_uiForm.swMapping->setCurrentIndex(1);
-  }
-
-  isDirtyRebin(true);
-}
-
-void Indirect::tabChanged(int index)
-{
-  QString tabName = m_uiForm.tabWidget->tabText(index);
-  m_uiForm.pbRun->setText("Run " + tabName);
-}
-/**
-* This function is called when the user clicks on the Background Removal button. It
-* displays the Background Removal dialog, initialising it if it hasn't been already.
-*/
-void Indirect::backgroundClicked()
-{
-  if ( m_backgroundDialog == NULL )
-  {
-    m_backgroundDialog = new Background(this);
-    connect(m_backgroundDialog, SIGNAL(accepted()), this, SLOT(backgroundRemoval()));
-    connect(m_backgroundDialog, SIGNAL(rejected()), this, SLOT(backgroundRemoval()));
-    m_backgroundDialog->show();
-  }
-  else
-  {
-    m_backgroundDialog->show();
-  }
-}
-/**
-* Slot called when m_backgroundDialog is closed. Assesses whether user desires background removal.
-*/
-void Indirect::backgroundRemoval()
-{
-  if ( m_backgroundDialog->removeBackground() )
-  {
-    m_bgRemoval = true;
-    m_uiForm.pbBack_2->setText("Background Removal (On)");
-  }
-  else
-  {
-    m_bgRemoval = false;
-    m_uiForm.pbBack_2->setText("Background Removal (Off)");
-  }
-  isDirty(true);
-}
-/**
-* Plots raw time data from .raw file before any data conversion has been performed.
-*/
-void Indirect::plotRaw()
-{
-  if ( m_uiForm.ind_runFiles->isValid() )
-  {
-    bool ok;
-    QString spectraRange = QInputDialog::getText(this, "Insert Spectra Ranges", "Range: ", QLineEdit::Normal, m_uiForm.leSpectraMin->text() +"-"+ m_uiForm.leSpectraMax->text(), &ok);
-
-    if ( !ok || spectraRange.isEmpty() )
-    {
-      return;
-    }
-    QStringList specList = spectraRange.split("-");
-
-    QString rawFile = m_uiForm.ind_runFiles->getFirstFilename();
-    if ( (specList.size() > 2) || ( specList.size() < 1) )
-    {
-      showInformationBox("Invalid input. Must be of form <SpecMin>-<SpecMax>");
-      return;
-    }
-    if ( specList.size() == 1 )
-    {
-      specList.append(specList[0]);
-    }
-
-    QString bgrange;
-
-    if ( m_bgRemoval )
-    {
-      QPair<double, double> range = m_backgroundDialog->getRange();
-      bgrange = "[ " + QString::number(range.first) + "," + QString::number(range.second) + " ]";
-    }
-    else
-    {
-      bgrange = "[-1, -1]";
-    }
-
-    QString pyInput =
-      "from mantidsimple import *\n"
-      "from mantidplot import *\n"
-      "import os.path as op\n"
-      "file = r'" + rawFile + "'\n"
-      "name = op.splitext( op.split(file)[1] )[0]\n"
-      "bgrange = " + bgrange + "\n"
-      "LoadRaw(file, name, SpectrumMin="+specList[0]+", SpectrumMax="+specList[1]+")\n"
-      "if ( bgrange != [-1, -1] ):\n"
-      "    #Remove background\n"
-      "    FlatBackground(name, name+'_bg', bgrange[0], bgrange[1], Mode='Mean')\n"
-      "    GroupDetectors(name+'_bg', name+'_grp', DetectorList=range("+specList[0]+","+specList[1]+"+1))\n"
-      "    GroupDetectors(name, name+'_grp_raw', DetectorList=range("+specList[0]+","+specList[1]+"+1))\n"
-      "else: # Just group detectors as they are\n"
-      "    GroupDetectors(name, name+'_grp', DetectorList=range("+specList[0]+","+specList[1]+"+1))\n"
-      "graph = plotSpectrum(name+'_grp', 0)\n";
-
-    QString pyOutput = runPythonCode(pyInput).trimmed();
-    
-    if ( pyOutput != "" )
-    {
-      showInformationBox(pyOutput);
-    }
-
-  }
-  else
-  {
-    showInformationBox("You must select a run file.");
-  }
-}
-/**
-* This function will disable the necessary elements of the interface when the user selects "Do Not Rebin"
-* and enable them again when this is de-selected.
-* @param state :: whether the "Do Not Rebin" checkbox is checked
-*/
-void Indirect::rebinCheck(bool state) 
-{
-  QString val;
-  if ( state ) val = " ";
-  else val = "*";
-  m_uiForm.rebin_pbRebin->setEnabled( !state );
-  m_uiForm.rebin_lbLow->setEnabled( !state );
-  m_uiForm.rebin_lbWidth->setEnabled( !state );
-  m_uiForm.rebin_lbHigh->setEnabled( !state );
-  m_uiForm.rebin_leELow->setEnabled( !state );
-  m_uiForm.rebin_leEWidth->setEnabled( !state );
-  m_uiForm.rebin_leEHigh->setEnabled( !state );
-  m_uiForm.valELow->setEnabled(!state);
-  m_uiForm.valELow->setText(val);
-  m_uiForm.valEWidth->setEnabled(!state);
-  m_uiForm.valEWidth->setText(val);
-  m_uiForm.valEHigh->setEnabled(!state);
-  m_uiForm.valEHigh->setText(val);
-  isDirtyRebin(true);
-}
-/**
-* Disables/enables the relevant parts of the UI when user checks/unchecks the Detailed Balance
-* ckDetailedBalance checkbox.
-* @param state :: state of the checkbox
-*/
-void Indirect::detailedBalanceCheck(bool state)
-{
-  m_uiForm.leDetailedBalance->setEnabled(state);
-  m_uiForm.lbDBKelvin->setEnabled(state);
-
-  isDirtyRebin(true);
-}
-/**
-* This function enables/disables the display of the options involved in creating the RES file.
-* @param state :: whether checkbox is checked or unchecked
-*/
-void Indirect::resCheck(bool state)
-{
-  m_calResR1->setVisible(state);
-  m_calResR2->setVisible(state);
-}
-/**
-* This function just calls the runClicked slot, but with tryToSave being 'false'
-*/
-void Indirect::rebinData()
-{
-  runConvertToEnergy(false);
-}
-
-void Indirect::useCalib(bool state)
-{
-  m_uiForm.ind_calibFile->isOptional(!state);
-  m_uiForm.ind_calibFile->setEnabled(state);
-}
-/**
-* This function is called when the user clicks on the "Create Calibration File" button.
-* Pretty much does what it says on the tin.
-*/
-void Indirect::calibCreate()
-{
-  QString file = m_uiForm.cal_leRunNo->getFirstFilename();
-  if ( ! validateCalib() || file == "" )
-  {
-    showInformationBox("Please check your input.");
-  }
-  else
-  {
-    QString suffix = "_" + m_uiForm.cbAnalyser->currentText() + m_uiForm.cbReflection->currentText() + "_calib";
-
-    QString filenames = "[r'"+m_uiForm.cal_leRunNo->getFilenames().join("', r'")+"']";
-
-    QString pyInput =
-      "from IndirectEnergyConversion import createCalibFile\n"
-      "plot = ";
-
-    if ( m_uiForm.cal_ckPlotResult->isChecked() )
-      pyInput +=	"True\n";
-    else
-      pyInput += "False\n";
-
-    pyInput +=
-      "file = createCalibFile("+filenames+", '"+suffix+"', %1, %2, %3, %4, %5, %6, PlotOpt=plot)\n"
-      "print file\n";
-
-    pyInput = pyInput.arg(QString::number(m_calDblMng->value(m_calCalProp["PeakMin"])));
-    pyInput = pyInput.arg(QString::number(m_calDblMng->value(m_calCalProp["PeakMax"])));
-    pyInput = pyInput.arg(QString::number(m_calDblMng->value(m_calCalProp["BackMin"])));
-    pyInput = pyInput.arg(QString::number(m_calDblMng->value(m_calCalProp["BackMax"])));
-    pyInput = pyInput.arg(m_uiForm.leSpectraMin->text());
-    pyInput = pyInput.arg(m_uiForm.leSpectraMax->text());
-
-    QString pyOutput = runPythonCode(pyInput).trimmed();
-
-    if ( pyOutput == "" )
-    {
-      showInformationBox("An error occurred creating the calib file.\n");
-    }
-    else
-    {
-      if ( m_uiForm.cal_ckRES->isChecked() )
-      {
-        createRESfile(filenames);
-      }
-      m_uiForm.ind_calibFile->setFileText(pyOutput);
-      m_uiForm.ckUseCalib->setChecked(true);
-    }
-  }
-}
-/**
-* Sets interface as "Dirty" - catches all relevant user changes that don't need special action
-*/
-void Indirect::setasDirty()
-{
-  isDirty(true);
-}
-/*
-* Sets interface as "Dirty" - catches all relevant user changes that don't need special action
-*/
-void Indirect::setasDirtyRebin()
-{
-  isDirtyRebin(true);
-}
-/**
-* Controls the ckUseCalib checkbox to automatically check it when a user inputs a file from clicking on 'browse'.
-* @param calib :: path to calib file
-*/
-void Indirect::calibFileChanged(const QString & calib)
-{
-  if ( calib.isEmpty() )
-  {
-    m_uiForm.ckUseCalib->setChecked(false);
-  }
-  else
-  {
-    m_uiForm.ckUseCalib->setChecked(true);
-  }
-}
-// CALIBRATION TAB
-void Indirect::calPlotRaw()
-{
-  QString filename = m_uiForm.cal_leRunNo->getFirstFilename();
-  
-  if ( filename == "" )
-  {
-    showInformationBox("Please enter a run number.");
-    return;
-  }
-    
-  QFileInfo fi(filename);
-  QString wsname = fi.baseName();
-
-  QString pyInput = "LoadRaw(r'" + filename + "', '" + wsname + "', SpectrumMin=" 
-    + m_uiForm.leSpectraMin->text() + ", SpectrumMax="
-    + m_uiForm.leSpectraMax->text() + ")\n";
-  QString pyOutput = runPythonCode(pyInput);
-    
-  Mantid::API::MatrixWorkspace_sptr input = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsname.toStdString()));
-
-  QVector<double> dataX = QVector<double>::fromStdVector(input->readX(0));
-  QVector<double> dataY = QVector<double>::fromStdVector(input->readY(0));
-
-  if ( m_calCalCurve != NULL )
-  {
-    m_calCalCurve->attach(0);
-    delete m_calCalCurve;
-    m_calCalCurve = 0;
-  }
-
-  m_calCalCurve = new QwtPlotCurve();
-  m_calCalCurve->setData(dataX, dataY);
-  m_calCalCurve->attach(m_calCalPlot);
-  
-  m_calCalPlot->setAxisScale(QwtPlot::xBottom, dataX.first(), dataX.last());
-
-  m_calCalR1->setRange(dataX.first(), dataX.last());
-  m_calCalR2->setRange(dataX.first(), dataX.last());
-
-  // Replot
-  m_calCalPlot->replot();
-
-}
-
-void Indirect::calPlotEnergy()
-{
-  if ( ! m_uiForm.cal_leRunNo->isValid() )
-  {
-    showInformationBox("Run number not valid.");
-    return;
-  }
-  QString files = "[r'" + m_uiForm.cal_leRunNo->getFilenames().join("', r'") + "']";
-  QString pyInput =
-    "from IndirectEnergyConversion import resolution\n"
-    "iconOpt = { 'first': " +QString::number(m_calDblMng->value(m_calResProp["SpecMin"]))+
-    ", 'last': " +QString::number(m_calDblMng->value(m_calResProp["SpecMax"]))+ "}\n"
-    "instrument = '" + m_uiForm.cbInst->currentText() + "'\n"
-    "analyser = '" + m_uiForm.cbAnalyser->currentText() + "'\n"
-    "reflection = '" + m_uiForm.cbReflection->currentText() + "'\n"
-    "files = " + files + "\n"
-    "outWS = resolution(files, iconOpt, '', '', instrument, analyser, reflection, Res=False)\n"
-    "print outWS\n";
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-  
-  Mantid::API::MatrixWorkspace_sptr input = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(pyOutput.toStdString()));
-
-  QVector<double> dataX = QVector<double>::fromStdVector(input->readX(0));
-  QVector<double> dataY = QVector<double>::fromStdVector(input->readY(0));
-
-  if ( m_calResCurve != NULL )
-  {
-    m_calResCurve->attach(0);
-    delete m_calResCurve;
-    m_calResCurve = 0;
-  }
-
-  m_calResCurve = new QwtPlotCurve();
-  m_calResCurve->setData(dataX, dataY);
-  m_calResCurve->attach(m_calResPlot);
-  
-  m_calResPlot->setAxisScale(QwtPlot::xBottom, dataX.first(), dataX.last());
-  m_calResR1->setRange(dataX.first(), dataX.last());
-
-  m_calResR2->setMinimum(m_calDblMng->value(m_calResProp["ELow"]));
-  m_calResR2->setMaximum(m_calDblMng->value(m_calResProp["EHigh"]));
-
-  // Replot
-  m_calResPlot->replot();
-}
-
-void Indirect::calMinChanged(double val)
-{
-  MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
-  if ( from == m_calCalR1 )
-  {
-    m_calDblMng->setValue(m_calCalProp["PeakMin"], val);
-  }
-  else if ( from == m_calCalR2 )
-  {
-    m_calDblMng->setValue(m_calCalProp["BackMin"], val);
-  }
-  else if ( from == m_calResR1 )
-  {
-    m_calDblMng->setValue(m_calResProp["Start"], val);
-  }
-}
-
-void Indirect::calMaxChanged(double val)
-{
-  MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
-  if ( from == m_calCalR1 )
-  {
-    m_calDblMng->setValue(m_calCalProp["PeakMax"], val);
-  }
-  else if ( from == m_calCalR2 )
-  {
-    m_calDblMng->setValue(m_calCalProp["BackMax"], val);
-  }
-  else if ( from == m_calResR1 )
-  {
-    m_calDblMng->setValue(m_calResProp["End"], val);
-  }
-}
-
-void Indirect::calUpdateRS(QtProperty* prop, double val)
-{
-  if ( prop == m_calCalProp["PeakMin"] ) m_calCalR1->setMinimum(val);
-  else if ( prop == m_calCalProp["PeakMax"] ) m_calCalR1->setMaximum(val);
-  else if ( prop == m_calCalProp["BackMin"] ) m_calCalR2->setMinimum(val);
-  else if ( prop == m_calCalProp["BackMax"] ) m_calCalR2->setMaximum(val);
-  else if ( prop == m_calResProp["Start"] ) m_calResR1->setMinimum(val);
-  else if ( prop == m_calResProp["End"] ) m_calResR1->setMaximum(val);
-  else if ( prop == m_calResProp["ELow"] ) m_calResR2->setMinimum(val);
-  else if ( prop == m_calResProp["EHigh"] ) m_calResR2->setMaximum(val);
-}
-
-void Indirect::sOfQwClicked()
-{
-  if ( validateSofQw() )
-  {
-    QString rebinString = m_uiForm.sqw_leQLow->text()+","+m_uiForm.sqw_leQWidth->text()+","+m_uiForm.sqw_leQHigh->text();
-    QString pyInput = "from mantidsimple import *\n";
-
-    if ( m_uiForm.sqw_cbInput->currentText() == "File" )
-    {
-      pyInput +=
-        "filename = r'" +m_uiForm.sqw_inputFile->getFirstFilename() + "'\n"
-        "(dir, file) = os.path.split(filename)\n"
-        "(sqwInput, ext) = os.path.splitext(file)\n"
-        "LoadNexus(filename, sqwInput)\n"
-        "cleanup = True\n"; 
-    }
-    else
-    {
-      pyInput +=
-        "sqwInput = '" + m_uiForm.sqw_cbWorkspace->currentText() + "'\n"
-        "cleanup = False\n";
-    }
-
-    // Create output name before rebinning
-    pyInput += "sqwOutput = sqwInput[:-3] + 'sqw'\n";
-
-    if ( m_uiForm.sqw_ckRebinE->isChecked() )
-    {
-      QString eRebinString = m_uiForm.sqw_leELow->text()+","+m_uiForm.sqw_leEWidth->text()+","+m_uiForm.sqw_leEHigh->text();
-      pyInput += "Rebin(sqwInput, sqwInput+'_r', '" + eRebinString + "')\n"
-        "if cleanup:\n"
-        "    mantid.deleteWorkspace(sqwInput)\n"
-        "sqwInput += '_r'\n"
-        "cleanup = True\n";
-    }
-    pyInput +=
-      "efixed = " + m_uiForm.leEfixed->text() + "\n"
-      "rebin = '" + rebinString + "'\n"      
-      "SofQW(sqwInput, sqwOutput, rebin, 'Indirect', EFixed=efixed)\n"
-      "if cleanup:\n"
-      "    mantid.deleteWorkspace(sqwInput)\n";
-
-    if ( m_uiForm.sqw_ckSave->isChecked() )
-    {
-      pyInput += "SaveNexus(sqwOutput, sqwOutput+'.nxs')\n";
-    }
-
-    if ( m_uiForm.sqw_cbPlotType->currentText() == "Contour" )
-    {
-      pyInput += "importMatrixWorkspace(sqwOutput).plotGraph2D()\n";
-    }
-    else if ( m_uiForm.sqw_cbPlotType->currentText() == "Specta" )
-    {
-      pyInput +=
-        "nspec = mtd[sqwOuput].getNumberHistograms()\n"
-        "plotSpectra(sqwOutput, range(0, nspec)\n";
-    }
-        
-    QString pyOutput = runPythonCode(pyInput).trimmed();
-  }
-  else
-  {
-    showInformationBox("Some of your input is invalid. Please check the input highlighted.");
-  }
-}
-
-void Indirect::sOfQwRebinE(bool state)
-{
-  QString val;
-  if ( state ) val = "*";
-  else val = " ";
-  m_uiForm.sqw_leELow->setEnabled(state);
-  m_uiForm.sqw_leEWidth->setEnabled(state);
-  m_uiForm.sqw_leEHigh->setEnabled(state);
-  m_uiForm.sqw_valELow->setEnabled(state);
-  m_uiForm.sqw_valELow->setText(val);
-  m_uiForm.sqw_valEWidth->setEnabled(state);
-  m_uiForm.sqw_valEWidth->setText(val);
-  m_uiForm.sqw_valEHigh->setEnabled(state);
-  m_uiForm.sqw_valEHigh->setText(val);
-  m_uiForm.sqw_lbELow->setEnabled(state);
-  m_uiForm.sqw_lbEWidth->setEnabled(state);
-  m_uiForm.sqw_lbEHigh->setEnabled(state);
-}
-
-void Indirect::sOfQwInputType(const QString& input)
-{
-  if ( input == "File" )
-  {
-    m_uiForm.sqw_swInput->setCurrentIndex(0);
-  }
-  else
-  {
-    m_uiForm.sqw_swInput->setCurrentIndex(1);
-    refreshWSlist();
-  }
-}
-
-void Indirect::sOfQwPlotInput()
-{
-  QString pyInput = "from mantidsimple import *\n"
-    "from mantidplot import *\n";
-
-  //...
-  if ( m_uiForm.sqw_cbInput->currentText() == "File" )
-  {
-    // get filename
-    if ( m_uiForm.sqw_inputFile->isValid() )
-    {
-      pyInput +=
-        "filename = r'" + m_uiForm.sqw_inputFile->getFirstFilename() + "'\n"
-        "(dir, file) = os.path.split(filename)\n"
-        "(input, ext) = os.path.splitext(file)\n"
-        "LoadNexus(filename, input)\n";
-    }
-    else
-    {
-      showInformationBox("Invalid filename.");
-      return;
-    }
-  }
-  else
-  {
-    pyInput += "input = '" + m_uiForm.sqw_cbWorkspace->currentText() + "'\n";
-  }
-
-  pyInput += "ConvertSpectrumAxis(input, input+'_q', 'MomentumTransfer', 'Indirect')\n"
-    "ws = importMatrixWorkspace(input+'_q')\n"
-    "ws.plotGraph2D()\n";
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-
-}
-
-// SLICE
-void Indirect::sliceRun()
-{
-  if ( ! validateSlice() )
-  {
-    showInformationBox("Please check your input.");
-    return;
-  }
-
-  QString pyInput =
-    "from IndirectEnergyConversion import slice\n"
-    "tofRange = [" + QString::number(m_sltDblMng->value(m_sltProp["R1S"])) + ","
-    + QString::number(m_sltDblMng->value(m_sltProp["R1E"]));
-  if ( m_sltBlnMng->value(m_sltProp["UseTwoRanges"]) )
-  {
-    pyInput +=
-      "," + QString::number(m_sltDblMng->value(m_sltProp["R2S"])) + ","
-      + QString::number(m_sltDblMng->value(m_sltProp["R2E"])) + "]\n";
-  }
-  else
-  {
-    pyInput += "]\n";
-  }
-  if ( m_uiForm.slice_ckUseCalib->isChecked() )
-  {
-    pyInput +=
-      "calib = r'" + m_uiForm.slice_calibFile->getFirstFilename() + "'\n";
-  }
-  else
-  {
-    pyInput +=
-      "calib = ''\n";
-  }
-  QString filenames = m_uiForm.slice_inputFile->getFilenames().join("', r'");
-  QString suffix = m_uiForm.cbAnalyser->currentText() + m_uiForm.cbReflection->currentText();
-  pyInput +=
-    "rawfile = [r'" + filenames + "']\n"
-    "spectra = ["+ QString::number(m_sltDblMng->value(m_sltProp["SpecMin"])) + "," + QString::number(m_sltDblMng->value(m_sltProp["SpecMax"])) +"]\n"
-    "suffix = '" + suffix + "'\n";
-
-  if ( m_uiForm.slice_ckVerbose->isChecked() ) pyInput += "verbose = True\n";
-  else pyInput += "verbose = False\n";
-
-  if ( m_uiForm.slice_ckPlot->isChecked() ) pyInput += "plot = True\n";
-  else pyInput += "plot = False\n";
-
-  if ( m_uiForm.slice_ckSave->isChecked() ) pyInput += "save = True\n";
-  else pyInput += "save = False\n";
-
-  pyInput +=
-    "slice(rawfile, calib, tofRange, spectra, suffix, Save=save, Verbose=verbose, Plot=plot)";
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-}
-
-void Indirect::slicePlotRaw()
-{
-  if ( m_uiForm.slice_inputFile->isValid() )
-  {
-    QString filename = m_uiForm.slice_inputFile->getFirstFilename();
-    QFileInfo fi(filename);
-    QString wsname = fi.baseName();
-
-    QString pyInput = "LoadRaw(r'" + filename + "', '" + wsname + "', SpectrumMin=" 
-      + m_uiForm.leSpectraMin->text() + ", SpectrumMax="
-      + m_uiForm.leSpectraMax->text() + ")\n";
-    QString pyOutput = runPythonCode(pyInput);
-
-    Mantid::API::MatrixWorkspace_sptr input = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsname.toStdString()));
-
-    QVector<double> dataX = QVector<double>::fromStdVector(input->readX(0));
-    QVector<double> dataY = QVector<double>::fromStdVector(input->readY(0));
-
-    if ( m_sltDataCurve != NULL )
-    {
-      m_sltDataCurve->attach(0);
-      delete m_sltDataCurve;
-      m_sltDataCurve = 0;
-    }
-
-    m_sltDataCurve = new QwtPlotCurve();
-    m_sltDataCurve->setData(dataX, dataY);
-    m_sltDataCurve->attach(m_sltPlot);
-
-    m_sltPlot->setAxisScale(QwtPlot::xBottom, dataX.first(), dataX.last());
-
-    m_sltR1->setRange(dataX.first(), dataX.last());
-
-    // Replot
-    m_sltPlot->replot();
-  }
-  else
-  {
-    showInformationBox("Selected input files are invalid.");
-  }
-
-}
-
-void Indirect::sliceTwoRanges(QtProperty*, bool state)
-{
-  m_sltR2->setVisible(state);
-}
-
-void Indirect::sliceCalib(bool state)
-{
-  m_uiForm.slice_calibFile->setEnabled(state);
-  m_uiForm.slice_calibFile->isOptional(!state);
-}
-
-void Indirect::sliceMinChanged(double val)
-{
-  MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
-  if ( from == m_sltR1 )
-  {
-    m_sltDblMng->setValue(m_sltProp["R1S"], val);
-  }
-  else if ( from == m_sltR2 )
-  {
-    m_sltDblMng->setValue(m_sltProp["R2S"], val);
-  }
-}
-
-void Indirect::sliceMaxChanged(double val)
-{
-  MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
-  if ( from == m_sltR1 )
-  {
-    m_sltDblMng->setValue(m_sltProp["R1E"], val);
-  }
-  else if ( from == m_sltR2 )
-  {
-    m_sltDblMng->setValue(m_sltProp["R2E"], val);
-  }
-}
-
-void Indirect::sliceUpdateRS(QtProperty* prop, double val)
-{
-  if ( prop == m_sltProp["R1S"] ) m_sltR1->setMinimum(val);
-  else if ( prop == m_sltProp["R1E"] ) m_sltR1->setMaximum(val);
-  else if ( prop == m_sltProp["R2S"] ) m_sltR2->setMinimum(val);
-  else if ( prop == m_sltProp["R2E"] ) m_sltR2->setMaximum(val);
-}
+#include "MantidQtCustomInterfaces/Indirect.h"
+
+#include "MantidQtCustomInterfaces/Background.h"
+
+#include "MantidKernel/ConfigService.h"
+#include "MantidAPI/AnalysisDataService.h"
+#include "MantidAPI/MatrixWorkspace.h"
+
+#include <Poco/NObserver.h>
+
+#include <QUrl>
+#include <QDesktopServices>
+#include <QDir>
+#include <QFileDialog>
+#include <QInputDialog>
+#include <QLineEdit>
+
+#include "qttreepropertybrowser.h"
+#include "qtpropertymanager.h"
+#include "qteditorfactory.h"
+#include "DoubleEditorFactory.h"
+#include <QtCheckBoxFactory>
+
+using namespace MantidQt::CustomInterfaces;
+
+/**
+* This is the constructor for the Indirect Instruments Interface.
+* It is used primarily to ensure sane values for member variables.
+*/
+Indirect::Indirect(QWidget *parent, Ui::ConvertToEnergy & uiForm) : 
+UserSubWindow(parent), m_uiForm(uiForm), m_backgroundDialog(NULL), m_isDirty(true),
+  m_isDirtyRebin(true), m_bgRemoval(false), m_valInt(NULL), m_valDbl(NULL), 
+  m_changeObserver(*this, &Indirect::handleDirectoryChange),
+  // Null pointers - Calibration Tab
+  m_calCalPlot(NULL), m_calResPlot(NULL),
+  m_calCalR1(NULL), m_calCalR2(NULL), m_calResR1(NULL),
+  m_calCalCurve(NULL), m_calResCurve(NULL),
+  // Null pointers - Diagnostics Tab
+  m_sltPlot(NULL), m_sltR1(NULL), m_sltR2(NULL), m_sltDataCurve(NULL)
+
+{
+  // Constructor
+}
+/**
+* This function performs any one-time actions needed when the Inelastic interface
+* is first selected, such as connecting signals to slots.
+*/
+void Indirect::initLayout()
+{
+  Mantid::Kernel::ConfigService::Instance().addObserver(m_changeObserver);
+
+  m_settingsGroup = "CustomInterfaces/ConvertToEnergy/Indirect/";
+
+  setupCalibration(); // setup the calibration miniplots
+  setupSlice(); // setup the slice miniplot
+
+  // "Energy Transfer" tab
+  connect(m_uiForm.cbAnalyser, SIGNAL(activated(int)), this, SLOT(analyserSelected(int)));
+  connect(m_uiForm.cbReflection, SIGNAL(activated(int)), this, SLOT(reflectionSelected(int)));
+  connect(m_uiForm.cbMappingOptions, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(mappingOptionSelected(const QString&)));
+  connect(m_uiForm.pbBack_2, SIGNAL(clicked()), this, SLOT(backgroundClicked()));
+  connect(m_uiForm.pbPlotRaw, SIGNAL(clicked()), this, SLOT(plotRaw()));
+  connect(m_uiForm.rebin_pbRebin, SIGNAL(clicked()), this, SLOT(rebinData()));
+  connect(m_uiForm.rebin_ckDNR, SIGNAL(toggled(bool)), this, SLOT(rebinCheck(bool)));
+  connect(m_uiForm.ckDetailedBalance, SIGNAL(toggled(bool)), this, SLOT(detailedBalanceCheck(bool)));
+
+  connect(m_uiForm.ind_runFiles, SIGNAL(fileEditingFinished()), this, SLOT(setasDirty()));
+  connect(m_uiForm.ind_calibFile, SIGNAL(fileEditingFinished()), this, SLOT(setasDirty()));
+  connect(m_uiForm.ind_calibFile, SIGNAL(fileTextChanged(const QString &)), this, SLOT(calibFileChanged(const QString &)));
+  connect(m_uiForm.leSpectraMin, SIGNAL(editingFinished()), this, SLOT(setasDirty()));
+  connect(m_uiForm.leSpectraMax, SIGNAL(editingFinished()), this, SLOT(setasDirty()));
+  connect(m_uiForm.ckSumFiles, SIGNAL(pressed()), this, SLOT(setasDirty()));
+  connect(m_uiForm.ckUseCalib, SIGNAL(toggled(bool)), this, SLOT(useCalib(bool)));
+  connect(m_uiForm.ckCleanUp, SIGNAL(pressed()), this, SLOT(setasDirtyRebin()));
+
+  connect(m_uiForm.rebin_leELow, SIGNAL(editingFinished()), this, SLOT(setasDirtyRebin()));
+  connect(m_uiForm.rebin_leEWidth, SIGNAL(editingFinished()), this, SLOT(setasDirtyRebin()));
+  connect(m_uiForm.rebin_leEHigh, SIGNAL(editingFinished()), this, SLOT(setasDirtyRebin()));
+  connect(m_uiForm.leDetailedBalance, SIGNAL(editingFinished()), this, SLOT(setasDirtyRebin()));
+  connect(m_uiForm.ind_mapFile, SIGNAL(fileEditingFinished()), this, SLOT(setasDirtyRebin()));
+
+  connect(m_uiForm.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int)));
+
+  // "Calibration" tab
+  connect(m_uiForm.cal_pbPlot, SIGNAL(clicked()), this, SLOT(calPlotRaw()));
+  connect(m_uiForm.cal_pbPlotEnergy, SIGNAL(clicked()), this, SLOT(calPlotEnergy()));
+  connect(m_uiForm.cal_ckRES, SIGNAL(toggled(bool)), this, SLOT(resCheck(bool)));
+
+  // "SofQW" tab
+  connect(m_uiForm.sqw_ckRebinE, SIGNAL(toggled(bool)), this, SLOT(sOfQwRebinE(bool)));
+  connect(m_uiForm.sqw_cbInput, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(sOfQwInputType(const QString&)));
+  connect(m_uiForm.sqw_pbRefresh, SIGNAL(clicked()), this, SLOT(refreshWSlist()));
+  connect(m_uiForm.sqw_pbPlotInput, SIGNAL(clicked()), this, SLOT(sOfQwPlotInput()));
+
+  // "Slice" tab
+  connect(m_uiForm.slice_pbPlotRaw, SIGNAL(clicked()), this, SLOT(slicePlotRaw()));
+  connect(m_uiForm.slice_ckUseCalib, SIGNAL(toggled(bool)), this, SLOT(sliceCalib(bool)));
+
+  // create validators
+  m_valInt = new QIntValidator(this);
+  m_valDbl = new QDoubleValidator(this);
+
+  // apply validators
+  m_uiForm.leNoGroups->setValidator(m_valInt);
+  m_uiForm.leDetailedBalance->setValidator(m_valInt);
+  m_uiForm.leSpectraMin->setValidator(m_valInt);
+  m_uiForm.leSpectraMax->setValidator(m_valInt);
+  m_uiForm.rebin_leELow->setValidator(m_valDbl);
+  m_uiForm.rebin_leEWidth->setValidator(m_valDbl);
+  m_uiForm.rebin_leEHigh->setValidator(m_valDbl);
+  
+  m_uiForm.sqw_leELow->setValidator(m_valDbl);
+  m_uiForm.sqw_leEWidth->setValidator(m_valDbl);
+  m_uiForm.sqw_leEHigh->setValidator(m_valDbl);
+  m_uiForm.sqw_leQLow->setValidator(m_valDbl);
+  m_uiForm.sqw_leQWidth->setValidator(m_valDbl);
+  m_uiForm.sqw_leQHigh->setValidator(m_valDbl);
+
+  // set default values for save formats
+  m_uiForm.save_ckSPE->setChecked(false);
+  m_uiForm.save_ckNexus->setChecked(true);
+
+  loadSettings();
+
+  refreshWSlist();
+}
+/**
+* This function will hold any Python-dependent setup actions for the interface.
+*/
+void Indirect::initLocalPython()
+{
+  // Nothing to do here at the moment.
+}
+/**
+* This function opens a web browser window to the Mantid Project wiki page for this
+* interface ("Inelastic" subsection of ConvertToEnergy).
+*/
+void Indirect::helpClicked()
+{
+  QString tabName = m_uiForm.tabWidget->tabText(m_uiForm.tabWidget->currentIndex());
+  QString url = "http://www.mantidproject.org/Indirect:";
+  if ( tabName == "Energy Transfer" )
+    url += "EnergyTransfer";
+  else if ( tabName == "Calibration" )
+    url += "Calibration";
+  else if ( tabName == "Diagnostics" )
+    url += "Diagnostics";
+  else if ( tabName == "S(Q, w)" )
+    url += "SofQW";
+  QDesktopServices::openUrl(QUrl(url));
+}
+/**
+* This function will control the actions needed for the Indirect interface when the
+* "Run" button is clicked by the user.
+* @param tryToSave :: whether to try and save the output. Generally true, false when user has clicked on the "Rebin" button instead of "Run"
+*/
+void Indirect::runClicked()
+{
+  QString tabName = m_uiForm.tabWidget->tabText(m_uiForm.tabWidget->currentIndex());
+
+  if ( tabName == "Energy Transfer" )
+  {
+    runConvertToEnergy();
+  }
+  else if ( tabName == "Calibration" )
+  {
+    calibCreate();
+  }
+  else if ( tabName == "Diagnostics" )
+  {
+    sliceRun();
+  }
+  else if ( tabName == "S(Q, w)" )
+  {
+    sOfQwClicked();
+  }
+}
+
+void Indirect::runConvertToEnergy(bool tryToSave)
+{
+  if ( ! validateInput() )
+  {
+    showInformationBox("Please check the input highlighted in red.");
+    return;
+  }
+  QString grouping = createMapFile(m_uiForm.cbMappingOptions->currentText());
+  if ( grouping == "" )
+  {
+    return;
+  }
+
+  QString pyInput = "from mantidsimple import *\n"
+    "import IndirectEnergyConversion as ind\n";
+
+  if ( m_uiForm.ckVerbose->isChecked() ) pyInput += "verbose = True\n";
+  else pyInput += "verbose = False\n";
+
+  pyInput += "first = " +m_uiForm.leSpectraMin->text()+ "\n"
+    "last = " +m_uiForm.leSpectraMax->text()+ "\n"
+    "instrument = '" + m_uiForm.cbInst->currentText()+"'\n"
+    "analyser = '"+m_uiForm.cbAnalyser->currentText()+"'\n"
+    "reflection = '"+m_uiForm.cbReflection->currentText()+"'\n";
+  
+  QStringList runFiles_list = m_uiForm.ind_runFiles->getFilenames();
+  QString runFiles = runFiles_list.join("', r'");
+
+  pyInput += "rawfiles = [r'"+runFiles+"']\n"
+    "Sum = ";
+  if ( m_uiForm.ckSumFiles->isChecked() )
+  {
+    pyInput += "True\n";
+  }
+  else
+  {
+    pyInput += "False\n";
+  }
+
+  if ( m_bgRemoval )
+  {
+    QPair<double,double> bgRange = m_backgroundDialog->getRange();
+    QString startTOF, endTOF;
+    startTOF.setNum(bgRange.first, 'e');
+    endTOF.setNum(bgRange.second, 'e');
+    pyInput += "bgRemove = ["+startTOF+", "+endTOF+"]\n";
+  }
+  else
+  {
+    pyInput += "bgRemove = [0, 0]\n";
+  }
+
+  if ( m_uiForm.ckUseCalib->isChecked() )
+  {
+    QString calib = m_uiForm.ind_calibFile->getFirstFilename();
+    pyInput += "calib = r'"+calib+"'\n";
+  }
+  else
+  {
+    pyInput += "calib = ''\n";
+  }
+
+  if ( ! m_uiForm.rebin_ckDNR->isChecked() )
+  { 
+    QString rebinParam = m_uiForm.rebin_leELow->text() + ","
+      + m_uiForm.rebin_leEWidth->text() + ","
+      + m_uiForm.rebin_leEHigh->text();
+    pyInput += "rebinParam = '"+rebinParam+"'\n";
+  }
+  else
+  {
+    pyInput += "rebinParam = ''\n";
+  }
+
+  if ( m_uiForm.ckDetailedBalance->isChecked() )
+    pyInput += "tempK = "+m_uiForm.leDetailedBalance->text()+"\n";
+  else
+    pyInput += "tempK = -1\n";
+
+  pyInput += "mapfile = r'"+grouping+"'\n";
+
+  if (tryToSave)
+  {
+    pyInput += savePyCode();
+  }
+  else
+  {
+    pyInput += "fileFormats = []\n";
+  }
+
+  if ( m_uiForm.ckCleanUp->isChecked() )
+  {
+    pyInput += "clean = False\n";
+  }
+  else
+  {
+    pyInput += "clean = True\n";
+  }
+
+  if ( isDirty() )
+  {
+    pyInput += "ws_list = ind.convert_to_energy(rawfiles, mapfile, first, last,"
+      "instrument, analyser, reflection,"
+      "SumFiles=Sum, bgremove=bgRemove, tempK=tempK, calib=calib, rebinParam=rebinParam,"
+      "saveFormats=fileFormats, CleanUp=clean, Verbose=verbose)\n";
+  }
+  else if ( isDirtyRebin() )
+  {
+    pyInput += "ws_list = ind.cte_rebin(mapfile, tempK, rebinParam, analyser, reflection,"
+      "fileFormats, CleanUp=clean, Verbose=verbose)\n";
+  }
+  else if ( tryToSave ) // where all we want to do is save and/or plot output
+  {
+    pyInput +=
+      "import re\n"
+      "wslist = mantid.getWorkspaceNames()\n"
+      "save_ws = re.compile(r'_'+ana+ref+'_red')\n"
+      "ws_list = []\n"
+      "for workspace in wslist:\n"
+      "   if save_ws.search(workspace):\n"
+      "      ws_list.append(workspace)\n"
+      "ind.saveItems(ws_list, fileFormats, Verbose=verbose)\n";
+  }
+
+  // Plot Output Handling
+  switch ( m_uiForm.ind_cbPlotOutput->currentIndex() )
+  {
+  case 0: // "None"
+    break;
+  case 1: // "Spectra"
+    {
+      // Plot a spectra of the first result workspace
+      pyInput += 
+        "if ( len(ws_list) > 0 ):\n"
+        "  nSpec = mtd[ws_list[0]].getNumberHistograms()\n"
+        "  plotSpectrum(ws_list[0], range(0, nSpec))\n";
+    }
+    break;
+  case 2: // "Contour"
+    {
+      // Plot a 2D Contour Lines of the first result workspace
+      pyInput += 
+        "if ( len(ws_list) > 0 ):\n"
+        "  ws = importMatrixWorkspace(ws_list[0])\n"
+        "  ws.plotGraph2D()\n";
+    }
+    break;
+  }
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+
+  if ( pyOutput != "" )
+  {
+    if ( pyOutput == "No intermediate workspaces were found. Run with 'Keep Intermediate Workspaces' checked." )
+    {
+      isDirty(true);
+      runConvertToEnergy(tryToSave=tryToSave);
+    }
+    else
+    {
+      showInformationBox("The following error occurred:\n" + pyOutput + "\n\nAnalysis did not complete.");
+    }
+  }
+  else
+  {
+    isDirty(false);
+    isDirtyRebin(false);
+  }
+
+}
+/**
+* This function holds any steps that must be performed on the selection of an instrument,
+* for example loading values from the Instrument Definition File (IDF).
+* @param prefix :: The selected instruments prefix in Mantid.
+*/
+void Indirect::setIDFValues(const QString & prefix)
+{
+  // empty ComboBoxes, LineEdits,etc of previous values
+  m_uiForm.cbAnalyser->clear();
+  m_uiForm.cbReflection->clear();
+  clearReflectionInfo();
+
+  rebinCheck(m_uiForm.rebin_ckDNR->isChecked());
+  detailedBalanceCheck(m_uiForm.ckDetailedBalance->isChecked());
+  resCheck(m_uiForm.cal_ckRES->isChecked());
+
+  // Get list of analysers and populate cbAnalyser
+  QString pyInput = 
+    "from IndirectEnergyConversion import getInstrumentDetails\n"
+    "result = getInstrumentDetails('" + m_uiForm.cbInst->currentText() + "')\n"
+    "print result\n";
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+
+  if ( pyOutput == "" )
+  {
+    showInformationBox("Could not get list of analysers from Instrument Parameter file.");
+  }
+  else
+  {
+    QStringList analysers = pyOutput.split("\n", QString::SkipEmptyParts);
+
+    for (int i = 0; i< analysers.count(); i++ )
+    {
+      QString text; // holds Text field of combo box (name of analyser)
+
+      if ( text != "diffraction" ) // do not put diffraction into the analyser list
+      {
+
+        QVariant data; // holds Data field of combo box (list of reflections)
+
+        QStringList analyser = analysers[i].split("-", QString::SkipEmptyParts);
+
+        text = analyser[0];
+
+        if ( analyser.count() > 1 )
+        {
+          QStringList reflections = analyser[1].split(",", QString::SkipEmptyParts);
+          data = QVariant(reflections);
+          m_uiForm.cbAnalyser->addItem(text, data);
+        }
+        else
+        {
+          m_uiForm.cbAnalyser->addItem(text);
+        }
+      }
+    }
+
+    analyserSelected(m_uiForm.cbAnalyser->currentIndex());
+  }
+}
+
+void Indirect::closeEvent(QCloseEvent* close)
+{
+  (void) close;
+  //saveSettings();
+  Mantid::Kernel::ConfigService::Instance().removeObserver(m_changeObserver);
+}
+
+void Indirect::handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf)
+{
+  std::string key = pNf->key();
+  std::string preValue = pNf->preValue();
+  std::string curValue = pNf->curValue();
+
+  if ( key == "datasearch.directories" || key == "defaultsave.directory" )
+  {
+    loadSettings();
+  }
+}
+/**
+* This function clears the values of the QLineEdit objec  ts used to hold Reflection-specific
+* information.
+*/
+void Indirect::clearReflectionInfo()
+{
+  m_uiForm.leSpectraMin->clear();
+  m_uiForm.leSpectraMax->clear();
+  m_uiForm.leEfixed->clear();
+  
+  isDirty(true);
+}
+/**
+* This function creates the mapping/grouping file for the data analysis.
+* @param groupType :: Type of grouping (All, Group, Indiviual)
+* @return path to mapping file, or an empty string if file could not be created.
+*/
+QString Indirect::createMapFile(const QString& groupType)
+{
+  QString groupFile, ngroup, nspec;
+  QString ndet = "( "+m_uiForm.leSpectraMax->text()+" - "+m_uiForm.leSpectraMin->text()+") + 1";
+
+  if ( groupType == "File" )
+  {
+    groupFile = m_uiForm.ind_mapFile->getFirstFilename();
+    if ( groupFile == "" )
+    {
+      showInformationBox("You must enter a path to the .map file.");
+    }
+    return groupFile;
+  }
+  else if ( groupType == "Groups" )
+  {
+    ngroup = m_uiForm.leNoGroups->text();
+    nspec = "( " +ndet+ " ) / " +ngroup;
+  }
+  else if ( groupType == "All" )
+  {
+    return "All";
+  }
+  else if ( groupType == "Individual" )
+  {
+    return "Individual";
+  }
+
+  groupFile = m_uiForm.cbInst->itemData(m_uiForm.cbInst->currentIndex()).toString().toLower();
+  groupFile += "_" + m_uiForm.cbAnalyser->currentText() + m_uiForm.cbReflection->currentText();
+  groupFile += "_" + groupType + ".map";	
+
+  QString pyInput =
+    "import IndirectEnergyConversion as ind\n"
+    "mapfile = ind.createMappingFile('"+groupFile+"', %1, %2, %3)\n"
+    "print mapfile\n";
+  pyInput = pyInput.arg(ngroup);
+  pyInput = pyInput.arg(nspec);
+  pyInput = pyInput.arg(m_uiForm.leSpectraMin->text());
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+
+  return pyOutput;
+}
+/**
+* This function creates the Python script necessary to set the variables used for saving data
+* in the main convert_to_energy script.
+* @return python code as a string
+*/
+QString Indirect::savePyCode()
+{
+  QStringList fileFormats;
+  QString fileFormatList;
+
+  if ( m_uiForm.save_ckNexus->isChecked() )
+    fileFormats << "nxs";
+  if ( m_uiForm.save_ckSPE->isChecked() )
+    fileFormats << "spe";
+  if ( m_uiForm.save_ckNxSPE->isChecked() )
+    fileFormats << "nxspe";
+
+  if ( fileFormats.size() != 0 )
+    fileFormatList = "[ '" + fileFormats.join("', '") + "']";
+  else
+    fileFormatList = "[]";
+
+  QString pyInput =
+    "# Save File Parameters\n"
+    "fileFormats = " + fileFormatList + "\n";
+
+  return pyInput;
+}
+/**
+* This function is called after calib has run and creates a RES file for use in later analysis (Fury,etc)
+* @param file :: the input file (WBV run.raw)
+*/
+void Indirect::createRESfile(const QString& file)
+{
+  QString pyInput =
+    "from IndirectEnergyConversion import resolution\n"
+    "iconOpt = { 'first': " +QString::number(m_calDblMng->value(m_calResProp["SpecMin"]))+
+    ", 'last': " +QString::number(m_calDblMng->value(m_calResProp["SpecMax"]))+"}\n"
+
+    "instrument = '" + m_uiForm.cbInst->currentText() + "'\n"
+    "analyser = '" + m_uiForm.cbAnalyser->currentText() + "'\n"
+    "reflection = '" + m_uiForm.cbReflection->currentText() + "'\n";
+
+  if ( m_uiForm.cal_ckPlotResult->isChecked() ) { pyInput +=	"plot = True\n"; }
+  else { pyInput += "plot = False\n"; }
+
+  QString rebinParam = QString::number(m_calDblMng->value(m_calResProp["ELow"])) + "," +
+    QString::number(m_calDblMng->value(m_calResProp["EWidth"])) + "," +
+    QString::number(m_calDblMng->value(m_calResProp["EHigh"]));
+
+  QString background = "[ " +QString::number(m_calDblMng->value(m_calResProp["Start"]))+ ", " +QString::number(m_calDblMng->value(m_calResProp["End"]))+"]";
+
+  pyInput +=
+    "background = " + background + "\n"
+    "rebinParam = '" + rebinParam + "'\n"
+    "file = " + file + "\n"
+    "resolution(file, iconOpt, rebinParam, background, instrument, analyser, reflection, plotOpt = plot)\n";
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+
+  if ( pyOutput != "" )
+  {
+    showInformationBox("Unable to create RES file: \n" + pyOutput);
+  }
+}
+/**
+* This function validates the input for the Convert To Energy process, highlighting invalid items.
+* @return true if input is ok, false otherwise
+*/
+bool Indirect::validateInput()
+{
+  bool valid = true;
+  // run files input
+  if ( ! m_uiForm.ind_runFiles->isValid() )
+  {
+    valid = false;
+  }
+
+  // calib file input
+
+  if ( m_uiForm.ckUseCalib->isChecked() && !m_uiForm.ind_calibFile->isValid() )
+  {
+    valid = false;
+  }
+
+  // mapping selection
+  if (
+    ( m_uiForm.cbMappingOptions->currentText() == "Groups" && m_uiForm.leNoGroups->text() == "" ) 
+    ||
+    ( m_uiForm.cbMappingOptions->currentText() == "File" && ! m_uiForm.ind_mapFile->isValid() )
+    )
+  {
+    valid = false;
+    m_uiForm.valNoGroups->setText("*");
+  }
+  else
+  {
+    m_uiForm.valNoGroups->setText("");
+  }
+
+  // detailed balance
+  if ( m_uiForm.ckDetailedBalance->isChecked() && m_uiForm.leDetailedBalance->text() == "" )
+  {
+    valid = false;
+    m_uiForm.valDetailedBalance->setText("*");
+  }
+  else
+  {
+    m_uiForm.valDetailedBalance->setText("");
+  }
+
+  // SpectraMin/SpectraMax
+  if (
+    m_uiForm.leSpectraMin->text() == ""
+    ||
+    m_uiForm.leSpectraMax->text() == ""
+    ||
+    (
+    m_uiForm.leSpectraMin->text().toDouble() > m_uiForm.leSpectraMax->text().toDouble()
+    )
+    )
+  {
+    valid = false;
+    m_uiForm.valSpectraMin->setText("*");
+    m_uiForm.valSpectraMax->setText("*");
+  }
+  else
+  {
+    m_uiForm.valSpectraMin->setText("");
+    m_uiForm.valSpectraMax->setText("");
+  }
+
+  if ( ! m_uiForm.rebin_ckDNR->isChecked() )
+  {
+    //
+    if ( m_uiForm.rebin_leELow->text() == "" )
+    {
+      valid = false;
+      m_uiForm.valELow->setText("*");
+    }
+    else
+    {
+      m_uiForm.valELow->setText("");
+    }
+
+    if ( m_uiForm.rebin_leEWidth->text() == "" )
+    {
+      valid = false;
+      m_uiForm.valEWidth->setText("*");
+    }
+    else
+    {
+      m_uiForm.valEWidth->setText("");
+    }
+
+    if ( m_uiForm.rebin_leEHigh->text() == "" )
+    {
+      valid = false;
+      m_uiForm.valEHigh->setText("*");
+    }
+    else
+    {
+      m_uiForm.valEHigh->setText("");
+    }
+
+    if ( m_uiForm.rebin_leELow->text().toDouble() > m_uiForm.rebin_leEHigh->text().toDouble() )
+    {
+      valid = false;
+      m_uiForm.valELow->setText("*");
+      m_uiForm.valEHigh->setText("*");
+    }
+
+  }
+  else
+  {
+    m_uiForm.valELow->setText("");
+    m_uiForm.valEWidth->setText("");
+    m_uiForm.valEHigh->setText("");
+  }
+
+
+  return valid;
+}
+/**
+* Validates user input on the calibration tab.
+*/
+bool Indirect::validateCalib()
+{
+  bool valid = true;
+
+  // run number
+  if ( ! m_uiForm.cal_leRunNo->isValid() )
+  {
+    valid = false;
+  }
+
+  if ( m_uiForm.cal_ckRES->isChecked() )
+  {
+    if ( m_calDblMng->value(m_calResProp["Start"]) > m_calDblMng->value(m_calResProp["End"]) )
+    {
+      valid = false;
+    }
+
+    if ( m_calDblMng->value(m_calResProp["ELow"]) > m_calDblMng->value(m_calResProp["EHigh"]) )
+    {
+      valid = false;
+    }
+
+  }
+
+  return valid;
+}
+
+bool Indirect::validateSofQw()
+{
+  bool valid = true;
+
+  if ( m_uiForm.sqw_cbInput->currentText() == "File" )
+  {
+    if ( ! m_uiForm.sqw_inputFile->isValid() )
+    {
+      valid = false;
+    }
+  }
+  else
+  {
+    if ( m_uiForm.sqw_cbWorkspace->currentText().isEmpty() )
+    {
+      valid = false;
+      m_uiForm.sqw_valWorkspace->setText("*");
+    }
+    else
+    {
+      m_uiForm.sqw_valWorkspace->setText(" ");
+    }
+  }
+
+  if ( m_uiForm.sqw_ckRebinE->isChecked() )
+  {
+    if ( m_uiForm.sqw_leELow->text() == "" )
+    {
+      valid = false;
+      m_uiForm.sqw_valELow->setText("*");
+    }
+    else
+    {
+      m_uiForm.sqw_valELow->setText(" ");
+    }
+
+    if ( m_uiForm.sqw_leEWidth->text() == "" )
+    {
+      valid = false;
+      m_uiForm.sqw_valEWidth->setText("*");
+    }
+    else
+    {
+      m_uiForm.sqw_valEWidth->setText(" ");
+    }
+    if ( m_uiForm.sqw_leEHigh->text() == "" )
+    {
+      valid = false;
+      m_uiForm.sqw_valEHigh->setText("*");
+    }
+    else
+    {
+      m_uiForm.sqw_valEHigh->setText(" ");
+    }
+  }
+
+  if ( m_uiForm.sqw_leQLow->text() == "" )
+  {
+    valid = false;
+    m_uiForm.sqw_valQLow->setText("*");
+  }
+  else
+  {
+    m_uiForm.sqw_valQLow->setText(" ");
+  }
+
+  if ( m_uiForm.sqw_leQWidth->text() == "" )
+  {
+    valid = false;
+    m_uiForm.sqw_valQWidth->setText("*");
+  }
+  else
+  {
+    m_uiForm.sqw_valQWidth->setText(" ");
+  }
+  if ( m_uiForm.sqw_leQHigh->text() == "" )
+  {
+    valid = false;
+    m_uiForm.sqw_valQHigh->setText("*");
+  }
+  else
+  {
+    m_uiForm.sqw_valQHigh->setText(" ");
+  }
+  return valid;
+}
+
+bool Indirect::validateSlice()
+{
+  bool valid = true;
+
+  if ( ! m_uiForm.slice_inputFile->isValid() )
+  {
+    valid = false;
+  }
+
+  return valid;
+}
+/**
+* Used to check whether any changes have been made by the user to the interface.
+* @return boolean m_isDirty
+*/
+bool Indirect::isDirty()
+{
+  return m_isDirty;
+}
+/**
+* Used to set value of m_isDirty, called from each function that signifies a change in the user interface.
+* Will be set to false in functions that use the input.
+* @param state :: whether to set the value to true or false.
+*/
+void Indirect::isDirty(bool state)
+{
+  m_isDirty = state;
+}
+/**
+* Used to check whether any changes have been made by the user to the interface.
+* @return boolean m_isDirtyRebin
+*/
+bool Indirect::isDirtyRebin()
+{
+  return m_isDirtyRebin;
+}
+/**
+* Used to set value of m_isDirtyRebin, called from each function that signifies a change in the user interface.
+* Will be set to false in functions that use the input.
+* @param state :: whether to set the value to true or false.
+*/
+void Indirect::isDirtyRebin(bool state)
+{
+  m_isDirtyRebin = state;
+}
+
+void Indirect::loadSettings()
+{
+  
+  // set values of m_dataDir and m_saveDir
+  m_dataDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("datasearch.directories"));
+  m_dataDir = m_dataDir.split(";", QString::SkipEmptyParts)[0];
+  m_saveDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory"));
+
+
+  QSettings settings;
+  // Load settings for MWRunFile widgets
+  settings.beginGroup(m_settingsGroup + "DataFiles");
+  settings.setValue("last_directory", m_dataDir);
+  m_uiForm.ind_runFiles->readSettings(settings.group());
+  m_uiForm.cal_leRunNo->readSettings(settings.group());
+  m_uiForm.slice_inputFile->readSettings(settings.group());
+  settings.endGroup();
+
+  settings.beginGroup(m_settingsGroup + "ProcessedFiles");
+  settings.setValue("last_directory", m_saveDir);
+  m_uiForm.ind_calibFile->readSettings(settings.group());
+  m_uiForm.ind_mapFile->readSettings(settings.group());
+  m_uiForm.slice_calibFile->readSettings(settings.group());
+  m_uiForm.sqw_inputFile->readSettings(settings.group());
+  settings.endGroup();
+
+  // And for instrument/analyser/reflection
+}
+
+void Indirect::saveSettings()
+{
+  // The only settings that we want to keep are the instrument / analyser / reflection ones
+  // Instrument is handled in ConvertToEnergy class
+}
+
+void Indirect::setupCalibration()
+{
+  int noDec = 6;
+  // General
+  m_calDblMng = new QtDoublePropertyManager();
+  m_calGrpMng = new QtGroupPropertyManager();
+
+  /* Calib */
+  m_calCalTree = new QtTreePropertyBrowser();
+  m_uiForm.cal_treeCal->addWidget(m_calCalTree);
+
+  DoubleEditorFactory *doubleEditorFactory = new DoubleEditorFactory();
+  m_calCalTree->setFactoryForManager(m_calDblMng, doubleEditorFactory);
+
+  m_calCalProp["PeakMin"] = m_calDblMng->addProperty("Peak Min");
+  m_calCalProp["PeakMax"] = m_calDblMng->addProperty("Peak Max");
+  m_calCalProp["BackMin"] = m_calDblMng->addProperty("Back Min");
+  m_calCalProp["BackMax"] = m_calDblMng->addProperty("Back Max");
+
+  m_calCalTree->addProperty(m_calCalProp["PeakMin"]);
+  m_calCalTree->addProperty(m_calCalProp["PeakMax"]);
+  m_calCalTree->addProperty(m_calCalProp["BackMin"]);
+  m_calCalTree->addProperty(m_calCalProp["BackMax"]);
+
+  m_calCalPlot = new QwtPlot(this);
+  m_calCalPlot->setAxisFont(QwtPlot::xBottom, this->font());
+  m_calCalPlot->setAxisFont(QwtPlot::yLeft, this->font());
+  m_uiForm.cal_plotCal->addWidget(m_calCalPlot);
+  m_calCalPlot->setCanvasBackground(Qt::white);
+
+  // R1 = Peak, R2 = Background
+  m_calCalR1 = new MantidWidgets::RangeSelector(m_calCalPlot);
+  connect(m_calCalR1, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double)));
+  connect(m_calCalR1, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double)));
+  m_calCalR2 = new MantidWidgets::RangeSelector(m_calCalPlot);
+  m_calCalR2->setColour(Qt::darkGreen); // dark green to signify background range
+  connect(m_calCalR2, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double)));
+  connect(m_calCalR2, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double)));
+
+  // Res
+  m_calResTree = new QtTreePropertyBrowser();
+  m_uiForm.cal_treeRes->addWidget(m_calResTree);
+
+  m_calResTree->setFactoryForManager(m_calDblMng, doubleEditorFactory);
+
+  // Res - Spectra Selection
+  m_calResProp["SpecMin"] = m_calDblMng->addProperty("Spectra Min");
+  m_calResProp["SpecMax"] = m_calDblMng->addProperty("Spectra Max");
+  m_calResTree->addProperty(m_calResProp["SpecMin"]);
+  m_calDblMng->setDecimals(m_calResProp["SpecMin"], 0);
+  m_calResTree->addProperty(m_calResProp["SpecMax"]);
+  m_calDblMng->setDecimals(m_calResProp["SpecMax"], 0);
+
+  // Res - Background Properties
+  QtProperty* resBG = m_calGrpMng->addProperty("Background");
+  m_calResProp["Start"] = m_calDblMng->addProperty("Start");
+  m_calResProp["End"] = m_calDblMng->addProperty("End");
+  resBG->addSubProperty(m_calResProp["Start"]);
+  resBG->addSubProperty(m_calResProp["End"]);
+  m_calResTree->addProperty(resBG);
+
+  // Res - rebinning
+  QtProperty* resRB = m_calGrpMng->addProperty("Rebinning");
+  m_calResProp["ELow"] = m_calDblMng->addProperty("Low");
+  m_calDblMng->setDecimals(m_calResProp["ELow"], noDec);
+  m_calDblMng->setValue(m_calResProp["ELow"], -0.2);
+  m_calResProp["EWidth"] = m_calDblMng->addProperty("Width");
+  m_calDblMng->setDecimals(m_calResProp["EWidth"], noDec);
+  m_calDblMng->setValue(m_calResProp["EWidth"], 0.002);
+  m_calResProp["EHigh"] = m_calDblMng->addProperty("High");
+  m_calDblMng->setDecimals(m_calResProp["EHigh"], noDec);
+  m_calDblMng->setValue(m_calResProp["EHigh"], 0.2);
+  resRB->addSubProperty(m_calResProp["ELow"]);
+  resRB->addSubProperty(m_calResProp["EWidth"]);
+  resRB->addSubProperty(m_calResProp["EHigh"]);
+  m_calResTree->addProperty(resRB);
+
+  m_calResPlot = new QwtPlot(this);
+  m_calResPlot->setAxisFont(QwtPlot::xBottom, this->font());
+  m_calResPlot->setAxisFont(QwtPlot::yLeft, this->font());
+  m_uiForm.cal_plotRes->addWidget(m_calResPlot);
+  m_calResPlot->setCanvasBackground(Qt::white);
+
+  // Create ResR2 first so ResR1 is drawn above it.
+  m_calResR2 = new MantidWidgets::RangeSelector(m_calResPlot, 
+    MantidQt::MantidWidgets::RangeSelector::XMINMAX, true, true);
+  m_calResR2->setColour(Qt::darkGreen);
+  m_calResR1 = new MantidWidgets::RangeSelector(m_calResPlot);
+
+  connect(m_calResR1, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double)));
+  connect(m_calResR1, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double)));
+  connect(m_calResR1, SIGNAL(rangeChanged(double, double)), m_calResR2, SLOT(setRange(double, double)));
+  connect(m_calDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(calUpdateRS(QtProperty*, double)));
+  connect(m_calDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(calUpdateRS(QtProperty*, double)));
+  connect(m_calDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(calUpdateRS(QtProperty*, double)));
+}
+
+void Indirect::setupSlice()
+{
+  // Property Tree
+  m_sltTree = new QtTreePropertyBrowser();
+  m_uiForm.slice_properties->addWidget(m_sltTree);
+
+  // Create Manager Objects
+  m_sltDblMng = new QtDoublePropertyManager();
+  m_sltBlnMng = new QtBoolPropertyManager();
+  m_sltGrpMng = new QtGroupPropertyManager();
+
+  // Editor Factories
+  DoubleEditorFactory *doubleEditorFactory = new DoubleEditorFactory();
+  QtCheckBoxFactory *checkboxFactory = new QtCheckBoxFactory();
+  m_sltTree->setFactoryForManager(m_sltDblMng, doubleEditorFactory);
+  m_sltTree->setFactoryForManager(m_sltBlnMng, checkboxFactory);
+
+  // Create Properties
+  m_sltProp["SpecMin"] = m_sltDblMng->addProperty("Spectra Min");
+  m_sltProp["SpecMax"] = m_sltDblMng->addProperty("Spectra Max");
+  m_sltDblMng->setDecimals(m_sltProp["SpecMin"], 0);
+  m_sltDblMng->setDecimals(m_sltProp["SpecMax"], 0);
+
+  m_sltProp["R1S"] = m_sltDblMng->addProperty("Start");
+  m_sltProp["R1E"] = m_sltDblMng->addProperty("End");
+  m_sltProp["R2S"] = m_sltDblMng->addProperty("Start");
+  m_sltProp["R2E"] = m_sltDblMng->addProperty("End");
+
+  m_sltProp["UseTwoRanges"] = m_sltBlnMng->addProperty("Use Two Ranges");
+
+  m_sltProp["Range1"] = m_sltGrpMng->addProperty("Range One");
+  m_sltProp["Range1"]->addSubProperty(m_sltProp["R1S"]);
+  m_sltProp["Range1"]->addSubProperty(m_sltProp["R1E"]);
+  m_sltProp["Range2"] = m_sltGrpMng->addProperty("Range Two");
+  m_sltProp["Range2"]->addSubProperty(m_sltProp["R2S"]);
+  m_sltProp["Range2"]->addSubProperty(m_sltProp["R2E"]);
+
+  m_sltTree->addProperty(m_sltProp["SpecMin"]);
+  m_sltTree->addProperty(m_sltProp["SpecMax"]);
+  m_sltTree->addProperty(m_sltProp["Range1"]);
+  m_sltTree->addProperty(m_sltProp["UseTwoRanges"]);
+  m_sltTree->addProperty(m_sltProp["Range2"]);
+
+  // Create Slice Plot Widget for Range Selection
+  m_sltPlot = new QwtPlot(this);
+  m_sltPlot->setAxisFont(QwtPlot::xBottom, this->font());
+  m_sltPlot->setAxisFont(QwtPlot::yLeft, this->font());
+  m_uiForm.slice_plot->addWidget(m_sltPlot);
+  m_sltPlot->setCanvasBackground(Qt::white);
+  // We always want one range selector... the second one can be controlled from
+  // within the sliceTwoRanges(bool state) function
+  m_sltR1 = new MantidWidgets::RangeSelector(m_sltPlot);
+  connect(m_sltR1, SIGNAL(minValueChanged(double)), this, SLOT(sliceMinChanged(double)));
+  connect(m_sltR1, SIGNAL(maxValueChanged(double)), this, SLOT(sliceMaxChanged(double)));
+
+  // second range
+  // create the second range
+  m_sltR2 = new MantidWidgets::RangeSelector(m_sltPlot);
+  m_sltR2->setColour(Qt::darkGreen); // dark green for background
+  connect(m_sltR1, SIGNAL(rangeChanged(double, double)), m_sltR2, SLOT(setRange(double, double)));
+  connect(m_sltR2, SIGNAL(minValueChanged(double)), this, SLOT(sliceMinChanged(double)));
+  connect(m_sltR2, SIGNAL(maxValueChanged(double)), this, SLOT(sliceMaxChanged(double)));
+  m_sltR2->setRange(m_sltR1->getRange());
+
+  // Refresh the plot window
+  m_sltPlot->replot();
+
+  connect(m_sltDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(sliceUpdateRS(QtProperty*, double)));
+  connect(m_sltBlnMng, SIGNAL(valueChanged(QtProperty*, bool)), this, SLOT(sliceTwoRanges(QtProperty*, bool)));
+
+  sliceTwoRanges(0, false); // set default value
+}
+
+void Indirect::refreshWSlist()
+{
+  m_uiForm.sqw_cbWorkspace->clear();
+  std::set<std::string> workspaceList = Mantid::API::AnalysisDataService::Instance().getObjectNames();
+  if ( ! workspaceList.empty() )
+  {
+    std::set<std::string>::const_iterator wsIt;
+    for ( wsIt=workspaceList.begin(); wsIt != workspaceList.end(); ++wsIt )
+    {
+      m_uiForm.sqw_cbWorkspace->addItem(QString::fromStdString(*wsIt));
+    }
+  }
+}
+/**
+* This function is called when the user selects an analyser from the cbAnalyser QComboBox
+* object. It's main purpose is to initialise the values for the Reflection ComboBox.
+* @param index :: Index of the value selected in the combo box.
+*/
+void Indirect::analyserSelected(int index)
+{
+  // populate Reflection combobox with correct values for Analyser selected.
+  m_uiForm.cbReflection->clear();
+  clearReflectionInfo();
+
+
+  QVariant currentData = m_uiForm.cbAnalyser->itemData(index);
+  if ( currentData == QVariant::Invalid )
+  {
+    m_uiForm.lbReflection->setEnabled(false);
+    m_uiForm.cbReflection->setEnabled(false);
+    return;
+  }
+  else
+  {
+    m_uiForm.lbReflection->setEnabled(true);
+    m_uiForm.cbReflection->setEnabled(true);
+    QStringList reflections = currentData.toStringList();
+    for ( int i = 0; i < reflections.count(); i++ )
+    {
+      m_uiForm.cbReflection->addItem(reflections[i]);
+    }
+  }
+
+  reflectionSelected(m_uiForm.cbReflection->currentIndex());
+}
+/**
+* This function is called when the user selects a reflection from the cbReflection QComboBox
+* object.
+* @param index :: Index of the value selected in the combo box.
+*/
+void Indirect::reflectionSelected(int index)
+{
+  // first, clear values in assosciated boxes:
+  clearReflectionInfo();
+
+  QString pyInput =
+    "from IndirectEnergyConversion import getReflectionDetails\n"
+    "instrument = '" + m_uiForm.cbInst->currentText() + "'\n"
+    "analyser = '" + m_uiForm.cbAnalyser->currentText() + "'\n"
+    "reflection = '" + m_uiForm.cbReflection->currentText() + "'\n"
+    "print getReflectionDetails(instrument, analyser, reflection)\n";
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+
+  QStringList values = pyOutput.split("\n", QString::SkipEmptyParts);
+
+  if ( values.count() < 3 )
+  {
+    showInformationBox("Could not gather necessary data from parameter file.");
+    return;
+  }
+  else
+  {
+    QString analysisType = values[0];
+    m_uiForm.leSpectraMin->setText(values[1]);
+    m_uiForm.leSpectraMax->setText(values[2]);
+    m_calDblMng->setValue(m_calResProp["SpecMin"], values[1].toDouble());
+    m_calDblMng->setValue(m_calResProp["SpecMax"], values[2].toDouble());
+    m_sltDblMng->setValue(m_sltProp["SpecMin"], values[1].toDouble());
+    m_sltDblMng->setValue(m_sltProp["SpecMax"], values[2].toDouble());
+    
+    if ( values.count() >= 8 )
+    {
+      m_uiForm.leEfixed->setText(values[3]);
+      
+      m_calDblMng->setValue(m_calCalProp["PeakMin"], values[4].toDouble());
+      m_calDblMng->setValue(m_calCalProp["PeakMax"], values[5].toDouble());
+      m_calDblMng->setValue(m_calCalProp["BackMin"], values[6].toDouble());
+      m_calDblMng->setValue(m_calCalProp["BackMax"], values[7].toDouble());
+
+      m_sltDblMng->setValue(m_sltProp["R1S"], values[4].toDouble());
+      m_sltDblMng->setValue(m_sltProp["R1E"], values[5].toDouble());
+      m_sltDblMng->setValue(m_sltProp["R2S"], values[6].toDouble());
+      m_sltDblMng->setValue(m_sltProp["R2E"], values[7].toDouble());
+    }
+    else
+    {
+      m_uiForm.leEfixed->clear();
+    }
+    // Default rebinning parameters can be set in instrument parameter file
+    if ( values.count() == 9 )
+    {
+      QStringList rbp = values[8].split(",", QString::SkipEmptyParts);
+      m_uiForm.rebin_ckDNR->setChecked(false);
+      m_uiForm.rebin_leELow->setText(rbp[0]);
+      m_uiForm.rebin_leEWidth->setText(rbp[1]);
+      m_uiForm.rebin_leEHigh->setText(rbp[2]);
+    }
+    else
+    {
+      m_uiForm.rebin_ckDNR->setChecked(true);
+      m_uiForm.rebin_leELow->setText("");
+      m_uiForm.rebin_leEWidth->setText("");
+      m_uiForm.rebin_leEHigh->setText("");
+    }
+  }
+
+  // clear validation markers
+  validateInput();
+  validateCalib();
+  validateSlice();
+}
+/**
+* This function runs when the user makes a selection on the cbMappingOptions QComboBox.
+* @param groupType :: Value of selection made by user.
+*/
+void Indirect::mappingOptionSelected(const QString& groupType)
+{
+  if ( groupType == "File" )
+  {
+    m_uiForm.swMapping->setCurrentIndex(0);
+  }
+  else if ( groupType == "All" )
+  {
+    m_uiForm.swMapping->setCurrentIndex(2);
+  }
+  else if ( groupType == "Individual" )
+  {
+    m_uiForm.swMapping->setCurrentIndex(2);
+  }
+  else if ( groupType == "Groups" )
+  {
+    m_uiForm.swMapping->setCurrentIndex(1);
+  }
+
+  isDirtyRebin(true);
+}
+
+void Indirect::tabChanged(int index)
+{
+  QString tabName = m_uiForm.tabWidget->tabText(index);
+  m_uiForm.pbRun->setText("Run " + tabName);
+}
+/**
+* This function is called when the user clicks on the Background Removal button. It
+* displays the Background Removal dialog, initialising it if it hasn't been already.
+*/
+void Indirect::backgroundClicked()
+{
+  if ( m_backgroundDialog == NULL )
+  {
+    m_backgroundDialog = new Background(this);
+    connect(m_backgroundDialog, SIGNAL(accepted()), this, SLOT(backgroundRemoval()));
+    connect(m_backgroundDialog, SIGNAL(rejected()), this, SLOT(backgroundRemoval()));
+    m_backgroundDialog->show();
+  }
+  else
+  {
+    m_backgroundDialog->show();
+  }
+}
+/**
+* Slot called when m_backgroundDialog is closed. Assesses whether user desires background removal.
+*/
+void Indirect::backgroundRemoval()
+{
+  if ( m_backgroundDialog->removeBackground() )
+  {
+    m_bgRemoval = true;
+    m_uiForm.pbBack_2->setText("Background Removal (On)");
+  }
+  else
+  {
+    m_bgRemoval = false;
+    m_uiForm.pbBack_2->setText("Background Removal (Off)");
+  }
+  isDirty(true);
+}
+/**
+* Plots raw time data from .raw file before any data conversion has been performed.
+*/
+void Indirect::plotRaw()
+{
+  if ( m_uiForm.ind_runFiles->isValid() )
+  {
+    bool ok;
+    QString spectraRange = QInputDialog::getText(this, "Insert Spectra Ranges", "Range: ", QLineEdit::Normal, m_uiForm.leSpectraMin->text() +"-"+ m_uiForm.leSpectraMax->text(), &ok);
+
+    if ( !ok || spectraRange.isEmpty() )
+    {
+      return;
+    }
+    QStringList specList = spectraRange.split("-");
+
+    QString rawFile = m_uiForm.ind_runFiles->getFirstFilename();
+    if ( (specList.size() > 2) || ( specList.size() < 1) )
+    {
+      showInformationBox("Invalid input. Must be of form <SpecMin>-<SpecMax>");
+      return;
+    }
+    if ( specList.size() == 1 )
+    {
+      specList.append(specList[0]);
+    }
+
+    QString bgrange;
+
+    if ( m_bgRemoval )
+    {
+      QPair<double, double> range = m_backgroundDialog->getRange();
+      bgrange = "[ " + QString::number(range.first) + "," + QString::number(range.second) + " ]";
+    }
+    else
+    {
+      bgrange = "[-1, -1]";
+    }
+
+    QString pyInput =
+      "from mantidsimple import *\n"
+      "from mantidplot import *\n"
+      "import os.path as op\n"
+      "file = r'" + rawFile + "'\n"
+      "name = op.splitext( op.split(file)[1] )[0]\n"
+      "bgrange = " + bgrange + "\n"
+      "LoadRaw(file, name, SpectrumMin="+specList[0]+", SpectrumMax="+specList[1]+")\n"
+      "if ( bgrange != [-1, -1] ):\n"
+      "    #Remove background\n"
+      "    FlatBackground(name, name+'_bg', bgrange[0], bgrange[1], Mode='Mean')\n"
+      "    GroupDetectors(name+'_bg', name+'_grp', DetectorList=range("+specList[0]+","+specList[1]+"+1))\n"
+      "    GroupDetectors(name, name+'_grp_raw', DetectorList=range("+specList[0]+","+specList[1]+"+1))\n"
+      "else: # Just group detectors as they are\n"
+      "    GroupDetectors(name, name+'_grp', DetectorList=range("+specList[0]+","+specList[1]+"+1))\n"
+      "graph = plotSpectrum(name+'_grp', 0)\n";
+
+    QString pyOutput = runPythonCode(pyInput).trimmed();
+    
+    if ( pyOutput != "" )
+    {
+      showInformationBox(pyOutput);
+    }
+
+  }
+  else
+  {
+    showInformationBox("You must select a run file.");
+  }
+}
+/**
+* This function will disable the necessary elements of the interface when the user selects "Do Not Rebin"
+* and enable them again when this is de-selected.
+* @param state :: whether the "Do Not Rebin" checkbox is checked
+*/
+void Indirect::rebinCheck(bool state) 
+{
+  QString val;
+  if ( state ) val = " ";
+  else val = "*";
+  m_uiForm.rebin_pbRebin->setEnabled( !state );
+  m_uiForm.rebin_lbLow->setEnabled( !state );
+  m_uiForm.rebin_lbWidth->setEnabled( !state );
+  m_uiForm.rebin_lbHigh->setEnabled( !state );
+  m_uiForm.rebin_leELow->setEnabled( !state );
+  m_uiForm.rebin_leEWidth->setEnabled( !state );
+  m_uiForm.rebin_leEHigh->setEnabled( !state );
+  m_uiForm.valELow->setEnabled(!state);
+  m_uiForm.valELow->setText(val);
+  m_uiForm.valEWidth->setEnabled(!state);
+  m_uiForm.valEWidth->setText(val);
+  m_uiForm.valEHigh->setEnabled(!state);
+  m_uiForm.valEHigh->setText(val);
+  isDirtyRebin(true);
+}
+/**
+* Disables/enables the relevant parts of the UI when user checks/unchecks the Detailed Balance
+* ckDetailedBalance checkbox.
+* @param state :: state of the checkbox
+*/
+void Indirect::detailedBalanceCheck(bool state)
+{
+  m_uiForm.leDetailedBalance->setEnabled(state);
+  m_uiForm.lbDBKelvin->setEnabled(state);
+
+  isDirtyRebin(true);
+}
+/**
+* This function enables/disables the display of the options involved in creating the RES file.
+* @param state :: whether checkbox is checked or unchecked
+*/
+void Indirect::resCheck(bool state)
+{
+  m_calResR1->setVisible(state);
+  m_calResR2->setVisible(state);
+}
+/**
+* This function just calls the runClicked slot, but with tryToSave being 'false'
+*/
+void Indirect::rebinData()
+{
+  runConvertToEnergy(false);
+}
+
+void Indirect::useCalib(bool state)
+{
+  m_uiForm.ind_calibFile->isOptional(!state);
+  m_uiForm.ind_calibFile->setEnabled(state);
+}
+/**
+* This function is called when the user clicks on the "Create Calibration File" button.
+* Pretty much does what it says on the tin.
+*/
+void Indirect::calibCreate()
+{
+  QString file = m_uiForm.cal_leRunNo->getFirstFilename();
+  if ( ! validateCalib() || file == "" )
+  {
+    showInformationBox("Please check your input.");
+  }
+  else
+  {
+    QString suffix = "_" + m_uiForm.cbAnalyser->currentText() + m_uiForm.cbReflection->currentText() + "_calib";
+
+    QString filenames = "[r'"+m_uiForm.cal_leRunNo->getFilenames().join("', r'")+"']";
+
+    QString pyInput =
+      "from IndirectEnergyConversion import createCalibFile\n"
+      "plot = ";
+
+    if ( m_uiForm.cal_ckPlotResult->isChecked() )
+      pyInput +=	"True\n";
+    else
+      pyInput += "False\n";
+
+    pyInput +=
+      "file = createCalibFile("+filenames+", '"+suffix+"', %1, %2, %3, %4, %5, %6, PlotOpt=plot)\n"
+      "print file\n";
+
+    pyInput = pyInput.arg(QString::number(m_calDblMng->value(m_calCalProp["PeakMin"])));
+    pyInput = pyInput.arg(QString::number(m_calDblMng->value(m_calCalProp["PeakMax"])));
+    pyInput = pyInput.arg(QString::number(m_calDblMng->value(m_calCalProp["BackMin"])));
+    pyInput = pyInput.arg(QString::number(m_calDblMng->value(m_calCalProp["BackMax"])));
+    pyInput = pyInput.arg(m_uiForm.leSpectraMin->text());
+    pyInput = pyInput.arg(m_uiForm.leSpectraMax->text());
+
+    QString pyOutput = runPythonCode(pyInput).trimmed();
+
+    if ( pyOutput == "" )
+    {
+      showInformationBox("An error occurred creating the calib file.\n");
+    }
+    else
+    {
+      if ( m_uiForm.cal_ckRES->isChecked() )
+      {
+        createRESfile(filenames);
+      }
+      m_uiForm.ind_calibFile->setFileText(pyOutput);
+      m_uiForm.ckUseCalib->setChecked(true);
+    }
+  }
+}
+/**
+* Sets interface as "Dirty" - catches all relevant user changes that don't need special action
+*/
+void Indirect::setasDirty()
+{
+  isDirty(true);
+}
+/*
+* Sets interface as "Dirty" - catches all relevant user changes that don't need special action
+*/
+void Indirect::setasDirtyRebin()
+{
+  isDirtyRebin(true);
+}
+/**
+* Controls the ckUseCalib checkbox to automatically check it when a user inputs a file from clicking on 'browse'.
+* @param calib :: path to calib file
+*/
+void Indirect::calibFileChanged(const QString & calib)
+{
+  if ( calib.isEmpty() )
+  {
+    m_uiForm.ckUseCalib->setChecked(false);
+  }
+  else
+  {
+    m_uiForm.ckUseCalib->setChecked(true);
+  }
+}
+// CALIBRATION TAB
+void Indirect::calPlotRaw()
+{
+  QString filename = m_uiForm.cal_leRunNo->getFirstFilename();
+  
+  if ( filename == "" )
+  {
+    showInformationBox("Please enter a run number.");
+    return;
+  }
+    
+  QFileInfo fi(filename);
+  QString wsname = fi.baseName();
+
+  QString pyInput = "LoadRaw(r'" + filename + "', '" + wsname + "', SpectrumMin=" 
+    + m_uiForm.leSpectraMin->text() + ", SpectrumMax="
+    + m_uiForm.leSpectraMax->text() + ")\n";
+  QString pyOutput = runPythonCode(pyInput);
+    
+  Mantid::API::MatrixWorkspace_sptr input = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsname.toStdString()));
+
+  QVector<double> dataX = QVector<double>::fromStdVector(input->readX(0));
+  QVector<double> dataY = QVector<double>::fromStdVector(input->readY(0));
+
+  if ( m_calCalCurve != NULL )
+  {
+    m_calCalCurve->attach(0);
+    delete m_calCalCurve;
+    m_calCalCurve = 0;
+  }
+
+  m_calCalCurve = new QwtPlotCurve();
+  m_calCalCurve->setData(dataX, dataY);
+  m_calCalCurve->attach(m_calCalPlot);
+  
+  m_calCalPlot->setAxisScale(QwtPlot::xBottom, dataX.first(), dataX.last());
+
+  m_calCalR1->setRange(dataX.first(), dataX.last());
+  m_calCalR2->setRange(dataX.first(), dataX.last());
+
+  // Replot
+  m_calCalPlot->replot();
+
+}
+
+void Indirect::calPlotEnergy()
+{
+  if ( ! m_uiForm.cal_leRunNo->isValid() )
+  {
+    showInformationBox("Run number not valid.");
+    return;
+  }
+  QString files = "[r'" + m_uiForm.cal_leRunNo->getFilenames().join("', r'") + "']";
+  QString pyInput =
+    "from IndirectEnergyConversion import resolution\n"
+    "iconOpt = { 'first': " +QString::number(m_calDblMng->value(m_calResProp["SpecMin"]))+
+    ", 'last': " +QString::number(m_calDblMng->value(m_calResProp["SpecMax"]))+ "}\n"
+    "instrument = '" + m_uiForm.cbInst->currentText() + "'\n"
+    "analyser = '" + m_uiForm.cbAnalyser->currentText() + "'\n"
+    "reflection = '" + m_uiForm.cbReflection->currentText() + "'\n"
+    "files = " + files + "\n"
+    "outWS = resolution(files, iconOpt, '', '', instrument, analyser, reflection, Res=False)\n"
+    "print outWS\n";
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+  
+  Mantid::API::MatrixWorkspace_sptr input = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(pyOutput.toStdString()));
+
+  QVector<double> dataX = QVector<double>::fromStdVector(input->readX(0));
+  QVector<double> dataY = QVector<double>::fromStdVector(input->readY(0));
+
+  if ( m_calResCurve != NULL )
+  {
+    m_calResCurve->attach(0);
+    delete m_calResCurve;
+    m_calResCurve = 0;
+  }
+
+  m_calResCurve = new QwtPlotCurve();
+  m_calResCurve->setData(dataX, dataY);
+  m_calResCurve->attach(m_calResPlot);
+  
+  m_calResPlot->setAxisScale(QwtPlot::xBottom, dataX.first(), dataX.last());
+  m_calResR1->setRange(dataX.first(), dataX.last());
+
+  m_calResR2->setMinimum(m_calDblMng->value(m_calResProp["ELow"]));
+  m_calResR2->setMaximum(m_calDblMng->value(m_calResProp["EHigh"]));
+
+  // Replot
+  m_calResPlot->replot();
+}
+
+void Indirect::calMinChanged(double val)
+{
+  MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
+  if ( from == m_calCalR1 )
+  {
+    m_calDblMng->setValue(m_calCalProp["PeakMin"], val);
+  }
+  else if ( from == m_calCalR2 )
+  {
+    m_calDblMng->setValue(m_calCalProp["BackMin"], val);
+  }
+  else if ( from == m_calResR1 )
+  {
+    m_calDblMng->setValue(m_calResProp["Start"], val);
+  }
+}
+
+void Indirect::calMaxChanged(double val)
+{
+  MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
+  if ( from == m_calCalR1 )
+  {
+    m_calDblMng->setValue(m_calCalProp["PeakMax"], val);
+  }
+  else if ( from == m_calCalR2 )
+  {
+    m_calDblMng->setValue(m_calCalProp["BackMax"], val);
+  }
+  else if ( from == m_calResR1 )
+  {
+    m_calDblMng->setValue(m_calResProp["End"], val);
+  }
+}
+
+void Indirect::calUpdateRS(QtProperty* prop, double val)
+{
+  if ( prop == m_calCalProp["PeakMin"] ) m_calCalR1->setMinimum(val);
+  else if ( prop == m_calCalProp["PeakMax"] ) m_calCalR1->setMaximum(val);
+  else if ( prop == m_calCalProp["BackMin"] ) m_calCalR2->setMinimum(val);
+  else if ( prop == m_calCalProp["BackMax"] ) m_calCalR2->setMaximum(val);
+  else if ( prop == m_calResProp["Start"] ) m_calResR1->setMinimum(val);
+  else if ( prop == m_calResProp["End"] ) m_calResR1->setMaximum(val);
+  else if ( prop == m_calResProp["ELow"] ) m_calResR2->setMinimum(val);
+  else if ( prop == m_calResProp["EHigh"] ) m_calResR2->setMaximum(val);
+}
+
+void Indirect::sOfQwClicked()
+{
+  if ( validateSofQw() )
+  {
+    QString rebinString = m_uiForm.sqw_leQLow->text()+","+m_uiForm.sqw_leQWidth->text()+","+m_uiForm.sqw_leQHigh->text();
+    QString pyInput = "from mantidsimple import *\n";
+
+    if ( m_uiForm.sqw_cbInput->currentText() == "File" )
+    {
+      pyInput +=
+        "filename = r'" +m_uiForm.sqw_inputFile->getFirstFilename() + "'\n"
+        "(dir, file) = os.path.split(filename)\n"
+        "(sqwInput, ext) = os.path.splitext(file)\n"
+        "LoadNexus(filename, sqwInput)\n"
+        "cleanup = True\n"; 
+    }
+    else
+    {
+      pyInput +=
+        "sqwInput = '" + m_uiForm.sqw_cbWorkspace->currentText() + "'\n"
+        "cleanup = False\n";
+    }
+
+    // Create output name before rebinning
+    pyInput += "sqwOutput = sqwInput[:-3] + 'sqw'\n";
+
+    if ( m_uiForm.sqw_ckRebinE->isChecked() )
+    {
+      QString eRebinString = m_uiForm.sqw_leELow->text()+","+m_uiForm.sqw_leEWidth->text()+","+m_uiForm.sqw_leEHigh->text();
+      pyInput += "Rebin(sqwInput, sqwInput+'_r', '" + eRebinString + "')\n"
+        "if cleanup:\n"
+        "    mantid.deleteWorkspace(sqwInput)\n"
+        "sqwInput += '_r'\n"
+        "cleanup = True\n";
+    }
+    pyInput +=
+      "efixed = " + m_uiForm.leEfixed->text() + "\n"
+      "rebin = '" + rebinString + "'\n"      
+      "SofQW(sqwInput, sqwOutput, rebin, 'Indirect', EFixed=efixed)\n"
+      "if cleanup:\n"
+      "    mantid.deleteWorkspace(sqwInput)\n";
+
+    if ( m_uiForm.sqw_ckSave->isChecked() )
+    {
+      pyInput += "SaveNexus(sqwOutput, sqwOutput+'.nxs')\n";
+    }
+
+    if ( m_uiForm.sqw_cbPlotType->currentText() == "Contour" )
+    {
+      pyInput += "importMatrixWorkspace(sqwOutput).plotGraph2D()\n";
+    }
+    else if ( m_uiForm.sqw_cbPlotType->currentText() == "Specta" )
+    {
+      pyInput +=
+        "nspec = mtd[sqwOuput].getNumberHistograms()\n"
+        "plotSpectra(sqwOutput, range(0, nspec)\n";
+    }
+        
+    QString pyOutput = runPythonCode(pyInput).trimmed();
+  }
+  else
+  {
+    showInformationBox("Some of your input is invalid. Please check the input highlighted.");
+  }
+}
+
+void Indirect::sOfQwRebinE(bool state)
+{
+  QString val;
+  if ( state ) val = "*";
+  else val = " ";
+  m_uiForm.sqw_leELow->setEnabled(state);
+  m_uiForm.sqw_leEWidth->setEnabled(state);
+  m_uiForm.sqw_leEHigh->setEnabled(state);
+  m_uiForm.sqw_valELow->setEnabled(state);
+  m_uiForm.sqw_valELow->setText(val);
+  m_uiForm.sqw_valEWidth->setEnabled(state);
+  m_uiForm.sqw_valEWidth->setText(val);
+  m_uiForm.sqw_valEHigh->setEnabled(state);
+  m_uiForm.sqw_valEHigh->setText(val);
+  m_uiForm.sqw_lbELow->setEnabled(state);
+  m_uiForm.sqw_lbEWidth->setEnabled(state);
+  m_uiForm.sqw_lbEHigh->setEnabled(state);
+}
+
+void Indirect::sOfQwInputType(const QString& input)
+{
+  if ( input == "File" )
+  {
+    m_uiForm.sqw_swInput->setCurrentIndex(0);
+  }
+  else
+  {
+    m_uiForm.sqw_swInput->setCurrentIndex(1);
+    refreshWSlist();
+  }
+}
+
+void Indirect::sOfQwPlotInput()
+{
+  QString pyInput = "from mantidsimple import *\n"
+    "from mantidplot import *\n";
+
+  //...
+  if ( m_uiForm.sqw_cbInput->currentText() == "File" )
+  {
+    // get filename
+    if ( m_uiForm.sqw_inputFile->isValid() )
+    {
+      pyInput +=
+        "filename = r'" + m_uiForm.sqw_inputFile->getFirstFilename() + "'\n"
+        "(dir, file) = os.path.split(filename)\n"
+        "(input, ext) = os.path.splitext(file)\n"
+        "LoadNexus(filename, input)\n";
+    }
+    else
+    {
+      showInformationBox("Invalid filename.");
+      return;
+    }
+  }
+  else
+  {
+    pyInput += "input = '" + m_uiForm.sqw_cbWorkspace->currentText() + "'\n";
+  }
+
+  pyInput += "ConvertSpectrumAxis(input, input+'_q', 'MomentumTransfer', 'Indirect')\n"
+    "ws = importMatrixWorkspace(input+'_q')\n"
+    "ws.plotGraph2D()\n";
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+
+}
+
+// SLICE
+void Indirect::sliceRun()
+{
+  if ( ! validateSlice() )
+  {
+    showInformationBox("Please check your input.");
+    return;
+  }
+
+  QString pyInput =
+    "from IndirectEnergyConversion import slice\n"
+    "tofRange = [" + QString::number(m_sltDblMng->value(m_sltProp["R1S"])) + ","
+    + QString::number(m_sltDblMng->value(m_sltProp["R1E"]));
+  if ( m_sltBlnMng->value(m_sltProp["UseTwoRanges"]) )
+  {
+    pyInput +=
+      "," + QString::number(m_sltDblMng->value(m_sltProp["R2S"])) + ","
+      + QString::number(m_sltDblMng->value(m_sltProp["R2E"])) + "]\n";
+  }
+  else
+  {
+    pyInput += "]\n";
+  }
+  if ( m_uiForm.slice_ckUseCalib->isChecked() )
+  {
+    pyInput +=
+      "calib = r'" + m_uiForm.slice_calibFile->getFirstFilename() + "'\n";
+  }
+  else
+  {
+    pyInput +=
+      "calib = ''\n";
+  }
+  QString filenames = m_uiForm.slice_inputFile->getFilenames().join("', r'");
+  QString suffix = m_uiForm.cbAnalyser->currentText() + m_uiForm.cbReflection->currentText();
+  pyInput +=
+    "rawfile = [r'" + filenames + "']\n"
+    "spectra = ["+ QString::number(m_sltDblMng->value(m_sltProp["SpecMin"])) + "," + QString::number(m_sltDblMng->value(m_sltProp["SpecMax"])) +"]\n"
+    "suffix = '" + suffix + "'\n";
+
+  if ( m_uiForm.slice_ckVerbose->isChecked() ) pyInput += "verbose = True\n";
+  else pyInput += "verbose = False\n";
+
+  if ( m_uiForm.slice_ckPlot->isChecked() ) pyInput += "plot = True\n";
+  else pyInput += "plot = False\n";
+
+  if ( m_uiForm.slice_ckSave->isChecked() ) pyInput += "save = True\n";
+  else pyInput += "save = False\n";
+
+  pyInput +=
+    "slice(rawfile, calib, tofRange, spectra, suffix, Save=save, Verbose=verbose, Plot=plot)";
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+}
+
+void Indirect::slicePlotRaw()
+{
+  if ( m_uiForm.slice_inputFile->isValid() )
+  {
+    QString filename = m_uiForm.slice_inputFile->getFirstFilename();
+    QFileInfo fi(filename);
+    QString wsname = fi.baseName();
+
+    QString pyInput = "LoadRaw(r'" + filename + "', '" + wsname + "', SpectrumMin=" 
+      + m_uiForm.leSpectraMin->text() + ", SpectrumMax="
+      + m_uiForm.leSpectraMax->text() + ")\n";
+    QString pyOutput = runPythonCode(pyInput);
+
+    Mantid::API::MatrixWorkspace_sptr input = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsname.toStdString()));
+
+    QVector<double> dataX = QVector<double>::fromStdVector(input->readX(0));
+    QVector<double> dataY = QVector<double>::fromStdVector(input->readY(0));
+
+    if ( m_sltDataCurve != NULL )
+    {
+      m_sltDataCurve->attach(0);
+      delete m_sltDataCurve;
+      m_sltDataCurve = 0;
+    }
+
+    m_sltDataCurve = new QwtPlotCurve();
+    m_sltDataCurve->setData(dataX, dataY);
+    m_sltDataCurve->attach(m_sltPlot);
+
+    m_sltPlot->setAxisScale(QwtPlot::xBottom, dataX.first(), dataX.last());
+
+    m_sltR1->setRange(dataX.first(), dataX.last());
+
+    // Replot
+    m_sltPlot->replot();
+  }
+  else
+  {
+    showInformationBox("Selected input files are invalid.");
+  }
+
+}
+
+void Indirect::sliceTwoRanges(QtProperty*, bool state)
+{
+  m_sltR2->setVisible(state);
+}
+
+void Indirect::sliceCalib(bool state)
+{
+  m_uiForm.slice_calibFile->setEnabled(state);
+  m_uiForm.slice_calibFile->isOptional(!state);
+}
+
+void Indirect::sliceMinChanged(double val)
+{
+  MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
+  if ( from == m_sltR1 )
+  {
+    m_sltDblMng->setValue(m_sltProp["R1S"], val);
+  }
+  else if ( from == m_sltR2 )
+  {
+    m_sltDblMng->setValue(m_sltProp["R2S"], val);
+  }
+}
+
+void Indirect::sliceMaxChanged(double val)
+{
+  MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
+  if ( from == m_sltR1 )
+  {
+    m_sltDblMng->setValue(m_sltProp["R1E"], val);
+  }
+  else if ( from == m_sltR2 )
+  {
+    m_sltDblMng->setValue(m_sltProp["R2E"], val);
+  }
+}
+
+void Indirect::sliceUpdateRS(QtProperty* prop, double val)
+{
+  if ( prop == m_sltProp["R1S"] ) m_sltR1->setMinimum(val);
+  else if ( prop == m_sltProp["R1E"] ) m_sltR1->setMaximum(val);
+  else if ( prop == m_sltProp["R2S"] ) m_sltR2->setMinimum(val);
+  else if ( prop == m_sltProp["R2E"] ) m_sltR2->setMaximum(val);
+}
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDataAnalysis.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDataAnalysis.cpp
index 5317e87862542820daf5cebea7bc4dfb30a382d9..88cf1295ba1179f69c793cd591d3941d1e5164a0 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDataAnalysis.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDataAnalysis.cpp
@@ -1,2509 +1,2509 @@
-//----------------------
-// Includes
-//----------------------
-#include "MantidQtCustomInterfaces/IndirectDataAnalysis.h"
-#include "MantidQtAPI/ManageUserDirectories.h"
-#include "MantidQtMantidWidgets/RangeSelector.h"
-
-#include "MantidAPI/CompositeFunctionMW.h"
-#include "MantidAPI/AlgorithmManager.h"
-#include "MantidAPI/AnalysisDataService.h"
-#include "MantidAPI/MatrixWorkspace.h"
-#include "MantidAPI/ITableWorkspace.h"
-#include "MantidAPI/TableRow.h"
-#include "MantidAPI/IConstraint.h"
-#include "MantidAPI/ConstraintFactory.h"
-#include "MantidAPI/Expression.h"
-
-#include <QValidator>
-#include <QIntValidator>
-#include <QDoubleValidator>
-
-#include <QLineEdit>
-#include <QFileInfo>
-#include <QMenu>
-
-#include <QDesktopServices>
-#include <QUrl>
-
-#include "DoubleEditorFactory.h"
-#include <QtCheckBoxFactory>
-#include "qttreepropertybrowser.h"
-#include "qtpropertymanager.h"
-#include "qteditorfactory.h"
-
-#include <qwt_plot.h>
-#include <qwt_plot_curve.h>
-
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-//Add this class to the list of specialised dialogs in this namespace
-DECLARE_SUBWINDOW(IndirectDataAnalysis);
-
-IndirectDataAnalysis::IndirectDataAnalysis(QWidget *parent) :
-  UserSubWindow(parent), m_nDec(6), m_valInt(NULL), m_valDbl(NULL), 
-  m_furyResFileType(true), 
-  m_elwPlot(NULL), m_elwR1(NULL), m_elwR2(NULL), m_elwDataCurve(NULL),
-  m_msdPlot(NULL), m_msdRange(NULL), m_msdDataCurve(NULL), m_msdTree(NULL), m_msdDblMng(NULL),
-  m_furPlot(NULL), m_furRange(NULL), m_furCurve(NULL), m_furTree(NULL), m_furDblMng(NULL),
-  m_ffDataCurve(NULL), m_ffFitCurve(NULL),
-  m_cfDataCurve(NULL), m_cfCalcCurve(NULL),
-  m_changeObserver(*this, &IndirectDataAnalysis::handleDirectoryChange)
-{
-}
-
-void IndirectDataAnalysis::closeEvent(QCloseEvent*)
-{
-  Mantid::Kernel::ConfigService::Instance().removeObserver(m_changeObserver);
-}
-
-void IndirectDataAnalysis::handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf)
-{
-  std::string key = pNf->key();
-  std::string preValue = pNf->preValue();
-  std::string curValue = pNf->curValue();
-
-  if ( key == "defaultsave.directory" )
-  {
-    loadSettings();
-  }
-}
-
-void IndirectDataAnalysis::initLayout()
-{
-  m_uiForm.setupUi(this);
-
-  // Connect Poco Notification Observer
-  Mantid::Kernel::ConfigService::Instance().addObserver(m_changeObserver);
-
-  // create validators
-  m_valInt = new QIntValidator(this);
-  m_valDbl = new QDoubleValidator(this);
-  // Create Editor Factories
-  m_dblEdFac = new DoubleEditorFactory();
-  m_blnEdFac = new QtCheckBoxFactory();
-
-  m_stringManager = new QtStringPropertyManager();
-
-  setupElwin();
-  setupMsd();
-  setupFury();
-  setupFuryFit();
-  setupConFit();
-  setupAbsorptionF2Py();
-  setupAbsCor();
-
-  connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(help()));
-  connect(m_uiForm.pbRun, SIGNAL(clicked()), this, SLOT(run()));
-  connect(m_uiForm.pbManageDirs, SIGNAL(clicked()), this, SLOT(openDirectoryDialog()));
-
-  // absorption
-  connect(m_uiForm.abs_cbShape, SIGNAL(currentIndexChanged(int)), m_uiForm.abs_swDetails, SLOT(setCurrentIndex(int)));
-  // apply validators - absorption
-  m_uiForm.abs_leAttenuation->setValidator(m_valDbl);
-  m_uiForm.abs_leScatter->setValidator(m_valDbl);
-  m_uiForm.abs_leDensity->setValidator(m_valDbl);
-  m_uiForm.abs_leFlatHeight->setValidator(m_valDbl);
-  m_uiForm.abs_leWidth->setValidator(m_valDbl);
-  m_uiForm.abs_leThickness->setValidator(m_valDbl);
-  m_uiForm.abs_leElementSize->setValidator(m_valDbl);
-  m_uiForm.abs_leCylHeight->setValidator(m_valDbl);
-  m_uiForm.abs_leRadius->setValidator(m_valDbl);
-  m_uiForm.abs_leSlices->setValidator(m_valInt);
-  m_uiForm.abs_leAnnuli->setValidator(m_valInt);
-}
-
-void IndirectDataAnalysis::initLocalPython()
-{
-  loadSettings();
-}
-
-void IndirectDataAnalysis::loadSettings()
-{
-  QSettings settings;
-  QString settingsGroup = "CustomInterfaces/IndirectAnalysis/";
-  QString saveDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory"));
-
-  settings.beginGroup(settingsGroup + "ProcessedFiles");
-  settings.setValue("last_directory", saveDir);
-  m_uiForm.elwin_inputFile->readSettings(settings.group());
-  m_uiForm.msd_inputFile->readSettings(settings.group());
-  m_uiForm.fury_iconFile->readSettings(settings.group());
-  m_uiForm.fury_resFile->readSettings(settings.group());
-  m_uiForm.furyfit_inputFile->readSettings(settings.group());
-  m_uiForm.confit_inputFile->readSettings(settings.group());
-  m_uiForm.confit_resInput->readSettings(settings.group());
-  m_uiForm.abs_inputFile->readSettings(settings.group());
-  m_uiForm.absp_inputFile->readSettings(settings.group());
-  m_uiForm.abscor_sample->readSettings(settings.group());
-  m_uiForm.abscor_can->readSettings(settings.group());
-  settings.endGroup();
-}
-
-void IndirectDataAnalysis::setupElwin()
-{
-  // Create QtTreePropertyBrowser object
-  m_elwTree = new QtTreePropertyBrowser();
-  m_uiForm.elwin_properties->addWidget(m_elwTree);
-
-  // Create Manager Objects
-  m_elwDblMng = new QtDoublePropertyManager();
-  m_elwBlnMng = new QtBoolPropertyManager();
-  m_elwGrpMng = new QtGroupPropertyManager();
-
-  // Editor Factories
-  m_elwTree->setFactoryForManager(m_elwDblMng, m_dblEdFac);
-  m_elwTree->setFactoryForManager(m_elwBlnMng, m_blnEdFac);
-
-  // Create Properties
-  m_elwProp["R1S"] = m_elwDblMng->addProperty("Start");
-  m_elwDblMng->setDecimals(m_elwProp["R1S"], m_nDec);
-  m_elwProp["R1E"] = m_elwDblMng->addProperty("End");
-  m_elwDblMng->setDecimals(m_elwProp["R1E"], m_nDec);  
-  m_elwProp["R2S"] = m_elwDblMng->addProperty("Start");
-  m_elwDblMng->setDecimals(m_elwProp["R2S"], m_nDec);
-  m_elwProp["R2E"] = m_elwDblMng->addProperty("End");
-  m_elwDblMng->setDecimals(m_elwProp["R2E"], m_nDec);
-
-  m_elwProp["UseTwoRanges"] = m_elwBlnMng->addProperty("Use Two Ranges");
-
-  m_elwProp["Range1"] = m_elwGrpMng->addProperty("Range One");
-  m_elwProp["Range1"]->addSubProperty(m_elwProp["R1S"]);
-  m_elwProp["Range1"]->addSubProperty(m_elwProp["R1E"]);
-  m_elwProp["Range2"] = m_elwGrpMng->addProperty("Range Two");
-  m_elwProp["Range2"]->addSubProperty(m_elwProp["R2S"]);
-  m_elwProp["Range2"]->addSubProperty(m_elwProp["R2E"]);
-
-  m_elwTree->addProperty(m_elwProp["Range1"]);
-  m_elwTree->addProperty(m_elwProp["UseTwoRanges"]);
-  m_elwTree->addProperty(m_elwProp["Range2"]);
-
-  // Create Slice Plot Widget for Range Selection
-  m_elwPlot = new QwtPlot(this);
-  m_elwPlot->setAxisFont(QwtPlot::xBottom, this->font());
-  m_elwPlot->setAxisFont(QwtPlot::yLeft, this->font());
-  m_uiForm.elwin_plot->addWidget(m_elwPlot);
-  m_elwPlot->setCanvasBackground(Qt::white);
-  // We always want one range selector... the second one can be controlled from
-  // within the elwinTwoRanges(bool state) function
-  m_elwR1 = new MantidWidgets::RangeSelector(m_elwPlot);
-  connect(m_elwR1, SIGNAL(minValueChanged(double)), this, SLOT(elwinMinChanged(double)));
-  connect(m_elwR1, SIGNAL(maxValueChanged(double)), this, SLOT(elwinMaxChanged(double)));
-  // create the second range
-  m_elwR2 = new MantidWidgets::RangeSelector(m_elwPlot);
-  m_elwR2->setColour(Qt::darkGreen); // dark green for background
-  connect(m_elwR1, SIGNAL(rangeChanged(double, double)), m_elwR2, SLOT(setRange(double, double)));
-  connect(m_elwR2, SIGNAL(minValueChanged(double)), this, SLOT(elwinMinChanged(double)));
-  connect(m_elwR2, SIGNAL(maxValueChanged(double)), this, SLOT(elwinMaxChanged(double)));
-  m_elwR2->setRange(m_elwR1->getRange());
-  // Refresh the plot window
-  m_elwPlot->replot();
-  
-  connect(m_elwDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(elwinUpdateRS(QtProperty*, double)));
-  connect(m_elwBlnMng, SIGNAL(valueChanged(QtProperty*, bool)), this, SLOT(elwinTwoRanges(QtProperty*, bool)));
-  elwinTwoRanges(0, false);
-
-  // m_uiForm element signals and slots
-  connect(m_uiForm.elwin_pbPlotInput, SIGNAL(clicked()), this, SLOT(elwinPlotInput()));
-
-  // Set any default values
-  m_elwDblMng->setValue(m_elwProp["R1S"], -0.02);
-  m_elwDblMng->setValue(m_elwProp["R1E"], 0.02);
-}
-
-void IndirectDataAnalysis::setupMsd()
-{
-  // Tree Browser
-  m_msdTree = new QtTreePropertyBrowser();
-  m_uiForm.msd_properties->addWidget(m_msdTree);
-
-  m_msdDblMng = new QtDoublePropertyManager();
-
-  m_msdTree->setFactoryForManager(m_msdDblMng, m_dblEdFac);
-
-  m_msdProp["Start"] = m_msdDblMng->addProperty("StartX");
-  m_msdDblMng->setDecimals(m_msdProp["Start"], m_nDec);
-  m_msdProp["End"] = m_msdDblMng->addProperty("EndX");
-  m_msdDblMng->setDecimals(m_msdProp["End"], m_nDec);
-
-  m_msdTree->addProperty(m_msdProp["Start"]);
-  m_msdTree->addProperty(m_msdProp["End"]);
-
-  m_msdPlot = new QwtPlot(this);
-  m_uiForm.msd_plot->addWidget(m_msdPlot);
-
-  // Cosmetics
-  m_msdPlot->setAxisFont(QwtPlot::xBottom, this->font());
-  m_msdPlot->setAxisFont(QwtPlot::yLeft, this->font());
-  m_msdPlot->setCanvasBackground(Qt::white);
-
-  m_msdRange = new MantidWidgets::RangeSelector(m_msdPlot);
-
-  connect(m_msdRange, SIGNAL(minValueChanged(double)), this, SLOT(msdMinChanged(double)));
-  connect(m_msdRange, SIGNAL(maxValueChanged(double)), this, SLOT(msdMaxChanged(double)));
-  connect(m_msdDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(msdUpdateRS(QtProperty*, double)));
-
-  connect(m_uiForm.msd_pbPlotInput, SIGNAL(clicked()), this, SLOT(msdPlotInput()));
-}
-
-void IndirectDataAnalysis::setupFury()
-{
-  m_furTree = new QtTreePropertyBrowser();
-  m_uiForm.fury_TreeSpace->addWidget(m_furTree);
-
-  m_furDblMng = new QtDoublePropertyManager();
-
-  m_furPlot = new QwtPlot(this);
-  m_uiForm.fury_PlotSpace->addWidget(m_furPlot);
-  m_furPlot->setCanvasBackground(Qt::white);
-  m_furPlot->setAxisFont(QwtPlot::xBottom, this->font());
-  m_furPlot->setAxisFont(QwtPlot::yLeft, this->font());
-
-  m_furProp["ELow"] = m_furDblMng->addProperty("ELow");
-  m_furDblMng->setDecimals(m_furProp["ELow"], m_nDec);
-  m_furProp["EWidth"] = m_furDblMng->addProperty("EWidth");
-  m_furDblMng->setDecimals(m_furProp["EWidth"], m_nDec);
-  m_furProp["EHigh"] = m_furDblMng->addProperty("EHigh");
-  m_furDblMng->setDecimals(m_furProp["EHigh"], m_nDec);
-
-  m_furTree->addProperty(m_furProp["ELow"]);
-  m_furTree->addProperty(m_furProp["EWidth"]);
-  m_furTree->addProperty(m_furProp["EHigh"]);
-
-  m_furTree->setFactoryForManager(m_furDblMng, m_dblEdFac);
-
-  m_furRange = new MantidQt::MantidWidgets::RangeSelector(m_furPlot);
-
-  // signals / slots & validators
-  connect(m_furRange, SIGNAL(minValueChanged(double)), this, SLOT(furyMinChanged(double)));
-  connect(m_furRange, SIGNAL(maxValueChanged(double)), this, SLOT(furyMaxChanged(double)));
-  connect(m_furDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(furyUpdateRS(QtProperty*, double)));
-  
-  connect(m_uiForm.fury_cbInputType, SIGNAL(currentIndexChanged(int)), m_uiForm.fury_swInput, SLOT(setCurrentIndex(int)));  
-  connect(m_uiForm.fury_cbResType, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(furyResType(const QString&)));
-  connect(m_uiForm.fury_pbPlotInput, SIGNAL(clicked()), this, SLOT(furyPlotInput()));
-}
-
-void IndirectDataAnalysis::setupFuryFit()
-{
-  m_ffTree = new QtTreePropertyBrowser();
-  m_uiForm.furyfit_properties->addWidget(m_ffTree);
-  
-  // Setup FuryFit Plot Window
-  m_ffPlot = new QwtPlot(this);
-  m_ffPlot->setAxisFont(QwtPlot::xBottom, this->font());
-  m_ffPlot->setAxisFont(QwtPlot::yLeft, this->font());
-  m_uiForm.furyfit_vlPlot->addWidget(m_ffPlot);
-  m_ffPlot->setCanvasBackground(QColor(255,255,255));
-  
-  m_ffRangeS = new MantidQt::MantidWidgets::RangeSelector(m_ffPlot);
-  connect(m_ffRangeS, SIGNAL(minValueChanged(double)), this, SLOT(furyfitXMinSelected(double)));
-  connect(m_ffRangeS, SIGNAL(maxValueChanged(double)), this, SLOT(furyfitXMaxSelected(double)));
-
-  m_ffBackRangeS = new MantidQt::MantidWidgets::RangeSelector(m_ffPlot,
-    MantidQt::MantidWidgets::RangeSelector::YSINGLE);
-  m_ffBackRangeS->setRange(0.0,1.0);
-  m_ffBackRangeS->setColour(Qt::darkGreen);
-  connect(m_ffBackRangeS, SIGNAL(minValueChanged(double)), this, SLOT(furyfitBackgroundSelected(double)));
-
-  // setupTreePropertyBrowser
-  m_groupManager = new QtGroupPropertyManager();
-  m_ffDblMng = new QtDoublePropertyManager();
-  m_ffRangeManager = new QtDoublePropertyManager();
-  
-  m_ffTree->setFactoryForManager(m_ffDblMng, m_dblEdFac);
-  m_ffTree->setFactoryForManager(m_ffRangeManager, m_dblEdFac);
-
-  m_ffProp["StartX"] = m_ffRangeManager->addProperty("StartX");
-  m_ffRangeManager->setDecimals(m_ffProp["StartX"], m_nDec);
-  m_ffProp["EndX"] = m_ffRangeManager->addProperty("EndX");
-  m_ffRangeManager->setDecimals(m_ffProp["EndX"], m_nDec);
-
-  connect(m_ffRangeManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(furyfitRangePropChanged(QtProperty*, double)));
-
-  m_ffProp["LinearBackground"] = m_groupManager->addProperty("LinearBackground");
-  m_ffProp["BackgroundA0"] = m_ffRangeManager->addProperty("A0");
-  m_ffRangeManager->setDecimals(m_ffProp["BackgroundA0"], m_nDec);
-  m_ffProp["LinearBackground"]->addSubProperty(m_ffProp["BackgroundA0"]);
-
-  m_ffProp["Exponential1"] = createExponential("Exponential 1");
-  m_ffProp["Exponential2"] = createExponential("Exponential 2");
-  
-  m_ffProp["StretchedExp"] = createStretchedExp("Stretched Exponential");
-
-  furyfitTypeSelection(m_uiForm.furyfit_cbFitType->currentIndex());
-
-  // Connect to PlotGuess checkbox
-  connect(m_ffDblMng, SIGNAL(propertyChanged(QtProperty*)), this, SLOT(furyfitPlotGuess(QtProperty*)));
-
-  // Signal/slot ui connections
-  connect(m_uiForm.furyfit_inputFile, SIGNAL(fileEditingFinished()), this, SLOT(furyfitPlotInput()));
-  connect(m_uiForm.furyfit_cbFitType, SIGNAL(currentIndexChanged(int)), this, SLOT(furyfitTypeSelection(int)));
-  connect(m_uiForm.furyfit_pbPlotInput, SIGNAL(clicked()), this, SLOT(furyfitPlotInput()));
-  connect(m_uiForm.furyfit_leSpecNo, SIGNAL(editingFinished()), this, SLOT(furyfitPlotInput()));
-  connect(m_uiForm.furyfit_cbInputType, SIGNAL(currentIndexChanged(int)), m_uiForm.furyfit_swInput, SLOT(setCurrentIndex(int)));  
-  connect(m_uiForm.furyfit_pbSeqFit, SIGNAL(clicked()), this, SLOT(furyfitSequential()));
-  // apply validators - furyfit
-  m_uiForm.furyfit_leSpecNo->setValidator(m_valInt);
-
-  // Set a custom handler for the QTreePropertyBrowser's ContextMenu event
-  m_ffTree->setContextMenuPolicy(Qt::CustomContextMenu);
-  connect(m_ffTree, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(fitContextMenu(const QPoint &)));
-}
-
-void IndirectDataAnalysis::setupConFit()
-{
-  // Create Property Managers
-  m_cfGrpMng = new QtGroupPropertyManager();
-  m_cfBlnMng = new QtBoolPropertyManager();
-  m_cfDblMng = new QtDoublePropertyManager();
-
-  // Create TreeProperty Widget
-  m_cfTree = new QtTreePropertyBrowser();
-  m_uiForm.confit_properties->addWidget(m_cfTree);
-
-  // add factories to managers
-  m_cfTree->setFactoryForManager(m_cfBlnMng, m_blnEdFac);
-  m_cfTree->setFactoryForManager(m_cfDblMng, m_dblEdFac);
-
-  // Create Plot Widget
-  m_cfPlot = new QwtPlot(this);
-  m_cfPlot->setAxisFont(QwtPlot::xBottom, this->font());
-  m_cfPlot->setAxisFont(QwtPlot::yLeft, this->font());
-  m_cfPlot->setCanvasBackground(Qt::white);
-  m_uiForm.confit_plot->addWidget(m_cfPlot);
-
-  // Create Range Selectors
-  m_cfRangeS = new MantidQt::MantidWidgets::RangeSelector(m_cfPlot);
-  m_cfBackgS = new MantidQt::MantidWidgets::RangeSelector(m_cfPlot, 
-    MantidQt::MantidWidgets::RangeSelector::YSINGLE);
-  m_cfBackgS->setColour(Qt::darkGreen);
-  m_cfBackgS->setRange(0.0, 1.0);
-  m_cfHwhmRange = new MantidQt::MantidWidgets::RangeSelector(m_cfPlot);
-  m_cfHwhmRange->setColour(Qt::red);
-
-  // Populate Property Widget
-  m_cfProp["FitRange"] = m_cfGrpMng->addProperty("Fitting Range");
-  m_cfProp["StartX"] = m_cfDblMng->addProperty("StartX");
-  m_cfDblMng->setDecimals(m_cfProp["StartX"], m_nDec);
-  m_cfProp["EndX"] = m_cfDblMng->addProperty("EndX");
-  m_cfDblMng->setDecimals(m_cfProp["EndX"], m_nDec);
-  m_cfProp["FitRange"]->addSubProperty(m_cfProp["StartX"]);
-  m_cfProp["FitRange"]->addSubProperty(m_cfProp["EndX"]);
-  m_cfTree->addProperty(m_cfProp["FitRange"]);
-
-  m_cfProp["LinearBackground"] = m_cfGrpMng->addProperty("Background");
-  m_cfProp["BGA0"] = m_cfDblMng->addProperty("A0");
-  m_cfDblMng->setDecimals(m_cfProp["BGA0"], m_nDec);
-  m_cfProp["BGA1"] = m_cfDblMng->addProperty("A1");
-  m_cfDblMng->setDecimals(m_cfProp["BGA1"], m_nDec);
-  m_cfProp["LinearBackground"]->addSubProperty(m_cfProp["BGA0"]);
-  m_cfProp["LinearBackground"]->addSubProperty(m_cfProp["BGA1"]);
-  m_cfTree->addProperty(m_cfProp["LinearBackground"]);
-
-  // Delta Function
-  m_cfProp["DeltaFunction"] = m_cfGrpMng->addProperty("Delta Function");
-  m_cfProp["UseDeltaFunc"] = m_cfBlnMng->addProperty("Use");
-  m_cfProp["DeltaHeight"] = m_cfDblMng->addProperty("Height");
-  m_cfDblMng->setDecimals(m_cfProp["DeltaHeight"], m_nDec);
-  m_cfProp["DeltaFunction"]->addSubProperty(m_cfProp["UseDeltaFunc"]);
-  m_cfTree->addProperty(m_cfProp["DeltaFunction"]);
-
-  m_cfProp["Lorentzian1"] = createLorentzian("Lorentzian 1");
-  m_cfProp["Lorentzian2"] = createLorentzian("Lorentzian 2");
-
-  // Connections
-  connect(m_cfRangeS, SIGNAL(minValueChanged(double)), this, SLOT(confitMinChanged(double)));
-  connect(m_cfRangeS, SIGNAL(maxValueChanged(double)), this, SLOT(confitMaxChanged(double)));
-  connect(m_cfBackgS, SIGNAL(minValueChanged(double)), this, SLOT(confitBackgLevel(double)));
-  connect(m_cfHwhmRange, SIGNAL(minValueChanged(double)), this, SLOT(confitHwhmChanged(double)));
-  connect(m_cfHwhmRange, SIGNAL(maxValueChanged(double)), this, SLOT(confitHwhmChanged(double)));
-  connect(m_cfDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(confitUpdateRS(QtProperty*, double)));
-  connect(m_cfBlnMng, SIGNAL(valueChanged(QtProperty*, bool)), this, SLOT(confitCheckBoxUpdate(QtProperty*, bool)));
-
-  connect(m_cfDblMng, SIGNAL(propertyChanged(QtProperty*)), this, SLOT(confitPlotGuess(QtProperty*)));
-
-  // Have HWHM Range linked to Fit Start/End Range
-  connect(m_cfRangeS, SIGNAL(rangeChanged(double, double)), m_cfHwhmRange, SLOT(setRange(double, double)));
-  m_cfHwhmRange->setRange(-1.0,1.0);
-  confitHwhmUpdateRS(0.02);
-
-  confitTypeSelection(m_uiForm.confit_cbFitType->currentIndex());
-  confitBgTypeSelection(m_uiForm.confit_cbBackground->currentIndex());
-
-  // Replot input automatically when file / spec no changes
-  connect(m_uiForm.confit_leSpecNo, SIGNAL(editingFinished()), this, SLOT(confitPlotInput()));
-  connect(m_uiForm.confit_inputFile, SIGNAL(fileEditingFinished()), this, SLOT(confitPlotInput()));
-  
-  connect(m_uiForm.confit_cbInputType, SIGNAL(currentIndexChanged(int)), m_uiForm.confit_swInput, SLOT(setCurrentIndex(int)));
-  connect(m_uiForm.confit_cbFitType, SIGNAL(currentIndexChanged(int)), this, SLOT(confitTypeSelection(int)));
-  connect(m_uiForm.confit_cbBackground, SIGNAL(currentIndexChanged(int)), this, SLOT(confitBgTypeSelection(int)));
-  connect(m_uiForm.confit_pbPlotInput, SIGNAL(clicked()), this, SLOT(confitPlotInput()));
-  connect(m_uiForm.confit_pbSequential, SIGNAL(clicked()), this, SLOT(confitSequential()));
-
-  m_uiForm.confit_leSpecNo->setValidator(m_valInt);
-  m_uiForm.confit_leSpecMax->setValidator(m_valInt);
-
-  // Context menu
-  m_cfTree->setContextMenuPolicy(Qt::CustomContextMenu);
-  connect(m_cfTree, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(fitContextMenu(const QPoint &)));
-}
-
-void IndirectDataAnalysis::setupAbsorptionF2Py()
-{
-  // set signals and slot connections for F2Py Absorption routine
-  connect(m_uiForm.absp_cbInputType, SIGNAL(currentIndexChanged(int)), m_uiForm.absp_swInput, SLOT(setCurrentIndex(int)));
-  connect(m_uiForm.absp_cbShape, SIGNAL(currentIndexChanged(int)), this, SLOT(absf2pShape(int)));
-  connect(m_uiForm.absp_ckUseCan, SIGNAL(toggled(bool)), this, SLOT(absf2pUseCanChecked(bool)));
-  connect(m_uiForm.absp_letc1, SIGNAL(editingFinished()), this, SLOT(absf2pTCSync()));
-  // apply QValidators to items.
-  m_uiForm.absp_lewidth->setValidator(m_valDbl);
-  m_uiForm.absp_leavar->setValidator(m_valDbl);
-  // sample
-  m_uiForm.absp_lesamden->setValidator(m_valDbl);
-  m_uiForm.absp_lesamsigs->setValidator(m_valDbl);
-  m_uiForm.absp_lesamsiga->setValidator(m_valDbl);
-  // can
-  m_uiForm.absp_lecanden->setValidator(m_valDbl);
-  m_uiForm.absp_lecansigs->setValidator(m_valDbl);
-  m_uiForm.absp_lecansiga->setValidator(m_valDbl);
-  // flat shape
-  m_uiForm.absp_lets->setValidator(m_valDbl);
-  m_uiForm.absp_letc1->setValidator(m_valDbl);
-  m_uiForm.absp_letc2->setValidator(m_valDbl);
-  // cylinder shape
-  m_uiForm.absp_ler1->setValidator(m_valDbl);
-  m_uiForm.absp_ler2->setValidator(m_valDbl);
-  m_uiForm.absp_ler3->setValidator(m_valDbl);
-}
-
-void IndirectDataAnalysis::setupAbsCor()
-{
-  // Disable Container inputs is "Use Container" is not checked
-  connect(m_uiForm.abscor_ckUseCan, SIGNAL(toggled(bool)), m_uiForm.abscor_lbContainerInputType, SLOT(setEnabled(bool)));
-  connect(m_uiForm.abscor_ckUseCan, SIGNAL(toggled(bool)), m_uiForm.abscor_cbContainerInputType, SLOT(setEnabled(bool)));
-  connect(m_uiForm.abscor_ckUseCan, SIGNAL(toggled(bool)), m_uiForm.abscor_swContainerInput, SLOT(setEnabled(bool)));
-
-  connect(m_uiForm.abscor_cbSampleInputType, SIGNAL(currentIndexChanged(int)), m_uiForm.abscor_swSampleInput, SLOT(setCurrentIndex(int)));
-  connect(m_uiForm.abscor_cbContainerInputType, SIGNAL(currentIndexChanged(int)), m_uiForm.abscor_swContainerInput, SLOT(setCurrentIndex(int)));
-}
-
-bool IndirectDataAnalysis::validateElwin()
-{
-  bool valid = true;
-
-  if ( ! m_uiForm.elwin_inputFile->isValid() )
-  {
-    valid = false;
-  }
-
-  return valid;
-}
-
-bool IndirectDataAnalysis::validateMsd()
-{
-  bool valid = true;
-
-  if ( ! m_uiForm.msd_inputFile->isValid() )
-  {
-    valid = false;
-  }
-
-  return valid;
-}
-
-bool IndirectDataAnalysis::validateFury()
-{
-  bool valid = true;
-
-  switch ( m_uiForm.fury_cbInputType->currentIndex() )
-  {
-  case 0:
-    {
-      if ( ! m_uiForm.fury_iconFile->isValid() )
-      {
-        valid = false;
-      }
-    }
-    break;
-  case 1:
-    {
-      if ( m_uiForm.fury_wsSample->currentText() == "" )
-      {
-        valid = false;
-      }
-    }
-    break;
-  }
-
-  if ( ! m_uiForm.fury_resFile->isValid()  )
-  {
-    valid = false;
-  }
-
-  return valid;
-}
-
-bool IndirectDataAnalysis::validateAbsorption()
-{
-  bool valid = true;
-
-  if ( ! m_uiForm.abs_inputFile->isValid() )
-  {
-    valid = false;
-  }
-
-  if ( m_uiForm.abs_leAttenuation->text() == "" )
-  {
-    m_uiForm.abs_valAttenuation->setText("*");
-    valid = false;
-  }
-  else
-  {
-    m_uiForm.abs_valAttenuation->setText(" ");
-  }
-
-  if ( m_uiForm.abs_leScatter->text() == "" )
-  {
-    m_uiForm.abs_valScatter->setText("*");
-    valid = false;
-  }
-  else
-  {
-    m_uiForm.abs_valScatter->setText(" ");
-  }
-
-  if ( m_uiForm.abs_leDensity->text() == "" )
-  {
-    m_uiForm.abs_valDensity->setText("*");
-    valid = false;
-  }
-  else
-  {
-    m_uiForm.abs_valDensity->setText(" ");
-  }
-
-  if ( m_uiForm.abs_cbShape->currentText() == "Flat Plate" )
-  {
-    // ... FLAT PLATE
-    if ( m_uiForm.abs_leFlatHeight->text() == "" )
-    {
-      m_uiForm.abs_valFlatHeight->setText("*");
-      valid = false;
-    }
-    else
-    {
-      m_uiForm.abs_valFlatHeight->setText(" ");
-    }
-
-    if ( m_uiForm.abs_leWidth->text() == "" )
-    {
-      m_uiForm.abs_valWidth->setText("*");
-      valid = false;
-    }
-    else
-    {
-      m_uiForm.abs_valWidth->setText(" ");
-    }
-
-    if ( m_uiForm.abs_leThickness->text() == "" )
-    {
-      m_uiForm.abs_valThickness->setText("*");
-      valid = false;
-    }
-    else
-    {
-      m_uiForm.abs_valThickness->setText(" ");
-    }
-
-    if ( m_uiForm.abs_leElementSize->text() == "" )
-    {
-      m_uiForm.abs_valElementSize->setText("*");
-      valid = false;
-    }
-    else
-    {
-      m_uiForm.abs_valElementSize->setText(" ");
-    }
-  }
-  else
-  {
-    // ... CYLINDER
-    if ( m_uiForm.abs_leCylHeight->text() == "" )
-    {
-      m_uiForm.abs_valCylHeight->setText("*");
-      valid = false;
-    }
-    else
-    {
-      m_uiForm.abs_valCylHeight->setText(" ");
-    }
-
-    if ( m_uiForm.abs_leRadius->text() == "" )
-    {
-      m_uiForm.abs_valRadius->setText("*");
-      valid = false;
-    }
-    else
-    {
-      m_uiForm.abs_valRadius->setText(" ");
-    }
-
-    if ( m_uiForm.abs_leSlices->text() == "" )
-    {
-      m_uiForm.abs_valSlices->setText("*");
-      valid = false;
-    }
-    else
-    {
-      m_uiForm.abs_valSlices->setText(" ");
-    }
-
-    if ( m_uiForm.abs_leAnnuli->text() == "" )
-    {
-      m_uiForm.abs_valAnnuli->setText("*");
-      valid = false;
-    }
-    else
-    {
-      m_uiForm.abs_valAnnuli->setText(" ");
-    }
-  }
-
-  return valid;
-}
-
-bool IndirectDataAnalysis::validateAbsorptionF2Py()
-{
-  bool valid = true;
-
-  // Input (file or workspace)
-  if ( m_uiForm.absp_cbInputType->currentText() == "File" )
-  {
-    if ( ! m_uiForm.absp_inputFile->isValid() ) { valid = false; }
-  }
-  else
-  {
-    if ( m_uiForm.absp_wsInput->currentText() == "" ) { valid = false; }
-  }
-
-  if ( m_uiForm.absp_cbShape->currentText() == "Flat" )
-  {
-    // Flat Geometry
-    if ( m_uiForm.absp_lets->text() != "" )
-    {
-      m_uiForm.absp_valts->setText(" ");
-    }
-    else
-    {
-      m_uiForm.absp_valts->setText("*");
-      valid = false;
-    }
-
-    if ( m_uiForm.absp_letc1->text() != "" )
-    {
-      m_uiForm.absp_valtc1->setText(" ");
-    }
-    else
-    {
-      m_uiForm.absp_valtc1->setText("*");
-      valid = false;
-    }
-
-    if ( m_uiForm.absp_letc2->text() != "" )
-    {
-      m_uiForm.absp_valtc2->setText(" ");
-    }
-    else
-    {
-      m_uiForm.absp_valtc2->setText("*");
-      valid = false;
-    }
-  }
-
-  if ( m_uiForm.absp_cbShape->currentText() == "Cylinder" )
-  {
-    // Cylinder geometry
-    if ( m_uiForm.absp_ler1->text() != "" )
-    {
-      m_uiForm.absp_valR1->setText(" ");
-    }
-    else
-    {
-      m_uiForm.absp_valR1->setText("*");
-      valid = false;
-    }
-
-    if ( m_uiForm.absp_ler2->text() != "" )
-    {
-      m_uiForm.absp_valR2->setText(" ");
-    }
-    else
-    {
-      m_uiForm.absp_valR2->setText("*");
-      valid = false;
-    }
-    
-    // R3  only relevant when using can
-    if ( m_uiForm.absp_ckUseCan->isChecked() )
-    {
-      if ( m_uiForm.absp_ler3->text() != "" )
-      {
-        m_uiForm.absp_valR3->setText(" ");
-      }
-      else
-      {
-        m_uiForm.absp_valR3->setText("*");
-        valid = false;
-      }
-    }
-  }
-
-  // Can angle to beam || Step size
-  if ( m_uiForm.absp_leavar->text() != "" )
-  {
-    m_uiForm.absp_valAvar->setText(" ");
-  }
-  else
-  {
-    m_uiForm.absp_valAvar->setText("*");
-    valid = false;
-  }
-
-  // Beam Width
-  if ( m_uiForm.absp_lewidth->text() != "" )
-  {
-    m_uiForm.absp_valWidth->setText(" ");
-  }
-  else
-  {
-    m_uiForm.absp_valWidth->setText("*");
-    valid = false;
-  }
-
-  // Sample details
-  if ( m_uiForm.absp_lesamden->text() != "" )
-  {
-    m_uiForm.absp_valSamden->setText(" ");
-  }
-  else
-  {
-    m_uiForm.absp_valSamden->setText("*");
-    valid = false;
-  }
-
-  if ( m_uiForm.absp_lesamsigs->text() != "" )
-  {
-    m_uiForm.absp_valSamsigs->setText(" ");
-  }
-  else
-  {
-    m_uiForm.absp_valSamsigs->setText("*");
-    valid = false;
-  }
-
-  if ( m_uiForm.absp_lesamsiga->text() != "" )
-  {
-    m_uiForm.absp_valSamsiga->setText(" ");
-  }
-  else
-  {
-    m_uiForm.absp_valSamsiga->setText("*");
-    valid = false;
-  }
-
-  // Can details (only test if "Use Can" is checked)
-  if ( m_uiForm.absp_ckUseCan->isChecked() )
-  {
-    if ( m_uiForm.absp_lecanden->text() != "" )
-    {
-      m_uiForm.absp_valCanden->setText(" ");
-    }
-    else
-    {
-      m_uiForm.absp_valCanden->setText("*");
-      valid = false;
-    }
-
-    if ( m_uiForm.absp_lecansigs->text() != "" )
-    {
-      m_uiForm.absp_valCansigs->setText(" ");
-    }
-    else
-    {
-      m_uiForm.absp_valCansigs->setText("*");
-      valid = false;
-    }
-
-    if ( m_uiForm.absp_lecansiga->text() != "" )
-    {
-      m_uiForm.absp_valCansiga->setText(" ");
-    }
-    else
-    {
-      m_uiForm.absp_valCansiga->setText("*");
-      valid = false;
-    }
-  }
-
-  return valid;
-}
-
-Mantid::API::CompositeFunctionMW* IndirectDataAnalysis::furyfitCreateFunction(bool tie)
-{
-  Mantid::API::CompositeFunctionMW* result = new Mantid::API::CompositeFunctionMW();
-  QString fname;
-  const int fitType = m_uiForm.furyfit_cbFitType->currentIndex();
-
-  Mantid::API::IFitFunction* func = Mantid::API::FunctionFactory::Instance().createFunction("LinearBackground");
-  func->setParameter("A0", m_ffDblMng->value(m_ffProp["BackgroundA0"]));
-  result->addFunction(func);
-  result->tie("f0.A1", "0");
-  if ( tie ) { result->tie("f0.A0", m_ffProp["BackgroundA0"]->valueText().toStdString()); }
-  
-  if ( fitType == 2 ) { fname = "Stretched Exponential"; }
-  else { fname = "Exponential 1"; }
-
-  result->addFunction(furyfitCreateUserFunction(fname, tie));
-
-  if ( fitType == 1 || fitType == 3 )
-  {
-    if ( fitType == 1 ) { fname = "Exponential 2"; }
-    else { fname = "Stretched Exponential"; }
-    result->addFunction(furyfitCreateUserFunction(fname, tie));
-  }
-
-  // Return CompositeFunction object to caller.
-  result->applyTies();
-  return result;
-}
-
-Mantid::API::IFitFunction* IndirectDataAnalysis::furyfitCreateUserFunction(const QString & name, bool tie)
-{
-  Mantid::API::IFitFunction* result = Mantid::API::FunctionFactory::Instance().createFunction("UserFunction");  
-  std::string formula;
-
-  if ( name.startsWith("Exp") ) { formula = "Intensity*exp(-(x/Tau))"; }
-  else { formula = "Intensity*exp(-(x/Tau)^Beta)"; }
-
-  Mantid::API::IFitFunction::Attribute att(formula);  
-  result->setAttribute("Formula", att);
-
-  result->setParameter("Intensity", m_ffDblMng->value(m_ffProp[name+".Intensity"]));
-
-  if ( tie || ! m_ffProp[name+".Intensity"]->subProperties().isEmpty() )
-  {
-    result->tie("Intensity", m_ffProp[name+".Intensity"]->valueText().toStdString());
-  }
-  result->setParameter("Tau", m_ffDblMng->value(m_ffProp[name+".Tau"]));
-  if ( tie || ! m_ffProp[name+".Tau"]->subProperties().isEmpty() )
-  {
-    result->tie("Tau", m_ffProp[name+".Tau"]->valueText().toStdString());
-  }
-  if ( name.startsWith("Str") )
-  {
-    result->setParameter("Beta", m_ffDblMng->value(m_ffProp[name+".Beta"]));
-    if ( tie || ! m_ffProp[name+".Beta"]->subProperties().isEmpty() )
-    {
-      result->tie("Beta", m_ffProp[name+".Beta"]->valueText().toStdString());
-    }
-  }
-
-  return result;
-}
-
-Mantid::API::CompositeFunctionMW* IndirectDataAnalysis::confitCreateFunction(bool tie)
-{
-  Mantid::API::CompositeFunctionMW* conv = dynamic_cast<Mantid::API::CompositeFunctionMW*>(Mantid::API::FunctionFactory::Instance().createFunction("Convolution"));
-  Mantid::API::CompositeFunctionMW* result = new Mantid::API::CompositeFunctionMW();
-  Mantid::API::CompositeFunctionMW* comp;
-
-  bool singleFunction = false;
-
-  if ( m_uiForm.confit_cbFitType->currentText() == "Two Lorentzians" )
-  {
-    comp = new Mantid::API::CompositeFunctionMW();
-  }
-  else
-  {
-    comp = conv;
-    singleFunction = true;
-  }
-
-  int index = 0;
-
-  // 0 = Fixed Flat, 1 = Fit Flat, 2 = Fit all
-  const int bgType = m_uiForm.confit_cbBackground->currentIndex();
-
-  // 1 - CompositeFunction A
-  // - - 1 LinearBackground
-  // - - 2 Convolution Function
-  // - - - - 1 Resolution
-  // - - - - 2 CompositeFunction B
-  // - - - - - - DeltaFunction (yes/no)
-  // - - - - - - Lorentzian 1 (yes/no)
-  // - - - - - - Lorentzian 2 (yes/no)
-
-  Mantid::API::IFitFunction* func;
-
-  // Background
-  func = Mantid::API::FunctionFactory::Instance().createFunction("LinearBackground");
-  index = result->addFunction(func);
-  if ( tie  || bgType == 0 || ! m_cfProp["BGA0"]->subProperties().isEmpty() )
-  {
-    result->tie("f0.A0", m_cfProp["BGA0"]->valueText().toStdString() );
-  }
-  else
-  {
-    func->setParameter("A0", m_cfProp["BGA0"]->valueText().toDouble());
-  }
-
-  if ( bgType != 2 )
-  {
-    result->tie("f0.A1", "0.0");
-  }
-  else
-  {
-    if ( tie || ! m_cfProp["BGA1"]->subProperties().isEmpty() )
-    {
-      result->tie("f0.A1", m_cfProp["BGA1"]->valueText().toStdString() );
-    }
-    else { func->setParameter("A1", m_cfProp["BGA1"]->valueText().toDouble()); }
-  }
-
-  // Resolution
-  func = Mantid::API::FunctionFactory::Instance().createFunction("Resolution");
-  index = conv->addFunction(func);
-  std::string resfilename = m_uiForm.confit_resInput->getFirstFilename().toStdString();
-  Mantid::API::IFitFunction::Attribute attr(resfilename);
-  func->setAttribute("FileName", attr);
-
-  // Delta Function
-  if ( m_cfBlnMng->value(m_cfProp["UseDeltaFunc"]) )
-  {
-    func = Mantid::API::FunctionFactory::Instance().createFunction("DeltaFunction");
-    index = comp->addFunction(func);
-    if ( tie || ! m_cfProp["DeltaHeight"]->subProperties().isEmpty() )
-    {
-      comp->tie("f0.Height", m_cfProp["DeltaHeight"]->valueText().toStdString() );
-    }
-    else { func->setParameter("Height", m_cfProp["DeltaHeight"]->valueText().toDouble()); }
-  }
-
-  // Lorentzians
-  switch ( m_uiForm.confit_cbFitType->currentIndex() )
-  {
-  case 0: // No Lorentzians
-    break;
-  case 1: // 1 Lorentzian
-    func = Mantid::API::FunctionFactory::Instance().createFunction("Lorentzian");
-    index = comp->addFunction(func);
-    populateFunction(func, comp, m_cfProp["Lorentzian1"], index, tie);
-    break;
-  case 2: // 2 Lorentzian
-    func = Mantid::API::FunctionFactory::Instance().createFunction("Lorentzian");
-    index = comp->addFunction(func);
-    populateFunction(func, comp, m_cfProp["Lorentzian1"], index, tie);
-    func = Mantid::API::FunctionFactory::Instance().createFunction("Lorentzian");
-    index = comp->addFunction(func);
-    populateFunction(func, comp, m_cfProp["Lorentzian2"], index, tie);
-    // Tie PeakCentres together
-    if ( ! tie )
-    {
-      QString tieL = "f" + QString::number(index-1) + ".PeakCentre";
-      QString tieR = "f" + QString::number(index) + ".PeakCentre";
-      comp->tie(tieL.toStdString(), tieR.toStdString());
-    }
-    break;
-  }
-
-  if ( ! singleFunction )
-    conv->addFunction(comp);
-  result->addFunction(conv);
-
-  result->applyTies();
-
-  return result;
-}
-
-QtProperty* IndirectDataAnalysis::createLorentzian(const QString & name)
-{
-  QtProperty* lorentzGroup = m_cfGrpMng->addProperty(name);
-  m_cfProp[name+".Height"] = m_cfDblMng->addProperty("Height");
-  // m_cfDblMng->setRange(m_cfProp[name+".Height"], 0.0, 1.0); // 0 < Height < 1
-  m_cfProp[name+".PeakCentre"] = m_cfDblMng->addProperty("PeakCentre");
-  m_cfProp[name+".HWHM"] = m_cfDblMng->addProperty("HWHM");
-  m_cfDblMng->setDecimals(m_cfProp[name+".Height"], m_nDec);
-  m_cfDblMng->setDecimals(m_cfProp[name+".PeakCentre"], m_nDec);
-  m_cfDblMng->setDecimals(m_cfProp[name+".HWHM"], m_nDec);
-  m_cfDblMng->setValue(m_cfProp[name+".HWHM"], 0.02);
-  lorentzGroup->addSubProperty(m_cfProp[name+".Height"]);
-  lorentzGroup->addSubProperty(m_cfProp[name+".PeakCentre"]);
-  lorentzGroup->addSubProperty(m_cfProp[name+".HWHM"]);
-  return lorentzGroup;
-}
-
-QtProperty* IndirectDataAnalysis::createExponential(const QString & name)
-{
-  QtProperty* expGroup = m_groupManager->addProperty(name);
-  m_ffProp[name+".Intensity"] = m_ffDblMng->addProperty("Intensity");
-  m_ffDblMng->setRange(m_ffProp[name+".Intensity"], 0.0, 1.0);
-  m_ffDblMng->setDecimals(m_ffProp[name+".Intensity"], m_nDec);
-  m_ffProp[name+".Tau"] = m_ffDblMng->addProperty("Tau");
-  m_ffDblMng->setDecimals(m_ffProp[name+".Tau"], m_nDec);
-  expGroup->addSubProperty(m_ffProp[name+".Intensity"]);
-  expGroup->addSubProperty(m_ffProp[name+".Tau"]);
-  return expGroup;
-}
-
-QtProperty* IndirectDataAnalysis::createStretchedExp(const QString & name)
-{
-  QtProperty* prop = m_groupManager->addProperty(name);
-  m_ffProp[name+".Intensity"] = m_ffDblMng->addProperty("Intensity");
-  m_ffDblMng->setRange(m_ffProp[name+".Intensity"], 0.0, 1.0);
-  m_ffProp[name+".Tau"] = m_ffDblMng->addProperty("Tau");
-  m_ffProp[name+".Beta"] = m_ffDblMng->addProperty("Beta");
-  m_ffDblMng->setDecimals(m_ffProp[name+".Intensity"], m_nDec);
-  m_ffDblMng->setDecimals(m_ffProp[name+".Tau"], m_nDec);
-  m_ffDblMng->setDecimals(m_ffProp[name+".Beta"], m_nDec);
-  m_ffDblMng->setRange(m_ffProp[name+".Beta"], 0.0, 1.0);
-  prop->addSubProperty(m_ffProp[name+".Intensity"]);
-  prop->addSubProperty(m_ffProp[name+".Tau"]);
-  prop->addSubProperty(m_ffProp[name+".Beta"]);
-  return prop;
-}
-
-void IndirectDataAnalysis::populateFunction(Mantid::API::IFitFunction* func, Mantid::API::IFitFunction* comp, QtProperty* group, int index, bool tie)
-{
-  // Get subproperties of group and apply them as parameters on the function object
-  QList<QtProperty*> props = group->subProperties();
-  QString pref = "f" + QString::number(index) + ".";
-
-  for ( int i = 0; i < props.size(); i++ )
-  {
-    if ( tie || ! props[i]->subProperties().isEmpty() )
-    {
-      QString propName = pref + props[i]->propertyName();
-      comp->tie(propName.toStdString(), props[i]->valueText().toStdString() );
-    }
-    else
-    {
-      std::string propName = props[i]->propertyName().toStdString();
-      double propValue = props[i]->valueText().toDouble();
-      func->setParameter(propName, propValue);
-    }
-  }
-}
-
-QwtPlotCurve* IndirectDataAnalysis::plotMiniplot(QwtPlot* plot, QwtPlotCurve* curve, std::string workspace, int index)
-{
-  if ( curve != NULL )
-  {
-    curve->attach(0);
-    delete curve;
-    curve = 0;
-  }
-
-  Mantid::API::MatrixWorkspace_const_sptr ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(workspace));
-
-  int nhist = ws->getNumberHistograms();
-  if ( index >= nhist )
-  {
-    showInformationBox("Error: Workspace index out of range.");
-    return 0;
-  }
-
-  const QVector<double> dataX = QVector<double>::fromStdVector(ws->readX(index));
-  const QVector<double> dataY = QVector<double>::fromStdVector(ws->readY(index));
-
-  curve = new QwtPlotCurve();
-  curve->setData(dataX, dataY);
-  curve->attach(plot);
-
-  plot->replot();
-
-  return curve;
-}
-
-void IndirectDataAnalysis::run()
-{
-  QString tabName = m_uiForm.tabWidget->tabText(m_uiForm.tabWidget->currentIndex());
-
-  if ( tabName == "Elwin" )  { elwinRun(); }
-  else if ( tabName == "MSD Fit" ) { msdRun(); }
-  else if ( tabName == "Fury" ) { furyRun(); }
-  else if ( tabName == "FuryFit" ) { furyfitRun(); }
-  else if ( tabName == "ConvFit" ) { confitRun(); }
-  else if ( tabName == "Absorption" ) { absorptionRun(); }
-  else if ( tabName == "Abs (F2PY)" ) { absf2pRun(); }
-  else if ( tabName == "Apply Corrections" ) { abscorRun(); }
-  else { showInformationBox("This tab does not have a 'Run' action."); }
-}
-
-void IndirectDataAnalysis::fitContextMenu(const QPoint &)
-{
-  QtBrowserItem* item;
-  QtDoublePropertyManager* dblMng;
-  
-  int pageNo = m_uiForm.tabWidget->currentIndex();
-  if ( pageNo == 3 )
-  { // FuryFit
-    item = m_ffTree->currentItem();
-    dblMng = m_ffDblMng;
-  }
-  else if ( pageNo == 4 )
-  { // Convolution Fit
-    item = m_cfTree->currentItem();
-    dblMng = m_cfDblMng;
-  }
-
-  if ( ! item )
-  {
-    return;
-  }
-
-  // is it a fit property ?
-  QtProperty* prop = item->property();
-  if ( prop->propertyManager() != dblMng )
-  {
-    return;
-  }
-
-  if ( pageNo == 4 && ( prop == m_cfProp["StartX"] || prop == m_cfProp["EndX"] ) )
-  {
-    return;
-  }
-
-  // is it already fixed?
-  QList<QtProperty*> subProps = prop->subProperties();
-  bool fixed = ! subProps.isEmpty();
-
-  // Create the menu
-  QMenu* menu = new QMenu("FuryFit", m_ffTree);
-  QAction* action;
-
-  if ( ! fixed )
-  {
-    action = new QAction("Fix", this);
-    connect(action, SIGNAL(triggered()), this, SLOT(fixItem()));
-  }
-  else
-  {
-    action = new QAction("Remove Fix", this);
-    connect(action, SIGNAL(triggered()), this, SLOT(unFixItem()));
-  }
-
-  menu->addAction(action);
-
-  // Show the menu
-  menu->popup(QCursor::pos());
-}
-
-void IndirectDataAnalysis::fixItem()
-{
-  int pageNo = m_uiForm.tabWidget->currentIndex();
-
-  QtBrowserItem* item;
-  if ( pageNo == 3 )
-  { // FuryFit
-    item = m_ffTree->currentItem();
-  }
-  else if ( pageNo == 4 )
-  { // Convolution Fit
-    item = m_cfTree->currentItem();
-  }
-
-  // Determine what the property is.
-  QtProperty* prop = item->property();
-
-  QtProperty* fixedProp = m_stringManager->addProperty("Fixed:");
-  m_stringManager->setValue(fixedProp, prop->valueText());
-  prop->addSubProperty(fixedProp);
-
-  fixedProp->setEnabled(false);
-  prop->setEnabled(false);
-  
-}
-
-void IndirectDataAnalysis::unFixItem()
-{
-  QtBrowserItem* item;
-  QtDoublePropertyManager* dblMng;
-  
-  int pageNo = m_uiForm.tabWidget->currentIndex();
-  if ( pageNo == 3 )
-  { // FuryFit
-    item = m_ffTree->currentItem();
-    dblMng = m_ffDblMng;
-  }
-  else if ( pageNo == 4 )
-  { // Convolution Fit
-    item = m_cfTree->currentItem();
-    dblMng = m_cfDblMng;
-  }
-
-  QtProperty* prop = item->property();
-  prop->subProperties().isEmpty();
-  QList<QtProperty*> subProps = prop->subProperties();
-
-  for ( QList<QtProperty*>::iterator it = subProps.begin(); it != subProps.end(); ++it )
-  {
-    if ( (*it)->propertyManager() != dblMng ) { delete (*it); }
-  }
-
-  prop->setEnabled(true);
-}
-
-void IndirectDataAnalysis::elwinRun()
-{
-  if ( ! validateElwin() )
-  {
-    showInformationBox("Please check your input.");
-    return;
-  }
-
-  QString pyInput =
-    "from IndirectDataAnalysis import elwin\n"
-    "input = [r'" + m_uiForm.elwin_inputFile->getFilenames().join("', r'") + "']\n"
-    "eRange = [ " + QString::number(m_elwDblMng->value(m_elwProp["R1S"])) +","+ QString::number(m_elwDblMng->value(m_elwProp["R1E"]));
-
-  if ( m_elwBlnMng->value(m_elwProp["UseTwoRanges"]) )
-  {
-    pyInput += ", " + QString::number(m_elwDblMng->value(m_elwProp["R2S"])) + ", " + QString::number(m_elwDblMng->value(m_elwProp["R2E"]));
-  }
-
-  pyInput+= "]\n";
-
-  if ( m_uiForm.elwin_ckVerbose->isChecked() ) pyInput += "verbose = True\n";
-  else pyInput += "verbose = False\n";
-
-  if ( m_uiForm.elwin_ckPlot->isChecked() ) pyInput += "plot = True\n";
-  else pyInput += "plot = False\n";
-
-  if ( m_uiForm.elwin_ckSave->isChecked() ) pyInput += "save = True\n";
-  else pyInput += "save = False\n";
-
-  pyInput +=
-    "eq1_ws, eq2_ws = elwin(input, eRange, Save=save, Verbose=verbose, Plot=plot)\n";
-
-  if ( m_uiForm.elwin_ckConcat->isChecked() )
-  {
-    pyInput += "from IndirectDataAnalysis import concatWSs\n"
-      "concatWSs(eq1_ws, 'MomentumTransfer', 'ElwinQResults')\n"
-      "concatWSs(eq2_ws, 'QSquared', 'ElwinQSqResults')\n";
-  }
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-
-}
-
-void IndirectDataAnalysis::elwinPlotInput()
-{
-  if ( m_uiForm.elwin_inputFile->isValid() )
-  {
-    QString filename = m_uiForm.elwin_inputFile->getFirstFilename();
-    QFileInfo fi(filename);
-    QString wsname = fi.baseName();
-
-    QString pyInput = "LoadNexus(r'" + filename + "', '" + wsname + "')\n";
-    QString pyOutput = runPythonCode(pyInput);
-
-    std::string workspace = wsname.toStdString();
-
-    m_elwDataCurve = plotMiniplot(m_elwPlot, m_elwDataCurve, workspace, 0);
-    
-    int npts = m_elwDataCurve->data().size();
-    double lower = m_elwDataCurve->data().x(0);
-    double upper = m_elwDataCurve->data().x(npts-1);
-    
-    m_elwR1->setRange(lower, upper);
-
-    // Replot
-    m_elwPlot->replot();
-  }
-  else
-  {
-    showInformationBox("Selected input files are invalid.");
-  }
-}
-
-void IndirectDataAnalysis::elwinTwoRanges(QtProperty*, bool val)
-{
-  m_elwR2->setVisible(val);
-}
-
-void IndirectDataAnalysis::elwinMinChanged(double val)
-{
-  MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
-  if ( from == m_elwR1 )
-  {
-    m_elwDblMng->setValue(m_elwProp["R1S"], val);
-  }
-  else if ( from == m_elwR2 )
-  {
-    m_elwDblMng->setValue(m_elwProp["R2S"], val);
-  }
-}
-
-void IndirectDataAnalysis::elwinMaxChanged(double val)
-{
-  MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
-  if ( from == m_elwR1 )
-  {
-    m_elwDblMng->setValue(m_elwProp["R1E"], val);
-  }
-  else if ( from == m_elwR2 )
-  {
-    m_elwDblMng->setValue(m_elwProp["R2E"], val);
-  }
-}
-
-void IndirectDataAnalysis::elwinUpdateRS(QtProperty* prop, double val)
-{
-  if ( prop == m_elwProp["R1S"] ) m_elwR1->setMinimum(val);
-  else if ( prop == m_elwProp["R1E"] ) m_elwR1->setMaximum(val);
-  else if ( prop == m_elwProp["R2S"] ) m_elwR2->setMinimum(val);
-  else if ( prop == m_elwProp["R2E"] ) m_elwR2->setMaximum(val);
-}
-
-void IndirectDataAnalysis::msdRun()
-{
-  if ( ! validateMsd() )
-  {
-    showInformationBox("Please check your input.");
-    return;
-  }
-
-  QString pyInput =
-    "from IndirectDataAnalysis import msdfit\n"
-    "startX = " + QString::number(m_msdDblMng->value(m_msdProp["Start"])) +"\n"
-    "endX = " + QString::number(m_msdDblMng->value(m_msdProp["End"])) +"\n"
-    "inputs = [r'" + m_uiForm.msd_inputFile->getFilenames().join("', r'") + "']\n";
-
-  if ( m_uiForm.msd_ckVerbose->isChecked() ) pyInput += "verbose = True\n";
-  else pyInput += "verbose = False\n";
-
-  if ( m_uiForm.msd_ckPlot->isChecked() ) pyInput += "plot = True\n";
-  else pyInput += "plot = False\n";
-
-  if ( m_uiForm.msd_ckSave->isChecked() ) pyInput += "save = True\n";
-  else pyInput += "save = False\n";
-
-  pyInput +=
-    "msdfit(inputs, startX, endX, Save=save, Verbose=verbose, Plot=plot)\n";
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-
-
-}
-
-void IndirectDataAnalysis::msdPlotInput()
-{
-  if ( m_uiForm.msd_inputFile->isValid() )
-  {
-    QString filename = m_uiForm.msd_inputFile->getFirstFilename();
-    QFileInfo fi(filename);
-    QString wsname = fi.baseName();
-
-    QString pyInput = "LoadNexus(r'" + filename + "', '" + wsname + "')\n";
-    QString pyOutput = runPythonCode(pyInput);
-
-    std::string workspace = wsname.toStdString();
-
-    m_msdDataCurve = plotMiniplot(m_msdPlot, m_msdDataCurve, workspace, 0);
-    int npnts = m_msdDataCurve->data().size();
-    double lower = m_msdDataCurve->data().x(0);
-    double upper = m_msdDataCurve->data().x(npnts-1);
-
-    m_msdRange->setRange(lower, upper);
-
-    // Replot
-    m_msdPlot->replot();
-  }
-  else
-  {
-    showInformationBox("Selected input files are invalid.");
-  }
-}
-
-void IndirectDataAnalysis::msdMinChanged(double val)
-{
-  m_msdDblMng->setValue(m_msdProp["Start"], val);
-}
-
-void IndirectDataAnalysis::msdMaxChanged(double val)
-{
-  m_msdDblMng->setValue(m_msdProp["End"], val);
-}
-
-void IndirectDataAnalysis::msdUpdateRS(QtProperty* prop, double val)
-{
-  if ( prop == m_msdProp["Start"] ) m_msdRange->setMinimum(val);
-  else if ( prop == m_msdProp["End"] ) m_msdRange->setMaximum(val);
-}
-
-void IndirectDataAnalysis::furyRun()
-{
-  if ( !validateFury() )
-  {
-    showInformationBox("Please check your input.");
-    return;
-  }
-
-  QString filenames;
-  switch ( m_uiForm.fury_cbInputType->currentIndex() )
-  {
-  case 0:
-    filenames = m_uiForm.fury_iconFile->getFilenames().join("', r'");
-    break;
-  case 1:
-    filenames = m_uiForm.fury_wsSample->currentText();
-    break;
-  }
-
-  QString pyInput =
-    "from IndirectDataAnalysis import fury\n"
-    "samples = [r'" + filenames + "']\n"
-    "resolution = r'" + m_uiForm.fury_resFile->getFirstFilename() + "'\n"
-    "rebin = '" + m_furProp["ELow"]->valueText() +","+ m_furProp["EWidth"]->valueText() +","+m_furProp["EHigh"]->valueText()+"'\n";
-
-  if ( m_uiForm.fury_ckVerbose->isChecked() ) pyInput += "verbose = True\n";
-  else pyInput += "verbose = False\n";
-
-  if ( m_uiForm.fury_ckPlot->isChecked() ) pyInput += "plot = True\n";
-  else pyInput += "plot = False\n";
-
-  if ( m_uiForm.fury_ckSave->isChecked() ) pyInput += "save = True\n";
-  else pyInput += "save = False\n";
-
-  pyInput +=
-    "fury_ws = fury(samples, resolution, rebin, Save=save, Verbose=verbose, Plot=plot)\n";
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-}
-
-void IndirectDataAnalysis::furyResType(const QString& type)
-{
-  QStringList exts;
-  if ( type == "RES File" )
-  {
-    exts.append("_res.nxs");
-    m_furyResFileType = true;
-  }
-  else
-  {
-    exts.append("_red.nxs");
-    m_furyResFileType = false;
-  }
-  m_uiForm.fury_resFile->setFileExtensions(exts);
-}
-
-void IndirectDataAnalysis::furyPlotInput()
-{
-  std::string workspace;
-  if ( m_uiForm.fury_cbInputType->currentIndex() == 0 )
-  {
-    if ( m_uiForm.fury_iconFile->isValid() )
-    {
-      QString filename = m_uiForm.fury_iconFile->getFirstFilename();
-      QFileInfo fi(filename);
-      QString wsname = fi.baseName();
-
-      QString pyInput = "LoadNexus(r'" + filename + "', '" + wsname + "')\n";
-      QString pyOutput = runPythonCode(pyInput);
-
-      workspace = wsname.toStdString();
-    }
-    else
-    {
-      showInformationBox("Selected input files are invalid.");
-      return;
-    }
-  }
-  else if ( m_uiForm.fury_cbInputType->currentIndex() == 1 )
-  {
-    workspace = m_uiForm.fury_wsSample->currentText().toStdString();
-    if ( workspace.empty() )
-    {
-      showInformationBox("No workspace selected.");
-      return;
-    }
-  }
-
-  m_furCurve = plotMiniplot(m_furPlot, m_furCurve, workspace, 0);
-  int npnts = m_furCurve->data().size();
-  double lower = m_furCurve->data().x(0);
-  double upper = m_furCurve->data().x(npnts-1);
-
-  m_furRange->setRange(lower, upper);
-
-  m_furPlot->replot();
-
-}
-
-void IndirectDataAnalysis::furyMaxChanged(double val)
-{
-  m_furDblMng->setValue(m_furProp["EHigh"], val);
-}
-
-void IndirectDataAnalysis::furyMinChanged(double val)
-{
-  m_furDblMng->setValue(m_furProp["ELow"], val);
-}
-
-void IndirectDataAnalysis::furyUpdateRS(QtProperty* prop, double val)
-{
-  if ( prop == m_furProp["ELow"] )
-    m_furRange->setMinimum(val);
-  else if ( prop == m_furProp["EHigh"] )
-    m_furRange->setMaximum(val);
-}
-
-void IndirectDataAnalysis::furyfitRun()
-{
-  // First create the function
-  Mantid::API::CompositeFunctionMW* function = furyfitCreateFunction();
-
-  m_uiForm.furyfit_ckPlotGuess->setChecked(false);
-  
-  const int fitType = m_uiForm.furyfit_cbFitType->currentIndex();
-
-  if ( m_uiForm.furyfit_ckConstrainIntensities->isChecked() )
-  {
-    switch ( fitType )
-    {
-    case 0: // 1 Exp
-    case 2: // 1 Str
-      m_furyfitTies = "f1.Intensity = 1-f0.A0";
-      break;
-    case 1: // 2 Exp
-    case 3: // 1 Exp & 1 Str
-      m_furyfitTies = "f1.Intensity=1-f2.Intensity-f0.A0";
-      break;
-    default:
-      break;
-    }
-  }
-
-  furyfitPlotInput();
-  if ( m_ffInputWS == NULL )
-  {
-    return;
-  }
-
-  std::string output = m_ffInputWSName + "_fit_s" + m_uiForm.furyfit_leSpecNo->text().toStdString();
-  // Create the Fit Algorithm
-  Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("Fit");
-  alg->initialize();
-  alg->setPropertyValue("InputWorkspace", m_ffInputWSName);
-  alg->setProperty("WorkspaceIndex", m_uiForm.furyfit_leSpecNo->text().toInt());
-  alg->setProperty("StartX", m_ffRangeManager->value(m_ffProp["StartX"]));
-  alg->setProperty("EndX", m_ffRangeManager->value(m_ffProp["EndX"]));
-  alg->setProperty("Ties", m_furyfitTies.toStdString());
-  alg->setPropertyValue("Function", *function);
-  alg->setPropertyValue("Output",output);
-  alg->execute();
-
-  if ( ! alg->isExecuted() )
-  {
-    QString msg = "There was an error executing the fitting algorithm. Please see the "
-      "Results Log pane for more details.";
-    showInformationBox(msg);
-    return;
-  }
-
-  // Now show the fitted curve of the mini plot
-  m_ffFitCurve = plotMiniplot(m_ffPlot, m_ffFitCurve, output+"_Workspace", 1);
-  QPen fitPen(Qt::red, Qt::SolidLine);
-  m_ffFitCurve->setPen(fitPen);
-  m_ffPlot->replot();
-
-  // Do it as we do in Convolution Fit tab
-  QMap<QString,double> parameters;
-  QStringList parNames = QString::fromStdString(alg->getPropertyValue("ParameterNames")).split(",", QString::SkipEmptyParts);
-  QStringList parVals = QString::fromStdString(alg->getPropertyValue("Parameters")).split(",", QString::SkipEmptyParts);
-  for ( int i = 0; i < parNames.size(); i++ )
-  {
-    parameters[parNames[i]] = parVals[i].toDouble();
-  }
-
-  m_ffRangeManager->setValue(m_ffProp["BackgroundA0"], parameters["f0.A0"]);
-  
-  if ( fitType != 2 )
-  {
-    // Exp 1
-    m_ffDblMng->setValue(m_ffProp["Exponential 1.Intensity"], parameters["f1.Intensity"]);
-    m_ffDblMng->setValue(m_ffProp["Exponential 1.Tau"], parameters["f1.Tau"]);
-    
-    if ( fitType == 1 )
-    {
-      // Exp 2
-      m_ffDblMng->setValue(m_ffProp["Exponential 2.Intensity"], parameters["f2.Intensity"]);
-      m_ffDblMng->setValue(m_ffProp["Exponential 2.Tau"], parameters["f2.Tau"]);
-    }
-  }
-  
-  if ( fitType > 1 )
-  {
-    // Str
-    QString fval;
-    if ( fitType == 2 ) { fval = "f1."; }
-    else { fval = "f2."; }
-    
-    m_ffDblMng->setValue(m_ffProp["Stretched Exponential.Intensity"], parameters[fval+"Intensity"]);
-    m_ffDblMng->setValue(m_ffProp["Stretched Exponential.Tau"], parameters[fval+"Tau"]);
-    m_ffDblMng->setValue(m_ffProp["Stretched Exponential.Beta"], parameters[fval+"Beta"]);
-  }
-
-  if ( m_uiForm.furyfit_ckPlotOutput->isChecked() )
-  {
-    QString pyInput = "from mantidplot import *\n"
-      "plotSpectrum('" + QString::fromStdString(output) + "_Workspace', [0,1,2])\n";
-    QString pyOutput = runPythonCode(pyInput);
-  }
-}
-
-void IndirectDataAnalysis::furyfitTypeSelection(int index)
-{
-  m_ffTree->clear();
-
-  m_ffTree->addProperty(m_ffProp["StartX"]);
-  m_ffTree->addProperty(m_ffProp["EndX"]);
-
-  m_ffTree->addProperty(m_ffProp["LinearBackground"]);
-
-  switch ( index )
-  {
-  case 0:
-    m_ffTree->addProperty(m_ffProp["Exponential1"]);
-    break;
-  case 1:
-    m_ffTree->addProperty(m_ffProp["Exponential1"]);
-    m_ffTree->addProperty(m_ffProp["Exponential2"]);
-    break;
-  case 2:
-    m_ffTree->addProperty(m_ffProp["StretchedExp"]);
-    break;
-  case 3:
-    m_ffTree->addProperty(m_ffProp["Exponential1"]);
-    m_ffTree->addProperty(m_ffProp["StretchedExp"]);
-    break;
-  }
-}
-
-void IndirectDataAnalysis::furyfitPlotInput()
-{
-  std::string wsname;
-
-  switch ( m_uiForm.furyfit_cbInputType->currentIndex() )
-  {
-  case 0: // "File"
-    {
-      if ( ! m_uiForm.furyfit_inputFile->isValid() )
-      {
-        return;
-      }
-      else
-      {
-      QFileInfo fi(m_uiForm.furyfit_inputFile->getFirstFilename());
-      wsname = fi.baseName().toStdString();
-      if ( (m_ffInputWS == NULL) || ( wsname != m_ffInputWSName ) )
-      {
-        std::string filename = m_uiForm.furyfit_inputFile->getFirstFilename().toStdString();
-        // LoadNexus
-        Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("LoadNexus");
-        alg->initialize();
-        alg->setPropertyValue("Filename", filename);
-        alg->setPropertyValue("OutputWorkspace",wsname);
-        alg->execute();
-        // get the output workspace
-        m_ffInputWS = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsname));
-      }
-      }
-    }
-    break;
-  case 1: // Workspace
-    {
-      wsname = m_uiForm.furyfit_wsIqt->currentText().toStdString();
-      try
-      {
-        m_ffInputWS = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsname));
-      }
-      catch ( Mantid::Kernel::Exception::NotFoundError & )
-      {
-        QString msg = "Workspace: '" + QString::fromStdString(wsname) + "' could not be "
-          "found in the Analysis Data Service.";
-        showInformationBox(msg);
-        return;
-      }
-    }
-    break;
-  }
-  m_ffInputWSName = wsname;
-
-  int specNo = m_uiForm.furyfit_leSpecNo->text().toInt();
-
-  m_ffDataCurve = plotMiniplot(m_ffPlot, m_ffDataCurve, m_ffInputWSName, specNo);
-
-  int nopnts =  m_ffDataCurve->data().size();
-  double lower = m_ffDataCurve->data().x(0);
-  double upper = m_ffDataCurve->data().x(nopnts-1);
-
-  m_ffRangeS->setRange(lower, upper);
-  m_ffRangeManager->setRange(m_ffProp["StartX"], lower, upper);
-  m_ffRangeManager->setRange(m_ffProp["EndX"], lower, upper);
-
-  m_ffPlot->setAxisScale(QwtPlot::xBottom, lower, upper);
-  m_ffPlot->setAxisScale(QwtPlot::yLeft, 0.0, 1.0);
-  m_ffPlot->replot();
-}
-
-void IndirectDataAnalysis::furyfitXMinSelected(double val)
-{
-  m_ffRangeManager->setValue(m_ffProp["StartX"], val);
-}
-
-void IndirectDataAnalysis::furyfitXMaxSelected(double val)
-{
-  m_ffRangeManager->setValue(m_ffProp["EndX"], val);
-}
-
-void IndirectDataAnalysis::furyfitBackgroundSelected(double val)
-{
-  m_ffRangeManager->setValue(m_ffProp["BackgroundA0"], val);
-}
-
-void IndirectDataAnalysis::furyfitRangePropChanged(QtProperty* prop, double val)
-{
-  if ( prop == m_ffProp["StartX"] )
-  {
-    m_ffRangeS->setMinimum(val);
-  }
-  else if ( prop == m_ffProp["EndX"] )
-  {
-    m_ffRangeS->setMaximum(val);
-  }
-  else if ( prop == m_ffProp["BackgroundA0"] )
-  {
-    m_ffBackRangeS->setMinimum(val);
-  }
-}
-
-void IndirectDataAnalysis::furyfitSequential()
-{
-  furyfitPlotInput();
-  if ( m_ffInputWS == NULL )
-  {
-    return;
-  }
-
-  Mantid::API::CompositeFunction* func = furyfitCreateFunction();
-
-  // Function Ties
-  func->tie("f0.A1", "0");
-  if ( m_uiForm.furyfit_ckConstrainIntensities->isChecked() )
-  {
-    switch ( m_uiForm.furyfit_cbFitType->currentIndex() )
-    {
-    case 0: // 1 Exp
-    case 2: // 1 Str
-      func->tie("f1.Intensity","1-f0.A0");
-      break;
-    case 1: // 2 Exp
-    case 3: // 1 Exp & 1 Str
-      func->tie("f1.Intensity","1-f2.Intensity-f0.A0");
-      break;
-    }
-  }
-
-  std::string function = std::string(*func);
-  
-  QString pyInput = "from IndirectDataAnalysis import furyfitSeq\n"
-    "input = '" + QString::fromStdString(m_ffInputWSName) + "'\n"
-    "func = r'" + QString::fromStdString(function) + "'\n"
-    "startx = " + m_ffProp["StartX"]->valueText() + "\n"
-    "endx = " + m_ffProp["EndX"]->valueText() + "\n"
-    "plot = '" + m_uiForm.furyfit_cbPlotOutput->currentText() + "'\n"
-    "save = ";
-  pyInput += m_uiForm.furyfit_ckSaveSeq->isChecked() ? "True\n" : "False\n";
-  pyInput += "furyfitSeq(input, func, startx, endx, save, plot)\n";
-  
-  QString pyOutput = runPythonCode(pyInput);
-}
-
-void IndirectDataAnalysis::furyfitPlotGuess(QtProperty*)
-{
-  if ( ! m_uiForm.furyfit_ckPlotGuess->isChecked() || m_ffDataCurve == NULL )
-  {
-    return;
-  }
-
-  Mantid::API::CompositeFunctionMW* function = furyfitCreateFunction(true);
-
-  // Create the double* array from the input workspace
-  int binIndxLow = m_ffInputWS->binIndexOf(m_ffRangeManager->value(m_ffProp["StartX"]));
-  int binIndxHigh = m_ffInputWS->binIndexOf(m_ffRangeManager->value(m_ffProp["EndX"]));
-  const int nData = binIndxHigh - binIndxLow;
-
-  double* inputXData = new double[nData];
-  double* outputData = new double[nData];
-
-  const Mantid::MantidVec& XValues = m_ffInputWS->readX(0);
-
-  const bool isHistogram = m_ffInputWS->isHistogramData();
-
-  for ( int i = 0; i < nData ; i++ )
-  {
-    if ( isHistogram )
-      inputXData[i] = 0.5*(XValues[binIndxLow+i]+XValues[binIndxLow+i+1]);
-    else
-      inputXData[i] = XValues[binIndxLow+i];
-  }
-
-  function->function(outputData, inputXData, nData);
-
-  QVector<double> dataX;
-  QVector<double> dataY;
-
-  for ( int i = 0; i < nData; i++ )
-  {
-    dataX.append(inputXData[i]);
-    dataY.append(outputData[i]);
-  }
-
-  // Create the curve
-  if ( m_ffFitCurve != NULL )
-  {
-    m_ffFitCurve->attach(0);
-    delete m_ffFitCurve;
-    m_ffFitCurve = 0;
-  }
-
-  m_ffFitCurve = new QwtPlotCurve();
-  m_ffFitCurve->setData(dataX, dataY);
-  m_ffFitCurve->attach(m_ffPlot);
-  QPen fitPen(Qt::red, Qt::SolidLine);
-  m_ffFitCurve->setPen(fitPen);
-  m_ffPlot->replot();
-}
-
-void IndirectDataAnalysis::confitRun()
-{
-  confitPlotInput();
-
-  if ( m_cfDataCurve == NULL )
-  {
-    showInformationBox("Input invalid");
-    return;
-  }
-
-  m_uiForm.confit_ckPlotGuess->setChecked(false);
-
-  Mantid::API::CompositeFunction* function = confitCreateFunction();
-  std::string output = m_cfInputWSName + "_convfit_s" + m_uiForm.confit_leSpecNo->text().toStdString();
-
-  Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("Fit");
-  alg->initialize();
-  alg->setPropertyValue("InputWorkspace", m_cfInputWSName);
-  alg->setProperty<int>("WorkspaceIndex", m_uiForm.confit_leSpecNo->text().toInt());
-  alg->setProperty<double>("StartX", m_cfDblMng->value(m_cfProp["StartX"]));
-  alg->setProperty<double>("EndX", m_cfDblMng->value(m_cfProp["EndX"]));
-  alg->setPropertyValue("Function", *function);
-  alg->setPropertyValue("Output", output);
-  alg->execute();
-
-  if ( ! alg->isExecuted() )
-  {
-    showInformationBox("Fit algorithm failed.");
-    return;
-  }
-
-  // Plot the line on the mini plot
-  m_cfCalcCurve = plotMiniplot(m_cfPlot, m_cfCalcCurve, output+"_Workspace", 1);
-  QPen fitPen(Qt::red, Qt::SolidLine);
-  m_cfCalcCurve->setPen(fitPen);
-  m_cfPlot->replot();
-
-  // Update parameter values (possibly easier from algorithm properties)
-  QMap<QString,double> parameters;
-  QStringList parNames = QString::fromStdString(alg->getPropertyValue("ParameterNames")).split(",", QString::SkipEmptyParts);
-  QStringList parVals = QString::fromStdString(alg->getPropertyValue("Parameters")).split(",", QString::SkipEmptyParts);
-  for ( int i = 0; i < parNames.size(); i++ )
-  {
-    parameters[parNames[i]] = parVals[i].toDouble();
-  }
-
-  // Populate Tree widget with values
-  // Background should always be f0
-  m_cfDblMng->setValue(m_cfProp["BGA0"], parameters["f0.A0"]);
-  m_cfDblMng->setValue(m_cfProp["BGA1"], parameters["f0.A1"]);
-
-  int noLorentz = m_uiForm.confit_cbFitType->currentIndex();
-
-  int funcIndex = 1;
-  QString prefBase = "f1.f";
-  if ( noLorentz > 1 || ( noLorentz > 0 && m_cfBlnMng->value(m_cfProp["UseDeltaFunc"]) ) )
-  {
-    prefBase += "1.f";
-    funcIndex--;
-  }
-
-  if ( m_cfBlnMng->value(m_cfProp["UseDeltaFunc"]) )
-  {
-    QString key = prefBase+QString::number(funcIndex)+".Height";
-    m_cfDblMng->setValue(m_cfProp["DeltaHeight"], parameters[key]);
-    funcIndex++;
-  }
-
-  if ( noLorentz > 0 )
-  {
-    // One Lorentz
-    QString pref = prefBase + QString::number(funcIndex) + ".";
-    m_cfDblMng->setValue(m_cfProp["Lorentzian 1.Height"], parameters[pref+"Height"]);
-    m_cfDblMng->setValue(m_cfProp["Lorentzian 1.PeakCentre"], parameters[pref+"PeakCentre"]);
-    m_cfDblMng->setValue(m_cfProp["Lorentzian 1.HWHM"], parameters[pref+"HWHM"]);
-    funcIndex++;
-  }
-
-  if ( noLorentz > 1 )
-  {
-    // Two Lorentz
-    QString pref = prefBase + QString::number(funcIndex) + ".";
-    m_cfDblMng->setValue(m_cfProp["Lorentzian 2.Height"], parameters[pref+"Height"]);
-    m_cfDblMng->setValue(m_cfProp["Lorentzian 2.PeakCentre"], parameters[pref+"PeakCentre"]);
-    m_cfDblMng->setValue(m_cfProp["Lorentzian 2.HWHM"], parameters[pref+"HWHM"]);
-  }
-
-  // Plot Output
-  if ( m_uiForm.confit_ckPlotOutput->isChecked() )
-  {
-    QString pyInput =
-      "plotSpectrum('" + QString::fromStdString(output) + "_Workspace', [0,1,2])\n";
-    QString pyOutput = runPythonCode(pyInput);
-  }
-
-}
-
-void IndirectDataAnalysis::confitTypeSelection(int index)
-{
-  m_cfTree->removeProperty(m_cfProp["Lorentzian1"]);
-  m_cfTree->removeProperty(m_cfProp["Lorentzian2"]);
-  
-  switch ( index )
-  {
-  case 0:
-    m_cfHwhmRange->setVisible(false);
-    break;
-  case 1:
-    m_cfTree->addProperty(m_cfProp["Lorentzian1"]);
-    m_cfHwhmRange->setVisible(true);
-    break;
-  case 2:
-    m_cfTree->addProperty(m_cfProp["Lorentzian1"]);
-    m_cfTree->addProperty(m_cfProp["Lorentzian2"]);
-    m_cfHwhmRange->setVisible(true);
-    break;
-  }    
-}
-
-void IndirectDataAnalysis::confitBgTypeSelection(int index)
-{
-  if ( index == 2 )
-  {
-    m_cfProp["LinearBackground"]->addSubProperty(m_cfProp["BGA1"]);
-  }
-  else
-  {
-    m_cfProp["LinearBackground"]->removeSubProperty(m_cfProp["BGA1"]);
-  }
-}
-
-void IndirectDataAnalysis::confitPlotInput()
-{
-  std::string wsname;
-  const bool plotGuess = m_uiForm.confit_ckPlotGuess->isChecked();
-  m_uiForm.confit_ckPlotGuess->setChecked(false);
-
-  switch ( m_uiForm.confit_cbInputType->currentIndex() )
-  {
-  case 0: // "File"
-    {
-      if ( m_uiForm.confit_inputFile->isValid() )
-      {
-        QFileInfo fi(m_uiForm.confit_inputFile->getFirstFilename());
-        wsname = fi.baseName().toStdString();
-        if ( (m_ffInputWS == NULL) || ( wsname != m_ffInputWSName ) )
-        {
-          std::string filename = m_uiForm.confit_inputFile->getFirstFilename().toStdString();
-          Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("LoadNexus");
-          alg->initialize();
-          alg->setPropertyValue("Filename", filename);
-          alg->setPropertyValue("OutputWorkspace",wsname);
-          alg->execute();
-          m_cfInputWS = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsname));
-        }
-      }
-      else
-      {
-        return;
-      }
-    }
-    break;
-  case 1: // Workspace
-    {
-      wsname = m_uiForm.confit_wsSample->currentText().toStdString();
-      try
-      {
-        m_cfInputWS = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsname));
-      }
-      catch ( Mantid::Kernel::Exception::NotFoundError & )
-      {
-        QString msg = "Workspace: '" + QString::fromStdString(wsname) + "' could not be "
-          "found in the Analysis Data Service.";
-        showInformationBox(msg);
-        return;
-      }
-    }
-    break;
-  }
-  m_cfInputWSName = wsname;
-
-  int specNo = m_uiForm.confit_leSpecNo->text().toInt();
-  // Set spectra max value
-  int specMax = m_cfInputWS->getNumberHistograms() - 1;
-  if ( specNo < 0 || specNo > specMax )
-  {
-    m_uiForm.confit_leSpecNo->setText("0");
-    specNo = 0;
-  }
-  int smCurrent = m_uiForm.confit_leSpecMax->text().toInt();
-  if ( smCurrent < 0 || smCurrent > specMax )
-    m_uiForm.confit_leSpecMax->setText(QString::number(specMax));
-
-  m_cfDataCurve = plotMiniplot(m_cfPlot, m_cfDataCurve, wsname, specNo);
-  int npnts = m_cfDataCurve->data().size();
-  const double & lower = m_cfDataCurve->data().x(0);
-  const double & upper = m_cfDataCurve->data().x(npnts-1);
-  m_cfRangeS->setRange(lower, upper);
-
-  m_uiForm.confit_ckPlotGuess->setChecked(plotGuess);
-}
-
-void IndirectDataAnalysis::confitPlotGuess(QtProperty*)
-{
-
-  if ( ! m_uiForm.confit_ckPlotGuess->isChecked() || m_cfDataCurve == NULL )
-  {
-    return;
-  }
-
-  Mantid::API::CompositeFunctionMW* function = confitCreateFunction(true);
-
-  if ( m_cfInputWS == NULL )
-  {
-    confitPlotInput();
-  }
-
-  std::string inputName = m_cfInputWS->getName();
-
-  const int binIndexLow = m_cfInputWS->binIndexOf(m_cfDblMng->value(m_cfProp["StartX"]));
-  const int binIndexHigh = m_cfInputWS->binIndexOf(m_cfDblMng->value(m_cfProp["EndX"]));
-  const int nData = binIndexHigh - binIndexLow;
-
-  double* inputXData = new double[nData];
-  double* outputData = new double[nData];
-
-  const Mantid::MantidVec& XValues = m_cfInputWS->readX(0);
-  const bool isHistogram = m_cfInputWS->isHistogramData();
-
-  for ( int i = 0; i < nData; i++ )
-  {
-    if ( isHistogram )
-    {
-      inputXData[i] = 0.5 * ( XValues[binIndexLow+i] + XValues[binIndexLow+i+1] );
-    }
-    else
-    {
-      inputXData[i] = XValues[binIndexLow+i];
-    }
-  }
-
-  function->function(outputData, inputXData, nData);
-
-  QVector<double> dataX, dataY;
-
-  for ( int i = 0; i < nData; i++ )
-  {
-    dataX.append(inputXData[i]);
-    dataY.append(outputData[i]);
-  }
-
-  if ( m_cfCalcCurve != NULL )
-  {
-    m_cfCalcCurve->attach(0);
-    delete m_cfCalcCurve;
-    m_cfCalcCurve = 0;
-  }
-
-  m_cfCalcCurve = new QwtPlotCurve();
-  m_cfCalcCurve->setData(dataX, dataY);
-  QPen fitPen(Qt::red, Qt::SolidLine);
-  m_cfCalcCurve->setPen(fitPen);
-  m_cfCalcCurve->attach(m_cfPlot);
-  m_cfPlot->replot();
-}
-
-void IndirectDataAnalysis::confitSequential()
-{
-  if ( m_cfInputWS == NULL )
-  {
-    return;
-  }
-
-  QString bg = m_uiForm.confit_cbBackground->currentText();
-  if ( bg == "Fixed Flat" )
-  {
-    bg = "FixF";
-  }
-  else if ( bg == "Fit Flat" )
-  {
-    bg = "FitF";
-  }
-  else if ( bg == "Fit Linear" )
-  {
-    bg = "FitL";
-  }
-
-  Mantid::API::CompositeFunction* func = confitCreateFunction();
-  std::string function = std::string(*func);
-  QString stX = m_cfProp["StartX"]->valueText();
-  QString enX = m_cfProp["EndX"]->valueText();
-
-  QString pyInput =
-    "from IndirectDataAnalysis import confitSeq\n"
-    "input = '" + QString::fromStdString(m_cfInputWSName) + "'\n"
-    "func = r'" + QString::fromStdString(function) + "'\n"
-    "startx = " + stX + "\n"
-    "endx = " + enX + "\n"
-    "specMin = " + m_uiForm.confit_leSpecNo->text() + "\n"
-    "specMax = " + m_uiForm.confit_leSpecMax->text() + "\n"
-    "plot = '" + m_uiForm.confit_cbPlotOutput->currentText() + "'\n"
-    "save = ";
-  
-  pyInput += m_uiForm.confit_ckSaveSeq->isChecked() ? "True\n" : "False\n";
-  
-  pyInput +=    
-    "bg = '" + bg + "'\n"
-    "confitSeq(input, func, startx, endx, save, plot, bg, specMin, specMax)\n";
-
-  QString pyOutput = runPythonCode(pyInput);
-}
-
-void IndirectDataAnalysis::confitMinChanged(double val)
-{
-  m_cfDblMng->setValue(m_cfProp["StartX"], val);
-}
-
-void IndirectDataAnalysis::confitMaxChanged(double val)
-{
-  m_cfDblMng->setValue(m_cfProp["EndX"], val);
-}
-
-void IndirectDataAnalysis::confitHwhmChanged(double val)
-{
-  const double peakCentre = m_cfDblMng->value(m_cfProp["Lorentzian 1.PeakCentre"]);
-  // Always want HWHM to display as positive.
-  if ( val > peakCentre )
-  {
-    m_cfDblMng->setValue(m_cfProp["Lorentzian 1.HWHM"], val-peakCentre);
-  }
-  else
-  {
-    m_cfDblMng->setValue(m_cfProp["Lorentzian 1.HWHM"], peakCentre-val);
-  }
-}
-
-void IndirectDataAnalysis::confitBackgLevel(double val)
-{
-  m_cfDblMng->setValue(m_cfProp["BGA0"], val);
-}
-
-void IndirectDataAnalysis::confitUpdateRS(QtProperty* prop, double val)
-{
-  if ( prop == m_cfProp["StartX"] ) { m_cfRangeS->setMinimum(val); }
-  else if ( prop == m_cfProp["EndX"] ) { m_cfRangeS->setMaximum(val); }
-  else if ( prop == m_cfProp["BGA0"] ) { m_cfBackgS->setMinimum(val); }
-  else if ( prop == m_cfProp["Lorentzian 1.HWHM"] ) { confitHwhmUpdateRS(val); }
-}
-
-void IndirectDataAnalysis::confitHwhmUpdateRS(double val)
-{
-  const double peakCentre = m_cfDblMng->value(m_cfProp["Lorentzian 1.PeakCentre"]);
-  m_cfHwhmRange->setMinimum(peakCentre-val);
-  m_cfHwhmRange->setMaximum(peakCentre+val);
-}
-
-void IndirectDataAnalysis::confitCheckBoxUpdate(QtProperty* prop, bool checked)
-{
-  // Add/remove some properties to display only relevant options
-  if ( prop == m_cfProp["UseDeltaFunc"] )
-  {
-    if ( checked ) { m_cfProp["DeltaFunction"]->addSubProperty(m_cfProp["DeltaHeight"]); }
-    else { m_cfProp["DeltaFunction"]->removeSubProperty(m_cfProp["DeltaHeight"]); }
-  }
-}
-
-void IndirectDataAnalysis::absorptionRun()
-{
-  if ( ! validateAbsorption() )
-  {
-    showInformationBox("Please check your input.");
-    return;
-  }
-
-  QString pyInput =
-    "from IndirectDataAnalysis import absorption\n"
-    "file = r'" + m_uiForm.abs_inputFile->getFirstFilename() + "'\n"
-    "mode = '" + m_uiForm.abs_cbShape->currentText() + "'\n"
-    "sample = [ %1, %2, %3 ]\n"
-    "can = [ %4, %5, %6, %7 ]\n";
-
-  pyInput = pyInput.arg(m_uiForm.abs_leAttenuation->text());
-  pyInput = pyInput.arg(m_uiForm.abs_leScatter->text());
-  pyInput = pyInput.arg(m_uiForm.abs_leDensity->text());
-
-  if ( m_uiForm.abs_cbShape->currentText() == "Flat Plate" )
-  {
-    pyInput = pyInput.arg(m_uiForm.abs_leFlatHeight->text());
-    pyInput = pyInput.arg(m_uiForm.abs_leWidth->text());
-    pyInput = pyInput.arg(m_uiForm.abs_leThickness->text());
-    pyInput = pyInput.arg(m_uiForm.abs_leElementSize->text());
-  }
-  else
-  {
-    pyInput = pyInput.arg(m_uiForm.abs_leCylHeight->text());
-    pyInput = pyInput.arg(m_uiForm.abs_leRadius->text());
-    pyInput = pyInput.arg(m_uiForm.abs_leSlices->text());
-    pyInput = pyInput.arg(m_uiForm.abs_leAnnuli->text());
-  }
-
-  if ( m_uiForm.abs_ckVerbose->isChecked() ) pyInput += "verbose = True\n";
-  else pyInput += "verbose = False\n";
-
-  if ( m_uiForm.abs_ckPlot->isChecked() ) pyInput += "plot = True\n";
-  else pyInput += "plot = False\n";
-
-  if ( m_uiForm.abs_ckSave->isChecked() ) pyInput += "save = True\n";
-  else pyInput += "save = False\n";
-
-  pyInput +=
-    "absorption(file, mode, sample, can, Save=save, Verbose=verbose, Plot=plot)\n";
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-}
-
-void IndirectDataAnalysis::openDirectoryDialog()
-{
-  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
-  ad->show();
-  ad->setFocus();
-}
-
-void IndirectDataAnalysis::help()
-{
-  QString tabName = m_uiForm.tabWidget->tabText(m_uiForm.tabWidget->currentIndex());
-  QString url = "http://www.mantidproject.org/IDA";
-  if ( tabName == "Initial Settings" )
-    url += "";
-  else if ( tabName == "Elwin" )
-    url += ":Elwin";
-  else if ( tabName == "MSD Fit" )
-    url += ":MSDFit";
-  else if ( tabName == "Fury" )
-    url += ":Fury";
-  else if ( tabName == "FuryFit" )
-    url += ":FuryFit";
-  else if ( tabName == "ConvFit" )
-    url += ":ConvFit";
-  else if ( tabName == "Absorption" )
-    url += ":Absorption";
-  else if ( tabName == "Abs (F2PY)" )
-    url += ":AbsF2P";
-  else if ( tabName == "Apply Corrections" )
-    url += ":AbsCor";
-  QDesktopServices::openUrl(QUrl(url));
-}
-
-void IndirectDataAnalysis::absf2pRun()
-{
-  if ( ! validateAbsorptionF2Py() )
-  {
-    showInformationBox("Invalid input.");
-    return;
-  }
-
-  QString pyInput = "import SpencerAbsCor\n";
-  
-  QString geom;
-  QString size;
-
-  if ( m_uiForm.absp_cbShape->currentText() == "Flat" )
-  {
-    geom = "flt";
-    size = "[" + m_uiForm.absp_lets->text() + ", " +
-      m_uiForm.absp_letc1->text() + ", " +
-      m_uiForm.absp_letc2->text() + "]";
-  }
-  else if ( m_uiForm.absp_cbShape->currentText() == "Cylinder" )
-  {
-    geom = "cyl";
-
-    // R3 only populated when using can. R4 is fixed to 0.0
-    if ( m_uiForm.absp_ckUseCan->isChecked() ) 
-    {
-      size = "[" + m_uiForm.absp_ler1->text() + ", " +
-        m_uiForm.absp_ler2->text() + ", " +
-        m_uiForm.absp_ler3->text() + ", 0.0 ]";
-    }
-    else
-    {
-      size = "[" + m_uiForm.absp_ler1->text() + ", " +
-        m_uiForm.absp_ler2->text() + ", 0.0, 0.0 ]";
-    }
-    
-  }
-
-  QString width = m_uiForm.absp_lewidth->text();
-
-  if ( m_uiForm.absp_cbInputType->currentText() == "File" )
-  {
-    QString input = m_uiForm.absp_inputFile->getFirstFilename();
-    if ( input == "" ) { return; }
-    pyInput +=
-    "import os.path as op\n"
-    "file = r'" + input + "'\n"
-    "( dir, filename ) = op.split(file)\n"
-    "( name, ext ) = op.splitext(filename)\n"
-    "LoadNexusProcessed(file, name)\n"
-    "inputws = name\n";
-  }
-  else
-  {
-    pyInput += "inputws = '" + m_uiForm.absp_wsInput->currentText() + "'\n";
-  }
-  
-  if ( m_uiForm.absp_ckUseCan->isChecked() )
-  {
-    pyInput +=
-      "ncan = 2\n"
-      "density = [" + m_uiForm.absp_lesamden->text() + ", " + m_uiForm.absp_lecanden->text() + ", " + m_uiForm.absp_lecanden->text() + "]\n"
-      "sigs = [" + m_uiForm.absp_lesamsigs->text() + "," + m_uiForm.absp_lecansigs->text() + "," + m_uiForm.absp_lecansigs->text() + "]\n"
-      "siga = [" + m_uiForm.absp_lesamsiga->text() + "," + m_uiForm.absp_lecansiga->text() + "," + m_uiForm.absp_lecansiga->text() + "]\n";
-  }
-  else
-  {
-    pyInput +=
-      "ncan = 1\n"
-      "density = [" + m_uiForm.absp_lesamden->text() + ", 0.0, 0.0 ]\n"
-      "sigs = [" + m_uiForm.absp_lesamsigs->text() + ", 0.0, 0.0]\n"
-      "siga = [" + m_uiForm.absp_lesamsiga->text() + ", 0.0, 0.0]\n";
-  }
-
-  pyInput +=
-    "geom = '" + geom + "'\n"
-    "beam = [3.0, 0.5*" + width + ", -0.5*" + width + ", 2.0, -2.0, 0.0, 3.0, 0.0, 3.0]\n"
-    "size = " + size + "\n"
-    "avar = " + m_uiForm.absp_leavar->text() + "\n"
-    "plotOpt = '" + m_uiForm.absp_cbPlotOutput->currentText() + "'\n"
-    "SpencerAbsCor.AbsRunFeeder(inputws, geom, beam, ncan, size, density, sigs, siga, avar, plotOpt=plotOpt)\n";
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-}
-
-void IndirectDataAnalysis::absf2pShape(int index)
-{
-  m_uiForm.absp_swShapeDetails->setCurrentIndex(index);
-  // Meaning of the "avar" variable changes depending on shape selection
-  if ( index == 0 ) { m_uiForm.absp_lbAvar->setText("Can Angle to Beam"); }
-  else if ( index == 1 ) { m_uiForm.absp_lbAvar->setText("Step Size"); }
-}
-
-void IndirectDataAnalysis::absf2pUseCanChecked(bool value)
-{
-  m_uiForm.absp_gbCan->setEnabled(value);
-
-  m_uiForm.absp_lbR3->setEnabled(value);
-  m_uiForm.absp_ler3->setEnabled(value);
-  m_uiForm.absp_valR3->setEnabled(value);
-}
-
-void IndirectDataAnalysis::absf2pTCSync()
-{
-  if ( m_uiForm.absp_letc2->text() == "" )
-  {
-    QString val = m_uiForm.absp_letc1->text();
-    m_uiForm.absp_letc2->setText(val);
-  }
-}
-
-void IndirectDataAnalysis::abscorRun()
-{
-  QString geom = m_uiForm.abscor_cbGeometry->currentText();
-  if ( geom == "Flat" )
-  {
-    geom = "flt";
-  }
-  else if ( geom == "Cylinder" )
-  {
-    geom = "cyl";
-  }
-
-  QString pyInput = "from IndirectDataAnalysis import abscorFeeder, loadNexus\n";
-
-  if ( m_uiForm.abscor_cbSampleInputType->currentText() == "File" )
-  {
-    pyInput +=
-      "sample = loadNexus(r'" + m_uiForm.abscor_sample->getFirstFilename() + "')\n";
-  }
-  else
-  {
-    pyInput +=
-      "sample = '" + m_uiForm.abscor_wsSample->currentText() + "'\n";
-  }
-
-  if ( m_uiForm.abscor_ckUseCan->isChecked() )
-  {
-    if ( m_uiForm.abscor_cbContainerInputType->currentText() == "File" )
-    {
-      pyInput +=
-        "container = loadNexus(r'" + m_uiForm.abscor_can->getFirstFilename() + "')\n";
-    }
-    else
-    {
-      pyInput +=
-        "container = '" + m_uiForm.abscor_wsContainer->currentText() + "'\n";
-    }
-  }
-  else
-  {
-    pyInput += "container = ''\n";
-  }
-
-  pyInput += "geom = '" + geom + "'\n";
-
-
-  if ( m_uiForm.abscor_ckUseCorrections->isChecked() )
-  {
-    pyInput += "useCor = True\n";
-  }
-  else
-  {
-    pyInput += "useCor = False\n";
-  }
-
-  pyInput += "abscorFeeder(sample, container, geom, useCor)\n";
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-}
-
-} //namespace CustomInterfaces
-} //namespace MantidQt
+//----------------------
+// Includes
+//----------------------
+#include "MantidQtCustomInterfaces/IndirectDataAnalysis.h"
+#include "MantidQtAPI/ManageUserDirectories.h"
+#include "MantidQtMantidWidgets/RangeSelector.h"
+
+#include "MantidAPI/CompositeFunctionMW.h"
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidAPI/AnalysisDataService.h"
+#include "MantidAPI/MatrixWorkspace.h"
+#include "MantidAPI/ITableWorkspace.h"
+#include "MantidAPI/TableRow.h"
+#include "MantidAPI/IConstraint.h"
+#include "MantidAPI/ConstraintFactory.h"
+#include "MantidAPI/Expression.h"
+
+#include <QValidator>
+#include <QIntValidator>
+#include <QDoubleValidator>
+
+#include <QLineEdit>
+#include <QFileInfo>
+#include <QMenu>
+
+#include <QDesktopServices>
+#include <QUrl>
+
+#include "DoubleEditorFactory.h"
+#include <QtCheckBoxFactory>
+#include "qttreepropertybrowser.h"
+#include "qtpropertymanager.h"
+#include "qteditorfactory.h"
+
+#include <qwt_plot.h>
+#include <qwt_plot_curve.h>
+
+namespace MantidQt
+{
+namespace CustomInterfaces
+{
+//Add this class to the list of specialised dialogs in this namespace
+DECLARE_SUBWINDOW(IndirectDataAnalysis);
+
+IndirectDataAnalysis::IndirectDataAnalysis(QWidget *parent) :
+  UserSubWindow(parent), m_nDec(6), m_valInt(NULL), m_valDbl(NULL), 
+  m_furyResFileType(true), 
+  m_elwPlot(NULL), m_elwR1(NULL), m_elwR2(NULL), m_elwDataCurve(NULL),
+  m_msdPlot(NULL), m_msdRange(NULL), m_msdDataCurve(NULL), m_msdTree(NULL), m_msdDblMng(NULL),
+  m_furPlot(NULL), m_furRange(NULL), m_furCurve(NULL), m_furTree(NULL), m_furDblMng(NULL),
+  m_ffDataCurve(NULL), m_ffFitCurve(NULL),
+  m_cfDataCurve(NULL), m_cfCalcCurve(NULL),
+  m_changeObserver(*this, &IndirectDataAnalysis::handleDirectoryChange)
+{
+}
+
+void IndirectDataAnalysis::closeEvent(QCloseEvent*)
+{
+  Mantid::Kernel::ConfigService::Instance().removeObserver(m_changeObserver);
+}
+
+void IndirectDataAnalysis::handleDirectoryChange(Mantid::Kernel::ConfigValChangeNotification_ptr pNf)
+{
+  std::string key = pNf->key();
+  std::string preValue = pNf->preValue();
+  std::string curValue = pNf->curValue();
+
+  if ( key == "defaultsave.directory" )
+  {
+    loadSettings();
+  }
+}
+
+void IndirectDataAnalysis::initLayout()
+{
+  m_uiForm.setupUi(this);
+
+  // Connect Poco Notification Observer
+  Mantid::Kernel::ConfigService::Instance().addObserver(m_changeObserver);
+
+  // create validators
+  m_valInt = new QIntValidator(this);
+  m_valDbl = new QDoubleValidator(this);
+  // Create Editor Factories
+  m_dblEdFac = new DoubleEditorFactory();
+  m_blnEdFac = new QtCheckBoxFactory();
+
+  m_stringManager = new QtStringPropertyManager();
+
+  setupElwin();
+  setupMsd();
+  setupFury();
+  setupFuryFit();
+  setupConFit();
+  setupAbsorptionF2Py();
+  setupAbsCor();
+
+  connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(help()));
+  connect(m_uiForm.pbRun, SIGNAL(clicked()), this, SLOT(run()));
+  connect(m_uiForm.pbManageDirs, SIGNAL(clicked()), this, SLOT(openDirectoryDialog()));
+
+  // absorption
+  connect(m_uiForm.abs_cbShape, SIGNAL(currentIndexChanged(int)), m_uiForm.abs_swDetails, SLOT(setCurrentIndex(int)));
+  // apply validators - absorption
+  m_uiForm.abs_leAttenuation->setValidator(m_valDbl);
+  m_uiForm.abs_leScatter->setValidator(m_valDbl);
+  m_uiForm.abs_leDensity->setValidator(m_valDbl);
+  m_uiForm.abs_leFlatHeight->setValidator(m_valDbl);
+  m_uiForm.abs_leWidth->setValidator(m_valDbl);
+  m_uiForm.abs_leThickness->setValidator(m_valDbl);
+  m_uiForm.abs_leElementSize->setValidator(m_valDbl);
+  m_uiForm.abs_leCylHeight->setValidator(m_valDbl);
+  m_uiForm.abs_leRadius->setValidator(m_valDbl);
+  m_uiForm.abs_leSlices->setValidator(m_valInt);
+  m_uiForm.abs_leAnnuli->setValidator(m_valInt);
+}
+
+void IndirectDataAnalysis::initLocalPython()
+{
+  loadSettings();
+}
+
+void IndirectDataAnalysis::loadSettings()
+{
+  QSettings settings;
+  QString settingsGroup = "CustomInterfaces/IndirectAnalysis/";
+  QString saveDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("defaultsave.directory"));
+
+  settings.beginGroup(settingsGroup + "ProcessedFiles");
+  settings.setValue("last_directory", saveDir);
+  m_uiForm.elwin_inputFile->readSettings(settings.group());
+  m_uiForm.msd_inputFile->readSettings(settings.group());
+  m_uiForm.fury_iconFile->readSettings(settings.group());
+  m_uiForm.fury_resFile->readSettings(settings.group());
+  m_uiForm.furyfit_inputFile->readSettings(settings.group());
+  m_uiForm.confit_inputFile->readSettings(settings.group());
+  m_uiForm.confit_resInput->readSettings(settings.group());
+  m_uiForm.abs_inputFile->readSettings(settings.group());
+  m_uiForm.absp_inputFile->readSettings(settings.group());
+  m_uiForm.abscor_sample->readSettings(settings.group());
+  m_uiForm.abscor_can->readSettings(settings.group());
+  settings.endGroup();
+}
+
+void IndirectDataAnalysis::setupElwin()
+{
+  // Create QtTreePropertyBrowser object
+  m_elwTree = new QtTreePropertyBrowser();
+  m_uiForm.elwin_properties->addWidget(m_elwTree);
+
+  // Create Manager Objects
+  m_elwDblMng = new QtDoublePropertyManager();
+  m_elwBlnMng = new QtBoolPropertyManager();
+  m_elwGrpMng = new QtGroupPropertyManager();
+
+  // Editor Factories
+  m_elwTree->setFactoryForManager(m_elwDblMng, m_dblEdFac);
+  m_elwTree->setFactoryForManager(m_elwBlnMng, m_blnEdFac);
+
+  // Create Properties
+  m_elwProp["R1S"] = m_elwDblMng->addProperty("Start");
+  m_elwDblMng->setDecimals(m_elwProp["R1S"], m_nDec);
+  m_elwProp["R1E"] = m_elwDblMng->addProperty("End");
+  m_elwDblMng->setDecimals(m_elwProp["R1E"], m_nDec);  
+  m_elwProp["R2S"] = m_elwDblMng->addProperty("Start");
+  m_elwDblMng->setDecimals(m_elwProp["R2S"], m_nDec);
+  m_elwProp["R2E"] = m_elwDblMng->addProperty("End");
+  m_elwDblMng->setDecimals(m_elwProp["R2E"], m_nDec);
+
+  m_elwProp["UseTwoRanges"] = m_elwBlnMng->addProperty("Use Two Ranges");
+
+  m_elwProp["Range1"] = m_elwGrpMng->addProperty("Range One");
+  m_elwProp["Range1"]->addSubProperty(m_elwProp["R1S"]);
+  m_elwProp["Range1"]->addSubProperty(m_elwProp["R1E"]);
+  m_elwProp["Range2"] = m_elwGrpMng->addProperty("Range Two");
+  m_elwProp["Range2"]->addSubProperty(m_elwProp["R2S"]);
+  m_elwProp["Range2"]->addSubProperty(m_elwProp["R2E"]);
+
+  m_elwTree->addProperty(m_elwProp["Range1"]);
+  m_elwTree->addProperty(m_elwProp["UseTwoRanges"]);
+  m_elwTree->addProperty(m_elwProp["Range2"]);
+
+  // Create Slice Plot Widget for Range Selection
+  m_elwPlot = new QwtPlot(this);
+  m_elwPlot->setAxisFont(QwtPlot::xBottom, this->font());
+  m_elwPlot->setAxisFont(QwtPlot::yLeft, this->font());
+  m_uiForm.elwin_plot->addWidget(m_elwPlot);
+  m_elwPlot->setCanvasBackground(Qt::white);
+  // We always want one range selector... the second one can be controlled from
+  // within the elwinTwoRanges(bool state) function
+  m_elwR1 = new MantidWidgets::RangeSelector(m_elwPlot);
+  connect(m_elwR1, SIGNAL(minValueChanged(double)), this, SLOT(elwinMinChanged(double)));
+  connect(m_elwR1, SIGNAL(maxValueChanged(double)), this, SLOT(elwinMaxChanged(double)));
+  // create the second range
+  m_elwR2 = new MantidWidgets::RangeSelector(m_elwPlot);
+  m_elwR2->setColour(Qt::darkGreen); // dark green for background
+  connect(m_elwR1, SIGNAL(rangeChanged(double, double)), m_elwR2, SLOT(setRange(double, double)));
+  connect(m_elwR2, SIGNAL(minValueChanged(double)), this, SLOT(elwinMinChanged(double)));
+  connect(m_elwR2, SIGNAL(maxValueChanged(double)), this, SLOT(elwinMaxChanged(double)));
+  m_elwR2->setRange(m_elwR1->getRange());
+  // Refresh the plot window
+  m_elwPlot->replot();
+  
+  connect(m_elwDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(elwinUpdateRS(QtProperty*, double)));
+  connect(m_elwBlnMng, SIGNAL(valueChanged(QtProperty*, bool)), this, SLOT(elwinTwoRanges(QtProperty*, bool)));
+  elwinTwoRanges(0, false);
+
+  // m_uiForm element signals and slots
+  connect(m_uiForm.elwin_pbPlotInput, SIGNAL(clicked()), this, SLOT(elwinPlotInput()));
+
+  // Set any default values
+  m_elwDblMng->setValue(m_elwProp["R1S"], -0.02);
+  m_elwDblMng->setValue(m_elwProp["R1E"], 0.02);
+}
+
+void IndirectDataAnalysis::setupMsd()
+{
+  // Tree Browser
+  m_msdTree = new QtTreePropertyBrowser();
+  m_uiForm.msd_properties->addWidget(m_msdTree);
+
+  m_msdDblMng = new QtDoublePropertyManager();
+
+  m_msdTree->setFactoryForManager(m_msdDblMng, m_dblEdFac);
+
+  m_msdProp["Start"] = m_msdDblMng->addProperty("StartX");
+  m_msdDblMng->setDecimals(m_msdProp["Start"], m_nDec);
+  m_msdProp["End"] = m_msdDblMng->addProperty("EndX");
+  m_msdDblMng->setDecimals(m_msdProp["End"], m_nDec);
+
+  m_msdTree->addProperty(m_msdProp["Start"]);
+  m_msdTree->addProperty(m_msdProp["End"]);
+
+  m_msdPlot = new QwtPlot(this);
+  m_uiForm.msd_plot->addWidget(m_msdPlot);
+
+  // Cosmetics
+  m_msdPlot->setAxisFont(QwtPlot::xBottom, this->font());
+  m_msdPlot->setAxisFont(QwtPlot::yLeft, this->font());
+  m_msdPlot->setCanvasBackground(Qt::white);
+
+  m_msdRange = new MantidWidgets::RangeSelector(m_msdPlot);
+
+  connect(m_msdRange, SIGNAL(minValueChanged(double)), this, SLOT(msdMinChanged(double)));
+  connect(m_msdRange, SIGNAL(maxValueChanged(double)), this, SLOT(msdMaxChanged(double)));
+  connect(m_msdDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(msdUpdateRS(QtProperty*, double)));
+
+  connect(m_uiForm.msd_pbPlotInput, SIGNAL(clicked()), this, SLOT(msdPlotInput()));
+}
+
+void IndirectDataAnalysis::setupFury()
+{
+  m_furTree = new QtTreePropertyBrowser();
+  m_uiForm.fury_TreeSpace->addWidget(m_furTree);
+
+  m_furDblMng = new QtDoublePropertyManager();
+
+  m_furPlot = new QwtPlot(this);
+  m_uiForm.fury_PlotSpace->addWidget(m_furPlot);
+  m_furPlot->setCanvasBackground(Qt::white);
+  m_furPlot->setAxisFont(QwtPlot::xBottom, this->font());
+  m_furPlot->setAxisFont(QwtPlot::yLeft, this->font());
+
+  m_furProp["ELow"] = m_furDblMng->addProperty("ELow");
+  m_furDblMng->setDecimals(m_furProp["ELow"], m_nDec);
+  m_furProp["EWidth"] = m_furDblMng->addProperty("EWidth");
+  m_furDblMng->setDecimals(m_furProp["EWidth"], m_nDec);
+  m_furProp["EHigh"] = m_furDblMng->addProperty("EHigh");
+  m_furDblMng->setDecimals(m_furProp["EHigh"], m_nDec);
+
+  m_furTree->addProperty(m_furProp["ELow"]);
+  m_furTree->addProperty(m_furProp["EWidth"]);
+  m_furTree->addProperty(m_furProp["EHigh"]);
+
+  m_furTree->setFactoryForManager(m_furDblMng, m_dblEdFac);
+
+  m_furRange = new MantidQt::MantidWidgets::RangeSelector(m_furPlot);
+
+  // signals / slots & validators
+  connect(m_furRange, SIGNAL(minValueChanged(double)), this, SLOT(furyMinChanged(double)));
+  connect(m_furRange, SIGNAL(maxValueChanged(double)), this, SLOT(furyMaxChanged(double)));
+  connect(m_furDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(furyUpdateRS(QtProperty*, double)));
+  
+  connect(m_uiForm.fury_cbInputType, SIGNAL(currentIndexChanged(int)), m_uiForm.fury_swInput, SLOT(setCurrentIndex(int)));  
+  connect(m_uiForm.fury_cbResType, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(furyResType(const QString&)));
+  connect(m_uiForm.fury_pbPlotInput, SIGNAL(clicked()), this, SLOT(furyPlotInput()));
+}
+
+void IndirectDataAnalysis::setupFuryFit()
+{
+  m_ffTree = new QtTreePropertyBrowser();
+  m_uiForm.furyfit_properties->addWidget(m_ffTree);
+  
+  // Setup FuryFit Plot Window
+  m_ffPlot = new QwtPlot(this);
+  m_ffPlot->setAxisFont(QwtPlot::xBottom, this->font());
+  m_ffPlot->setAxisFont(QwtPlot::yLeft, this->font());
+  m_uiForm.furyfit_vlPlot->addWidget(m_ffPlot);
+  m_ffPlot->setCanvasBackground(QColor(255,255,255));
+  
+  m_ffRangeS = new MantidQt::MantidWidgets::RangeSelector(m_ffPlot);
+  connect(m_ffRangeS, SIGNAL(minValueChanged(double)), this, SLOT(furyfitXMinSelected(double)));
+  connect(m_ffRangeS, SIGNAL(maxValueChanged(double)), this, SLOT(furyfitXMaxSelected(double)));
+
+  m_ffBackRangeS = new MantidQt::MantidWidgets::RangeSelector(m_ffPlot,
+    MantidQt::MantidWidgets::RangeSelector::YSINGLE);
+  m_ffBackRangeS->setRange(0.0,1.0);
+  m_ffBackRangeS->setColour(Qt::darkGreen);
+  connect(m_ffBackRangeS, SIGNAL(minValueChanged(double)), this, SLOT(furyfitBackgroundSelected(double)));
+
+  // setupTreePropertyBrowser
+  m_groupManager = new QtGroupPropertyManager();
+  m_ffDblMng = new QtDoublePropertyManager();
+  m_ffRangeManager = new QtDoublePropertyManager();
+  
+  m_ffTree->setFactoryForManager(m_ffDblMng, m_dblEdFac);
+  m_ffTree->setFactoryForManager(m_ffRangeManager, m_dblEdFac);
+
+  m_ffProp["StartX"] = m_ffRangeManager->addProperty("StartX");
+  m_ffRangeManager->setDecimals(m_ffProp["StartX"], m_nDec);
+  m_ffProp["EndX"] = m_ffRangeManager->addProperty("EndX");
+  m_ffRangeManager->setDecimals(m_ffProp["EndX"], m_nDec);
+
+  connect(m_ffRangeManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(furyfitRangePropChanged(QtProperty*, double)));
+
+  m_ffProp["LinearBackground"] = m_groupManager->addProperty("LinearBackground");
+  m_ffProp["BackgroundA0"] = m_ffRangeManager->addProperty("A0");
+  m_ffRangeManager->setDecimals(m_ffProp["BackgroundA0"], m_nDec);
+  m_ffProp["LinearBackground"]->addSubProperty(m_ffProp["BackgroundA0"]);
+
+  m_ffProp["Exponential1"] = createExponential("Exponential 1");
+  m_ffProp["Exponential2"] = createExponential("Exponential 2");
+  
+  m_ffProp["StretchedExp"] = createStretchedExp("Stretched Exponential");
+
+  furyfitTypeSelection(m_uiForm.furyfit_cbFitType->currentIndex());
+
+  // Connect to PlotGuess checkbox
+  connect(m_ffDblMng, SIGNAL(propertyChanged(QtProperty*)), this, SLOT(furyfitPlotGuess(QtProperty*)));
+
+  // Signal/slot ui connections
+  connect(m_uiForm.furyfit_inputFile, SIGNAL(fileEditingFinished()), this, SLOT(furyfitPlotInput()));
+  connect(m_uiForm.furyfit_cbFitType, SIGNAL(currentIndexChanged(int)), this, SLOT(furyfitTypeSelection(int)));
+  connect(m_uiForm.furyfit_pbPlotInput, SIGNAL(clicked()), this, SLOT(furyfitPlotInput()));
+  connect(m_uiForm.furyfit_leSpecNo, SIGNAL(editingFinished()), this, SLOT(furyfitPlotInput()));
+  connect(m_uiForm.furyfit_cbInputType, SIGNAL(currentIndexChanged(int)), m_uiForm.furyfit_swInput, SLOT(setCurrentIndex(int)));  
+  connect(m_uiForm.furyfit_pbSeqFit, SIGNAL(clicked()), this, SLOT(furyfitSequential()));
+  // apply validators - furyfit
+  m_uiForm.furyfit_leSpecNo->setValidator(m_valInt);
+
+  // Set a custom handler for the QTreePropertyBrowser's ContextMenu event
+  m_ffTree->setContextMenuPolicy(Qt::CustomContextMenu);
+  connect(m_ffTree, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(fitContextMenu(const QPoint &)));
+}
+
+void IndirectDataAnalysis::setupConFit()
+{
+  // Create Property Managers
+  m_cfGrpMng = new QtGroupPropertyManager();
+  m_cfBlnMng = new QtBoolPropertyManager();
+  m_cfDblMng = new QtDoublePropertyManager();
+
+  // Create TreeProperty Widget
+  m_cfTree = new QtTreePropertyBrowser();
+  m_uiForm.confit_properties->addWidget(m_cfTree);
+
+  // add factories to managers
+  m_cfTree->setFactoryForManager(m_cfBlnMng, m_blnEdFac);
+  m_cfTree->setFactoryForManager(m_cfDblMng, m_dblEdFac);
+
+  // Create Plot Widget
+  m_cfPlot = new QwtPlot(this);
+  m_cfPlot->setAxisFont(QwtPlot::xBottom, this->font());
+  m_cfPlot->setAxisFont(QwtPlot::yLeft, this->font());
+  m_cfPlot->setCanvasBackground(Qt::white);
+  m_uiForm.confit_plot->addWidget(m_cfPlot);
+
+  // Create Range Selectors
+  m_cfRangeS = new MantidQt::MantidWidgets::RangeSelector(m_cfPlot);
+  m_cfBackgS = new MantidQt::MantidWidgets::RangeSelector(m_cfPlot, 
+    MantidQt::MantidWidgets::RangeSelector::YSINGLE);
+  m_cfBackgS->setColour(Qt::darkGreen);
+  m_cfBackgS->setRange(0.0, 1.0);
+  m_cfHwhmRange = new MantidQt::MantidWidgets::RangeSelector(m_cfPlot);
+  m_cfHwhmRange->setColour(Qt::red);
+
+  // Populate Property Widget
+  m_cfProp["FitRange"] = m_cfGrpMng->addProperty("Fitting Range");
+  m_cfProp["StartX"] = m_cfDblMng->addProperty("StartX");
+  m_cfDblMng->setDecimals(m_cfProp["StartX"], m_nDec);
+  m_cfProp["EndX"] = m_cfDblMng->addProperty("EndX");
+  m_cfDblMng->setDecimals(m_cfProp["EndX"], m_nDec);
+  m_cfProp["FitRange"]->addSubProperty(m_cfProp["StartX"]);
+  m_cfProp["FitRange"]->addSubProperty(m_cfProp["EndX"]);
+  m_cfTree->addProperty(m_cfProp["FitRange"]);
+
+  m_cfProp["LinearBackground"] = m_cfGrpMng->addProperty("Background");
+  m_cfProp["BGA0"] = m_cfDblMng->addProperty("A0");
+  m_cfDblMng->setDecimals(m_cfProp["BGA0"], m_nDec);
+  m_cfProp["BGA1"] = m_cfDblMng->addProperty("A1");
+  m_cfDblMng->setDecimals(m_cfProp["BGA1"], m_nDec);
+  m_cfProp["LinearBackground"]->addSubProperty(m_cfProp["BGA0"]);
+  m_cfProp["LinearBackground"]->addSubProperty(m_cfProp["BGA1"]);
+  m_cfTree->addProperty(m_cfProp["LinearBackground"]);
+
+  // Delta Function
+  m_cfProp["DeltaFunction"] = m_cfGrpMng->addProperty("Delta Function");
+  m_cfProp["UseDeltaFunc"] = m_cfBlnMng->addProperty("Use");
+  m_cfProp["DeltaHeight"] = m_cfDblMng->addProperty("Height");
+  m_cfDblMng->setDecimals(m_cfProp["DeltaHeight"], m_nDec);
+  m_cfProp["DeltaFunction"]->addSubProperty(m_cfProp["UseDeltaFunc"]);
+  m_cfTree->addProperty(m_cfProp["DeltaFunction"]);
+
+  m_cfProp["Lorentzian1"] = createLorentzian("Lorentzian 1");
+  m_cfProp["Lorentzian2"] = createLorentzian("Lorentzian 2");
+
+  // Connections
+  connect(m_cfRangeS, SIGNAL(minValueChanged(double)), this, SLOT(confitMinChanged(double)));
+  connect(m_cfRangeS, SIGNAL(maxValueChanged(double)), this, SLOT(confitMaxChanged(double)));
+  connect(m_cfBackgS, SIGNAL(minValueChanged(double)), this, SLOT(confitBackgLevel(double)));
+  connect(m_cfHwhmRange, SIGNAL(minValueChanged(double)), this, SLOT(confitHwhmChanged(double)));
+  connect(m_cfHwhmRange, SIGNAL(maxValueChanged(double)), this, SLOT(confitHwhmChanged(double)));
+  connect(m_cfDblMng, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(confitUpdateRS(QtProperty*, double)));
+  connect(m_cfBlnMng, SIGNAL(valueChanged(QtProperty*, bool)), this, SLOT(confitCheckBoxUpdate(QtProperty*, bool)));
+
+  connect(m_cfDblMng, SIGNAL(propertyChanged(QtProperty*)), this, SLOT(confitPlotGuess(QtProperty*)));
+
+  // Have HWHM Range linked to Fit Start/End Range
+  connect(m_cfRangeS, SIGNAL(rangeChanged(double, double)), m_cfHwhmRange, SLOT(setRange(double, double)));
+  m_cfHwhmRange->setRange(-1.0,1.0);
+  confitHwhmUpdateRS(0.02);
+
+  confitTypeSelection(m_uiForm.confit_cbFitType->currentIndex());
+  confitBgTypeSelection(m_uiForm.confit_cbBackground->currentIndex());
+
+  // Replot input automatically when file / spec no changes
+  connect(m_uiForm.confit_leSpecNo, SIGNAL(editingFinished()), this, SLOT(confitPlotInput()));
+  connect(m_uiForm.confit_inputFile, SIGNAL(fileEditingFinished()), this, SLOT(confitPlotInput()));
+  
+  connect(m_uiForm.confit_cbInputType, SIGNAL(currentIndexChanged(int)), m_uiForm.confit_swInput, SLOT(setCurrentIndex(int)));
+  connect(m_uiForm.confit_cbFitType, SIGNAL(currentIndexChanged(int)), this, SLOT(confitTypeSelection(int)));
+  connect(m_uiForm.confit_cbBackground, SIGNAL(currentIndexChanged(int)), this, SLOT(confitBgTypeSelection(int)));
+  connect(m_uiForm.confit_pbPlotInput, SIGNAL(clicked()), this, SLOT(confitPlotInput()));
+  connect(m_uiForm.confit_pbSequential, SIGNAL(clicked()), this, SLOT(confitSequential()));
+
+  m_uiForm.confit_leSpecNo->setValidator(m_valInt);
+  m_uiForm.confit_leSpecMax->setValidator(m_valInt);
+
+  // Context menu
+  m_cfTree->setContextMenuPolicy(Qt::CustomContextMenu);
+  connect(m_cfTree, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(fitContextMenu(const QPoint &)));
+}
+
+void IndirectDataAnalysis::setupAbsorptionF2Py()
+{
+  // set signals and slot connections for F2Py Absorption routine
+  connect(m_uiForm.absp_cbInputType, SIGNAL(currentIndexChanged(int)), m_uiForm.absp_swInput, SLOT(setCurrentIndex(int)));
+  connect(m_uiForm.absp_cbShape, SIGNAL(currentIndexChanged(int)), this, SLOT(absf2pShape(int)));
+  connect(m_uiForm.absp_ckUseCan, SIGNAL(toggled(bool)), this, SLOT(absf2pUseCanChecked(bool)));
+  connect(m_uiForm.absp_letc1, SIGNAL(editingFinished()), this, SLOT(absf2pTCSync()));
+  // apply QValidators to items.
+  m_uiForm.absp_lewidth->setValidator(m_valDbl);
+  m_uiForm.absp_leavar->setValidator(m_valDbl);
+  // sample
+  m_uiForm.absp_lesamden->setValidator(m_valDbl);
+  m_uiForm.absp_lesamsigs->setValidator(m_valDbl);
+  m_uiForm.absp_lesamsiga->setValidator(m_valDbl);
+  // can
+  m_uiForm.absp_lecanden->setValidator(m_valDbl);
+  m_uiForm.absp_lecansigs->setValidator(m_valDbl);
+  m_uiForm.absp_lecansiga->setValidator(m_valDbl);
+  // flat shape
+  m_uiForm.absp_lets->setValidator(m_valDbl);
+  m_uiForm.absp_letc1->setValidator(m_valDbl);
+  m_uiForm.absp_letc2->setValidator(m_valDbl);
+  // cylinder shape
+  m_uiForm.absp_ler1->setValidator(m_valDbl);
+  m_uiForm.absp_ler2->setValidator(m_valDbl);
+  m_uiForm.absp_ler3->setValidator(m_valDbl);
+}
+
+void IndirectDataAnalysis::setupAbsCor()
+{
+  // Disable Container inputs is "Use Container" is not checked
+  connect(m_uiForm.abscor_ckUseCan, SIGNAL(toggled(bool)), m_uiForm.abscor_lbContainerInputType, SLOT(setEnabled(bool)));
+  connect(m_uiForm.abscor_ckUseCan, SIGNAL(toggled(bool)), m_uiForm.abscor_cbContainerInputType, SLOT(setEnabled(bool)));
+  connect(m_uiForm.abscor_ckUseCan, SIGNAL(toggled(bool)), m_uiForm.abscor_swContainerInput, SLOT(setEnabled(bool)));
+
+  connect(m_uiForm.abscor_cbSampleInputType, SIGNAL(currentIndexChanged(int)), m_uiForm.abscor_swSampleInput, SLOT(setCurrentIndex(int)));
+  connect(m_uiForm.abscor_cbContainerInputType, SIGNAL(currentIndexChanged(int)), m_uiForm.abscor_swContainerInput, SLOT(setCurrentIndex(int)));
+}
+
+bool IndirectDataAnalysis::validateElwin()
+{
+  bool valid = true;
+
+  if ( ! m_uiForm.elwin_inputFile->isValid() )
+  {
+    valid = false;
+  }
+
+  return valid;
+}
+
+bool IndirectDataAnalysis::validateMsd()
+{
+  bool valid = true;
+
+  if ( ! m_uiForm.msd_inputFile->isValid() )
+  {
+    valid = false;
+  }
+
+  return valid;
+}
+
+bool IndirectDataAnalysis::validateFury()
+{
+  bool valid = true;
+
+  switch ( m_uiForm.fury_cbInputType->currentIndex() )
+  {
+  case 0:
+    {
+      if ( ! m_uiForm.fury_iconFile->isValid() )
+      {
+        valid = false;
+      }
+    }
+    break;
+  case 1:
+    {
+      if ( m_uiForm.fury_wsSample->currentText() == "" )
+      {
+        valid = false;
+      }
+    }
+    break;
+  }
+
+  if ( ! m_uiForm.fury_resFile->isValid()  )
+  {
+    valid = false;
+  }
+
+  return valid;
+}
+
+bool IndirectDataAnalysis::validateAbsorption()
+{
+  bool valid = true;
+
+  if ( ! m_uiForm.abs_inputFile->isValid() )
+  {
+    valid = false;
+  }
+
+  if ( m_uiForm.abs_leAttenuation->text() == "" )
+  {
+    m_uiForm.abs_valAttenuation->setText("*");
+    valid = false;
+  }
+  else
+  {
+    m_uiForm.abs_valAttenuation->setText(" ");
+  }
+
+  if ( m_uiForm.abs_leScatter->text() == "" )
+  {
+    m_uiForm.abs_valScatter->setText("*");
+    valid = false;
+  }
+  else
+  {
+    m_uiForm.abs_valScatter->setText(" ");
+  }
+
+  if ( m_uiForm.abs_leDensity->text() == "" )
+  {
+    m_uiForm.abs_valDensity->setText("*");
+    valid = false;
+  }
+  else
+  {
+    m_uiForm.abs_valDensity->setText(" ");
+  }
+
+  if ( m_uiForm.abs_cbShape->currentText() == "Flat Plate" )
+  {
+    // ... FLAT PLATE
+    if ( m_uiForm.abs_leFlatHeight->text() == "" )
+    {
+      m_uiForm.abs_valFlatHeight->setText("*");
+      valid = false;
+    }
+    else
+    {
+      m_uiForm.abs_valFlatHeight->setText(" ");
+    }
+
+    if ( m_uiForm.abs_leWidth->text() == "" )
+    {
+      m_uiForm.abs_valWidth->setText("*");
+      valid = false;
+    }
+    else
+    {
+      m_uiForm.abs_valWidth->setText(" ");
+    }
+
+    if ( m_uiForm.abs_leThickness->text() == "" )
+    {
+      m_uiForm.abs_valThickness->setText("*");
+      valid = false;
+    }
+    else
+    {
+      m_uiForm.abs_valThickness->setText(" ");
+    }
+
+    if ( m_uiForm.abs_leElementSize->text() == "" )
+    {
+      m_uiForm.abs_valElementSize->setText("*");
+      valid = false;
+    }
+    else
+    {
+      m_uiForm.abs_valElementSize->setText(" ");
+    }
+  }
+  else
+  {
+    // ... CYLINDER
+    if ( m_uiForm.abs_leCylHeight->text() == "" )
+    {
+      m_uiForm.abs_valCylHeight->setText("*");
+      valid = false;
+    }
+    else
+    {
+      m_uiForm.abs_valCylHeight->setText(" ");
+    }
+
+    if ( m_uiForm.abs_leRadius->text() == "" )
+    {
+      m_uiForm.abs_valRadius->setText("*");
+      valid = false;
+    }
+    else
+    {
+      m_uiForm.abs_valRadius->setText(" ");
+    }
+
+    if ( m_uiForm.abs_leSlices->text() == "" )
+    {
+      m_uiForm.abs_valSlices->setText("*");
+      valid = false;
+    }
+    else
+    {
+      m_uiForm.abs_valSlices->setText(" ");
+    }
+
+    if ( m_uiForm.abs_leAnnuli->text() == "" )
+    {
+      m_uiForm.abs_valAnnuli->setText("*");
+      valid = false;
+    }
+    else
+    {
+      m_uiForm.abs_valAnnuli->setText(" ");
+    }
+  }
+
+  return valid;
+}
+
+bool IndirectDataAnalysis::validateAbsorptionF2Py()
+{
+  bool valid = true;
+
+  // Input (file or workspace)
+  if ( m_uiForm.absp_cbInputType->currentText() == "File" )
+  {
+    if ( ! m_uiForm.absp_inputFile->isValid() ) { valid = false; }
+  }
+  else
+  {
+    if ( m_uiForm.absp_wsInput->currentText() == "" ) { valid = false; }
+  }
+
+  if ( m_uiForm.absp_cbShape->currentText() == "Flat" )
+  {
+    // Flat Geometry
+    if ( m_uiForm.absp_lets->text() != "" )
+    {
+      m_uiForm.absp_valts->setText(" ");
+    }
+    else
+    {
+      m_uiForm.absp_valts->setText("*");
+      valid = false;
+    }
+
+    if ( m_uiForm.absp_letc1->text() != "" )
+    {
+      m_uiForm.absp_valtc1->setText(" ");
+    }
+    else
+    {
+      m_uiForm.absp_valtc1->setText("*");
+      valid = false;
+    }
+
+    if ( m_uiForm.absp_letc2->text() != "" )
+    {
+      m_uiForm.absp_valtc2->setText(" ");
+    }
+    else
+    {
+      m_uiForm.absp_valtc2->setText("*");
+      valid = false;
+    }
+  }
+
+  if ( m_uiForm.absp_cbShape->currentText() == "Cylinder" )
+  {
+    // Cylinder geometry
+    if ( m_uiForm.absp_ler1->text() != "" )
+    {
+      m_uiForm.absp_valR1->setText(" ");
+    }
+    else
+    {
+      m_uiForm.absp_valR1->setText("*");
+      valid = false;
+    }
+
+    if ( m_uiForm.absp_ler2->text() != "" )
+    {
+      m_uiForm.absp_valR2->setText(" ");
+    }
+    else
+    {
+      m_uiForm.absp_valR2->setText("*");
+      valid = false;
+    }
+    
+    // R3  only relevant when using can
+    if ( m_uiForm.absp_ckUseCan->isChecked() )
+    {
+      if ( m_uiForm.absp_ler3->text() != "" )
+      {
+        m_uiForm.absp_valR3->setText(" ");
+      }
+      else
+      {
+        m_uiForm.absp_valR3->setText("*");
+        valid = false;
+      }
+    }
+  }
+
+  // Can angle to beam || Step size
+  if ( m_uiForm.absp_leavar->text() != "" )
+  {
+    m_uiForm.absp_valAvar->setText(" ");
+  }
+  else
+  {
+    m_uiForm.absp_valAvar->setText("*");
+    valid = false;
+  }
+
+  // Beam Width
+  if ( m_uiForm.absp_lewidth->text() != "" )
+  {
+    m_uiForm.absp_valWidth->setText(" ");
+  }
+  else
+  {
+    m_uiForm.absp_valWidth->setText("*");
+    valid = false;
+  }
+
+  // Sample details
+  if ( m_uiForm.absp_lesamden->text() != "" )
+  {
+    m_uiForm.absp_valSamden->setText(" ");
+  }
+  else
+  {
+    m_uiForm.absp_valSamden->setText("*");
+    valid = false;
+  }
+
+  if ( m_uiForm.absp_lesamsigs->text() != "" )
+  {
+    m_uiForm.absp_valSamsigs->setText(" ");
+  }
+  else
+  {
+    m_uiForm.absp_valSamsigs->setText("*");
+    valid = false;
+  }
+
+  if ( m_uiForm.absp_lesamsiga->text() != "" )
+  {
+    m_uiForm.absp_valSamsiga->setText(" ");
+  }
+  else
+  {
+    m_uiForm.absp_valSamsiga->setText("*");
+    valid = false;
+  }
+
+  // Can details (only test if "Use Can" is checked)
+  if ( m_uiForm.absp_ckUseCan->isChecked() )
+  {
+    if ( m_uiForm.absp_lecanden->text() != "" )
+    {
+      m_uiForm.absp_valCanden->setText(" ");
+    }
+    else
+    {
+      m_uiForm.absp_valCanden->setText("*");
+      valid = false;
+    }
+
+    if ( m_uiForm.absp_lecansigs->text() != "" )
+    {
+      m_uiForm.absp_valCansigs->setText(" ");
+    }
+    else
+    {
+      m_uiForm.absp_valCansigs->setText("*");
+      valid = false;
+    }
+
+    if ( m_uiForm.absp_lecansiga->text() != "" )
+    {
+      m_uiForm.absp_valCansiga->setText(" ");
+    }
+    else
+    {
+      m_uiForm.absp_valCansiga->setText("*");
+      valid = false;
+    }
+  }
+
+  return valid;
+}
+
+Mantid::API::CompositeFunctionMW* IndirectDataAnalysis::furyfitCreateFunction(bool tie)
+{
+  Mantid::API::CompositeFunctionMW* result = new Mantid::API::CompositeFunctionMW();
+  QString fname;
+  const int fitType = m_uiForm.furyfit_cbFitType->currentIndex();
+
+  Mantid::API::IFitFunction* func = Mantid::API::FunctionFactory::Instance().createFunction("LinearBackground");
+  func->setParameter("A0", m_ffDblMng->value(m_ffProp["BackgroundA0"]));
+  result->addFunction(func);
+  result->tie("f0.A1", "0");
+  if ( tie ) { result->tie("f0.A0", m_ffProp["BackgroundA0"]->valueText().toStdString()); }
+  
+  if ( fitType == 2 ) { fname = "Stretched Exponential"; }
+  else { fname = "Exponential 1"; }
+
+  result->addFunction(furyfitCreateUserFunction(fname, tie));
+
+  if ( fitType == 1 || fitType == 3 )
+  {
+    if ( fitType == 1 ) { fname = "Exponential 2"; }
+    else { fname = "Stretched Exponential"; }
+    result->addFunction(furyfitCreateUserFunction(fname, tie));
+  }
+
+  // Return CompositeFunction object to caller.
+  result->applyTies();
+  return result;
+}
+
+Mantid::API::IFitFunction* IndirectDataAnalysis::furyfitCreateUserFunction(const QString & name, bool tie)
+{
+  Mantid::API::IFitFunction* result = Mantid::API::FunctionFactory::Instance().createFunction("UserFunction");  
+  std::string formula;
+
+  if ( name.startsWith("Exp") ) { formula = "Intensity*exp(-(x/Tau))"; }
+  else { formula = "Intensity*exp(-(x/Tau)^Beta)"; }
+
+  Mantid::API::IFitFunction::Attribute att(formula);  
+  result->setAttribute("Formula", att);
+
+  result->setParameter("Intensity", m_ffDblMng->value(m_ffProp[name+".Intensity"]));
+
+  if ( tie || ! m_ffProp[name+".Intensity"]->subProperties().isEmpty() )
+  {
+    result->tie("Intensity", m_ffProp[name+".Intensity"]->valueText().toStdString());
+  }
+  result->setParameter("Tau", m_ffDblMng->value(m_ffProp[name+".Tau"]));
+  if ( tie || ! m_ffProp[name+".Tau"]->subProperties().isEmpty() )
+  {
+    result->tie("Tau", m_ffProp[name+".Tau"]->valueText().toStdString());
+  }
+  if ( name.startsWith("Str") )
+  {
+    result->setParameter("Beta", m_ffDblMng->value(m_ffProp[name+".Beta"]));
+    if ( tie || ! m_ffProp[name+".Beta"]->subProperties().isEmpty() )
+    {
+      result->tie("Beta", m_ffProp[name+".Beta"]->valueText().toStdString());
+    }
+  }
+
+  return result;
+}
+
+Mantid::API::CompositeFunctionMW* IndirectDataAnalysis::confitCreateFunction(bool tie)
+{
+  Mantid::API::CompositeFunctionMW* conv = dynamic_cast<Mantid::API::CompositeFunctionMW*>(Mantid::API::FunctionFactory::Instance().createFunction("Convolution"));
+  Mantid::API::CompositeFunctionMW* result = new Mantid::API::CompositeFunctionMW();
+  Mantid::API::CompositeFunctionMW* comp;
+
+  bool singleFunction = false;
+
+  if ( m_uiForm.confit_cbFitType->currentText() == "Two Lorentzians" )
+  {
+    comp = new Mantid::API::CompositeFunctionMW();
+  }
+  else
+  {
+    comp = conv;
+    singleFunction = true;
+  }
+
+  int index = 0;
+
+  // 0 = Fixed Flat, 1 = Fit Flat, 2 = Fit all
+  const int bgType = m_uiForm.confit_cbBackground->currentIndex();
+
+  // 1 - CompositeFunction A
+  // - - 1 LinearBackground
+  // - - 2 Convolution Function
+  // - - - - 1 Resolution
+  // - - - - 2 CompositeFunction B
+  // - - - - - - DeltaFunction (yes/no)
+  // - - - - - - Lorentzian 1 (yes/no)
+  // - - - - - - Lorentzian 2 (yes/no)
+
+  Mantid::API::IFitFunction* func;
+
+  // Background
+  func = Mantid::API::FunctionFactory::Instance().createFunction("LinearBackground");
+  index = result->addFunction(func);
+  if ( tie  || bgType == 0 || ! m_cfProp["BGA0"]->subProperties().isEmpty() )
+  {
+    result->tie("f0.A0", m_cfProp["BGA0"]->valueText().toStdString() );
+  }
+  else
+  {
+    func->setParameter("A0", m_cfProp["BGA0"]->valueText().toDouble());
+  }
+
+  if ( bgType != 2 )
+  {
+    result->tie("f0.A1", "0.0");
+  }
+  else
+  {
+    if ( tie || ! m_cfProp["BGA1"]->subProperties().isEmpty() )
+    {
+      result->tie("f0.A1", m_cfProp["BGA1"]->valueText().toStdString() );
+    }
+    else { func->setParameter("A1", m_cfProp["BGA1"]->valueText().toDouble()); }
+  }
+
+  // Resolution
+  func = Mantid::API::FunctionFactory::Instance().createFunction("Resolution");
+  index = conv->addFunction(func);
+  std::string resfilename = m_uiForm.confit_resInput->getFirstFilename().toStdString();
+  Mantid::API::IFitFunction::Attribute attr(resfilename);
+  func->setAttribute("FileName", attr);
+
+  // Delta Function
+  if ( m_cfBlnMng->value(m_cfProp["UseDeltaFunc"]) )
+  {
+    func = Mantid::API::FunctionFactory::Instance().createFunction("DeltaFunction");
+    index = comp->addFunction(func);
+    if ( tie || ! m_cfProp["DeltaHeight"]->subProperties().isEmpty() )
+    {
+      comp->tie("f0.Height", m_cfProp["DeltaHeight"]->valueText().toStdString() );
+    }
+    else { func->setParameter("Height", m_cfProp["DeltaHeight"]->valueText().toDouble()); }
+  }
+
+  // Lorentzians
+  switch ( m_uiForm.confit_cbFitType->currentIndex() )
+  {
+  case 0: // No Lorentzians
+    break;
+  case 1: // 1 Lorentzian
+    func = Mantid::API::FunctionFactory::Instance().createFunction("Lorentzian");
+    index = comp->addFunction(func);
+    populateFunction(func, comp, m_cfProp["Lorentzian1"], index, tie);
+    break;
+  case 2: // 2 Lorentzian
+    func = Mantid::API::FunctionFactory::Instance().createFunction("Lorentzian");
+    index = comp->addFunction(func);
+    populateFunction(func, comp, m_cfProp["Lorentzian1"], index, tie);
+    func = Mantid::API::FunctionFactory::Instance().createFunction("Lorentzian");
+    index = comp->addFunction(func);
+    populateFunction(func, comp, m_cfProp["Lorentzian2"], index, tie);
+    // Tie PeakCentres together
+    if ( ! tie )
+    {
+      QString tieL = "f" + QString::number(index-1) + ".PeakCentre";
+      QString tieR = "f" + QString::number(index) + ".PeakCentre";
+      comp->tie(tieL.toStdString(), tieR.toStdString());
+    }
+    break;
+  }
+
+  if ( ! singleFunction )
+    conv->addFunction(comp);
+  result->addFunction(conv);
+
+  result->applyTies();
+
+  return result;
+}
+
+QtProperty* IndirectDataAnalysis::createLorentzian(const QString & name)
+{
+  QtProperty* lorentzGroup = m_cfGrpMng->addProperty(name);
+  m_cfProp[name+".Height"] = m_cfDblMng->addProperty("Height");
+  // m_cfDblMng->setRange(m_cfProp[name+".Height"], 0.0, 1.0); // 0 < Height < 1
+  m_cfProp[name+".PeakCentre"] = m_cfDblMng->addProperty("PeakCentre");
+  m_cfProp[name+".HWHM"] = m_cfDblMng->addProperty("HWHM");
+  m_cfDblMng->setDecimals(m_cfProp[name+".Height"], m_nDec);
+  m_cfDblMng->setDecimals(m_cfProp[name+".PeakCentre"], m_nDec);
+  m_cfDblMng->setDecimals(m_cfProp[name+".HWHM"], m_nDec);
+  m_cfDblMng->setValue(m_cfProp[name+".HWHM"], 0.02);
+  lorentzGroup->addSubProperty(m_cfProp[name+".Height"]);
+  lorentzGroup->addSubProperty(m_cfProp[name+".PeakCentre"]);
+  lorentzGroup->addSubProperty(m_cfProp[name+".HWHM"]);
+  return lorentzGroup;
+}
+
+QtProperty* IndirectDataAnalysis::createExponential(const QString & name)
+{
+  QtProperty* expGroup = m_groupManager->addProperty(name);
+  m_ffProp[name+".Intensity"] = m_ffDblMng->addProperty("Intensity");
+  m_ffDblMng->setRange(m_ffProp[name+".Intensity"], 0.0, 1.0);
+  m_ffDblMng->setDecimals(m_ffProp[name+".Intensity"], m_nDec);
+  m_ffProp[name+".Tau"] = m_ffDblMng->addProperty("Tau");
+  m_ffDblMng->setDecimals(m_ffProp[name+".Tau"], m_nDec);
+  expGroup->addSubProperty(m_ffProp[name+".Intensity"]);
+  expGroup->addSubProperty(m_ffProp[name+".Tau"]);
+  return expGroup;
+}
+
+QtProperty* IndirectDataAnalysis::createStretchedExp(const QString & name)
+{
+  QtProperty* prop = m_groupManager->addProperty(name);
+  m_ffProp[name+".Intensity"] = m_ffDblMng->addProperty("Intensity");
+  m_ffDblMng->setRange(m_ffProp[name+".Intensity"], 0.0, 1.0);
+  m_ffProp[name+".Tau"] = m_ffDblMng->addProperty("Tau");
+  m_ffProp[name+".Beta"] = m_ffDblMng->addProperty("Beta");
+  m_ffDblMng->setDecimals(m_ffProp[name+".Intensity"], m_nDec);
+  m_ffDblMng->setDecimals(m_ffProp[name+".Tau"], m_nDec);
+  m_ffDblMng->setDecimals(m_ffProp[name+".Beta"], m_nDec);
+  m_ffDblMng->setRange(m_ffProp[name+".Beta"], 0.0, 1.0);
+  prop->addSubProperty(m_ffProp[name+".Intensity"]);
+  prop->addSubProperty(m_ffProp[name+".Tau"]);
+  prop->addSubProperty(m_ffProp[name+".Beta"]);
+  return prop;
+}
+
+void IndirectDataAnalysis::populateFunction(Mantid::API::IFitFunction* func, Mantid::API::IFitFunction* comp, QtProperty* group, int index, bool tie)
+{
+  // Get subproperties of group and apply them as parameters on the function object
+  QList<QtProperty*> props = group->subProperties();
+  QString pref = "f" + QString::number(index) + ".";
+
+  for ( int i = 0; i < props.size(); i++ )
+  {
+    if ( tie || ! props[i]->subProperties().isEmpty() )
+    {
+      QString propName = pref + props[i]->propertyName();
+      comp->tie(propName.toStdString(), props[i]->valueText().toStdString() );
+    }
+    else
+    {
+      std::string propName = props[i]->propertyName().toStdString();
+      double propValue = props[i]->valueText().toDouble();
+      func->setParameter(propName, propValue);
+    }
+  }
+}
+
+QwtPlotCurve* IndirectDataAnalysis::plotMiniplot(QwtPlot* plot, QwtPlotCurve* curve, std::string workspace, int index)
+{
+  if ( curve != NULL )
+  {
+    curve->attach(0);
+    delete curve;
+    curve = 0;
+  }
+
+  Mantid::API::MatrixWorkspace_const_sptr ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(workspace));
+
+  int nhist = ws->getNumberHistograms();
+  if ( index >= nhist )
+  {
+    showInformationBox("Error: Workspace index out of range.");
+    return 0;
+  }
+
+  const QVector<double> dataX = QVector<double>::fromStdVector(ws->readX(index));
+  const QVector<double> dataY = QVector<double>::fromStdVector(ws->readY(index));
+
+  curve = new QwtPlotCurve();
+  curve->setData(dataX, dataY);
+  curve->attach(plot);
+
+  plot->replot();
+
+  return curve;
+}
+
+void IndirectDataAnalysis::run()
+{
+  QString tabName = m_uiForm.tabWidget->tabText(m_uiForm.tabWidget->currentIndex());
+
+  if ( tabName == "Elwin" )  { elwinRun(); }
+  else if ( tabName == "MSD Fit" ) { msdRun(); }
+  else if ( tabName == "Fury" ) { furyRun(); }
+  else if ( tabName == "FuryFit" ) { furyfitRun(); }
+  else if ( tabName == "ConvFit" ) { confitRun(); }
+  else if ( tabName == "Absorption" ) { absorptionRun(); }
+  else if ( tabName == "Abs (F2PY)" ) { absf2pRun(); }
+  else if ( tabName == "Apply Corrections" ) { abscorRun(); }
+  else { showInformationBox("This tab does not have a 'Run' action."); }
+}
+
+void IndirectDataAnalysis::fitContextMenu(const QPoint &)
+{
+  QtBrowserItem* item;
+  QtDoublePropertyManager* dblMng;
+  
+  int pageNo = m_uiForm.tabWidget->currentIndex();
+  if ( pageNo == 3 )
+  { // FuryFit
+    item = m_ffTree->currentItem();
+    dblMng = m_ffDblMng;
+  }
+  else if ( pageNo == 4 )
+  { // Convolution Fit
+    item = m_cfTree->currentItem();
+    dblMng = m_cfDblMng;
+  }
+
+  if ( ! item )
+  {
+    return;
+  }
+
+  // is it a fit property ?
+  QtProperty* prop = item->property();
+  if ( prop->propertyManager() != dblMng )
+  {
+    return;
+  }
+
+  if ( pageNo == 4 && ( prop == m_cfProp["StartX"] || prop == m_cfProp["EndX"] ) )
+  {
+    return;
+  }
+
+  // is it already fixed?
+  QList<QtProperty*> subProps = prop->subProperties();
+  bool fixed = ! subProps.isEmpty();
+
+  // Create the menu
+  QMenu* menu = new QMenu("FuryFit", m_ffTree);
+  QAction* action;
+
+  if ( ! fixed )
+  {
+    action = new QAction("Fix", this);
+    connect(action, SIGNAL(triggered()), this, SLOT(fixItem()));
+  }
+  else
+  {
+    action = new QAction("Remove Fix", this);
+    connect(action, SIGNAL(triggered()), this, SLOT(unFixItem()));
+  }
+
+  menu->addAction(action);
+
+  // Show the menu
+  menu->popup(QCursor::pos());
+}
+
+void IndirectDataAnalysis::fixItem()
+{
+  int pageNo = m_uiForm.tabWidget->currentIndex();
+
+  QtBrowserItem* item;
+  if ( pageNo == 3 )
+  { // FuryFit
+    item = m_ffTree->currentItem();
+  }
+  else if ( pageNo == 4 )
+  { // Convolution Fit
+    item = m_cfTree->currentItem();
+  }
+
+  // Determine what the property is.
+  QtProperty* prop = item->property();
+
+  QtProperty* fixedProp = m_stringManager->addProperty("Fixed:");
+  m_stringManager->setValue(fixedProp, prop->valueText());
+  prop->addSubProperty(fixedProp);
+
+  fixedProp->setEnabled(false);
+  prop->setEnabled(false);
+  
+}
+
+void IndirectDataAnalysis::unFixItem()
+{
+  QtBrowserItem* item;
+  QtDoublePropertyManager* dblMng;
+  
+  int pageNo = m_uiForm.tabWidget->currentIndex();
+  if ( pageNo == 3 )
+  { // FuryFit
+    item = m_ffTree->currentItem();
+    dblMng = m_ffDblMng;
+  }
+  else if ( pageNo == 4 )
+  { // Convolution Fit
+    item = m_cfTree->currentItem();
+    dblMng = m_cfDblMng;
+  }
+
+  QtProperty* prop = item->property();
+  prop->subProperties().isEmpty();
+  QList<QtProperty*> subProps = prop->subProperties();
+
+  for ( QList<QtProperty*>::iterator it = subProps.begin(); it != subProps.end(); ++it )
+  {
+    if ( (*it)->propertyManager() != dblMng ) { delete (*it); }
+  }
+
+  prop->setEnabled(true);
+}
+
+void IndirectDataAnalysis::elwinRun()
+{
+  if ( ! validateElwin() )
+  {
+    showInformationBox("Please check your input.");
+    return;
+  }
+
+  QString pyInput =
+    "from IndirectDataAnalysis import elwin\n"
+    "input = [r'" + m_uiForm.elwin_inputFile->getFilenames().join("', r'") + "']\n"
+    "eRange = [ " + QString::number(m_elwDblMng->value(m_elwProp["R1S"])) +","+ QString::number(m_elwDblMng->value(m_elwProp["R1E"]));
+
+  if ( m_elwBlnMng->value(m_elwProp["UseTwoRanges"]) )
+  {
+    pyInput += ", " + QString::number(m_elwDblMng->value(m_elwProp["R2S"])) + ", " + QString::number(m_elwDblMng->value(m_elwProp["R2E"]));
+  }
+
+  pyInput+= "]\n";
+
+  if ( m_uiForm.elwin_ckVerbose->isChecked() ) pyInput += "verbose = True\n";
+  else pyInput += "verbose = False\n";
+
+  if ( m_uiForm.elwin_ckPlot->isChecked() ) pyInput += "plot = True\n";
+  else pyInput += "plot = False\n";
+
+  if ( m_uiForm.elwin_ckSave->isChecked() ) pyInput += "save = True\n";
+  else pyInput += "save = False\n";
+
+  pyInput +=
+    "eq1_ws, eq2_ws = elwin(input, eRange, Save=save, Verbose=verbose, Plot=plot)\n";
+
+  if ( m_uiForm.elwin_ckConcat->isChecked() )
+  {
+    pyInput += "from IndirectDataAnalysis import concatWSs\n"
+      "concatWSs(eq1_ws, 'MomentumTransfer', 'ElwinQResults')\n"
+      "concatWSs(eq2_ws, 'QSquared', 'ElwinQSqResults')\n";
+  }
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+
+}
+
+void IndirectDataAnalysis::elwinPlotInput()
+{
+  if ( m_uiForm.elwin_inputFile->isValid() )
+  {
+    QString filename = m_uiForm.elwin_inputFile->getFirstFilename();
+    QFileInfo fi(filename);
+    QString wsname = fi.baseName();
+
+    QString pyInput = "LoadNexus(r'" + filename + "', '" + wsname + "')\n";
+    QString pyOutput = runPythonCode(pyInput);
+
+    std::string workspace = wsname.toStdString();
+
+    m_elwDataCurve = plotMiniplot(m_elwPlot, m_elwDataCurve, workspace, 0);
+    
+    int npts = m_elwDataCurve->data().size();
+    double lower = m_elwDataCurve->data().x(0);
+    double upper = m_elwDataCurve->data().x(npts-1);
+    
+    m_elwR1->setRange(lower, upper);
+
+    // Replot
+    m_elwPlot->replot();
+  }
+  else
+  {
+    showInformationBox("Selected input files are invalid.");
+  }
+}
+
+void IndirectDataAnalysis::elwinTwoRanges(QtProperty*, bool val)
+{
+  m_elwR2->setVisible(val);
+}
+
+void IndirectDataAnalysis::elwinMinChanged(double val)
+{
+  MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
+  if ( from == m_elwR1 )
+  {
+    m_elwDblMng->setValue(m_elwProp["R1S"], val);
+  }
+  else if ( from == m_elwR2 )
+  {
+    m_elwDblMng->setValue(m_elwProp["R2S"], val);
+  }
+}
+
+void IndirectDataAnalysis::elwinMaxChanged(double val)
+{
+  MantidWidgets::RangeSelector* from = qobject_cast<MantidWidgets::RangeSelector*>(sender());
+  if ( from == m_elwR1 )
+  {
+    m_elwDblMng->setValue(m_elwProp["R1E"], val);
+  }
+  else if ( from == m_elwR2 )
+  {
+    m_elwDblMng->setValue(m_elwProp["R2E"], val);
+  }
+}
+
+void IndirectDataAnalysis::elwinUpdateRS(QtProperty* prop, double val)
+{
+  if ( prop == m_elwProp["R1S"] ) m_elwR1->setMinimum(val);
+  else if ( prop == m_elwProp["R1E"] ) m_elwR1->setMaximum(val);
+  else if ( prop == m_elwProp["R2S"] ) m_elwR2->setMinimum(val);
+  else if ( prop == m_elwProp["R2E"] ) m_elwR2->setMaximum(val);
+}
+
+void IndirectDataAnalysis::msdRun()
+{
+  if ( ! validateMsd() )
+  {
+    showInformationBox("Please check your input.");
+    return;
+  }
+
+  QString pyInput =
+    "from IndirectDataAnalysis import msdfit\n"
+    "startX = " + QString::number(m_msdDblMng->value(m_msdProp["Start"])) +"\n"
+    "endX = " + QString::number(m_msdDblMng->value(m_msdProp["End"])) +"\n"
+    "inputs = [r'" + m_uiForm.msd_inputFile->getFilenames().join("', r'") + "']\n";
+
+  if ( m_uiForm.msd_ckVerbose->isChecked() ) pyInput += "verbose = True\n";
+  else pyInput += "verbose = False\n";
+
+  if ( m_uiForm.msd_ckPlot->isChecked() ) pyInput += "plot = True\n";
+  else pyInput += "plot = False\n";
+
+  if ( m_uiForm.msd_ckSave->isChecked() ) pyInput += "save = True\n";
+  else pyInput += "save = False\n";
+
+  pyInput +=
+    "msdfit(inputs, startX, endX, Save=save, Verbose=verbose, Plot=plot)\n";
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+
+
+}
+
+void IndirectDataAnalysis::msdPlotInput()
+{
+  if ( m_uiForm.msd_inputFile->isValid() )
+  {
+    QString filename = m_uiForm.msd_inputFile->getFirstFilename();
+    QFileInfo fi(filename);
+    QString wsname = fi.baseName();
+
+    QString pyInput = "LoadNexus(r'" + filename + "', '" + wsname + "')\n";
+    QString pyOutput = runPythonCode(pyInput);
+
+    std::string workspace = wsname.toStdString();
+
+    m_msdDataCurve = plotMiniplot(m_msdPlot, m_msdDataCurve, workspace, 0);
+    int npnts = m_msdDataCurve->data().size();
+    double lower = m_msdDataCurve->data().x(0);
+    double upper = m_msdDataCurve->data().x(npnts-1);
+
+    m_msdRange->setRange(lower, upper);
+
+    // Replot
+    m_msdPlot->replot();
+  }
+  else
+  {
+    showInformationBox("Selected input files are invalid.");
+  }
+}
+
+void IndirectDataAnalysis::msdMinChanged(double val)
+{
+  m_msdDblMng->setValue(m_msdProp["Start"], val);
+}
+
+void IndirectDataAnalysis::msdMaxChanged(double val)
+{
+  m_msdDblMng->setValue(m_msdProp["End"], val);
+}
+
+void IndirectDataAnalysis::msdUpdateRS(QtProperty* prop, double val)
+{
+  if ( prop == m_msdProp["Start"] ) m_msdRange->setMinimum(val);
+  else if ( prop == m_msdProp["End"] ) m_msdRange->setMaximum(val);
+}
+
+void IndirectDataAnalysis::furyRun()
+{
+  if ( !validateFury() )
+  {
+    showInformationBox("Please check your input.");
+    return;
+  }
+
+  QString filenames;
+  switch ( m_uiForm.fury_cbInputType->currentIndex() )
+  {
+  case 0:
+    filenames = m_uiForm.fury_iconFile->getFilenames().join("', r'");
+    break;
+  case 1:
+    filenames = m_uiForm.fury_wsSample->currentText();
+    break;
+  }
+
+  QString pyInput =
+    "from IndirectDataAnalysis import fury\n"
+    "samples = [r'" + filenames + "']\n"
+    "resolution = r'" + m_uiForm.fury_resFile->getFirstFilename() + "'\n"
+    "rebin = '" + m_furProp["ELow"]->valueText() +","+ m_furProp["EWidth"]->valueText() +","+m_furProp["EHigh"]->valueText()+"'\n";
+
+  if ( m_uiForm.fury_ckVerbose->isChecked() ) pyInput += "verbose = True\n";
+  else pyInput += "verbose = False\n";
+
+  if ( m_uiForm.fury_ckPlot->isChecked() ) pyInput += "plot = True\n";
+  else pyInput += "plot = False\n";
+
+  if ( m_uiForm.fury_ckSave->isChecked() ) pyInput += "save = True\n";
+  else pyInput += "save = False\n";
+
+  pyInput +=
+    "fury_ws = fury(samples, resolution, rebin, Save=save, Verbose=verbose, Plot=plot)\n";
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+}
+
+void IndirectDataAnalysis::furyResType(const QString& type)
+{
+  QStringList exts;
+  if ( type == "RES File" )
+  {
+    exts.append("_res.nxs");
+    m_furyResFileType = true;
+  }
+  else
+  {
+    exts.append("_red.nxs");
+    m_furyResFileType = false;
+  }
+  m_uiForm.fury_resFile->setFileExtensions(exts);
+}
+
+void IndirectDataAnalysis::furyPlotInput()
+{
+  std::string workspace;
+  if ( m_uiForm.fury_cbInputType->currentIndex() == 0 )
+  {
+    if ( m_uiForm.fury_iconFile->isValid() )
+    {
+      QString filename = m_uiForm.fury_iconFile->getFirstFilename();
+      QFileInfo fi(filename);
+      QString wsname = fi.baseName();
+
+      QString pyInput = "LoadNexus(r'" + filename + "', '" + wsname + "')\n";
+      QString pyOutput = runPythonCode(pyInput);
+
+      workspace = wsname.toStdString();
+    }
+    else
+    {
+      showInformationBox("Selected input files are invalid.");
+      return;
+    }
+  }
+  else if ( m_uiForm.fury_cbInputType->currentIndex() == 1 )
+  {
+    workspace = m_uiForm.fury_wsSample->currentText().toStdString();
+    if ( workspace.empty() )
+    {
+      showInformationBox("No workspace selected.");
+      return;
+    }
+  }
+
+  m_furCurve = plotMiniplot(m_furPlot, m_furCurve, workspace, 0);
+  int npnts = m_furCurve->data().size();
+  double lower = m_furCurve->data().x(0);
+  double upper = m_furCurve->data().x(npnts-1);
+
+  m_furRange->setRange(lower, upper);
+
+  m_furPlot->replot();
+
+}
+
+void IndirectDataAnalysis::furyMaxChanged(double val)
+{
+  m_furDblMng->setValue(m_furProp["EHigh"], val);
+}
+
+void IndirectDataAnalysis::furyMinChanged(double val)
+{
+  m_furDblMng->setValue(m_furProp["ELow"], val);
+}
+
+void IndirectDataAnalysis::furyUpdateRS(QtProperty* prop, double val)
+{
+  if ( prop == m_furProp["ELow"] )
+    m_furRange->setMinimum(val);
+  else if ( prop == m_furProp["EHigh"] )
+    m_furRange->setMaximum(val);
+}
+
+void IndirectDataAnalysis::furyfitRun()
+{
+  // First create the function
+  Mantid::API::CompositeFunctionMW* function = furyfitCreateFunction();
+
+  m_uiForm.furyfit_ckPlotGuess->setChecked(false);
+  
+  const int fitType = m_uiForm.furyfit_cbFitType->currentIndex();
+
+  if ( m_uiForm.furyfit_ckConstrainIntensities->isChecked() )
+  {
+    switch ( fitType )
+    {
+    case 0: // 1 Exp
+    case 2: // 1 Str
+      m_furyfitTies = "f1.Intensity = 1-f0.A0";
+      break;
+    case 1: // 2 Exp
+    case 3: // 1 Exp & 1 Str
+      m_furyfitTies = "f1.Intensity=1-f2.Intensity-f0.A0";
+      break;
+    default:
+      break;
+    }
+  }
+
+  furyfitPlotInput();
+  if ( m_ffInputWS == NULL )
+  {
+    return;
+  }
+
+  std::string output = m_ffInputWSName + "_fit_s" + m_uiForm.furyfit_leSpecNo->text().toStdString();
+  // Create the Fit Algorithm
+  Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("Fit");
+  alg->initialize();
+  alg->setPropertyValue("InputWorkspace", m_ffInputWSName);
+  alg->setProperty("WorkspaceIndex", m_uiForm.furyfit_leSpecNo->text().toInt());
+  alg->setProperty("StartX", m_ffRangeManager->value(m_ffProp["StartX"]));
+  alg->setProperty("EndX", m_ffRangeManager->value(m_ffProp["EndX"]));
+  alg->setProperty("Ties", m_furyfitTies.toStdString());
+  alg->setPropertyValue("Function", *function);
+  alg->setPropertyValue("Output",output);
+  alg->execute();
+
+  if ( ! alg->isExecuted() )
+  {
+    QString msg = "There was an error executing the fitting algorithm. Please see the "
+      "Results Log pane for more details.";
+    showInformationBox(msg);
+    return;
+  }
+
+  // Now show the fitted curve of the mini plot
+  m_ffFitCurve = plotMiniplot(m_ffPlot, m_ffFitCurve, output+"_Workspace", 1);
+  QPen fitPen(Qt::red, Qt::SolidLine);
+  m_ffFitCurve->setPen(fitPen);
+  m_ffPlot->replot();
+
+  // Do it as we do in Convolution Fit tab
+  QMap<QString,double> parameters;
+  QStringList parNames = QString::fromStdString(alg->getPropertyValue("ParameterNames")).split(",", QString::SkipEmptyParts);
+  QStringList parVals = QString::fromStdString(alg->getPropertyValue("Parameters")).split(",", QString::SkipEmptyParts);
+  for ( int i = 0; i < parNames.size(); i++ )
+  {
+    parameters[parNames[i]] = parVals[i].toDouble();
+  }
+
+  m_ffRangeManager->setValue(m_ffProp["BackgroundA0"], parameters["f0.A0"]);
+  
+  if ( fitType != 2 )
+  {
+    // Exp 1
+    m_ffDblMng->setValue(m_ffProp["Exponential 1.Intensity"], parameters["f1.Intensity"]);
+    m_ffDblMng->setValue(m_ffProp["Exponential 1.Tau"], parameters["f1.Tau"]);
+    
+    if ( fitType == 1 )
+    {
+      // Exp 2
+      m_ffDblMng->setValue(m_ffProp["Exponential 2.Intensity"], parameters["f2.Intensity"]);
+      m_ffDblMng->setValue(m_ffProp["Exponential 2.Tau"], parameters["f2.Tau"]);
+    }
+  }
+  
+  if ( fitType > 1 )
+  {
+    // Str
+    QString fval;
+    if ( fitType == 2 ) { fval = "f1."; }
+    else { fval = "f2."; }
+    
+    m_ffDblMng->setValue(m_ffProp["Stretched Exponential.Intensity"], parameters[fval+"Intensity"]);
+    m_ffDblMng->setValue(m_ffProp["Stretched Exponential.Tau"], parameters[fval+"Tau"]);
+    m_ffDblMng->setValue(m_ffProp["Stretched Exponential.Beta"], parameters[fval+"Beta"]);
+  }
+
+  if ( m_uiForm.furyfit_ckPlotOutput->isChecked() )
+  {
+    QString pyInput = "from mantidplot import *\n"
+      "plotSpectrum('" + QString::fromStdString(output) + "_Workspace', [0,1,2])\n";
+    QString pyOutput = runPythonCode(pyInput);
+  }
+}
+
+void IndirectDataAnalysis::furyfitTypeSelection(int index)
+{
+  m_ffTree->clear();
+
+  m_ffTree->addProperty(m_ffProp["StartX"]);
+  m_ffTree->addProperty(m_ffProp["EndX"]);
+
+  m_ffTree->addProperty(m_ffProp["LinearBackground"]);
+
+  switch ( index )
+  {
+  case 0:
+    m_ffTree->addProperty(m_ffProp["Exponential1"]);
+    break;
+  case 1:
+    m_ffTree->addProperty(m_ffProp["Exponential1"]);
+    m_ffTree->addProperty(m_ffProp["Exponential2"]);
+    break;
+  case 2:
+    m_ffTree->addProperty(m_ffProp["StretchedExp"]);
+    break;
+  case 3:
+    m_ffTree->addProperty(m_ffProp["Exponential1"]);
+    m_ffTree->addProperty(m_ffProp["StretchedExp"]);
+    break;
+  }
+}
+
+void IndirectDataAnalysis::furyfitPlotInput()
+{
+  std::string wsname;
+
+  switch ( m_uiForm.furyfit_cbInputType->currentIndex() )
+  {
+  case 0: // "File"
+    {
+      if ( ! m_uiForm.furyfit_inputFile->isValid() )
+      {
+        return;
+      }
+      else
+      {
+      QFileInfo fi(m_uiForm.furyfit_inputFile->getFirstFilename());
+      wsname = fi.baseName().toStdString();
+      if ( (m_ffInputWS == NULL) || ( wsname != m_ffInputWSName ) )
+      {
+        std::string filename = m_uiForm.furyfit_inputFile->getFirstFilename().toStdString();
+        // LoadNexus
+        Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("LoadNexus");
+        alg->initialize();
+        alg->setPropertyValue("Filename", filename);
+        alg->setPropertyValue("OutputWorkspace",wsname);
+        alg->execute();
+        // get the output workspace
+        m_ffInputWS = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsname));
+      }
+      }
+    }
+    break;
+  case 1: // Workspace
+    {
+      wsname = m_uiForm.furyfit_wsIqt->currentText().toStdString();
+      try
+      {
+        m_ffInputWS = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsname));
+      }
+      catch ( Mantid::Kernel::Exception::NotFoundError & )
+      {
+        QString msg = "Workspace: '" + QString::fromStdString(wsname) + "' could not be "
+          "found in the Analysis Data Service.";
+        showInformationBox(msg);
+        return;
+      }
+    }
+    break;
+  }
+  m_ffInputWSName = wsname;
+
+  int specNo = m_uiForm.furyfit_leSpecNo->text().toInt();
+
+  m_ffDataCurve = plotMiniplot(m_ffPlot, m_ffDataCurve, m_ffInputWSName, specNo);
+
+  int nopnts =  m_ffDataCurve->data().size();
+  double lower = m_ffDataCurve->data().x(0);
+  double upper = m_ffDataCurve->data().x(nopnts-1);
+
+  m_ffRangeS->setRange(lower, upper);
+  m_ffRangeManager->setRange(m_ffProp["StartX"], lower, upper);
+  m_ffRangeManager->setRange(m_ffProp["EndX"], lower, upper);
+
+  m_ffPlot->setAxisScale(QwtPlot::xBottom, lower, upper);
+  m_ffPlot->setAxisScale(QwtPlot::yLeft, 0.0, 1.0);
+  m_ffPlot->replot();
+}
+
+void IndirectDataAnalysis::furyfitXMinSelected(double val)
+{
+  m_ffRangeManager->setValue(m_ffProp["StartX"], val);
+}
+
+void IndirectDataAnalysis::furyfitXMaxSelected(double val)
+{
+  m_ffRangeManager->setValue(m_ffProp["EndX"], val);
+}
+
+void IndirectDataAnalysis::furyfitBackgroundSelected(double val)
+{
+  m_ffRangeManager->setValue(m_ffProp["BackgroundA0"], val);
+}
+
+void IndirectDataAnalysis::furyfitRangePropChanged(QtProperty* prop, double val)
+{
+  if ( prop == m_ffProp["StartX"] )
+  {
+    m_ffRangeS->setMinimum(val);
+  }
+  else if ( prop == m_ffProp["EndX"] )
+  {
+    m_ffRangeS->setMaximum(val);
+  }
+  else if ( prop == m_ffProp["BackgroundA0"] )
+  {
+    m_ffBackRangeS->setMinimum(val);
+  }
+}
+
+void IndirectDataAnalysis::furyfitSequential()
+{
+  furyfitPlotInput();
+  if ( m_ffInputWS == NULL )
+  {
+    return;
+  }
+
+  Mantid::API::CompositeFunction* func = furyfitCreateFunction();
+
+  // Function Ties
+  func->tie("f0.A1", "0");
+  if ( m_uiForm.furyfit_ckConstrainIntensities->isChecked() )
+  {
+    switch ( m_uiForm.furyfit_cbFitType->currentIndex() )
+    {
+    case 0: // 1 Exp
+    case 2: // 1 Str
+      func->tie("f1.Intensity","1-f0.A0");
+      break;
+    case 1: // 2 Exp
+    case 3: // 1 Exp & 1 Str
+      func->tie("f1.Intensity","1-f2.Intensity-f0.A0");
+      break;
+    }
+  }
+
+  std::string function = std::string(*func);
+  
+  QString pyInput = "from IndirectDataAnalysis import furyfitSeq\n"
+    "input = '" + QString::fromStdString(m_ffInputWSName) + "'\n"
+    "func = r'" + QString::fromStdString(function) + "'\n"
+    "startx = " + m_ffProp["StartX"]->valueText() + "\n"
+    "endx = " + m_ffProp["EndX"]->valueText() + "\n"
+    "plot = '" + m_uiForm.furyfit_cbPlotOutput->currentText() + "'\n"
+    "save = ";
+  pyInput += m_uiForm.furyfit_ckSaveSeq->isChecked() ? "True\n" : "False\n";
+  pyInput += "furyfitSeq(input, func, startx, endx, save, plot)\n";
+  
+  QString pyOutput = runPythonCode(pyInput);
+}
+
+void IndirectDataAnalysis::furyfitPlotGuess(QtProperty*)
+{
+  if ( ! m_uiForm.furyfit_ckPlotGuess->isChecked() || m_ffDataCurve == NULL )
+  {
+    return;
+  }
+
+  Mantid::API::CompositeFunctionMW* function = furyfitCreateFunction(true);
+
+  // Create the double* array from the input workspace
+  int binIndxLow = m_ffInputWS->binIndexOf(m_ffRangeManager->value(m_ffProp["StartX"]));
+  int binIndxHigh = m_ffInputWS->binIndexOf(m_ffRangeManager->value(m_ffProp["EndX"]));
+  const int nData = binIndxHigh - binIndxLow;
+
+  double* inputXData = new double[nData];
+  double* outputData = new double[nData];
+
+  const Mantid::MantidVec& XValues = m_ffInputWS->readX(0);
+
+  const bool isHistogram = m_ffInputWS->isHistogramData();
+
+  for ( int i = 0; i < nData ; i++ )
+  {
+    if ( isHistogram )
+      inputXData[i] = 0.5*(XValues[binIndxLow+i]+XValues[binIndxLow+i+1]);
+    else
+      inputXData[i] = XValues[binIndxLow+i];
+  }
+
+  function->function(outputData, inputXData, nData);
+
+  QVector<double> dataX;
+  QVector<double> dataY;
+
+  for ( int i = 0; i < nData; i++ )
+  {
+    dataX.append(inputXData[i]);
+    dataY.append(outputData[i]);
+  }
+
+  // Create the curve
+  if ( m_ffFitCurve != NULL )
+  {
+    m_ffFitCurve->attach(0);
+    delete m_ffFitCurve;
+    m_ffFitCurve = 0;
+  }
+
+  m_ffFitCurve = new QwtPlotCurve();
+  m_ffFitCurve->setData(dataX, dataY);
+  m_ffFitCurve->attach(m_ffPlot);
+  QPen fitPen(Qt::red, Qt::SolidLine);
+  m_ffFitCurve->setPen(fitPen);
+  m_ffPlot->replot();
+}
+
+void IndirectDataAnalysis::confitRun()
+{
+  confitPlotInput();
+
+  if ( m_cfDataCurve == NULL )
+  {
+    showInformationBox("Input invalid");
+    return;
+  }
+
+  m_uiForm.confit_ckPlotGuess->setChecked(false);
+
+  Mantid::API::CompositeFunction* function = confitCreateFunction();
+  std::string output = m_cfInputWSName + "_convfit_s" + m_uiForm.confit_leSpecNo->text().toStdString();
+
+  Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("Fit");
+  alg->initialize();
+  alg->setPropertyValue("InputWorkspace", m_cfInputWSName);
+  alg->setProperty<int>("WorkspaceIndex", m_uiForm.confit_leSpecNo->text().toInt());
+  alg->setProperty<double>("StartX", m_cfDblMng->value(m_cfProp["StartX"]));
+  alg->setProperty<double>("EndX", m_cfDblMng->value(m_cfProp["EndX"]));
+  alg->setPropertyValue("Function", *function);
+  alg->setPropertyValue("Output", output);
+  alg->execute();
+
+  if ( ! alg->isExecuted() )
+  {
+    showInformationBox("Fit algorithm failed.");
+    return;
+  }
+
+  // Plot the line on the mini plot
+  m_cfCalcCurve = plotMiniplot(m_cfPlot, m_cfCalcCurve, output+"_Workspace", 1);
+  QPen fitPen(Qt::red, Qt::SolidLine);
+  m_cfCalcCurve->setPen(fitPen);
+  m_cfPlot->replot();
+
+  // Update parameter values (possibly easier from algorithm properties)
+  QMap<QString,double> parameters;
+  QStringList parNames = QString::fromStdString(alg->getPropertyValue("ParameterNames")).split(",", QString::SkipEmptyParts);
+  QStringList parVals = QString::fromStdString(alg->getPropertyValue("Parameters")).split(",", QString::SkipEmptyParts);
+  for ( int i = 0; i < parNames.size(); i++ )
+  {
+    parameters[parNames[i]] = parVals[i].toDouble();
+  }
+
+  // Populate Tree widget with values
+  // Background should always be f0
+  m_cfDblMng->setValue(m_cfProp["BGA0"], parameters["f0.A0"]);
+  m_cfDblMng->setValue(m_cfProp["BGA1"], parameters["f0.A1"]);
+
+  int noLorentz = m_uiForm.confit_cbFitType->currentIndex();
+
+  int funcIndex = 1;
+  QString prefBase = "f1.f";
+  if ( noLorentz > 1 || ( noLorentz > 0 && m_cfBlnMng->value(m_cfProp["UseDeltaFunc"]) ) )
+  {
+    prefBase += "1.f";
+    funcIndex--;
+  }
+
+  if ( m_cfBlnMng->value(m_cfProp["UseDeltaFunc"]) )
+  {
+    QString key = prefBase+QString::number(funcIndex)+".Height";
+    m_cfDblMng->setValue(m_cfProp["DeltaHeight"], parameters[key]);
+    funcIndex++;
+  }
+
+  if ( noLorentz > 0 )
+  {
+    // One Lorentz
+    QString pref = prefBase + QString::number(funcIndex) + ".";
+    m_cfDblMng->setValue(m_cfProp["Lorentzian 1.Height"], parameters[pref+"Height"]);
+    m_cfDblMng->setValue(m_cfProp["Lorentzian 1.PeakCentre"], parameters[pref+"PeakCentre"]);
+    m_cfDblMng->setValue(m_cfProp["Lorentzian 1.HWHM"], parameters[pref+"HWHM"]);
+    funcIndex++;
+  }
+
+  if ( noLorentz > 1 )
+  {
+    // Two Lorentz
+    QString pref = prefBase + QString::number(funcIndex) + ".";
+    m_cfDblMng->setValue(m_cfProp["Lorentzian 2.Height"], parameters[pref+"Height"]);
+    m_cfDblMng->setValue(m_cfProp["Lorentzian 2.PeakCentre"], parameters[pref+"PeakCentre"]);
+    m_cfDblMng->setValue(m_cfProp["Lorentzian 2.HWHM"], parameters[pref+"HWHM"]);
+  }
+
+  // Plot Output
+  if ( m_uiForm.confit_ckPlotOutput->isChecked() )
+  {
+    QString pyInput =
+      "plotSpectrum('" + QString::fromStdString(output) + "_Workspace', [0,1,2])\n";
+    QString pyOutput = runPythonCode(pyInput);
+  }
+
+}
+
+void IndirectDataAnalysis::confitTypeSelection(int index)
+{
+  m_cfTree->removeProperty(m_cfProp["Lorentzian1"]);
+  m_cfTree->removeProperty(m_cfProp["Lorentzian2"]);
+  
+  switch ( index )
+  {
+  case 0:
+    m_cfHwhmRange->setVisible(false);
+    break;
+  case 1:
+    m_cfTree->addProperty(m_cfProp["Lorentzian1"]);
+    m_cfHwhmRange->setVisible(true);
+    break;
+  case 2:
+    m_cfTree->addProperty(m_cfProp["Lorentzian1"]);
+    m_cfTree->addProperty(m_cfProp["Lorentzian2"]);
+    m_cfHwhmRange->setVisible(true);
+    break;
+  }    
+}
+
+void IndirectDataAnalysis::confitBgTypeSelection(int index)
+{
+  if ( index == 2 )
+  {
+    m_cfProp["LinearBackground"]->addSubProperty(m_cfProp["BGA1"]);
+  }
+  else
+  {
+    m_cfProp["LinearBackground"]->removeSubProperty(m_cfProp["BGA1"]);
+  }
+}
+
+void IndirectDataAnalysis::confitPlotInput()
+{
+  std::string wsname;
+  const bool plotGuess = m_uiForm.confit_ckPlotGuess->isChecked();
+  m_uiForm.confit_ckPlotGuess->setChecked(false);
+
+  switch ( m_uiForm.confit_cbInputType->currentIndex() )
+  {
+  case 0: // "File"
+    {
+      if ( m_uiForm.confit_inputFile->isValid() )
+      {
+        QFileInfo fi(m_uiForm.confit_inputFile->getFirstFilename());
+        wsname = fi.baseName().toStdString();
+        if ( (m_ffInputWS == NULL) || ( wsname != m_ffInputWSName ) )
+        {
+          std::string filename = m_uiForm.confit_inputFile->getFirstFilename().toStdString();
+          Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("LoadNexus");
+          alg->initialize();
+          alg->setPropertyValue("Filename", filename);
+          alg->setPropertyValue("OutputWorkspace",wsname);
+          alg->execute();
+          m_cfInputWS = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsname));
+        }
+      }
+      else
+      {
+        return;
+      }
+    }
+    break;
+  case 1: // Workspace
+    {
+      wsname = m_uiForm.confit_wsSample->currentText().toStdString();
+      try
+      {
+        m_cfInputWS = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(wsname));
+      }
+      catch ( Mantid::Kernel::Exception::NotFoundError & )
+      {
+        QString msg = "Workspace: '" + QString::fromStdString(wsname) + "' could not be "
+          "found in the Analysis Data Service.";
+        showInformationBox(msg);
+        return;
+      }
+    }
+    break;
+  }
+  m_cfInputWSName = wsname;
+
+  int specNo = m_uiForm.confit_leSpecNo->text().toInt();
+  // Set spectra max value
+  int specMax = m_cfInputWS->getNumberHistograms() - 1;
+  if ( specNo < 0 || specNo > specMax )
+  {
+    m_uiForm.confit_leSpecNo->setText("0");
+    specNo = 0;
+  }
+  int smCurrent = m_uiForm.confit_leSpecMax->text().toInt();
+  if ( smCurrent < 0 || smCurrent > specMax )
+    m_uiForm.confit_leSpecMax->setText(QString::number(specMax));
+
+  m_cfDataCurve = plotMiniplot(m_cfPlot, m_cfDataCurve, wsname, specNo);
+  int npnts = m_cfDataCurve->data().size();
+  const double & lower = m_cfDataCurve->data().x(0);
+  const double & upper = m_cfDataCurve->data().x(npnts-1);
+  m_cfRangeS->setRange(lower, upper);
+
+  m_uiForm.confit_ckPlotGuess->setChecked(plotGuess);
+}
+
+void IndirectDataAnalysis::confitPlotGuess(QtProperty*)
+{
+
+  if ( ! m_uiForm.confit_ckPlotGuess->isChecked() || m_cfDataCurve == NULL )
+  {
+    return;
+  }
+
+  Mantid::API::CompositeFunctionMW* function = confitCreateFunction(true);
+
+  if ( m_cfInputWS == NULL )
+  {
+    confitPlotInput();
+  }
+
+  std::string inputName = m_cfInputWS->getName();
+
+  const int binIndexLow = m_cfInputWS->binIndexOf(m_cfDblMng->value(m_cfProp["StartX"]));
+  const int binIndexHigh = m_cfInputWS->binIndexOf(m_cfDblMng->value(m_cfProp["EndX"]));
+  const int nData = binIndexHigh - binIndexLow;
+
+  double* inputXData = new double[nData];
+  double* outputData = new double[nData];
+
+  const Mantid::MantidVec& XValues = m_cfInputWS->readX(0);
+  const bool isHistogram = m_cfInputWS->isHistogramData();
+
+  for ( int i = 0; i < nData; i++ )
+  {
+    if ( isHistogram )
+    {
+      inputXData[i] = 0.5 * ( XValues[binIndexLow+i] + XValues[binIndexLow+i+1] );
+    }
+    else
+    {
+      inputXData[i] = XValues[binIndexLow+i];
+    }
+  }
+
+  function->function(outputData, inputXData, nData);
+
+  QVector<double> dataX, dataY;
+
+  for ( int i = 0; i < nData; i++ )
+  {
+    dataX.append(inputXData[i]);
+    dataY.append(outputData[i]);
+  }
+
+  if ( m_cfCalcCurve != NULL )
+  {
+    m_cfCalcCurve->attach(0);
+    delete m_cfCalcCurve;
+    m_cfCalcCurve = 0;
+  }
+
+  m_cfCalcCurve = new QwtPlotCurve();
+  m_cfCalcCurve->setData(dataX, dataY);
+  QPen fitPen(Qt::red, Qt::SolidLine);
+  m_cfCalcCurve->setPen(fitPen);
+  m_cfCalcCurve->attach(m_cfPlot);
+  m_cfPlot->replot();
+}
+
+void IndirectDataAnalysis::confitSequential()
+{
+  if ( m_cfInputWS == NULL )
+  {
+    return;
+  }
+
+  QString bg = m_uiForm.confit_cbBackground->currentText();
+  if ( bg == "Fixed Flat" )
+  {
+    bg = "FixF";
+  }
+  else if ( bg == "Fit Flat" )
+  {
+    bg = "FitF";
+  }
+  else if ( bg == "Fit Linear" )
+  {
+    bg = "FitL";
+  }
+
+  Mantid::API::CompositeFunction* func = confitCreateFunction();
+  std::string function = std::string(*func);
+  QString stX = m_cfProp["StartX"]->valueText();
+  QString enX = m_cfProp["EndX"]->valueText();
+
+  QString pyInput =
+    "from IndirectDataAnalysis import confitSeq\n"
+    "input = '" + QString::fromStdString(m_cfInputWSName) + "'\n"
+    "func = r'" + QString::fromStdString(function) + "'\n"
+    "startx = " + stX + "\n"
+    "endx = " + enX + "\n"
+    "specMin = " + m_uiForm.confit_leSpecNo->text() + "\n"
+    "specMax = " + m_uiForm.confit_leSpecMax->text() + "\n"
+    "plot = '" + m_uiForm.confit_cbPlotOutput->currentText() + "'\n"
+    "save = ";
+  
+  pyInput += m_uiForm.confit_ckSaveSeq->isChecked() ? "True\n" : "False\n";
+  
+  pyInput +=    
+    "bg = '" + bg + "'\n"
+    "confitSeq(input, func, startx, endx, save, plot, bg, specMin, specMax)\n";
+
+  QString pyOutput = runPythonCode(pyInput);
+}
+
+void IndirectDataAnalysis::confitMinChanged(double val)
+{
+  m_cfDblMng->setValue(m_cfProp["StartX"], val);
+}
+
+void IndirectDataAnalysis::confitMaxChanged(double val)
+{
+  m_cfDblMng->setValue(m_cfProp["EndX"], val);
+}
+
+void IndirectDataAnalysis::confitHwhmChanged(double val)
+{
+  const double peakCentre = m_cfDblMng->value(m_cfProp["Lorentzian 1.PeakCentre"]);
+  // Always want HWHM to display as positive.
+  if ( val > peakCentre )
+  {
+    m_cfDblMng->setValue(m_cfProp["Lorentzian 1.HWHM"], val-peakCentre);
+  }
+  else
+  {
+    m_cfDblMng->setValue(m_cfProp["Lorentzian 1.HWHM"], peakCentre-val);
+  }
+}
+
+void IndirectDataAnalysis::confitBackgLevel(double val)
+{
+  m_cfDblMng->setValue(m_cfProp["BGA0"], val);
+}
+
+void IndirectDataAnalysis::confitUpdateRS(QtProperty* prop, double val)
+{
+  if ( prop == m_cfProp["StartX"] ) { m_cfRangeS->setMinimum(val); }
+  else if ( prop == m_cfProp["EndX"] ) { m_cfRangeS->setMaximum(val); }
+  else if ( prop == m_cfProp["BGA0"] ) { m_cfBackgS->setMinimum(val); }
+  else if ( prop == m_cfProp["Lorentzian 1.HWHM"] ) { confitHwhmUpdateRS(val); }
+}
+
+void IndirectDataAnalysis::confitHwhmUpdateRS(double val)
+{
+  const double peakCentre = m_cfDblMng->value(m_cfProp["Lorentzian 1.PeakCentre"]);
+  m_cfHwhmRange->setMinimum(peakCentre-val);
+  m_cfHwhmRange->setMaximum(peakCentre+val);
+}
+
+void IndirectDataAnalysis::confitCheckBoxUpdate(QtProperty* prop, bool checked)
+{
+  // Add/remove some properties to display only relevant options
+  if ( prop == m_cfProp["UseDeltaFunc"] )
+  {
+    if ( checked ) { m_cfProp["DeltaFunction"]->addSubProperty(m_cfProp["DeltaHeight"]); }
+    else { m_cfProp["DeltaFunction"]->removeSubProperty(m_cfProp["DeltaHeight"]); }
+  }
+}
+
+void IndirectDataAnalysis::absorptionRun()
+{
+  if ( ! validateAbsorption() )
+  {
+    showInformationBox("Please check your input.");
+    return;
+  }
+
+  QString pyInput =
+    "from IndirectDataAnalysis import absorption\n"
+    "file = r'" + m_uiForm.abs_inputFile->getFirstFilename() + "'\n"
+    "mode = '" + m_uiForm.abs_cbShape->currentText() + "'\n"
+    "sample = [ %1, %2, %3 ]\n"
+    "can = [ %4, %5, %6, %7 ]\n";
+
+  pyInput = pyInput.arg(m_uiForm.abs_leAttenuation->text());
+  pyInput = pyInput.arg(m_uiForm.abs_leScatter->text());
+  pyInput = pyInput.arg(m_uiForm.abs_leDensity->text());
+
+  if ( m_uiForm.abs_cbShape->currentText() == "Flat Plate" )
+  {
+    pyInput = pyInput.arg(m_uiForm.abs_leFlatHeight->text());
+    pyInput = pyInput.arg(m_uiForm.abs_leWidth->text());
+    pyInput = pyInput.arg(m_uiForm.abs_leThickness->text());
+    pyInput = pyInput.arg(m_uiForm.abs_leElementSize->text());
+  }
+  else
+  {
+    pyInput = pyInput.arg(m_uiForm.abs_leCylHeight->text());
+    pyInput = pyInput.arg(m_uiForm.abs_leRadius->text());
+    pyInput = pyInput.arg(m_uiForm.abs_leSlices->text());
+    pyInput = pyInput.arg(m_uiForm.abs_leAnnuli->text());
+  }
+
+  if ( m_uiForm.abs_ckVerbose->isChecked() ) pyInput += "verbose = True\n";
+  else pyInput += "verbose = False\n";
+
+  if ( m_uiForm.abs_ckPlot->isChecked() ) pyInput += "plot = True\n";
+  else pyInput += "plot = False\n";
+
+  if ( m_uiForm.abs_ckSave->isChecked() ) pyInput += "save = True\n";
+  else pyInput += "save = False\n";
+
+  pyInput +=
+    "absorption(file, mode, sample, can, Save=save, Verbose=verbose, Plot=plot)\n";
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+}
+
+void IndirectDataAnalysis::openDirectoryDialog()
+{
+  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
+  ad->show();
+  ad->setFocus();
+}
+
+void IndirectDataAnalysis::help()
+{
+  QString tabName = m_uiForm.tabWidget->tabText(m_uiForm.tabWidget->currentIndex());
+  QString url = "http://www.mantidproject.org/IDA";
+  if ( tabName == "Initial Settings" )
+    url += "";
+  else if ( tabName == "Elwin" )
+    url += ":Elwin";
+  else if ( tabName == "MSD Fit" )
+    url += ":MSDFit";
+  else if ( tabName == "Fury" )
+    url += ":Fury";
+  else if ( tabName == "FuryFit" )
+    url += ":FuryFit";
+  else if ( tabName == "ConvFit" )
+    url += ":ConvFit";
+  else if ( tabName == "Absorption" )
+    url += ":Absorption";
+  else if ( tabName == "Abs (F2PY)" )
+    url += ":AbsF2P";
+  else if ( tabName == "Apply Corrections" )
+    url += ":AbsCor";
+  QDesktopServices::openUrl(QUrl(url));
+}
+
+void IndirectDataAnalysis::absf2pRun()
+{
+  if ( ! validateAbsorptionF2Py() )
+  {
+    showInformationBox("Invalid input.");
+    return;
+  }
+
+  QString pyInput = "import SpencerAbsCor\n";
+  
+  QString geom;
+  QString size;
+
+  if ( m_uiForm.absp_cbShape->currentText() == "Flat" )
+  {
+    geom = "flt";
+    size = "[" + m_uiForm.absp_lets->text() + ", " +
+      m_uiForm.absp_letc1->text() + ", " +
+      m_uiForm.absp_letc2->text() + "]";
+  }
+  else if ( m_uiForm.absp_cbShape->currentText() == "Cylinder" )
+  {
+    geom = "cyl";
+
+    // R3 only populated when using can. R4 is fixed to 0.0
+    if ( m_uiForm.absp_ckUseCan->isChecked() ) 
+    {
+      size = "[" + m_uiForm.absp_ler1->text() + ", " +
+        m_uiForm.absp_ler2->text() + ", " +
+        m_uiForm.absp_ler3->text() + ", 0.0 ]";
+    }
+    else
+    {
+      size = "[" + m_uiForm.absp_ler1->text() + ", " +
+        m_uiForm.absp_ler2->text() + ", 0.0, 0.0 ]";
+    }
+    
+  }
+
+  QString width = m_uiForm.absp_lewidth->text();
+
+  if ( m_uiForm.absp_cbInputType->currentText() == "File" )
+  {
+    QString input = m_uiForm.absp_inputFile->getFirstFilename();
+    if ( input == "" ) { return; }
+    pyInput +=
+    "import os.path as op\n"
+    "file = r'" + input + "'\n"
+    "( dir, filename ) = op.split(file)\n"
+    "( name, ext ) = op.splitext(filename)\n"
+    "LoadNexusProcessed(file, name)\n"
+    "inputws = name\n";
+  }
+  else
+  {
+    pyInput += "inputws = '" + m_uiForm.absp_wsInput->currentText() + "'\n";
+  }
+  
+  if ( m_uiForm.absp_ckUseCan->isChecked() )
+  {
+    pyInput +=
+      "ncan = 2\n"
+      "density = [" + m_uiForm.absp_lesamden->text() + ", " + m_uiForm.absp_lecanden->text() + ", " + m_uiForm.absp_lecanden->text() + "]\n"
+      "sigs = [" + m_uiForm.absp_lesamsigs->text() + "," + m_uiForm.absp_lecansigs->text() + "," + m_uiForm.absp_lecansigs->text() + "]\n"
+      "siga = [" + m_uiForm.absp_lesamsiga->text() + "," + m_uiForm.absp_lecansiga->text() + "," + m_uiForm.absp_lecansiga->text() + "]\n";
+  }
+  else
+  {
+    pyInput +=
+      "ncan = 1\n"
+      "density = [" + m_uiForm.absp_lesamden->text() + ", 0.0, 0.0 ]\n"
+      "sigs = [" + m_uiForm.absp_lesamsigs->text() + ", 0.0, 0.0]\n"
+      "siga = [" + m_uiForm.absp_lesamsiga->text() + ", 0.0, 0.0]\n";
+  }
+
+  pyInput +=
+    "geom = '" + geom + "'\n"
+    "beam = [3.0, 0.5*" + width + ", -0.5*" + width + ", 2.0, -2.0, 0.0, 3.0, 0.0, 3.0]\n"
+    "size = " + size + "\n"
+    "avar = " + m_uiForm.absp_leavar->text() + "\n"
+    "plotOpt = '" + m_uiForm.absp_cbPlotOutput->currentText() + "'\n"
+    "SpencerAbsCor.AbsRunFeeder(inputws, geom, beam, ncan, size, density, sigs, siga, avar, plotOpt=plotOpt)\n";
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+}
+
+void IndirectDataAnalysis::absf2pShape(int index)
+{
+  m_uiForm.absp_swShapeDetails->setCurrentIndex(index);
+  // Meaning of the "avar" variable changes depending on shape selection
+  if ( index == 0 ) { m_uiForm.absp_lbAvar->setText("Can Angle to Beam"); }
+  else if ( index == 1 ) { m_uiForm.absp_lbAvar->setText("Step Size"); }
+}
+
+void IndirectDataAnalysis::absf2pUseCanChecked(bool value)
+{
+  m_uiForm.absp_gbCan->setEnabled(value);
+
+  m_uiForm.absp_lbR3->setEnabled(value);
+  m_uiForm.absp_ler3->setEnabled(value);
+  m_uiForm.absp_valR3->setEnabled(value);
+}
+
+void IndirectDataAnalysis::absf2pTCSync()
+{
+  if ( m_uiForm.absp_letc2->text() == "" )
+  {
+    QString val = m_uiForm.absp_letc1->text();
+    m_uiForm.absp_letc2->setText(val);
+  }
+}
+
+void IndirectDataAnalysis::abscorRun()
+{
+  QString geom = m_uiForm.abscor_cbGeometry->currentText();
+  if ( geom == "Flat" )
+  {
+    geom = "flt";
+  }
+  else if ( geom == "Cylinder" )
+  {
+    geom = "cyl";
+  }
+
+  QString pyInput = "from IndirectDataAnalysis import abscorFeeder, loadNexus\n";
+
+  if ( m_uiForm.abscor_cbSampleInputType->currentText() == "File" )
+  {
+    pyInput +=
+      "sample = loadNexus(r'" + m_uiForm.abscor_sample->getFirstFilename() + "')\n";
+  }
+  else
+  {
+    pyInput +=
+      "sample = '" + m_uiForm.abscor_wsSample->currentText() + "'\n";
+  }
+
+  if ( m_uiForm.abscor_ckUseCan->isChecked() )
+  {
+    if ( m_uiForm.abscor_cbContainerInputType->currentText() == "File" )
+    {
+      pyInput +=
+        "container = loadNexus(r'" + m_uiForm.abscor_can->getFirstFilename() + "')\n";
+    }
+    else
+    {
+      pyInput +=
+        "container = '" + m_uiForm.abscor_wsContainer->currentText() + "'\n";
+    }
+  }
+  else
+  {
+    pyInput += "container = ''\n";
+  }
+
+  pyInput += "geom = '" + geom + "'\n";
+
+
+  if ( m_uiForm.abscor_ckUseCorrections->isChecked() )
+  {
+    pyInput += "useCor = True\n";
+  }
+  else
+  {
+    pyInput += "useCor = False\n";
+  }
+
+  pyInput += "abscorFeeder(sample, container, geom, useCor)\n";
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+}
+
+} //namespace CustomInterfaces
+} //namespace MantidQt
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDiffractionReduction.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDiffractionReduction.cpp
index d991ff86cd16ebcb03eeea20f1b2ed4f5f4ef149..15eb4fc5a03fae8b64a9073081b1e4149ef0e5c0 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDiffractionReduction.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDiffractionReduction.cpp
@@ -1,244 +1,244 @@
-//----------------------
-// Includes
-//----------------------
-#include "MantidQtCustomInterfaces/IndirectDiffractionReduction.h"
-
-#include "MantidQtAPI/ManageUserDirectories.h"
-
-#include <QDesktopServices>
-#include <QUrl>
-
-
-//Add this class to the list of specialised dialogs in this namespace
-namespace MantidQt
-{
-namespace CustomInterfaces
-{
-  DECLARE_SUBWINDOW(IndirectDiffractionReduction);
-
-using namespace MantidQt::CustomInterfaces;
-
-//----------------------
-// Public member functions
-//----------------------
-///Constructor
-IndirectDiffractionReduction::IndirectDiffractionReduction(QWidget *parent) :
-  UserSubWindow(parent), m_realDiffraction(false)
-{
-}
-
-void IndirectDiffractionReduction::demonRun()
-{
-  if ( validateDemon() )
-  {
-    QString pyInput = "from IndirectDataAnalysis import demon\n"
-      "files = [r'" + m_uiForm.dem_rawFiles->getFilenames().join("',r'") + "']\n"
-      "first = " +m_uiForm.set_leSpecMin->text()+"\n"
-      "last = " +m_uiForm.set_leSpecMax->text()+"\n"
-      "instrument = '" + m_uiForm.set_cbInst->currentText() + "'\n"
-      "cal = r'" + m_uiForm.dem_calFile->getFirstFilename() + "'\n"
-      "grouping = " + grouping() + "\n";
-
-    if ( m_uiForm.dem_cbCorrection->currentText() == "Monitor" )
-    {
-      pyInput += "vanadium = ''\n"
-        "monitor = True\n";
-    }
-    else // Divide by Vanadium run
-    {
-      pyInput += "vanadium = r'" + m_uiForm.dem_vanadiumFile->getFirstFilename() + "'\n"
-        "monitor = False\n";
-    }
-
-    pyInput += "plot = '" + m_uiForm.cbPlotType->currentText() + "'\n";
-
-    if ( m_uiForm.dem_ckVerbose->isChecked() ) pyInput += "verbose = True\n";
-    else pyInput += "verbose = False\n";
-
-    if ( m_uiForm.dem_ckSave->isChecked() ) pyInput += "save = True\n";
-    else pyInput += "save = False\n";
-    
-    pyInput += "ws = demon(files, first, last, instrument, grouping=grouping, "
-      "Monitor=monitor, Vanadium=vanadium, cal=cal, Verbose=verbose, Plot=plot, "
-      "Save=save)\n";
-    QString pyOutput = runPythonCode(pyInput).trimmed();
-  }
-  else
-  {
-    showInformationBox("Input invalid.");
-  }
-}
-
-void IndirectDiffractionReduction::instrumentSelected(int)
-{
-  m_uiForm.set_cbReflection->blockSignals(true);
-  m_uiForm.set_cbReflection->clear();
-
-  QString pyInput = 
-    "from IndirectEnergyConversion import getInstrumentDetails\n"
-    "result = getInstrumentDetails('" + m_uiForm.set_cbInst->currentText() + "')\n"
-    "print result\n";
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-
-  if ( pyOutput == "" )
-  {
-    showInformationBox("Could not get list of analysers from Instrument Parameter file.");
-  }
-  else
-  {
-    QStringList analysers = pyOutput.split("\n", QString::SkipEmptyParts);
-
-    for (int i = 0; i< analysers.count(); i++ )
-    {
-      QStringList analyser = analysers[i].split("-", QString::SkipEmptyParts);
-      if ( analyser[0] == "diffraction" && analyser.count() > 1)
-      {
-        QStringList reflections = analyser[1].split(",", QString::SkipEmptyParts);
-        for ( int j = 0; j < reflections.count(); j++ )
-        {
-          m_uiForm.set_cbReflection->addItem(reflections[j]);
-        }
-        if ( reflections.count() == 1 )
-        {
-          m_uiForm.set_lbReflection->hide();
-          m_uiForm.set_cbReflection->hide();          
-        }
-        else
-        {
-          m_uiForm.set_lbReflection->show();
-          m_uiForm.set_cbReflection->show();
-        }
-      }
-    }
-
-    reflectionSelected(m_uiForm.set_cbReflection->currentIndex());
-
-    m_uiForm.set_cbReflection->blockSignals(false);
-
-    // Set options for "real diffraction"
-    if ( m_uiForm.set_cbInst->currentText() == "OSIRIS" )
-    {
-      m_realDiffraction = true;
-      m_uiForm.dem_swGrouping->setCurrentIndex(0);
-    }
-    else
-    {
-      m_realDiffraction = false;
-      m_uiForm.dem_swGrouping->setCurrentIndex(1);
-    }
-  }
-}
-
-void IndirectDiffractionReduction::reflectionSelected(int)
-{
-  QString pyInput =
-    "from IndirectEnergyConversion import getReflectionDetails\n"
-    "instrument = '" + m_uiForm.set_cbInst->currentText() + "'\n"
-    "reflection = '" + m_uiForm.set_cbReflection->currentText() + "'\n"
-    "print getReflectionDetails(instrument, 'diffraction', reflection)\n";
-
-  QString pyOutput = runPythonCode(pyInput).trimmed();
-  QStringList values = pyOutput.split("\n", QString::SkipEmptyParts);
-
-  if ( values.count() < 3 )
-  {
-    showInformationBox("Could not gather necessary data from parameter file.");
-    return;
-  }
-  else
-  {
-    QString analysisType = values[0];
-    m_uiForm.set_leSpecMin->setText(values[1]);
-    m_uiForm.set_leSpecMax->setText(values[2]);
-  }
-}
-
-void IndirectDiffractionReduction::correctionSelected(int index)
-{
-  m_uiForm.dem_vanadiumFile->setEnabled((index==1));
-}
-
-
-void IndirectDiffractionReduction::groupingSelected(const QString & selected)
-{
-  bool state = ( selected == "N Groups" );
-  m_uiForm.dem_leNumGroups->setEnabled(state);
-  m_uiForm.dem_lbNumGroups->setEnabled(state);  
-}
-
-void IndirectDiffractionReduction::openDirectoryDialog()
-{
-  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
-  ad->show();
-  ad->setFocus();
-}
-
-void IndirectDiffractionReduction::help()
-{
-  QString url = "http://www.mantidproject.org/Indirect_Diffraction_Reduction";
-  QDesktopServices::openUrl(QUrl(url));
-}
-
-void IndirectDiffractionReduction::initLayout()
-{
-  m_uiForm.setupUi(this);
-
-  connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(help()));
-  connect(m_uiForm.pbManageDirs, SIGNAL(clicked()), this, SLOT(openDirectoryDialog()));
-  connect(m_uiForm.pbRun, SIGNAL(clicked()), this, SLOT(demonRun()));
-
-  connect(m_uiForm.set_cbInst, SIGNAL(currentIndexChanged(int)), this, SLOT(instrumentSelected(int)));
-  connect(m_uiForm.set_cbReflection, SIGNAL(currentIndexChanged(int)), this, SLOT(reflectionSelected(int)));
-  connect(m_uiForm.dem_cbCorrection, SIGNAL(currentIndexChanged(int)), this, SLOT(correctionSelected(int)));
-  connect(m_uiForm.dem_cbGrouping, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(groupingSelected(const QString &)));
-
-  loadSettings();
-}
-
-void IndirectDiffractionReduction::initLocalPython()
-{
-  instrumentSelected(0);
-}
-
-void IndirectDiffractionReduction::loadSettings()
-{
-  QSettings settings;
-  QString settingsGroup = "CustomInterfaces/DEMON/DataDir";
-  QString dataDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("datasearch.directories")).split(";")[0];
-
-  settings.beginGroup(settingsGroup);
-  settings.setValue("last_directory", dataDir);
-  m_uiForm.dem_rawFiles->readSettings(settings.group());
-  m_uiForm.dem_calFile->readSettings(settings.group());
-  settings.endGroup();
-}
-
-bool IndirectDiffractionReduction::validateDemon()
-{
-  return m_uiForm.dem_rawFiles->isValid();
-}
-
-QString IndirectDiffractionReduction::grouping()
-{
-  QString option = "'" + m_uiForm.dem_cbGrouping->currentText() + "'";
-
-  if ( option == "'Individual'" || option == "'All'" )
-  {
-    return option;
-  }
-  else
-  {
-    QString pyInput = "import IndirectEnergyConversion as IEC\n"
-      "nspec =  (( %2 - %3 ) + 1 )/ %1\n"
-      "file = IEC.createMappingFile('demon.map', %1, nspec, %3)\n"
-      "print file\n";
-    pyInput = pyInput.arg(m_uiForm.dem_leNumGroups->text(), m_uiForm.set_leSpecMax->text(), m_uiForm.set_leSpecMin->text());
-    QString pyOutput = runPythonCode(pyInput).trimmed();
-    return "r'" + pyOutput + "'";
-  }
-
-}
-
-}
-}
+//----------------------
+// Includes
+//----------------------
+#include "MantidQtCustomInterfaces/IndirectDiffractionReduction.h"
+
+#include "MantidQtAPI/ManageUserDirectories.h"
+
+#include <QDesktopServices>
+#include <QUrl>
+
+
+//Add this class to the list of specialised dialogs in this namespace
+namespace MantidQt
+{
+namespace CustomInterfaces
+{
+  DECLARE_SUBWINDOW(IndirectDiffractionReduction);
+
+using namespace MantidQt::CustomInterfaces;
+
+//----------------------
+// Public member functions
+//----------------------
+///Constructor
+IndirectDiffractionReduction::IndirectDiffractionReduction(QWidget *parent) :
+  UserSubWindow(parent), m_realDiffraction(false)
+{
+}
+
+void IndirectDiffractionReduction::demonRun()
+{
+  if ( validateDemon() )
+  {
+    QString pyInput = "from IndirectDataAnalysis import demon\n"
+      "files = [r'" + m_uiForm.dem_rawFiles->getFilenames().join("',r'") + "']\n"
+      "first = " +m_uiForm.set_leSpecMin->text()+"\n"
+      "last = " +m_uiForm.set_leSpecMax->text()+"\n"
+      "instrument = '" + m_uiForm.set_cbInst->currentText() + "'\n"
+      "cal = r'" + m_uiForm.dem_calFile->getFirstFilename() + "'\n"
+      "grouping = " + grouping() + "\n";
+
+    if ( m_uiForm.dem_cbCorrection->currentText() == "Monitor" )
+    {
+      pyInput += "vanadium = ''\n"
+        "monitor = True\n";
+    }
+    else // Divide by Vanadium run
+    {
+      pyInput += "vanadium = r'" + m_uiForm.dem_vanadiumFile->getFirstFilename() + "'\n"
+        "monitor = False\n";
+    }
+
+    pyInput += "plot = '" + m_uiForm.cbPlotType->currentText() + "'\n";
+
+    if ( m_uiForm.dem_ckVerbose->isChecked() ) pyInput += "verbose = True\n";
+    else pyInput += "verbose = False\n";
+
+    if ( m_uiForm.dem_ckSave->isChecked() ) pyInput += "save = True\n";
+    else pyInput += "save = False\n";
+    
+    pyInput += "ws = demon(files, first, last, instrument, grouping=grouping, "
+      "Monitor=monitor, Vanadium=vanadium, cal=cal, Verbose=verbose, Plot=plot, "
+      "Save=save)\n";
+    QString pyOutput = runPythonCode(pyInput).trimmed();
+  }
+  else
+  {
+    showInformationBox("Input invalid.");
+  }
+}
+
+void IndirectDiffractionReduction::instrumentSelected(int)
+{
+  m_uiForm.set_cbReflection->blockSignals(true);
+  m_uiForm.set_cbReflection->clear();
+
+  QString pyInput = 
+    "from IndirectEnergyConversion import getInstrumentDetails\n"
+    "result = getInstrumentDetails('" + m_uiForm.set_cbInst->currentText() + "')\n"
+    "print result\n";
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+
+  if ( pyOutput == "" )
+  {
+    showInformationBox("Could not get list of analysers from Instrument Parameter file.");
+  }
+  else
+  {
+    QStringList analysers = pyOutput.split("\n", QString::SkipEmptyParts);
+
+    for (int i = 0; i< analysers.count(); i++ )
+    {
+      QStringList analyser = analysers[i].split("-", QString::SkipEmptyParts);
+      if ( analyser[0] == "diffraction" && analyser.count() > 1)
+      {
+        QStringList reflections = analyser[1].split(",", QString::SkipEmptyParts);
+        for ( int j = 0; j < reflections.count(); j++ )
+        {
+          m_uiForm.set_cbReflection->addItem(reflections[j]);
+        }
+        if ( reflections.count() == 1 )
+        {
+          m_uiForm.set_lbReflection->hide();
+          m_uiForm.set_cbReflection->hide();          
+        }
+        else
+        {
+          m_uiForm.set_lbReflection->show();
+          m_uiForm.set_cbReflection->show();
+        }
+      }
+    }
+
+    reflectionSelected(m_uiForm.set_cbReflection->currentIndex());
+
+    m_uiForm.set_cbReflection->blockSignals(false);
+
+    // Set options for "real diffraction"
+    if ( m_uiForm.set_cbInst->currentText() == "OSIRIS" )
+    {
+      m_realDiffraction = true;
+      m_uiForm.dem_swGrouping->setCurrentIndex(0);
+    }
+    else
+    {
+      m_realDiffraction = false;
+      m_uiForm.dem_swGrouping->setCurrentIndex(1);
+    }
+  }
+}
+
+void IndirectDiffractionReduction::reflectionSelected(int)
+{
+  QString pyInput =
+    "from IndirectEnergyConversion import getReflectionDetails\n"
+    "instrument = '" + m_uiForm.set_cbInst->currentText() + "'\n"
+    "reflection = '" + m_uiForm.set_cbReflection->currentText() + "'\n"
+    "print getReflectionDetails(instrument, 'diffraction', reflection)\n";
+
+  QString pyOutput = runPythonCode(pyInput).trimmed();
+  QStringList values = pyOutput.split("\n", QString::SkipEmptyParts);
+
+  if ( values.count() < 3 )
+  {
+    showInformationBox("Could not gather necessary data from parameter file.");
+    return;
+  }
+  else
+  {
+    QString analysisType = values[0];
+    m_uiForm.set_leSpecMin->setText(values[1]);
+    m_uiForm.set_leSpecMax->setText(values[2]);
+  }
+}
+
+void IndirectDiffractionReduction::correctionSelected(int index)
+{
+  m_uiForm.dem_vanadiumFile->setEnabled((index==1));
+}
+
+
+void IndirectDiffractionReduction::groupingSelected(const QString & selected)
+{
+  bool state = ( selected == "N Groups" );
+  m_uiForm.dem_leNumGroups->setEnabled(state);
+  m_uiForm.dem_lbNumGroups->setEnabled(state);  
+}
+
+void IndirectDiffractionReduction::openDirectoryDialog()
+{
+  MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
+  ad->show();
+  ad->setFocus();
+}
+
+void IndirectDiffractionReduction::help()
+{
+  QString url = "http://www.mantidproject.org/Indirect_Diffraction_Reduction";
+  QDesktopServices::openUrl(QUrl(url));
+}
+
+void IndirectDiffractionReduction::initLayout()
+{
+  m_uiForm.setupUi(this);
+
+  connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(help()));
+  connect(m_uiForm.pbManageDirs, SIGNAL(clicked()), this, SLOT(openDirectoryDialog()));
+  connect(m_uiForm.pbRun, SIGNAL(clicked()), this, SLOT(demonRun()));
+
+  connect(m_uiForm.set_cbInst, SIGNAL(currentIndexChanged(int)), this, SLOT(instrumentSelected(int)));
+  connect(m_uiForm.set_cbReflection, SIGNAL(currentIndexChanged(int)), this, SLOT(reflectionSelected(int)));
+  connect(m_uiForm.dem_cbCorrection, SIGNAL(currentIndexChanged(int)), this, SLOT(correctionSelected(int)));
+  connect(m_uiForm.dem_cbGrouping, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(groupingSelected(const QString &)));
+
+  loadSettings();
+}
+
+void IndirectDiffractionReduction::initLocalPython()
+{
+  instrumentSelected(0);
+}
+
+void IndirectDiffractionReduction::loadSettings()
+{
+  QSettings settings;
+  QString settingsGroup = "CustomInterfaces/DEMON/DataDir";
+  QString dataDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("datasearch.directories")).split(";")[0];
+
+  settings.beginGroup(settingsGroup);
+  settings.setValue("last_directory", dataDir);
+  m_uiForm.dem_rawFiles->readSettings(settings.group());
+  m_uiForm.dem_calFile->readSettings(settings.group());
+  settings.endGroup();
+}
+
+bool IndirectDiffractionReduction::validateDemon()
+{
+  return m_uiForm.dem_rawFiles->isValid();
+}
+
+QString IndirectDiffractionReduction::grouping()
+{
+  QString option = "'" + m_uiForm.dem_cbGrouping->currentText() + "'";
+
+  if ( option == "'Individual'" || option == "'All'" )
+  {
+    return option;
+  }
+  else
+  {
+    QString pyInput = "import IndirectEnergyConversion as IEC\n"
+      "nspec =  (( %2 - %3 ) + 1 )/ %1\n"
+      "file = IEC.createMappingFile('demon.map', %1, nspec, %3)\n"
+      "print file\n";
+    pyInput = pyInput.arg(m_uiForm.dem_leNumGroups->text(), m_uiForm.set_leSpecMax->text(), m_uiForm.set_leSpecMin->text());
+    QString pyOutput = runPythonCode(pyInput).trimmed();
+    return "r'" + pyOutput + "'";
+  }
+
+}
+
+}
+}
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SANSDiagnostics.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SANSDiagnostics.cpp
index 07bd6a5b2836bfaaac5ed830b558f21436f094d7..82852e4be37969020b0743657bbcebfa4a33be98 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/SANSDiagnostics.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SANSDiagnostics.cpp
@@ -1,389 +1,389 @@
-#include "MantidQtCustomInterfaces/SANSDiagnostics.h"
-#include "MantidAPI/MatrixWorkspace.h"
-#include "MantidKernel/UserStringParser.h"
-#include "MantidAPI/WorkspaceGroup.h"
-#include "MantidGeometry/Instrument/RectangularDetector.h"
-#include "MantidAPI/SpectraDetectorMap.h"
-
-
-namespace MantidQt
-{
-  namespace CustomInterfaces
-  {
-    using namespace Mantid::Kernel;
-    using namespace Mantid::API;
-
-    ///Constructor
-    SANSDiagnostics::SANSDiagnostics(QWidget *parent, Ui::SANSRunWindow *ParWidgets):
-    m_SANSForm(ParWidgets), parForm(parent),m_totalPeriods(0),m_rectDetectors(),m_Period(0),
-      g_log(Mantid::Kernel::Logger::get("SANSDiagnostics"))
-    {
-      initLayout();
-      //connect to SANSRunWindow to apply mask
-      connect(this,SIGNAL(applyMask(const QString&,bool)),parent,SLOT(applyMask(const QString&,bool)));
-    }
-    ///Destructor
-    SANSDiagnostics::~SANSDiagnostics()
-    {
-      saveSettings();
-    }
-
-    ///initialise the diagonstics tab
-    void SANSDiagnostics::initLayout()
-    {
-      //loads the last saved settings
-      loadSettings();
-      setToolTips();
-      //disable the rectanglar detctors initially
-      disableDetectorGroupBoxes(true);
-      //daisable periods controls
-      changePeriodsControls(true);
-    
-      //disable time region contorls
-      m_SANSForm->region_det1->setDisabled(true);
-      m_SANSForm->region_det2->setDisabled(true);
-      m_SANSForm->tirange_edit1->setDisabled(true);
-      m_SANSForm->tirange_edit2->setDisabled(true);
-
-      //disable the check boxes for Time channel and Pixel masks
-      m_SANSForm->tcmask1->setDisabled(true);
-      m_SANSForm->tcmask2->setDisabled(true);
-      m_SANSForm->pmask1->setDisabled(true);
-      m_SANSForm->tcmask3->setDisabled(true);
-      m_SANSForm->tcmask4->setDisabled(true);
-      m_SANSForm->pmask2->setDisabled(true);
-
-      connect(this, SIGNAL(runAsPythonScript(const QString&)),
-        parForm, SIGNAL(runAsPythonScript(const QString&)));
-
-      ///connect file finder plugin signal to loadfirstspectrum slot of this class
-      connect(m_SANSForm->file_run_edit,SIGNAL(fileEditingFinished()),this,SLOT(loadFirstSpectrum()));
-      connect(m_SANSForm->hi_Btn1,SIGNAL(clicked()),this,SLOT(firstDetectorHorizontalIntegralClicked()));
-      connect(m_SANSForm->vi_Btn1,SIGNAL(clicked()),this,SLOT(firstDetectorVerticalIntegralClicked()));
-      connect(m_SANSForm->ti_Btn1,SIGNAL(clicked()),this,SLOT(firstDetectorTimeIntegralClicked()));
-      //2nd detector
-      connect(m_SANSForm->hi_Btn2,SIGNAL(clicked()),this,SLOT(secondDetectorHorizontalIntegralClicked()));
-      connect(m_SANSForm->vi_Btn2,SIGNAL(clicked()),this,SLOT(secondDetectorVerticalIntegralClicked()));
-      connect(m_SANSForm->ti_Btn2,SIGNAL(clicked()),this,SLOT(secondDetectorTimeIntegralClicked()));
-      /// if period is entered display rectangual detector banks for that period
-      connect(m_SANSForm->period_edit,SIGNAL(editingFinished()),this,SLOT(displayDetectorBanksofMemberWorkspace()));
-      
-      
-    }
-    /// set tool tips
-    void SANSDiagnostics::setToolTips()
-    {
-      m_SANSForm->label_period->setToolTip("Period number of the member workspace to process  if the loaded file contains multi period data");
-      m_SANSForm->hrange_det1->setToolTip("H/V_Min and H/V_Max values for SumRowColumn algorithm");
-      m_SANSForm->vrange_det1->setToolTip("H/V_Min and H/V_Max values for SumRowColumn algorithm");
-
-      m_SANSForm->hrange_det2->setToolTip("H/V_Min and H/V_Max values for SumRowColumn algorithm");
-      m_SANSForm->vrange_det2->setToolTip("H/V_Min and H/V_Max values for SumRowColumn algorithm");
-
-      m_SANSForm->hi_Btn1->setToolTip("Executes SANS specific SumRowColumn algorithm and displays the H Plot for the first detectro bank ");
-      m_SANSForm->vi_Btn1->setToolTip("Executes SANS specific SumRowColumn algorithm and displays the V Plot for the first detectro bank");
-      m_SANSForm->hi_Btn2->setToolTip("Executes SANS specific SumRowColumn algorithm and displays the H Plot for the second detectro bank ");
-      m_SANSForm->vi_Btn2->setToolTip("Executes SANS specific SumRowColumn algorithm and displays the V Plot for the second detectro bank ");
-
-      m_SANSForm->ti_Btn1->setToolTip("Executes SumSpectra algorithm and displays the Plot for the first detectro bank ");
-      m_SANSForm->ti_Btn2->setToolTip("Executes SumSpectra algorithm and displays the Plot for the second detectro bank");
-      m_SANSForm->total_perioids->setToolTip("Total number of periods");
-
-    }
-
-  /** This method loads the first spectrum
-    * and displays periods and rectangular detectors if any.
-    */ 
-    void SANSDiagnostics::loadFirstSpectrum()
-    {
-      
-      //get the file names using the filefinder plugin
-      QString filename =getFileName();
-      if(filename.isEmpty())
-      {
-        return;
-      }
-      //get first string from the filename  list.
-      std::string fileName=filename.toStdString();
-      std::replace(fileName.begin(),fileName.end(),'\\','/');
-      //if the file name same as the last entered file name don't run the load algorithm again 
-      if(!m_fileName.compare(QString::fromStdString(fileName))) return;
-      m_fileName=QString::fromStdString(fileName);
-      //load the first spectrum
-      if(!runLoadAlgorithm(m_fileName,"1","1"))
-      {
-        return;
-      }
-      //total periods
-      m_totalPeriods=getTotalNumberofPeriods();
-      if(m_totalPeriods<=1)
-      {
-       // disble Periods Controls;
-        changePeriodsControls(true);
-      }
-      if(m_totalPeriods==1)
-      {        
-        displayRectangularDetectors(m_outws_load);
-      }
-      else if(m_totalPeriods>1)
-      {
-        // enable Periods Controls;
-        changePeriodsControls(false);
-        displayTotalPeriods();
-      }
-
-    }
-
-    ///Display total periods
-    void SANSDiagnostics::displayTotalPeriods()
-    {
-
-      std::string speriods("/");
-      std::string period;
-      try
-      {
-        period=boost::lexical_cast<std::string>(m_totalPeriods);
-      }
-      catch(boost::bad_lexical_cast&)
-      {
-        g_log.error("Error when displaying the total number of periods");
-      }
-      speriods+=period;
-
-      QString style="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
-        "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
-        "p, li { white-space: pre-wrap; }\n"
-        "</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
-        "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:12pt;\">";
-      style+=QString::fromStdString(speriods);
-      style+="</span></p></body></html>";
-      std::string key=style.toStdString();
-      m_SANSForm->total_perioids->setText(QApplication::translate("SANSRunWindow",key.c_str(),0, QApplication::UnicodeUTF8));
-
-    }
-    /// This method disables the total periods controls
-    void SANSDiagnostics::changePeriodsControls(bool bEnable)
-    {
-       //daisable periods controls
-      m_SANSForm->period_edit->setDisabled(bEnable);
-      m_SANSForm->total_perioids->setDisabled(bEnable);
-      m_SANSForm->label_period->setDisabled(bEnable);
-    }
-
-    /// get the period number entered in the Periods box
-    int SANSDiagnostics::getPeriodNumber()
-    {
-      QString period=m_SANSForm->period_edit->text();
-      int periodNum=0;
-      try
-      {
-        periodNum=boost::lexical_cast<int>(period.toStdString());
-      }
-      catch(boost::bad_lexical_cast&)
-      {
-        g_log.error("Error when reading the user entered  period number");
-        return 0;
-      }
-      return periodNum;
-    }
-    /**This method returns the member workspace name for the period
-    *  @param period - period number
-    *  @returns name of the member workspace.
-    */
-    QString SANSDiagnostics::getMemberWorkspace(int period)
-    {   
-      Mantid::API::Workspace_sptr ws_sptr;
-      try
-      {
-        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(m_outws_load.toStdString());
-
-      }
-      catch(Exception::NotFoundError&)
-      {
-        g_log.error()<<"Error when accessing the Workspace "+m_outws_load.toStdString()<<std::endl;
-        return "";
-      }
-      if(Mantid::API::WorkspaceGroup_sptr wsgrp_sptr=boost::dynamic_pointer_cast<WorkspaceGroup>(ws_sptr))
-      {
-        std::vector<std::string> members= wsgrp_sptr->getNames();
-        try
-        {
-          return QString::fromStdString(members.at(period-1));//return the member workspace.
-        }
-        catch(std::out_of_range&)
-        {
-          g_log.error("The period number entered is wrong.");
-        }
-      }
-      return "";
-    }
-    ///returns true if the workspace contains multi period data i.e;multi period data
-    bool SANSDiagnostics::isMultiPeriod()
-    {
-      Mantid::API::Workspace_sptr ws_sptr;
-      try
-      {
-        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(m_outws_load.toStdString());
-
-      }
-      catch(Exception::NotFoundError&)
-      {
-        return false;
-      }
-      Mantid::API::WorkspaceGroup_sptr wsgrp_sptr=boost::dynamic_pointer_cast<WorkspaceGroup>(ws_sptr);
-      return (wsgrp_sptr?true:false);
-    }
-    /// Deisplays rectangular detecctors of the selected member workspace.
-    void SANSDiagnostics::displayDetectorBanksofMemberWorkspace()
-    { 
-
-      //if multi period get the user selected workspace
-      int periodNum=getPeriodNumber();
-      
-      std::string sPeriods;
-      try
-      {
-        sPeriods= boost::lexical_cast<std::string>(m_totalPeriods);
-      }
-      catch(boost::bad_lexical_cast&)
-      {
-
-      }
-      if(periodNum>m_totalPeriods || periodNum<1)
-      {
-        g_log.error("Error:Period number entered is is wrong.Enter a value between 1 and total number of periods "+ sPeriods );
-        return;
-      }
-      //this check is doing bcoz the editfinished signal seems to be emitted more than once .
-      if(periodNum==m_Period)
-      {
-      return;
-      }
-      m_Period=periodNum;
-      if(m_totalPeriods>1)
-      {        
-        m_memberwsName= getMemberWorkspace(periodNum);
-      }
-
-      displayRectangularDetectors(m_memberwsName);
-    }
-    /// This method displays the rectangular detectors
-    void SANSDiagnostics::displayRectangularDetectors(const QString& wsName)
-    { 
-
-      Mantid::API::Workspace_sptr ws_sptr;
-      try
-      {
-        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(wsName.toStdString());
-
-      }
-      catch(Exception::NotFoundError&)
-      {
-        g_log.error()<<"Error when accessing the Workspace "+wsName.toStdString()<<std::endl;
-      }
-      if(!ws_sptr)
-      {
-        return;
-      }
-
-      //get rectangular detector details.
-      std::vector<boost::shared_ptr<RectDetectorDetails> > rectDetectors=rectangularDetectorDetails(ws_sptr);
-      m_rectDetectors.assign(rectDetectors.begin(),rectDetectors.end());
-      if(rectDetectors.empty())
-      {
-        g_log.error()<<"The instrument associated to the file "+m_fileName.toStdString()<<" does not have any RectangularDetectors "<<std::endl;
-        disableDetectorGroupBoxes(true);
-        return;
-      }
-      //get the name of detectors
-      QString det1Name,det2Name;
-      //first detector name
-      det1Name=getDetectorName(0);
-      if(!det1Name.isEmpty())
-      {
-        //enable the detector display controls
-        m_SANSForm->groupBox_Detector1->setDisabled(false);
-        //set anme
-        m_SANSForm->groupBox_Detector1->setTitle(det1Name);
-        m_SANSForm->groupBox_Detector1->show();
-      }
-      else
-      {
-        m_SANSForm->groupBox_Detector1->setDisabled(true);
-      }
-     
-      //2nd detector
-      det2Name=getDetectorName(1);
-      if(!det2Name.isEmpty())
-      { 
-        m_SANSForm->groupBox_Detector2->setDisabled(false);
-        m_SANSForm->groupBox_Detector2->setTitle(det2Name);
-        m_SANSForm->groupBox_Detector2->show();
-      }
-      else
-      {
-        m_SANSForm->groupBox_Detector2->setDisabled(true);
-        
-      }
-
-    }
-
-  /** This method returns the detector name from list of detctors for a given index
-    * @param index of the rectangular detector
-    * @return detector name
-    */
-    const QString SANSDiagnostics::getDetectorName(int index)
-    {
-      boost::shared_ptr<RectDetectorDetails> rectDet;
-      try
-      {
-        rectDet = m_rectDetectors.at(index);
-      } 
-      catch(std::out_of_range&)
-      {     
-      } 
-      if(rectDet)
-      {  
-        return rectDet->getDetcetorName();
-      }
-      return "";
-    }
-
-  /** This method returns a vector of rectanglar detector's name, min & max detector id.
-    * @param ws_sptr shared pointer to workspace
-    * @returns vector of rectangular detectors details
-    */
-    std::vector<boost::shared_ptr<RectDetectorDetails> > SANSDiagnostics::rectangularDetectorDetails(Mantid::API::Workspace_sptr& ws_sptr)
-    {      
-
-      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
-      if(!mws_sptr)
-      {
-        return std::vector<boost::shared_ptr<RectDetectorDetails> > ();
-      }
-      Mantid::Geometry::IInstrument_sptr inst=mws_sptr->getInstrument();
-      if(!inst)
-      {       
-        return std::vector<boost::shared_ptr<RectDetectorDetails> > ();
-      }
-      std::vector<boost::shared_ptr<RectDetectorDetails> > rectDetectors;
+#include "MantidQtCustomInterfaces/SANSDiagnostics.h"
+#include "MantidAPI/MatrixWorkspace.h"
+#include "MantidKernel/UserStringParser.h"
+#include "MantidAPI/WorkspaceGroup.h"
+#include "MantidGeometry/Instrument/RectangularDetector.h"
+#include "MantidAPI/SpectraDetectorMap.h"
+
+
+namespace MantidQt
+{
+  namespace CustomInterfaces
+  {
+    using namespace Mantid::Kernel;
+    using namespace Mantid::API;
+
+    ///Constructor
+    SANSDiagnostics::SANSDiagnostics(QWidget *parent, Ui::SANSRunWindow *ParWidgets):
+    m_SANSForm(ParWidgets), parForm(parent),m_totalPeriods(0),m_rectDetectors(),m_Period(0),
+      g_log(Mantid::Kernel::Logger::get("SANSDiagnostics"))
+    {
+      initLayout();
+      //connect to SANSRunWindow to apply mask
+      connect(this,SIGNAL(applyMask(const QString&,bool)),parent,SLOT(applyMask(const QString&,bool)));
+    }
+    ///Destructor
+    SANSDiagnostics::~SANSDiagnostics()
+    {
+      saveSettings();
+    }
+
+    ///initialise the diagonstics tab
+    void SANSDiagnostics::initLayout()
+    {
+      //loads the last saved settings
+      loadSettings();
+      setToolTips();
+      //disable the rectanglar detctors initially
+      disableDetectorGroupBoxes(true);
+      //daisable periods controls
+      changePeriodsControls(true);
+    
+      //disable time region contorls
+      m_SANSForm->region_det1->setDisabled(true);
+      m_SANSForm->region_det2->setDisabled(true);
+      m_SANSForm->tirange_edit1->setDisabled(true);
+      m_SANSForm->tirange_edit2->setDisabled(true);
+
+      //disable the check boxes for Time channel and Pixel masks
+      m_SANSForm->tcmask1->setDisabled(true);
+      m_SANSForm->tcmask2->setDisabled(true);
+      m_SANSForm->pmask1->setDisabled(true);
+      m_SANSForm->tcmask3->setDisabled(true);
+      m_SANSForm->tcmask4->setDisabled(true);
+      m_SANSForm->pmask2->setDisabled(true);
+
+      connect(this, SIGNAL(runAsPythonScript(const QString&)),
+        parForm, SIGNAL(runAsPythonScript(const QString&)));
+
+      ///connect file finder plugin signal to loadfirstspectrum slot of this class
+      connect(m_SANSForm->file_run_edit,SIGNAL(fileEditingFinished()),this,SLOT(loadFirstSpectrum()));
+      connect(m_SANSForm->hi_Btn1,SIGNAL(clicked()),this,SLOT(firstDetectorHorizontalIntegralClicked()));
+      connect(m_SANSForm->vi_Btn1,SIGNAL(clicked()),this,SLOT(firstDetectorVerticalIntegralClicked()));
+      connect(m_SANSForm->ti_Btn1,SIGNAL(clicked()),this,SLOT(firstDetectorTimeIntegralClicked()));
+      //2nd detector
+      connect(m_SANSForm->hi_Btn2,SIGNAL(clicked()),this,SLOT(secondDetectorHorizontalIntegralClicked()));
+      connect(m_SANSForm->vi_Btn2,SIGNAL(clicked()),this,SLOT(secondDetectorVerticalIntegralClicked()));
+      connect(m_SANSForm->ti_Btn2,SIGNAL(clicked()),this,SLOT(secondDetectorTimeIntegralClicked()));
+      /// if period is entered display rectangual detector banks for that period
+      connect(m_SANSForm->period_edit,SIGNAL(editingFinished()),this,SLOT(displayDetectorBanksofMemberWorkspace()));
+      
+      
+    }
+    /// set tool tips
+    void SANSDiagnostics::setToolTips()
+    {
+      m_SANSForm->label_period->setToolTip("Period number of the member workspace to process  if the loaded file contains multi period data");
+      m_SANSForm->hrange_det1->setToolTip("H/V_Min and H/V_Max values for SumRowColumn algorithm");
+      m_SANSForm->vrange_det1->setToolTip("H/V_Min and H/V_Max values for SumRowColumn algorithm");
+
+      m_SANSForm->hrange_det2->setToolTip("H/V_Min and H/V_Max values for SumRowColumn algorithm");
+      m_SANSForm->vrange_det2->setToolTip("H/V_Min and H/V_Max values for SumRowColumn algorithm");
+
+      m_SANSForm->hi_Btn1->setToolTip("Executes SANS specific SumRowColumn algorithm and displays the H Plot for the first detectro bank ");
+      m_SANSForm->vi_Btn1->setToolTip("Executes SANS specific SumRowColumn algorithm and displays the V Plot for the first detectro bank");
+      m_SANSForm->hi_Btn2->setToolTip("Executes SANS specific SumRowColumn algorithm and displays the H Plot for the second detectro bank ");
+      m_SANSForm->vi_Btn2->setToolTip("Executes SANS specific SumRowColumn algorithm and displays the V Plot for the second detectro bank ");
+
+      m_SANSForm->ti_Btn1->setToolTip("Executes SumSpectra algorithm and displays the Plot for the first detectro bank ");
+      m_SANSForm->ti_Btn2->setToolTip("Executes SumSpectra algorithm and displays the Plot for the second detectro bank");
+      m_SANSForm->total_perioids->setToolTip("Total number of periods");
+
+    }
+
+  /** This method loads the first spectrum
+    * and displays periods and rectangular detectors if any.
+    */ 
+    void SANSDiagnostics::loadFirstSpectrum()
+    {
+      
+      //get the file names using the filefinder plugin
+      QString filename =getFileName();
+      if(filename.isEmpty())
+      {
+        return;
+      }
+      //get first string from the filename  list.
+      std::string fileName=filename.toStdString();
+      std::replace(fileName.begin(),fileName.end(),'\\','/');
+      //if the file name same as the last entered file name don't run the load algorithm again 
+      if(!m_fileName.compare(QString::fromStdString(fileName))) return;
+      m_fileName=QString::fromStdString(fileName);
+      //load the first spectrum
+      if(!runLoadAlgorithm(m_fileName,"1","1"))
+      {
+        return;
+      }
+      //total periods
+      m_totalPeriods=getTotalNumberofPeriods();
+      if(m_totalPeriods<=1)
+      {
+       // disble Periods Controls;
+        changePeriodsControls(true);
+      }
+      if(m_totalPeriods==1)
+      {        
+        displayRectangularDetectors(m_outws_load);
+      }
+      else if(m_totalPeriods>1)
+      {
+        // enable Periods Controls;
+        changePeriodsControls(false);
+        displayTotalPeriods();
+      }
+
+    }
+
+    ///Display total periods
+    void SANSDiagnostics::displayTotalPeriods()
+    {
+
+      std::string speriods("/");
+      std::string period;
+      try
+      {
+        period=boost::lexical_cast<std::string>(m_totalPeriods);
+      }
+      catch(boost::bad_lexical_cast&)
+      {
+        g_log.error("Error when displaying the total number of periods");
+      }
+      speriods+=period;
+
+      QString style="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
+        "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
+        "p, li { white-space: pre-wrap; }\n"
+        "</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
+        "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:12pt;\">";
+      style+=QString::fromStdString(speriods);
+      style+="</span></p></body></html>";
+      std::string key=style.toStdString();
+      m_SANSForm->total_perioids->setText(QApplication::translate("SANSRunWindow",key.c_str(),0, QApplication::UnicodeUTF8));
+
+    }
+    /// This method disables the total periods controls
+    void SANSDiagnostics::changePeriodsControls(bool bEnable)
+    {
+       //daisable periods controls
+      m_SANSForm->period_edit->setDisabled(bEnable);
+      m_SANSForm->total_perioids->setDisabled(bEnable);
+      m_SANSForm->label_period->setDisabled(bEnable);
+    }
+
+    /// get the period number entered in the Periods box
+    int SANSDiagnostics::getPeriodNumber()
+    {
+      QString period=m_SANSForm->period_edit->text();
+      int periodNum=0;
+      try
+      {
+        periodNum=boost::lexical_cast<int>(period.toStdString());
+      }
+      catch(boost::bad_lexical_cast&)
+      {
+        g_log.error("Error when reading the user entered  period number");
+        return 0;
+      }
+      return periodNum;
+    }
+    /**This method returns the member workspace name for the period
+    *  @param period - period number
+    *  @returns name of the member workspace.
+    */
+    QString SANSDiagnostics::getMemberWorkspace(int period)
+    {   
+      Mantid::API::Workspace_sptr ws_sptr;
+      try
+      {
+        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(m_outws_load.toStdString());
+
+      }
+      catch(Exception::NotFoundError&)
+      {
+        g_log.error()<<"Error when accessing the Workspace "+m_outws_load.toStdString()<<std::endl;
+        return "";
+      }
+      if(Mantid::API::WorkspaceGroup_sptr wsgrp_sptr=boost::dynamic_pointer_cast<WorkspaceGroup>(ws_sptr))
+      {
+        std::vector<std::string> members= wsgrp_sptr->getNames();
+        try
+        {
+          return QString::fromStdString(members.at(period-1));//return the member workspace.
+        }
+        catch(std::out_of_range&)
+        {
+          g_log.error("The period number entered is wrong.");
+        }
+      }
+      return "";
+    }
+    ///returns true if the workspace contains multi period data i.e;multi period data
+    bool SANSDiagnostics::isMultiPeriod()
+    {
+      Mantid::API::Workspace_sptr ws_sptr;
+      try
+      {
+        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(m_outws_load.toStdString());
+
+      }
+      catch(Exception::NotFoundError&)
+      {
+        return false;
+      }
+      Mantid::API::WorkspaceGroup_sptr wsgrp_sptr=boost::dynamic_pointer_cast<WorkspaceGroup>(ws_sptr);
+      return (wsgrp_sptr?true:false);
+    }
+    /// Deisplays rectangular detecctors of the selected member workspace.
+    void SANSDiagnostics::displayDetectorBanksofMemberWorkspace()
+    { 
+
+      //if multi period get the user selected workspace
+      int periodNum=getPeriodNumber();
+      
+      std::string sPeriods;
+      try
+      {
+        sPeriods= boost::lexical_cast<std::string>(m_totalPeriods);
+      }
+      catch(boost::bad_lexical_cast&)
+      {
+
+      }
+      if(periodNum>m_totalPeriods || periodNum<1)
+      {
+        g_log.error("Error:Period number entered is is wrong.Enter a value between 1 and total number of periods "+ sPeriods );
+        return;
+      }
+      //this check is doing bcoz the editfinished signal seems to be emitted more than once .
+      if(periodNum==m_Period)
+      {
+      return;
+      }
+      m_Period=periodNum;
+      if(m_totalPeriods>1)
+      {        
+        m_memberwsName= getMemberWorkspace(periodNum);
+      }
+
+      displayRectangularDetectors(m_memberwsName);
+    }
+    /// This method displays the rectangular detectors
+    void SANSDiagnostics::displayRectangularDetectors(const QString& wsName)
+    { 
+
+      Mantid::API::Workspace_sptr ws_sptr;
+      try
+      {
+        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(wsName.toStdString());
+
+      }
+      catch(Exception::NotFoundError&)
+      {
+        g_log.error()<<"Error when accessing the Workspace "+wsName.toStdString()<<std::endl;
+      }
+      if(!ws_sptr)
+      {
+        return;
+      }
+
+      //get rectangular detector details.
+      std::vector<boost::shared_ptr<RectDetectorDetails> > rectDetectors=rectangularDetectorDetails(ws_sptr);
+      m_rectDetectors.assign(rectDetectors.begin(),rectDetectors.end());
+      if(rectDetectors.empty())
+      {
+        g_log.error()<<"The instrument associated to the file "+m_fileName.toStdString()<<" does not have any RectangularDetectors "<<std::endl;
+        disableDetectorGroupBoxes(true);
+        return;
+      }
+      //get the name of detectors
+      QString det1Name,det2Name;
+      //first detector name
+      det1Name=getDetectorName(0);
+      if(!det1Name.isEmpty())
+      {
+        //enable the detector display controls
+        m_SANSForm->groupBox_Detector1->setDisabled(false);
+        //set anme
+        m_SANSForm->groupBox_Detector1->setTitle(det1Name);
+        m_SANSForm->groupBox_Detector1->show();
+      }
+      else
+      {
+        m_SANSForm->groupBox_Detector1->setDisabled(true);
+      }
+     
+      //2nd detector
+      det2Name=getDetectorName(1);
+      if(!det2Name.isEmpty())
+      { 
+        m_SANSForm->groupBox_Detector2->setDisabled(false);
+        m_SANSForm->groupBox_Detector2->setTitle(det2Name);
+        m_SANSForm->groupBox_Detector2->show();
+      }
+      else
+      {
+        m_SANSForm->groupBox_Detector2->setDisabled(true);
+        
+      }
+
+    }
+
+  /** This method returns the detector name from list of detctors for a given index
+    * @param index of the rectangular detector
+    * @return detector name
+    */
+    const QString SANSDiagnostics::getDetectorName(int index)
+    {
+      boost::shared_ptr<RectDetectorDetails> rectDet;
+      try
+      {
+        rectDet = m_rectDetectors.at(index);
+      } 
+      catch(std::out_of_range&)
+      {     
+      } 
+      if(rectDet)
+      {  
+        return rectDet->getDetcetorName();
+      }
+      return "";
+    }
+
+  /** This method returns a vector of rectanglar detector's name, min & max detector id.
+    * @param ws_sptr shared pointer to workspace
+    * @returns vector of rectangular detectors details
+    */
+    std::vector<boost::shared_ptr<RectDetectorDetails> > SANSDiagnostics::rectangularDetectorDetails(Mantid::API::Workspace_sptr& ws_sptr)
+    {      
+
+      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
+      if(!mws_sptr)
+      {
+        return std::vector<boost::shared_ptr<RectDetectorDetails> > ();
+      }
+      Mantid::Geometry::IInstrument_sptr inst=mws_sptr->getInstrument();
+      if(!inst)
+      {       
+        return std::vector<boost::shared_ptr<RectDetectorDetails> > ();
+      }
+      std::vector<boost::shared_ptr<RectDetectorDetails> > rectDetectors;
       for (int i=0; i < inst->nelements(); i++)
       {                
         Mantid::Geometry::IComponent_sptr comp=(*inst)[i];
         boost::shared_ptr<Mantid::Geometry::RectangularDetector> det = 
           boost::dynamic_pointer_cast<Mantid::Geometry::RectangularDetector>( comp );
-        if (det)
-        { 
-          boost::shared_ptr<RectDetectorDetails> rect(new RectDetectorDetails);
-          rect->setDetcetorName(QString::fromStdString(det->getName()));
-          rect->setMinimumDetcetorId(det->minDetectorID());
-          rect->setMaximumDetcetorId(det->maxDetectorID());
-          rectDetectors.push_back(rect);
-
-        }
-        else
-        {
-
+        if (det)
+        { 
+          boost::shared_ptr<RectDetectorDetails> rect(new RectDetectorDetails);
+          rect->setDetcetorName(QString::fromStdString(det->getName()));
+          rect->setMinimumDetcetorId(det->minDetectorID());
+          rect->setMaximumDetcetorId(det->maxDetectorID());
+          rectDetectors.push_back(rect);
+
+        }
+        else
+        {
+
           boost::shared_ptr<Mantid::Geometry::ICompAssembly> assem = 
             boost::dynamic_pointer_cast<Mantid::Geometry::ICompAssembly>(comp);
           if (assem)
@@ -394,1038 +394,1038 @@ namespace MantidQt
               if (det) 
               { 
 
-                boost::shared_ptr<RectDetectorDetails> rect(new RectDetectorDetails);
-                rect->setDetcetorName(QString::fromStdString(det->getName()));
-                rect->setMinimumDetcetorId(det->minDetectorID());
-                rect->setMaximumDetcetorId(det->maxDetectorID());
+                boost::shared_ptr<RectDetectorDetails> rect(new RectDetectorDetails);
+                rect->setDetcetorName(QString::fromStdString(det->getName()));
+                rect->setMinimumDetcetorId(det->minDetectorID());
+                rect->setMaximumDetcetorId(det->maxDetectorID());
                 rectDetectors.push_back(rect);
               }
 
             }
-          }
-        }
-      }
-      return rectDetectors;
-    }
-
-  /** This method returns spectrum list for the selected detector
-    * @param mws_sptr shared pointer to workspace
-    * @param detNum number used to identify detector
-    * @param specList  -list of spectrum
-    */
-    void SANSDiagnostics::getSpectraList(const Mantid::API::MatrixWorkspace_sptr& mws_sptr,const int detNum,std::vector<int>&specList)
-    {
-      boost::shared_ptr<RectDetectorDetails> rectDet;
-      try
-      {
-        rectDet= m_rectDetectors.at(detNum);
-      }
-      catch(std::out_of_range& )
-      {
-        if(detNum==0)
-        {
-          g_log.error()<<"Error : The instrument does not have any RectangularDetectors "<<std::endl;
-        }
-        else if(detNum==1)
-        {
-          g_log.error()<<"Error : The instrument  have only one  RectangularDetector"<<std::endl;
-        }
-        return;
-      }
-      if(!rectDet)
-      {
-        g_log.error()<<"Error when accessing the details of rectangular detector"<<std::endl;
-        return;
-      }
-      std::vector<int> detIdList;
-      detIdList.push_back(rectDet->getMinimumDetcetorId());
-      detIdList.push_back(rectDet->getMaximumDetcetorId());
-      specList= mws_sptr->spectraMap().getSpectra(detIdList);
-     
-    }
-  /** This method returns the minimum and maximum spectrum ids
-    * @param specList - list of spectra.
-    * @param minSpec - minimum spectrum number
-    * @param maxSpec - maximum spectrum number
-    */
-    void SANSDiagnostics::minandMaxSpectrumIds(const std::vector<int>& specList,QString& minSpec, QString& maxSpec)
-    {      
-      int spec_min =*std::min_element(specList.begin(),specList.end());
-      int spec_max=*std::max_element(specList.begin(),specList.end());
-    
-      std::string s_min,s_max;
-      try
-      {
-        s_min = boost::lexical_cast<std::string >(spec_min);
-
-      }
-      catch(boost::bad_lexical_cast& )
-      {
-        g_log.error("Invalid Spectrum Minimum Number ");
-        return;
-      }
-      try
-      {
-        s_max  = boost::lexical_cast<std::string >(spec_max);
-      }
-      catch(boost::bad_lexical_cast&)
-      {
-        g_log.error("Invalid Spectrum Maximum Number ");
-        return;
-      }
-
-      minSpec=QString::fromStdString(s_min);
-      maxSpec=QString::fromStdString(s_max);
-      
-    }
-
-    /** This method returns workspace Indexes for the given spectrum indexes
-      * @param mws_sptr - shared pointer to workspace
-      * @param specList - list of spectra
-      * @param startWSIndex - start index of workspace
-      * @param endWSIndex  - end index of the workspace
-    */
-
-    void SANSDiagnostics::getWorkspaceIndexes(const Mantid::API::MatrixWorkspace_sptr& mws_sptr,
-                                              const std::vector<int>& specList,
-                                              QString& startWSIndex,QString& endWSIndex)
-    {      
-            
-      std::vector<int> wsindexList;
-      mws_sptr->getIndicesFromSpectra(specList,wsindexList);
-      std::string wsStart;
-      std::string wsEnd;
-      try
-      {        
-        wsStart= boost::lexical_cast<std::string>(wsindexList.at(0));
-        wsEnd = boost::lexical_cast<std::string>(wsindexList.at(1));
-      }
-      catch(boost::bad_lexical_cast&)
-      {
-        g_log.error()<<"Error: Invalid start / end workspace index"<<std::endl;
-      }
-      catch(std::out_of_range&)
-      {
-        g_log.error()<<"Error: Invalid start / end workspace index"<<std::endl;
-      }
-     
-      startWSIndex = QString::fromStdString(wsStart);
-      endWSIndex =  QString::fromStdString(wsEnd);
-          
-    }
-
-    //This method disables the rectangular detectors group boxes
-    void SANSDiagnostics::disableDetectorGroupBoxes(bool bStatus)
-    {
-      //disable the rectanglar detctors initially
-      m_SANSForm->groupBox_Detector1->setDisabled(bStatus);
-      m_SANSForm->groupBox_Detector2->setDisabled(bStatus);
-    }
-
-    /// This method returns the list of file names entered 
-    /// opened using browse in the file finder widget
-    QString SANSDiagnostics::getFileName()
-    {
-      //get the file name using the filefinder plugin
-      QString filename;
-      if(m_SANSForm->file_run_edit->isValid())
-      {
-        filename=m_SANSForm->file_run_edit->getFirstFilename();
-      }
-      if(filename.isEmpty())
-      {
-        return "";
-      }
-      return filename;
-    }
-
-  /**This method returns workspace name from the  file name 
-    * @param fileName name of the file
-    * @returns workspace name
-    */
-    QString SANSDiagnostics::getWorkspaceNameFileName(const QString& fileName)
-    {
-      //construct workspace name from the file name.
-      int index1=fileName.lastIndexOf(".");
-      if(index1==-1)
-      {        
-        return "";
-      }
-      int index2=fileName.lastIndexOf("/");
-      if(index2==-1)
-      {        
-        return "";
-      }
-      return fileName.mid(index2+1,index1-index2-1);
-    }
-
-    ///This method returns name of the   workspace which is to be
-    /// used as the i/p  for sumrowcolumn or sumspectra algorithm 
-    QString SANSDiagnostics::getWorkspaceToProcess()
-    {
-      QString wsName;
-      //if the load algorithm created workspace is group workspace
-      // return the workspace corresponding to  user selected workspace.
-      if(isMultiPeriod())
-      {
-        wsName=m_memberwsName;
-      }
-      else
-      {
-        wsName=m_outws_load;
-      }
-      return wsName;
-    }
-
-
-  /**This method checks the spec min and are in valid range
-    * @param specMin - minimum spectrum number
-    * @param specMax - maximum spectrum number
-    * @returns true if the spectra is in valid range.
-    */
-    bool SANSDiagnostics::isValidSpectra(const QString& specMin,const QString& specMax)
-    {
-      int spec_min=0;
-      int spec_max=0;
-      try
-      {
-        spec_min=boost::lexical_cast<int>(specMin.toStdString());
-        spec_max=boost::lexical_cast<int>(specMax.toStdString());
-      }
-      catch(boost::bad_lexical_cast&)
-      {
-        g_log.error()<<"Inavlid spectrum number found in  the selected detector bank "<<std::endl;
-        return false;
-      }
-      if(spec_min<1 )
-      {
-        g_log.error()<<"Inavlid spectrum minimum "+specMin.toStdString()+ " 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;
-                                                                          
-      }
-      return ((spec_min>=1 && spec_max<=Mantid::EMPTY_INT())?true:false);
-    }
-
-
-    /// Handler for first detector horizontal integral button
-    void SANSDiagnostics::firstDetectorHorizontalIntegralClicked()
-    {           
-      QString orientation("D_H");
-      QString minSpec;
-      QString maxSpec;
-      int detNum=0;//first detector
-
-      QString ipwsName= getWorkspaceToProcess();
-      Mantid::API::Workspace_sptr ws_sptr;
-      try
-      {
-        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(ipwsName.toStdString());
-
-      }
-      catch(Exception::NotFoundError&)
-      {
-        g_log.error()<<"Error when accessing the Workspace "+ipwsName.toStdString()<<std::endl;
-        return;
-
-      }
-      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
-      if(!mws_sptr)
-      {
-        return;
-      }
-      std::vector<int> specList;
-      getSpectraList(mws_sptr,detNum,specList);
-      minandMaxSpectrumIds(specList,minSpec,maxSpec);
-      if(!isValidSpectra(minSpec,maxSpec))
-      {
-        m_SANSForm->groupBox_Detector1->setDisabled(true);
-        return;
-      } 
-      
-      QString detName= getDetectorName(0);
-      //give the detectorname_H for workspace
-      detName+="_H";
-      const QString opws(detName);
-      ///horizontal integral range string
-      QString hiRange=m_SANSForm->hirange_edit1->text();
-     
-      IntegralClicked(hiRange,orientation,minSpec,maxSpec,opws,m_SANSForm->tcmask1->isChecked(),true);
-         
-    }
-
-    /// Handler for first detector vertical integral button
-    void SANSDiagnostics::firstDetectorVerticalIntegralClicked()
-    {
-      QString orientation("D_V");
-      QString minSpec;
-      QString maxSpec;
-      int detNum=0;//first detector
-     
-      QString ipwsName= getWorkspaceToProcess();
-      Mantid::API::Workspace_sptr ws_sptr;
-      try
-      {
-        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(ipwsName.toStdString());
-
-      }
-      catch(Exception::NotFoundError&)
-      {
-        g_log.error()<<"Error when accessing the Workspace "+ipwsName.toStdString()<<std::endl;
-        return;
-
-      }
-      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
-      if(!mws_sptr)
-      {
-        return;
-      }
-
-      std::vector<int> specList;
-      getSpectraList(mws_sptr,detNum,specList);
-      minandMaxSpectrumIds(specList,minSpec,maxSpec);
-
-      if(!isValidSpectra(minSpec,maxSpec))
-      {
-        m_SANSForm->groupBox_Detector1->setDisabled(true);
-        return;
-      }
-      QString detName= getDetectorName(0);
-      //give the detectorname_V for workspace
-      detName+="_V";
-      QString opws(detName);
-      ///horizontal integral range string
-      QString viRange=m_SANSForm->virange_edit1->text();
-      
-      IntegralClicked(viRange,orientation,minSpec,maxSpec,opws,m_SANSForm->tcmask2->isChecked(),true);
-
-    }
-
-
-    /// Handler for first detector time integral button
-    void SANSDiagnostics::firstDetectorTimeIntegralClicked()
-    {
-      int detNum=0;//first detector
-      QString minSpec;
-      QString maxSpec;
-     
-      QString ipwsName= getWorkspaceToProcess();
-      Mantid::API::Workspace_sptr ws_sptr;
-      try
-      {
-        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(ipwsName.toStdString());
-
-      }
-      catch(Exception::NotFoundError&)
-      {
-        g_log.error()<<"Error when accessing the Workspace "+ipwsName.toStdString()<<std::endl;
-        return;
-
-      }
-      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
-      if(!mws_sptr)
-      {
-        return;
-      }
-
-      std::vector<int> specList;
-      getSpectraList(mws_sptr,detNum,specList);
-      minandMaxSpectrumIds(specList,minSpec,maxSpec);
-      QString wsStartIndex, wsEndIndex;
-      
-      if(!isValidSpectra(minSpec,maxSpec))
-      {
-        m_SANSForm->groupBox_Detector1->setDisabled(true);
-        return;
-      }
-      /// now run the load algorithm with the spec_min and spec_max
-      if(!runLoadAlgorithm(m_fileName,minSpec,maxSpec))
-      {
-        return;
-      }
-
-      QString loadedws=getWorkspaceToProcess(); 
-      Mantid::API::Workspace_sptr loadedws_sptr;
-      try
-      {
-        loadedws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(loadedws.toStdString());
-
-      }
-      catch(Exception::NotFoundError&)
-      {
-        g_log.error()<<"Error when accessing the Workspace "+loadedws.toStdString()<<std::endl;
-        return;
-
-      }
-      Mantid::API::MatrixWorkspace_sptr mws_sptr1=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(loadedws_sptr);
-      if(!mws_sptr1)
-      {
-        return;
-      }
-      //get the workspace index from spectra list
-      getWorkspaceIndexes(mws_sptr1,specList,wsStartIndex,wsEndIndex);
-      
-      //apply mask
-      maskDetector(loadedws,m_SANSForm->pmask1->isChecked(),false);
-      
-      QString detName= getDetectorName(0);
-      //give the detectorname_V for workspace
-      detName+="_T";
-      QString opws(detName);
-           
-      //execute SumSpectra 
-      if(!runsumSpectra(loadedws,opws,wsStartIndex,wsEndIndex))
-      {
-        return;
-      }
-     
-      QString plotws = "\"" + opws +"\"";
-      plotSpectrum(plotws,0);
-    }
-
-
-
-   /**This method gets called from the handler of Vertical/Horizontal Integral button click.
-    * executes LoadRaw and SumRowColumn algorithm.
-    * @param range string entered by user
-    * @param orientation orientation
-    * @param specMin- minimum spectrum index
-    * @param specMax - maximum spectrum index
-    * @param opws - output workspace.
-    * @param bMask boolean used for masking
-    * @param time_pixel true if time masking,false if pixel mask
-    */
-    void SANSDiagnostics::IntegralClicked(const QString& range,const QString& orientation,
-      const QString& specMin,const QString& specMax,const QString& opws,bool bMask,bool time_pixel)
-    {
-      /// now run the load algorithm with the spec_min and spec_max
-      if(!runLoadAlgorithm(m_fileName,specMin,specMax))
-      {
-        return;
-      } 
-      //get the workspace name
-      QString loadedws = getWorkspaceToProcess(); 
-            
-      //aplly mask
-      if(bMask)
-      {
-        maskDetector(loadedws,bMask,time_pixel);
-      }
-    
-      if(range.isEmpty())
-      {        
-        QString HVMin,HVMax;
-        HVMinHVMaxStringValues(Mantid::EMPTY_INT(),Mantid::EMPTY_INT(),HVMin,HVMax);
-        if(!runsumRowColumn(loadedws,opws,orientation,HVMin,HVMax))
-        {
-          return ;
-        }
-        QString plotws = "\"" + opws +"\"";
-        plotSpectrum(plotws,0);
-        return;
-      }
-      //parse the range string
-      int count=0;
-      UserStringParser parser;
-      std::vector<std::vector<unsigned int> > parsedVals;
-      try
-      {
-        parsedVals=parser.parse(range.toStdString());
-      }
-      catch(std::runtime_error& e)
-      {
-        g_log.error(e.what());
-        return;
-      }
-      catch(std::out_of_range& e)
-      {
-        g_log.error(e.what());
-        return;
-      }
-           
-      QString wsPlotString;
-      //loop through each element of the parsed value vector
-      std::vector<std::vector<unsigned int> >::const_iterator parsedValcitr;
-      for(parsedValcitr=parsedVals.begin();parsedValcitr!=parsedVals.end();++parsedValcitr)
-      {
-        if((*parsedValcitr).empty())
-        {
-          return;
-        }
-        //check the vector contains sequential vales.
-        if(!isSequentialValues((*parsedValcitr)))
-        {
-          g_log.error("Values between H/V_Min and H/V_Max in the Range string  are not sequential ");
-          return ;
-        }
-        //first value in the vector  is the HVmin
-        int min=(*parsedValcitr).at(0);
-        int max;
-        ///last value is HVMax
-        if((*parsedValcitr).size()>1)
-        {
-          max=(*parsedValcitr).at((*parsedValcitr).size()-1);
-        }
-        else
-        {
-          //if the vector contains only one value HVMax=HVMin
-          max=min;
-        }
-
-        QString HVMin,HVMax;
-        HVMinHVMaxStringValues(min,max,HVMin,HVMax);
-        
-        ++count;
-        std::stringstream num;
-        num<<count;
-        QString outputwsname=opws+QString::fromStdString(num.str());
-
-        //now execute sumrowcolumn with hvmin and havmax from the first and last vales from the vector
-        if(!runsumRowColumn(loadedws,outputwsname,orientation,HVMin,HVMax))
-        {
-          return ;
-        }
-               
-        wsPlotString+="\"";
-        wsPlotString+=outputwsname;
-        wsPlotString+="\"";
-        wsPlotString+=",";
-      }
-
-      //remove the last comma
-      int index=wsPlotString.lastIndexOf(",");
-      wsPlotString.remove(index,1);
-  
-      //plot the zeroth spectrum for all the workspaces created.
-      int specNum=0;
-      plotSpectrum(wsPlotString,specNum);
-    
-    }
-
-    /** Get values of HVMin and HvMax values for sumrowcolumn algorithm
-      * @param minVal spectrum min value
-      * @param maxVal spectrum maximum value
-      * @param hvMin  spectrum min string
-      * @param hvMax  spectrum max string
-    */
-    void SANSDiagnostics::HVMinHVMaxStringValues(const int minVal,const int maxVal,QString& hvMin,QString& hvMax)
-    {
-      try
-      {
-        //first value in the vector 
-        hvMin=QString::fromStdString(boost::lexical_cast<std::string>(minVal));
-        ///last value is HVMax
-        hvMax=QString::fromStdString(boost::lexical_cast<std::string>(maxVal));
-      }
-      catch(boost::bad_lexical_cast& )
-      {
-        g_log.error("Error when getting the H/V_Min and H/V_Max value from the Range string ");
-      }
-      
-    }
-
-   /** This method applys time channel masks to the detector bank selected.
-      * @param wsName - name of the workspace.
-      * @param bMask - boolean flag to indicate the mask check box selected
-      */
-    void SANSDiagnostics::maskDetector(const QString& wsName,bool bMask,bool time_pixel)
-    {
-      //if  mask control selected
-      if(bMask)
-      {
-        emit applyMask(wsName,time_pixel);
-      }
-    }
-
-  /**This method plots spectrum for the given workspace
-    * @param wsName - name of the workspace
-    * @param specNum - spectrum number
-    */ 
-    void SANSDiagnostics::plotSpectrum(const QString& wsName,int specNum)
-    {      
-      QString plotspec="plotSpectrum([";
-      plotspec+=wsName;
-      plotspec+="],";
-      plotspec+=QString::number(specNum);
-      plotspec+=")";
-      runPythonCode(plotspec);
-    }
-
-    /// Handler for second detector horizontal integral button
-    void SANSDiagnostics::secondDetectorHorizontalIntegralClicked()
-    {
-      QString orientation("D_H");
-      QString minSpec;
-      QString maxSpec;
-      int detNum=1;//second detector
-      
-      QString ipwsName= getWorkspaceToProcess();
-      Mantid::API::Workspace_sptr ws_sptr;
-      try
-      {
-        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(ipwsName.toStdString());
-
-      }
-      catch(Exception::NotFoundError&)
-      {
-        g_log.error()<<"Error when accessing the Workspace "+ipwsName.toStdString()<<std::endl;
-        return;
-
-      }
-      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
-      if(!mws_sptr)
-      {
-        return;
-      }
-      
-      std::vector<int> specList;
-      getSpectraList(mws_sptr,detNum,specList);
-      minandMaxSpectrumIds(specList,minSpec,maxSpec);
-       
-      if(!isValidSpectra(minSpec,maxSpec))
-      {
-        m_SANSForm->groupBox_Detector2->setDisabled(true);
-        return;
-      }
-      QString detName= getDetectorName(detNum);
-      //give the detectorname_H for workspace
-      detName+="_H";
-      QString opws(detName);
-      ///horizontal integral range string
-      QString hiRange=m_SANSForm->hirange_edit2->text();
-      IntegralClicked(hiRange,orientation,minSpec,maxSpec,opws,m_SANSForm->tcmask3->isChecked(),true);
-
-    }
-    /// Handler for second detector horizontal integral button
-    void SANSDiagnostics::secondDetectorVerticalIntegralClicked()
-    {      
-      QString orientation("D_V");
-      QString minSpec;
-      QString maxSpec;
-      int detNum=1;//first detector
-
-      QString ipwsName= getWorkspaceToProcess();
-      Mantid::API::Workspace_sptr ws_sptr;
-      try
-      {
-        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(ipwsName.toStdString());
-
-      }
-      catch(Exception::NotFoundError&)
-      {
-        g_log.error()<<"Error when accessing the Workspace "+ipwsName.toStdString()<<std::endl;
-        return;
-
-      }
-      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
-      if(!mws_sptr)
-      {
-        return;
-      }
-
-      std::vector<int> specList;
-      getSpectraList(mws_sptr,detNum,specList);
-      minandMaxSpectrumIds(specList,minSpec,maxSpec);
-      if(!isValidSpectra(minSpec,maxSpec))
-      {
-        m_SANSForm->groupBox_Detector2->setDisabled(true);
-        return;
-      }
-      QString detName= getDetectorName(detNum);
-      //give the detectorname_H for workspace
-      detName+="_V";
-      QString opws(detName);
-
-      ///horizontal integral range string
-      QString viRange=m_SANSForm->virange_edit2->text();
-      IntegralClicked(viRange,orientation,minSpec,maxSpec,opws,m_SANSForm->tcmask4->isChecked(),true);
-    }
-    /// Handler for second detector horizontal integral button
-    void SANSDiagnostics::secondDetectorTimeIntegralClicked()
-    {
-      //second detector
-      int detNum=1;
-      QString minSpec;
-      QString maxSpec;
-
-      //Get the workspace created by load algorithm initially with specmin=1 and specmax=1
-      QString initialwsName= getWorkspaceToProcess();
-      Mantid::API::Workspace_sptr ws_sptr;
-      try
-      {
-        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(initialwsName.toStdString());
-      }
-      catch(Exception::NotFoundError&)
-      {
-        g_log.error()<<"Error when accessing the Workspace "+initialwsName.toStdString()<<std::endl;
-        return;
-      }
-      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
-      if(!mws_sptr)
-      {
-        return;
-      }
-            
-      std::vector<int> specList;
-      //get spectrum list from detector ids
-      getSpectraList(mws_sptr,detNum,specList);
-      // get maximum and minimum spectrum ids
-      minandMaxSpectrumIds(specList,minSpec,maxSpec);
-      QString wsStartIndex, wsEndIndex;
-      //   
-      if(!isValidSpectra(minSpec,maxSpec))
-      {
-        m_SANSForm->groupBox_Detector2->setDisabled(true);
-        return;
-      }
-      /// now run the load algorithm with the spec_min and spec_max
-      if(!runLoadAlgorithm(m_fileName,minSpec,maxSpec))
-      {
-        return;
-      } 
-      //Get the workspace created by load algorithm  with spec_min and specmax for the detectors
-      QString loadedws= getWorkspaceToProcess();
-      //apply mask
-      maskDetector(loadedws,m_SANSForm->pmask2->isChecked(),false);
-    
-      Mantid::API::Workspace_sptr loadedws_sptr;
-      try
-      {
-        loadedws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(loadedws.toStdString());
-
-      }
-      catch(Exception::NotFoundError&)
-      {
-        g_log.error()<<"Error when accessing the Workspace "+loadedws.toStdString()<<std::endl;
-        return;
-
-      }
-      Mantid::API::MatrixWorkspace_sptr mloadedws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(loadedws_sptr);
-      if(!loadedws_sptr)
-      {
-        return;
-      }
-      //get workspace indexes
-      getWorkspaceIndexes(mloadedws_sptr,specList,wsStartIndex,wsEndIndex);
-      
-      QString detName= getDetectorName(1);
-      //give the detectorname_V for workspace
-      detName+="_T";
-      QString opws(detName);
-      //execute SumSpectra 
-     if(!runsumSpectra(loadedws,opws,wsStartIndex,wsEndIndex))
-     {
-       return;
-     }
-
-     QString plotws = "\"" + opws +"\"";
-     plotSpectrum(plotws,0);
-
-    }
-
-    
-    /// get the total number of periods in the loaded raw/nexus file
-    int SANSDiagnostics::getTotalNumberofPeriods()
-    {
-      Mantid::API::Workspace_sptr ws_sptr;
-      try
-      {
-        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(m_outws_load.toStdString());
-
-      }
-      catch(Exception::NotFoundError&)
-      {
-        g_log.error()<<"Error: when accessing the workspace "<<m_outws_load.toStdString()<<std::endl;
-        return 0;
-      }
-      if(Mantid::API::WorkspaceGroup_sptr wsgrp_sptr=boost::dynamic_pointer_cast<WorkspaceGroup>(ws_sptr))
-      {
-        return wsgrp_sptr->getNumberOfEntries();
-      }
-      return 1;
-    }
-    /// This method loads last saved settings values from registry
-    void SANSDiagnostics::loadSettings()
-    {
-     
-      QSettings settings;
-      m_settingsGroup = "CustomInterfaces/SANSRunWindow/SANSDiagnostics";
-      settings.beginGroup(m_settingsGroup);
-      m_SANSForm->file_run_edit->readSettings(settings.group());
-      settings.endGroup();
-    }
-
-    ///save settings
-    void SANSDiagnostics::saveSettings()
-    {
-      m_dataDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("datasearch.directories"));
-      m_dataDir = m_dataDir.split(";", QString::SkipEmptyParts)[0];
-      QSettings settings;
-      m_settingsGroup="CustomInterfaces/SANSRunWindow/SANSDiagnostics";
-      settings.beginGroup(m_settingsGroup);
-      settings.setValue("last_directory", m_dataDir);
-      settings.setValue("File",getFileName());
-      settings.endGroup();
-      m_SANSForm->file_run_edit->saveSettings(settings.group());
-      
-    }
-
-    /**Execute sumrowcolumn algorithm 
-    * @param values a vector containing the values for hvmin,hvmax
-    * @param periodNum - number of the  period to load
-    * @param ipws - name of the i/p workspace
-    * @param opws - name of the o/p workspace
-    * @param orientation - orientation of the detector
-    */
-    bool SANSDiagnostics::executeSumRowColumn(const std::vector<unsigned int>& values,
-      const QString ipws,const QString& opws,const QString& orientation)
-    {      
-      if(values.empty())
-      {
-        return false ;
-      }
-
-      QString HVMin;
-      QString HVMax; 
-      //check the vector contains sequential vales.
-      if(!isSequentialValues(values))
-      {
-        g_log.error("Values between HVMin and HVMax in the Range string  are not sequential ");
-        return false;
-      }
-      try
-      {
-        //first value in the vector 
-        HVMin=QString::fromStdString(boost::lexical_cast<std::string>(values.at(0)));
-        ///last value is HVMax
-        if(values.size()>1)
-        {
-          HVMax=QString::fromStdString(boost::lexical_cast<std::string>(values.at(values.size()-1)));
-        }
-        else
-        {
-          //if the vector contains only one value HVMax=HVMin
-          HVMax=HVMin;
-        }
-      }
-      catch(boost::bad_lexical_cast& )
-      {
-      }
-      catch(std::out_of_range& )
-      {
-      }
-      //now execute sumrowcolumn with hvmin and havmax from the first and last vales from the vector
-      if(!runsumRowColumn(ipws,opws,orientation,HVMin,HVMax))
-      {
-        return false;
-      }
-      return true;
-    }
-
-  /**Execute sumrowcolumn algorithm with the vales
-    * @param ipwsName name of the input workspace
-    * @param opwsName name of the output workspace
-    * @param orientation indicates row or columns to sum
-    * @param hvMin minimum value of
-    * @param hvMax
-    */
-    bool SANSDiagnostics::runsumRowColumn(const QString ipwsName,const QString& opwsName,
-      const QString& orientation,const QString& hvMin,const QString& hvMax)
-    {
-
-       Mantid::API::Workspace_sptr ws_sptr;
-      try
-      {
-        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(ipwsName.toStdString());
-
-      }
-      catch(Exception::NotFoundError&)
-      {
-        g_log.error()<<"Error when  trying to access the workspace "<<ipwsName.toStdString()<<" which is not loaded"<<std::endl;
-        return false;
-      }
-      if(opwsName.isEmpty())
-      {
-         g_log.error()<<"Output workspace name is empty , can't create workspace 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;
-         return false;
-      }
-      if(hvMax.isEmpty())
-      {
-         g_log.error()<<"Error when executing SumRowColumn algorithm :Empty H/V_Max String value "<<std::endl;
-         return false;
-      }
-
-      QString code=
-        "try:\n"
-        "  SumRowColumn('";
-      code+=ipwsName;
-      code+="', '";
-      code+=opwsName;
-      code+="', '";
-      code+=orientation;
-      code+="', ";
-      code+="HVMin=";
-      code+=hvMin;
-      code+=",";
-      code+="HVMax=";
-      code+=hvMax;
-      code+=")\n";
-      code+="except:\n";
-      code+="  print 'Failure'";
-
-      QString ret= runPythonCode(code.trimmed());
-      if(!ret.isEmpty())
-      {
-        g_log.error()<<"Error when executing the SumRowColumn algorithm "<<ret.toStdString()<<std::endl;
-        return false;
-      }
-      return true;
-    }
-
-  /** This method creates script string for sumspectra algorithm
-    * @param ipwsName - name of the input workspace
-    * @param opwsName - name of the ooutput workspace
-    * @param wsStartIndex - start workspace index
-    * @param wsEndIndex - end workspace Index
-    * @returns - sumspectra script string
-    */
-    bool  SANSDiagnostics::runsumSpectra(const QString& ipwsName,const QString& opwsName,const QString& wsStartIndex,const QString& wsEndIndex)
-    {
-      
-      if(opwsName.isEmpty())
-      {
-         g_log.error()<<"Output workspace name is empty , can't create workspace with empty name"<<std::endl;
-         return false;
-      }
-
-      if(wsStartIndex.isEmpty())
-      {
-        g_log.error()<<"Error: Invalid StartWorkspaceIndex"<<std::endl;
-        return false;
-      }
-      if(wsEndIndex.isEmpty())
-      {
-        g_log.error()<<"Error Invalid EndWorkspaceIndex"<<std::endl;
-        return false;
-      }
-           
-      QString code=
-        "try:\n"
-        "  SumSpectra(\"";
-      code+=ipwsName;
-      code+="\",\"";
-      code+=opwsName;
-      code+="\",";
-      code+="StartWorkspaceIndex=";
-      code+=wsStartIndex;
-      code+=",";
-      code+="EndWorkspaceIndex=";
-      code+=wsEndIndex;
-      code+=")\n";
-      code+="except:\n";
-      code+="  print 'Failure'"; 
-     
-      QString ret= runPythonCode(code.trimmed());
-      if(!ret.isEmpty())
-      {
-        g_log.error()<<"Error when executing the SumSpectra algorithm "<<ret.toStdString()<<std::endl;
-        return false;
-      }
-      return true;
-    }
-
-
-  /**This method executes load algorithm with filename,specmin,specmax
-    * @param fileName - name of the file
-    * @param specMin  - spectrum minimum
-    * @param specMax  - spectrum maximum
-    */
-    bool SANSDiagnostics::runLoadAlgorithm(const QString& fileName,const QString& specMin,const QString& specMax)
-    {
-
-      if(fileName.isEmpty()) return false;
-      //get the output workspace for load algorithm from file name
-      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;
-         return false;
-      }
-        
-      QString load=
-        "try:\n"
-        "  Load('";
-      load+=fileName;
-      load+="','";
-      load+=m_outws_load;
-      load+="',";
-      load+="SpectrumMin=";
-      load+=specMin;
-      load+=",";
-      load+="SpectrumMax=";
-      load+=specMax;
-      load+=")\n";
-      load+="except:\n";
-      load+="  print 'Failure'"; 
-      QString ret= runPythonCode(load.trimmed());
-      if(!ret.isEmpty())
-      {
-        g_log.error()<<"Error when executing the Load algorithm "<<std::endl;
-        return false;
-      }
-      return true;
-    }
-    /**Checks the values in the given vector is sequential
-    * @param values  vector containing numbers
-    * @returns true if the vector is sequential
-    */
-    bool SANSDiagnostics::isSequentialValues(const std::vector<unsigned int>& values)
-    {
-      try
-      {
-        unsigned int startVal=values.at(0);
-        std::vector<unsigned int>::const_iterator citr;
-        for(int i=1;i<values.size();++i)
-        {
-          if(values.at(i)==startVal+1)
-          {
-            startVal=values.at(i);
-          }
-          else
-          {
-            return false;
-          }
-
-        }
-
-      }
-      catch(std::out_of_range&)
-      {
-        g_log.error("Error when executing SumRowColumn Algorithm" );
-        return false;
-      }
-      return true;
-    }
-    
-  /** This method enables the mask controls in teh diagnostics UI
-    */
-    void  SANSDiagnostics::enableMaskFileControls()
-    {
-      //enable time and pixel check masks
-      m_SANSForm->tcmask1->setEnabled(true);
-      m_SANSForm->tcmask2->setEnabled(true);
-      m_SANSForm->pmask1->setEnabled(true);
-      m_SANSForm->tcmask3->setEnabled(true);
-      m_SANSForm->tcmask4->setEnabled(true);
-      m_SANSForm->pmask2->setEnabled(true);
-    }
-
-  }
+          }
+        }
+      }
+      return rectDetectors;
+    }
+
+  /** This method returns spectrum list for the selected detector
+    * @param mws_sptr shared pointer to workspace
+    * @param detNum number used to identify detector
+    * @param specList  -list of spectrum
+    */
+    void SANSDiagnostics::getSpectraList(const Mantid::API::MatrixWorkspace_sptr& mws_sptr,const int detNum,std::vector<int>&specList)
+    {
+      boost::shared_ptr<RectDetectorDetails> rectDet;
+      try
+      {
+        rectDet= m_rectDetectors.at(detNum);
+      }
+      catch(std::out_of_range& )
+      {
+        if(detNum==0)
+        {
+          g_log.error()<<"Error : The instrument does not have any RectangularDetectors "<<std::endl;
+        }
+        else if(detNum==1)
+        {
+          g_log.error()<<"Error : The instrument  have only one  RectangularDetector"<<std::endl;
+        }
+        return;
+      }
+      if(!rectDet)
+      {
+        g_log.error()<<"Error when accessing the details of rectangular detector"<<std::endl;
+        return;
+      }
+      std::vector<int> detIdList;
+      detIdList.push_back(rectDet->getMinimumDetcetorId());
+      detIdList.push_back(rectDet->getMaximumDetcetorId());
+      specList= mws_sptr->spectraMap().getSpectra(detIdList);
+     
+    }
+  /** This method returns the minimum and maximum spectrum ids
+    * @param specList - list of spectra.
+    * @param minSpec - minimum spectrum number
+    * @param maxSpec - maximum spectrum number
+    */
+    void SANSDiagnostics::minandMaxSpectrumIds(const std::vector<int>& specList,QString& minSpec, QString& maxSpec)
+    {      
+      int spec_min =*std::min_element(specList.begin(),specList.end());
+      int spec_max=*std::max_element(specList.begin(),specList.end());
+    
+      std::string s_min,s_max;
+      try
+      {
+        s_min = boost::lexical_cast<std::string >(spec_min);
+
+      }
+      catch(boost::bad_lexical_cast& )
+      {
+        g_log.error("Invalid Spectrum Minimum Number ");
+        return;
+      }
+      try
+      {
+        s_max  = boost::lexical_cast<std::string >(spec_max);
+      }
+      catch(boost::bad_lexical_cast&)
+      {
+        g_log.error("Invalid Spectrum Maximum Number ");
+        return;
+      }
+
+      minSpec=QString::fromStdString(s_min);
+      maxSpec=QString::fromStdString(s_max);
+      
+    }
+
+    /** This method returns workspace Indexes for the given spectrum indexes
+      * @param mws_sptr - shared pointer to workspace
+      * @param specList - list of spectra
+      * @param startWSIndex - start index of workspace
+      * @param endWSIndex  - end index of the workspace
+    */
+
+    void SANSDiagnostics::getWorkspaceIndexes(const Mantid::API::MatrixWorkspace_sptr& mws_sptr,
+                                              const std::vector<int>& specList,
+                                              QString& startWSIndex,QString& endWSIndex)
+    {      
+            
+      std::vector<int> wsindexList;
+      mws_sptr->getIndicesFromSpectra(specList,wsindexList);
+      std::string wsStart;
+      std::string wsEnd;
+      try
+      {        
+        wsStart= boost::lexical_cast<std::string>(wsindexList.at(0));
+        wsEnd = boost::lexical_cast<std::string>(wsindexList.at(1));
+      }
+      catch(boost::bad_lexical_cast&)
+      {
+        g_log.error()<<"Error: Invalid start / end workspace index"<<std::endl;
+      }
+      catch(std::out_of_range&)
+      {
+        g_log.error()<<"Error: Invalid start / end workspace index"<<std::endl;
+      }
+     
+      startWSIndex = QString::fromStdString(wsStart);
+      endWSIndex =  QString::fromStdString(wsEnd);
+          
+    }
+
+    //This method disables the rectangular detectors group boxes
+    void SANSDiagnostics::disableDetectorGroupBoxes(bool bStatus)
+    {
+      //disable the rectanglar detctors initially
+      m_SANSForm->groupBox_Detector1->setDisabled(bStatus);
+      m_SANSForm->groupBox_Detector2->setDisabled(bStatus);
+    }
+
+    /// This method returns the list of file names entered 
+    /// opened using browse in the file finder widget
+    QString SANSDiagnostics::getFileName()
+    {
+      //get the file name using the filefinder plugin
+      QString filename;
+      if(m_SANSForm->file_run_edit->isValid())
+      {
+        filename=m_SANSForm->file_run_edit->getFirstFilename();
+      }
+      if(filename.isEmpty())
+      {
+        return "";
+      }
+      return filename;
+    }
+
+  /**This method returns workspace name from the  file name 
+    * @param fileName name of the file
+    * @returns workspace name
+    */
+    QString SANSDiagnostics::getWorkspaceNameFileName(const QString& fileName)
+    {
+      //construct workspace name from the file name.
+      int index1=fileName.lastIndexOf(".");
+      if(index1==-1)
+      {        
+        return "";
+      }
+      int index2=fileName.lastIndexOf("/");
+      if(index2==-1)
+      {        
+        return "";
+      }
+      return fileName.mid(index2+1,index1-index2-1);
+    }
+
+    ///This method returns name of the   workspace which is to be
+    /// used as the i/p  for sumrowcolumn or sumspectra algorithm 
+    QString SANSDiagnostics::getWorkspaceToProcess()
+    {
+      QString wsName;
+      //if the load algorithm created workspace is group workspace
+      // return the workspace corresponding to  user selected workspace.
+      if(isMultiPeriod())
+      {
+        wsName=m_memberwsName;
+      }
+      else
+      {
+        wsName=m_outws_load;
+      }
+      return wsName;
+    }
+
+
+  /**This method checks the spec min and are in valid range
+    * @param specMin - minimum spectrum number
+    * @param specMax - maximum spectrum number
+    * @returns true if the spectra is in valid range.
+    */
+    bool SANSDiagnostics::isValidSpectra(const QString& specMin,const QString& specMax)
+    {
+      int spec_min=0;
+      int spec_max=0;
+      try
+      {
+        spec_min=boost::lexical_cast<int>(specMin.toStdString());
+        spec_max=boost::lexical_cast<int>(specMax.toStdString());
+      }
+      catch(boost::bad_lexical_cast&)
+      {
+        g_log.error()<<"Inavlid spectrum number found in  the selected detector bank "<<std::endl;
+        return false;
+      }
+      if(spec_min<1 )
+      {
+        g_log.error()<<"Inavlid spectrum minimum "+specMin.toStdString()+ " 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;
+                                                                          
+      }
+      return ((spec_min>=1 && spec_max<=Mantid::EMPTY_INT())?true:false);
+    }
+
+
+    /// Handler for first detector horizontal integral button
+    void SANSDiagnostics::firstDetectorHorizontalIntegralClicked()
+    {           
+      QString orientation("D_H");
+      QString minSpec;
+      QString maxSpec;
+      int detNum=0;//first detector
+
+      QString ipwsName= getWorkspaceToProcess();
+      Mantid::API::Workspace_sptr ws_sptr;
+      try
+      {
+        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(ipwsName.toStdString());
+
+      }
+      catch(Exception::NotFoundError&)
+      {
+        g_log.error()<<"Error when accessing the Workspace "+ipwsName.toStdString()<<std::endl;
+        return;
+
+      }
+      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
+      if(!mws_sptr)
+      {
+        return;
+      }
+      std::vector<int> specList;
+      getSpectraList(mws_sptr,detNum,specList);
+      minandMaxSpectrumIds(specList,minSpec,maxSpec);
+      if(!isValidSpectra(minSpec,maxSpec))
+      {
+        m_SANSForm->groupBox_Detector1->setDisabled(true);
+        return;
+      } 
+      
+      QString detName= getDetectorName(0);
+      //give the detectorname_H for workspace
+      detName+="_H";
+      const QString opws(detName);
+      ///horizontal integral range string
+      QString hiRange=m_SANSForm->hirange_edit1->text();
+     
+      IntegralClicked(hiRange,orientation,minSpec,maxSpec,opws,m_SANSForm->tcmask1->isChecked(),true);
+         
+    }
+
+    /// Handler for first detector vertical integral button
+    void SANSDiagnostics::firstDetectorVerticalIntegralClicked()
+    {
+      QString orientation("D_V");
+      QString minSpec;
+      QString maxSpec;
+      int detNum=0;//first detector
+     
+      QString ipwsName= getWorkspaceToProcess();
+      Mantid::API::Workspace_sptr ws_sptr;
+      try
+      {
+        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(ipwsName.toStdString());
+
+      }
+      catch(Exception::NotFoundError&)
+      {
+        g_log.error()<<"Error when accessing the Workspace "+ipwsName.toStdString()<<std::endl;
+        return;
+
+      }
+      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
+      if(!mws_sptr)
+      {
+        return;
+      }
+
+      std::vector<int> specList;
+      getSpectraList(mws_sptr,detNum,specList);
+      minandMaxSpectrumIds(specList,minSpec,maxSpec);
+
+      if(!isValidSpectra(minSpec,maxSpec))
+      {
+        m_SANSForm->groupBox_Detector1->setDisabled(true);
+        return;
+      }
+      QString detName= getDetectorName(0);
+      //give the detectorname_V for workspace
+      detName+="_V";
+      QString opws(detName);
+      ///horizontal integral range string
+      QString viRange=m_SANSForm->virange_edit1->text();
+      
+      IntegralClicked(viRange,orientation,minSpec,maxSpec,opws,m_SANSForm->tcmask2->isChecked(),true);
+
+    }
+
+
+    /// Handler for first detector time integral button
+    void SANSDiagnostics::firstDetectorTimeIntegralClicked()
+    {
+      int detNum=0;//first detector
+      QString minSpec;
+      QString maxSpec;
+     
+      QString ipwsName= getWorkspaceToProcess();
+      Mantid::API::Workspace_sptr ws_sptr;
+      try
+      {
+        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(ipwsName.toStdString());
+
+      }
+      catch(Exception::NotFoundError&)
+      {
+        g_log.error()<<"Error when accessing the Workspace "+ipwsName.toStdString()<<std::endl;
+        return;
+
+      }
+      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
+      if(!mws_sptr)
+      {
+        return;
+      }
+
+      std::vector<int> specList;
+      getSpectraList(mws_sptr,detNum,specList);
+      minandMaxSpectrumIds(specList,minSpec,maxSpec);
+      QString wsStartIndex, wsEndIndex;
+      
+      if(!isValidSpectra(minSpec,maxSpec))
+      {
+        m_SANSForm->groupBox_Detector1->setDisabled(true);
+        return;
+      }
+      /// now run the load algorithm with the spec_min and spec_max
+      if(!runLoadAlgorithm(m_fileName,minSpec,maxSpec))
+      {
+        return;
+      }
+
+      QString loadedws=getWorkspaceToProcess(); 
+      Mantid::API::Workspace_sptr loadedws_sptr;
+      try
+      {
+        loadedws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(loadedws.toStdString());
+
+      }
+      catch(Exception::NotFoundError&)
+      {
+        g_log.error()<<"Error when accessing the Workspace "+loadedws.toStdString()<<std::endl;
+        return;
+
+      }
+      Mantid::API::MatrixWorkspace_sptr mws_sptr1=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(loadedws_sptr);
+      if(!mws_sptr1)
+      {
+        return;
+      }
+      //get the workspace index from spectra list
+      getWorkspaceIndexes(mws_sptr1,specList,wsStartIndex,wsEndIndex);
+      
+      //apply mask
+      maskDetector(loadedws,m_SANSForm->pmask1->isChecked(),false);
+      
+      QString detName= getDetectorName(0);
+      //give the detectorname_V for workspace
+      detName+="_T";
+      QString opws(detName);
+           
+      //execute SumSpectra 
+      if(!runsumSpectra(loadedws,opws,wsStartIndex,wsEndIndex))
+      {
+        return;
+      }
+     
+      QString plotws = "\"" + opws +"\"";
+      plotSpectrum(plotws,0);
+    }
+
+
+
+   /**This method gets called from the handler of Vertical/Horizontal Integral button click.
+    * executes LoadRaw and SumRowColumn algorithm.
+    * @param range string entered by user
+    * @param orientation orientation
+    * @param specMin- minimum spectrum index
+    * @param specMax - maximum spectrum index
+    * @param opws - output workspace.
+    * @param bMask boolean used for masking
+    * @param time_pixel true if time masking,false if pixel mask
+    */
+    void SANSDiagnostics::IntegralClicked(const QString& range,const QString& orientation,
+      const QString& specMin,const QString& specMax,const QString& opws,bool bMask,bool time_pixel)
+    {
+      /// now run the load algorithm with the spec_min and spec_max
+      if(!runLoadAlgorithm(m_fileName,specMin,specMax))
+      {
+        return;
+      } 
+      //get the workspace name
+      QString loadedws = getWorkspaceToProcess(); 
+            
+      //aplly mask
+      if(bMask)
+      {
+        maskDetector(loadedws,bMask,time_pixel);
+      }
+    
+      if(range.isEmpty())
+      {        
+        QString HVMin,HVMax;
+        HVMinHVMaxStringValues(Mantid::EMPTY_INT(),Mantid::EMPTY_INT(),HVMin,HVMax);
+        if(!runsumRowColumn(loadedws,opws,orientation,HVMin,HVMax))
+        {
+          return ;
+        }
+        QString plotws = "\"" + opws +"\"";
+        plotSpectrum(plotws,0);
+        return;
+      }
+      //parse the range string
+      int count=0;
+      UserStringParser parser;
+      std::vector<std::vector<unsigned int> > parsedVals;
+      try
+      {
+        parsedVals=parser.parse(range.toStdString());
+      }
+      catch(std::runtime_error& e)
+      {
+        g_log.error(e.what());
+        return;
+      }
+      catch(std::out_of_range& e)
+      {
+        g_log.error(e.what());
+        return;
+      }
+           
+      QString wsPlotString;
+      //loop through each element of the parsed value vector
+      std::vector<std::vector<unsigned int> >::const_iterator parsedValcitr;
+      for(parsedValcitr=parsedVals.begin();parsedValcitr!=parsedVals.end();++parsedValcitr)
+      {
+        if((*parsedValcitr).empty())
+        {
+          return;
+        }
+        //check the vector contains sequential vales.
+        if(!isSequentialValues((*parsedValcitr)))
+        {
+          g_log.error("Values between H/V_Min and H/V_Max in the Range string  are not sequential ");
+          return ;
+        }
+        //first value in the vector  is the HVmin
+        int min=(*parsedValcitr).at(0);
+        int max;
+        ///last value is HVMax
+        if((*parsedValcitr).size()>1)
+        {
+          max=(*parsedValcitr).at((*parsedValcitr).size()-1);
+        }
+        else
+        {
+          //if the vector contains only one value HVMax=HVMin
+          max=min;
+        }
+
+        QString HVMin,HVMax;
+        HVMinHVMaxStringValues(min,max,HVMin,HVMax);
+        
+        ++count;
+        std::stringstream num;
+        num<<count;
+        QString outputwsname=opws+QString::fromStdString(num.str());
+
+        //now execute sumrowcolumn with hvmin and havmax from the first and last vales from the vector
+        if(!runsumRowColumn(loadedws,outputwsname,orientation,HVMin,HVMax))
+        {
+          return ;
+        }
+               
+        wsPlotString+="\"";
+        wsPlotString+=outputwsname;
+        wsPlotString+="\"";
+        wsPlotString+=",";
+      }
+
+      //remove the last comma
+      int index=wsPlotString.lastIndexOf(",");
+      wsPlotString.remove(index,1);
+  
+      //plot the zeroth spectrum for all the workspaces created.
+      int specNum=0;
+      plotSpectrum(wsPlotString,specNum);
+    
+    }
+
+    /** Get values of HVMin and HvMax values for sumrowcolumn algorithm
+      * @param minVal spectrum min value
+      * @param maxVal spectrum maximum value
+      * @param hvMin  spectrum min string
+      * @param hvMax  spectrum max string
+    */
+    void SANSDiagnostics::HVMinHVMaxStringValues(const int minVal,const int maxVal,QString& hvMin,QString& hvMax)
+    {
+      try
+      {
+        //first value in the vector 
+        hvMin=QString::fromStdString(boost::lexical_cast<std::string>(minVal));
+        ///last value is HVMax
+        hvMax=QString::fromStdString(boost::lexical_cast<std::string>(maxVal));
+      }
+      catch(boost::bad_lexical_cast& )
+      {
+        g_log.error("Error when getting the H/V_Min and H/V_Max value from the Range string ");
+      }
+      
+    }
+
+   /** This method applys time channel masks to the detector bank selected.
+      * @param wsName - name of the workspace.
+      * @param bMask - boolean flag to indicate the mask check box selected
+      */
+    void SANSDiagnostics::maskDetector(const QString& wsName,bool bMask,bool time_pixel)
+    {
+      //if  mask control selected
+      if(bMask)
+      {
+        emit applyMask(wsName,time_pixel);
+      }
+    }
+
+  /**This method plots spectrum for the given workspace
+    * @param wsName - name of the workspace
+    * @param specNum - spectrum number
+    */ 
+    void SANSDiagnostics::plotSpectrum(const QString& wsName,int specNum)
+    {      
+      QString plotspec="plotSpectrum([";
+      plotspec+=wsName;
+      plotspec+="],";
+      plotspec+=QString::number(specNum);
+      plotspec+=")";
+      runPythonCode(plotspec);
+    }
+
+    /// Handler for second detector horizontal integral button
+    void SANSDiagnostics::secondDetectorHorizontalIntegralClicked()
+    {
+      QString orientation("D_H");
+      QString minSpec;
+      QString maxSpec;
+      int detNum=1;//second detector
+      
+      QString ipwsName= getWorkspaceToProcess();
+      Mantid::API::Workspace_sptr ws_sptr;
+      try
+      {
+        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(ipwsName.toStdString());
+
+      }
+      catch(Exception::NotFoundError&)
+      {
+        g_log.error()<<"Error when accessing the Workspace "+ipwsName.toStdString()<<std::endl;
+        return;
+
+      }
+      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
+      if(!mws_sptr)
+      {
+        return;
+      }
+      
+      std::vector<int> specList;
+      getSpectraList(mws_sptr,detNum,specList);
+      minandMaxSpectrumIds(specList,minSpec,maxSpec);
+       
+      if(!isValidSpectra(minSpec,maxSpec))
+      {
+        m_SANSForm->groupBox_Detector2->setDisabled(true);
+        return;
+      }
+      QString detName= getDetectorName(detNum);
+      //give the detectorname_H for workspace
+      detName+="_H";
+      QString opws(detName);
+      ///horizontal integral range string
+      QString hiRange=m_SANSForm->hirange_edit2->text();
+      IntegralClicked(hiRange,orientation,minSpec,maxSpec,opws,m_SANSForm->tcmask3->isChecked(),true);
+
+    }
+    /// Handler for second detector horizontal integral button
+    void SANSDiagnostics::secondDetectorVerticalIntegralClicked()
+    {      
+      QString orientation("D_V");
+      QString minSpec;
+      QString maxSpec;
+      int detNum=1;//first detector
+
+      QString ipwsName= getWorkspaceToProcess();
+      Mantid::API::Workspace_sptr ws_sptr;
+      try
+      {
+        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(ipwsName.toStdString());
+
+      }
+      catch(Exception::NotFoundError&)
+      {
+        g_log.error()<<"Error when accessing the Workspace "+ipwsName.toStdString()<<std::endl;
+        return;
+
+      }
+      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
+      if(!mws_sptr)
+      {
+        return;
+      }
+
+      std::vector<int> specList;
+      getSpectraList(mws_sptr,detNum,specList);
+      minandMaxSpectrumIds(specList,minSpec,maxSpec);
+      if(!isValidSpectra(minSpec,maxSpec))
+      {
+        m_SANSForm->groupBox_Detector2->setDisabled(true);
+        return;
+      }
+      QString detName= getDetectorName(detNum);
+      //give the detectorname_H for workspace
+      detName+="_V";
+      QString opws(detName);
+
+      ///horizontal integral range string
+      QString viRange=m_SANSForm->virange_edit2->text();
+      IntegralClicked(viRange,orientation,minSpec,maxSpec,opws,m_SANSForm->tcmask4->isChecked(),true);
+    }
+    /// Handler for second detector horizontal integral button
+    void SANSDiagnostics::secondDetectorTimeIntegralClicked()
+    {
+      //second detector
+      int detNum=1;
+      QString minSpec;
+      QString maxSpec;
+
+      //Get the workspace created by load algorithm initially with specmin=1 and specmax=1
+      QString initialwsName= getWorkspaceToProcess();
+      Mantid::API::Workspace_sptr ws_sptr;
+      try
+      {
+        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(initialwsName.toStdString());
+      }
+      catch(Exception::NotFoundError&)
+      {
+        g_log.error()<<"Error when accessing the Workspace "+initialwsName.toStdString()<<std::endl;
+        return;
+      }
+      Mantid::API::MatrixWorkspace_sptr mws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws_sptr);
+      if(!mws_sptr)
+      {
+        return;
+      }
+            
+      std::vector<int> specList;
+      //get spectrum list from detector ids
+      getSpectraList(mws_sptr,detNum,specList);
+      // get maximum and minimum spectrum ids
+      minandMaxSpectrumIds(specList,minSpec,maxSpec);
+      QString wsStartIndex, wsEndIndex;
+      //   
+      if(!isValidSpectra(minSpec,maxSpec))
+      {
+        m_SANSForm->groupBox_Detector2->setDisabled(true);
+        return;
+      }
+      /// now run the load algorithm with the spec_min and spec_max
+      if(!runLoadAlgorithm(m_fileName,minSpec,maxSpec))
+      {
+        return;
+      } 
+      //Get the workspace created by load algorithm  with spec_min and specmax for the detectors
+      QString loadedws= getWorkspaceToProcess();
+      //apply mask
+      maskDetector(loadedws,m_SANSForm->pmask2->isChecked(),false);
+    
+      Mantid::API::Workspace_sptr loadedws_sptr;
+      try
+      {
+        loadedws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(loadedws.toStdString());
+
+      }
+      catch(Exception::NotFoundError&)
+      {
+        g_log.error()<<"Error when accessing the Workspace "+loadedws.toStdString()<<std::endl;
+        return;
+
+      }
+      Mantid::API::MatrixWorkspace_sptr mloadedws_sptr=boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(loadedws_sptr);
+      if(!loadedws_sptr)
+      {
+        return;
+      }
+      //get workspace indexes
+      getWorkspaceIndexes(mloadedws_sptr,specList,wsStartIndex,wsEndIndex);
+      
+      QString detName= getDetectorName(1);
+      //give the detectorname_V for workspace
+      detName+="_T";
+      QString opws(detName);
+      //execute SumSpectra 
+     if(!runsumSpectra(loadedws,opws,wsStartIndex,wsEndIndex))
+     {
+       return;
+     }
+
+     QString plotws = "\"" + opws +"\"";
+     plotSpectrum(plotws,0);
+
+    }
+
+    
+    /// get the total number of periods in the loaded raw/nexus file
+    int SANSDiagnostics::getTotalNumberofPeriods()
+    {
+      Mantid::API::Workspace_sptr ws_sptr;
+      try
+      {
+        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(m_outws_load.toStdString());
+
+      }
+      catch(Exception::NotFoundError&)
+      {
+        g_log.error()<<"Error: when accessing the workspace "<<m_outws_load.toStdString()<<std::endl;
+        return 0;
+      }
+      if(Mantid::API::WorkspaceGroup_sptr wsgrp_sptr=boost::dynamic_pointer_cast<WorkspaceGroup>(ws_sptr))
+      {
+        return wsgrp_sptr->getNumberOfEntries();
+      }
+      return 1;
+    }
+    /// This method loads last saved settings values from registry
+    void SANSDiagnostics::loadSettings()
+    {
+     
+      QSettings settings;
+      m_settingsGroup = "CustomInterfaces/SANSRunWindow/SANSDiagnostics";
+      settings.beginGroup(m_settingsGroup);
+      m_SANSForm->file_run_edit->readSettings(settings.group());
+      settings.endGroup();
+    }
+
+    ///save settings
+    void SANSDiagnostics::saveSettings()
+    {
+      m_dataDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("datasearch.directories"));
+      m_dataDir = m_dataDir.split(";", QString::SkipEmptyParts)[0];
+      QSettings settings;
+      m_settingsGroup="CustomInterfaces/SANSRunWindow/SANSDiagnostics";
+      settings.beginGroup(m_settingsGroup);
+      settings.setValue("last_directory", m_dataDir);
+      settings.setValue("File",getFileName());
+      settings.endGroup();
+      m_SANSForm->file_run_edit->saveSettings(settings.group());
+      
+    }
+
+    /**Execute sumrowcolumn algorithm 
+    * @param values a vector containing the values for hvmin,hvmax
+    * @param periodNum - number of the  period to load
+    * @param ipws - name of the i/p workspace
+    * @param opws - name of the o/p workspace
+    * @param orientation - orientation of the detector
+    */
+    bool SANSDiagnostics::executeSumRowColumn(const std::vector<unsigned int>& values,
+      const QString ipws,const QString& opws,const QString& orientation)
+    {      
+      if(values.empty())
+      {
+        return false ;
+      }
+
+      QString HVMin;
+      QString HVMax; 
+      //check the vector contains sequential vales.
+      if(!isSequentialValues(values))
+      {
+        g_log.error("Values between HVMin and HVMax in the Range string  are not sequential ");
+        return false;
+      }
+      try
+      {
+        //first value in the vector 
+        HVMin=QString::fromStdString(boost::lexical_cast<std::string>(values.at(0)));
+        ///last value is HVMax
+        if(values.size()>1)
+        {
+          HVMax=QString::fromStdString(boost::lexical_cast<std::string>(values.at(values.size()-1)));
+        }
+        else
+        {
+          //if the vector contains only one value HVMax=HVMin
+          HVMax=HVMin;
+        }
+      }
+      catch(boost::bad_lexical_cast& )
+      {
+      }
+      catch(std::out_of_range& )
+      {
+      }
+      //now execute sumrowcolumn with hvmin and havmax from the first and last vales from the vector
+      if(!runsumRowColumn(ipws,opws,orientation,HVMin,HVMax))
+      {
+        return false;
+      }
+      return true;
+    }
+
+  /**Execute sumrowcolumn algorithm with the vales
+    * @param ipwsName name of the input workspace
+    * @param opwsName name of the output workspace
+    * @param orientation indicates row or columns to sum
+    * @param hvMin minimum value of
+    * @param hvMax
+    */
+    bool SANSDiagnostics::runsumRowColumn(const QString ipwsName,const QString& opwsName,
+      const QString& orientation,const QString& hvMin,const QString& hvMax)
+    {
+
+       Mantid::API::Workspace_sptr ws_sptr;
+      try
+      {
+        ws_sptr = Mantid::API::AnalysisDataService::Instance().retrieve(ipwsName.toStdString());
+
+      }
+      catch(Exception::NotFoundError&)
+      {
+        g_log.error()<<"Error when  trying to access the workspace "<<ipwsName.toStdString()<<" which is not loaded"<<std::endl;
+        return false;
+      }
+      if(opwsName.isEmpty())
+      {
+         g_log.error()<<"Output workspace name is empty , can't create workspace 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;
+         return false;
+      }
+      if(hvMax.isEmpty())
+      {
+         g_log.error()<<"Error when executing SumRowColumn algorithm :Empty H/V_Max String value "<<std::endl;
+         return false;
+      }
+
+      QString code=
+        "try:\n"
+        "  SumRowColumn('";
+      code+=ipwsName;
+      code+="', '";
+      code+=opwsName;
+      code+="', '";
+      code+=orientation;
+      code+="', ";
+      code+="HVMin=";
+      code+=hvMin;
+      code+=",";
+      code+="HVMax=";
+      code+=hvMax;
+      code+=")\n";
+      code+="except:\n";
+      code+="  print 'Failure'";
+
+      QString ret= runPythonCode(code.trimmed());
+      if(!ret.isEmpty())
+      {
+        g_log.error()<<"Error when executing the SumRowColumn algorithm "<<ret.toStdString()<<std::endl;
+        return false;
+      }
+      return true;
+    }
+
+  /** This method creates script string for sumspectra algorithm
+    * @param ipwsName - name of the input workspace
+    * @param opwsName - name of the ooutput workspace
+    * @param wsStartIndex - start workspace index
+    * @param wsEndIndex - end workspace Index
+    * @returns - sumspectra script string
+    */
+    bool  SANSDiagnostics::runsumSpectra(const QString& ipwsName,const QString& opwsName,const QString& wsStartIndex,const QString& wsEndIndex)
+    {
+      
+      if(opwsName.isEmpty())
+      {
+         g_log.error()<<"Output workspace name is empty , can't create workspace with empty name"<<std::endl;
+         return false;
+      }
+
+      if(wsStartIndex.isEmpty())
+      {
+        g_log.error()<<"Error: Invalid StartWorkspaceIndex"<<std::endl;
+        return false;
+      }
+      if(wsEndIndex.isEmpty())
+      {
+        g_log.error()<<"Error Invalid EndWorkspaceIndex"<<std::endl;
+        return false;
+      }
+           
+      QString code=
+        "try:\n"
+        "  SumSpectra(\"";
+      code+=ipwsName;
+      code+="\",\"";
+      code+=opwsName;
+      code+="\",";
+      code+="StartWorkspaceIndex=";
+      code+=wsStartIndex;
+      code+=",";
+      code+="EndWorkspaceIndex=";
+      code+=wsEndIndex;
+      code+=")\n";
+      code+="except:\n";
+      code+="  print 'Failure'"; 
+     
+      QString ret= runPythonCode(code.trimmed());
+      if(!ret.isEmpty())
+      {
+        g_log.error()<<"Error when executing the SumSpectra algorithm "<<ret.toStdString()<<std::endl;
+        return false;
+      }
+      return true;
+    }
+
+
+  /**This method executes load algorithm with filename,specmin,specmax
+    * @param fileName - name of the file
+    * @param specMin  - spectrum minimum
+    * @param specMax  - spectrum maximum
+    */
+    bool SANSDiagnostics::runLoadAlgorithm(const QString& fileName,const QString& specMin,const QString& specMax)
+    {
+
+      if(fileName.isEmpty()) return false;
+      //get the output workspace for load algorithm from file name
+      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;
+         return false;
+      }
+        
+      QString load=
+        "try:\n"
+        "  Load('";
+      load+=fileName;
+      load+="','";
+      load+=m_outws_load;
+      load+="',";
+      load+="SpectrumMin=";
+      load+=specMin;
+      load+=",";
+      load+="SpectrumMax=";
+      load+=specMax;
+      load+=")\n";
+      load+="except:\n";
+      load+="  print 'Failure'"; 
+      QString ret= runPythonCode(load.trimmed());
+      if(!ret.isEmpty())
+      {
+        g_log.error()<<"Error when executing the Load algorithm "<<std::endl;
+        return false;
+      }
+      return true;
+    }
+    /**Checks the values in the given vector is sequential
+    * @param values  vector containing numbers
+    * @returns true if the vector is sequential
+    */
+    bool SANSDiagnostics::isSequentialValues(const std::vector<unsigned int>& values)
+    {
+      try
+      {
+        unsigned int startVal=values.at(0);
+        std::vector<unsigned int>::const_iterator citr;
+        for(int i=1;i<values.size();++i)
+        {
+          if(values.at(i)==startVal+1)
+          {
+            startVal=values.at(i);
+          }
+          else
+          {
+            return false;
+          }
+
+        }
+
+      }
+      catch(std::out_of_range&)
+      {
+        g_log.error("Error when executing SumRowColumn Algorithm" );
+        return false;
+      }
+      return true;
+    }
+    
+  /** This method enables the mask controls in teh diagnostics UI
+    */
+    void  SANSDiagnostics::enableMaskFileControls()
+    {
+      //enable time and pixel check masks
+      m_SANSForm->tcmask1->setEnabled(true);
+      m_SANSForm->tcmask2->setEnabled(true);
+      m_SANSForm->pmask1->setEnabled(true);
+      m_SANSForm->tcmask3->setEnabled(true);
+      m_SANSForm->tcmask4->setEnabled(true);
+      m_SANSForm->pmask2->setEnabled(true);
+    }
+
+  }
 }
\ No newline at end of file
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp
index 6a9c93c113965799cea882de5ba57bbd587aa2a4..2aa894283014696f09ddbb4dae640725df0ce0d2 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp
@@ -3,7 +3,7 @@
 //----------------------
 #include "MantidQtCustomInterfaces/SANSRunWindow.h"
 #include "MantidQtCustomInterfaces/SANSUtilityDialogs.h"
-#include "MantidQtCustomInterfaces/SANSAddFiles.h"
+#include "MantidQtCustomInterfaces/SANSAddFiles.h"
 #include "MantidQtAPI/ManageUserDirectories.h"
 #include "MantidQtAPI/FileDialogHandler.h"
 #include "MantidQtAPI/PythonRunner.h"
@@ -78,7 +78,7 @@ SANSRunWindow::~SANSRunWindow()
 {
   try
   {
-    ConfigService::Instance().removeObserver(m_newInDir);
+    ConfigService::Instance().removeObserver(m_newInDir);
     if( isInitialized() )
     {
       // Seems to crash on destruction of if I don't do this 
@@ -89,7 +89,7 @@ SANSRunWindow::~SANSRunWindow()
     delete m_diagnosticsTab;
   }
   catch(...)
-  {
+  {
     //we've cleaned up the best we can, move on
   }
 }
@@ -165,7 +165,7 @@ void SANSRunWindow::initLayout()
   }
   connect(this,SIGNAL(userfileLoaded()),m_diagnosticsTab,SLOT(enableMaskFileControls()));
   //Listen for Workspace delete signals
-  AnalysisDataService::Instance().notificationCenter.addObserver(m_delete_observer);
+  AnalysisDataService::Instance().notificationCenter.addObserver(m_delete_observer);
 
   readSettings();
 }
@@ -194,7 +194,7 @@ void SANSRunWindow::initAnalysDetTab()
   
  
   //Listen for Workspace delete signals
-  AnalysisDataService::Instance().notificationCenter.addObserver(m_delete_observer);
+  AnalysisDataService::Instance().notificationCenter.addObserver(m_delete_observer);
 
   makeValidator(m_uiForm.wavRanVal_lb, m_uiForm.wavRanges, m_uiForm.tab_2,
              "A comma separated list of numbers is required here");
@@ -598,7 +598,7 @@ bool SANSRunWindow::oldLoadUserFile()
   if( QFileInfo(filetext).isRelative() )
   {
     QString data_path(m_uiForm.saveDir_lb->text().trimmed());
-
+
     filetext = QDir(data_path).absoluteFilePath(filetext);
   }
 
@@ -1265,13 +1265,13 @@ void SANSRunWindow::applyMask(const QString& wsName,bool time_pixel)
   {
     addUserMaskStrings(str,"mask.parse_instruction",PixelMask);
   }
-  
-  script += str;
-  script += "mask.execute(i.ReductionSingleton(),\"";
-  script += wsName;
-  script += "\"";
-  script += ",xcentre=0,ycentre=0)";
-  runPythonCode(script.trimmed());
+  
+  script += str;
+  script += "mask.execute(i.ReductionSingleton(),\"";
+  script += wsName;
+  script += "\"";
+  script += ",xcentre=0,ycentre=0)";
+  runPythonCode(script.trimmed());
  
 }
 void SANSRunWindow::oldUserMaskStrings(QString & exec_script)
@@ -1595,8 +1595,8 @@ void SANSRunWindow::markError(QLabel* label)
 /**
  * Select the base directory for the data
  */
-void SANSRunWindow::selectDataDir()
-{
+void SANSRunWindow::selectDataDir()
+{
   MantidQt::API::ManageUserDirectories::openUserDirsDialog(this);
 }
 
@@ -3539,38 +3539,38 @@ void SANSRunWindow::checkLogFlags()
 */
 void SANSRunWindow::upDateDataDir()
 {
-  const std::vector<std::string> &dirs
-    = ConfigService::Instance().getDataSearchDirs();
-  if ( ! dirs.empty() )
-  {// use the first directory in the list
-    QString dataDir = QString::fromStdString(dirs.front());
-    //check for windows and its annoying path separator thing, windows' paths can't contain /
-    if ( dataDir.contains('\\') && ! dataDir.contains('/') )
-    {
-      dataDir.replace('\\', '/');
-    }
-    m_uiForm.saveDir_lb->setText(dataDir);
-
-    m_uiForm.plusDirs_lb->setText(
-      QString("+ ") + QString::number(dirs.size()-1) + QString(" others"));
-  }
-  else
-  {
-    m_uiForm.saveDir_lb->setText("No input search directories defined");
-    m_uiForm.plusDirs_lb->setText("");
-  }
-
-}
-/** Update the input directory labels if the Mantid system input
-*  directories have changed
-*  @param pDirInfo :: a pointer to an object with the output directory name in it
-*/
-void SANSRunWindow::handleInputDirChange(Mantid::Kernel::ConfigValChangeNotification_ptr pDirInfo)
-{
-  if ( pDirInfo->key() == "datasearch.directories" )
-  {
-    upDateDataDir();
-  }
+  const std::vector<std::string> &dirs
+    = ConfigService::Instance().getDataSearchDirs();
+  if ( ! dirs.empty() )
+  {// use the first directory in the list
+    QString dataDir = QString::fromStdString(dirs.front());
+    //check for windows and its annoying path separator thing, windows' paths can't contain /
+    if ( dataDir.contains('\\') && ! dataDir.contains('/') )
+    {
+      dataDir.replace('\\', '/');
+    }
+    m_uiForm.saveDir_lb->setText(dataDir);
+
+    m_uiForm.plusDirs_lb->setText(
+      QString("+ ") + QString::number(dirs.size()-1) + QString(" others"));
+  }
+  else
+  {
+    m_uiForm.saveDir_lb->setText("No input search directories defined");
+    m_uiForm.plusDirs_lb->setText("");
+  }
+
+}
+/** Update the input directory labels if the Mantid system input
+*  directories have changed
+*  @param pDirInfo :: a pointer to an object with the output directory name in it
+*/
+void SANSRunWindow::handleInputDirChange(Mantid::Kernel::ConfigValChangeNotification_ptr pDirInfo)
+{
+  if ( pDirInfo->key() == "datasearch.directories" )
+  {
+    upDateDataDir();
+  }
 }
 
 } //namespace CustomInterfaces
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/background.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/background.cpp
index dd20821ed917d6a6dbd928decf698cf7e8dfd4ba..59dd5ac80ee869a9931d9f7434dad7baa3054309 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/background.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/background.cpp
@@ -1,172 +1,172 @@
-//----------------------
-// Includes
-//----------------------
-#include "MantidQtCustomInterfaces/Background.h"
-#include "MantidAPI/FrameworkManager.h"
-#include <QLabel>
-#include <QHBoxLayout>
-#include <QVBoxLayout>
-#include <QPushButton>
-#include <QDoubleValidator>
-#include <QCloseEvent>
-#include <QShowEvent>
-
-#include <QMessageBox>
-
-using namespace MantidQt::CustomInterfaces;
-
-//----------------------
-// Public member functions
-//----------------------
-/** Sets up all the controls in the dialog box using the settings found under
- *  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)
-{
-  setWindowTitle("Background Removal Settings");
-
-  QGridLayout *grid = new QGridLayout;
-
-  m_ckDoRemove->setText("Remove background as found between these points");
-  QHBoxLayout *lineOne = new QHBoxLayout;
-  lineOne->addWidget(m_ckDoRemove);
-  lineOne->addStretch();
-
-  QLabel *lbStart = new QLabel("TOF Start");
-  QLabel *lbEnd = new QLabel("TOF End");
-  m_leStart->setValidator(new QDoubleValidator(this));
-  m_leEnd->setValidator(new QDoubleValidator(this));
-  m_ckDoRemove->setChecked(false);
-
-  QHBoxLayout *lineTwo = new QHBoxLayout;
-  lineTwo->addStretch();
-  lineTwo->addWidget(lbStart);
-  lineTwo->addWidget(m_leStart);
-  lineTwo->addWidget(lbEnd);
-  lineTwo->addWidget(m_leEnd);
-  lineTwo->addStretch();
-
-  QPushButton *pbOK = new QPushButton("OK");
-  QPushButton *pbCancel = new QPushButton("Cancel");
-  connect(pbCancel, SIGNAL(clicked()), this, SLOT(reject()));
-  connect(pbOK, SIGNAL(clicked()), this, SLOT(close()));
-   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);
-}
-
-//----------------------------------------------------
-// Public member functions
-//----------------------------------------------------
-
-/**
- * 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;
-}
-
-/**
- * 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;
-}
-
-/**
- * Retrieve the time-of-flight range from the dialog
- * @returns A pair containing the TOF range
- */
-QPair<double, double> Background::getRange() const
-{
-  return QPair<double, double>(m_rangeMin, m_rangeMax);
-}
-
-/**
- * Set the background range
- * @param min :: Minimum value
- * @param max :: Maximum value
- */
-void Background::setRange(double min, double max)
-{
-  m_rangeMin = min;
-  m_rangeMax = max;
-}
-
-//----------------------------------------------------
-// Public member functions
-//----------------------------------------------------
-
-/// Set up the dialog layout
-void Background::initLayout()
-{
-}
-
-/**
- * Called in response to a show() event
- * @param event :: The event details
- */
-void Background::showEvent(QShowEvent* e)
-{
-  m_leStart->setText(QString::number(m_rangeMin));
-  m_leEnd->setText(QString::number(m_rangeMax));
-  m_ckDoRemove->setChecked(m_doRemoval);
-  sanityCheck();
-  e->accept();
-}
-
-/**
- * Called in response to a close event
- * @parma event The event details
- */
-void Background::closeEvent(QCloseEvent* event)
-{
-  if( sanityCheck() )
-  {
-    m_doRemoval = m_ckDoRemove->isChecked();
-    m_rangeMin = m_leStart->text().toDouble();;
-    m_rangeMax = m_leEnd->text().toDouble();
-    event->accept();
-    emit accepted();
-  }
-  else
-  {
-    event->ignore();
-  }
-}
-
-bool Background::sanityCheck()
-{
-  double min = m_leStart->text().toDouble();
-  double max = m_leEnd->text().toDouble();
-  if( m_ckDoRemove->isChecked() && min > max )
-  {
-    m_leStart->setStyleSheet("background-color: red");
-    m_leEnd->setStyleSheet("background-color: red");
-    return false;
-  }
-  else
-  {
-    m_leStart->setStyleSheet("background-color: white");
-    m_leEnd->setStyleSheet("background-color: white");
-    return true;
-  }
-}
-
-
+//----------------------
+// Includes
+//----------------------
+#include "MantidQtCustomInterfaces/Background.h"
+#include "MantidAPI/FrameworkManager.h"
+#include <QLabel>
+#include <QHBoxLayout>
+#include <QVBoxLayout>
+#include <QPushButton>
+#include <QDoubleValidator>
+#include <QCloseEvent>
+#include <QShowEvent>
+
+#include <QMessageBox>
+
+using namespace MantidQt::CustomInterfaces;
+
+//----------------------
+// Public member functions
+//----------------------
+/** Sets up all the controls in the dialog box using the settings found under
+ *  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)
+{
+  setWindowTitle("Background Removal Settings");
+
+  QGridLayout *grid = new QGridLayout;
+
+  m_ckDoRemove->setText("Remove background as found between these points");
+  QHBoxLayout *lineOne = new QHBoxLayout;
+  lineOne->addWidget(m_ckDoRemove);
+  lineOne->addStretch();
+
+  QLabel *lbStart = new QLabel("TOF Start");
+  QLabel *lbEnd = new QLabel("TOF End");
+  m_leStart->setValidator(new QDoubleValidator(this));
+  m_leEnd->setValidator(new QDoubleValidator(this));
+  m_ckDoRemove->setChecked(false);
+
+  QHBoxLayout *lineTwo = new QHBoxLayout;
+  lineTwo->addStretch();
+  lineTwo->addWidget(lbStart);
+  lineTwo->addWidget(m_leStart);
+  lineTwo->addWidget(lbEnd);
+  lineTwo->addWidget(m_leEnd);
+  lineTwo->addStretch();
+
+  QPushButton *pbOK = new QPushButton("OK");
+  QPushButton *pbCancel = new QPushButton("Cancel");
+  connect(pbCancel, SIGNAL(clicked()), this, SLOT(reject()));
+  connect(pbOK, SIGNAL(clicked()), this, SLOT(close()));
+   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);
+}
+
+//----------------------------------------------------
+// Public member functions
+//----------------------------------------------------
+
+/**
+ * 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;
+}
+
+/**
+ * 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;
+}
+
+/**
+ * Retrieve the time-of-flight range from the dialog
+ * @returns A pair containing the TOF range
+ */
+QPair<double, double> Background::getRange() const
+{
+  return QPair<double, double>(m_rangeMin, m_rangeMax);
+}
+
+/**
+ * Set the background range
+ * @param min :: Minimum value
+ * @param max :: Maximum value
+ */
+void Background::setRange(double min, double max)
+{
+  m_rangeMin = min;
+  m_rangeMax = max;
+}
+
+//----------------------------------------------------
+// Public member functions
+//----------------------------------------------------
+
+/// Set up the dialog layout
+void Background::initLayout()
+{
+}
+
+/**
+ * Called in response to a show() event
+ * @param event :: The event details
+ */
+void Background::showEvent(QShowEvent* e)
+{
+  m_leStart->setText(QString::number(m_rangeMin));
+  m_leEnd->setText(QString::number(m_rangeMax));
+  m_ckDoRemove->setChecked(m_doRemoval);
+  sanityCheck();
+  e->accept();
+}
+
+/**
+ * Called in response to a close event
+ * @parma event The event details
+ */
+void Background::closeEvent(QCloseEvent* event)
+{
+  if( sanityCheck() )
+  {
+    m_doRemoval = m_ckDoRemove->isChecked();
+    m_rangeMin = m_leStart->text().toDouble();;
+    m_rangeMax = m_leEnd->text().toDouble();
+    event->accept();
+    emit accepted();
+  }
+  else
+  {
+    event->ignore();
+  }
+}
+
+bool Background::sanityCheck()
+{
+  double min = m_leStart->text().toDouble();
+  double max = m_leEnd->text().toDouble();
+  if( m_ckDoRemove->isChecked() && min > max )
+  {
+    m_leStart->setStyleSheet("background-color: red");
+    m_leEnd->setStyleSheet("background-color: red");
+    return false;
+  }
+  else
+  {
+    m_leStart->setStyleSheet("background-color: white");
+    m_leEnd->setStyleSheet("background-color: white");
+    return true;
+  }
+}
+
+
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/deltaECalc.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/deltaECalc.cpp
index ede872b1cea11dfb67d5d937495b1c12f73eabee..a6b0b8c5020156afe11b7f953c542822c34ea50f 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/deltaECalc.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/deltaECalc.cpp
@@ -1,228 +1,228 @@
-#include "MantidQtCustomInterfaces/deltaECalc.h"
-#include "MantidKernel/ConfigService.h"
-#include "MantidAPI/IAlgorithm.h"
-#include "MantidAPI/AlgorithmManager.h"
-#include "MantidAPI/FileProperty.h"
-#include <QDir>
-#include "boost/lexical_cast.hpp"
-#include <cmath>
-
-using namespace MantidQt::CustomInterfaces;
-using namespace Mantid::Kernel;
-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
-* @param userSettings :: the form that the user filled in
-* @throw invalid_argument where problems with user data prevent the calculation from proceeding
-*/
-deltaECalc::deltaECalc(QWidget * const interface, const Ui::ConvertToEnergy &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 inputFiles :: a coma separated list of data file names
-* @param whiteB :: The filename of the white beam run
-*/
-void deltaECalc::createProcessingScript(const QStringList &runFiles, const QString &whiteBeam,
-					const QStringList &absRunFiles, const QString &absWhiteBeam,
-					const QString & saveName)
-{ 
-  QString pyCode = "import 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._to_stdout = False\n");
-
-  addAnalysisOptions(pyCode);
-  addMaskingCommands(pyCode);
-  // Check save formats
-  QStringList fileExts;
-  if( m_sets.save_ckSPE->isChecked() )
-  {
-    fileExts.append("'.spe'");
-  }
-  if( m_sets.save_ckNexus->isChecked() )
-  {
-    fileExts.append("'.nxs'");
-  }
-  if( m_sets.save_ckNxSPE->isChecked() )
-  {
-    fileExts.append("'.nxspe'");
-  }
-  pyCode += "mono_sample.save_formats = [" + fileExts.join(",") + "]\n\n";
-
-  // 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 + "'");
-  // Absolute values
-  QString pyAbsRunFiles = createPyListAsString(absRunFiles);
-  QString absEiGuess = m_sets.leVanEi->text();
-  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" : motorName;
-
-  if( m_sets.ckSumSpecs->isChecked() || runFiles.size() == 1)
-  {
-    QString pySaveName;
-    if( saveName.isEmpty() )
-    {
-      pySaveName = "None";
-    }
-    else
-    {
-      pySaveName = "r'" + saveName + "'";
-    }
-    pyCode += QString("mono_sample.convert_to_energy(%1, %2, %3, %4, %5, %6, %7, motor='%8', offset=%9)");
-    pyCode = pyCode.arg(pyRunFiles, eiGuess,pyWhiteBeam,pyAbsRunFiles,absEiGuess, pyAbsWhiteBeam, pySaveName, pyMotorName, pySeOffset);
-  }
-  else
-  {
-    QString pySaveName;
-    if( saveName.isEmpty() )
-    {
-      pySaveName = "None";
-    }
-    else
-    {
-      pySaveName = "r'" + QFileInfo(saveName).absolutePath() + "'";
-    }
-    pyCode += "rfiles = " + pyRunFiles + "\n";
-    if( absRunFiles.isEmpty() )
-    {
-      pyCode +=
-        "for run in rfiles:\n"
-        "  mono_sample.convert_to_energy(run, %1, %2, save_path=%3,motor='%4', offset=%5)\n";
-      pyCode = pyCode.arg(eiGuess, pyWhiteBeam, pySaveName, pyMotorName, pySeOffset);
-    }
-    else
-    {
-      pyCode += "abs_rfiles = " + pyAbsRunFiles + "\n";
-      pyCode +=
-        "for run, abs in zip(rfiles, abs_rfiles):\n"
-        "  mono_sample.convert_to_energy(run, %1, %2, abs, %3, %4, save_path=%5,motor=%6, offset=%7)\n";
-      pyCode = pyCode.arg(eiGuess, pyWhiteBeam, absEiGuess, pyAbsWhiteBeam, pySaveName, pyMotorName, pySeOffset);
-    }
-  }
-  m_pyScript = pyCode;
-}
-
-/**
- * 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.normalise_method = '%1'\n").arg(inputValue);
-
-  pyCode += QString("mono_sample.background = %1\n");
-  if( this->m_bgRemove )
-  {
-    pyCode = pyCode.arg("True");
-    pyCode += QString("mono_sample.background_range = [%1, %2]\n").arg(this->m_TOFWinSt).arg(this->m_TOFWinEnd);
-  }
-  else
-  {
-    pyCode = pyCode.arg("False");
-  }
-
-  //Convert to energy
-  pyCode += QString("mono_sample.fix_ei = %1\n");
-  if( m_sets.ckFixEi->isChecked() )
-  {
-    pyCode = pyCode.arg("True");
-  }
-  else
-  {
-    pyCode = pyCode.arg("False");
-  }
-  pyCode += QString("mono_sample.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() )
-  {
-    pyCode += QString("mono_sample.map_file = r'%1'\n").arg(mapFile);
-  }
-  if( m_sets.ckRunAbsol->isChecked() )
-  {
-    QString absMapFile = m_sets.absMapFile->getFirstFilename();
-    if ( !absMapFile.isEmpty() )
-    {
-        pyCode += QString("mono_sample.abs_map_file = r'%1'\n").arg(absMapFile);
-    }
-    // Set the mono vanadium integration range
-    pyCode += QString("mono_sample.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.sample_mass = %1\n").arg(m_sets.leSamMass->text());
-    pyCode += QString("mono_sample.sample_rmm = %1\n").arg(m_sets.leRMMMass->text());
-    // And any changed vanadium mass
-    pyCode += QString("mono_sample.van_mass = %1\n").arg(m_sets.leVanMass->text());
-  }
-}
-
-
-void deltaECalc::addMaskingCommands(QString & analysisScript)
-{
-  if( m_diagnosedWS.isEmpty() )
-  {
-    return;
-  }
-  
-  analysisScript += "mono_sample.spectra_masks = '" + m_diagnosedWS + "'\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 += "mtd.deleteWorkspace('%2')\n";
-
-//   analysisScript = analysisScript.arg(m_diagnosedWS).arg(tmpWS);
-}
-
-QString deltaECalc::createPyListAsString(const QStringList & names) const
-{
-  if( names.isEmpty() )
-  {
-    return "None";
-  }
-  QString asString = "[r'";
-  asString += names.join("',r'");
-  asString += "']";
-  return asString;
-}
-
-/** Use the detector masking present in the workspace whose name was passed in
-*  the input workspace/s
-*  @param maskWS :: name of the workspace whose detector masking will be copied
-*/
-void deltaECalc::setDiagnosedWorkspaceName(const QString &maskWS)
-{
-  m_diagnosedWS = maskWS;
-}
-/** Insert the number before the dot of the extension
-* @param filename :: the a full path or partial path or just the name of a file
-* @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
-{
-  // 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();
-  }
-  return f.getBaseName()+"_"+boost::lexical_cast<std::string>(number)+
-    "."+f.getExtension();
-}
+#include "MantidQtCustomInterfaces/deltaECalc.h"
+#include "MantidKernel/ConfigService.h"
+#include "MantidAPI/IAlgorithm.h"
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidAPI/FileProperty.h"
+#include <QDir>
+#include "boost/lexical_cast.hpp"
+#include <cmath>
+
+using namespace MantidQt::CustomInterfaces;
+using namespace Mantid::Kernel;
+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
+* @param userSettings :: the form that the user filled in
+* @throw invalid_argument where problems with user data prevent the calculation from proceeding
+*/
+deltaECalc::deltaECalc(QWidget * const interface, const Ui::ConvertToEnergy &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 inputFiles :: a coma separated list of data file names
+* @param whiteB :: The filename of the white beam run
+*/
+void deltaECalc::createProcessingScript(const QStringList &runFiles, const QString &whiteBeam,
+					const QStringList &absRunFiles, const QString &absWhiteBeam,
+					const QString & saveName)
+{ 
+  QString pyCode = "import 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._to_stdout = False\n");
+
+  addAnalysisOptions(pyCode);
+  addMaskingCommands(pyCode);
+  // Check save formats
+  QStringList fileExts;
+  if( m_sets.save_ckSPE->isChecked() )
+  {
+    fileExts.append("'.spe'");
+  }
+  if( m_sets.save_ckNexus->isChecked() )
+  {
+    fileExts.append("'.nxs'");
+  }
+  if( m_sets.save_ckNxSPE->isChecked() )
+  {
+    fileExts.append("'.nxspe'");
+  }
+  pyCode += "mono_sample.save_formats = [" + fileExts.join(",") + "]\n\n";
+
+  // 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 + "'");
+  // Absolute values
+  QString pyAbsRunFiles = createPyListAsString(absRunFiles);
+  QString absEiGuess = m_sets.leVanEi->text();
+  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" : motorName;
+
+  if( m_sets.ckSumSpecs->isChecked() || runFiles.size() == 1)
+  {
+    QString pySaveName;
+    if( saveName.isEmpty() )
+    {
+      pySaveName = "None";
+    }
+    else
+    {
+      pySaveName = "r'" + saveName + "'";
+    }
+    pyCode += QString("mono_sample.convert_to_energy(%1, %2, %3, %4, %5, %6, %7, motor='%8', offset=%9)");
+    pyCode = pyCode.arg(pyRunFiles, eiGuess,pyWhiteBeam,pyAbsRunFiles,absEiGuess, pyAbsWhiteBeam, pySaveName, pyMotorName, pySeOffset);
+  }
+  else
+  {
+    QString pySaveName;
+    if( saveName.isEmpty() )
+    {
+      pySaveName = "None";
+    }
+    else
+    {
+      pySaveName = "r'" + QFileInfo(saveName).absolutePath() + "'";
+    }
+    pyCode += "rfiles = " + pyRunFiles + "\n";
+    if( absRunFiles.isEmpty() )
+    {
+      pyCode +=
+        "for run in rfiles:\n"
+        "  mono_sample.convert_to_energy(run, %1, %2, save_path=%3,motor='%4', offset=%5)\n";
+      pyCode = pyCode.arg(eiGuess, pyWhiteBeam, pySaveName, pyMotorName, pySeOffset);
+    }
+    else
+    {
+      pyCode += "abs_rfiles = " + pyAbsRunFiles + "\n";
+      pyCode +=
+        "for run, abs in zip(rfiles, abs_rfiles):\n"
+        "  mono_sample.convert_to_energy(run, %1, %2, abs, %3, %4, save_path=%5,motor=%6, offset=%7)\n";
+      pyCode = pyCode.arg(eiGuess, pyWhiteBeam, absEiGuess, pyAbsWhiteBeam, pySaveName, pyMotorName, pySeOffset);
+    }
+  }
+  m_pyScript = pyCode;
+}
+
+/**
+ * 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.normalise_method = '%1'\n").arg(inputValue);
+
+  pyCode += QString("mono_sample.background = %1\n");
+  if( this->m_bgRemove )
+  {
+    pyCode = pyCode.arg("True");
+    pyCode += QString("mono_sample.background_range = [%1, %2]\n").arg(this->m_TOFWinSt).arg(this->m_TOFWinEnd);
+  }
+  else
+  {
+    pyCode = pyCode.arg("False");
+  }
+
+  //Convert to energy
+  pyCode += QString("mono_sample.fix_ei = %1\n");
+  if( m_sets.ckFixEi->isChecked() )
+  {
+    pyCode = pyCode.arg("True");
+  }
+  else
+  {
+    pyCode = pyCode.arg("False");
+  }
+  pyCode += QString("mono_sample.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() )
+  {
+    pyCode += QString("mono_sample.map_file = r'%1'\n").arg(mapFile);
+  }
+  if( m_sets.ckRunAbsol->isChecked() )
+  {
+    QString absMapFile = m_sets.absMapFile->getFirstFilename();
+    if ( !absMapFile.isEmpty() )
+    {
+        pyCode += QString("mono_sample.abs_map_file = r'%1'\n").arg(absMapFile);
+    }
+    // Set the mono vanadium integration range
+    pyCode += QString("mono_sample.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.sample_mass = %1\n").arg(m_sets.leSamMass->text());
+    pyCode += QString("mono_sample.sample_rmm = %1\n").arg(m_sets.leRMMMass->text());
+    // And any changed vanadium mass
+    pyCode += QString("mono_sample.van_mass = %1\n").arg(m_sets.leVanMass->text());
+  }
+}
+
+
+void deltaECalc::addMaskingCommands(QString & analysisScript)
+{
+  if( m_diagnosedWS.isEmpty() )
+  {
+    return;
+  }
+  
+  analysisScript += "mono_sample.spectra_masks = '" + m_diagnosedWS + "'\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 += "mtd.deleteWorkspace('%2')\n";
+
+//   analysisScript = analysisScript.arg(m_diagnosedWS).arg(tmpWS);
+}
+
+QString deltaECalc::createPyListAsString(const QStringList & names) const
+{
+  if( names.isEmpty() )
+  {
+    return "None";
+  }
+  QString asString = "[r'";
+  asString += names.join("',r'");
+  asString += "']";
+  return asString;
+}
+
+/** Use the detector masking present in the workspace whose name was passed in
+*  the input workspace/s
+*  @param maskWS :: name of the workspace whose detector masking will be copied
+*/
+void deltaECalc::setDiagnosedWorkspaceName(const QString &maskWS)
+{
+  m_diagnosedWS = maskWS;
+}
+/** Insert the number before the dot of the extension
+* @param filename :: the a full path or partial path or just the name of a file
+* @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
+{
+  // 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();
+  }
+  return f.getBaseName()+"_"+boost::lexical_cast<std::string>(number)+
+    "."+f.getExtension();
+}
diff --git a/Code/Mantid/MantidQt/DesignerPlugins/inc/MantidQtDesignerPlugins/WorkspaceSelectorPlugin.h b/Code/Mantid/MantidQt/DesignerPlugins/inc/MantidQtDesignerPlugins/WorkspaceSelectorPlugin.h
index 7522f194835dabe6f52659a71f7fb5dc21b7b9c1..952480d8d71989add05ab56c653fe6a58bcc3d77 100644
--- a/Code/Mantid/MantidQt/DesignerPlugins/inc/MantidQtDesignerPlugins/WorkspaceSelectorPlugin.h
+++ b/Code/Mantid/MantidQt/DesignerPlugins/inc/MantidQtDesignerPlugins/WorkspaceSelectorPlugin.h
@@ -1,68 +1,68 @@
-#ifndef MANTIDQT_DESIGNERPLUGINS_WORKSPACESELECTORPLUGIN_H
-#define MANTIDQT_DESIGNERPLUGINS_WORKSPACESELECTORPLUGIN_H
-
-#include <QDesignerCustomWidgetInterface>
-
-/** 
-The WorkspaceSelectorPlugin creates a Qt designer plugin out of the WorkspaceSelector widget.
-
-@author Michael Whitty
-@date 23/02/2011
-
-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://svn.mantidproject.org/mantid/trunk/Code/Mantid>    
-*/
-class WorkspaceSelectorPlugin : public QObject, public QDesignerCustomWidgetInterface
-{
-  Q_OBJECT
-  Q_INTERFACES(QDesignerCustomWidgetInterface)
-
-public:
-  /// Default constructor
-  WorkspaceSelectorPlugin(QObject *parent = 0);
-  /// Initialize the plugin
-  void initialize(QDesignerFormEditorInterface *core);
-  /// Returns a pointer to a newly constructed widget for this plugin wraps
-  QWidget *createWidget(QWidget *parent);
-  /// Returns if the plugin is initliaized
-  bool isInitialized() const;
-  /// Returns if this plugins is able to contain other widgets
-  bool isContainer() const;
-  /// Returns the fully-qualified class name
-  QString name() const;
-  /// Returns the group name within the designer 
-  QString group() const;
-  /// Returns the icon to use
-  QIcon icon() const;
-  /// Returns a tool tip for the widget
-  QString toolTip() const;
-  /// Returns a short description of the widget
-  QString whatsThis() const;
-  /// Returns the include file that appears at the top of the generated .h file
-  QString includeFile() const;
-  /// Returns the XML that defines the widget and its properties
-  QString domXml() const; 
-
-private:
-  /// Are we initialized? 
-  bool m_initialized;
-};
-
-
+#ifndef MANTIDQT_DESIGNERPLUGINS_WORKSPACESELECTORPLUGIN_H
+#define MANTIDQT_DESIGNERPLUGINS_WORKSPACESELECTORPLUGIN_H
+
+#include <QDesignerCustomWidgetInterface>
+
+/** 
+The WorkspaceSelectorPlugin creates a Qt designer plugin out of the WorkspaceSelector widget.
+
+@author Michael Whitty
+@date 23/02/2011
+
+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://svn.mantidproject.org/mantid/trunk/Code/Mantid>    
+*/
+class WorkspaceSelectorPlugin : public QObject, public QDesignerCustomWidgetInterface
+{
+  Q_OBJECT
+  Q_INTERFACES(QDesignerCustomWidgetInterface)
+
+public:
+  /// Default constructor
+  WorkspaceSelectorPlugin(QObject *parent = 0);
+  /// Initialize the plugin
+  void initialize(QDesignerFormEditorInterface *core);
+  /// Returns a pointer to a newly constructed widget for this plugin wraps
+  QWidget *createWidget(QWidget *parent);
+  /// Returns if the plugin is initliaized
+  bool isInitialized() const;
+  /// Returns if this plugins is able to contain other widgets
+  bool isContainer() const;
+  /// Returns the fully-qualified class name
+  QString name() const;
+  /// Returns the group name within the designer 
+  QString group() const;
+  /// Returns the icon to use
+  QIcon icon() const;
+  /// Returns a tool tip for the widget
+  QString toolTip() const;
+  /// Returns a short description of the widget
+  QString whatsThis() const;
+  /// Returns the include file that appears at the top of the generated .h file
+  QString includeFile() const;
+  /// Returns the XML that defines the widget and its properties
+  QString domXml() const; 
+
+private:
+  /// Are we initialized? 
+  bool m_initialized;
+};
+
+
 #endif //MANTIDQT_DESIGNERPLUGINS_WORKSPACESELECTORPLUGIN_H
\ No newline at end of file
diff --git a/Code/Mantid/MantidQt/DesignerPlugins/src/WorkspaceSelectorPlugin.cpp b/Code/Mantid/MantidQt/DesignerPlugins/src/WorkspaceSelectorPlugin.cpp
index 7006f339ecfb22066de244473c36d6826b2c085d..de07fc2d2e486149f0ccbf9ad350083ad747fbb7 100644
--- a/Code/Mantid/MantidQt/DesignerPlugins/src/WorkspaceSelectorPlugin.cpp
+++ b/Code/Mantid/MantidQt/DesignerPlugins/src/WorkspaceSelectorPlugin.cpp
@@ -1,124 +1,124 @@
-//-----------------------------------------------------------
-// Includes
-//-----------------------------------------------------------
-#include "MantidQtDesignerPlugins/WorkspaceSelectorPlugin.h"
-#include "MantidQtMantidWidgets/WorkspaceSelector.h"
-
-#include <QDesignerFormEditorInterface>
-#include <QtPlugin>
-
-using namespace MantidQt::MantidWidgets;
-
-/**
- * Default constructor
- * @param parent :: The parent of the plugin (default: NULL)
- */
-WorkspaceSelectorPlugin::WorkspaceSelectorPlugin(QObject *parent) : QObject(parent), m_initialized(false)
-{
-}
-
-/**
- * Initialize the plugin
- * @param formEditor :: A pointer to the interface that will control this plugin
- */
-void WorkspaceSelectorPlugin::initialize(QDesignerFormEditorInterface * formEditor)
-{
-  (void) formEditor;
-  if (m_initialized)
-  {
-    return;
-  }
-  m_initialized = true;
-}
-
-/**
- * Create a widget of the type wrapped by the plugin
- * @param parent :: The parent widget
- * @returns A newly constructed widget for the wrapped type.
- */
-QWidget *WorkspaceSelectorPlugin::createWidget(QWidget *parent)
-{
-  return new WorkspaceSelector(parent, false);
-}
-
-/**
-* Returns whether the plugin initialized or not
-* @returns True if initialize() has been called, false otherwise
-*/
-bool WorkspaceSelectorPlugin::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
- */
-bool WorkspaceSelectorPlugin::isContainer() const
-{
-  return false;
-}
-
-/**
- * Returns the class name of the widget that this plugin manages
- * @returns A string containing the fully qualified class name of the widget
- */
-QString WorkspaceSelectorPlugin::name() const
-{
-  return "MantidQt::MantidWidgets::WorkspaceSelector";
-}
-
-/**
- * Returns the group within the designer that this plugin should be placed
- * @returns The name of the group of widgets in the designer 
- */
-QString WorkspaceSelectorPlugin::group() const
-{
-  return "MantidWidgets";
-}
-
-/**
- * Returns the icon to display in the designer
- * @returns An icon that is used within the designer
- */
-QIcon WorkspaceSelectorPlugin::icon() const
-{
-  return QIcon();
-}
-
-/**
- * The tooltip for the widget
- * @returns A string containing the tooltip for this widget
- */
-QString WorkspaceSelectorPlugin::toolTip() const
-{
-  return "Select a workspace for use in this operation";
-}
-
-/** A short description of the widget
- * @returns A string containing a short description of the widget
- */
-QString WorkspaceSelectorPlugin::whatsThis() const
-{  
-  return "A workspace selector widget.";
-}
-
-/**
- * The include file to use when generating the header file
- * @returns A string containing the path to the widget's header file
- */
-QString WorkspaceSelectorPlugin::includeFile() const
-{
-  return "MantidQtMantidWidgets/WorkspaceSelector.h";
-}
-
-/**
- * Returns the XML used to define the widget in the designer
- * @returns A string containing the XML for the widget
- */
-QString WorkspaceSelectorPlugin::domXml() const
-{
-  return 
-    "<widget class=\"MantidQt::MantidWidgets::WorkspaceSelector\" name=\"workspaceSelector\">\n"
-    "</widget>\n";
-}
+//-----------------------------------------------------------
+// Includes
+//-----------------------------------------------------------
+#include "MantidQtDesignerPlugins/WorkspaceSelectorPlugin.h"
+#include "MantidQtMantidWidgets/WorkspaceSelector.h"
+
+#include <QDesignerFormEditorInterface>
+#include <QtPlugin>
+
+using namespace MantidQt::MantidWidgets;
+
+/**
+ * Default constructor
+ * @param parent :: The parent of the plugin (default: NULL)
+ */
+WorkspaceSelectorPlugin::WorkspaceSelectorPlugin(QObject *parent) : QObject(parent), m_initialized(false)
+{
+}
+
+/**
+ * Initialize the plugin
+ * @param formEditor :: A pointer to the interface that will control this plugin
+ */
+void WorkspaceSelectorPlugin::initialize(QDesignerFormEditorInterface * formEditor)
+{
+  (void) formEditor;
+  if (m_initialized)
+  {
+    return;
+  }
+  m_initialized = true;
+}
+
+/**
+ * Create a widget of the type wrapped by the plugin
+ * @param parent :: The parent widget
+ * @returns A newly constructed widget for the wrapped type.
+ */
+QWidget *WorkspaceSelectorPlugin::createWidget(QWidget *parent)
+{
+  return new WorkspaceSelector(parent, false);
+}
+
+/**
+* Returns whether the plugin initialized or not
+* @returns True if initialize() has been called, false otherwise
+*/
+bool WorkspaceSelectorPlugin::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
+ */
+bool WorkspaceSelectorPlugin::isContainer() const
+{
+  return false;
+}
+
+/**
+ * Returns the class name of the widget that this plugin manages
+ * @returns A string containing the fully qualified class name of the widget
+ */
+QString WorkspaceSelectorPlugin::name() const
+{
+  return "MantidQt::MantidWidgets::WorkspaceSelector";
+}
+
+/**
+ * Returns the group within the designer that this plugin should be placed
+ * @returns The name of the group of widgets in the designer 
+ */
+QString WorkspaceSelectorPlugin::group() const
+{
+  return "MantidWidgets";
+}
+
+/**
+ * Returns the icon to display in the designer
+ * @returns An icon that is used within the designer
+ */
+QIcon WorkspaceSelectorPlugin::icon() const
+{
+  return QIcon();
+}
+
+/**
+ * The tooltip for the widget
+ * @returns A string containing the tooltip for this widget
+ */
+QString WorkspaceSelectorPlugin::toolTip() const
+{
+  return "Select a workspace for use in this operation";
+}
+
+/** A short description of the widget
+ * @returns A string containing a short description of the widget
+ */
+QString WorkspaceSelectorPlugin::whatsThis() const
+{  
+  return "A workspace selector widget.";
+}
+
+/**
+ * The include file to use when generating the header file
+ * @returns A string containing the path to the widget's header file
+ */
+QString WorkspaceSelectorPlugin::includeFile() const
+{
+  return "MantidQtMantidWidgets/WorkspaceSelector.h";
+}
+
+/**
+ * Returns the XML used to define the widget in the designer
+ * @returns A string containing the XML for the widget
+ */
+QString WorkspaceSelectorPlugin::domXml() const
+{
+  return 
+    "<widget class=\"MantidQt::MantidWidgets::WorkspaceSelector\" name=\"workspaceSelector\">\n"
+    "</widget>\n";
+}
diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DiagResults.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DiagResults.h
index 007bc3a33bfbc19c79450a30c5b834cc8daf9b21..10735bbd763d633395e361aa3634b821b52fec1c 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DiagResults.h
+++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/DiagResults.h
@@ -1,51 +1,51 @@
-#ifndef MANTIDQTCUSTOMINTERFACES_EXCITATIONSDIAGRESULTS_H_
-#define MANTIDQTCUSTOMINTERFACES_EXCITATIONSDIAGRESULTS_H_
-
-#include "MantidQtAPI/MantidDialog.h"
-#include "WidgetDllOption.h"
-#include <QHash>
-#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);
-      void showButtons(bool show=true);
-
-    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 addButtons(int row);
-      void setupButtons(int row, QString test);
-      void closeEvent(QCloseEvent *event);
-    private slots:
-      void tableList(int row);
-      void instruView(int row);
-
-    private:
-      /// the layout that widgets are added to
-      QGridLayout *m_Grid;
-      /// points to the slot that deals with list buttons being pressed
-      QSignalMapper *m_ListMapper;
-      /// points to the slot that deals with view buttons being pressed
-      QSignalMapper *m_ViewMapper;
-      /// stores the name of the workspaces that contains the results of each test
-      QHash<int,QString> m_diagWS;
-    };
-  }
-}
-
-#endif //MANTIDQTCUSTOMINTERFACES_EXCITATIONSDIAGRESULTS_H_
+#ifndef MANTIDQTCUSTOMINTERFACES_EXCITATIONSDIAGRESULTS_H_
+#define MANTIDQTCUSTOMINTERFACES_EXCITATIONSDIAGRESULTS_H_
+
+#include "MantidQtAPI/MantidDialog.h"
+#include "WidgetDllOption.h"
+#include <QHash>
+#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);
+      void showButtons(bool show=true);
+
+    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 addButtons(int row);
+      void setupButtons(int row, QString test);
+      void closeEvent(QCloseEvent *event);
+    private slots:
+      void tableList(int row);
+      void instruView(int row);
+
+    private:
+      /// the layout that widgets are added to
+      QGridLayout *m_Grid;
+      /// points to the slot that deals with list buttons being pressed
+      QSignalMapper *m_ListMapper;
+      /// points to the slot that deals with view buttons being pressed
+      QSignalMapper *m_ViewMapper;
+      /// stores the name of the workspaces that contains the results of each test
+      QHash<int,QString> m_diagWS;
+    };
+  }
+}
+
+#endif //MANTIDQTCUSTOMINTERFACES_EXCITATIONSDIAGRESULTS_H_
diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ICatSearch.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ICatSearch.h
index cf9e2309837f55c51ecda14b0ca73cc80ddd9be7..dcb91fba0cf19d62e4ea51b75a0fa66bcc4c14e0 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ICatSearch.h
+++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/ICatSearch.h
@@ -1,149 +1,149 @@
-
-#ifndef MANTIDWIDGETS_ICATSEARCH_H_
-#define MANTIDWIDGETS_ICATSEARCH_H_
-
-//----------------------
-// Includes
-//----------------------
-
-#include "ui_ICatSearch.h"
-#include "MantidAPI/ITableWorkspace.h"
-#include "MantidQtMantidWidgets/ICatInvestigation.h"
-#include "MantidQtMantidWidgets/ICatUtils.h"
-#include "WidgetDllOption.h"
-
-#include <algorithm>
-#include <QObject>
-#include <QCalendarWidget>
-#include <QHash>
-
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-class  EXPORT_OPT_MANTIDQT_MANTIDWIDGETS ICatSearch : public QWidget
-{
-  Q_OBJECT
-
-public:
-  /// Default Constructor
-  ICatSearch(QWidget *parent = 0);
-    ~ICatSearch();
- signals:
-  void error(const QString&,int param=0);
-private:
-  /// Initialize the layout
-  virtual void initLayout();
-  ///populating the instrumentbox 
-  void populateInstrumentBox();
-  ///get start and end run numbers
-  void getRunValues(double& startRun,double& endRun);
-  ///get the user set start and end dates
-  void getDates(QString& startDate,QString& endDate);
-   /// get the user selected instrument
-  void getSelectedInstrument(QString& instrName);
-  /// execute the algorithm
-  bool executeSearch(Mantid::API::ITableWorkspace_sptr& ws1_sptr);
-
-  /// this method populates the search result widget.
-  void updatesearchResults(Mantid::API::ITableWorkspace_sptr & ws_sptr );
-  /// save settings to registry
-  void saveSettings();
-  /// read settings from registry
-  void readSettings();
-
-  void closeEvent(QCloseEvent* event);
-
-  void setparentWidget(QWidget*);
-  //bool eventFilter(QObject *obj, QEvent *event);
-  QWidget* getParentWidget();
-
-  //if  casesensitive check box selected 
-  bool isCaseSensitiveSearch();
-
-  //event filtering
-  bool eventFilter(QObject *obj, QEvent *event);
-
-   /// This method sets the property of algorithm
-   template<typename T >
-   bool setProperty(QString name,T value)
-   {
-	
-	   try
-	   {
-		   m_alg->setProperty(name.toStdString(),value);
-	   }
-	   catch(std::invalid_argument& e)
-	   {	
-		 
-		   emit error(e.what());
-           showInvalidMarkerLabel(name);
-		 
-		   return false;
-	   }
-	   catch (Mantid::Kernel::Exception::NotFoundError& e)
-	   {
-		   emit error(e.what());
-		   showInvalidMarkerLabel(name);
-		   return false;
-	   }
-	  
-	   hideInvalidMarkerLabel(name);
-	   return true;
-   }
-
-   /// This method adds invalid marker labels to hashtable
-   void addtoPropertyLabelsHash();
-   /// this method creates shared pointer to search algorithm
-   Mantid::API::IAlgorithm_sptr createAlgorithm();
-   /// show invalid marker labels
-   void showInvalidMarkerLabel(const QString& name);
-   /// hide invalid marker labels
-   void hideInvalidMarkerLabel(const QString& name);
- 
-private slots:
-	///handler for search button
-	void onSearch();
-	///handler for close button
-	void onClose();
-	///
-	void investigationSelected(QTableWidgetItem *);
-	///start date changed
-	void getDate(const QDate& date  );
-	///popup DateTime calender to select date
-	void popupCalendar();
-	//handler for helpbutton
-	void helpButtonClicked();
-	 
-private:
-  ///The form generated by Qt Designer
-  Ui::ICatSearch m_uiForm;
- 
-  ///investigation widget
-  MantidQt::MantidWidgets::ICatInvestigation* m_invstWidget;
-
-  ///parent widget
-  QWidget* m_applicationWindow;
-
-  ///pointer to object to identify starta nd end date tool button
-  QObject* m_sender;
-
-    ///stores investigation data 
-  Mantid::API::ITableWorkspace_sptr m_ws_sptr;
-
-  ///shared pointer to icat utils object
-  boost::shared_ptr<ICatUtils> m_utils_sptr;
-
-  /// hash containing property name and invalid marker * label
-  QHash<QString,QWidget*> m_propLabelHash;
-
-  /// shared pointer to search algorithm
-  Mantid::API::IAlgorithm_sptr m_alg;
-
-
-};
-
-}
-}
-
-#endif //MANTIDQTCUSTOMINTERFACES_ICATSEARCH_H_
+
+#ifndef MANTIDWIDGETS_ICATSEARCH_H_
+#define MANTIDWIDGETS_ICATSEARCH_H_
+
+//----------------------
+// Includes
+//----------------------
+
+#include "ui_ICatSearch.h"
+#include "MantidAPI/ITableWorkspace.h"
+#include "MantidQtMantidWidgets/ICatInvestigation.h"
+#include "MantidQtMantidWidgets/ICatUtils.h"
+#include "WidgetDllOption.h"
+
+#include <algorithm>
+#include <QObject>
+#include <QCalendarWidget>
+#include <QHash>
+
+namespace MantidQt
+{
+namespace MantidWidgets
+{
+class  EXPORT_OPT_MANTIDQT_MANTIDWIDGETS ICatSearch : public QWidget
+{
+  Q_OBJECT
+
+public:
+  /// Default Constructor
+  ICatSearch(QWidget *parent = 0);
+    ~ICatSearch();
+ signals:
+  void error(const QString&,int param=0);
+private:
+  /// Initialize the layout
+  virtual void initLayout();
+  ///populating the instrumentbox 
+  void populateInstrumentBox();
+  ///get start and end run numbers
+  void getRunValues(double& startRun,double& endRun);
+  ///get the user set start and end dates
+  void getDates(QString& startDate,QString& endDate);
+   /// get the user selected instrument
+  void getSelectedInstrument(QString& instrName);
+  /// execute the algorithm
+  bool executeSearch(Mantid::API::ITableWorkspace_sptr& ws1_sptr);
+
+  /// this method populates the search result widget.
+  void updatesearchResults(Mantid::API::ITableWorkspace_sptr & ws_sptr );
+  /// save settings to registry
+  void saveSettings();
+  /// read settings from registry
+  void readSettings();
+
+  void closeEvent(QCloseEvent* event);
+
+  void setparentWidget(QWidget*);
+  //bool eventFilter(QObject *obj, QEvent *event);
+  QWidget* getParentWidget();
+
+  //if  casesensitive check box selected 
+  bool isCaseSensitiveSearch();
+
+  //event filtering
+  bool eventFilter(QObject *obj, QEvent *event);
+
+   /// This method sets the property of algorithm
+   template<typename T >
+   bool setProperty(QString name,T value)
+   {
+	
+	   try
+	   {
+		   m_alg->setProperty(name.toStdString(),value);
+	   }
+	   catch(std::invalid_argument& e)
+	   {	
+		 
+		   emit error(e.what());
+           showInvalidMarkerLabel(name);
+		 
+		   return false;
+	   }
+	   catch (Mantid::Kernel::Exception::NotFoundError& e)
+	   {
+		   emit error(e.what());
+		   showInvalidMarkerLabel(name);
+		   return false;
+	   }
+	  
+	   hideInvalidMarkerLabel(name);
+	   return true;
+   }
+
+   /// This method adds invalid marker labels to hashtable
+   void addtoPropertyLabelsHash();
+   /// this method creates shared pointer to search algorithm
+   Mantid::API::IAlgorithm_sptr createAlgorithm();
+   /// show invalid marker labels
+   void showInvalidMarkerLabel(const QString& name);
+   /// hide invalid marker labels
+   void hideInvalidMarkerLabel(const QString& name);
+ 
+private slots:
+	///handler for search button
+	void onSearch();
+	///handler for close button
+	void onClose();
+	///
+	void investigationSelected(QTableWidgetItem *);
+	///start date changed
+	void getDate(const QDate& date  );
+	///popup DateTime calender to select date
+	void popupCalendar();
+	//handler for helpbutton
+	void helpButtonClicked();
+	 
+private:
+  ///The form generated by Qt Designer
+  Ui::ICatSearch m_uiForm;
+ 
+  ///investigation widget
+  MantidQt::MantidWidgets::ICatInvestigation* m_invstWidget;
+
+  ///parent widget
+  QWidget* m_applicationWindow;
+
+  ///pointer to object to identify starta nd end date tool button
+  QObject* m_sender;
+
+    ///stores investigation data 
+  Mantid::API::ITableWorkspace_sptr m_ws_sptr;
+
+  ///shared pointer to icat utils object
+  boost::shared_ptr<ICatUtils> m_utils_sptr;
+
+  /// hash containing property name and invalid marker * label
+  QHash<QString,QWidget*> m_propLabelHash;
+
+  /// shared pointer to search algorithm
+  Mantid::API::IAlgorithm_sptr m_alg;
+
+
+};
+
+}
+}
+
+#endif //MANTIDQTCUSTOMINTERFACES_ICATSEARCH_H_
diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWDiag.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWDiag.h
index b077b09bc41c0e61d6738e1b4282103c10ffd93b..b5508e1633240eff1598cb3af56aa4fafebdd90a 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWDiag.h
+++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/MWDiag.h
@@ -1,95 +1,95 @@
-#ifndef MANTIDQTCUSTOMINTERFACES_MWDIAG_H_
-#define MANTIDQTCUSTOMINTERFACES_MWDIAG_H_
-
-#include "ui_MWDiag.h"
-#include "MantidQtAPI/MantidWidget.h"
-#include "WidgetDllOption.h"
-#include <QSettings>
-#include <QStringList>
-#include <QComboBox>
-#include <boost/shared_ptr.hpp>
-
-//-----------------------------------------------
-// Forward declarations
-//------------------------------------------------
-namespace Mantid
-{
-  namespace Geometry
-  {
-    class IInstrument;
-  }
-}
-
-namespace MantidQt
-{
-  namespace MantidWidgets
-  {
-    //-----------------------------------------------
-    // Forward declarations
-    //------------------------------------------------
-    class MWRunFiles;
-    class DiagResults;
-    
-    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 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;
-
-      QString createDiagnosticScript() const;
-      void showTestResults(const QString & testSummary) const;
-
-      void closeDialog();
-      QString openFileDialog(const bool save, const QStringList &exts);
-      boost::shared_ptr<Mantid::Geometry::IInstrument> getInstrument(const QString & name);
-      QString getSetting(const QString & settingName, 
-			 boost::shared_ptr<Mantid::Geometry::IInstrument> inst = boost::shared_ptr<Mantid::Geometry::IInstrument>(), 
-			 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;}
-      void validateHardMaskFile();
-    };
-  }
-}
-
-#endif //MANTIDQTCUSTOMINTERFACES_MWDIAG_H_
+#ifndef MANTIDQTCUSTOMINTERFACES_MWDIAG_H_
+#define MANTIDQTCUSTOMINTERFACES_MWDIAG_H_
+
+#include "ui_MWDiag.h"
+#include "MantidQtAPI/MantidWidget.h"
+#include "WidgetDllOption.h"
+#include <QSettings>
+#include <QStringList>
+#include <QComboBox>
+#include <boost/shared_ptr.hpp>
+
+//-----------------------------------------------
+// Forward declarations
+//------------------------------------------------
+namespace Mantid
+{
+  namespace Geometry
+  {
+    class IInstrument;
+  }
+}
+
+namespace MantidQt
+{
+  namespace MantidWidgets
+  {
+    //-----------------------------------------------
+    // Forward declarations
+    //------------------------------------------------
+    class MWRunFiles;
+    class DiagResults;
+    
+    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 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;
+
+      QString createDiagnosticScript() const;
+      void showTestResults(const QString & testSummary) const;
+
+      void closeDialog();
+      QString openFileDialog(const bool save, const QStringList &exts);
+      boost::shared_ptr<Mantid::Geometry::IInstrument> getInstrument(const QString & name);
+      QString getSetting(const QString & settingName, 
+			 boost::shared_ptr<Mantid::Geometry::IInstrument> inst = boost::shared_ptr<Mantid::Geometry::IInstrument>(), 
+			 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;}
+      void validateHardMaskFile();
+    };
+  }
+}
+
+#endif //MANTIDQTCUSTOMINTERFACES_MWDIAG_H_
diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RangeSelector.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RangeSelector.h
index 207edb9f564aea8cf5edbeb159bf5b1315ff287b..4270da45f3c23fbadebae5b96168d529c94792e2 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RangeSelector.h
+++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/RangeSelector.h
@@ -1,91 +1,91 @@
-#ifndef MANTIDQT_MANTIDWIDGET_POSHPLOTTING_H
-#define MANTIDQT_MANTIDWIDGET_POSHPLOTTING_H
-
-#include "WidgetDllOption.h"
-
-#include <qwt_plot_picker.h>
-#include <qwt_plot.h>
-#include <qwt_plot_marker.h>
-
-#include <QPen>
-
-namespace MantidQt
-{
-namespace MantidWidgets
-{
-  /**
-  * 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() {};
-
-    bool eventFilter(QObject*, QEvent*);
-    
-    bool changingMin(double, double);
-    bool changingMax(double, double);
-
-    std::pair<double,double> getRange();
-    void setRange(std::pair<double,double> range); /// Overloaded function provided for convenience
-
-  signals:
-    void minValueChanged(double);
-    void maxValueChanged(double);
-    void rangeChanged(double, double);
-    
-  public slots:
-    void setRange(double, double);
-    void minChanged(double);
-    void maxChanged(double);
-    void setMinimum(double); ///< outside setting of value
-    void setMaximum(double); ///< outside setting of value
-    void reapply(); ///< re-apply the range selector lines
-    void setColour(QColor colour);
-    void setInfoOnly(bool state);
-    void setVisible(bool state);
-
-  private:
-    void setMin(double val);
-    void setMax(double val);
-    void verify();
-    bool inRange(double);
-
-
-    // MEMBER ATTRIBUTES
-    SelectType m_type; ///< type of selection widget is for
-
-    double m_min;
-    double m_max;
-    double m_lower; ///< lowest allowed value for range
-    double m_higher; ///< highest allowed value for range
-    
-    QwtPlotCanvas* m_canvas;
-    QwtPlot* m_plot;
-
-    QwtPlotMarker* m_mrkMin;
-    QwtPlotMarker* m_mrkMax;
-
-    bool m_minChanging;
-    bool m_maxChanging;
-
-    bool m_infoOnly;
-    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
-
-#endif
+#ifndef MANTIDQT_MANTIDWIDGET_POSHPLOTTING_H
+#define MANTIDQT_MANTIDWIDGET_POSHPLOTTING_H
+
+#include "WidgetDllOption.h"
+
+#include <qwt_plot_picker.h>
+#include <qwt_plot.h>
+#include <qwt_plot_marker.h>
+
+#include <QPen>
+
+namespace MantidQt
+{
+namespace MantidWidgets
+{
+  /**
+  * 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() {};
+
+    bool eventFilter(QObject*, QEvent*);
+    
+    bool changingMin(double, double);
+    bool changingMax(double, double);
+
+    std::pair<double,double> getRange();
+    void setRange(std::pair<double,double> range); /// Overloaded function provided for convenience
+
+  signals:
+    void minValueChanged(double);
+    void maxValueChanged(double);
+    void rangeChanged(double, double);
+    
+  public slots:
+    void setRange(double, double);
+    void minChanged(double);
+    void maxChanged(double);
+    void setMinimum(double); ///< outside setting of value
+    void setMaximum(double); ///< outside setting of value
+    void reapply(); ///< re-apply the range selector lines
+    void setColour(QColor colour);
+    void setInfoOnly(bool state);
+    void setVisible(bool state);
+
+  private:
+    void setMin(double val);
+    void setMax(double val);
+    void verify();
+    bool inRange(double);
+
+
+    // MEMBER ATTRIBUTES
+    SelectType m_type; ///< type of selection widget is for
+
+    double m_min;
+    double m_max;
+    double m_lower; ///< lowest allowed value for range
+    double m_higher; ///< highest allowed value for range
+    
+    QwtPlotCanvas* m_canvas;
+    QwtPlot* m_plot;
+
+    QwtPlotMarker* m_mrkMin;
+    QwtPlotMarker* m_mrkMax;
+
+    bool m_minChanging;
+    bool m_maxChanging;
+
+    bool m_infoOnly;
+    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
+
+#endif
diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WidgetDllOption.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WidgetDllOption.h
index c37efdd1112b105b262c6b878b1b903425b49e2f..39aa524f3a6eb447d12eb7f92d92c2e17868d413 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WidgetDllOption.h
+++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WidgetDllOption.h
@@ -1,12 +1,12 @@
-#ifndef MANTIDQT_MANTIDWIDGETS_DLLOPTION_H_
-#define MANTIDQT_MANTIDWIDGETS_DLLOPTION_H_
-
-#include <MantidKernel/System.h>
-
-#ifdef IN_MANTIDQT_MANTIDWIDGETS
-#define EXPORT_OPT_MANTIDQT_MANTIDWIDGETS DLLExport 
-#else
-#define EXPORT_OPT_MANTIDQT_MANTIDWIDGETS DLLImport
-#endif /* IN_MANTIDQT_MANTIDWIDGETS */
-
-#endif //MANTIDQT_MANTIDWIDGETS_DLLOPTION_H_
+#ifndef MANTIDQT_MANTIDWIDGETS_DLLOPTION_H_
+#define MANTIDQT_MANTIDWIDGETS_DLLOPTION_H_
+
+#include <MantidKernel/System.h>
+
+#ifdef IN_MANTIDQT_MANTIDWIDGETS
+#define EXPORT_OPT_MANTIDQT_MANTIDWIDGETS DLLExport 
+#else
+#define EXPORT_OPT_MANTIDQT_MANTIDWIDGETS DLLImport
+#endif /* IN_MANTIDQT_MANTIDWIDGETS */
+
+#endif //MANTIDQT_MANTIDWIDGETS_DLLOPTION_H_
diff --git a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WorkspaceSelector.h b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WorkspaceSelector.h
index 16542f970655799f5952a06104cf15b63b3a30f2..41f445cbb60181b1f48371baad326bc43b2ed8a9 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WorkspaceSelector.h
+++ b/Code/Mantid/MantidQt/MantidWidgets/inc/MantidQtMantidWidgets/WorkspaceSelector.h
@@ -1,117 +1,117 @@
-#ifndef MANTIDQTMANTIDWIDGETS_WORKSPACESELECTOR_H_
-#define MANTIDQTMANTIDWIDGETS_WORKSPACESELECTOR_H_
-
-#include "WidgetDllOption.h"
-#include <QComboBox>
-#include <QStringList>
-#include "MantidAPI/AnalysisDataService.h"
-
-#include <Poco/AutoPtr.h>
-#include <Poco/NObserver.h>
-
-// Forward declarations
-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
-
-  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://svn.mantidproject.org/mantid/trunk/Code/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(QString Suffix READ getSuffix WRITE setSuffix)
-    Q_PROPERTY(QString Algorithm READ getValidatingAlgorithm WRITE setValidatingAlgorithm)
-
-  public:
-    /// Default Constructor
-    WorkspaceSelector(QWidget *parent = NULL, bool init = true);
-    /// Destructor
-    virtual ~WorkspaceSelector();
-
-    QStringList getWorkspaceTypes() const;
-    void setWorkspaceTypes(const QStringList & types);
-    bool showHiddenWorkspaces() const;
-    void showHiddenWorkspaces(const bool & show);
-    QString getSuffix() const;
-    void setSuffix(const QString & suffix);
-    QString getValidatingAlgorithm() const;
-    void setValidatingAlgorithm(const QString & algName);
-    bool isValid() const;
-
-  private:
-    void handleAddEvent(Mantid::API::WorkspaceAddNotification_ptr pNf);
-    void handleRemEvent(Mantid::API::WorkspaceDeleteNotification_ptr pNf);
-
-    bool checkEligibility(const QString & name, Mantid::API::Workspace_sptr object) const;
-    void refresh();
-
-  private:
-    /// Poco Observers for ADS Notifications
-    Poco::NObserver<WorkspaceSelector, Mantid::API::WorkspaceAddNotification> m_addObserver;
-    Poco::NObserver<WorkspaceSelector, Mantid::API::WorkspaceDeleteNotification> m_remObserver;
-
-    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;
-    // suffix
-    QString m_suffix;
-    QString m_algName;
-    QString m_algPropName;
-
-    // Algorithm to validate against
-    boost::shared_ptr<Mantid::API::Algorithm> m_algorithm;
-
-  };
-
-}
-}
-
-#endif //MANTIDQTMANTIDWIDGETS_INSTRUMENTSELECTOR_H_
+#ifndef MANTIDQTMANTIDWIDGETS_WORKSPACESELECTOR_H_
+#define MANTIDQTMANTIDWIDGETS_WORKSPACESELECTOR_H_
+
+#include "WidgetDllOption.h"
+#include <QComboBox>
+#include <QStringList>
+#include "MantidAPI/AnalysisDataService.h"
+
+#include <Poco/AutoPtr.h>
+#include <Poco/NObserver.h>
+
+// Forward declarations
+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
+
+  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://svn.mantidproject.org/mantid/trunk/Code/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(QString Suffix READ getSuffix WRITE setSuffix)
+    Q_PROPERTY(QString Algorithm READ getValidatingAlgorithm WRITE setValidatingAlgorithm)
+
+  public:
+    /// Default Constructor
+    WorkspaceSelector(QWidget *parent = NULL, bool init = true);
+    /// Destructor
+    virtual ~WorkspaceSelector();
+
+    QStringList getWorkspaceTypes() const;
+    void setWorkspaceTypes(const QStringList & types);
+    bool showHiddenWorkspaces() const;
+    void showHiddenWorkspaces(const bool & show);
+    QString getSuffix() const;
+    void setSuffix(const QString & suffix);
+    QString getValidatingAlgorithm() const;
+    void setValidatingAlgorithm(const QString & algName);
+    bool isValid() const;
+
+  private:
+    void handleAddEvent(Mantid::API::WorkspaceAddNotification_ptr pNf);
+    void handleRemEvent(Mantid::API::WorkspaceDeleteNotification_ptr pNf);
+
+    bool checkEligibility(const QString & name, Mantid::API::Workspace_sptr object) const;
+    void refresh();
+
+  private:
+    /// Poco Observers for ADS Notifications
+    Poco::NObserver<WorkspaceSelector, Mantid::API::WorkspaceAddNotification> m_addObserver;
+    Poco::NObserver<WorkspaceSelector, Mantid::API::WorkspaceDeleteNotification> m_remObserver;
+
+    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;
+    // suffix
+    QString m_suffix;
+    QString m_algName;
+    QString m_algPropName;
+
+    // Algorithm to validate against
+    boost::shared_ptr<Mantid::API::Algorithm> m_algorithm;
+
+  };
+
+}
+}
+
+#endif //MANTIDQTMANTIDWIDGETS_INSTRUMENTSELECTOR_H_
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/DiagResults.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/DiagResults.cpp
index 3027e3cca2a6fe04d3a05be53a63a74ef20cdb60..8a28e005549f7c38026aa8905b2e224fe8a74a9f 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/DiagResults.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/DiagResults.cpp
@@ -1,244 +1,244 @@
-//----------------------
-// Includes
-//----------------------
-#include "MantidQtMantidWidgets/DiagResults.h"
-#include "MantidAPI/FrameworkManager.h"
-#include "MantidAPI/AnalysisDataService.h"
-#include "MantidKernel/Exception.h"
-#include <QLabel>
-#include <QHBoxLayout>
-#include <QGridLayout>
-#include <QPushButton>
-#include <QCloseEvent>
-#include <QHashIterator>
-#include <QRegExp>
-
-#include <boost/lexical_cast.hpp>
-
-using namespace MantidQt::API;
-using namespace MantidQt::MantidWidgets;
-
-
-namespace
-{
-  /// the total number of tests that results are reported for here
-  const int NUMTESTS = 4;
-  /// the list of tests that we display results for
-  const QString TESTS[NUMTESTS] =
-  { "First detector vanadium test", "Second detector vanadium test", "Background test", "PSD Bleed test"};
-}
-
-//----------------------
-// Public member functions
-//----------------------
-///Constructor
-DiagResults::DiagResults(QWidget *parent): MantidDialog(parent),
-  m_Grid(new QGridLayout), m_ListMapper(new QSignalMapper(this)),
-  m_ViewMapper(new QSignalMapper(this))
-{
-  setWindowTitle("Failed detectors list");
-
-  connect(m_ListMapper, SIGNAL(mapped(int)), this, SLOT(tableList(int)));
-  connect(m_ViewMapper, SIGNAL(mapped(int)), SLOT(instruView(int)));
-  
-  addRow("Test", "Number of failed spectra");
-  // make one row of buttons for each set of results
-  int row = 0;
-  for ( int i = 0; i < NUMTESTS; i ++ )
-  {
-    QString col1 = TESTS[i];
-    QString col2 = "N/A";
-    row = addRow(col1, col2);
-    addButtons(row);
-  }
-  row++;
-  QPushButton *close = new QPushButton("Close");
-  m_Grid->addWidget(close, row, 1);
-  connect(close, SIGNAL(clicked()), this, SLOT(close()));
-
-  setLayout(m_Grid);
-
-  setAttribute(Qt::WA_DeleteOnClose, false);
-}
-
-/**
- * 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.");
-  }
-
-  QStringList results = testSummary.split("\n");
-  // First result line is the header
-  for(int i = 1; i <= NUMTESTS; ++i)
-  {
-    QString testName = results[i].section(":", 0, 1);
-    QString fieldValues = results[i].section(":", 1);
-    QStringList columns = fieldValues.split(QRegExp("\\s+"), QString::SkipEmptyParts);
-    Q_ASSERT(columns.size() == 2);
-    QString status;
-    if( columns[0] == "None" ) status = "N/A";
-    else status = columns[1];
-    // Store the name of the test workspace
-    m_diagWS[i+1] = columns[0];
-    updateRow(i+1, status);
-  }
-  
-}
-
-/** Enable or disable the buttons used to run Python scripts
-*  @param show :: the buttons are enabled if this is set to true and disabled otherwise
-*/
-void DiagResults::showButtons(bool show)
-{
-  for( int i = 0; i < NUMTESTS; i ++ )
-  {
-    const int row = i + 1 + 1;
-    QPushButton *bpList =
-      qobject_cast<QPushButton*>(m_Grid->itemAtPosition(row, 2)->widget());
-
-    if ( bpList && bpList->text() == "List" )
-    {
-      bpList->setEnabled(show);
-    }
-    QPushButton *bpView =
-      qobject_cast<QPushButton*>(m_Grid->itemAtPosition(row, 3)->widget());
-    if ( bpView && bpView->text() == "View" )
-    {
-      bpView->setEnabled(show);
-    }
-  }
-}
-//----------------------
-// Private member functions
-//----------------------
-/// insert a row at the bottom of the grid
-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);
-  m_Grid->addWidget(new QLabel(secondColumn), row, 1);
-  return row;
-}
-
-/** Displays a summary of the results of tests in to text labels
-*  @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)
-{
-  // Get the text label from the grid
-  QWidget *widget = m_Grid->itemAtPosition(row, 1)->widget();
-  QLabel *label = qobject_cast<QLabel*>(widget);
-  label->setText(text);
-  // Update the buttons depending on the status of text
-  QPushButton *listButton = qobject_cast<QPushButton*>(m_Grid->itemAtPosition(row, 2)->widget());
-  QPushButton *viewButton = qobject_cast<QPushButton*>(m_Grid->itemAtPosition(row, 3)->widget());
-  if(text == "N/A")
-  {
-    listButton->setEnabled(false);
-    viewButton->setEnabled(false);
-  }
-  else
-  {
-    listButton->setEnabled(true);
-    viewButton->setEnabled(true);
-  }
-
-}
-
-/// insert a row at the bottom of the grid
-void DiagResults::addButtons(int row)
-{
-  QPushButton *list = new QPushButton("List");
-  connect(list, SIGNAL(clicked()), m_ListMapper, SLOT(map()));
-  m_ListMapper->setMapping(list, row);
-  list->setToolTip("List the detector IDs of the detectors found bad");
-  m_Grid->addWidget(list, row, 2);
-  list->setEnabled(false);
-
-  QPushButton *view = new QPushButton("View");
-  connect(view, SIGNAL(clicked()), m_ViewMapper, SLOT(map()));
-  m_ViewMapper->setMapping(view, row);
-  view->setToolTip("Show the locations of the bad detectors");
-  m_Grid->addWidget(view, row, 3);
-  view->setEnabled(false);
-}
-
-/** Enable the controls on the row and conect the buttons to the slots
-*  from which their Python script is executed
-*  @param row :: the index number of the row to enable
-*  @param test :: the name of the test that row corrosponds to
-*/
-void DiagResults::setupButtons(int row, QString test)
-{
-  QPushButton *bpList =
-    qobject_cast<QPushButton*>(m_Grid->itemAtPosition(row, 2)->widget());
-  if ( bpList && ( bpList->text() != "List" ) )
-  {
-    bpList->setText("List");
-    connect(bpList, SIGNAL(clicked()), m_ListMapper, SLOT(map()));
-    m_ListMapper->setMapping(bpList, test );
-  }
-
-  QPushButton *bpView =
-    qobject_cast<QPushButton*>(m_Grid->itemAtPosition(row, 3)->widget());
-  if ( bpView && ( bpView->text() != "View" ) )
-  {
-    bpView->setText("View");
-    connect(bpView, SIGNAL(clicked()), m_ViewMapper, SLOT(map()));
-    m_ViewMapper->setMapping(bpView, test);
-  }
-}
-
-/// enables the run button on the parent window so the user can do more analysis
-void DiagResults::closeEvent(QCloseEvent *event)
-{
-  // Remove all tempary workspaces
-  QHashIterator<int,QString> itr(m_diagWS);
-  while(itr.hasNext() )
-  {
-    QString remove = itr.next().value();
-    if( remove != "None" ) 
-    {
-      Mantid::API::FrameworkManager::Instance().deleteWorkspace(remove.toStdString());
-    }
-  }
-  emit died();
-  event->accept();
-}
-
-void DiagResults::tableList(int row)
-{
-  QString wsName = m_diagWS[row];
-  QString testName = TESTS[row - 2];
-  QString pyCode = 
-    "import diagnostics\n"
-    "failed_spectra = diagnostics.get_failed_spectra_list('%1')\n"
-    "num_failed = len(failed_spectra)\n"
-    "failed_table = newTable('Failed Spectra - %2 ', num_failed, 1)\n"
-    "for i in range(num_failed):\n"
-    "    failed_table.setText(1, i+1, str(failed_spectra[i]))\n"
-    "failed_table.show()";
-
-  //Set the workspace name and testName
-  pyCode = pyCode.arg(wsName,testName);
-  runPythonCode(pyCode, true);
-}
-
-void DiagResults::instruView(int row)
-{
-  QString wsName = m_diagWS[row];
-  QString pyCode = 
-    "inst_view = getInstrumentView('%1')\n"
-    "inst_view.setWindowTitle('Failed detectors')\n"
-    "inst_view.setColorMapRange(0.0, 1.0)\n"
-    "inst_view.show()";
-  pyCode = pyCode.arg(wsName);
-  runPythonCode(pyCode, true);
-}
+//----------------------
+// Includes
+//----------------------
+#include "MantidQtMantidWidgets/DiagResults.h"
+#include "MantidAPI/FrameworkManager.h"
+#include "MantidAPI/AnalysisDataService.h"
+#include "MantidKernel/Exception.h"
+#include <QLabel>
+#include <QHBoxLayout>
+#include <QGridLayout>
+#include <QPushButton>
+#include <QCloseEvent>
+#include <QHashIterator>
+#include <QRegExp>
+
+#include <boost/lexical_cast.hpp>
+
+using namespace MantidQt::API;
+using namespace MantidQt::MantidWidgets;
+
+
+namespace
+{
+  /// the total number of tests that results are reported for here
+  const int NUMTESTS = 4;
+  /// the list of tests that we display results for
+  const QString TESTS[NUMTESTS] =
+  { "First detector vanadium test", "Second detector vanadium test", "Background test", "PSD Bleed test"};
+}
+
+//----------------------
+// Public member functions
+//----------------------
+///Constructor
+DiagResults::DiagResults(QWidget *parent): MantidDialog(parent),
+  m_Grid(new QGridLayout), m_ListMapper(new QSignalMapper(this)),
+  m_ViewMapper(new QSignalMapper(this))
+{
+  setWindowTitle("Failed detectors list");
+
+  connect(m_ListMapper, SIGNAL(mapped(int)), this, SLOT(tableList(int)));
+  connect(m_ViewMapper, SIGNAL(mapped(int)), SLOT(instruView(int)));
+  
+  addRow("Test", "Number of failed spectra");
+  // make one row of buttons for each set of results
+  int row = 0;
+  for ( int i = 0; i < NUMTESTS; i ++ )
+  {
+    QString col1 = TESTS[i];
+    QString col2 = "N/A";
+    row = addRow(col1, col2);
+    addButtons(row);
+  }
+  row++;
+  QPushButton *close = new QPushButton("Close");
+  m_Grid->addWidget(close, row, 1);
+  connect(close, SIGNAL(clicked()), this, SLOT(close()));
+
+  setLayout(m_Grid);
+
+  setAttribute(Qt::WA_DeleteOnClose, false);
+}
+
+/**
+ * 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.");
+  }
+
+  QStringList results = testSummary.split("\n");
+  // First result line is the header
+  for(int i = 1; i <= NUMTESTS; ++i)
+  {
+    QString testName = results[i].section(":", 0, 1);
+    QString fieldValues = results[i].section(":", 1);
+    QStringList columns = fieldValues.split(QRegExp("\\s+"), QString::SkipEmptyParts);
+    Q_ASSERT(columns.size() == 2);
+    QString status;
+    if( columns[0] == "None" ) status = "N/A";
+    else status = columns[1];
+    // Store the name of the test workspace
+    m_diagWS[i+1] = columns[0];
+    updateRow(i+1, status);
+  }
+  
+}
+
+/** Enable or disable the buttons used to run Python scripts
+*  @param show :: the buttons are enabled if this is set to true and disabled otherwise
+*/
+void DiagResults::showButtons(bool show)
+{
+  for( int i = 0; i < NUMTESTS; i ++ )
+  {
+    const int row = i + 1 + 1;
+    QPushButton *bpList =
+      qobject_cast<QPushButton*>(m_Grid->itemAtPosition(row, 2)->widget());
+
+    if ( bpList && bpList->text() == "List" )
+    {
+      bpList->setEnabled(show);
+    }
+    QPushButton *bpView =
+      qobject_cast<QPushButton*>(m_Grid->itemAtPosition(row, 3)->widget());
+    if ( bpView && bpView->text() == "View" )
+    {
+      bpView->setEnabled(show);
+    }
+  }
+}
+//----------------------
+// Private member functions
+//----------------------
+/// insert a row at the bottom of the grid
+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);
+  m_Grid->addWidget(new QLabel(secondColumn), row, 1);
+  return row;
+}
+
+/** Displays a summary of the results of tests in to text labels
+*  @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)
+{
+  // Get the text label from the grid
+  QWidget *widget = m_Grid->itemAtPosition(row, 1)->widget();
+  QLabel *label = qobject_cast<QLabel*>(widget);
+  label->setText(text);
+  // Update the buttons depending on the status of text
+  QPushButton *listButton = qobject_cast<QPushButton*>(m_Grid->itemAtPosition(row, 2)->widget());
+  QPushButton *viewButton = qobject_cast<QPushButton*>(m_Grid->itemAtPosition(row, 3)->widget());
+  if(text == "N/A")
+  {
+    listButton->setEnabled(false);
+    viewButton->setEnabled(false);
+  }
+  else
+  {
+    listButton->setEnabled(true);
+    viewButton->setEnabled(true);
+  }
+
+}
+
+/// insert a row at the bottom of the grid
+void DiagResults::addButtons(int row)
+{
+  QPushButton *list = new QPushButton("List");
+  connect(list, SIGNAL(clicked()), m_ListMapper, SLOT(map()));
+  m_ListMapper->setMapping(list, row);
+  list->setToolTip("List the detector IDs of the detectors found bad");
+  m_Grid->addWidget(list, row, 2);
+  list->setEnabled(false);
+
+  QPushButton *view = new QPushButton("View");
+  connect(view, SIGNAL(clicked()), m_ViewMapper, SLOT(map()));
+  m_ViewMapper->setMapping(view, row);
+  view->setToolTip("Show the locations of the bad detectors");
+  m_Grid->addWidget(view, row, 3);
+  view->setEnabled(false);
+}
+
+/** Enable the controls on the row and conect the buttons to the slots
+*  from which their Python script is executed
+*  @param row :: the index number of the row to enable
+*  @param test :: the name of the test that row corrosponds to
+*/
+void DiagResults::setupButtons(int row, QString test)
+{
+  QPushButton *bpList =
+    qobject_cast<QPushButton*>(m_Grid->itemAtPosition(row, 2)->widget());
+  if ( bpList && ( bpList->text() != "List" ) )
+  {
+    bpList->setText("List");
+    connect(bpList, SIGNAL(clicked()), m_ListMapper, SLOT(map()));
+    m_ListMapper->setMapping(bpList, test );
+  }
+
+  QPushButton *bpView =
+    qobject_cast<QPushButton*>(m_Grid->itemAtPosition(row, 3)->widget());
+  if ( bpView && ( bpView->text() != "View" ) )
+  {
+    bpView->setText("View");
+    connect(bpView, SIGNAL(clicked()), m_ViewMapper, SLOT(map()));
+    m_ViewMapper->setMapping(bpView, test);
+  }
+}
+
+/// enables the run button on the parent window so the user can do more analysis
+void DiagResults::closeEvent(QCloseEvent *event)
+{
+  // Remove all tempary workspaces
+  QHashIterator<int,QString> itr(m_diagWS);
+  while(itr.hasNext() )
+  {
+    QString remove = itr.next().value();
+    if( remove != "None" ) 
+    {
+      Mantid::API::FrameworkManager::Instance().deleteWorkspace(remove.toStdString());
+    }
+  }
+  emit died();
+  event->accept();
+}
+
+void DiagResults::tableList(int row)
+{
+  QString wsName = m_diagWS[row];
+  QString testName = TESTS[row - 2];
+  QString pyCode = 
+    "import diagnostics\n"
+    "failed_spectra = diagnostics.get_failed_spectra_list('%1')\n"
+    "num_failed = len(failed_spectra)\n"
+    "failed_table = newTable('Failed Spectra - %2 ', num_failed, 1)\n"
+    "for i in range(num_failed):\n"
+    "    failed_table.setText(1, i+1, str(failed_spectra[i]))\n"
+    "failed_table.show()";
+
+  //Set the workspace name and testName
+  pyCode = pyCode.arg(wsName,testName);
+  runPythonCode(pyCode, true);
+}
+
+void DiagResults::instruView(int row)
+{
+  QString wsName = m_diagWS[row];
+  QString pyCode = 
+    "inst_view = getInstrumentView('%1')\n"
+    "inst_view.setWindowTitle('Failed detectors')\n"
+    "inst_view.setColorMapRange(0.0, 1.0)\n"
+    "inst_view.show()";
+  pyCode = pyCode.arg(wsName);
+  runPythonCode(pyCode, true);
+}
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/ICatAdvancedSearch.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/ICatAdvancedSearch.cpp
index 472c22670237962efb57ebfbcea6cb0c5c1aa3c5..0232843e2fa2c1c76c35975dd7ef3b81804e38b0 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/ICatAdvancedSearch.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/ICatAdvancedSearch.cpp
@@ -1,683 +1,683 @@
-
-#include "MantidQtMantidWidgets/ICatAdvancedSearch.h"
-#include "MantidAPI/AlgorithmManager.h"
-#include "MantidAPI/AnalysisDataService.h"
-#include "MantidAPI/Column.h"
-#include "MantidAPI/TableRow.h" 
-
-#include <QDesktopServices>
-#include <QSettings>
-#include <QUrl>
-
-using namespace Mantid::Kernel;
-using namespace Mantid::API;
-using namespace MantidQt::MantidWidgets;
-
-ICatAdvancedSearch::ICatAdvancedSearch(QWidget* par):
-QWidget(par),m_utils_sptr(new ICatUtils),m_applicationWindow(NULL)
-{	
-
-	//	 getting the application window pointer and setting it 
-	//this is bcoz parent()->parent() is not working in some slots as I expected 
-	QObject* qobj = parent();
-	QWidget* parent = qobject_cast<QWidget*>(qobj->parent());
-	if(parent)
-	{
-		setparentWidget(parent);
-	}
-	m_utils_sptr->setParent(parent);
-    initLayout();
-	m_alg=createAlgorithm();
-	addtoPropertyLabelsHash();
-	
-}
-ICatAdvancedSearch::~ICatAdvancedSearch()
-{
-}
-/* this method sets the parent widget as application window
-*/
-void ICatAdvancedSearch::setparentWidget(QWidget* par)
-{
-	m_applicationWindow= par;
-}
-void ICatAdvancedSearch::initLayout()
-{
-	m_uiForm.setupUi(this);
-
-	// as the instrument/investigation type combo box's popup down and up arrow disappeared when the light blue back ground is set in ICat search dailog 
-	// I'm setting this style sheet to bring the combo box arrows back.
-
-	QString str="QComboBox#Instrument QListView{background-color: white;background-image: url(ICatCombobackground.png);background-attachment: scroll;}"
-		"QComboBox#Instrument QListView QScrollBar:vertical{background-image: url(:/images/ICatComboVScrollbar.png); background-repeat: repeat-y; width: 17px; height:20px;} ";
-	m_uiForm.Instrument->setStyleSheet(str);
-
-    str="QComboBox#InvestigationType QListView{background-color: white;background-image: url(ICatCombobackground.png);background-attachment: scroll;}"
-		"QComboBox#InvestigationType QListView QScrollBar:vertical{background-image: url(:/images/ICatComboVScrollbar.png); background-repeat: repeat-y; width: 17px; height:20px;} ";
-	m_uiForm.InvestigationType->setStyleSheet(str);
-	
-	populateInstrumentBox();
-	populateInvestigationType();
-
-
-	QValidator * val= new QIntValidator(0,100000000,m_uiForm.StartRun);
-	m_uiForm.StartRun->setValidator(val);
-	m_uiForm.EndRun->setValidator(val);
-
-	readSettings();
-
-	connect(m_uiForm.searchButton,SIGNAL(clicked()),this,SLOT(onSearch()));
-	connect(m_uiForm.closeButton,SIGNAL(clicked()),this,SLOT(onClose()));
-	connect(m_uiForm.advSearchtableWidget,SIGNAL(itemDoubleClicked(QTableWidgetItem* )),
-		this,SLOT(investigationSelected(QTableWidgetItem* )));
-	connect(this,SIGNAL(error(const QString&)),parent()->parent(),SLOT(writeErrorToLogWindow(const QString& )));
-	connect(m_uiForm.startdatetoolButton,SIGNAL(clicked()),this,SLOT(popupCalendar()));
-	connect(m_uiForm.enddatetoolButton,SIGNAL(clicked()),this,SLOT(popupCalendar()));
-	connect(m_uiForm.helpButton,SIGNAL(clicked()),this,SLOT(helpButtonClicked()));
-
-	m_uiForm.StartRun->installEventFilter(this);
-	m_uiForm.EndRun->installEventFilter(this);
-	m_uiForm.Keywords->installEventFilter(this);
-	m_uiForm.advframeWidget->installEventFilter(this);
-	m_uiForm.InvestigationName->installEventFilter(this);
-	m_uiForm.InvestigationAbstract->installEventFilter(this);
-	m_uiForm.SampleName->installEventFilter(this);
-	m_uiForm.InvestigatorSurName->installEventFilter(this);
-	m_uiForm.DataFileName->installEventFilter(this);
-}
-
-void ICatAdvancedSearch::populateInstrumentBox()
-{	
-	try{
-		if(!m_utils_sptr)
-			return;
-		m_utils_sptr->populateInstrumentBox(m_uiForm.Instrument);
-	}
-	catch(std::invalid_argument& e)
-	{
-		emit error(e.what());
-		return;
-	}
-	catch (Mantid::Kernel::Exception::NotFoundError& e)
-	{
-		emit error(e.what());
-		return;
-	
-	}
-	catch(std::runtime_error & e)
-	{
-		emit error(e.what());
-		return;
-	}
-	catch(...)
-	{
-		emit error("Error when Populating the instruments box");
-	}
-	return;
-
-}
-
-void ICatAdvancedSearch::populateInvestigationType()
-{
-  std::vector<std::string> invstList;
-  try
-  {
-	invstList = executeListInvestigationTypes();
-  }
-  catch(std::runtime_error & e)
-  {
-    emit error(e.what());
-  }
-	if(invstList.empty())
-	{
-		emit error("Investigation Types list is empty");
-
-	}
-	std::vector<std::string>::const_iterator citr;
-	// loop through values
-	for(citr=invstList.begin();citr!=invstList.end();++citr)
-	{
-		//populate the instrument box  
-		m_uiForm.InvestigationType->addItem(QString::fromStdString(*citr));
-
-	}
-	//sorting the combo by instrument name;
-	m_uiForm.InvestigationType->model()->sort(0);
-	m_uiForm.InvestigationType->insertItem(-1,"");
-
-}
-
-std::vector<std::string> ICatAdvancedSearch:: executeListInvestigationTypes()
-{	
-	QString algName("CatalogListInvestigationTypes");
-	const int version=-1;
-	Mantid::API::IAlgorithm_sptr alg;
-	try
-	{
-		alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
-	}
-	catch(...)
-	{
-		throw std::runtime_error("Error when Populating the Investigations types list box"); 
-		
-	}
-		
-	Poco::ActiveResult<bool> result(alg->executeAsync());
-	while( !result.available() )
-	{
-		QCoreApplication::processEvents();
-	}
-	if(!alg->isExecuted())
-	{
-
-		//if the algorithm failed check the session id passed is valid
-		if(! m_utils_sptr->isSessionValid(alg))
-		{			
-			//at this point session is invalid, popup loginbox to login
-			if(m_utils_sptr->login())
-			{
-			//now populate instrument box
-			 std::vector<std::string> invstTypes =executeListInvestigationTypes();
-			 return invstTypes;
-			}
-      else
-      {
-        throw std::runtime_error("Please Login to the information catalog using the login menu provided to do the investigation search.");
-      }
-		}
-		else
-		{			
-			return std::vector<std::string>();
-		}
-	
-	}
-
-	std::vector<std::string> invstlist ;
-	try
-	{
-		
-	  invstlist= alg->getProperty("InvestigationTypes");
-	}
-	catch (Mantid::Kernel::Exception::NotFoundError&)
-	{
-		throw  std::runtime_error(" Error when retrieving the Investigation Types from the selected  catalog");
-	}
-	return invstlist;
-	
-	
-}
-
-Mantid::API::IAlgorithm_sptr ICatAdvancedSearch::createAlgorithm()
-{
-	QString algName("CatalogSearch");
-	Mantid::API::IAlgorithm_sptr alg;
-	const int version=-1;
-	try
-	{
-	alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
-	}
-	catch(...)
-	{
-		throw std::runtime_error("Error when creating search algorithm"); 
-	}
-	return alg;
-
-}
-
-void ICatAdvancedSearch	::onSearch()
-{
-	m_ws_sptr.reset();
-	//before starting new search investigations clear the old one.
-	m_utils_sptr->clearSearch(m_uiForm.advSearchtableWidget,"advanced_investigations");
-
-	//update the label status
-	m_utils_sptr->setLabelText(m_uiForm.advsearchLabel,"Searching investigations...");
-
-	QString invstName;
-	QString invstAbstract;
-	QString sampleName;
-	QString invstSurName;
-	QString dataFileName;
-	QString instrName;
-	QString invstType;
-	QString keywords;
-
-	bool bCase;
-	double startRun=0,endRun=0;
-	QString startDate,endDate;
-
-	getInvestigationName(invstName);
-	getInvestigationAbstract(invstAbstract);
-	getSampleName(sampleName);
-	getInvestigatorSurName(invstSurName);
-	getDatafileName(dataFileName);
-	getCaseSensitive(bCase);
-	getInvestigationType(invstType);
-	getRunNumbers(startRun,endRun);
-	getDates(startDate,endDate);
-	getInstrument(instrName);
-	getKeyWords(keywords);
-		
-	if(!setProperty("StartRun",startRun))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-	if(!setProperty("EndRun",endRun))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-	if(!setProperty("Instrument",instrName.toStdString()))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-	if(!setProperty("StartDate",startDate.toStdString()))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-	if(!setProperty("EndDate",endDate.toStdString()))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-
-	if(!setProperty("Case Sensitive",bCase))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-	if(!setProperty("Keywords",keywords.toStdString()))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-
-	if(!setProperty("Investigation Name",invstName.toStdString()))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-	if(!setProperty("Investigation Abstract",invstAbstract.toStdString()))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-	if(!setProperty("Investigation Type",invstType.toStdString()))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-	if(!setProperty("Sample Name",sampleName.toStdString()))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-	if(!setProperty("Investigator SurName",invstSurName.toStdString()))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-	if(!setProperty("DataFile Name",dataFileName.toStdString()))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-	if(!setProperty("OutputWorkspace","advanced_investigations"))
-	{
-		updatesearchResults(m_ws_sptr);
-		return ;
-	}
-	Poco::ActiveResult<bool> result(m_alg->executeAsync());
-	while(!result.available() )
-	{
-		QCoreApplication::processEvents();
-		
-	}
-	if(result.available())
-	{
-		//if(!m_alg->isExecuted())
-		if(result.failed())
-		{			
-			m_ws_sptr.reset();
-			updatesearchResults(m_ws_sptr);
-			return ;
-		}
-		if(AnalysisDataService::Instance().doesExist("advanced_investigations"))
-		{
-			m_ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
-				(AnalysisDataService::Instance().retrieve("advanced_investigations"));
-			updatesearchResults(m_ws_sptr);
-		}
-
-		
-	}
-	return ;
-
-	
-}
-
-struct Contains
-{ 
-Contains(std::string name):m_name(name){}
-bool operator()(Mantid::Kernel::Property* prop)
-{
-std::string name=prop->name();
-std::string::iterator pos = std::remove_if(name.begin(),name.end(), isspace);
-name.erase(pos,name.end());//removing the sapce
-
-return (!name.compare(m_name));
-}
-std::string m_name;
-
-};
-
-/** This method adds prpoerty name and validator label for the property to a hash table
-  * This method iterates through each widget in the search grid layout and gets the label widget
-  * and if it's validator label adds this to a hash table.
-  * validator label objectname  for each property is "propertyname_2" eg;"StartDate_2"
-  * from the label object name remove the "_2" to get propertyname
-  * some property has space between words.remove the space(as space not allowed in QT object names)
-  * and compare with propertyname to know the label is a validator label
-*/
-void ICatAdvancedSearch::addtoPropertyLabelsHash()
-{		
-	//get total row and column count in the gridlayout where search controls are placed
-	int totalcol= m_uiForm.gridLayout->columnCount();
-	int totalrow =m_uiForm.gridLayout->rowCount();
-	//loop through each widget in the gridlayout
-	for (int row=0;row<totalrow;++row)
-	{
-		for (int col=0;col<totalcol;++col)
-		{
-			QLayoutItem  *item= m_uiForm.gridLayout->itemAtPosition(row,col); 
-			if(!item) continue;
-			QWidget* widget=item->widget();
-			if(!widget) continue;
-			QLabel* label=qobject_cast<QLabel*>(widget);
-			if(!label)
-				continue;
-			
-			//validator labels is named as "propertyname_2",
-			// remove "_2" from label name to get property name
-			int index=label->objectName().indexOf("_");
-			if(index!=-1)
-			{
-				QString name;
-				name=label->objectName().left(index);
-				std::string propName=name.toStdString();
-				
-				std::vector<Mantid::Kernel::Property*> props=m_alg->getProperties();
-				//if this name exists in algorithm properties vector it's a property validator label
-				std::vector<Mantid::Kernel::Property*>::iterator result;
-				result=std::find_if(props.begin(),props.end(),Contains(propName));
-				if(result!=props.end())
-				{				
-					//at this point the label is a validator label
-					m_propLabelHash[QString::fromStdString((*result)->name())]=label;
-					label->hide();//initially hide the label 
-
-				}
-			}
-			
-		}
-	}
-	
-}
-
-/// show invalid marker labels
-void ICatAdvancedSearch::showInvalidMarkerLabel(const QString& name)
-{
-	if(m_propLabelHash.contains(name))
-	{	
-		std::string documentation;
-		std::vector<Mantid::Kernel::Property*> props=m_alg->getProperties();
-		//if this name exists in algorithm properties vector it's a proprty validator label
-		std::vector<Mantid::Kernel::Property*>::iterator result;
-		result=std::find_if(props.begin(),props.end(),Contains(name.toStdString()));
-		if(result!=props.end())
-		{
-			documentation=(*result)->documentation();
-
-		}
-		m_propLabelHash.value(name)->setToolTip(QString::fromStdString(documentation));
-		m_propLabelHash.value(name)->show();
-	}
-}
-/// hide invalid marker labels
-void ICatAdvancedSearch::hideInvalidMarkerLabel(const QString& name)
-{
-	if(m_propLabelHash.contains(name))
-	{
-		if(m_propLabelHash.value(name)->isVisible())
-		{
-			m_propLabelHash.value(name)->hide();
-		}
-	}
-}
-
-void ICatAdvancedSearch::getInvestigationName(QString& invstName)
-{
-	invstName = m_uiForm.InvestigationName->text();
-}
-void ICatAdvancedSearch::getInvestigationAbstract(QString& invstAbstract)
-{
-	invstAbstract = m_uiForm.InvestigationAbstract->text();
-}
-void ICatAdvancedSearch::getInvestigatorSurName(QString& invstSurName)
-{
-	invstSurName = m_uiForm.InvestigatorSurName->text();
-}
-
-void ICatAdvancedSearch::getSampleName(QString& sampleName)
-{
-	sampleName = m_uiForm.SampleName->text();
-}
-			
-void ICatAdvancedSearch::getDatafileName(QString& dataFileName)
-{
-	dataFileName = m_uiForm.DataFileName->text();
-}
-
-void ICatAdvancedSearch::getInvestigationType(QString& invstType)
-{
-
-	invstType=m_uiForm.InvestigationType->currentText();
-}
-
-void ICatAdvancedSearch::getRunNumbers(double& startRun,double& endRun)
-{
-	endRun = m_uiForm.EndRun->text().toDouble();
-	startRun = m_uiForm.StartRun->text().toDouble();
-}
-void ICatAdvancedSearch::getDates(QString& startDate,QString& endDate)
-{
-
-	startDate = m_uiForm.StartDate->text();
-	endDate =m_uiForm.EndDate->text();
-	if(!startDate.compare("//",Qt::CaseInsensitive))
-	{
-		startDate="";
-	}
-	if(!endDate.compare("//",Qt::CaseInsensitive))
-	{
-		endDate="";
-	}
-}
-void ICatAdvancedSearch::getInstrument(QString& instrName)
-{
-	instrName=m_uiForm.Instrument->currentText();
-}
-void ICatAdvancedSearch::getCaseSensitive(bool & bCase )
-{
-	bCase= m_uiForm.casesensitiveBox->isChecked();
-}
-void ICatAdvancedSearch::getKeyWords(QString& keywords)
-{
-	keywords=m_uiForm.Keywords->text();
-}
-
-/* This method updates the search result to search tree
- * @param ws_sptr :: workspace shared pointer
-*/ 
-void ICatAdvancedSearch::updatesearchResults(ITableWorkspace_sptr& ws_sptr )
-{	
-	//ICatUtils utils;
-	if(!m_utils_sptr)
-		return;
-	m_utils_sptr->resetSearchResultsWidget(m_uiForm.advSearchtableWidget);
-	m_utils_sptr->updatesearchResults(ws_sptr,m_uiForm.advSearchtableWidget);
-	m_utils_sptr->updateSearchLabel(ws_sptr,m_uiForm.advsearchLabel);
-
-}
-
-/** This method closes the search widget.
-*/
-void ICatAdvancedSearch::onClose()
-{
-	saveSettings();
-	this->close();
-	QObject* qobj=parent();
-	QWidget* parent=qobject_cast<QWidget*>(qobj);
-	if(parent)
-	{
-		parent->close();
-	}
-}
-
-/** This method is called when an investigation is selected  from investigations list
-  *@param item ::  item in the table
-*/
-void ICatAdvancedSearch::investigationSelected(QTableWidgetItem * item )
-{
-	//ICatUtils utils;
-	if(!m_utils_sptr)
-		return;
-	m_utils_sptr->investigationSelected(m_uiForm.advSearchtableWidget,item,m_applicationWindow,m_ws_sptr);
-}
-
-///popup DateTime calender to select date
-void ICatAdvancedSearch:: popupCalendar()
-{
-	if(!m_utils_sptr)
-		return;
-
-	m_utils_sptr->popupCalendar(this);
-	
-	QObject * qsender= sender();
-	if(!qsender) return;
-	 m_sender=qsender;
-	
-}
-
-///This signal is selects a date from the calendarwidget and 
-//set the selected to start and end date boxes.
-void ICatAdvancedSearch::getDate(const QDate& date  )
-{
-	m_utils_sptr->closeCalendarWidget();//close the calendar widget
-	if(!m_sender) return;
-
-	//set the date to start and end line edit
-	if(!m_sender->objectName().compare("startdatetoolButton"))
-	{
-	m_uiForm.StartDate->setText(date.toString("dd/MM/yyyy"));
-	}
-	if(!m_sender->objectName().compare("enddatetoolButton"))
-	{
-	m_uiForm.EndDate->setText(date.toString("dd/MM/yyyy"));
-	}
-}
-
-//handler for helpbutton
-void ICatAdvancedSearch::helpButtonClicked()
-{
-	QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Advanced_Search"));
-
-}
-
-/** This method saves search settings
-*/
-void ICatAdvancedSearch::saveSettings()
-{
-	QSettings searchsettings;
-	searchsettings.beginGroup("ICatSettings/AdvancedSearch");
-	searchsettings.setValue("Start Run",m_uiForm.StartRun->text());
-    searchsettings.setValue("End Run",m_uiForm.EndRun->text());
-	searchsettings.setValue("Instrument",m_uiForm.Instrument->currentText());
-	searchsettings.setValue("Start Date",m_uiForm.StartDate->text());
-	searchsettings.setValue("End Date",m_uiForm.EndDate->text());
-	searchsettings.setValue("Keywords",m_uiForm.Keywords->text());
-	searchsettings.setValue("Case Sensitive",m_uiForm.casesensitiveBox->isChecked());
-
-	searchsettings.setValue("Investigation Name",m_uiForm.InvestigationName->text());
-	searchsettings.setValue("Investigation Abstract",m_uiForm.InvestigationAbstract->text());
-	searchsettings.setValue("Sample Name",m_uiForm.SampleName->text());
-	searchsettings.setValue("Investigators Surname",m_uiForm.InvestigatorSurName->text());
-	searchsettings.setValue("Datafile Name",m_uiForm.DataFileName->text());
-	searchsettings.setValue("Investigation Type",m_uiForm.InvestigationType->currentText());
-	searchsettings.endGroup();
-
-}
-
-/// read settings from registry
-void ICatAdvancedSearch::readSettings()
-{
-	QSettings searchsettings;
-	searchsettings.beginGroup("ICatSettings/AdvancedSearch");
-	m_uiForm.StartRun->setText(searchsettings.value("Start Run").toString());
-	m_uiForm.EndRun->setText(searchsettings.value("End Run").toString());
-	//m_uiForm.Instrument->setItemText (0,searchsettings.value("instrument").toString());
-	int index=m_uiForm.Instrument->findText(searchsettings.value("Instrument").toString());
-	if(index!=-1)
-	{
-		m_uiForm.Instrument->setCurrentIndex(index);
-	}
-
-	m_uiForm.StartDate->setText(searchsettings.value("Start Date").toString());
-	m_uiForm.EndDate->setText(searchsettings.value("End Date").toString());
-	m_uiForm.casesensitiveBox->setChecked(searchsettings.value("Case Sensitive").toBool());
-	m_uiForm.InvestigationName->setText(searchsettings.value("Investigation Name").toString());
-	m_uiForm.InvestigationAbstract->setText(searchsettings.value("Investigation Abstract").toString());
-	m_uiForm.SampleName->setText(searchsettings.value("Sample Name").toString());
-	m_uiForm.InvestigatorSurName->setText(searchsettings.value("Investigators Surname").toString());
-	m_uiForm.DataFileName->setText(searchsettings.value("Datafile Name").toString());
-	index=m_uiForm.InvestigationType->findText(searchsettings.value("Investigation Type").toString());
-	if(index!=-1)
-	{
-		m_uiForm.InvestigationType->setCurrentIndex(index);
-	}
-
-
-	searchsettings.endGroup();
-}
-bool ICatAdvancedSearch::eventFilter(QObject *obj, QEvent *event)
-{
-	if (event->type() ==QEvent::FocusIn && obj==m_uiForm.advframeWidget)
-	{		
-		if(m_utils_sptr->calendarWidget())
-		{
-			m_utils_sptr->calendarWidget()->hide();
-		}
-	
-	}
-	else if (event->type()==QEvent::MouseButtonPress)
-	{
-		if(m_utils_sptr->calendarWidget())
-		{
-			m_utils_sptr->calendarWidget()->hide();
-		}
-
-	}
-	else
-	{
-		// standard event processing
-		return QWidget::eventFilter(obj, event);
-	}
-	return true;
-}
-
-
-
-
-
+
+#include "MantidQtMantidWidgets/ICatAdvancedSearch.h"
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidAPI/AnalysisDataService.h"
+#include "MantidAPI/Column.h"
+#include "MantidAPI/TableRow.h" 
+
+#include <QDesktopServices>
+#include <QSettings>
+#include <QUrl>
+
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
+using namespace MantidQt::MantidWidgets;
+
+ICatAdvancedSearch::ICatAdvancedSearch(QWidget* par):
+QWidget(par),m_utils_sptr(new ICatUtils),m_applicationWindow(NULL)
+{	
+
+	//	 getting the application window pointer and setting it 
+	//this is bcoz parent()->parent() is not working in some slots as I expected 
+	QObject* qobj = parent();
+	QWidget* parent = qobject_cast<QWidget*>(qobj->parent());
+	if(parent)
+	{
+		setparentWidget(parent);
+	}
+	m_utils_sptr->setParent(parent);
+    initLayout();
+	m_alg=createAlgorithm();
+	addtoPropertyLabelsHash();
+	
+}
+ICatAdvancedSearch::~ICatAdvancedSearch()
+{
+}
+/* this method sets the parent widget as application window
+*/
+void ICatAdvancedSearch::setparentWidget(QWidget* par)
+{
+	m_applicationWindow= par;
+}
+void ICatAdvancedSearch::initLayout()
+{
+	m_uiForm.setupUi(this);
+
+	// as the instrument/investigation type combo box's popup down and up arrow disappeared when the light blue back ground is set in ICat search dailog 
+	// I'm setting this style sheet to bring the combo box arrows back.
+
+	QString str="QComboBox#Instrument QListView{background-color: white;background-image: url(ICatCombobackground.png);background-attachment: scroll;}"
+		"QComboBox#Instrument QListView QScrollBar:vertical{background-image: url(:/images/ICatComboVScrollbar.png); background-repeat: repeat-y; width: 17px; height:20px;} ";
+	m_uiForm.Instrument->setStyleSheet(str);
+
+    str="QComboBox#InvestigationType QListView{background-color: white;background-image: url(ICatCombobackground.png);background-attachment: scroll;}"
+		"QComboBox#InvestigationType QListView QScrollBar:vertical{background-image: url(:/images/ICatComboVScrollbar.png); background-repeat: repeat-y; width: 17px; height:20px;} ";
+	m_uiForm.InvestigationType->setStyleSheet(str);
+	
+	populateInstrumentBox();
+	populateInvestigationType();
+
+
+	QValidator * val= new QIntValidator(0,100000000,m_uiForm.StartRun);
+	m_uiForm.StartRun->setValidator(val);
+	m_uiForm.EndRun->setValidator(val);
+
+	readSettings();
+
+	connect(m_uiForm.searchButton,SIGNAL(clicked()),this,SLOT(onSearch()));
+	connect(m_uiForm.closeButton,SIGNAL(clicked()),this,SLOT(onClose()));
+	connect(m_uiForm.advSearchtableWidget,SIGNAL(itemDoubleClicked(QTableWidgetItem* )),
+		this,SLOT(investigationSelected(QTableWidgetItem* )));
+	connect(this,SIGNAL(error(const QString&)),parent()->parent(),SLOT(writeErrorToLogWindow(const QString& )));
+	connect(m_uiForm.startdatetoolButton,SIGNAL(clicked()),this,SLOT(popupCalendar()));
+	connect(m_uiForm.enddatetoolButton,SIGNAL(clicked()),this,SLOT(popupCalendar()));
+	connect(m_uiForm.helpButton,SIGNAL(clicked()),this,SLOT(helpButtonClicked()));
+
+	m_uiForm.StartRun->installEventFilter(this);
+	m_uiForm.EndRun->installEventFilter(this);
+	m_uiForm.Keywords->installEventFilter(this);
+	m_uiForm.advframeWidget->installEventFilter(this);
+	m_uiForm.InvestigationName->installEventFilter(this);
+	m_uiForm.InvestigationAbstract->installEventFilter(this);
+	m_uiForm.SampleName->installEventFilter(this);
+	m_uiForm.InvestigatorSurName->installEventFilter(this);
+	m_uiForm.DataFileName->installEventFilter(this);
+}
+
+void ICatAdvancedSearch::populateInstrumentBox()
+{	
+	try{
+		if(!m_utils_sptr)
+			return;
+		m_utils_sptr->populateInstrumentBox(m_uiForm.Instrument);
+	}
+	catch(std::invalid_argument& e)
+	{
+		emit error(e.what());
+		return;
+	}
+	catch (Mantid::Kernel::Exception::NotFoundError& e)
+	{
+		emit error(e.what());
+		return;
+	
+	}
+	catch(std::runtime_error & e)
+	{
+		emit error(e.what());
+		return;
+	}
+	catch(...)
+	{
+		emit error("Error when Populating the instruments box");
+	}
+	return;
+
+}
+
+void ICatAdvancedSearch::populateInvestigationType()
+{
+  std::vector<std::string> invstList;
+  try
+  {
+	invstList = executeListInvestigationTypes();
+  }
+  catch(std::runtime_error & e)
+  {
+    emit error(e.what());
+  }
+	if(invstList.empty())
+	{
+		emit error("Investigation Types list is empty");
+
+	}
+	std::vector<std::string>::const_iterator citr;
+	// loop through values
+	for(citr=invstList.begin();citr!=invstList.end();++citr)
+	{
+		//populate the instrument box  
+		m_uiForm.InvestigationType->addItem(QString::fromStdString(*citr));
+
+	}
+	//sorting the combo by instrument name;
+	m_uiForm.InvestigationType->model()->sort(0);
+	m_uiForm.InvestigationType->insertItem(-1,"");
+
+}
+
+std::vector<std::string> ICatAdvancedSearch:: executeListInvestigationTypes()
+{	
+	QString algName("CatalogListInvestigationTypes");
+	const int version=-1;
+	Mantid::API::IAlgorithm_sptr alg;
+	try
+	{
+		alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
+	}
+	catch(...)
+	{
+		throw std::runtime_error("Error when Populating the Investigations types list box"); 
+		
+	}
+		
+	Poco::ActiveResult<bool> result(alg->executeAsync());
+	while( !result.available() )
+	{
+		QCoreApplication::processEvents();
+	}
+	if(!alg->isExecuted())
+	{
+
+		//if the algorithm failed check the session id passed is valid
+		if(! m_utils_sptr->isSessionValid(alg))
+		{			
+			//at this point session is invalid, popup loginbox to login
+			if(m_utils_sptr->login())
+			{
+			//now populate instrument box
+			 std::vector<std::string> invstTypes =executeListInvestigationTypes();
+			 return invstTypes;
+			}
+      else
+      {
+        throw std::runtime_error("Please Login to the information catalog using the login menu provided to do the investigation search.");
+      }
+		}
+		else
+		{			
+			return std::vector<std::string>();
+		}
+	
+	}
+
+	std::vector<std::string> invstlist ;
+	try
+	{
+		
+	  invstlist= alg->getProperty("InvestigationTypes");
+	}
+	catch (Mantid::Kernel::Exception::NotFoundError&)
+	{
+		throw  std::runtime_error(" Error when retrieving the Investigation Types from the selected  catalog");
+	}
+	return invstlist;
+	
+	
+}
+
+Mantid::API::IAlgorithm_sptr ICatAdvancedSearch::createAlgorithm()
+{
+	QString algName("CatalogSearch");
+	Mantid::API::IAlgorithm_sptr alg;
+	const int version=-1;
+	try
+	{
+	alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
+	}
+	catch(...)
+	{
+		throw std::runtime_error("Error when creating search algorithm"); 
+	}
+	return alg;
+
+}
+
+void ICatAdvancedSearch	::onSearch()
+{
+	m_ws_sptr.reset();
+	//before starting new search investigations clear the old one.
+	m_utils_sptr->clearSearch(m_uiForm.advSearchtableWidget,"advanced_investigations");
+
+	//update the label status
+	m_utils_sptr->setLabelText(m_uiForm.advsearchLabel,"Searching investigations...");
+
+	QString invstName;
+	QString invstAbstract;
+	QString sampleName;
+	QString invstSurName;
+	QString dataFileName;
+	QString instrName;
+	QString invstType;
+	QString keywords;
+
+	bool bCase;
+	double startRun=0,endRun=0;
+	QString startDate,endDate;
+
+	getInvestigationName(invstName);
+	getInvestigationAbstract(invstAbstract);
+	getSampleName(sampleName);
+	getInvestigatorSurName(invstSurName);
+	getDatafileName(dataFileName);
+	getCaseSensitive(bCase);
+	getInvestigationType(invstType);
+	getRunNumbers(startRun,endRun);
+	getDates(startDate,endDate);
+	getInstrument(instrName);
+	getKeyWords(keywords);
+		
+	if(!setProperty("StartRun",startRun))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+	if(!setProperty("EndRun",endRun))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+	if(!setProperty("Instrument",instrName.toStdString()))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+	if(!setProperty("StartDate",startDate.toStdString()))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+	if(!setProperty("EndDate",endDate.toStdString()))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+
+	if(!setProperty("Case Sensitive",bCase))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+	if(!setProperty("Keywords",keywords.toStdString()))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+
+	if(!setProperty("Investigation Name",invstName.toStdString()))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+	if(!setProperty("Investigation Abstract",invstAbstract.toStdString()))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+	if(!setProperty("Investigation Type",invstType.toStdString()))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+	if(!setProperty("Sample Name",sampleName.toStdString()))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+	if(!setProperty("Investigator SurName",invstSurName.toStdString()))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+	if(!setProperty("DataFile Name",dataFileName.toStdString()))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+	if(!setProperty("OutputWorkspace","advanced_investigations"))
+	{
+		updatesearchResults(m_ws_sptr);
+		return ;
+	}
+	Poco::ActiveResult<bool> result(m_alg->executeAsync());
+	while(!result.available() )
+	{
+		QCoreApplication::processEvents();
+		
+	}
+	if(result.available())
+	{
+		//if(!m_alg->isExecuted())
+		if(result.failed())
+		{			
+			m_ws_sptr.reset();
+			updatesearchResults(m_ws_sptr);
+			return ;
+		}
+		if(AnalysisDataService::Instance().doesExist("advanced_investigations"))
+		{
+			m_ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
+				(AnalysisDataService::Instance().retrieve("advanced_investigations"));
+			updatesearchResults(m_ws_sptr);
+		}
+
+		
+	}
+	return ;
+
+	
+}
+
+struct Contains
+{ 
+Contains(std::string name):m_name(name){}
+bool operator()(Mantid::Kernel::Property* prop)
+{
+std::string name=prop->name();
+std::string::iterator pos = std::remove_if(name.begin(),name.end(), isspace);
+name.erase(pos,name.end());//removing the sapce
+
+return (!name.compare(m_name));
+}
+std::string m_name;
+
+};
+
+/** This method adds prpoerty name and validator label for the property to a hash table
+  * This method iterates through each widget in the search grid layout and gets the label widget
+  * and if it's validator label adds this to a hash table.
+  * validator label objectname  for each property is "propertyname_2" eg;"StartDate_2"
+  * from the label object name remove the "_2" to get propertyname
+  * some property has space between words.remove the space(as space not allowed in QT object names)
+  * and compare with propertyname to know the label is a validator label
+*/
+void ICatAdvancedSearch::addtoPropertyLabelsHash()
+{		
+	//get total row and column count in the gridlayout where search controls are placed
+	int totalcol= m_uiForm.gridLayout->columnCount();
+	int totalrow =m_uiForm.gridLayout->rowCount();
+	//loop through each widget in the gridlayout
+	for (int row=0;row<totalrow;++row)
+	{
+		for (int col=0;col<totalcol;++col)
+		{
+			QLayoutItem  *item= m_uiForm.gridLayout->itemAtPosition(row,col); 
+			if(!item) continue;
+			QWidget* widget=item->widget();
+			if(!widget) continue;
+			QLabel* label=qobject_cast<QLabel*>(widget);
+			if(!label)
+				continue;
+			
+			//validator labels is named as "propertyname_2",
+			// remove "_2" from label name to get property name
+			int index=label->objectName().indexOf("_");
+			if(index!=-1)
+			{
+				QString name;
+				name=label->objectName().left(index);
+				std::string propName=name.toStdString();
+				
+				std::vector<Mantid::Kernel::Property*> props=m_alg->getProperties();
+				//if this name exists in algorithm properties vector it's a property validator label
+				std::vector<Mantid::Kernel::Property*>::iterator result;
+				result=std::find_if(props.begin(),props.end(),Contains(propName));
+				if(result!=props.end())
+				{				
+					//at this point the label is a validator label
+					m_propLabelHash[QString::fromStdString((*result)->name())]=label;
+					label->hide();//initially hide the label 
+
+				}
+			}
+			
+		}
+	}
+	
+}
+
+/// show invalid marker labels
+void ICatAdvancedSearch::showInvalidMarkerLabel(const QString& name)
+{
+	if(m_propLabelHash.contains(name))
+	{	
+		std::string documentation;
+		std::vector<Mantid::Kernel::Property*> props=m_alg->getProperties();
+		//if this name exists in algorithm properties vector it's a proprty validator label
+		std::vector<Mantid::Kernel::Property*>::iterator result;
+		result=std::find_if(props.begin(),props.end(),Contains(name.toStdString()));
+		if(result!=props.end())
+		{
+			documentation=(*result)->documentation();
+
+		}
+		m_propLabelHash.value(name)->setToolTip(QString::fromStdString(documentation));
+		m_propLabelHash.value(name)->show();
+	}
+}
+/// hide invalid marker labels
+void ICatAdvancedSearch::hideInvalidMarkerLabel(const QString& name)
+{
+	if(m_propLabelHash.contains(name))
+	{
+		if(m_propLabelHash.value(name)->isVisible())
+		{
+			m_propLabelHash.value(name)->hide();
+		}
+	}
+}
+
+void ICatAdvancedSearch::getInvestigationName(QString& invstName)
+{
+	invstName = m_uiForm.InvestigationName->text();
+}
+void ICatAdvancedSearch::getInvestigationAbstract(QString& invstAbstract)
+{
+	invstAbstract = m_uiForm.InvestigationAbstract->text();
+}
+void ICatAdvancedSearch::getInvestigatorSurName(QString& invstSurName)
+{
+	invstSurName = m_uiForm.InvestigatorSurName->text();
+}
+
+void ICatAdvancedSearch::getSampleName(QString& sampleName)
+{
+	sampleName = m_uiForm.SampleName->text();
+}
+			
+void ICatAdvancedSearch::getDatafileName(QString& dataFileName)
+{
+	dataFileName = m_uiForm.DataFileName->text();
+}
+
+void ICatAdvancedSearch::getInvestigationType(QString& invstType)
+{
+
+	invstType=m_uiForm.InvestigationType->currentText();
+}
+
+void ICatAdvancedSearch::getRunNumbers(double& startRun,double& endRun)
+{
+	endRun = m_uiForm.EndRun->text().toDouble();
+	startRun = m_uiForm.StartRun->text().toDouble();
+}
+void ICatAdvancedSearch::getDates(QString& startDate,QString& endDate)
+{
+
+	startDate = m_uiForm.StartDate->text();
+	endDate =m_uiForm.EndDate->text();
+	if(!startDate.compare("//",Qt::CaseInsensitive))
+	{
+		startDate="";
+	}
+	if(!endDate.compare("//",Qt::CaseInsensitive))
+	{
+		endDate="";
+	}
+}
+void ICatAdvancedSearch::getInstrument(QString& instrName)
+{
+	instrName=m_uiForm.Instrument->currentText();
+}
+void ICatAdvancedSearch::getCaseSensitive(bool & bCase )
+{
+	bCase= m_uiForm.casesensitiveBox->isChecked();
+}
+void ICatAdvancedSearch::getKeyWords(QString& keywords)
+{
+	keywords=m_uiForm.Keywords->text();
+}
+
+/* This method updates the search result to search tree
+ * @param ws_sptr :: workspace shared pointer
+*/ 
+void ICatAdvancedSearch::updatesearchResults(ITableWorkspace_sptr& ws_sptr )
+{	
+	//ICatUtils utils;
+	if(!m_utils_sptr)
+		return;
+	m_utils_sptr->resetSearchResultsWidget(m_uiForm.advSearchtableWidget);
+	m_utils_sptr->updatesearchResults(ws_sptr,m_uiForm.advSearchtableWidget);
+	m_utils_sptr->updateSearchLabel(ws_sptr,m_uiForm.advsearchLabel);
+
+}
+
+/** This method closes the search widget.
+*/
+void ICatAdvancedSearch::onClose()
+{
+	saveSettings();
+	this->close();
+	QObject* qobj=parent();
+	QWidget* parent=qobject_cast<QWidget*>(qobj);
+	if(parent)
+	{
+		parent->close();
+	}
+}
+
+/** This method is called when an investigation is selected  from investigations list
+  *@param item ::  item in the table
+*/
+void ICatAdvancedSearch::investigationSelected(QTableWidgetItem * item )
+{
+	//ICatUtils utils;
+	if(!m_utils_sptr)
+		return;
+	m_utils_sptr->investigationSelected(m_uiForm.advSearchtableWidget,item,m_applicationWindow,m_ws_sptr);
+}
+
+///popup DateTime calender to select date
+void ICatAdvancedSearch:: popupCalendar()
+{
+	if(!m_utils_sptr)
+		return;
+
+	m_utils_sptr->popupCalendar(this);
+	
+	QObject * qsender= sender();
+	if(!qsender) return;
+	 m_sender=qsender;
+	
+}
+
+///This signal is selects a date from the calendarwidget and 
+//set the selected to start and end date boxes.
+void ICatAdvancedSearch::getDate(const QDate& date  )
+{
+	m_utils_sptr->closeCalendarWidget();//close the calendar widget
+	if(!m_sender) return;
+
+	//set the date to start and end line edit
+	if(!m_sender->objectName().compare("startdatetoolButton"))
+	{
+	m_uiForm.StartDate->setText(date.toString("dd/MM/yyyy"));
+	}
+	if(!m_sender->objectName().compare("enddatetoolButton"))
+	{
+	m_uiForm.EndDate->setText(date.toString("dd/MM/yyyy"));
+	}
+}
+
+//handler for helpbutton
+void ICatAdvancedSearch::helpButtonClicked()
+{
+	QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Advanced_Search"));
+
+}
+
+/** This method saves search settings
+*/
+void ICatAdvancedSearch::saveSettings()
+{
+	QSettings searchsettings;
+	searchsettings.beginGroup("ICatSettings/AdvancedSearch");
+	searchsettings.setValue("Start Run",m_uiForm.StartRun->text());
+    searchsettings.setValue("End Run",m_uiForm.EndRun->text());
+	searchsettings.setValue("Instrument",m_uiForm.Instrument->currentText());
+	searchsettings.setValue("Start Date",m_uiForm.StartDate->text());
+	searchsettings.setValue("End Date",m_uiForm.EndDate->text());
+	searchsettings.setValue("Keywords",m_uiForm.Keywords->text());
+	searchsettings.setValue("Case Sensitive",m_uiForm.casesensitiveBox->isChecked());
+
+	searchsettings.setValue("Investigation Name",m_uiForm.InvestigationName->text());
+	searchsettings.setValue("Investigation Abstract",m_uiForm.InvestigationAbstract->text());
+	searchsettings.setValue("Sample Name",m_uiForm.SampleName->text());
+	searchsettings.setValue("Investigators Surname",m_uiForm.InvestigatorSurName->text());
+	searchsettings.setValue("Datafile Name",m_uiForm.DataFileName->text());
+	searchsettings.setValue("Investigation Type",m_uiForm.InvestigationType->currentText());
+	searchsettings.endGroup();
+
+}
+
+/// read settings from registry
+void ICatAdvancedSearch::readSettings()
+{
+	QSettings searchsettings;
+	searchsettings.beginGroup("ICatSettings/AdvancedSearch");
+	m_uiForm.StartRun->setText(searchsettings.value("Start Run").toString());
+	m_uiForm.EndRun->setText(searchsettings.value("End Run").toString());
+	//m_uiForm.Instrument->setItemText (0,searchsettings.value("instrument").toString());
+	int index=m_uiForm.Instrument->findText(searchsettings.value("Instrument").toString());
+	if(index!=-1)
+	{
+		m_uiForm.Instrument->setCurrentIndex(index);
+	}
+
+	m_uiForm.StartDate->setText(searchsettings.value("Start Date").toString());
+	m_uiForm.EndDate->setText(searchsettings.value("End Date").toString());
+	m_uiForm.casesensitiveBox->setChecked(searchsettings.value("Case Sensitive").toBool());
+	m_uiForm.InvestigationName->setText(searchsettings.value("Investigation Name").toString());
+	m_uiForm.InvestigationAbstract->setText(searchsettings.value("Investigation Abstract").toString());
+	m_uiForm.SampleName->setText(searchsettings.value("Sample Name").toString());
+	m_uiForm.InvestigatorSurName->setText(searchsettings.value("Investigators Surname").toString());
+	m_uiForm.DataFileName->setText(searchsettings.value("Datafile Name").toString());
+	index=m_uiForm.InvestigationType->findText(searchsettings.value("Investigation Type").toString());
+	if(index!=-1)
+	{
+		m_uiForm.InvestigationType->setCurrentIndex(index);
+	}
+
+
+	searchsettings.endGroup();
+}
+bool ICatAdvancedSearch::eventFilter(QObject *obj, QEvent *event)
+{
+	if (event->type() ==QEvent::FocusIn && obj==m_uiForm.advframeWidget)
+	{		
+		if(m_utils_sptr->calendarWidget())
+		{
+			m_utils_sptr->calendarWidget()->hide();
+		}
+	
+	}
+	else if (event->type()==QEvent::MouseButtonPress)
+	{
+		if(m_utils_sptr->calendarWidget())
+		{
+			m_utils_sptr->calendarWidget()->hide();
+		}
+
+	}
+	else
+	{
+		// standard event processing
+		return QWidget::eventFilter(obj, event);
+	}
+	return true;
+}
+
+
+
+
+
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/ICatInvestigation.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/ICatInvestigation.cpp
index 3f9fdef5beec65f8a644e9034133dae03b39e8c1..eba58be7d4642f2d16113103928e63934d6d2264 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/ICatInvestigation.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/ICatInvestigation.cpp
@@ -1,742 +1,742 @@
-//----------------------
-// Includes
-//----------------------
-#include "MantidQtMantidWidgets/ICatInvestigation.h"
-#include "MantidAPI/AnalysisDataService.h"
-#include "MantidAPI/ITableWorkspace.h"
-#include "MantidAPI/Column.h"
-#include "MantidAPI/TableRow.h" 
-#include "MantidKernel/ConfigService.h"
-
-#include<QHeaderView>
-#include <QDesktopServices>
-#include <QUrl>
-
-
-using namespace Mantid::API;
-using namespace MantidQt::MantidWidgets;
-
-//----------------------
-// Public member functions
-//----------------------
-///Constructor
-ICatInvestigation::ICatInvestigation(long long investId,const QString &RbNumber,
-									 const QString &Title,const QString &Instrument,ITableWorkspace_sptr& ws2_sptr,QWidget *par) :
-                                     QWidget(par),m_invstId(investId),m_RbNumber(RbNumber),m_Title(Title),
-									 m_Instrument(Instrument),m_downloadedFileList()
-{
-	initLayout();
-	m_uiForm.invsttableWidget->verticalHeader()->setVisible(false);
-	m_investws_sptr=ws2_sptr;
-	//Tree on LHS of the investigation display	
-	populateInvestigationTreeWidget();
-	//an item selected from the LHS treewidget
-	connect(m_uiForm.invsttreeWidget,SIGNAL(itemClicked (QTreeWidgetItem*, int )),this,SLOT(investigationClicked(QTreeWidgetItem*, int)));
-	/// cancel clicked
-	connect(m_uiForm.cancelButton,SIGNAL(clicked()),this,SLOT(onCancel()));
-
-	connect(m_uiForm.invsttreeWidget,SIGNAL(itemExpanded(QTreeWidgetItem* )),this,SLOT(investigationWidgetItemExpanded(QTreeWidgetItem* )));
-	connect(m_uiForm.invsttableWidget,SIGNAL(itemClicked (QTableWidgetItem* )),this,SLOT(tableItemSelected(QTableWidgetItem* )));
-	
-	//download button clciked
-	connect(m_uiForm.downloadButton,SIGNAL(clicked()),this,SLOT(onDownload()));
-	//load button clicked
-	connect(m_uiForm.LoadButton,SIGNAL(clicked()),this,SLOT(onLoad()));
-	/// send error mesages to logwindow
- 	connect(this,SIGNAL(error(const QString&,int) ),parent()->parent(),SLOT(writeErrorLogWindow(const QString&)));
-	//execute loadraw asynchronously
-	connect(this,SIGNAL(loadRawAsynch(const QString&,const QString&)),parent()->parent(),SLOT(executeLoadRawAsynch(const QString&,const QString& )));
-	//execute loadnexus asynchronously
-	connect(this,SIGNAL(loadNexusAsynch(const QString&,const QString&)),parent()->parent(),SLOT(executeLoadNexusAsynch(const QString&,const QString& )));
-	//select all file button clicked
-	connect(m_uiForm.selectallButton,SIGNAL(clicked()),this,SLOT(onSelectAllFiles()));
-	//download button clicked
-	connect(this,SIGNAL(download(const std::vector<std::string>&,const std::vector<long long>&)),
-		parent()->parent(),SLOT(executeDownloadDataFiles(const std::vector<std::string>&,const std::vector<long long>&)));
-	///
-	connect(this,SIGNAL(executeLoadAlgorithm(const QString&, const QString&, const QString&)),parent()->parent(),
-		SLOT(executeloadAlgorithm(const QString&, const QString&, const QString&)));
-	//helpbutton clicked
-	connect(m_uiForm.helpButton,SIGNAL(clicked()),this,SLOT(helpButtonClicked()));
-}
-
-/// Set up the dialog layout
-void ICatInvestigation::initLayout()
-{
-  m_uiForm.setupUi(this);
-}
-
-/// Poulate the tree widget on LHS
-void ICatInvestigation::populateInvestigationTreeWidget(){
-	
-
-  m_uiForm.invsttreeWidget->setHeaderLabel("");
-	QStringList qlist;
-	qlist.push_back(m_Title);
-	QTreeWidgetItem *item1 = new QTreeWidgetItem(qlist);
-	item1->setToolTip(0,m_Title);
-
-	qlist.clear();
-	QString rbNumber("Rb number: ");
-	rbNumber+=m_RbNumber;
-	qlist.push_back(rbNumber);
-	QTreeWidgetItem *item2 = new QTreeWidgetItem(qlist);
-	item2->setToolTip(0,rbNumber);
-	item1->addChild(item2);
-
-	qlist.clear();
-	QString instrument("Instrument: ");
-	instrument+=m_Instrument;
-	qlist.push_back(instrument);
-	QTreeWidgetItem *item3 = new QTreeWidgetItem(qlist);
-	item1->addChild(item3);
-
-	m_uiForm.invsttreeWidget->insertTopLevelItem(0,item1);
-
-	qlist.clear();
-	qlist.push_back("DataSets");
-	QTreeWidgetItem *item4 = new QTreeWidgetItem(qlist);
-	item1->addChild(item4);
-	item4->setToolTip(0,"View investigations datasets");
-
-	qlist.clear();
-	qlist.push_back("Default");
-	QTreeWidgetItem *item5 = new QTreeWidgetItem(qlist);
-	item4->addChild(item5);
-	item5->setToolTip(0,"View default's files");
-
-	qlist.clear();
-	qlist.push_back("Status:");
-	QTreeWidgetItem *sitem = new QTreeWidgetItem(qlist);
-	item5->addChild(sitem);
-	
-	qlist.clear();
-	qlist.push_back("Type:");
-	QTreeWidgetItem *titem = new QTreeWidgetItem(qlist);
-	item5->addChild(titem);
-	qlist.clear();
-	qlist.push_back("Description:");
-	QTreeWidgetItem* ditem = new QTreeWidgetItem(qlist);
-	item5->addChild(ditem);
-	
-}
-
-///
-void ICatInvestigation::tableItemSelected(QTableWidgetItem*)
-{
-	m_uiForm.downloadButton->setEnabled(true);
-}
-/// execute getdatafIles algorithm
-ITableWorkspace_sptr ICatInvestigation::executeGetdataFiles()
-{
-	QString algName("CatalogGetDataFiles");
-	const int version=1;
-	Mantid::API::ITableWorkspace_sptr  ws_sptr;
-	Mantid::API::IAlgorithm_sptr alg;
+//----------------------
+// Includes
+//----------------------
+#include "MantidQtMantidWidgets/ICatInvestigation.h"
+#include "MantidAPI/AnalysisDataService.h"
+#include "MantidAPI/ITableWorkspace.h"
+#include "MantidAPI/Column.h"
+#include "MantidAPI/TableRow.h" 
+#include "MantidKernel/ConfigService.h"
+
+#include<QHeaderView>
+#include <QDesktopServices>
+#include <QUrl>
+
+
+using namespace Mantid::API;
+using namespace MantidQt::MantidWidgets;
+
+//----------------------
+// Public member functions
+//----------------------
+///Constructor
+ICatInvestigation::ICatInvestigation(long long investId,const QString &RbNumber,
+									 const QString &Title,const QString &Instrument,ITableWorkspace_sptr& ws2_sptr,QWidget *par) :
+                                     QWidget(par),m_invstId(investId),m_RbNumber(RbNumber),m_Title(Title),
+									 m_Instrument(Instrument),m_downloadedFileList()
+{
+	initLayout();
+	m_uiForm.invsttableWidget->verticalHeader()->setVisible(false);
+	m_investws_sptr=ws2_sptr;
+	//Tree on LHS of the investigation display	
+	populateInvestigationTreeWidget();
+	//an item selected from the LHS treewidget
+	connect(m_uiForm.invsttreeWidget,SIGNAL(itemClicked (QTreeWidgetItem*, int )),this,SLOT(investigationClicked(QTreeWidgetItem*, int)));
+	/// cancel clicked
+	connect(m_uiForm.cancelButton,SIGNAL(clicked()),this,SLOT(onCancel()));
+
+	connect(m_uiForm.invsttreeWidget,SIGNAL(itemExpanded(QTreeWidgetItem* )),this,SLOT(investigationWidgetItemExpanded(QTreeWidgetItem* )));
+	connect(m_uiForm.invsttableWidget,SIGNAL(itemClicked (QTableWidgetItem* )),this,SLOT(tableItemSelected(QTableWidgetItem* )));
+	
+	//download button clciked
+	connect(m_uiForm.downloadButton,SIGNAL(clicked()),this,SLOT(onDownload()));
+	//load button clicked
+	connect(m_uiForm.LoadButton,SIGNAL(clicked()),this,SLOT(onLoad()));
+	/// send error mesages to logwindow
+ 	connect(this,SIGNAL(error(const QString&,int) ),parent()->parent(),SLOT(writeErrorLogWindow(const QString&)));
+	//execute loadraw asynchronously
+	connect(this,SIGNAL(loadRawAsynch(const QString&,const QString&)),parent()->parent(),SLOT(executeLoadRawAsynch(const QString&,const QString& )));
+	//execute loadnexus asynchronously
+	connect(this,SIGNAL(loadNexusAsynch(const QString&,const QString&)),parent()->parent(),SLOT(executeLoadNexusAsynch(const QString&,const QString& )));
+	//select all file button clicked
+	connect(m_uiForm.selectallButton,SIGNAL(clicked()),this,SLOT(onSelectAllFiles()));
+	//download button clicked
+	connect(this,SIGNAL(download(const std::vector<std::string>&,const std::vector<long long>&)),
+		parent()->parent(),SLOT(executeDownloadDataFiles(const std::vector<std::string>&,const std::vector<long long>&)));
+	///
+	connect(this,SIGNAL(executeLoadAlgorithm(const QString&, const QString&, const QString&)),parent()->parent(),
+		SLOT(executeloadAlgorithm(const QString&, const QString&, const QString&)));
+	//helpbutton clicked
+	connect(m_uiForm.helpButton,SIGNAL(clicked()),this,SLOT(helpButtonClicked()));
+}
+
+/// Set up the dialog layout
+void ICatInvestigation::initLayout()
+{
+  m_uiForm.setupUi(this);
+}
+
+/// Poulate the tree widget on LHS
+void ICatInvestigation::populateInvestigationTreeWidget(){
+	
+
+  m_uiForm.invsttreeWidget->setHeaderLabel("");
+	QStringList qlist;
+	qlist.push_back(m_Title);
+	QTreeWidgetItem *item1 = new QTreeWidgetItem(qlist);
+	item1->setToolTip(0,m_Title);
+
+	qlist.clear();
+	QString rbNumber("Rb number: ");
+	rbNumber+=m_RbNumber;
+	qlist.push_back(rbNumber);
+	QTreeWidgetItem *item2 = new QTreeWidgetItem(qlist);
+	item2->setToolTip(0,rbNumber);
+	item1->addChild(item2);
+
+	qlist.clear();
+	QString instrument("Instrument: ");
+	instrument+=m_Instrument;
+	qlist.push_back(instrument);
+	QTreeWidgetItem *item3 = new QTreeWidgetItem(qlist);
+	item1->addChild(item3);
+
+	m_uiForm.invsttreeWidget->insertTopLevelItem(0,item1);
+
+	qlist.clear();
+	qlist.push_back("DataSets");
+	QTreeWidgetItem *item4 = new QTreeWidgetItem(qlist);
+	item1->addChild(item4);
+	item4->setToolTip(0,"View investigations datasets");
+
+	qlist.clear();
+	qlist.push_back("Default");
+	QTreeWidgetItem *item5 = new QTreeWidgetItem(qlist);
+	item4->addChild(item5);
+	item5->setToolTip(0,"View default's files");
+
+	qlist.clear();
+	qlist.push_back("Status:");
+	QTreeWidgetItem *sitem = new QTreeWidgetItem(qlist);
+	item5->addChild(sitem);
+	
+	qlist.clear();
+	qlist.push_back("Type:");
+	QTreeWidgetItem *titem = new QTreeWidgetItem(qlist);
+	item5->addChild(titem);
+	qlist.clear();
+	qlist.push_back("Description:");
+	QTreeWidgetItem* ditem = new QTreeWidgetItem(qlist);
+	item5->addChild(ditem);
+	
+}
+
+///
+void ICatInvestigation::tableItemSelected(QTableWidgetItem*)
+{
+	m_uiForm.downloadButton->setEnabled(true);
+}
+/// execute getdatafIles algorithm
+ITableWorkspace_sptr ICatInvestigation::executeGetdataFiles()
+{
+	QString algName("CatalogGetDataFiles");
+	const int version=1;
+	Mantid::API::ITableWorkspace_sptr  ws_sptr;
+	Mantid::API::IAlgorithm_sptr alg;
+	try
+	{
+		alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
+	}
+	catch(...)
+	{
+		throw std::runtime_error("Error when loading the data files associated to the selected investigation "); 
+	}
+	try
+	{
+		alg->setProperty("InvestigationId",m_invstId);
+		alg->setProperty("FilterLogFiles",isDataFilesChecked());
+		alg->setPropertyValue("OutputWorkspace","datafiles");
+	}
+	catch(std::invalid_argument& e)
+	{		
+		emit error(e.what());
+		return ws_sptr;
+	}
+	catch (Mantid::Kernel::Exception::NotFoundError& e)
+	{
+		emit error(e.what());
+		return ws_sptr;
+	}
+	
 	try
 	{
-		alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
-	}
-	catch(...)
-	{
-		throw std::runtime_error("Error when loading the data files associated to the selected investigation "); 
-	}
-	try
-	{
-		alg->setProperty("InvestigationId",m_invstId);
-		alg->setProperty("FilterLogFiles",isDataFilesChecked());
-		alg->setPropertyValue("OutputWorkspace","datafiles");
-	}
-	catch(std::invalid_argument& e)
-	{		
-		emit error(e.what());
-		return ws_sptr;
-	}
-	catch (Mantid::Kernel::Exception::NotFoundError& e)
-	{
-		emit error(e.what());
-		return ws_sptr;
-	}
-	
-	try
-	{
 		Poco::ActiveResult<bool> result(alg->executeAsync());
 		while( !result.available() )
 		{
 			QCoreApplication::processEvents();
 		}
-	}
+	}
 	catch(...)
     {     
 		return ws_sptr;
-    }
-	if(AnalysisDataService::Instance().doesExist("datafiles"))
-	{
-	ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
-		(AnalysisDataService::Instance().retrieve("datafiles"));
-	}
-	return ws_sptr;
-	
-}
-/// This  executes the GetDataSets algorithm and creates workspace
-ITableWorkspace_sptr ICatInvestigation::executeGetdataSets()
-{
-	QString algName("CatalogGetDataSets");
-	const int version=1;
-	ITableWorkspace_sptr ws_sptr;
-	Mantid::API::IAlgorithm_sptr alg;
+    }
+	if(AnalysisDataService::Instance().doesExist("datafiles"))
+	{
+	ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
+		(AnalysisDataService::Instance().retrieve("datafiles"));
+	}
+	return ws_sptr;
+	
+}
+/// This  executes the GetDataSets algorithm and creates workspace
+ITableWorkspace_sptr ICatInvestigation::executeGetdataSets()
+{
+	QString algName("CatalogGetDataSets");
+	const int version=1;
+	ITableWorkspace_sptr ws_sptr;
+	Mantid::API::IAlgorithm_sptr alg;
+	try
+	{
+		alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
+	}
+	catch(...)
+	{
+		throw std::runtime_error("Error when displaying the data sets associated to the selected investigation"); 
+	}
+	try
+	{
+		alg->setProperty("InvestigationId",m_invstId);
+		alg->setPropertyValue("OutputWorkspace","datasets");
+	}
+	catch(std::invalid_argument& e)
+	{		
+		emit error(e.what());
+		return ws_sptr;
+	}
+	catch (Mantid::Kernel::Exception::NotFoundError& e)
+	{
+		emit error(e.what());
+		return ws_sptr;
+	}
+	
 	try
 	{
-		alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
-	}
-	catch(...)
-	{
-		throw std::runtime_error("Error when displaying the data sets associated to the selected investigation"); 
-	}
-	try
-	{
-		alg->setProperty("InvestigationId",m_invstId);
-		alg->setPropertyValue("OutputWorkspace","datasets");
-	}
-	catch(std::invalid_argument& e)
-	{		
-		emit error(e.what());
-		return ws_sptr;
-	}
-	catch (Mantid::Kernel::Exception::NotFoundError& e)
-	{
-		emit error(e.what());
-		return ws_sptr;
-	}
-	
-	try
-	{
 		Poco::ActiveResult<bool> result(alg->executeAsync());
 		while( !result.available() )
 		{
 			QCoreApplication::processEvents();
 		}
-	}
+	}
 	catch(...)
 	{     
 		return ws_sptr;
-	}
-	if(AnalysisDataService::Instance().doesExist("datasets"))
-	{
-		ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
-			(AnalysisDataService::Instance().retrieve("datasets"));
-	}
-
-	return ws_sptr;
-}
-
-/** this method gets called when an item on the investigation tree widget is  clicked
-  *@param item :: selected item
-  *@param int :: 
-*/
-void ICatInvestigation::investigationClicked(QTreeWidgetItem* item, int)
-{
-	if(!item)return;
-	if(!item->text(0).compare("Default"))
-	{			
-		if(isDataFilesChecked())
-		{
-			if(!m_filteredws_sptr)
-			{
-        updateLabel("Loading data files...");
-				m_filteredws_sptr=executeGetdataFiles();
-			}
-      
-			populateinvestigationWidget(m_filteredws_sptr,"DataFiles",true);
-		}
-		else
-		{
-			if(!m_datafilesws_sptr)
-			{
-        updateLabel("Loading files...");
-				m_datafilesws_sptr = executeGetdataFiles();
-			}
-			if(!m_datafilesws_sptr) return;
-			populateinvestigationWidget(m_datafilesws_sptr,"DataFiles",true);
-		}
-	}
-	else if(!item->text(0).compare("DataSets"))
-	{
-		if(!m_datasetsws_sptr){
-      updateLabel("Loading datasets...");
-			m_datasetsws_sptr= executeGetdataSets();
-
-		}
-		if(!m_datasetsws_sptr)return;
-		populateinvestigationWidget(m_datasetsws_sptr,"DataSets",false);
-	}
-	
-}
-/**This method populates the investigation table widget
-  *@param ws_sptr :: shared pointer to workspace
-  *@param  type - string used to identify datasets or data files
-  *@param bEnable :: flag to enable sorting
-*/
-void ICatInvestigation::populateinvestigationWidget(Mantid::API::ITableWorkspace_sptr dataws_sptr,const QString& type,bool bEnable)
-{	
-	if(!dataws_sptr){return;}
-
-	Mantid::API::ITableWorkspace_sptr ws_sptr(dataws_sptr);
-  if(!ws_sptr){return;}
-
-	//turn off sorting as per QT documentation
-	m_uiForm.invsttableWidget->setSortingEnabled(false);
-	
-	//below for loop for clearing the table widget on each mouse click,otherwise rows will be appended.
-	// table widget clear() method is clearing only the item text,not removing the rows,columns
-	// so i'm using removeRow().When I removed the row from top of the table it was not working.
-
-	for (int i=m_uiForm.invsttableWidget->rowCount()-1;i>=0;--i)
-	{
-		m_uiForm.invsttableWidget->removeRow(i);
-	}
-	m_uiForm.invsttableWidget->setRowCount(ws_sptr->rowCount());
-	m_uiForm.invsttableWidget->setColumnCount(ws_sptr->columnCount());
-	 
-	for (int i=0;i<ws_sptr->rowCount();++i)
-	{
-		//setting the row height of tableWidget 
-		m_uiForm.invsttableWidget->setRowHeight(i,20);
-	}
-
-	QStringList qlabelList;
+	}
+	if(AnalysisDataService::Instance().doesExist("datasets"))
+	{
+		ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
+			(AnalysisDataService::Instance().retrieve("datasets"));
+	}
+
+	return ws_sptr;
+}
+
+/** this method gets called when an item on the investigation tree widget is  clicked
+  *@param item :: selected item
+  *@param int :: 
+*/
+void ICatInvestigation::investigationClicked(QTreeWidgetItem* item, int)
+{
+	if(!item)return;
+	if(!item->text(0).compare("Default"))
+	{			
+		if(isDataFilesChecked())
+		{
+			if(!m_filteredws_sptr)
+			{
+        updateLabel("Loading data files...");
+				m_filteredws_sptr=executeGetdataFiles();
+			}
+      
+			populateinvestigationWidget(m_filteredws_sptr,"DataFiles",true);
+		}
+		else
+		{
+			if(!m_datafilesws_sptr)
+			{
+        updateLabel("Loading files...");
+				m_datafilesws_sptr = executeGetdataFiles();
+			}
+			if(!m_datafilesws_sptr) return;
+			populateinvestigationWidget(m_datafilesws_sptr,"DataFiles",true);
+		}
+	}
+	else if(!item->text(0).compare("DataSets"))
+	{
+		if(!m_datasetsws_sptr){
+      updateLabel("Loading datasets...");
+			m_datasetsws_sptr= executeGetdataSets();
+
+		}
+		if(!m_datasetsws_sptr)return;
+		populateinvestigationWidget(m_datasetsws_sptr,"DataSets",false);
+	}
+	
+}
+/**This method populates the investigation table widget
+  *@param ws_sptr :: shared pointer to workspace
+  *@param  type - string used to identify datasets or data files
+  *@param bEnable :: flag to enable sorting
+*/
+void ICatInvestigation::populateinvestigationWidget(Mantid::API::ITableWorkspace_sptr dataws_sptr,const QString& type,bool bEnable)
+{	
+	if(!dataws_sptr){return;}
+
+	Mantid::API::ITableWorkspace_sptr ws_sptr(dataws_sptr);
+  if(!ws_sptr){return;}
+
+	//turn off sorting as per QT documentation
+	m_uiForm.invsttableWidget->setSortingEnabled(false);
+	
+	//below for loop for clearing the table widget on each mouse click,otherwise rows will be appended.
+	// table widget clear() method is clearing only the item text,not removing the rows,columns
+	// so i'm using removeRow().When I removed the row from top of the table it was not working.
+
+	for (int i=m_uiForm.invsttableWidget->rowCount()-1;i>=0;--i)
+	{
+		m_uiForm.invsttableWidget->removeRow(i);
+	}
+	m_uiForm.invsttableWidget->setRowCount(ws_sptr->rowCount());
+	m_uiForm.invsttableWidget->setColumnCount(ws_sptr->columnCount());
+	 
+	for (int i=0;i<ws_sptr->rowCount();++i)
+	{
+		//setting the row height of tableWidget 
+		m_uiForm.invsttableWidget->setRowHeight(i,20);
+	}
+
+	QStringList qlabelList;
 	for(int i=0;i<ws_sptr->columnCount();i++)
 	{
 		Column_sptr col_sptr = ws_sptr->getColumn(i);
 		//get the column name to display as the header of table widget
-		QString colTitle = QString::fromStdString(col_sptr->name());
+		QString colTitle = QString::fromStdString(col_sptr->name());
 		qlabelList.push_back(colTitle);
 
 		for(int j=0;j<ws_sptr->rowCount();++j)
 		{
 			std::ostringstream ostr;
 			col_sptr->print(ostr,j);
-
-			QTableWidgetItem *newItem  = new QTableWidgetItem(QString::fromStdString(ostr.str()));
-			newItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
-			m_uiForm.invsttableWidget->setItem(j,i, newItem);
+
+			QTableWidgetItem *newItem  = new QTableWidgetItem(QString::fromStdString(ostr.str()));
+			newItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
+			m_uiForm.invsttableWidget->setItem(j,i, newItem);
 			newItem->setToolTip(QString::fromStdString(ostr.str()));
 			
 		}
-	}
-	//setting table widget header labels from table workspace
-	m_uiForm.invsttableWidget->setHorizontalHeaderLabels(qlabelList);
-	QFont font;
-	font.setBold(true);
-	for (int i=0;i<m_uiForm.invsttableWidget->columnCount();++i)
-	{
-		m_uiForm.invsttableWidget->horizontalHeaderItem(i)->setFont(font);;
-	}
-	//resizing the coluns based on data size
-	m_uiForm.invsttableWidget->resizeColumnsToContents();
-		
-	QString labelText;
-	std::stringstream totalCount;
-	totalCount<<ws_sptr->rowCount();
-	labelText="Data: "+QString::fromStdString(totalCount.str())+" "+type+" found";
-  updateLabel(labelText);
-			
-	//if flag is set sort by first column
-	if(bEnable)
-	{   
-		m_uiForm.invsttableWidget->setSortingEnabled(true);
-		m_uiForm.invsttableWidget->sortByColumn(0,Qt::AscendingOrder);
-	}
- }
-/** Cancel button clicked
-*/
-void  ICatInvestigation::onCancel()
-{
-	this->close();
-	QObject* qobj=parent();
-	QWidget* parent=qobject_cast<QWidget*>(qobj);
-	if(parent)
-	{
-		parent->close();
-	}
-}
-/**update label on labled widget with the given text
-*/
-void ICatInvestigation::updateLabel(const QString& labelText)
-{
-  QFont font;
-	font.setBold(true);
- 	m_uiForm.invstlabel->clear();
-	m_uiForm.invstlabel->setText(labelText);
-	m_uiForm.invstlabel->setAlignment(Qt::AlignHCenter);
-	m_uiForm.invstlabel->setFont(font);
-}
-void ICatInvestigation::onSelectAllFiles()
-{
-	QItemSelectionModel* selectionModel = m_uiForm.invsttableWidget->selectionModel(); 
-	QAbstractItemModel *model = m_uiForm.invsttableWidget->model();
-	int rowCount = model->rowCount();
-	int colCount = model->columnCount();
-	
-	QModelIndex topLeft = model->index(0,0,QModelIndex()); 
-	QModelIndex bottomRight = model->index(rowCount-1,colCount-1,QModelIndex());
-	
-	QItemSelection selection(topLeft, bottomRight);
-	selectionModel->select(selection, QItemSelectionModel::Select);
-
-		
-}
-/// if data file checkbox selected
-bool ICatInvestigation::isDataFilesChecked()
-{
-	return m_uiForm.dataFilescheckBox->isChecked();
-}
-/** This method gets the selected file name from the selected row in the table
-  * @param fileNames :: table widget item selected.
-*/
-void ICatInvestigation::getSelectedFileNames(std::vector<std::string>& fileNames)
-{
-	
-	QItemSelectionModel *selmodel = m_uiForm.invsttableWidget->selectionModel();
-	QModelIndexList  indexes=selmodel->selectedRows();
-	QModelIndex index;
-	QAbstractItemModel *model = m_uiForm.invsttableWidget->model();
-	foreach(index, indexes) 
-	{			
-		QString text = model->data(index, Qt::DisplayRole).toString();
-		fileNames.push_back(text.toStdString());
-
-	}
-}
-
-/** This method returns the fileids of the given files.
-@param fileNames :: list of filenames
-@param fileIds :: reference to a vector of fileIds
-*/
-void ICatInvestigation::getFileIds(const std::vector<std::string> &fileNames, std::vector<long long >&fileIds)
-{
-	ITableWorkspace_sptr ws_sptr;
-
-	if(AnalysisDataService::Instance().doesExist("datafiles"))
-	{
-		ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
-			(AnalysisDataService::Instance().retrieve("datafiles"));
-	}
-	long long fileId=0;
-	const int col=0;
-	int row=0;
-	std::vector<std::string>::const_iterator citr;
-	for(citr=fileNames.begin();citr!=fileNames.end();++citr)
-	{
-		try
-		{
-		ws_sptr->find(*citr,row,col);
-		fileId=ws_sptr->cell<int64_t>(row,col+2);//3rd column is the file id.
-		}
-		catch(std::range_error&)
-		{
-			throw std::runtime_error("selected file "+*citr+" not exists in the ICat search results workspace");
-		}
-		catch(std::out_of_range&)
-		{
-			throw std::runtime_error("selected file "+*citr+" not exists in the ithe ICat search results workspace");;
-		}
-		catch(std::runtime_error&)
-		{
-			throw std::runtime_error("selected file "+*citr+" not exists in the the ICat search results workspace");;
-		}
-
-		fileIds.push_back(fileId);
-		++row;
-	}
-	
-}
-/** download button clicked
-*/
-void  ICatInvestigation::onDownload()
-{
-	//get selected file name to download
-    std::vector<std::string> fileNames;
-	std::vector<std::string> fileLocs;
-	//get selected file from the Mantid-ICat interface to download
-	getSelectedFileNames(fileNames);
-	if(fileNames.empty())
-	{
-		QString msg="No files are selected to download.Click on any file to select it" 
-			"\n or Use the 'Select All Files' button provided or mouse left button shift/Ctrl key to select the files.";
-		emit error(msg);
-		return;
-	}
-
-	std::vector<long long >fileIds;
-	//get the file ids for the given file names.
-	getFileIds(fileNames,fileIds);
-	
-	emit download(fileNames,fileIds);
-	
-}
-/** This slot sets the file locations returned by download algorithm to downloaded filelist
-*/
-void ICatInvestigation::setfileLocations(const std::vector<std::string>& fileLocs)
-{	
-	m_downloadedFileList.assign(fileLocs.begin(),fileLocs.end());
-	
-}
-
-/**This method gets called when Treewidget item defaults expanded
-  *@param item :: treewidget item 
-*/
-void ICatInvestigation::investigationWidgetItemExpanded(QTreeWidgetItem* item )
-{
-	if(item->text(0)=="Default")
-	{
-		if(!m_datasetsws_sptr){
-			m_datasetsws_sptr = executeGetdataSets();
-		}
-
-		QStringList qlist;
-		std::string status = m_datasetsws_sptr->getRef<std::string>("Status",0);
-		QString qval="Status: "+QString::fromStdString(status);
-		QTreeWidgetItem* child = item->child(0);
-		child->setText(0,qval);
-		child->setToolTip(0,qval);
-		
-		std::string type = m_datasetsws_sptr->getRef<std::string>("Type",0);
-		qlist.clear();
-		qval="Type: "+QString::fromStdString(type);
-		
-	    child = item->child(1);
-		child->setText(0,qval);
-		child->setToolTip(0,qval);
-
-		std::string description = m_datasetsws_sptr->getRef<std::string>("Description",0);
-		qval="Description: "+QString::fromStdString(description);
-		child=item->child(2);
-		child->setText(0,qval);
-		child->setToolTip(0,qval);
-	
-	}
-		
-}
-/// Load button clicked
-void ICatInvestigation::onLoad()
-{
-	///get selected filename (raw,nexus,log) from table widget 
-	std::vector<std::string> sfileNames;
-	getSelectedFileNames(sfileNames);
-	if(sfileNames.empty())
-	{
-		QString msg="Files must be downloaded before trying to load.";
-		emit error( msg);
-	}
-
-	// before loading check the file is downloaded
-	std::vector<std::string>::const_iterator citr;
-	for(citr=sfileNames.begin();citr!=sfileNames.end();++citr)
-	{		
-		std::string loadPath;
-		if(isFileExistsInDownloadedList(*citr,loadPath ))
-		{
-			//if the file is downloaded ,then load to mantid and create workspace
-			loadData(QString::fromStdString(loadPath));
-		}
-		else
-		{
-			emit error("The file "+ QString::fromStdString(*citr)+ " is not downloaded. Use the downlaod button provided to down load the file and then load." );
-		}
-		
-	}
-
-		
-}
-
-bool ICatInvestigation::isFileExistsInDownloadedList(const std::string& selectedFile,std::string& loadPath )
-{
-	std::basic_string <char>::size_type npos = -1;
-	std::basic_string <char>::size_type index;
-	std::string filenamePart;
-
-	std::vector<std::string>::const_iterator cditr;
-	for(cditr=m_downloadedFileList.begin();cditr!=m_downloadedFileList.end();++cditr)
-	{
-		// the selected file name from UI contains only file names,but the downloaded filelist returned
-		// by downlaod algorithm contains filename with full path
-		// below code extarcts the file name part and checks file exists in the downloaded list
-		index=(*cditr).find_last_of("/");
-		if(index!=npos)
-		{
-			filenamePart=(*cditr).substr(index+1,(*cditr).length()-index);
-			QString temp=QString::fromStdString(filenamePart);
-			QString temp1=QString::fromStdString(selectedFile);
-			if(!temp.compare(temp1,Qt::CaseInsensitive))
-			{	
-				loadPath=(*cditr);
-				return true;
-			}
-			
-		}
-		
-	}
-	return false;
-
-}
-/**This method loads the data file
-  *@param filePath :: name of the file
-*/
-void ICatInvestigation::loadData( const QString& filePath)
-{
-
-	QString wsName;
-	int index = filePath.lastIndexOf(".");
-	int index1 = filePath.lastIndexOf("/");
-	if(index!=-1 && index1!=-1)
-	{
-		wsName=filePath.mid(index1+1,index-index1-1);
-	}
-
-	if (isRawFile(filePath))
-	{		
-		if(!isLoadingControlled())
-		{
-			executeLoadRaw(filePath,wsName);
-		
-		}
-		else
-		{		
-			emit loadRawAsynch(filePath,wsName);
-		}
-	}
-	else if (isNexusFile(filePath))
-	{
-
-		if(!isLoadingControlled())
-		{
-			executeLoadNexus(filePath,wsName);
-		}
-		else
-		{			
-			emit loadNexusAsynch(filePath,wsName);
-			
-		}
-	}
-	else
-	{
-		emit error("ICat interface is not supporting the loading of log files.",1);
-		
-	}
-}
-/// If user selected controlled loading of data check box
-bool ICatInvestigation::isLoadingControlled()
-{
-	return m_uiForm.loadcheckBox->isChecked();
-}
-
-/**This method checks the file name extension and returns true if it's raw file 
-  *@param fileName :: name of the file
-  *@return  boolean
-*/
-bool ICatInvestigation::isRawFile(const QString& fileName)
-{
-	int index = fileName.lastIndexOf(".");
-	bool braw;
-	QString extn;
-	if(index!=-1)
-	{
-		extn=fileName.right(fileName.length()-index-1);
-	}
-	(!extn.compare("raw",Qt::CaseInsensitive))? braw=true : braw=false;
-	return braw;
-}
-
-/**This method checks the file name extension and returns true if it's nexus file 
-  *@param fileName :: name of the file
-  *@return  true if it's nexus file
-*/
-bool ICatInvestigation::isNexusFile(const QString& fileName)
-{
-	bool bnxs;
-	QString extn;
-	int index = fileName.lastIndexOf(".");
-	if(index!=-1)
-	{
-		extn=fileName.right(fileName.length()-index-1);
-	}
-	(!extn.compare("nxs",Qt::CaseInsensitive) )? bnxs=true : bnxs=false;
-	
-	return bnxs;
-	
-}
-
-/** This method executes loadRaw algorithm
-  * @param fileName :: name of the raw file
-  * @param wsName :: name of the workspace to store the data
-*/
-void ICatInvestigation::executeLoadRaw(const QString& fileName,const QString& wsName)
-{	
-	emit executeLoadAlgorithm("LoadRaw",fileName,wsName);
-}
-
-/** This method executes loadNexus algorithm
-  * @param fileName :: name of the nexus file
-  * @param wsName :: name of the workspace to store the data
-*/
-void ICatInvestigation::executeLoadNexus(const QString& fileName,const QString& wsName)
-{
-	emit executeLoadAlgorithm("LoadNexus",fileName,wsName);
-}
-/**This method executes loadraw/loadnexus algorithm
-  *@param algName :: algoritm name
-  *@param version :: -algorithm version
-  *@param fileName :: name of the file to load
-  *@param wsName :: name of the workspace to store the data
-*/
-bool ICatInvestigation::execute(const QString& algName,const int& version,const QString& fileName,const QString& wsName)
-{
-	Mantid::API::IAlgorithm_sptr alg;
+	}
+	//setting table widget header labels from table workspace
+	m_uiForm.invsttableWidget->setHorizontalHeaderLabels(qlabelList);
+	QFont font;
+	font.setBold(true);
+	for (int i=0;i<m_uiForm.invsttableWidget->columnCount();++i)
+	{
+		m_uiForm.invsttableWidget->horizontalHeaderItem(i)->setFont(font);;
+	}
+	//resizing the coluns based on data size
+	m_uiForm.invsttableWidget->resizeColumnsToContents();
+		
+	QString labelText;
+	std::stringstream totalCount;
+	totalCount<<ws_sptr->rowCount();
+	labelText="Data: "+QString::fromStdString(totalCount.str())+" "+type+" found";
+  updateLabel(labelText);
+			
+	//if flag is set sort by first column
+	if(bEnable)
+	{   
+		m_uiForm.invsttableWidget->setSortingEnabled(true);
+		m_uiForm.invsttableWidget->sortByColumn(0,Qt::AscendingOrder);
+	}
+ }
+/** Cancel button clicked
+*/
+void  ICatInvestigation::onCancel()
+{
+	this->close();
+	QObject* qobj=parent();
+	QWidget* parent=qobject_cast<QWidget*>(qobj);
+	if(parent)
+	{
+		parent->close();
+	}
+}
+/**update label on labled widget with the given text
+*/
+void ICatInvestigation::updateLabel(const QString& labelText)
+{
+  QFont font;
+	font.setBold(true);
+ 	m_uiForm.invstlabel->clear();
+	m_uiForm.invstlabel->setText(labelText);
+	m_uiForm.invstlabel->setAlignment(Qt::AlignHCenter);
+	m_uiForm.invstlabel->setFont(font);
+}
+void ICatInvestigation::onSelectAllFiles()
+{
+	QItemSelectionModel* selectionModel = m_uiForm.invsttableWidget->selectionModel(); 
+	QAbstractItemModel *model = m_uiForm.invsttableWidget->model();
+	int rowCount = model->rowCount();
+	int colCount = model->columnCount();
+	
+	QModelIndex topLeft = model->index(0,0,QModelIndex()); 
+	QModelIndex bottomRight = model->index(rowCount-1,colCount-1,QModelIndex());
+	
+	QItemSelection selection(topLeft, bottomRight);
+	selectionModel->select(selection, QItemSelectionModel::Select);
+
+		
+}
+/// if data file checkbox selected
+bool ICatInvestigation::isDataFilesChecked()
+{
+	return m_uiForm.dataFilescheckBox->isChecked();
+}
+/** This method gets the selected file name from the selected row in the table
+  * @param fileNames :: table widget item selected.
+*/
+void ICatInvestigation::getSelectedFileNames(std::vector<std::string>& fileNames)
+{
+	
+	QItemSelectionModel *selmodel = m_uiForm.invsttableWidget->selectionModel();
+	QModelIndexList  indexes=selmodel->selectedRows();
+	QModelIndex index;
+	QAbstractItemModel *model = m_uiForm.invsttableWidget->model();
+	foreach(index, indexes) 
+	{			
+		QString text = model->data(index, Qt::DisplayRole).toString();
+		fileNames.push_back(text.toStdString());
+
+	}
+}
+
+/** This method returns the fileids of the given files.
+@param fileNames :: list of filenames
+@param fileIds :: reference to a vector of fileIds
+*/
+void ICatInvestigation::getFileIds(const std::vector<std::string> &fileNames, std::vector<long long >&fileIds)
+{
+	ITableWorkspace_sptr ws_sptr;
+
+	if(AnalysisDataService::Instance().doesExist("datafiles"))
+	{
+		ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
+			(AnalysisDataService::Instance().retrieve("datafiles"));
+	}
+	long long fileId=0;
+	const int col=0;
+	int row=0;
+	std::vector<std::string>::const_iterator citr;
+	for(citr=fileNames.begin();citr!=fileNames.end();++citr)
+	{
+		try
+		{
+		ws_sptr->find(*citr,row,col);
+		fileId=ws_sptr->cell<int64_t>(row,col+2);//3rd column is the file id.
+		}
+		catch(std::range_error&)
+		{
+			throw std::runtime_error("selected file "+*citr+" not exists in the ICat search results workspace");
+		}
+		catch(std::out_of_range&)
+		{
+			throw std::runtime_error("selected file "+*citr+" not exists in the ithe ICat search results workspace");;
+		}
+		catch(std::runtime_error&)
+		{
+			throw std::runtime_error("selected file "+*citr+" not exists in the the ICat search results workspace");;
+		}
+
+		fileIds.push_back(fileId);
+		++row;
+	}
+	
+}
+/** download button clicked
+*/
+void  ICatInvestigation::onDownload()
+{
+	//get selected file name to download
+    std::vector<std::string> fileNames;
+	std::vector<std::string> fileLocs;
+	//get selected file from the Mantid-ICat interface to download
+	getSelectedFileNames(fileNames);
+	if(fileNames.empty())
+	{
+		QString msg="No files are selected to download.Click on any file to select it" 
+			"\n or Use the 'Select All Files' button provided or mouse left button shift/Ctrl key to select the files.";
+		emit error(msg);
+		return;
+	}
+
+	std::vector<long long >fileIds;
+	//get the file ids for the given file names.
+	getFileIds(fileNames,fileIds);
+	
+	emit download(fileNames,fileIds);
+	
+}
+/** This slot sets the file locations returned by download algorithm to downloaded filelist
+*/
+void ICatInvestigation::setfileLocations(const std::vector<std::string>& fileLocs)
+{	
+	m_downloadedFileList.assign(fileLocs.begin(),fileLocs.end());
+	
+}
+
+/**This method gets called when Treewidget item defaults expanded
+  *@param item :: treewidget item 
+*/
+void ICatInvestigation::investigationWidgetItemExpanded(QTreeWidgetItem* item )
+{
+	if(item->text(0)=="Default")
+	{
+		if(!m_datasetsws_sptr){
+			m_datasetsws_sptr = executeGetdataSets();
+		}
+
+		QStringList qlist;
+		std::string status = m_datasetsws_sptr->getRef<std::string>("Status",0);
+		QString qval="Status: "+QString::fromStdString(status);
+		QTreeWidgetItem* child = item->child(0);
+		child->setText(0,qval);
+		child->setToolTip(0,qval);
+		
+		std::string type = m_datasetsws_sptr->getRef<std::string>("Type",0);
+		qlist.clear();
+		qval="Type: "+QString::fromStdString(type);
+		
+	    child = item->child(1);
+		child->setText(0,qval);
+		child->setToolTip(0,qval);
+
+		std::string description = m_datasetsws_sptr->getRef<std::string>("Description",0);
+		qval="Description: "+QString::fromStdString(description);
+		child=item->child(2);
+		child->setText(0,qval);
+		child->setToolTip(0,qval);
+	
+	}
+		
+}
+/// Load button clicked
+void ICatInvestigation::onLoad()
+{
+	///get selected filename (raw,nexus,log) from table widget 
+	std::vector<std::string> sfileNames;
+	getSelectedFileNames(sfileNames);
+	if(sfileNames.empty())
+	{
+		QString msg="Files must be downloaded before trying to load.";
+		emit error( msg);
+	}
+
+	// before loading check the file is downloaded
+	std::vector<std::string>::const_iterator citr;
+	for(citr=sfileNames.begin();citr!=sfileNames.end();++citr)
+	{		
+		std::string loadPath;
+		if(isFileExistsInDownloadedList(*citr,loadPath ))
+		{
+			//if the file is downloaded ,then load to mantid and create workspace
+			loadData(QString::fromStdString(loadPath));
+		}
+		else
+		{
+			emit error("The file "+ QString::fromStdString(*citr)+ " is not downloaded. Use the downlaod button provided to down load the file and then load." );
+		}
+		
+	}
+
+		
+}
+
+bool ICatInvestigation::isFileExistsInDownloadedList(const std::string& selectedFile,std::string& loadPath )
+{
+	std::basic_string <char>::size_type npos = -1;
+	std::basic_string <char>::size_type index;
+	std::string filenamePart;
+
+	std::vector<std::string>::const_iterator cditr;
+	for(cditr=m_downloadedFileList.begin();cditr!=m_downloadedFileList.end();++cditr)
+	{
+		// the selected file name from UI contains only file names,but the downloaded filelist returned
+		// by downlaod algorithm contains filename with full path
+		// below code extarcts the file name part and checks file exists in the downloaded list
+		index=(*cditr).find_last_of("/");
+		if(index!=npos)
+		{
+			filenamePart=(*cditr).substr(index+1,(*cditr).length()-index);
+			QString temp=QString::fromStdString(filenamePart);
+			QString temp1=QString::fromStdString(selectedFile);
+			if(!temp.compare(temp1,Qt::CaseInsensitive))
+			{	
+				loadPath=(*cditr);
+				return true;
+			}
+			
+		}
+		
+	}
+	return false;
+
+}
+/**This method loads the data file
+  *@param filePath :: name of the file
+*/
+void ICatInvestigation::loadData( const QString& filePath)
+{
+
+	QString wsName;
+	int index = filePath.lastIndexOf(".");
+	int index1 = filePath.lastIndexOf("/");
+	if(index!=-1 && index1!=-1)
+	{
+		wsName=filePath.mid(index1+1,index-index1-1);
+	}
+
+	if (isRawFile(filePath))
+	{		
+		if(!isLoadingControlled())
+		{
+			executeLoadRaw(filePath,wsName);
+		
+		}
+		else
+		{		
+			emit loadRawAsynch(filePath,wsName);
+		}
+	}
+	else if (isNexusFile(filePath))
+	{
+
+		if(!isLoadingControlled())
+		{
+			executeLoadNexus(filePath,wsName);
+		}
+		else
+		{			
+			emit loadNexusAsynch(filePath,wsName);
+			
+		}
+	}
+	else
+	{
+		emit error("ICat interface is not supporting the loading of log files.",1);
+		
+	}
+}
+/// If user selected controlled loading of data check box
+bool ICatInvestigation::isLoadingControlled()
+{
+	return m_uiForm.loadcheckBox->isChecked();
+}
+
+/**This method checks the file name extension and returns true if it's raw file 
+  *@param fileName :: name of the file
+  *@return  boolean
+*/
+bool ICatInvestigation::isRawFile(const QString& fileName)
+{
+	int index = fileName.lastIndexOf(".");
+	bool braw;
+	QString extn;
+	if(index!=-1)
+	{
+		extn=fileName.right(fileName.length()-index-1);
+	}
+	(!extn.compare("raw",Qt::CaseInsensitive))? braw=true : braw=false;
+	return braw;
+}
+
+/**This method checks the file name extension and returns true if it's nexus file 
+  *@param fileName :: name of the file
+  *@return  true if it's nexus file
+*/
+bool ICatInvestigation::isNexusFile(const QString& fileName)
+{
+	bool bnxs;
+	QString extn;
+	int index = fileName.lastIndexOf(".");
+	if(index!=-1)
+	{
+		extn=fileName.right(fileName.length()-index-1);
+	}
+	(!extn.compare("nxs",Qt::CaseInsensitive) )? bnxs=true : bnxs=false;
+	
+	return bnxs;
+	
+}
+
+/** This method executes loadRaw algorithm
+  * @param fileName :: name of the raw file
+  * @param wsName :: name of the workspace to store the data
+*/
+void ICatInvestigation::executeLoadRaw(const QString& fileName,const QString& wsName)
+{	
+	emit executeLoadAlgorithm("LoadRaw",fileName,wsName);
+}
+
+/** This method executes loadNexus algorithm
+  * @param fileName :: name of the nexus file
+  * @param wsName :: name of the workspace to store the data
+*/
+void ICatInvestigation::executeLoadNexus(const QString& fileName,const QString& wsName)
+{
+	emit executeLoadAlgorithm("LoadNexus",fileName,wsName);
+}
+/**This method executes loadraw/loadnexus algorithm
+  *@param algName :: algoritm name
+  *@param version :: -algorithm version
+  *@param fileName :: name of the file to load
+  *@param wsName :: name of the workspace to store the data
+*/
+bool ICatInvestigation::execute(const QString& algName,const int& version,const QString& fileName,const QString& wsName)
+{
+	Mantid::API::IAlgorithm_sptr alg;
+	try
+	{
+		alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
+	}
+	catch(...)
+	{
+		throw std::runtime_error("Error when loading the file"+ fileName.toStdString()); 
+	}
+	try
+	{
+		alg->setProperty("Filename",fileName.toStdString());
+		alg->setPropertyValue("OutputWorkspace",wsName.toStdString());
+	}
+	catch(std::invalid_argument& e)
+	{		
+		emit error(e.what());
+		return false;
+	}
+	catch (Mantid::Kernel::Exception::NotFoundError& e)
+	{
+		emit error(e.what());
+		return false;
+	}
+		
 	try
 	{
-		alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
-	}
-	catch(...)
-	{
-		throw std::runtime_error("Error when loading the file"+ fileName.toStdString()); 
-	}
-	try
-	{
-		alg->setProperty("Filename",fileName.toStdString());
-		alg->setPropertyValue("OutputWorkspace",wsName.toStdString());
-	}
-	catch(std::invalid_argument& e)
-	{		
-		emit error(e.what());
-		return false;
-	}
-	catch (Mantid::Kernel::Exception::NotFoundError& e)
-	{
-		emit error(e.what());
-		return false;
-	}
-		
-	try
-	{
 		Poco::ActiveResult<bool> result(alg->executeAsync());
 		while( !result.available() )
 		{
 			QCoreApplication::processEvents();
 		}
 		return (!result.failed());
-	}
+	}
 	catch(...)
     {   
 	  return false;
-    }
-	
-
-}
-
-//handler for helpbutton
-void ICatInvestigation::helpButtonClicked()
-{
-	QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Investigation"));
-
-}
+    }
+	
+
+}
+
+//handler for helpbutton
+void ICatInvestigation::helpButtonClicked()
+{
+	QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Investigation"));
+
+}
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/ICatMyDataSearch.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/ICatMyDataSearch.cpp
index 45e08813d8dedcab9442243326cd4fb87e117584..54e702efd02b2d6ef321b1c24541d0c61076001f 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/ICatMyDataSearch.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/ICatMyDataSearch.cpp
@@ -1,80 +1,80 @@
-#include "MantidQtMantidWidgets/ICatMyDataSearch.h"
-#include "MantidAPI/AlgorithmManager.h"
-#include "MantidAPI/AnalysisDataService.h"
-
-
-#include<QStringList>
-#include<QTreeWidget>
-#include<QTreeWidgetItem>
-#include<QFont>
-
-using namespace Mantid::API;
-using namespace MantidQt::MantidWidgets;
-
-ICatMyDataSearch::ICatMyDataSearch(QWidget*par):QWidget(par),m_utils_sptr(new ICatUtils)
-{
-	m_uiForm.setupUi(this);
-
-	connect(this,SIGNAL(error(const QString&)),parent()->parent(),SLOT(writeErrorToLogWindow(const QString&)));
-	connect(m_uiForm.myDatatableWidget,SIGNAL(itemDoubleClicked(QTableWidgetItem* )),
-		this,SLOT(investigationSelected(QTableWidgetItem* )));
-
-	QObject* qobj=parent();
-	QWidget* parent=qobject_cast<QWidget*>(qobj->parent());
-	if(parent)
-	{
-		setparentWidget(parent);
-	}
-	if(!m_utils_sptr)
-  {
-      return ;
-  }
-		m_utils_sptr->setParent(parent);
-	Mantid::API::ITableWorkspace_sptr  ws_sptr ;
-	if(executeMyDataSearch(ws_sptr))
-	{		
-		m_utils_sptr->updatesearchResults(ws_sptr,m_uiForm.myDatatableWidget);
-    m_utils_sptr->updateSearchLabel(ws_sptr,m_uiForm.mydatalabel);
-	
-	}
-	
-	
-}
-
-/* this method sets the parent widget as application window
-*/
-void ICatMyDataSearch::setparentWidget(QWidget* par)
-{
-	m_applicationWindow= par;
-}
-bool ICatMyDataSearch::executeMyDataSearch(ITableWorkspace_sptr& ws_sptr)
-{
-	Mantid::API::IAlgorithm_sptr alg;
+#include "MantidQtMantidWidgets/ICatMyDataSearch.h"
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidAPI/AnalysisDataService.h"
+
+
+#include<QStringList>
+#include<QTreeWidget>
+#include<QTreeWidgetItem>
+#include<QFont>
+
+using namespace Mantid::API;
+using namespace MantidQt::MantidWidgets;
+
+ICatMyDataSearch::ICatMyDataSearch(QWidget*par):QWidget(par),m_utils_sptr(new ICatUtils)
+{
+	m_uiForm.setupUi(this);
+
+	connect(this,SIGNAL(error(const QString&)),parent()->parent(),SLOT(writeErrorToLogWindow(const QString&)));
+	connect(m_uiForm.myDatatableWidget,SIGNAL(itemDoubleClicked(QTableWidgetItem* )),
+		this,SLOT(investigationSelected(QTableWidgetItem* )));
+
+	QObject* qobj=parent();
+	QWidget* parent=qobject_cast<QWidget*>(qobj->parent());
+	if(parent)
+	{
+		setparentWidget(parent);
+	}
+	if(!m_utils_sptr)
+  {
+      return ;
+  }
+		m_utils_sptr->setParent(parent);
+	Mantid::API::ITableWorkspace_sptr  ws_sptr ;
+	if(executeMyDataSearch(ws_sptr))
+	{		
+		m_utils_sptr->updatesearchResults(ws_sptr,m_uiForm.myDatatableWidget);
+    m_utils_sptr->updateSearchLabel(ws_sptr,m_uiForm.mydatalabel);
+	
+	}
+	
+	
+}
+
+/* this method sets the parent widget as application window
+*/
+void ICatMyDataSearch::setparentWidget(QWidget* par)
+{
+	m_applicationWindow= par;
+}
+bool ICatMyDataSearch::executeMyDataSearch(ITableWorkspace_sptr& ws_sptr)
+{
+	Mantid::API::IAlgorithm_sptr alg;
+	try
+	{
+		alg = Mantid::API::AlgorithmManager::Instance().create("CatalogMyDataSearch",1);
+	}
+	catch(...)
+	{
+		throw std::runtime_error("Error when loading Mydata search results."); 
+	}
 	try
 	{
-		alg = Mantid::API::AlgorithmManager::Instance().create("CatalogMyDataSearch",1);
-	}
-	catch(...)
-	{
-		throw std::runtime_error("Error when loading Mydata search results."); 
-	}
-	try
-	{
-		alg->setPropertyValue("OutputWorkspace","MyInvestigations");
-		
-	}
-	catch(std::invalid_argument& e)
-	{		
-		emit error(e.what());
-		return false;
-	}
-	catch (Mantid::Kernel::Exception::NotFoundError& e)
-	{
-		emit error(e.what());
-		return false;
-	}
-	
-	
+		alg->setPropertyValue("OutputWorkspace","MyInvestigations");
+		
+	}
+	catch(std::invalid_argument& e)
+	{		
+		emit error(e.what());
+		return false;
+	}
+	catch (Mantid::Kernel::Exception::NotFoundError& e)
+	{
+		emit error(e.what());
+		return false;
+	}
+	
+	
 	Poco::ActiveResult<bool> result(alg->executeAsync());
 	while( !result.available() )
 	{
@@ -86,38 +86,38 @@ bool ICatMyDataSearch::executeMyDataSearch(ITableWorkspace_sptr& ws_sptr)
     {
       return false;
     }
-    //if the algorithm failed check the session id passed is valid
-		if(!m_utils_sptr->isSessionValid(alg))
-		{			
-			//at this point session is invalid, popup loginbox to login
-			if(m_utils_sptr->login())
-			{
-     
-			 return(executeMyDataSearch(ws_sptr)?true:false );
-      
-			}
-      else
-      {
-        return false;
-      }
-    
+    //if the algorithm failed check the session id passed is valid
+		if(!m_utils_sptr->isSessionValid(alg))
+		{			
+			//at this point session is invalid, popup loginbox to login
+			if(m_utils_sptr->login())
+			{
+     
+			 return(executeMyDataSearch(ws_sptr)?true:false );
+      
+			}
+      else
+      {
+        return false;
+      }
+    
 		}
-	}
-	
-	if(AnalysisDataService::Instance().doesExist("MyInvestigations"))
-	{
-		ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
-			(AnalysisDataService::Instance().retrieve("MyInvestigations"));
-
-	}
-	
-	return true;
-
-}
-void ICatMyDataSearch::investigationSelected(QTableWidgetItem* item)
-{
-	ICatUtils utils;
-	utils.investigationSelected(m_uiForm.myDatatableWidget,item,m_applicationWindow,m_ws2_sptr);
-
-}
-
+	}
+	
+	if(AnalysisDataService::Instance().doesExist("MyInvestigations"))
+	{
+		ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
+			(AnalysisDataService::Instance().retrieve("MyInvestigations"));
+
+	}
+	
+	return true;
+
+}
+void ICatMyDataSearch::investigationSelected(QTableWidgetItem* item)
+{
+	ICatUtils utils;
+	utils.investigationSelected(m_uiForm.myDatatableWidget,item,m_applicationWindow,m_ws2_sptr);
+
+}
+
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/ICatSearch.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/ICatSearch.cpp
index 889b0d943b595e8b87ffc13e3e02e4a597946d95..259a5e0f2a5a440983833d308368f5cdeaa40471 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/ICatSearch.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/ICatSearch.cpp
@@ -1,541 +1,541 @@
-
-//----------------------
-// Includes
-//----------------------
-#include "MantidQtMantidWidgets/ICatSearch.h"
-#include "MantidAPI/AlgorithmManager.h"
-#include "MantidAPI/AnalysisDataService.h"
-#include "MantidAPI/Column.h"
-#include "MantidAPI/TableRow.h" 
-#include "MantidQtAPI/InterfaceManager.h"
-
-#include<QStringList>
-#include<QFont>
-#include <QTableWidgetItem>
-#include <QSettings>
-#include <QMdiSubWindow>
-#include <QDesktopServices>
-#include <QUrl>
-#include <QLayoutItem>
-
-using namespace Mantid::Kernel;
-using namespace Mantid::API;
-
-using namespace MantidQt::MantidWidgets;
-
-//----------------------
-// Public member functions
-//----------------------
-///Constructor
-ICatSearch::ICatSearch(QWidget *par) :
-QWidget(par),m_sender(NULL),m_invstWidget(NULL),
-	m_utils_sptr(new ICatUtils),m_applicationWindow(NULL)
-{
-	
-	// getting the application window pointer and setting it as the parent 
-	QObject* qobj = parent();
-	QWidget* parent = qobject_cast<QWidget*>(qobj->parent());
-	if(parent)
-	{
-		setparentWidget(parent);
-	}
-	m_utils_sptr->setParent(parent);
-	initLayout();
-    m_alg=createAlgorithm();
-	addtoPropertyLabelsHash();
-	
-}
-ICatSearch::~ICatSearch()
-{
-}
-QWidget* ICatSearch::getParentWidget()
-{
-	return m_applicationWindow;
-}
-/* this method sets the parent widget as application window
-*/
-void ICatSearch::setparentWidget(QWidget* par)
-{
-	m_applicationWindow= par;
-}
-/// Set up the dialog layout
-void ICatSearch::initLayout()
-{
- 	m_uiForm.setupUi(this);
-	// when light blue back ground is set in ICat search dailog ,
-	//the instrument combo box popup down and up arrow disappears
-	// I'm setting this style sheet to bring the combobox's popup listview's arrows back.
-	QString str="QComboBox#Instrument QListView{background-color: white;background-image:"
-		"url(ICatCombobackground.png);background-attachment: scroll;}"
-		"QComboBox#Instrument QListView QScrollBar:vertical{background-image:"
-		"url(:/images/ICatComboVScrollbar.png); "
-		"background-repeat: repeat-y; width: 17px; height:20px;} ";
-	m_uiForm.Instrument->setStyleSheet(str);
-	
-  connect(this,SIGNAL(error(const QString&)),parent()->parent(),SLOT(writeErrorToLogWindow(const QString&)));
-	try
-	{
-	populateInstrumentBox();
-	}
-	catch(Mantid::Kernel::Exception::NotFoundError&)
-	{
-		emit error("Error when Populating instruments box");
-
-	}
-	catch(std::runtime_error & e)
-	{
-		emit error(e.what());
-	}
-	
-	//validator for start and end run numbers
-	QValidator * runval= new QIntValidator(0,100000000,m_uiForm.StartRun);
-	m_uiForm.StartRun->setValidator(runval);
-	m_uiForm.EndRun->setValidator(runval);
-			
-	//getting last saved input data from registry
-	readSettings();
-
-	connect(m_uiForm.searchButton,SIGNAL(clicked()),this,SLOT(onSearch()));
-	connect(m_uiForm.closeButton,SIGNAL(clicked()),this,SLOT(onClose()));
-	connect(m_uiForm.searchtableWidget,SIGNAL(itemDoubleClicked(QTableWidgetItem* )),
-		this,SLOT(investigationSelected(QTableWidgetItem* )));
-	
-	connect(m_uiForm.startdatetoolButton,SIGNAL(clicked()),this,SLOT(popupCalendar()));
-	connect(m_uiForm.enddatetoolButton,SIGNAL(clicked()),this,SLOT(popupCalendar()));
-	connect(m_uiForm.helpButton,SIGNAL(clicked()),this,SLOT(helpButtonClicked()));
-
-	//this is for hiding the calendar widget if it's visible
-	m_uiForm.StartRun->installEventFilter(this);
-	m_uiForm.EndRun->installEventFilter(this);
-	m_uiForm.Keywords->installEventFilter(this);
-	m_uiForm.searchframeWidget->installEventFilter(this);
-		
-}
-/// This method gets called  when the widget is closed
-void ICatSearch::closeEvent(QCloseEvent*)
-{
-	saveSettings();
-}
-
-/// This method is the handler for search button
-void ICatSearch::onSearch()
-{	 
-	//clear the workspace pointer
-	m_ws_sptr.reset();
-   // execute the search by run number algorithm
-	executeSearch(m_ws_sptr);
-}
-
-/** Is case sensitive search
-*/
-bool ICatSearch::isCaseSensitiveSearch()
-{
-	return m_uiForm.CaseSensitive->isChecked();
-}
-
-
-
-/* This method updates the search result to search tree
- * @param ws_sptr :: workspace shared pointer
-*/ 
-void ICatSearch::updatesearchResults(ITableWorkspace_sptr& ws_sptr )
-{	
-	if(!m_utils_sptr)
-  {
-		return;
-  }
-	m_utils_sptr->resetSearchResultsWidget(m_uiForm.searchtableWidget);
-	m_utils_sptr->updatesearchResults(ws_sptr,m_uiForm.searchtableWidget);
-	m_utils_sptr->updateSearchLabel(ws_sptr,m_uiForm.searchlabel);
-
-}
-
-/** This method populates the instrument box
-*/
-void ICatSearch::populateInstrumentBox(){
-  				
-		if(!m_utils_sptr)
-    {
-			return;
-    }
-		m_utils_sptr->populateInstrumentBox(m_uiForm.Instrument);
-	
-}
-
-/**This method gets run numbers from the start and end run boxes.
-  *@param startRun :: start run number
-  *@param endRun :: end run number
-*/
-void ICatSearch::getRunValues(double& startRun,double& endRun)
-{
-	endRun = m_uiForm.EndRun->text().toDouble();
-	startRun = m_uiForm.StartRun->text().toDouble();
-}
-
-/**This method gets start and end dates from the start and end date boxes.
-  *@param startDate :: start date  
-  *@param endDate :: end date
-*/
-void ICatSearch::getDates(QString& startDate,QString& endDate)
-{
-	startDate = m_uiForm.StartDate->text();
-	endDate =m_uiForm.EndDate->text();
-
-	if(!startDate.compare("//",Qt::CaseInsensitive))
-	{
-		startDate="";
-	}
-
-	if(!endDate.compare("//",Qt::CaseInsensitive))
-	{
-		endDate="";
-	}
-
-}
-///popup DateTime calender to select date
-void ICatSearch:: popupCalendar()
-{
-	if(!m_utils_sptr)
-		return;
-
-	m_utils_sptr->popupCalendar(this);
-	
-	QObject * qsender= sender();
-	if(!qsender) return;
-	 m_sender=qsender;
-	
-}
-///date changed
-void ICatSearch::getDate(const QDate& date  )
-{
-	//calendarWidget()->close();
-	m_utils_sptr->closeCalendarWidget();//close the calendar widget
-	if(!m_sender) return;
-
-	if(!m_sender->objectName().compare("startdatetoolButton"))
-	{
-	m_uiForm.StartDate->setText(date.toString("dd/MM/yyyy"));
-	}
-	if(!m_sender->objectName().compare("enddatetoolButton"))
-	{
-	m_uiForm.EndDate->setText(date.toString("dd/MM/yyyy"));
-	}
-}
-
-/**This method gets the selected instrument
-  *@param instrName :: name of the selected instrument
-*/
-void ICatSearch::getSelectedInstrument(QString& instrName)
-{
-	instrName=m_uiForm.Instrument->currentText();
-}
-
-Mantid::API::IAlgorithm_sptr ICatSearch::createAlgorithm()
-{
-	QString algName("CatalogSearch");
-	Mantid::API::IAlgorithm_sptr alg;
-	const int version=-1;
-	try
-	{
-	alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
-	}
-	catch(...)
-	{
-		throw std::runtime_error("Error when creating search algorithm"); 
-	}
-	return alg;
-
-}
-/**This method executes the search by run number algorithm
- *@param ws_sptr :: shared pointer to outputworkspace
-*/
-bool  ICatSearch::executeSearch(ITableWorkspace_sptr& ws_sptr)
-{
-	//before starting new search investigations clear the old one.
-	m_utils_sptr->clearSearch(m_uiForm.searchtableWidget,"investigations");
-	
-	//update the label status
-	m_utils_sptr->setLabelText(m_uiForm.searchlabel,"Searching investigations...");
-	
-	//now get the input values for search
-	QString startDate,endDate;
-	getDates(startDate,endDate);
-
-	double startRun=0,endRun=0;
-	//get start and end run values 
-	getRunValues(startRun,endRun);
-	
-	// get the selected instrument
-	QString instr ;
-	getSelectedInstrument(instr);
-	
-	bool bCase(isCaseSensitiveSearch());
-	
-	QString keywords= m_uiForm.Keywords->text();
-
-		
-	if(!setProperty("StartRun",startRun))
-	{
-		updatesearchResults(ws_sptr);
-		return false;
-	}
-	
-	if(!setProperty("EndRun",endRun)){
-		
-		updatesearchResults(ws_sptr);
-		return false;
-	}
-	if(!setProperty("Instrument",instr.toStdString())){
-		updatesearchResults(ws_sptr);
-		return false;
-	}
-	if(!setProperty("StartDate",startDate.toStdString())){
-		updatesearchResults(ws_sptr);
-		return false;
-	}
-	if(!setProperty("EndDate",endDate.toStdString())){
-		updatesearchResults(ws_sptr);
-		return false;
-	}
-	if(!setProperty("Case Sensitive",bCase)){
-		updatesearchResults(ws_sptr);
-		return false;
-	}
-	if(!setProperty("Keywords",keywords.toStdString())){
-		updatesearchResults(ws_sptr);
-		return false;
-	}
-	if(!setProperty("OutputWorkspace","investigations")){
-		updatesearchResults(ws_sptr);
-		return false;
-	}
-	
-	// execute the algorithm asynchrnously	
-	Poco::ActiveResult<bool> result(m_alg->executeAsync());
-	while(!result.available() )
-	{
-		QCoreApplication::processEvents();
-		
-	}
-	if(result.available())
-	{
-		if(result.failed())
-		{
-			ws_sptr.reset();
-			updatesearchResults(ws_sptr);
-			emit error(QString::fromStdString(result.exception()->message()));
-			return false;
-		}
-		if(AnalysisDataService::Instance().doesExist("investigations"))
-		{
-			ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
-				(AnalysisDataService::Instance().retrieve("investigations"));
-			updatesearchResults(ws_sptr);
-		}
-			
-		
-	}
-	return true;
-
-}
-
-struct Contains
-{ 
-Contains(std::string name):m_name(name){}
-bool operator()(Mantid::Kernel::Property* prop)
-{
-std::string name=prop->name();
-std::string::iterator pos = std::remove_if(name.begin(),name.end(), isspace);
-name.erase(pos,name.end());//removing the sapce
-
-return (!name.compare(m_name));
-}
-std::string m_name;
-
-};
-
-/** This method adds prpoerty name and validator label for the property to a hash table
-  * This method iterates through each widget in the search grid layout and gets the label widget
-  * and if it's validator label adds this to a hash table.
-  * validator label objectname  for each property is "propertyname_2" eg;"StartDate_2"
-  * from the label object name remove the "_2" to get propertyname
-  * some property has space between words.remove the space(as space not allowed in QT object names)
-  * and compare with propertyname to know the label is a validator label
-*/
-void ICatSearch::addtoPropertyLabelsHash()
-{		
-	//get total row and column count in the gridlayout where search controls are placed
-	int totalcol= m_uiForm.gridLayout->columnCount();
-	int totalrow =m_uiForm.gridLayout->rowCount();
-	//loop through each widget in the gridlayout
-	for (int row=0;row<totalrow;++row)
-	{
-		for (int col=0;col<totalcol;++col)
-		{
-			QLayoutItem  *item= m_uiForm.gridLayout->itemAtPosition(row,col); 
-			if(!item) continue;
-			QWidget* widget=item->widget();
-			if(!widget) continue;
-			QLabel* label=qobject_cast<QLabel*>(widget);
-			if(!label)
-			{
-				continue;
-			}
-			
-			//for each property,the validator label is named as "propertyname_2",
-			//now remove "_2" from label name to get property name
-			int index=label->objectName().indexOf("_");
-			if(index==-1)
-			{
-				continue;
-			}
-				QString name;
-				name=label->objectName().left(index);
-				std::string propName=name.toStdString();
-				
-				std::vector<Mantid::Kernel::Property*> props=m_alg->getProperties();
-				//if this name exists in algorithm properties vector it's a property validator label
-				std::vector<Mantid::Kernel::Property*>::iterator prop;
-				prop=std::find_if(props.begin(),props.end(),Contains(propName));
-				if(prop!=props.end())
-				{				
-					//at this point the label is a validator label
-					//add the lable to a hash 
-					m_propLabelHash[QString::fromStdString((*prop)->name())]=label;
-					label->hide();//initially hide the label 
-
-				}
-		
-			
-		}
-	}
-	
-}
-/// This method shows the invalid marker label for a property
-void ICatSearch::showInvalidMarkerLabel(const QString& name)
-{
-	if(m_propLabelHash.contains(name))
-	{	
-		std::string documentation;
-		std::vector<Mantid::Kernel::Property*> props=m_alg->getProperties();
-		//if this name exists in algorithm properties vector it's a proprty validator label
-		std::vector<Mantid::Kernel::Property*>::iterator result;
-		result=std::find_if(props.begin(),props.end(),Contains(name.toStdString()));
-		if(result!=props.end())
-		{
-			documentation=(*result)->documentation();
-
-		}
-		m_propLabelHash.value(name)->setToolTip(QString::fromStdString(documentation));
-		m_propLabelHash.value(name)->show();
-	}
-}
-/// hide invalid marker labels
-void ICatSearch::hideInvalidMarkerLabel(const QString& name)
-{
-	if(m_propLabelHash.contains(name))
-	{
-		if(m_propLabelHash.value(name)->isVisible())
-		{
-			m_propLabelHash.value(name)->hide();
-		}
-	}
-}
-/** This method closes the search widget.
-*/
-void ICatSearch::onClose()
-{
-	this->close();
-	QObject* qobj=parent();
-	QWidget* parent=qobject_cast<QWidget*>(qobj);
-	if(parent)
-	{
-		parent->close();
-	}
-}
-
-/** This method is called when an investigation is selected  from investigations list
-  *@param item ::  item in the table
-*/
-void ICatSearch::investigationSelected(QTableWidgetItem * item )
-{
-	//ICatUtils utils;
-	if(!m_utils_sptr)
-		return;
-	m_utils_sptr->investigationSelected(m_uiForm.searchtableWidget,item,m_applicationWindow,m_ws_sptr);
-}
-
-/** This method saves search settings
-*/
-void ICatSearch::saveSettings()
-{
-	QSettings searchsettings;
-	searchsettings.beginGroup("ICatSettings/Search");
-	searchsettings.setValue("StartRun",m_uiForm.StartRun->text());
-    searchsettings.setValue("EndRun",m_uiForm.EndRun->text());
-	searchsettings.setValue("Instrument",m_uiForm.Instrument->currentText());
-	searchsettings.setValue("Start Date",m_uiForm.StartDate->text());
-	searchsettings.setValue("End Date",m_uiForm.EndDate->text());
-	searchsettings.setValue("Keywords",m_uiForm.Keywords->text());
-	searchsettings.setValue("Case Sensitive",m_uiForm.CaseSensitive->isChecked());
-	
-	searchsettings.endGroup();
-
-}
-/// read settings from registry
-void ICatSearch::readSettings()
-{
-	QSettings searchsettings;
-	searchsettings.beginGroup("ICatSettings/Search");
-	m_uiForm.StartRun->setText(searchsettings.value("startRun").toString());
-	m_uiForm.EndRun->setText(searchsettings.value("endRun").toString());
-	//m_uiForm.Instrument->setItemText (0,searchsettings.value("instrument").toString());
-	int index=m_uiForm.Instrument->findText(searchsettings.value("instrument").toString());
-	if(index!=-1)
-	{
-		m_uiForm.Instrument->setCurrentIndex(index);
-	}
-	m_uiForm.StartDate->setText(searchsettings.value("Start Date").toString());
-	m_uiForm.EndDate->setText(searchsettings.value("End Date").toString());
-	m_uiForm.CaseSensitive->setChecked(searchsettings.value("Case Sensitive").toBool());
-
-	searchsettings.endGroup();
-}
-
-//handler for helpbutton
-void ICatSearch::helpButtonClicked()
-{
-	QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/ISIS_Search"));
-
-}
-
-bool ICatSearch::eventFilter(QObject *obj, QEvent *event)
-{
-	if (event->type() ==QEvent::FocusIn && obj==m_uiForm.searchframeWidget)
-	{		
-		if(m_utils_sptr->calendarWidget())
-		{
-			m_utils_sptr->calendarWidget()->hide();
-		}
-	
-	}
-	else if (event->type()==QEvent::MouseButtonPress)
-	{
-		if(m_utils_sptr->calendarWidget())
-		{
-			m_utils_sptr->calendarWidget()->hide();
-		}
-
-	}
-	else
-	{
-		// standard event processing
-		return QWidget::eventFilter(obj, event);
-	}
-	return true;
-}
-
-
-
-
-
+
+//----------------------
+// Includes
+//----------------------
+#include "MantidQtMantidWidgets/ICatSearch.h"
+#include "MantidAPI/AlgorithmManager.h"
+#include "MantidAPI/AnalysisDataService.h"
+#include "MantidAPI/Column.h"
+#include "MantidAPI/TableRow.h" 
+#include "MantidQtAPI/InterfaceManager.h"
+
+#include<QStringList>
+#include<QFont>
+#include <QTableWidgetItem>
+#include <QSettings>
+#include <QMdiSubWindow>
+#include <QDesktopServices>
+#include <QUrl>
+#include <QLayoutItem>
+
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
+
+using namespace MantidQt::MantidWidgets;
+
+//----------------------
+// Public member functions
+//----------------------
+///Constructor
+ICatSearch::ICatSearch(QWidget *par) :
+QWidget(par),m_sender(NULL),m_invstWidget(NULL),
+	m_utils_sptr(new ICatUtils),m_applicationWindow(NULL)
+{
+	
+	// getting the application window pointer and setting it as the parent 
+	QObject* qobj = parent();
+	QWidget* parent = qobject_cast<QWidget*>(qobj->parent());
+	if(parent)
+	{
+		setparentWidget(parent);
+	}
+	m_utils_sptr->setParent(parent);
+	initLayout();
+    m_alg=createAlgorithm();
+	addtoPropertyLabelsHash();
+	
+}
+ICatSearch::~ICatSearch()
+{
+}
+QWidget* ICatSearch::getParentWidget()
+{
+	return m_applicationWindow;
+}
+/* this method sets the parent widget as application window
+*/
+void ICatSearch::setparentWidget(QWidget* par)
+{
+	m_applicationWindow= par;
+}
+/// Set up the dialog layout
+void ICatSearch::initLayout()
+{
+ 	m_uiForm.setupUi(this);
+	// when light blue back ground is set in ICat search dailog ,
+	//the instrument combo box popup down and up arrow disappears
+	// I'm setting this style sheet to bring the combobox's popup listview's arrows back.
+	QString str="QComboBox#Instrument QListView{background-color: white;background-image:"
+		"url(ICatCombobackground.png);background-attachment: scroll;}"
+		"QComboBox#Instrument QListView QScrollBar:vertical{background-image:"
+		"url(:/images/ICatComboVScrollbar.png); "
+		"background-repeat: repeat-y; width: 17px; height:20px;} ";
+	m_uiForm.Instrument->setStyleSheet(str);
+	
+  connect(this,SIGNAL(error(const QString&)),parent()->parent(),SLOT(writeErrorToLogWindow(const QString&)));
+	try
+	{
+	populateInstrumentBox();
+	}
+	catch(Mantid::Kernel::Exception::NotFoundError&)
+	{
+		emit error("Error when Populating instruments box");
+
+	}
+	catch(std::runtime_error & e)
+	{
+		emit error(e.what());
+	}
+	
+	//validator for start and end run numbers
+	QValidator * runval= new QIntValidator(0,100000000,m_uiForm.StartRun);
+	m_uiForm.StartRun->setValidator(runval);
+	m_uiForm.EndRun->setValidator(runval);
+			
+	//getting last saved input data from registry
+	readSettings();
+
+	connect(m_uiForm.searchButton,SIGNAL(clicked()),this,SLOT(onSearch()));
+	connect(m_uiForm.closeButton,SIGNAL(clicked()),this,SLOT(onClose()));
+	connect(m_uiForm.searchtableWidget,SIGNAL(itemDoubleClicked(QTableWidgetItem* )),
+		this,SLOT(investigationSelected(QTableWidgetItem* )));
+	
+	connect(m_uiForm.startdatetoolButton,SIGNAL(clicked()),this,SLOT(popupCalendar()));
+	connect(m_uiForm.enddatetoolButton,SIGNAL(clicked()),this,SLOT(popupCalendar()));
+	connect(m_uiForm.helpButton,SIGNAL(clicked()),this,SLOT(helpButtonClicked()));
+
+	//this is for hiding the calendar widget if it's visible
+	m_uiForm.StartRun->installEventFilter(this);
+	m_uiForm.EndRun->installEventFilter(this);
+	m_uiForm.Keywords->installEventFilter(this);
+	m_uiForm.searchframeWidget->installEventFilter(this);
+		
+}
+/// This method gets called  when the widget is closed
+void ICatSearch::closeEvent(QCloseEvent*)
+{
+	saveSettings();
+}
+
+/// This method is the handler for search button
+void ICatSearch::onSearch()
+{	 
+	//clear the workspace pointer
+	m_ws_sptr.reset();
+   // execute the search by run number algorithm
+	executeSearch(m_ws_sptr);
+}
+
+/** Is case sensitive search
+*/
+bool ICatSearch::isCaseSensitiveSearch()
+{
+	return m_uiForm.CaseSensitive->isChecked();
+}
+
+
+
+/* This method updates the search result to search tree
+ * @param ws_sptr :: workspace shared pointer
+*/ 
+void ICatSearch::updatesearchResults(ITableWorkspace_sptr& ws_sptr )
+{	
+	if(!m_utils_sptr)
+  {
+		return;
+  }
+	m_utils_sptr->resetSearchResultsWidget(m_uiForm.searchtableWidget);
+	m_utils_sptr->updatesearchResults(ws_sptr,m_uiForm.searchtableWidget);
+	m_utils_sptr->updateSearchLabel(ws_sptr,m_uiForm.searchlabel);
+
+}
+
+/** This method populates the instrument box
+*/
+void ICatSearch::populateInstrumentBox(){
+  				
+		if(!m_utils_sptr)
+    {
+			return;
+    }
+		m_utils_sptr->populateInstrumentBox(m_uiForm.Instrument);
+	
+}
+
+/**This method gets run numbers from the start and end run boxes.
+  *@param startRun :: start run number
+  *@param endRun :: end run number
+*/
+void ICatSearch::getRunValues(double& startRun,double& endRun)
+{
+	endRun = m_uiForm.EndRun->text().toDouble();
+	startRun = m_uiForm.StartRun->text().toDouble();
+}
+
+/**This method gets start and end dates from the start and end date boxes.
+  *@param startDate :: start date  
+  *@param endDate :: end date
+*/
+void ICatSearch::getDates(QString& startDate,QString& endDate)
+{
+	startDate = m_uiForm.StartDate->text();
+	endDate =m_uiForm.EndDate->text();
+
+	if(!startDate.compare("//",Qt::CaseInsensitive))
+	{
+		startDate="";
+	}
+
+	if(!endDate.compare("//",Qt::CaseInsensitive))
+	{
+		endDate="";
+	}
+
+}
+///popup DateTime calender to select date
+void ICatSearch:: popupCalendar()
+{
+	if(!m_utils_sptr)
+		return;
+
+	m_utils_sptr->popupCalendar(this);
+	
+	QObject * qsender= sender();
+	if(!qsender) return;
+	 m_sender=qsender;
+	
+}
+///date changed
+void ICatSearch::getDate(const QDate& date  )
+{
+	//calendarWidget()->close();
+	m_utils_sptr->closeCalendarWidget();//close the calendar widget
+	if(!m_sender) return;
+
+	if(!m_sender->objectName().compare("startdatetoolButton"))
+	{
+	m_uiForm.StartDate->setText(date.toString("dd/MM/yyyy"));
+	}
+	if(!m_sender->objectName().compare("enddatetoolButton"))
+	{
+	m_uiForm.EndDate->setText(date.toString("dd/MM/yyyy"));
+	}
+}
+
+/**This method gets the selected instrument
+  *@param instrName :: name of the selected instrument
+*/
+void ICatSearch::getSelectedInstrument(QString& instrName)
+{
+	instrName=m_uiForm.Instrument->currentText();
+}
+
+Mantid::API::IAlgorithm_sptr ICatSearch::createAlgorithm()
+{
+	QString algName("CatalogSearch");
+	Mantid::API::IAlgorithm_sptr alg;
+	const int version=-1;
+	try
+	{
+	alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
+	}
+	catch(...)
+	{
+		throw std::runtime_error("Error when creating search algorithm"); 
+	}
+	return alg;
+
+}
+/**This method executes the search by run number algorithm
+ *@param ws_sptr :: shared pointer to outputworkspace
+*/
+bool  ICatSearch::executeSearch(ITableWorkspace_sptr& ws_sptr)
+{
+	//before starting new search investigations clear the old one.
+	m_utils_sptr->clearSearch(m_uiForm.searchtableWidget,"investigations");
+	
+	//update the label status
+	m_utils_sptr->setLabelText(m_uiForm.searchlabel,"Searching investigations...");
+	
+	//now get the input values for search
+	QString startDate,endDate;
+	getDates(startDate,endDate);
+
+	double startRun=0,endRun=0;
+	//get start and end run values 
+	getRunValues(startRun,endRun);
+	
+	// get the selected instrument
+	QString instr ;
+	getSelectedInstrument(instr);
+	
+	bool bCase(isCaseSensitiveSearch());
+	
+	QString keywords= m_uiForm.Keywords->text();
+
+		
+	if(!setProperty("StartRun",startRun))
+	{
+		updatesearchResults(ws_sptr);
+		return false;
+	}
+	
+	if(!setProperty("EndRun",endRun)){
+		
+		updatesearchResults(ws_sptr);
+		return false;
+	}
+	if(!setProperty("Instrument",instr.toStdString())){
+		updatesearchResults(ws_sptr);
+		return false;
+	}
+	if(!setProperty("StartDate",startDate.toStdString())){
+		updatesearchResults(ws_sptr);
+		return false;
+	}
+	if(!setProperty("EndDate",endDate.toStdString())){
+		updatesearchResults(ws_sptr);
+		return false;
+	}
+	if(!setProperty("Case Sensitive",bCase)){
+		updatesearchResults(ws_sptr);
+		return false;
+	}
+	if(!setProperty("Keywords",keywords.toStdString())){
+		updatesearchResults(ws_sptr);
+		return false;
+	}
+	if(!setProperty("OutputWorkspace","investigations")){
+		updatesearchResults(ws_sptr);
+		return false;
+	}
+	
+	// execute the algorithm asynchrnously	
+	Poco::ActiveResult<bool> result(m_alg->executeAsync());
+	while(!result.available() )
+	{
+		QCoreApplication::processEvents();
+		
+	}
+	if(result.available())
+	{
+		if(result.failed())
+		{
+			ws_sptr.reset();
+			updatesearchResults(ws_sptr);
+			emit error(QString::fromStdString(result.exception()->message()));
+			return false;
+		}
+		if(AnalysisDataService::Instance().doesExist("investigations"))
+		{
+			ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
+				(AnalysisDataService::Instance().retrieve("investigations"));
+			updatesearchResults(ws_sptr);
+		}
+			
+		
+	}
+	return true;
+
+}
+
+struct Contains
+{ 
+Contains(std::string name):m_name(name){}
+bool operator()(Mantid::Kernel::Property* prop)
+{
+std::string name=prop->name();
+std::string::iterator pos = std::remove_if(name.begin(),name.end(), isspace);
+name.erase(pos,name.end());//removing the sapce
+
+return (!name.compare(m_name));
+}
+std::string m_name;
+
+};
+
+/** This method adds prpoerty name and validator label for the property to a hash table
+  * This method iterates through each widget in the search grid layout and gets the label widget
+  * and if it's validator label adds this to a hash table.
+  * validator label objectname  for each property is "propertyname_2" eg;"StartDate_2"
+  * from the label object name remove the "_2" to get propertyname
+  * some property has space between words.remove the space(as space not allowed in QT object names)
+  * and compare with propertyname to know the label is a validator label
+*/
+void ICatSearch::addtoPropertyLabelsHash()
+{		
+	//get total row and column count in the gridlayout where search controls are placed
+	int totalcol= m_uiForm.gridLayout->columnCount();
+	int totalrow =m_uiForm.gridLayout->rowCount();
+	//loop through each widget in the gridlayout
+	for (int row=0;row<totalrow;++row)
+	{
+		for (int col=0;col<totalcol;++col)
+		{
+			QLayoutItem  *item= m_uiForm.gridLayout->itemAtPosition(row,col); 
+			if(!item) continue;
+			QWidget* widget=item->widget();
+			if(!widget) continue;
+			QLabel* label=qobject_cast<QLabel*>(widget);
+			if(!label)
+			{
+				continue;
+			}
+			
+			//for each property,the validator label is named as "propertyname_2",
+			//now remove "_2" from label name to get property name
+			int index=label->objectName().indexOf("_");
+			if(index==-1)
+			{
+				continue;
+			}
+				QString name;
+				name=label->objectName().left(index);
+				std::string propName=name.toStdString();
+				
+				std::vector<Mantid::Kernel::Property*> props=m_alg->getProperties();
+				//if this name exists in algorithm properties vector it's a property validator label
+				std::vector<Mantid::Kernel::Property*>::iterator prop;
+				prop=std::find_if(props.begin(),props.end(),Contains(propName));
+				if(prop!=props.end())
+				{				
+					//at this point the label is a validator label
+					//add the lable to a hash 
+					m_propLabelHash[QString::fromStdString((*prop)->name())]=label;
+					label->hide();//initially hide the label 
+
+				}
+		
+			
+		}
+	}
+	
+}
+/// This method shows the invalid marker label for a property
+void ICatSearch::showInvalidMarkerLabel(const QString& name)
+{
+	if(m_propLabelHash.contains(name))
+	{	
+		std::string documentation;
+		std::vector<Mantid::Kernel::Property*> props=m_alg->getProperties();
+		//if this name exists in algorithm properties vector it's a proprty validator label
+		std::vector<Mantid::Kernel::Property*>::iterator result;
+		result=std::find_if(props.begin(),props.end(),Contains(name.toStdString()));
+		if(result!=props.end())
+		{
+			documentation=(*result)->documentation();
+
+		}
+		m_propLabelHash.value(name)->setToolTip(QString::fromStdString(documentation));
+		m_propLabelHash.value(name)->show();
+	}
+}
+/// hide invalid marker labels
+void ICatSearch::hideInvalidMarkerLabel(const QString& name)
+{
+	if(m_propLabelHash.contains(name))
+	{
+		if(m_propLabelHash.value(name)->isVisible())
+		{
+			m_propLabelHash.value(name)->hide();
+		}
+	}
+}
+/** This method closes the search widget.
+*/
+void ICatSearch::onClose()
+{
+	this->close();
+	QObject* qobj=parent();
+	QWidget* parent=qobject_cast<QWidget*>(qobj);
+	if(parent)
+	{
+		parent->close();
+	}
+}
+
+/** This method is called when an investigation is selected  from investigations list
+  *@param item ::  item in the table
+*/
+void ICatSearch::investigationSelected(QTableWidgetItem * item )
+{
+	//ICatUtils utils;
+	if(!m_utils_sptr)
+		return;
+	m_utils_sptr->investigationSelected(m_uiForm.searchtableWidget,item,m_applicationWindow,m_ws_sptr);
+}
+
+/** This method saves search settings
+*/
+void ICatSearch::saveSettings()
+{
+	QSettings searchsettings;
+	searchsettings.beginGroup("ICatSettings/Search");
+	searchsettings.setValue("StartRun",m_uiForm.StartRun->text());
+    searchsettings.setValue("EndRun",m_uiForm.EndRun->text());
+	searchsettings.setValue("Instrument",m_uiForm.Instrument->currentText());
+	searchsettings.setValue("Start Date",m_uiForm.StartDate->text());
+	searchsettings.setValue("End Date",m_uiForm.EndDate->text());
+	searchsettings.setValue("Keywords",m_uiForm.Keywords->text());
+	searchsettings.setValue("Case Sensitive",m_uiForm.CaseSensitive->isChecked());
+	
+	searchsettings.endGroup();
+
+}
+/// read settings from registry
+void ICatSearch::readSettings()
+{
+	QSettings searchsettings;
+	searchsettings.beginGroup("ICatSettings/Search");
+	m_uiForm.StartRun->setText(searchsettings.value("startRun").toString());
+	m_uiForm.EndRun->setText(searchsettings.value("endRun").toString());
+	//m_uiForm.Instrument->setItemText (0,searchsettings.value("instrument").toString());
+	int index=m_uiForm.Instrument->findText(searchsettings.value("instrument").toString());
+	if(index!=-1)
+	{
+		m_uiForm.Instrument->setCurrentIndex(index);
+	}
+	m_uiForm.StartDate->setText(searchsettings.value("Start Date").toString());
+	m_uiForm.EndDate->setText(searchsettings.value("End Date").toString());
+	m_uiForm.CaseSensitive->setChecked(searchsettings.value("Case Sensitive").toBool());
+
+	searchsettings.endGroup();
+}
+
+//handler for helpbutton
+void ICatSearch::helpButtonClicked()
+{
+	QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/ISIS_Search"));
+
+}
+
+bool ICatSearch::eventFilter(QObject *obj, QEvent *event)
+{
+	if (event->type() ==QEvent::FocusIn && obj==m_uiForm.searchframeWidget)
+	{		
+		if(m_utils_sptr->calendarWidget())
+		{
+			m_utils_sptr->calendarWidget()->hide();
+		}
+	
+	}
+	else if (event->type()==QEvent::MouseButtonPress)
+	{
+		if(m_utils_sptr->calendarWidget())
+		{
+			m_utils_sptr->calendarWidget()->hide();
+		}
+
+	}
+	else
+	{
+		// standard event processing
+		return QWidget::eventFilter(obj, event);
+	}
+	return true;
+}
+
+
+
+
+
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/ICatUtils.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/ICatUtils.cpp
index 89049aa8f268239e54d7aff8774eb8eb0746a4e3..dd823efaf02f462fdc0f87808b0a2577ed38735c 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/ICatUtils.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/ICatUtils.cpp
@@ -1,378 +1,378 @@
-
-#include "MantidQtMantidWidgets/ICatUtils.h"
-#include "MantidAPI/AnalysisDataService.h"
-#include "MantidQtAPI/InterfaceManager.h"
-#include "MantidQtAPI/AlgorithmDialog.h"
-
-#include <QMdiSubWindow>
-#include <QStringList>
-#include <QFont>
-#include <QHeaderView>
-#include <QDialog>
-#include <QPalette>
-#include <QColor>
-
-using namespace MantidQt::MantidWidgets;
-
-using namespace Mantid::API;
-
-
-ICatUtils::ICatUtils():m_calendarWidget(NULL),m_applicationWindow(NULL)
-{
-	
-	
-}
-
-/**This method updates the search result to search tree
- *@param ws_sptr :: workspace shared pointer
- *@param tablewidget :: pointer to table widget
-*/ 
-void ICatUtils::updatesearchResults(Mantid::API::ITableWorkspace_sptr& ws_sptr,QTableWidget* tablewidget )
-{
-	if(!ws_sptr || ws_sptr->rowCount()==0)
-	{
-		return ;
-	}
-
-	//now set alternating color flag
-	tablewidget->setAlternatingRowColors(true);
-	//stylesheet for alternating background color
-	tablewidget->setStyleSheet("alternate-background-color: rgb(216, 225, 255)");
-	//disable  sorting as per QT documentation.otherwise  setitem will give undesired results
-	tablewidget->setSortingEnabled(false);
-
-	tablewidget->verticalHeader()->setVisible(false);
-	tablewidget->setRowCount(ws_sptr->rowCount());	
-	tablewidget->setColumnCount(ws_sptr->columnCount());	
-
-	for (int i=0;i<ws_sptr->rowCount();++i)
-	{
-		//setting the row height of tableWidget 
-		tablewidget->setRowHeight(i,20);
-	}
-	
-	QStringList qlabelList;
-	for(int i=0;i<ws_sptr->columnCount();i++)
-	{
-		Column_sptr col_sptr = ws_sptr->getColumn(i);
-		//get the column name to display as the header of table widget
-		QString colTitle = QString::fromStdString(col_sptr->name());
-		qlabelList.push_back(colTitle);
-	
-		for(int j=0;j<ws_sptr->rowCount();++j)
-		{
-		    std::ostringstream ostr;
-		     col_sptr->print(ostr,j);
-						 
-			 QTableWidgetItem *newItem  = new QTableWidgetItem(QString::fromStdString(ostr.str()));
-			 newItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
-			 tablewidget->setItem(j,i, newItem);
-			 newItem->setToolTip(QString::fromStdString(ostr.str()));
-		}
-	}
-	QFont font;
-	font.setBold(true);
-	//setting table widget header labels from table workspace
-	tablewidget->setHorizontalHeaderLabels(qlabelList);
-	for (int i=0;i<tablewidget->columnCount();++i)
-	{
-		tablewidget->horizontalHeaderItem(i)->setFont(font);
-	}
-	//sorting by title
-	tablewidget->sortByColumn(2,Qt::AscendingOrder);
-	//enable sorting
-	tablewidget->setSortingEnabled(true);
-
-}
-
-//for clearing the table widget
-void ICatUtils::resetSearchResultsWidget(QTableWidget* tablewidget )
-{
-	//below for loop is for clearing the table widget on search button click.Bcoz Each click on search button to load data,rows were getting appended.
-	// table widget clear() method is clearing only the tablewidgetitem text,not removing the rows,columns
-	// so i'm using removeRow().When I removed the row from top of the table it was not working.so the for loop starts from bottom to top
-	for (int i=tablewidget->rowCount()-1;i>=0;--i)
-	{
-		tablewidget->removeRow(i);
-	}
-	for (int j=tablewidget->columnCount()-1;j>=0;--j)
-	{
-		tablewidget->removeColumn(j);
-	}
-	//now set alternating color flag
-	tablewidget->setAlternatingRowColors(false);
-	// reset the background color to white
-	// if it's not reset to white alternating colour is not working.
-	tablewidget->setStyleSheet("background-color: rgb(216, 225, 255)");
-	
-	//disable  sorting as per QT documentation.otherwise  setitem will give undesired results
-	tablewidget->setSortingEnabled(false);
-
-	tablewidget->verticalHeader()->setVisible(false);
-}
-
-
-//This method clears the data associated to the previous search
-void ICatUtils::clearSearch(QTableWidget* tablewidget,const std::string & wsName )
-{
-	//before starting new search investigations clear the old one.
-
-	if(AnalysisDataService::Instance().doesExist(wsName))
-	{
-		AnalysisDataService::Instance().remove(wsName);
-
-	}
-
-	resetSearchResultsWidget(tablewidget);
-
-}
-/**This method is called when an investigation is selected  from investigations list
- *@param item ::  table widget item
- */
-void ICatUtils::investigationSelected(QTableWidget* tablewidget,QTableWidgetItem* item,
-									   QWidget* parent,Mantid::API::ITableWorkspace_sptr ws_sptr )
-{
-	if(!item) return ;
-	int row=item->row();
-
-	// column zero is investigation id
-	QTableWidgetItem* invstItem = tablewidget->item(row,0);
-	QString qinvstId = invstItem->text();
-	long long invstId = qinvstId.toLongLong();
-    
-	//column one is RbNumber
-	QTableWidgetItem* rbNumberItem = tablewidget->item(row,1);
-	if(!rbNumberItem) return;
-    QString qRbNumber = rbNumberItem->text();
-	///column two is Title
-	QTableWidgetItem* titleItem = tablewidget->item(row,2);
-	if(!titleItem)return ;
-	QString qTitle = titleItem->text();
-    //column 4 is Instrument
-	QTableWidgetItem* instrumentItem = tablewidget->item(row,3);
-	if(!instrumentItem)return;
-	QString qInstrument = instrumentItem->text();
-		
-	//parent of user_win is application window;
-	QMdiSubWindow* usr_win = new QMdiSubWindow(parent);
-	if(!usr_win) return;
-	usr_win->setAttribute(Qt::WA_DeleteOnClose, false);
-
-	m_invstWidget= new ICatInvestigation(invstId,qRbNumber,qTitle,qInstrument,ws_sptr,usr_win);
-	if( m_invstWidget )
-	{ 
-		QRect frame = QRect(usr_win->frameGeometry().topLeft() - usr_win->geometry().topLeft(), 
-			usr_win->geometry().bottomRight() - usr_win->geometry().bottomRight());
-		usr_win->setWidget(m_invstWidget);
-		QRect iface_geom = QRect(frame.topLeft() + m_invstWidget->geometry().topLeft(), 
-			frame.bottomRight() + m_invstWidget->geometry().bottomRight()+QPoint(15,35));
-		usr_win->setGeometry(iface_geom);
-		usr_win->move(QPoint(600, 400));
-		usr_win->show();
-	}
-}
-/** This method executes the ListInstruments algorithm
-  * and fills the instrument box with instrument lists returned by ICat API
-  * @return shared pointer to workspace which contains instrument names
-*/
-std::vector<std::string> ICatUtils::executeListInstruments()
-{
-	QString algName("CatalogListInstruments");
-	const int version=-1;
-	Mantid::API::IAlgorithm_sptr alg;
-	try
-	{
-		alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
-	}
-	catch(...)
-	{
-		throw std::runtime_error("Error when Populating the instrument list box"); 
-			
-	}
-		
-	Poco::ActiveResult<bool> result(alg->executeAsync());
-	while( !result.available() )
-	{
-		QCoreApplication::processEvents();
-	}
-	if(!alg->isExecuted())
-	{		
-		//if the algorithm failed check the session id passed is valid
-		if(!isSessionValid(alg))
-		{			
-			//at this point session is invalid, popup loginbox to login
-			if(login())
-			{
-			//now populate instrument box
-			 std::vector<std::string> instruments =executeListInstruments();
-			 return instruments;
-			}
-      else
-      {
-        throw std::runtime_error("Please Login to the information catalog using the login menu provided to do the investigation search.");
-      }
-		}
-		else
-		{			
-			return std::vector<std::string>();
-		}
-	}
-	std::vector<std::string>instrlist;
-	try
-	{
-		
-	  instrlist= alg->getProperty("InstrumentList");
-	}
-	catch (Mantid::Kernel::Exception::NotFoundError& e)
-	{
-		throw e;
-	}
-	return instrlist;
-
-}
-bool ICatUtils::isSessionValid(const Mantid::API::IAlgorithm_sptr& alg)
-{
-	try
-	{
-	return  alg->getProperty("isValid");
-	}
-	catch (Mantid::Kernel::Exception::NotFoundError&e)
-	{
-		throw e;
-	}
-   
-}
-bool ICatUtils::login()
-{
-	QString algName("CatalogLogin");
-	const int version =-1;
-	Mantid::API::IAlgorithm_sptr alg;
-	try
-	{
-		alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
-	}
-	catch(...)
-	{		
-		throw std::runtime_error("Error when Populating the instrument list box"); 
-	}
-	if(!m_applicationWindow)
-	{return false;}
-
-	MantidQt::API::AlgorithmDialog *dlg =MantidQt::API::InterfaceManager::Instance().createDialog(alg.get(), m_applicationWindow, false, "", "", "");
-	if(!dlg) return false;
-	if(dlg->exec()==QDialog::Accepted)
-	{
-		delete dlg;
-		Poco::ActiveResult<bool> result(alg->executeAsync());
-		while( !result.available() )
-		{
-			QCoreApplication::processEvents();
-		}
-	
-		if(!alg->isExecuted())
-		{
-			return false;
-		}
-		return true;
-	}
-  else
-  {        
-    return false;
-  }
-}
-
-/** This method populates the instrument box
-*/
-void ICatUtils::populateInstrumentBox(QComboBox* instrumentBox)
-{
-	
-	/// execute the algorithm ListInstruments
-	std::vector<std::string> instrlist = executeListInstruments();
-
-	if(instrlist.empty())
-	{
-		throw std::runtime_error("Instrument list is empty");
-	}
-
-	/// loop through values
-	std::vector<std::string>::const_iterator citr;
-	for (citr=instrlist.begin();citr!=instrlist.end();++citr)
-	{
-		//populate the instrument box  
-		instrumentBox->addItem(QString::fromStdString(*citr));
-	}
-
-	//sorting the combo by instrument name;
-	instrumentBox->model()->sort(0);
-	instrumentBox->insertItem(-1,"");
-}
-
-
-/// for displaying the investigatiosn count 
-void ICatUtils::updateSearchLabel(const Mantid::API::ITableWorkspace_sptr& ws_sptr,QLabel* label)
-{
-	std::stringstream rowcount;
-	QString results("Search Results : ");
-	if(!ws_sptr)
-	{
-		results+="No investigations to display as an error occured";
-	}
-	else{
-		rowcount<<ws_sptr->rowCount();
-		results+=QString::fromStdString(rowcount.str()) + " Investigations Found";
-	}
-    setLabelText(label,results);
-}
-void ICatUtils::setLabelText(QLabel* plabel,const QString& text)
-{
-	//setting the label string
-	QFont font;
-	font.setBold(true);
-	plabel->setText(text);
-	plabel->setAlignment(Qt::AlignHCenter);
-	plabel->setFont(font);
-}
-void  ICatUtils::popupCalendar(QWidget* parent)
-{
-	m_calendarWidget = new SearchCalendar(parent);
-	connect(m_calendarWidget,SIGNAL(clicked(const QDate&)) ,parent,SLOT(getDate(const QDate&)));
-    m_calendarWidget->setObjectName(QString::fromUtf8("calendarWidget"));
-    m_calendarWidget->setGeometry(QRect(386, 64, 211, 148));
-    m_calendarWidget->setGridVisible(true);
-	m_calendarWidget->show();
-	
-}
-
-/// close calendarwidget
-void ICatUtils::closeCalendarWidget()
-{
-	if(m_calendarWidget)
-	{
-		m_calendarWidget->hide();
-	}
-}
-/// This method returns the calendar widget
-QCalendarWidget* ICatUtils::calendarWidget()
-{
-	return m_calendarWidget;
-}
-
-/// This method sets the parent widget of search widgets.
-void ICatUtils::setParent(QWidget*parent)
-{
-	m_applicationWindow=parent;
-
-}
-
-SearchCalendar::SearchCalendar(QWidget* par):QCalendarWidget(par)
-{
-}
-
-
-
-
-
-
-
-
-
+
+#include "MantidQtMantidWidgets/ICatUtils.h"
+#include "MantidAPI/AnalysisDataService.h"
+#include "MantidQtAPI/InterfaceManager.h"
+#include "MantidQtAPI/AlgorithmDialog.h"
+
+#include <QMdiSubWindow>
+#include <QStringList>
+#include <QFont>
+#include <QHeaderView>
+#include <QDialog>
+#include <QPalette>
+#include <QColor>
+
+using namespace MantidQt::MantidWidgets;
+
+using namespace Mantid::API;
+
+
+ICatUtils::ICatUtils():m_calendarWidget(NULL),m_applicationWindow(NULL)
+{
+	
+	
+}
+
+/**This method updates the search result to search tree
+ *@param ws_sptr :: workspace shared pointer
+ *@param tablewidget :: pointer to table widget
+*/ 
+void ICatUtils::updatesearchResults(Mantid::API::ITableWorkspace_sptr& ws_sptr,QTableWidget* tablewidget )
+{
+	if(!ws_sptr || ws_sptr->rowCount()==0)
+	{
+		return ;
+	}
+
+	//now set alternating color flag
+	tablewidget->setAlternatingRowColors(true);
+	//stylesheet for alternating background color
+	tablewidget->setStyleSheet("alternate-background-color: rgb(216, 225, 255)");
+	//disable  sorting as per QT documentation.otherwise  setitem will give undesired results
+	tablewidget->setSortingEnabled(false);
+
+	tablewidget->verticalHeader()->setVisible(false);
+	tablewidget->setRowCount(ws_sptr->rowCount());	
+	tablewidget->setColumnCount(ws_sptr->columnCount());	
+
+	for (int i=0;i<ws_sptr->rowCount();++i)
+	{
+		//setting the row height of tableWidget 
+		tablewidget->setRowHeight(i,20);
+	}
+	
+	QStringList qlabelList;
+	for(int i=0;i<ws_sptr->columnCount();i++)
+	{
+		Column_sptr col_sptr = ws_sptr->getColumn(i);
+		//get the column name to display as the header of table widget
+		QString colTitle = QString::fromStdString(col_sptr->name());
+		qlabelList.push_back(colTitle);
+	
+		for(int j=0;j<ws_sptr->rowCount();++j)
+		{
+		    std::ostringstream ostr;
+		     col_sptr->print(ostr,j);
+						 
+			 QTableWidgetItem *newItem  = new QTableWidgetItem(QString::fromStdString(ostr.str()));
+			 newItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
+			 tablewidget->setItem(j,i, newItem);
+			 newItem->setToolTip(QString::fromStdString(ostr.str()));
+		}
+	}
+	QFont font;
+	font.setBold(true);
+	//setting table widget header labels from table workspace
+	tablewidget->setHorizontalHeaderLabels(qlabelList);
+	for (int i=0;i<tablewidget->columnCount();++i)
+	{
+		tablewidget->horizontalHeaderItem(i)->setFont(font);
+	}
+	//sorting by title
+	tablewidget->sortByColumn(2,Qt::AscendingOrder);
+	//enable sorting
+	tablewidget->setSortingEnabled(true);
+
+}
+
+//for clearing the table widget
+void ICatUtils::resetSearchResultsWidget(QTableWidget* tablewidget )
+{
+	//below for loop is for clearing the table widget on search button click.Bcoz Each click on search button to load data,rows were getting appended.
+	// table widget clear() method is clearing only the tablewidgetitem text,not removing the rows,columns
+	// so i'm using removeRow().When I removed the row from top of the table it was not working.so the for loop starts from bottom to top
+	for (int i=tablewidget->rowCount()-1;i>=0;--i)
+	{
+		tablewidget->removeRow(i);
+	}
+	for (int j=tablewidget->columnCount()-1;j>=0;--j)
+	{
+		tablewidget->removeColumn(j);
+	}
+	//now set alternating color flag
+	tablewidget->setAlternatingRowColors(false);
+	// reset the background color to white
+	// if it's not reset to white alternating colour is not working.
+	tablewidget->setStyleSheet("background-color: rgb(216, 225, 255)");
+	
+	//disable  sorting as per QT documentation.otherwise  setitem will give undesired results
+	tablewidget->setSortingEnabled(false);
+
+	tablewidget->verticalHeader()->setVisible(false);
+}
+
+
+//This method clears the data associated to the previous search
+void ICatUtils::clearSearch(QTableWidget* tablewidget,const std::string & wsName )
+{
+	//before starting new search investigations clear the old one.
+
+	if(AnalysisDataService::Instance().doesExist(wsName))
+	{
+		AnalysisDataService::Instance().remove(wsName);
+
+	}
+
+	resetSearchResultsWidget(tablewidget);
+
+}
+/**This method is called when an investigation is selected  from investigations list
+ *@param item ::  table widget item
+ */
+void ICatUtils::investigationSelected(QTableWidget* tablewidget,QTableWidgetItem* item,
+									   QWidget* parent,Mantid::API::ITableWorkspace_sptr ws_sptr )
+{
+	if(!item) return ;
+	int row=item->row();
+
+	// column zero is investigation id
+	QTableWidgetItem* invstItem = tablewidget->item(row,0);
+	QString qinvstId = invstItem->text();
+	long long invstId = qinvstId.toLongLong();
+    
+	//column one is RbNumber
+	QTableWidgetItem* rbNumberItem = tablewidget->item(row,1);
+	if(!rbNumberItem) return;
+    QString qRbNumber = rbNumberItem->text();
+	///column two is Title
+	QTableWidgetItem* titleItem = tablewidget->item(row,2);
+	if(!titleItem)return ;
+	QString qTitle = titleItem->text();
+    //column 4 is Instrument
+	QTableWidgetItem* instrumentItem = tablewidget->item(row,3);
+	if(!instrumentItem)return;
+	QString qInstrument = instrumentItem->text();
+		
+	//parent of user_win is application window;
+	QMdiSubWindow* usr_win = new QMdiSubWindow(parent);
+	if(!usr_win) return;
+	usr_win->setAttribute(Qt::WA_DeleteOnClose, false);
+
+	m_invstWidget= new ICatInvestigation(invstId,qRbNumber,qTitle,qInstrument,ws_sptr,usr_win);
+	if( m_invstWidget )
+	{ 
+		QRect frame = QRect(usr_win->frameGeometry().topLeft() - usr_win->geometry().topLeft(), 
+			usr_win->geometry().bottomRight() - usr_win->geometry().bottomRight());
+		usr_win->setWidget(m_invstWidget);
+		QRect iface_geom = QRect(frame.topLeft() + m_invstWidget->geometry().topLeft(), 
+			frame.bottomRight() + m_invstWidget->geometry().bottomRight()+QPoint(15,35));
+		usr_win->setGeometry(iface_geom);
+		usr_win->move(QPoint(600, 400));
+		usr_win->show();
+	}
+}
+/** This method executes the ListInstruments algorithm
+  * and fills the instrument box with instrument lists returned by ICat API
+  * @return shared pointer to workspace which contains instrument names
+*/
+std::vector<std::string> ICatUtils::executeListInstruments()
+{
+	QString algName("CatalogListInstruments");
+	const int version=-1;
+	Mantid::API::IAlgorithm_sptr alg;
+	try
+	{
+		alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
+	}
+	catch(...)
+	{
+		throw std::runtime_error("Error when Populating the instrument list box"); 
+			
+	}
+		
+	Poco::ActiveResult<bool> result(alg->executeAsync());
+	while( !result.available() )
+	{
+		QCoreApplication::processEvents();
+	}
+	if(!alg->isExecuted())
+	{		
+		//if the algorithm failed check the session id passed is valid
+		if(!isSessionValid(alg))
+		{			
+			//at this point session is invalid, popup loginbox to login
+			if(login())
+			{
+			//now populate instrument box
+			 std::vector<std::string> instruments =executeListInstruments();
+			 return instruments;
+			}
+      else
+      {
+        throw std::runtime_error("Please Login to the information catalog using the login menu provided to do the investigation search.");
+      }
+		}
+		else
+		{			
+			return std::vector<std::string>();
+		}
+	}
+	std::vector<std::string>instrlist;
+	try
+	{
+		
+	  instrlist= alg->getProperty("InstrumentList");
+	}
+	catch (Mantid::Kernel::Exception::NotFoundError& e)
+	{
+		throw e;
+	}
+	return instrlist;
+
+}
+bool ICatUtils::isSessionValid(const Mantid::API::IAlgorithm_sptr& alg)
+{
+	try
+	{
+	return  alg->getProperty("isValid");
+	}
+	catch (Mantid::Kernel::Exception::NotFoundError&e)
+	{
+		throw e;
+	}
+   
+}
+bool ICatUtils::login()
+{
+	QString algName("CatalogLogin");
+	const int version =-1;
+	Mantid::API::IAlgorithm_sptr alg;
+	try
+	{
+		alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
+	}
+	catch(...)
+	{		
+		throw std::runtime_error("Error when Populating the instrument list box"); 
+	}
+	if(!m_applicationWindow)
+	{return false;}
+
+	MantidQt::API::AlgorithmDialog *dlg =MantidQt::API::InterfaceManager::Instance().createDialog(alg.get(), m_applicationWindow, false, "", "", "");
+	if(!dlg) return false;
+	if(dlg->exec()==QDialog::Accepted)
+	{
+		delete dlg;
+		Poco::ActiveResult<bool> result(alg->executeAsync());
+		while( !result.available() )
+		{
+			QCoreApplication::processEvents();
+		}
+	
+		if(!alg->isExecuted())
+		{
+			return false;
+		}
+		return true;
+	}
+  else
+  {        
+    return false;
+  }
+}
+
+/** This method populates the instrument box
+*/
+void ICatUtils::populateInstrumentBox(QComboBox* instrumentBox)
+{
+	
+	/// execute the algorithm ListInstruments
+	std::vector<std::string> instrlist = executeListInstruments();
+
+	if(instrlist.empty())
+	{
+		throw std::runtime_error("Instrument list is empty");
+	}
+
+	/// loop through values
+	std::vector<std::string>::const_iterator citr;
+	for (citr=instrlist.begin();citr!=instrlist.end();++citr)
+	{
+		//populate the instrument box  
+		instrumentBox->addItem(QString::fromStdString(*citr));
+	}
+
+	//sorting the combo by instrument name;
+	instrumentBox->model()->sort(0);
+	instrumentBox->insertItem(-1,"");
+}
+
+
+/// for displaying the investigatiosn count 
+void ICatUtils::updateSearchLabel(const Mantid::API::ITableWorkspace_sptr& ws_sptr,QLabel* label)
+{
+	std::stringstream rowcount;
+	QString results("Search Results : ");
+	if(!ws_sptr)
+	{
+		results+="No investigations to display as an error occured";
+	}
+	else{
+		rowcount<<ws_sptr->rowCount();
+		results+=QString::fromStdString(rowcount.str()) + " Investigations Found";
+	}
+    setLabelText(label,results);
+}
+void ICatUtils::setLabelText(QLabel* plabel,const QString& text)
+{
+	//setting the label string
+	QFont font;
+	font.setBold(true);
+	plabel->setText(text);
+	plabel->setAlignment(Qt::AlignHCenter);
+	plabel->setFont(font);
+}
+void  ICatUtils::popupCalendar(QWidget* parent)
+{
+	m_calendarWidget = new SearchCalendar(parent);
+	connect(m_calendarWidget,SIGNAL(clicked(const QDate&)) ,parent,SLOT(getDate(const QDate&)));
+    m_calendarWidget->setObjectName(QString::fromUtf8("calendarWidget"));
+    m_calendarWidget->setGeometry(QRect(386, 64, 211, 148));
+    m_calendarWidget->setGridVisible(true);
+	m_calendarWidget->show();
+	
+}
+
+/// close calendarwidget
+void ICatUtils::closeCalendarWidget()
+{
+	if(m_calendarWidget)
+	{
+		m_calendarWidget->hide();
+	}
+}
+/// This method returns the calendar widget
+QCalendarWidget* ICatUtils::calendarWidget()
+{
+	return m_calendarWidget;
+}
+
+/// This method sets the parent widget of search widgets.
+void ICatUtils::setParent(QWidget*parent)
+{
+	m_applicationWindow=parent;
+
+}
+
+SearchCalendar::SearchCalendar(QWidget* par):QCalendarWidget(par)
+{
+}
+
+
+
+
+
+
+
+
+
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/MWDiag.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/MWDiag.cpp
index 33917033b5792813fb97acc60079952fc4c3cb92..fba88a17b689a91bca0d2d95dd99678ede9c3533 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/MWDiag.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/MWDiag.cpp
@@ -1,606 +1,606 @@
-#include "MantidQtMantidWidgets/MWDiag.h"
-#include "MantidQtMantidWidgets/DiagResults.h"
-#include "MantidQtMantidWidgets/MWRunFiles.h"
-#include "MantidQtAPI/AlgorithmInputHistory.h"
-#include "MantidQtAPI/FileDialogHandler.h"
-#include "MantidAPI/FrameworkManager.h"
-#include "MantidAPI/AnalysisDataService.h"
-#include "MantidAPI/MatrixWorkspace.h"
-#include "MantidKernel/Exception.h"
-#include "MantidAPI/FileProperty.h"
-#include "MantidGeometry/IInstrument.h"
-
-#include <QSignalMapper>
-#include <QFileInfo>
-#include <QFileDialog>
-#include <QDir>
-#include <QStringList>
-#include <QMessageBox>
-#include <QDoubleValidator>
-
-#include <vector>
-#include <string>
-
-using namespace Mantid::Kernel;
-using namespace Mantid::API;
-using namespace MantidQt::API;
-using namespace MantidQt::MantidWidgets;
-using Mantid::Geometry::IInstrument_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)
-{
-  // allows saving and loading the values the user entered on to the form
-  m_prevSets.beginGroup(prevSettingsGr);
-  // Layout the widgets
-  m_designWidg.setupUi(this);
-
-  loadSettings();
-  setupToolTips();
-  setUpValidators();
-  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()
-{
-  // Want the defaults from the instrument if nothing is saved in the config
-  IInstrument_sptr instrument = getInstrument(m_instru->currentText());
-
-  m_designWidg.leIFile->setText(getSetting("input mask"));
-  m_designWidg.leOFile->setText(getSetting("output file"));
-  m_designWidg.leSignificance->setText(getSetting("significance", instrument, "signif"));
-  m_designWidg.leHighAbs->setText(getSetting("high abs", instrument, "large"));
-  m_designWidg.leLowAbs->setText(getSetting("low abs", instrument, "tiny"));
-  m_designWidg.leHighMed->setText(getSetting("high median", instrument, "median_hi"));
-  m_designWidg.leLowMed->setText(getSetting("low median", instrument, "median_lo"));
-  m_designWidg.leVariation->setText(getSetting("variation", instrument, "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, "bkgd_threshold"));
-  m_designWidg.bleed_maxrate->setText(getSetting("bleed_max_framerate", instrument, "bleed_max_framerate"));
-  m_designWidg.ignored_pixels->setText(getSetting("bleed_ignored_pixels", instrument, "bleed_ignored_pixels"));
-
-  // Boolean settings
-  // Background tests
-  QString value = getSetting("test background", instrument, "check_background");
-  bool checked = static_cast<bool>(value.toUInt());
-  m_designWidg.ckDoBack->setChecked(checked);
-  // Zero removal
-  value = getSetting("no zero background", instrument, "remove_zero");
-  checked = static_cast<bool>(value.toUInt());
-  m_designWidg.ckZeroCounts->setChecked(checked);
-  // Bleed test
-  value = getSetting("bleed_test", instrument, "bleed_test");
-  checked = static_cast<bool>(value.toUInt());
-  m_designWidg.bleed_group->setChecked(checked);
-}
-
-void MWDiag::setSumState(bool checked)
-{
-  m_sumMono = checked;
-}
-
-
-/**
- * Get an instrument pointer for the name instrument
- */
-IInstrument_sptr MWDiag::getInstrument(const QString & name)
-{
-  std::string ws_name = "__empty_" + name.toStdString();
-  
-  AnalysisDataServiceImpl& dataStore = AnalysisDataService::Instance();
-  if( !dataStore.doesExist(ws_name) )
-  {
-    QString pyInput =
-      "from DirectEnergyConversion import setup_reducer\n"
-      "setup_reducer('%1')";
-    pyInput = pyInput.arg(QString::fromStdString(ws_name));
-    runPythonCode(pyInput);
-    if( !dataStore.doesExist(ws_name) )
-    {
-      return IInstrument_sptr();
-    }
-  }
-  MatrixWorkspace_sptr inst_ws = 
-    boost::dynamic_pointer_cast<MatrixWorkspace>(dataStore.retrieve(ws_name));
-  
-  return inst_ws->getInstrument();
-}
-
-QString MWDiag::getSetting(const QString & settingName, IInstrument_sptr instrument,
-			   const QString & idfName) const
-{
-  QString value;
-  if( m_prevSets.contains(settingName) )
-  {
-    value = m_prevSets.value(settingName).toString();
-  }
-  else if( instrument && !idfName.isEmpty() )
-  {
-    std::vector<double> params = instrument->getNumberParameter(idfName.toStdString());
-    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";
-
-  return value;
-}
-
-/// 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()
-{
-  m_prevSets.setValue("input mask", m_designWidg.leIFile->text());
-  m_prevSets.setValue("output file", m_designWidg.leOFile->text());
-
-  m_prevSets.setValue("significance", m_designWidg.leSignificance->text());
-  m_prevSets.setValue("no solid", m_designWidg.ckAngles->isChecked());
-  
-  m_prevSets.setValue("high abs", m_designWidg.leHighAbs->text());
-  m_prevSets.setValue("low abs", m_designWidg.leLowAbs->text());
-  m_prevSets.setValue("high median", m_designWidg.leHighMed->text());
-  m_prevSets.setValue("low median", m_designWidg.leLowMed->text());
-  
-  m_prevSets.setValue("variation", m_designWidg.leVariation->text());
-  
-  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_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 iFileToolTip = "A file containing a list of spectra numbers which we aleady know should be masked";
-  m_designWidg.lbIFile->setToolTip(iFileToolTip);
-  m_designWidg.leIFile->setToolTip(iFileToolTip);
-  m_designWidg.pbIFile->setToolTip(iFileToolTip);
-  
-  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 labelled 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)";
-  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)";
-  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)";
-  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)";
-  m_designWidg.leLowMed->setToolTip(lowMedToolTip);
-  m_designWidg.lbLowMed->setToolTip(lowMedToolTip);
-
-  QString variationToolTip = 
-    "When comparing equilivient 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"
-    "medain 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)";
-  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)";
-  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)";
-  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");
-}
-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.pbIFile, QString("InputFile"));
-  signalMapper->setMapping(m_designWidg.pbOFile, QString("OutputFile"));
-  connect(m_designWidg.pbIFile, SIGNAL(clicked()), signalMapper, SLOT(map()));
-  connect(m_designWidg.pbOFile, SIGNAL(clicked()), signalMapper, SLOT(map()));  
-  connect(signalMapper, SIGNAL(mapped(const QString &)),
-         this, SLOT(browseClicked(const QString &)));
-  connect(m_designWidg.leIFile, SIGNAL(editingFinished()), this, SLOT(validateHardMaskFile()));
-
-  // signals connected to the interface that this form is on
-  if ( parentInterface != NULL )
-  {
-
-    // controls that copy the text from other controls
-    connect(parentInterface, SIGNAL(MWDiag_updateWBV(const QString&)),
-      m_designWidg.white_file, SLOT(setFileText(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()
-{
-  // 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));
-  m_designWidg.leLowAbs->setValidator(new QDoubleValidator(this));
-  m_designWidg.leHighMed->setValidator(new QDoubleValidator(this));
-  m_designWidg.leLowMed->setValidator(new QDoubleValidator(this));
-  m_designWidg.leVariation->setValidator(new QDoubleValidator(this));
-  m_designWidg.leAcceptance->setValidator(new QDoubleValidator(this));
-  m_designWidg.leStartTime->setValidator(new QDoubleValidator(this));
-  m_designWidg.leEndTime->setValidator(new QDoubleValidator(this));
-
-  validateHardMaskFile();
-}
-
-/**
- * Returns true if the input on the form is valid, false otherwise
- */
-bool MWDiag::isInputValid() const
-{
-  bool valid(true);
-  if( m_designWidg.valInmsk->isVisible() )
-  {
-    valid &= false;
-  }
-  else
-  {
-    valid &= true;
-  }
-  
-  valid &= m_designWidg.white_file->isValid();
-  valid &= m_designWidg.white_file_2->isValid();
-
-  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)
-{
-  QLineEdit *editBox;
-  QStringList extensions;
-  bool toSave = false;
-  if ( buttonDis == "InputFile")
-  {
-    editBox = m_designWidg.leIFile;
-  }
-  if ( buttonDis == "OutputFile")
-  {
-    editBox = m_designWidg.leOFile;
-    extensions << "msk";
-    toSave = true;
-  }
-	
-  QString filepath = openFileDialog(toSave, extensions);
-  if( filepath.isEmpty() ) return;
-  QWidget *focus = QApplication::focusWidget();
-  editBox->setFocus();
-  editBox->setText(filepath);
-  if( focus )
-  {
-    focus->setFocus();
-  }
-  else
-  {
-    this->setFocus();
-  }
-}
-
-/**
- * Create a diagnostic script from the given
- */
-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 )
-    {
-      sampleRun = "r'" + m_monoFiles[0] + "'";
-    }
-    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
-  {
-    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 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 variation = m_designWidg.leVariation->text();
-  QString hard_mask_file = "r'" + m_designWidg.leIFile->text() + "'";
-  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 = 
-    "diag_total_mask = diagnostics.diagnose(";
-  
-  if( m_designWidg.ckDoBack->isChecked() )
-  {
-    // Do the background check so we need all fields
-    diagCall += 
-      "white_run=" + whiteBeam + ","
-      "sample_run=" + sampleRun + ","
-      "other_white=" + whiteBeam2 + ","
-      "remove_zero=" + removeZeroes + ","
-      "tiny=" + lowCounts + ","
-      "large=" + highCounts + ","
-      "median_lo=" + lowMedian + ","
-      "median_hi=" + highMedian + ","
-      "signif=" + significance + ","
-      "bkgd_threshold=" + acceptance + ","
-      "bkgd_range=" + bkgdRange + ","
-      "variation=" + variation + ","
-      "hard_mask=" + hard_mask_file;
-  }
-  else
-  {
-    // No background check so don't need all of the fields
-    diagCall += 
-      "white_run=" + whiteBeam + ","
-      "other_white=" + whiteBeam2 + ","
-      "tiny=" + lowCounts + ","
-      "large=" + highCounts + ","
-      "median_lo=" + lowMedian + ","
-      "median_hi=" + highMedian + ","
-      "signif=" + 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
-  {
-    diagCall += ",bleed_test=False";
-  }
-
-  // Print results argument and Closing  argument bracket
-  diagCall += ", print_results=True)\n";
-
-  QString pyCode = 
-    "import diagnostics\n"
-    "try:\n"
-    "    " + diagCall + "\n"
-    "except RuntimeError, exc:\n"
-    "    print 'Exception:'\n"
-    "    print str(exc)\n";
-  
-  return pyCode;
-}
-
-/**
- * Show the test result dialog
- */
-void MWDiag::showTestResults(const QString & testSummary) const
-{
-  if( !m_dispDialog )
-  {
-    m_dispDialog = new DiagResults(this->parentWidget());
-    connect(m_dispDialog, SIGNAL(runAsPythonScript(const QString&)), this, 
-	    SIGNAL(runAsPythonScript(const QString&)));
-  }
-  
-  m_dispDialog->updateResults(testSummary);
-  m_dispDialog->show();
-}
-
-/** close the results window, if there is one open
-*/
-void MWDiag::closeDialog()
-{
-  if (m_dispDialog)
-  {
-    m_dispDialog->close();
-  }
-}
-
-/**
- *
- */
-QString MWDiag::openFileDialog(const bool save, const QStringList &exts)
-{
-  QString filter;
-  if ( !exts.empty() )
-  {
-    filter = "Files (";
-    for ( int i = 0; i < exts.size(); i ++ )
-    {
-      filter.append("*." + exts[i] + " ");
-    }
-    filter.trimmed();
-    filter.append(")");
-  }
-  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());
-        }
-  }
-  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 
-*  @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
-  closeDialog();
-  // prepare to remove any intermediate workspaces used only during the calculations
-  std::vector<std::string> tempOutputWS;
-  QString prob1;
-
-  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
-  QString scriptResults = runPythonCode(diagCode);
-
-  // Now display them to the user if all went well
-  // but bail out if not
-  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
-*  @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
-  m_sTOFAutoVal = start;
-  m_eTOFAutoVal = end;
-  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
-*/
-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);
-}
-
-/**
- * Validate the hard mask file input
-*/
-void MWDiag::validateHardMaskFile()
-{
-  std::string filename = m_designWidg.leIFile->text().toStdString();
-  if( filename.empty() )
-  {
-    m_designWidg.valInmsk->hide();
-    return;
-  }
-
-  FileProperty *validateHardMask = new FileProperty("UnusedName", filename,FileProperty::Load);
-  QString error = QString::fromStdString(validateHardMask->isValid()); 
-  if( error.isEmpty() )
-  {
-    m_designWidg.valInmsk->hide();
-  }
-  else
-  {
-    m_designWidg.valInmsk->show();
-  }
-  m_designWidg.valInmsk->setToolTip(error);
-}
+#include "MantidQtMantidWidgets/MWDiag.h"
+#include "MantidQtMantidWidgets/DiagResults.h"
+#include "MantidQtMantidWidgets/MWRunFiles.h"
+#include "MantidQtAPI/AlgorithmInputHistory.h"
+#include "MantidQtAPI/FileDialogHandler.h"
+#include "MantidAPI/FrameworkManager.h"
+#include "MantidAPI/AnalysisDataService.h"
+#include "MantidAPI/MatrixWorkspace.h"
+#include "MantidKernel/Exception.h"
+#include "MantidAPI/FileProperty.h"
+#include "MantidGeometry/IInstrument.h"
+
+#include <QSignalMapper>
+#include <QFileInfo>
+#include <QFileDialog>
+#include <QDir>
+#include <QStringList>
+#include <QMessageBox>
+#include <QDoubleValidator>
+
+#include <vector>
+#include <string>
+
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
+using namespace MantidQt::API;
+using namespace MantidQt::MantidWidgets;
+using Mantid::Geometry::IInstrument_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)
+{
+  // allows saving and loading the values the user entered on to the form
+  m_prevSets.beginGroup(prevSettingsGr);
+  // Layout the widgets
+  m_designWidg.setupUi(this);
+
+  loadSettings();
+  setupToolTips();
+  setUpValidators();
+  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()
+{
+  // Want the defaults from the instrument if nothing is saved in the config
+  IInstrument_sptr instrument = getInstrument(m_instru->currentText());
+
+  m_designWidg.leIFile->setText(getSetting("input mask"));
+  m_designWidg.leOFile->setText(getSetting("output file"));
+  m_designWidg.leSignificance->setText(getSetting("significance", instrument, "signif"));
+  m_designWidg.leHighAbs->setText(getSetting("high abs", instrument, "large"));
+  m_designWidg.leLowAbs->setText(getSetting("low abs", instrument, "tiny"));
+  m_designWidg.leHighMed->setText(getSetting("high median", instrument, "median_hi"));
+  m_designWidg.leLowMed->setText(getSetting("low median", instrument, "median_lo"));
+  m_designWidg.leVariation->setText(getSetting("variation", instrument, "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, "bkgd_threshold"));
+  m_designWidg.bleed_maxrate->setText(getSetting("bleed_max_framerate", instrument, "bleed_max_framerate"));
+  m_designWidg.ignored_pixels->setText(getSetting("bleed_ignored_pixels", instrument, "bleed_ignored_pixels"));
+
+  // Boolean settings
+  // Background tests
+  QString value = getSetting("test background", instrument, "check_background");
+  bool checked = static_cast<bool>(value.toUInt());
+  m_designWidg.ckDoBack->setChecked(checked);
+  // Zero removal
+  value = getSetting("no zero background", instrument, "remove_zero");
+  checked = static_cast<bool>(value.toUInt());
+  m_designWidg.ckZeroCounts->setChecked(checked);
+  // Bleed test
+  value = getSetting("bleed_test", instrument, "bleed_test");
+  checked = static_cast<bool>(value.toUInt());
+  m_designWidg.bleed_group->setChecked(checked);
+}
+
+void MWDiag::setSumState(bool checked)
+{
+  m_sumMono = checked;
+}
+
+
+/**
+ * Get an instrument pointer for the name instrument
+ */
+IInstrument_sptr MWDiag::getInstrument(const QString & name)
+{
+  std::string ws_name = "__empty_" + name.toStdString();
+  
+  AnalysisDataServiceImpl& dataStore = AnalysisDataService::Instance();
+  if( !dataStore.doesExist(ws_name) )
+  {
+    QString pyInput =
+      "from DirectEnergyConversion import setup_reducer\n"
+      "setup_reducer('%1')";
+    pyInput = pyInput.arg(QString::fromStdString(ws_name));
+    runPythonCode(pyInput);
+    if( !dataStore.doesExist(ws_name) )
+    {
+      return IInstrument_sptr();
+    }
+  }
+  MatrixWorkspace_sptr inst_ws = 
+    boost::dynamic_pointer_cast<MatrixWorkspace>(dataStore.retrieve(ws_name));
+  
+  return inst_ws->getInstrument();
+}
+
+QString MWDiag::getSetting(const QString & settingName, IInstrument_sptr instrument,
+			   const QString & idfName) const
+{
+  QString value;
+  if( m_prevSets.contains(settingName) )
+  {
+    value = m_prevSets.value(settingName).toString();
+  }
+  else if( instrument && !idfName.isEmpty() )
+  {
+    std::vector<double> params = instrument->getNumberParameter(idfName.toStdString());
+    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";
+
+  return value;
+}
+
+/// 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()
+{
+  m_prevSets.setValue("input mask", m_designWidg.leIFile->text());
+  m_prevSets.setValue("output file", m_designWidg.leOFile->text());
+
+  m_prevSets.setValue("significance", m_designWidg.leSignificance->text());
+  m_prevSets.setValue("no solid", m_designWidg.ckAngles->isChecked());
+  
+  m_prevSets.setValue("high abs", m_designWidg.leHighAbs->text());
+  m_prevSets.setValue("low abs", m_designWidg.leLowAbs->text());
+  m_prevSets.setValue("high median", m_designWidg.leHighMed->text());
+  m_prevSets.setValue("low median", m_designWidg.leLowMed->text());
+  
+  m_prevSets.setValue("variation", m_designWidg.leVariation->text());
+  
+  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_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 iFileToolTip = "A file containing a list of spectra numbers which we aleady know should be masked";
+  m_designWidg.lbIFile->setToolTip(iFileToolTip);
+  m_designWidg.leIFile->setToolTip(iFileToolTip);
+  m_designWidg.pbIFile->setToolTip(iFileToolTip);
+  
+  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 labelled 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)";
+  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)";
+  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)";
+  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)";
+  m_designWidg.leLowMed->setToolTip(lowMedToolTip);
+  m_designWidg.lbLowMed->setToolTip(lowMedToolTip);
+
+  QString variationToolTip = 
+    "When comparing equilivient 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"
+    "medain 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)";
+  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)";
+  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)";
+  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");
+}
+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.pbIFile, QString("InputFile"));
+  signalMapper->setMapping(m_designWidg.pbOFile, QString("OutputFile"));
+  connect(m_designWidg.pbIFile, SIGNAL(clicked()), signalMapper, SLOT(map()));
+  connect(m_designWidg.pbOFile, SIGNAL(clicked()), signalMapper, SLOT(map()));  
+  connect(signalMapper, SIGNAL(mapped(const QString &)),
+         this, SLOT(browseClicked(const QString &)));
+  connect(m_designWidg.leIFile, SIGNAL(editingFinished()), this, SLOT(validateHardMaskFile()));
+
+  // signals connected to the interface that this form is on
+  if ( parentInterface != NULL )
+  {
+
+    // controls that copy the text from other controls
+    connect(parentInterface, SIGNAL(MWDiag_updateWBV(const QString&)),
+      m_designWidg.white_file, SLOT(setFileText(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()
+{
+  // 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));
+  m_designWidg.leLowAbs->setValidator(new QDoubleValidator(this));
+  m_designWidg.leHighMed->setValidator(new QDoubleValidator(this));
+  m_designWidg.leLowMed->setValidator(new QDoubleValidator(this));
+  m_designWidg.leVariation->setValidator(new QDoubleValidator(this));
+  m_designWidg.leAcceptance->setValidator(new QDoubleValidator(this));
+  m_designWidg.leStartTime->setValidator(new QDoubleValidator(this));
+  m_designWidg.leEndTime->setValidator(new QDoubleValidator(this));
+
+  validateHardMaskFile();
+}
+
+/**
+ * Returns true if the input on the form is valid, false otherwise
+ */
+bool MWDiag::isInputValid() const
+{
+  bool valid(true);
+  if( m_designWidg.valInmsk->isVisible() )
+  {
+    valid &= false;
+  }
+  else
+  {
+    valid &= true;
+  }
+  
+  valid &= m_designWidg.white_file->isValid();
+  valid &= m_designWidg.white_file_2->isValid();
+
+  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)
+{
+  QLineEdit *editBox;
+  QStringList extensions;
+  bool toSave = false;
+  if ( buttonDis == "InputFile")
+  {
+    editBox = m_designWidg.leIFile;
+  }
+  if ( buttonDis == "OutputFile")
+  {
+    editBox = m_designWidg.leOFile;
+    extensions << "msk";
+    toSave = true;
+  }
+	
+  QString filepath = openFileDialog(toSave, extensions);
+  if( filepath.isEmpty() ) return;
+  QWidget *focus = QApplication::focusWidget();
+  editBox->setFocus();
+  editBox->setText(filepath);
+  if( focus )
+  {
+    focus->setFocus();
+  }
+  else
+  {
+    this->setFocus();
+  }
+}
+
+/**
+ * Create a diagnostic script from the given
+ */
+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 )
+    {
+      sampleRun = "r'" + m_monoFiles[0] + "'";
+    }
+    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
+  {
+    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 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 variation = m_designWidg.leVariation->text();
+  QString hard_mask_file = "r'" + m_designWidg.leIFile->text() + "'";
+  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 = 
+    "diag_total_mask = diagnostics.diagnose(";
+  
+  if( m_designWidg.ckDoBack->isChecked() )
+  {
+    // Do the background check so we need all fields
+    diagCall += 
+      "white_run=" + whiteBeam + ","
+      "sample_run=" + sampleRun + ","
+      "other_white=" + whiteBeam2 + ","
+      "remove_zero=" + removeZeroes + ","
+      "tiny=" + lowCounts + ","
+      "large=" + highCounts + ","
+      "median_lo=" + lowMedian + ","
+      "median_hi=" + highMedian + ","
+      "signif=" + significance + ","
+      "bkgd_threshold=" + acceptance + ","
+      "bkgd_range=" + bkgdRange + ","
+      "variation=" + variation + ","
+      "hard_mask=" + hard_mask_file;
+  }
+  else
+  {
+    // No background check so don't need all of the fields
+    diagCall += 
+      "white_run=" + whiteBeam + ","
+      "other_white=" + whiteBeam2 + ","
+      "tiny=" + lowCounts + ","
+      "large=" + highCounts + ","
+      "median_lo=" + lowMedian + ","
+      "median_hi=" + highMedian + ","
+      "signif=" + 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
+  {
+    diagCall += ",bleed_test=False";
+  }
+
+  // Print results argument and Closing  argument bracket
+  diagCall += ", print_results=True)\n";
+
+  QString pyCode = 
+    "import diagnostics\n"
+    "try:\n"
+    "    " + diagCall + "\n"
+    "except RuntimeError, exc:\n"
+    "    print 'Exception:'\n"
+    "    print str(exc)\n";
+  
+  return pyCode;
+}
+
+/**
+ * Show the test result dialog
+ */
+void MWDiag::showTestResults(const QString & testSummary) const
+{
+  if( !m_dispDialog )
+  {
+    m_dispDialog = new DiagResults(this->parentWidget());
+    connect(m_dispDialog, SIGNAL(runAsPythonScript(const QString&)), this, 
+	    SIGNAL(runAsPythonScript(const QString&)));
+  }
+  
+  m_dispDialog->updateResults(testSummary);
+  m_dispDialog->show();
+}
+
+/** close the results window, if there is one open
+*/
+void MWDiag::closeDialog()
+{
+  if (m_dispDialog)
+  {
+    m_dispDialog->close();
+  }
+}
+
+/**
+ *
+ */
+QString MWDiag::openFileDialog(const bool save, const QStringList &exts)
+{
+  QString filter;
+  if ( !exts.empty() )
+  {
+    filter = "Files (";
+    for ( int i = 0; i < exts.size(); i ++ )
+    {
+      filter.append("*." + exts[i] + " ");
+    }
+    filter.trimmed();
+    filter.append(")");
+  }
+  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());
+        }
+  }
+  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 
+*  @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
+  closeDialog();
+  // prepare to remove any intermediate workspaces used only during the calculations
+  std::vector<std::string> tempOutputWS;
+  QString prob1;
+
+  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
+  QString scriptResults = runPythonCode(diagCode);
+
+  // Now display them to the user if all went well
+  // but bail out if not
+  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
+*  @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
+  m_sTOFAutoVal = start;
+  m_eTOFAutoVal = end;
+  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
+*/
+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);
+}
+
+/**
+ * Validate the hard mask file input
+*/
+void MWDiag::validateHardMaskFile()
+{
+  std::string filename = m_designWidg.leIFile->text().toStdString();
+  if( filename.empty() )
+  {
+    m_designWidg.valInmsk->hide();
+    return;
+  }
+
+  FileProperty *validateHardMask = new FileProperty("UnusedName", filename,FileProperty::Load);
+  QString error = QString::fromStdString(validateHardMask->isValid()); 
+  if( error.isEmpty() )
+  {
+    m_designWidg.valInmsk->hide();
+  }
+  else
+  {
+    m_designWidg.valInmsk->show();
+  }
+  m_designWidg.valInmsk->setToolTip(error);
+}
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/MWRunFiles.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/MWRunFiles.cpp
index 2544dbe78cd38548fca9bbe8fa866aff9a905ae8..670a9dcc43ac20dae4693b3ea16d72082b8d2e4a 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/MWRunFiles.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/MWRunFiles.cpp
@@ -8,8 +8,8 @@
 
 #include <QStringList>
 #include <QFileDialog>
-#include <QFileInfo>
-#include <QHash>
+#include <QFileInfo>
+#include <QHash>
 #include "Poco/File.h"
 
 using namespace Mantid::Kernel;
@@ -401,15 +401,15 @@ void MWRunFiles::findFiles()
       foreach(file, filestext)
       {
         std::string result = fileSearcher.getFullPath(file.toStdString());
-        Poco::File test(result);
-        if ( ( ! result.empty() ) && test.exists() )
-        {
-          filenames.push_back(file.toStdString());
-        }
-        else
-        {
-          throw std::invalid_argument("File \"" + file.toStdString() + "\" not found");
-        }
+        Poco::File test(result);
+        if ( ( ! result.empty() ) && test.exists() )
+        {
+          filenames.push_back(file.toStdString());
+        }
+        else
+        {
+          throw std::invalid_argument("File \"" + file.toStdString() + "\" not found");
+        }
       }
     }
   }
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp
index 5f1a842473ce7365614455884a51923d31f1a1ef..ca7fd3fdbefb60d2e060b101fb00a684b199d1ab 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/RangeSelector.cpp
@@ -1,378 +1,378 @@
-#include "MantidQtMantidWidgets/RangeSelector.h"
-
-#include <qwt_plot_picker.h>
-
-#include <QEvent>
-#include <QMouseEvent>
-
-using namespace MantidQt::MantidWidgets;
-
-RangeSelector::RangeSelector(QwtPlot* plot, SelectType type, bool visible, bool infoOnly) : QwtPlotPicker(plot->canvas()), m_canvas(plot->canvas()), m_plot(plot), m_type(type), m_visible(visible), m_infoOnly(infoOnly)
-{
-  m_canvas->installEventFilter(this);
-
-  m_canvas->setCursor(Qt::PointingHandCursor); ///< @todo Make this an option at some point
-
-  m_mrkMin = new QwtPlotMarker();
-  m_mrkMax = new QwtPlotMarker();
-
-  QwtPlotMarker::LineStyle lineStyle;
-  
-  switch ( m_type )
-  {
-  case XMINMAX:
-  case XSINGLE:
-    lineStyle = QwtPlotMarker::VLine;
-    m_movCursor = Qt::SizeHorCursor;
-    break;
-  case YMINMAX:
-  case YSINGLE:
-    lineStyle = QwtPlotMarker::HLine;
-    m_movCursor = Qt::SizeVerCursor;
-    break;
-  default:
-    lineStyle = QwtPlotMarker::Cross;
-    break;
-  }
-
-  switch ( m_type )
-  {
-  case XMINMAX:
-  case YMINMAX:
-    m_mrkMax->setLineStyle(lineStyle);
-    m_mrkMax->attach(m_plot);
-    m_mrkMax->setYValue(1.0);
-  case XSINGLE:
-  case YSINGLE:
-    m_mrkMin->setLineStyle(lineStyle);
-    m_mrkMin->attach(m_plot);
-    m_mrkMin->setYValue(0.0);
-    break;
-  }
-
-  connect(this, SIGNAL(minValueChanged(double)), this, SLOT(minChanged(double)));
-  connect(this, SIGNAL(maxValueChanged(double)), this, SLOT(maxChanged(double)));
-
-  m_minChanging = false;
-  m_maxChanging = false;
-
-  setMin(100); // known starting values
-  setMax(200);
-
-  /// Setup pen with default values
-  m_pen = new QPen();
-  m_pen->setColor(Qt::blue);
-  m_pen->setStyle(Qt::DashDotLine);
-
-  // Apply pen to marker objects
-  m_mrkMin->setLinePen(*m_pen);
-  m_mrkMax->setLinePen(*m_pen);
-}
-
-bool RangeSelector::eventFilter(QObject* obj, QEvent* evn)
-{
-  // Do not handle the event if the widget is set to be invisible
-  if ( !m_visible || m_infoOnly )
-  {
-    return false;
-  }
-
-  switch ( evn->type() )
-  {
-  case QEvent::MouseButtonPress: // User has started moving something (perhaps)
-    {
-    QPoint p = ((QMouseEvent*)evn)->pos();
-    double x, dx;
-    switch ( m_type )
-    {
-    case XMINMAX:
-    case XSINGLE:
-      x = m_plot->invTransform(QwtPlot::xBottom, p.x());
-      dx = m_plot->invTransform(QwtPlot::xBottom, p.x()+3);
-      break;
-    case YMINMAX:
-    case YSINGLE:
-      x = m_plot->invTransform(QwtPlot::yLeft, p.y());
-      dx = m_plot->invTransform(QwtPlot::yLeft, p.y()+3);
-      break;
-    }
-    if ( inRange(x) )
-    {
-      if ( changingMin(x, dx) )
-      {
-        m_minChanging = true;
-        m_canvas->setCursor(m_movCursor);
-        setMin(x);
-        m_plot->replot();
-        return true;
-      }
-      else if ( changingMax(x, dx) )
-      {
-        m_maxChanging = true;
-        m_canvas->setCursor(m_movCursor);
-        setMax(x);
-        m_plot->replot();
-        return true;
-      }
-      else
-      {
-        return false;
-      }
-    }
-    else
-    {
-      return false;
-    }
-    break;
-    }
-  case QEvent::MouseMove: // User is in the process of moving something (perhaps)
-    {
-    if ( m_minChanging || m_maxChanging )
-    {
-    QPoint p = ((QMouseEvent*)evn)->pos();
-    double x;
-    switch ( m_type )
-    {
-    case XMINMAX:
-    case XSINGLE:
-      x = m_plot->invTransform(QwtPlot::xBottom, p.x());
-      break;
-    case YMINMAX:
-    case YSINGLE:
-      x = m_plot->invTransform(QwtPlot::yLeft, p.y());
-      break;
-    }
-    if ( inRange(x) )
-    {
-      if ( m_minChanging )
-      {
-        setMin(x);
-        if ( x > m_max )
-          setMax(x);
-      }
-      else
-      {
-        setMax(x);
-        if ( x < m_min )
-          setMin(x);
-      }
-    }
-    else
-    {
-      m_canvas->setCursor(Qt::PointingHandCursor);
-      m_minChanging = false;
-      m_maxChanging = false;
-    }
-    m_plot->replot();
-    return true;
-    }
-    else
-    {
-    return false;
-    }
-    break;
-    }
-  case QEvent::MouseButtonRelease: // User has finished moving something (perhaps)
-    {
-    if ( m_minChanging || m_maxChanging )
-    {
-    m_canvas->setCursor(Qt::PointingHandCursor);
-    QPoint p = ((QMouseEvent*)evn)->pos();
-    double x;
-    switch ( m_type )
-    {
-    case XMINMAX:
-    case XSINGLE:
-      x = m_plot->invTransform(QwtPlot::xBottom, p.x());
-      break;
-    case YMINMAX:
-    case YSINGLE:
-      x = m_plot->invTransform(QwtPlot::yLeft, p.y());
-      break;
-    }
-    if ( inRange(x) )
-    {
-    if ( m_minChanging )
-      setMin(x);
-    else
-      setMax(x);
-    }
-    m_plot->replot();
-    m_minChanging = false;
-    m_maxChanging = false;
-    return true;
-    }
-    else
-    {
-    return false;
-    }
-    break;
-    }
-  default:
-    return false;
-  }
-}
-
-std::pair<double, double> RangeSelector::getRange()
-{
-  std::pair<double,double> range(m_lower,m_higher);
-  return range;
-}
-
-void RangeSelector::setRange(double min, double max)
-{
-  m_lower = min;
-  m_higher = max;
-  verify();
-  emit rangeChanged(min, max);
-}
-
-void RangeSelector::setRange(std::pair<double,double> range)
-{
-  double min = range.first;
-  double max = range.second;
-  this->setRange(min, max);
-}
-
-void RangeSelector::minChanged(double val)
-{
-  switch ( m_type )
-  {
-  case XMINMAX:
-  case XSINGLE:
-    m_mrkMin->setValue(val, 1.0);
-    break;
-  case YMINMAX:
-  case YSINGLE:
-    m_mrkMin->setValue(1.0, val);
-    break;
-  }
-  m_plot->replot();
-}
-
-void RangeSelector::maxChanged(double val)
-{
-  switch ( m_type )
-  {
-  case XMINMAX:
-  case XSINGLE:
-    m_mrkMax->setValue(val, 1.0);
-    break;
-  case YMINMAX:
-  case YSINGLE:
-    m_mrkMax->setValue(1.0, val);
-    break;
-  }
-  m_plot->replot();
-}
-
-void RangeSelector::setMinimum(double val)
-{
-  setMin(val);
-}
-
-void RangeSelector::setMaximum(double val)
-{
-  setMax(val);
-}
-
-void RangeSelector::reapply()
-{
-  m_mrkMin->attach(m_plot);
-  m_mrkMax->attach(m_plot);
-}
-
-void RangeSelector::setColour(QColor colour)
-{
-  m_pen->setColor(colour);
-  switch ( m_type )
-  {
-  case XMINMAX:
-  case YMINMAX:
-    m_mrkMax->setLinePen(*m_pen);
-  case XSINGLE:
-  case YSINGLE:
-    m_mrkMin->setLinePen(*m_pen);
-    break;
-  }
-}
-
-void RangeSelector::setInfoOnly(bool state)
-{
-  m_infoOnly = state;
-}
-
-void RangeSelector::setVisible(bool state)
-{
-  if ( state )
-  {
-    m_mrkMin->show();
-    m_mrkMax->show();
-  }
-  else
-  {
-    m_mrkMin->hide();
-    m_mrkMax->hide();
-  }
-  m_plot->replot();
-  m_visible = state;
-}
-
-void RangeSelector::setMin(double val)
-{
-  if ( val != m_min )
-  {
-    m_min = val;
-    emit minValueChanged(val);
-  }
-}
-
-void RangeSelector::setMax(double val)
-{
-  if ( val != m_max )
-  {
-    m_max = val;
-    emit maxValueChanged(val);
-  }
-}
-
-bool RangeSelector::changingMin(double x, double dx)
-{
-  return ( fabs(x - m_min) <= fabs(dx-x) );
-}
-
-bool RangeSelector::changingMax(double x, double dx)
-{
-  return ( fabs(x - m_max) <= fabs(dx-x) );
-}
-
-void RangeSelector::verify()
-{
-  if ( m_min < m_lower || m_min > m_higher )
-  {
-    setMin(m_lower);
-  }
-  if ( m_max < m_lower || m_max > m_higher )
-  {
-    setMax(m_higher);
-  }
-
-  if ( m_min > m_max )
-  {
-    double tmp = m_min;
-    setMin(m_max);
-    setMax(tmp);
-  }
-}
-
-bool RangeSelector::inRange(double x)
-{
-  if ( x < m_lower || x > m_higher )
-  {
-    return false;
-  }
-  else
-  {
-    return true;
-  }
-}
+#include "MantidQtMantidWidgets/RangeSelector.h"
+
+#include <qwt_plot_picker.h>
+
+#include <QEvent>
+#include <QMouseEvent>
+
+using namespace MantidQt::MantidWidgets;
+
+RangeSelector::RangeSelector(QwtPlot* plot, SelectType type, bool visible, bool infoOnly) : QwtPlotPicker(plot->canvas()), m_canvas(plot->canvas()), m_plot(plot), m_type(type), m_visible(visible), m_infoOnly(infoOnly)
+{
+  m_canvas->installEventFilter(this);
+
+  m_canvas->setCursor(Qt::PointingHandCursor); ///< @todo Make this an option at some point
+
+  m_mrkMin = new QwtPlotMarker();
+  m_mrkMax = new QwtPlotMarker();
+
+  QwtPlotMarker::LineStyle lineStyle;
+  
+  switch ( m_type )
+  {
+  case XMINMAX:
+  case XSINGLE:
+    lineStyle = QwtPlotMarker::VLine;
+    m_movCursor = Qt::SizeHorCursor;
+    break;
+  case YMINMAX:
+  case YSINGLE:
+    lineStyle = QwtPlotMarker::HLine;
+    m_movCursor = Qt::SizeVerCursor;
+    break;
+  default:
+    lineStyle = QwtPlotMarker::Cross;
+    break;
+  }
+
+  switch ( m_type )
+  {
+  case XMINMAX:
+  case YMINMAX:
+    m_mrkMax->setLineStyle(lineStyle);
+    m_mrkMax->attach(m_plot);
+    m_mrkMax->setYValue(1.0);
+  case XSINGLE:
+  case YSINGLE:
+    m_mrkMin->setLineStyle(lineStyle);
+    m_mrkMin->attach(m_plot);
+    m_mrkMin->setYValue(0.0);
+    break;
+  }
+
+  connect(this, SIGNAL(minValueChanged(double)), this, SLOT(minChanged(double)));
+  connect(this, SIGNAL(maxValueChanged(double)), this, SLOT(maxChanged(double)));
+
+  m_minChanging = false;
+  m_maxChanging = false;
+
+  setMin(100); // known starting values
+  setMax(200);
+
+  /// Setup pen with default values
+  m_pen = new QPen();
+  m_pen->setColor(Qt::blue);
+  m_pen->setStyle(Qt::DashDotLine);
+
+  // Apply pen to marker objects
+  m_mrkMin->setLinePen(*m_pen);
+  m_mrkMax->setLinePen(*m_pen);
+}
+
+bool RangeSelector::eventFilter(QObject* obj, QEvent* evn)
+{
+  // Do not handle the event if the widget is set to be invisible
+  if ( !m_visible || m_infoOnly )
+  {
+    return false;
+  }
+
+  switch ( evn->type() )
+  {
+  case QEvent::MouseButtonPress: // User has started moving something (perhaps)
+    {
+    QPoint p = ((QMouseEvent*)evn)->pos();
+    double x, dx;
+    switch ( m_type )
+    {
+    case XMINMAX:
+    case XSINGLE:
+      x = m_plot->invTransform(QwtPlot::xBottom, p.x());
+      dx = m_plot->invTransform(QwtPlot::xBottom, p.x()+3);
+      break;
+    case YMINMAX:
+    case YSINGLE:
+      x = m_plot->invTransform(QwtPlot::yLeft, p.y());
+      dx = m_plot->invTransform(QwtPlot::yLeft, p.y()+3);
+      break;
+    }
+    if ( inRange(x) )
+    {
+      if ( changingMin(x, dx) )
+      {
+        m_minChanging = true;
+        m_canvas->setCursor(m_movCursor);
+        setMin(x);
+        m_plot->replot();
+        return true;
+      }
+      else if ( changingMax(x, dx) )
+      {
+        m_maxChanging = true;
+        m_canvas->setCursor(m_movCursor);
+        setMax(x);
+        m_plot->replot();
+        return true;
+      }
+      else
+      {
+        return false;
+      }
+    }
+    else
+    {
+      return false;
+    }
+    break;
+    }
+  case QEvent::MouseMove: // User is in the process of moving something (perhaps)
+    {
+    if ( m_minChanging || m_maxChanging )
+    {
+    QPoint p = ((QMouseEvent*)evn)->pos();
+    double x;
+    switch ( m_type )
+    {
+    case XMINMAX:
+    case XSINGLE:
+      x = m_plot->invTransform(QwtPlot::xBottom, p.x());
+      break;
+    case YMINMAX:
+    case YSINGLE:
+      x = m_plot->invTransform(QwtPlot::yLeft, p.y());
+      break;
+    }
+    if ( inRange(x) )
+    {
+      if ( m_minChanging )
+      {
+        setMin(x);
+        if ( x > m_max )
+          setMax(x);
+      }
+      else
+      {
+        setMax(x);
+        if ( x < m_min )
+          setMin(x);
+      }
+    }
+    else
+    {
+      m_canvas->setCursor(Qt::PointingHandCursor);
+      m_minChanging = false;
+      m_maxChanging = false;
+    }
+    m_plot->replot();
+    return true;
+    }
+    else
+    {
+    return false;
+    }
+    break;
+    }
+  case QEvent::MouseButtonRelease: // User has finished moving something (perhaps)
+    {
+    if ( m_minChanging || m_maxChanging )
+    {
+    m_canvas->setCursor(Qt::PointingHandCursor);
+    QPoint p = ((QMouseEvent*)evn)->pos();
+    double x;
+    switch ( m_type )
+    {
+    case XMINMAX:
+    case XSINGLE:
+      x = m_plot->invTransform(QwtPlot::xBottom, p.x());
+      break;
+    case YMINMAX:
+    case YSINGLE:
+      x = m_plot->invTransform(QwtPlot::yLeft, p.y());
+      break;
+    }
+    if ( inRange(x) )
+    {
+    if ( m_minChanging )
+      setMin(x);
+    else
+      setMax(x);
+    }
+    m_plot->replot();
+    m_minChanging = false;
+    m_maxChanging = false;
+    return true;
+    }
+    else
+    {
+    return false;
+    }
+    break;
+    }
+  default:
+    return false;
+  }
+}
+
+std::pair<double, double> RangeSelector::getRange()
+{
+  std::pair<double,double> range(m_lower,m_higher);
+  return range;
+}
+
+void RangeSelector::setRange(double min, double max)
+{
+  m_lower = min;
+  m_higher = max;
+  verify();
+  emit rangeChanged(min, max);
+}
+
+void RangeSelector::setRange(std::pair<double,double> range)
+{
+  double min = range.first;
+  double max = range.second;
+  this->setRange(min, max);
+}
+
+void RangeSelector::minChanged(double val)
+{
+  switch ( m_type )
+  {
+  case XMINMAX:
+  case XSINGLE:
+    m_mrkMin->setValue(val, 1.0);
+    break;
+  case YMINMAX:
+  case YSINGLE:
+    m_mrkMin->setValue(1.0, val);
+    break;
+  }
+  m_plot->replot();
+}
+
+void RangeSelector::maxChanged(double val)
+{
+  switch ( m_type )
+  {
+  case XMINMAX:
+  case XSINGLE:
+    m_mrkMax->setValue(val, 1.0);
+    break;
+  case YMINMAX:
+  case YSINGLE:
+    m_mrkMax->setValue(1.0, val);
+    break;
+  }
+  m_plot->replot();
+}
+
+void RangeSelector::setMinimum(double val)
+{
+  setMin(val);
+}
+
+void RangeSelector::setMaximum(double val)
+{
+  setMax(val);
+}
+
+void RangeSelector::reapply()
+{
+  m_mrkMin->attach(m_plot);
+  m_mrkMax->attach(m_plot);
+}
+
+void RangeSelector::setColour(QColor colour)
+{
+  m_pen->setColor(colour);
+  switch ( m_type )
+  {
+  case XMINMAX:
+  case YMINMAX:
+    m_mrkMax->setLinePen(*m_pen);
+  case XSINGLE:
+  case YSINGLE:
+    m_mrkMin->setLinePen(*m_pen);
+    break;
+  }
+}
+
+void RangeSelector::setInfoOnly(bool state)
+{
+  m_infoOnly = state;
+}
+
+void RangeSelector::setVisible(bool state)
+{
+  if ( state )
+  {
+    m_mrkMin->show();
+    m_mrkMax->show();
+  }
+  else
+  {
+    m_mrkMin->hide();
+    m_mrkMax->hide();
+  }
+  m_plot->replot();
+  m_visible = state;
+}
+
+void RangeSelector::setMin(double val)
+{
+  if ( val != m_min )
+  {
+    m_min = val;
+    emit minValueChanged(val);
+  }
+}
+
+void RangeSelector::setMax(double val)
+{
+  if ( val != m_max )
+  {
+    m_max = val;
+    emit maxValueChanged(val);
+  }
+}
+
+bool RangeSelector::changingMin(double x, double dx)
+{
+  return ( fabs(x - m_min) <= fabs(dx-x) );
+}
+
+bool RangeSelector::changingMax(double x, double dx)
+{
+  return ( fabs(x - m_max) <= fabs(dx-x) );
+}
+
+void RangeSelector::verify()
+{
+  if ( m_min < m_lower || m_min > m_higher )
+  {
+    setMin(m_lower);
+  }
+  if ( m_max < m_lower || m_max > m_higher )
+  {
+    setMax(m_higher);
+  }
+
+  if ( m_min > m_max )
+  {
+    double tmp = m_min;
+    setMin(m_max);
+    setMax(tmp);
+  }
+}
+
+bool RangeSelector::inRange(double x)
+{
+  if ( x < m_lower || x > m_higher )
+  {
+    return false;
+  }
+  else
+  {
+    return true;
+  }
+}
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/WorkspaceSelector.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/WorkspaceSelector.cpp
index 70912ee410379f5975499900f9d4330e4216f644..2519a55598c152d8c75f13a2452f7e80338a80e4 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/WorkspaceSelector.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/WorkspaceSelector.cpp
@@ -1,196 +1,196 @@
-//------------------------------------------------------
-// Includes
-//------------------------------------------------------
-#include "MantidQtMantidWidgets/WorkspaceSelector.h"
-
-#include <Poco/Notification.h>
-#include <Poco/NotificationCenter.h>
-#include <Poco/AutoPtr.h>
-#include <Poco/NObserver.h>
-
-#include "MantidAPI/AlgorithmManager.h"
-
-using namespace MantidQt::MantidWidgets;
-
-/**
-* Default constructor
-* @param parent :: A widget to act as this widget's parent (default = NULL)
-* @param init :: If true then the widget will make calls to the framework (default = true)
-*/
-WorkspaceSelector::WorkspaceSelector(QWidget *parent, bool init) : QComboBox(parent),
-  m_addObserver(*this, &WorkspaceSelector::handleAddEvent), 
-  m_remObserver(*this, &WorkspaceSelector::handleRemEvent),
-  m_init(init), m_workspaceTypes(), m_showHidden(true), m_suffix(), m_algName(), m_algPropName(), m_algorithm()
-{
-  setEditable(false); 
-  if( init )
-  {
-    Mantid::API::AnalysisDataServiceImpl& ads = Mantid::API::AnalysisDataService::Instance();
-    ads.notificationCenter.addObserver(m_addObserver);
-    ads.notificationCenter.addObserver(m_remObserver);
-  }
-}
-
-/**
-* Destructor for WorkspaceSelector
-* De-subscribes this object from the Poco NotificationCentre
-*/
-WorkspaceSelector::~WorkspaceSelector()
-{
-  if ( m_init )
-  {
-    Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_addObserver);
-    Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_remObserver);
-  }
-}
-
-QStringList WorkspaceSelector::getWorkspaceTypes() const
-{
-  return m_workspaceTypes;
-}
-
-void WorkspaceSelector::setWorkspaceTypes(const QStringList & types)
-{
-  if ( types != m_workspaceTypes )
-  {
-    m_workspaceTypes = types;
-    if ( m_init )
-    {
-      refresh();
-    }
-  }
-}
-
-bool WorkspaceSelector::showHiddenWorkspaces() const
-{
-  return m_showHidden;
-}
-
-void WorkspaceSelector::showHiddenWorkspaces(const bool & show)
-{
-  if ( show != m_showHidden )
-  {
-    m_showHidden = show;
-    if ( m_init )
-    {
-      refresh();
-    }
-  }
-}
-
-QString WorkspaceSelector::getSuffix() const
-{
-  return m_suffix;
-}
-
-void WorkspaceSelector::setSuffix(const QString & suffix)
-{
-  if ( suffix != m_suffix )
-  {
-    m_suffix = suffix;
-    if ( m_init )
-    {
-      refresh();
-    }
-  }
-}
-
-QString WorkspaceSelector::getValidatingAlgorithm() const
-{
-  return m_algName;
-}
-
-void WorkspaceSelector::setValidatingAlgorithm(const QString & algName)
-{
-  if ( algName == m_algName )
-  {
-    return;
-  }
-  m_algName = algName;
-  if ( m_init )
-  {
-    m_algorithm = Mantid::API::AlgorithmManager::Instance().createUnmanaged(algName.toStdString());
-    m_algorithm->initialize();
-    std::vector<Mantid::Kernel::Property*> props = m_algorithm->getProperties();
-    for ( std::vector<Mantid::Kernel::Property*>::iterator it = props.begin(); it != props.end(); ++it )
-    {
-      if ( (*it)->direction() == Mantid::Kernel::Direction::Input )
-      {
-        // try to cast property to WorkspaceProperty
-        Mantid::API::WorkspaceProperty<>* wsProp = dynamic_cast<Mantid::API::WorkspaceProperty<>*>(*it);
-        if ( wsProp != NULL )
-        {
-          m_algPropName = QString::fromStdString((*it)->name());
-          break;
-        }
-      }
-    }
-    refresh();
-  }
-}
-
-void WorkspaceSelector::handleAddEvent(Mantid::API::WorkspaceAddNotification_ptr pNf) 
-{
-  QString name = QString::fromStdString( pNf->object_name() );
-  if ( checkEligibility(name, pNf->object() ) )
-  {
-    addItem(name);
-  }
-}
-
-void WorkspaceSelector::handleRemEvent(Mantid::API::WorkspaceDeleteNotification_ptr pNf)
-{
-  QString name = QString::fromStdString(pNf->object_name());
-  int index = findText(name);
-  if ( index != -1 )
-  {
-    removeItem(index);
-  }
-}
-
-bool WorkspaceSelector::checkEligibility(const QString & name, Mantid::API::Workspace_sptr object) const
-{
-  if ( m_algorithm && ! m_algPropName.isEmpty() )
-  {
-    try
-    {
-      m_algorithm->setPropertyValue(m_algPropName.toStdString(), name.toStdString());
-    }
-    catch ( std::invalid_argument & )
-    {
-      return false;
-    }
-  }
-  else if ( ( ! m_workspaceTypes.empty() ) && m_workspaceTypes.indexOf(QString::fromStdString(object->id())) == -1 )
-  {
-    return false;
-  }
-  else if ( ( ! m_showHidden ) && name.startsWith("__") )
-  {
-    return false;
-  }
-  else if ( ( ! m_suffix.isEmpty() ) && ( ! name.endsWith(m_suffix) ) )
-  {
-    return false;
-  }
-
-  return true;
-}
-
-void WorkspaceSelector::refresh()
-{
-  clear();
-  Mantid::API::AnalysisDataServiceImpl& ads = Mantid::API::AnalysisDataService::Instance();
-  std::set<std::string> items = ads.getObjectNames();
-  if ( ! items.empty() )
-  {
-    for ( std::set<std::string>::iterator it = items.begin(); it != items.end(); ++it )
-    {      
-      QString name = QString::fromStdString(*it);
-      if ( checkEligibility( name, ads.retrieve(*it) ) )
-      {
-        addItem(name);
-      }
-    }
-  }
+//------------------------------------------------------
+// Includes
+//------------------------------------------------------
+#include "MantidQtMantidWidgets/WorkspaceSelector.h"
+
+#include <Poco/Notification.h>
+#include <Poco/NotificationCenter.h>
+#include <Poco/AutoPtr.h>
+#include <Poco/NObserver.h>
+
+#include "MantidAPI/AlgorithmManager.h"
+
+using namespace MantidQt::MantidWidgets;
+
+/**
+* Default constructor
+* @param parent :: A widget to act as this widget's parent (default = NULL)
+* @param init :: If true then the widget will make calls to the framework (default = true)
+*/
+WorkspaceSelector::WorkspaceSelector(QWidget *parent, bool init) : QComboBox(parent),
+  m_addObserver(*this, &WorkspaceSelector::handleAddEvent), 
+  m_remObserver(*this, &WorkspaceSelector::handleRemEvent),
+  m_init(init), m_workspaceTypes(), m_showHidden(true), m_suffix(), m_algName(), m_algPropName(), m_algorithm()
+{
+  setEditable(false); 
+  if( init )
+  {
+    Mantid::API::AnalysisDataServiceImpl& ads = Mantid::API::AnalysisDataService::Instance();
+    ads.notificationCenter.addObserver(m_addObserver);
+    ads.notificationCenter.addObserver(m_remObserver);
+  }
+}
+
+/**
+* Destructor for WorkspaceSelector
+* De-subscribes this object from the Poco NotificationCentre
+*/
+WorkspaceSelector::~WorkspaceSelector()
+{
+  if ( m_init )
+  {
+    Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_addObserver);
+    Mantid::API::AnalysisDataService::Instance().notificationCenter.removeObserver(m_remObserver);
+  }
+}
+
+QStringList WorkspaceSelector::getWorkspaceTypes() const
+{
+  return m_workspaceTypes;
+}
+
+void WorkspaceSelector::setWorkspaceTypes(const QStringList & types)
+{
+  if ( types != m_workspaceTypes )
+  {
+    m_workspaceTypes = types;
+    if ( m_init )
+    {
+      refresh();
+    }
+  }
+}
+
+bool WorkspaceSelector::showHiddenWorkspaces() const
+{
+  return m_showHidden;
+}
+
+void WorkspaceSelector::showHiddenWorkspaces(const bool & show)
+{
+  if ( show != m_showHidden )
+  {
+    m_showHidden = show;
+    if ( m_init )
+    {
+      refresh();
+    }
+  }
+}
+
+QString WorkspaceSelector::getSuffix() const
+{
+  return m_suffix;
+}
+
+void WorkspaceSelector::setSuffix(const QString & suffix)
+{
+  if ( suffix != m_suffix )
+  {
+    m_suffix = suffix;
+    if ( m_init )
+    {
+      refresh();
+    }
+  }
+}
+
+QString WorkspaceSelector::getValidatingAlgorithm() const
+{
+  return m_algName;
+}
+
+void WorkspaceSelector::setValidatingAlgorithm(const QString & algName)
+{
+  if ( algName == m_algName )
+  {
+    return;
+  }
+  m_algName = algName;
+  if ( m_init )
+  {
+    m_algorithm = Mantid::API::AlgorithmManager::Instance().createUnmanaged(algName.toStdString());
+    m_algorithm->initialize();
+    std::vector<Mantid::Kernel::Property*> props = m_algorithm->getProperties();
+    for ( std::vector<Mantid::Kernel::Property*>::iterator it = props.begin(); it != props.end(); ++it )
+    {
+      if ( (*it)->direction() == Mantid::Kernel::Direction::Input )
+      {
+        // try to cast property to WorkspaceProperty
+        Mantid::API::WorkspaceProperty<>* wsProp = dynamic_cast<Mantid::API::WorkspaceProperty<>*>(*it);
+        if ( wsProp != NULL )
+        {
+          m_algPropName = QString::fromStdString((*it)->name());
+          break;
+        }
+      }
+    }
+    refresh();
+  }
+}
+
+void WorkspaceSelector::handleAddEvent(Mantid::API::WorkspaceAddNotification_ptr pNf) 
+{
+  QString name = QString::fromStdString( pNf->object_name() );
+  if ( checkEligibility(name, pNf->object() ) )
+  {
+    addItem(name);
+  }
+}
+
+void WorkspaceSelector::handleRemEvent(Mantid::API::WorkspaceDeleteNotification_ptr pNf)
+{
+  QString name = QString::fromStdString(pNf->object_name());
+  int index = findText(name);
+  if ( index != -1 )
+  {
+    removeItem(index);
+  }
+}
+
+bool WorkspaceSelector::checkEligibility(const QString & name, Mantid::API::Workspace_sptr object) const
+{
+  if ( m_algorithm && ! m_algPropName.isEmpty() )
+  {
+    try
+    {
+      m_algorithm->setPropertyValue(m_algPropName.toStdString(), name.toStdString());
+    }
+    catch ( std::invalid_argument & )
+    {
+      return false;
+    }
+  }
+  else if ( ( ! m_workspaceTypes.empty() ) && m_workspaceTypes.indexOf(QString::fromStdString(object->id())) == -1 )
+  {
+    return false;
+  }
+  else if ( ( ! m_showHidden ) && name.startsWith("__") )
+  {
+    return false;
+  }
+  else if ( ( ! m_suffix.isEmpty() ) && ( ! name.endsWith(m_suffix) ) )
+  {
+    return false;
+  }
+
+  return true;
+}
+
+void WorkspaceSelector::refresh()
+{
+  clear();
+  Mantid::API::AnalysisDataServiceImpl& ads = Mantid::API::AnalysisDataService::Instance();
+  std::set<std::string> items = ads.getObjectNames();
+  if ( ! items.empty() )
+  {
+    for ( std::set<std::string>::iterator it = items.begin(); it != items.end(); ++it )
+    {      
+      QString name = QString::fromStdString(*it);
+      if ( checkEligibility( name, ads.retrieve(*it) ) )
+      {
+        addItem(name);
+      }
+    }
+  }
 }
\ No newline at end of file
diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/pythonCalc.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/pythonCalc.cpp
index 736796b0231a50a431d7a8679e46ea0dbb7825c9..79702eee7358f36991a201a6bf6860bcb1f38104 100644
--- a/Code/Mantid/MantidQt/MantidWidgets/src/pythonCalc.cpp
+++ b/Code/Mantid/MantidQt/MantidWidgets/src/pythonCalc.cpp
@@ -1,160 +1,160 @@
-#include "MantidQtMantidWidgets/pythonCalc.h"
-#include "MantidKernel/Exception.h"
-#include "MantidAPI/IAlgorithm.h"
-#include "MantidKernel/PropertyWithValue.h"
-#include "MantidAPI/AlgorithmManager.h"
-#include <QMessageBox>
-#include <QHash>
-#include <QTextStream>
-#include <QFile>
-#include <stdexcept>
-#include <cmath>
-
-using namespace Mantid::Kernel;
-using namespace Mantid::API;
-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;
-}
-/** Protected constructor only desendents of this class can be construected
-*  @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 pythonGenerat :: 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
-	    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";
-  }
-  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)
-{
-  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());
-    }
-    QTextStream stream(&py_script);
-    QString line;
-    while( !stream.atEnd() )
-    {
-	    line = stream.readLine();
-  	  m_pyScript.append(line + "\n");
-    }
-    py_script.close();
-  }
-  catch( ... )
-  {
-    py_script.close();
-    throw;
-  }
-}
-/** 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)
-{
-  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());
-    }
-    QTextStream stream(&py_script);
-    QString line;
-    while( !stream.atEnd() )
-    {
-	    line = stream.readLine();
-  	  m_pyScript.append(line + "\n");
-    }
-    py_script.close();
-  }
-  catch( ... )
-  {
-    py_script.close();
-    throw;
-  }
-}
-/** Replaces the marker word in the m_pyScript with the text in the QLineEdit
-*  checking if the value will fail validation, storing any error in m_fails
-* @param pythonMark :: the word to search for and replace
-* @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)
-{
-  QString setting = userVal->text();
-  std::string error = replaceErrsFind(pythonMark, setting, check);
-  if ( ! error.empty() )
-  {
-    m_fails[userVal] = error;
-  }
-}
-/** Replaces the marker word in the m_pyScript with the passed string checking
-*  if the value will fail validation (errors are stored m_fails)
-* @param pythonMark :: the word to search for and replace
-* @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+"'");
-  return check->setValue(setting.toStdString());
-}
-/** Appends the text in the QLineEdit to m_pyScript and stores any error
-*   in m_fails
-* @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()+"'");
-  std::string error = check->setValue(userVal->text().toStdString());
-  if ( ! error.empty() )
-  {
-    m_fails[userVal] = error;
-  }
-}
-/** Sends interpretes the Python code through runPythonCode() and returns
-*  a results summary
-*  @return any print statements executed in the Python script
-*/
-QString pythonCalc::run()
-{
- QString tests = runPythonCode(m_pyScript, false);
- //std::cerr << "results\n";
- //std::cerr << tests.toStdString() << "\n";
- return tests;
-}
+#include "MantidQtMantidWidgets/pythonCalc.h"
+#include "MantidKernel/Exception.h"
+#include "MantidAPI/IAlgorithm.h"
+#include "MantidKernel/PropertyWithValue.h"
+#include "MantidAPI/AlgorithmManager.h"
+#include <QMessageBox>
+#include <QHash>
+#include <QTextStream>
+#include <QFile>
+#include <stdexcept>
+#include <cmath>
+
+using namespace Mantid::Kernel;
+using namespace Mantid::API;
+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;
+}
+/** Protected constructor only desendents of this class can be construected
+*  @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 pythonGenerat :: 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
+	    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";
+  }
+  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)
+{
+  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());
+    }
+    QTextStream stream(&py_script);
+    QString line;
+    while( !stream.atEnd() )
+    {
+	    line = stream.readLine();
+  	  m_pyScript.append(line + "\n");
+    }
+    py_script.close();
+  }
+  catch( ... )
+  {
+    py_script.close();
+    throw;
+  }
+}
+/** 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)
+{
+  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());
+    }
+    QTextStream stream(&py_script);
+    QString line;
+    while( !stream.atEnd() )
+    {
+	    line = stream.readLine();
+  	  m_pyScript.append(line + "\n");
+    }
+    py_script.close();
+  }
+  catch( ... )
+  {
+    py_script.close();
+    throw;
+  }
+}
+/** Replaces the marker word in the m_pyScript with the text in the QLineEdit
+*  checking if the value will fail validation, storing any error in m_fails
+* @param pythonMark :: the word to search for and replace
+* @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)
+{
+  QString setting = userVal->text();
+  std::string error = replaceErrsFind(pythonMark, setting, check);
+  if ( ! error.empty() )
+  {
+    m_fails[userVal] = error;
+  }
+}
+/** Replaces the marker word in the m_pyScript with the passed string checking
+*  if the value will fail validation (errors are stored m_fails)
+* @param pythonMark :: the word to search for and replace
+* @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+"'");
+  return check->setValue(setting.toStdString());
+}
+/** Appends the text in the QLineEdit to m_pyScript and stores any error
+*   in m_fails
+* @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()+"'");
+  std::string error = check->setValue(userVal->text().toStdString());
+  if ( ! error.empty() )
+  {
+    m_fails[userVal] = error;
+  }
+}
+/** Sends interpretes the Python code through runPythonCode() and returns
+*  a results summary
+*  @return any print statements executed in the Python script
+*/
+QString pythonCalc::run()
+{
+ QString tests = runPythonCode(m_pyScript, false);
+ //std::cerr << "results\n";
+ //std::cerr << tests.toStdString() << "\n";
+ return tests;
+}
diff --git a/Code/Mantid/QtPropertyBrowser/src/StringDialogEditorFactory.cpp b/Code/Mantid/QtPropertyBrowser/src/StringDialogEditorFactory.cpp
index 3e94b5952e71603f70adecfcba36b648dfbefee6..edc2f29bb8369f9344381cf87c43773c5e5e79f1 100644
--- a/Code/Mantid/QtPropertyBrowser/src/StringDialogEditorFactory.cpp
+++ b/Code/Mantid/QtPropertyBrowser/src/StringDialogEditorFactory.cpp
@@ -1,83 +1,83 @@
-#include "StringDialogEditorFactory.h"
-
-#include <QHBoxLayout>
-#include <QLineEdit>
-#include <QPushButton>
-#include <QFileDialog>
-#include <QLabel>
-#include <QDialog>
-#include <QSettings>
-
-#include <iostream>
-
-void StringDialogEditorFactory::connectPropertyManager(QtStringPropertyManager *manager)
-{
-}
-
-QWidget* StringDialogEditorFactory::createEditor(QtStringPropertyManager *manager, QtProperty *property,QWidget *parent)
-{
-  return new StringDialogEditor(property,parent);
-}
-
-void StringDialogEditorFactory::disconnectPropertyManager(QtStringPropertyManager *manager)
-{
-}
-
-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)
-  {
-    m_lineEdit->setText(mgr->value(property));
-  }
-
-  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->setSpacing(0);
-  layout->setStretchFactor(button,0);
-  this->setLayout(layout);
-}
-
-void StringDialogEditor::runDialog()
-{
-  QSettings settings;
-  QString dir = settings.value("Mantid/FitBrowser/ResolutionDir").toString();
-  QString StringDialog = QFileDialog::getOpenFileName(this, tr("Open File"),dir);
-  if (!StringDialog.isEmpty())
-  {
-    m_lineEdit->setText(StringDialog);
-    updateProperty();
-  }
-}
-
-void StringDialogEditor::setText(const QString& txt)
-{
-  m_lineEdit->setText(txt);
-}
-
-QString StringDialogEditor::getText()const
-{
-  return m_lineEdit->text();
-}
-
-StringDialogEditor::~StringDialogEditor()
-{
-}
-
-void StringDialogEditor::updateProperty()
-{
-  QtStringPropertyManager* mgr = dynamic_cast<QtStringPropertyManager*>(m_property->propertyManager());
-  if (mgr)
-  {
-    mgr->setValue(m_property,m_lineEdit->text());
-  }
-}
-
+#include "StringDialogEditorFactory.h"
+
+#include <QHBoxLayout>
+#include <QLineEdit>
+#include <QPushButton>
+#include <QFileDialog>
+#include <QLabel>
+#include <QDialog>
+#include <QSettings>
+
+#include <iostream>
+
+void StringDialogEditorFactory::connectPropertyManager(QtStringPropertyManager *manager)
+{
+}
+
+QWidget* StringDialogEditorFactory::createEditor(QtStringPropertyManager *manager, QtProperty *property,QWidget *parent)
+{
+  return new StringDialogEditor(property,parent);
+}
+
+void StringDialogEditorFactory::disconnectPropertyManager(QtStringPropertyManager *manager)
+{
+}
+
+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)
+  {
+    m_lineEdit->setText(mgr->value(property));
+  }
+
+  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->setSpacing(0);
+  layout->setStretchFactor(button,0);
+  this->setLayout(layout);
+}
+
+void StringDialogEditor::runDialog()
+{
+  QSettings settings;
+  QString dir = settings.value("Mantid/FitBrowser/ResolutionDir").toString();
+  QString StringDialog = QFileDialog::getOpenFileName(this, tr("Open File"),dir);
+  if (!StringDialog.isEmpty())
+  {
+    m_lineEdit->setText(StringDialog);
+    updateProperty();
+  }
+}
+
+void StringDialogEditor::setText(const QString& txt)
+{
+  m_lineEdit->setText(txt);
+}
+
+QString StringDialogEditor::getText()const
+{
+  return m_lineEdit->text();
+}
+
+StringDialogEditor::~StringDialogEditor()
+{
+}
+
+void StringDialogEditor::updateProperty()
+{
+  QtStringPropertyManager* mgr = dynamic_cast<QtStringPropertyManager*>(m_property->propertyManager());
+  if (mgr)
+  {
+    mgr->setValue(m_property,m_lineEdit->text());
+  }
+}
+
diff --git a/Code/Mantid/QtPropertyBrowser/src/StringDialogEditorFactory.h b/Code/Mantid/QtPropertyBrowser/src/StringDialogEditorFactory.h
index e02a2b67795db82c806aecc091a99243654e5463..35994ba2e9ea91bcc678b829984b8ce6146b3cea 100644
--- a/Code/Mantid/QtPropertyBrowser/src/StringDialogEditorFactory.h
+++ b/Code/Mantid/QtPropertyBrowser/src/StringDialogEditorFactory.h
@@ -1,35 +1,35 @@
-#ifndef STRINGDIALOGEDITORFACTORY_H
-#define STRINGDIALOGEDITORFACTORY_H
-
-#include "qtpropertymanager.h"
-
-class QLineEdit;
-
-class QT_QTPROPERTYBROWSER_EXPORT StringDialogEditorFactory : public QtAbstractEditorFactory<QtStringPropertyManager>
-{
-    Q_OBJECT
-public:
-  StringDialogEditorFactory(QObject *parent = 0): QtAbstractEditorFactory<QtStringPropertyManager>(parent){}
-protected:
-  void connectPropertyManager(QtStringPropertyManager *manager);
-  QWidget *createEditor(QtStringPropertyManager *manager, QtProperty *property,QWidget *parent);
-  void disconnectPropertyManager(QtStringPropertyManager *manager);
-};
-
-class QT_QTPROPERTYBROWSER_EXPORT StringDialogEditor: public QWidget
-{
-  Q_OBJECT
-public:
-  StringDialogEditor(QtProperty *property, QWidget *parent);
-  ~StringDialogEditor();
-protected slots:
-  virtual void runDialog();
-  void updateProperty();
-  void setText(const QString& txt);
-  QString getText()const;
-private:
-  QLineEdit* m_lineEdit;
-  QtProperty* m_property;
-};
-
-#endif // STRINGDIALOGEDITORFACTORY_H
+#ifndef STRINGDIALOGEDITORFACTORY_H
+#define STRINGDIALOGEDITORFACTORY_H
+
+#include "qtpropertymanager.h"
+
+class QLineEdit;
+
+class QT_QTPROPERTYBROWSER_EXPORT StringDialogEditorFactory : public QtAbstractEditorFactory<QtStringPropertyManager>
+{
+    Q_OBJECT
+public:
+  StringDialogEditorFactory(QObject *parent = 0): QtAbstractEditorFactory<QtStringPropertyManager>(parent){}
+protected:
+  void connectPropertyManager(QtStringPropertyManager *manager);
+  QWidget *createEditor(QtStringPropertyManager *manager, QtProperty *property,QWidget *parent);
+  void disconnectPropertyManager(QtStringPropertyManager *manager);
+};
+
+class QT_QTPROPERTYBROWSER_EXPORT StringDialogEditor: public QWidget
+{
+  Q_OBJECT
+public:
+  StringDialogEditor(QtProperty *property, QWidget *parent);
+  ~StringDialogEditor();
+protected slots:
+  virtual void runDialog();
+  void updateProperty();
+  void setText(const QString& txt);
+  QString getText()const;
+private:
+  QLineEdit* m_lineEdit;
+  QtProperty* m_property;
+};
+
+#endif // STRINGDIALOGEDITORFACTORY_H
diff --git a/Code/Mantid/QtPropertyBrowser/src/qtbuttonpropertybrowser.cpp b/Code/Mantid/QtPropertyBrowser/src/qtbuttonpropertybrowser.cpp
index ab2ea377fc56b5f48cb01e0ef5405b7fa5cf9d84..145a37b6441c25dfdb6c9c1a792157618d00ff58 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qtbuttonpropertybrowser.cpp
+++ b/Code/Mantid/QtPropertyBrowser/src/qtbuttonpropertybrowser.cpp
@@ -1,676 +1,676 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qtbuttonpropertybrowser.h"
-#include <QtCore/QSet>
-#include <QtGui/QGridLayout>
-#include <QtGui/QLabel>
-#include <QtCore/QTimer>
-#include <QtCore/QMap>
-#include <QtGui/QToolButton>
-#include <QtGui/QStyle>
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-class QtButtonPropertyBrowserPrivate
-{
-    QtButtonPropertyBrowser *q_ptr;
-    Q_DECLARE_PUBLIC(QtButtonPropertyBrowser)
-public:
-
-    void init(QWidget *parent);
-
-    void propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex);
-    void propertyRemoved(QtBrowserItem *index);
-    void propertyChanged(QtBrowserItem *index);
-    QWidget *createEditor(QtProperty *property, QWidget *parent) const
-        { return q_ptr->createEditor(property, parent); }
-
-    void slotEditorDestroyed();
-    void slotUpdate();
-    void slotToggled(bool checked);
-
-    struct WidgetItem
-    {
-        WidgetItem() : widget(0), label(0), widgetLabel(0),
-                button(0), container(0), layout(0), /*line(0), */parent(0), expanded(false) { }
-        QWidget *widget; // can be null
-        QLabel *label; // main label with property name
-        QLabel *widgetLabel; // label substitute showing the current value if there is no widget
-        QToolButton *button; // expandable button for items with children
-        QWidget *container; // container which is expanded when the button is clicked
-        QGridLayout *layout; // layout in container
-        WidgetItem *parent;
-        QList<WidgetItem *> children;
-        bool expanded;
-    };
-private:
-    void updateLater();
-    void updateItem(WidgetItem *item);
-    void insertRow(QGridLayout *layout, int row) const;
-    void removeRow(QGridLayout *layout, int row) const;
-    int gridRow(WidgetItem *item) const;
-    int gridSpan(WidgetItem *item) const;
-    void setExpanded(WidgetItem *item, bool expanded);
-    QToolButton *createButton(QWidget *panret = 0) const;
-
-    QMap<QtBrowserItem *, WidgetItem *> m_indexToItem;
-    QMap<WidgetItem *, QtBrowserItem *> m_itemToIndex;
-    QMap<QWidget *, WidgetItem *> m_widgetToItem;
-    QMap<QObject *, WidgetItem *> m_buttonToItem;
-    QGridLayout *m_mainLayout;
-    QList<WidgetItem *> m_children;
-    QList<WidgetItem *> m_recreateQueue;
-};
-
-QToolButton *QtButtonPropertyBrowserPrivate::createButton(QWidget *parent) const
-{
-    QToolButton *button = new QToolButton(parent);
-    button->setCheckable(true);
-    button->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed));
-    button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
-    button->setArrowType(Qt::DownArrow);
-    button->setIconSize(QSize(3, 16));
-    /*
-    QIcon icon;
-    icon.addPixmap(q_ptr->style()->standardPixmap(QStyle::SP_ArrowDown), QIcon::Normal, QIcon::Off);
-    icon.addPixmap(q_ptr->style()->standardPixmap(QStyle::SP_ArrowUp), QIcon::Normal, QIcon::On);
-    button->setIcon(icon);
-    */
-    return button;
-}
-
-int QtButtonPropertyBrowserPrivate::gridRow(WidgetItem *item) const
-{
-    QList<WidgetItem *> siblings;
-    if (item->parent)
-        siblings = item->parent->children;
-    else
-        siblings = m_children;
-
-    int row = 0;
-    QListIterator<WidgetItem *> it(siblings);
-    while (it.hasNext()) {
-        WidgetItem *sibling = it.next();
-        if (sibling == item)
-            return row;
-        row += gridSpan(sibling);
-    }
-    return -1;
-}
-
-int QtButtonPropertyBrowserPrivate::gridSpan(WidgetItem *item) const
-{
-    if (item->container && item->expanded)
-        return 2;
-    return 1;
-}
-
-void QtButtonPropertyBrowserPrivate::init(QWidget *parent)
-{
-    m_mainLayout = new QGridLayout();
-    parent->setLayout(m_mainLayout);
-    QLayoutItem *item = new QSpacerItem(0, 0,
-                QSizePolicy::Fixed, QSizePolicy::Expanding);
-    m_mainLayout->addItem(item, 0, 0);
-}
-
-void QtButtonPropertyBrowserPrivate::slotEditorDestroyed()
-{
-    QWidget *editor = qobject_cast<QWidget *>(q_ptr->sender());
-    if (!editor)
-        return;
-    if (!m_widgetToItem.contains(editor))
-        return;
-    m_widgetToItem[editor]->widget = 0;
-    m_widgetToItem.remove(editor);
-}
-
-void QtButtonPropertyBrowserPrivate::slotUpdate()
-{
-    QListIterator<WidgetItem *> itItem(m_recreateQueue);
-    while (itItem.hasNext()) {
-        WidgetItem *item = itItem.next();
-
-        WidgetItem *parent = item->parent;
-        QWidget *w = 0;
-        QGridLayout *l = 0;
-        const int oldRow = gridRow(item);
-        if (parent) {
-            w = parent->container;
-            l = parent->layout;
-        } else {
-            w = q_ptr;
-            l = m_mainLayout;
-        }
-
-        int span = 1;
-        if (!item->widget && !item->widgetLabel)
-            span = 2;
-        item->label = new QLabel(w);
-        item->label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
-        l->addWidget(item->label, oldRow, 0, 1, span);
-
-        updateItem(item);
-    }
-    m_recreateQueue.clear();
-}
-
-void QtButtonPropertyBrowserPrivate::setExpanded(WidgetItem *item, bool expanded)
-{
-    if (item->expanded == expanded)
-        return;
-
-    if (!item->container)
-        return;
-
-    item->expanded = expanded;
-    const int row = gridRow(item);
-    WidgetItem *parent = item->parent;
-    QGridLayout *l = 0;
-    if (parent)
-        l = parent->layout;
-    else
-        l = m_mainLayout;
-
-    if (expanded) {
-        insertRow(l, row + 1);
-        l->addWidget(item->container, row + 1, 0, 1, 2);
-        item->container->show();
-    } else {
-        l->removeWidget(item->container);
-        item->container->hide();
-        removeRow(l, row + 1);
-    }
-
-    item->button->setChecked(expanded);
-    item->button->setArrowType(expanded ? Qt::UpArrow : Qt::DownArrow);
-}
-
-void QtButtonPropertyBrowserPrivate::slotToggled(bool checked)
-{
-    WidgetItem *item = m_buttonToItem.value(q_ptr->sender());
-    if (!item)
-        return;
-
-    setExpanded(item, checked);
-
-    if (checked)
-        emit q_ptr->expanded(m_itemToIndex.value(item));
-    else
-        emit q_ptr->collapsed(m_itemToIndex.value(item));
-}
-
-void QtButtonPropertyBrowserPrivate::updateLater()
-{
-    QTimer::singleShot(0, q_ptr, SLOT(slotUpdate()));
-}
-
-void QtButtonPropertyBrowserPrivate::propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex)
-{
-    WidgetItem *afterItem = m_indexToItem.value(afterIndex);
-    WidgetItem *parentItem = m_indexToItem.value(index->parent());
-
-    WidgetItem *newItem = new WidgetItem();
-    newItem->parent = parentItem;
-
-    QGridLayout *layout = 0;
-    QWidget *parentWidget = 0;
-    int row = -1;
-    if (!afterItem) {
-        row = 0;
-        if (parentItem)
-            parentItem->children.insert(0, newItem);
-        else
-            m_children.insert(0, newItem);
-    } else {
-        row = gridRow(afterItem) + gridSpan(afterItem);
-        if (parentItem)
-            parentItem->children.insert(parentItem->children.indexOf(afterItem) + 1, newItem);
-        else
-            m_children.insert(m_children.indexOf(afterItem) + 1, newItem);
-    }
-
-    if (!parentItem) {
-        layout = m_mainLayout;
-        parentWidget = q_ptr;
-    } else {
-        if (!parentItem->container) {
-            m_recreateQueue.removeAll(parentItem);
-            WidgetItem *grandParent = parentItem->parent;
-            QWidget *w = 0;
-            QGridLayout *l = 0;
-            const int oldRow = gridRow(parentItem);
-            if (grandParent) {
-                w = grandParent->container;
-                l = grandParent->layout;
-            } else {
-                w = q_ptr;
-                l = m_mainLayout;
-            }
-            QFrame *container = new QFrame();
-            container->setFrameShape(QFrame::Panel);
-            container->setFrameShadow(QFrame::Raised);
-            parentItem->container = container;
-            parentItem->button = createButton();
-            m_buttonToItem[parentItem->button] = parentItem;
-            q_ptr->connect(parentItem->button, SIGNAL(toggled(bool)), q_ptr, SLOT(slotToggled(bool)));
-            parentItem->layout = new QGridLayout();
-            container->setLayout(parentItem->layout);
-            if (parentItem->label) {
-                l->removeWidget(parentItem->label);
-                delete parentItem->label;
-                parentItem->label = 0;
-            }
-            int span = 1;
-            if (!parentItem->widget && !parentItem->widgetLabel)
-                span = 2;
-            l->addWidget(parentItem->button, oldRow, 0, 1, span);
-            updateItem(parentItem);
-        }
-        layout = parentItem->layout;
-        parentWidget = parentItem->container;
-    }
-
-    newItem->label = new QLabel(parentWidget);
-    newItem->label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
-    newItem->widget = createEditor(index->property(), parentWidget);
-    if (newItem->widget) {
-        QObject::connect(newItem->widget, SIGNAL(destroyed()), q_ptr, SLOT(slotEditorDestroyed()));
-        m_widgetToItem[newItem->widget] = newItem;
-    } else if (index->property()->hasValue()) {
-        newItem->widgetLabel = new QLabel(parentWidget);
-        newItem->widgetLabel->setSizePolicy(QSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed));
-    }
-
-    insertRow(layout, row);
-    int span = 1;
-    if (newItem->widget)
-        layout->addWidget(newItem->widget, row, 1);
-    else if (newItem->widgetLabel)
-        layout->addWidget(newItem->widgetLabel, row, 1);
-    else
-        span = 2;
-    layout->addWidget(newItem->label, row, 0, span, 1);
-
-    m_itemToIndex[newItem] = index;
-    m_indexToItem[index] = newItem;
-
-    updateItem(newItem);
-}
-
-void QtButtonPropertyBrowserPrivate::propertyRemoved(QtBrowserItem *index)
-{
-    WidgetItem *item = m_indexToItem.value(index);
-
-    m_indexToItem.remove(index);
-    m_itemToIndex.remove(item);
-
-    WidgetItem *parentItem = item->parent;
-
-    const int row = gridRow(item);
-
-    if (parentItem)
-        parentItem->children.removeAt(parentItem->children.indexOf(item));
-    else
-        m_children.removeAt(m_children.indexOf(item));
-
-    const int colSpan = gridSpan(item);
-
-    m_buttonToItem.remove(item->button);
-
-    if (item->widget)
-        delete item->widget;
-    if (item->label)
-        delete item->label;
-    if (item->widgetLabel)
-        delete item->widgetLabel;
-    if (item->button)
-        delete item->button;
-    if (item->container)
-        delete item->container;
-
-    if (!parentItem) {
-        removeRow(m_mainLayout, row);
-        if (colSpan > 1)
-            removeRow(m_mainLayout, row);
-    } else if (parentItem->children.count() != 0) {
-        removeRow(parentItem->layout, row);
-        if (colSpan > 1)
-            removeRow(parentItem->layout, row);
-    } else {
-        const WidgetItem *grandParent = parentItem->parent;
-        QGridLayout *l = 0;
-        if (grandParent) {
-            l = grandParent->layout;
-        } else {
-            l = m_mainLayout;
-        }
-
-        const int parentRow = gridRow(parentItem);
-        const int parentSpan = gridSpan(parentItem);
-
-        l->removeWidget(parentItem->button);
-        l->removeWidget(parentItem->container);
-        delete parentItem->button;
-        delete parentItem->container;
-        parentItem->button = 0;
-        parentItem->container = 0;
-        parentItem->layout = 0;
-        if (!m_recreateQueue.contains(parentItem))
-            m_recreateQueue.append(parentItem);
-        if (parentSpan > 1)
-            removeRow(l, parentRow + 1);
-
-        updateLater();
-    }
-    m_recreateQueue.removeAll(item);
-
-    delete item;
-}
-
-void QtButtonPropertyBrowserPrivate::insertRow(QGridLayout *layout, int row) const
-{
-    QMap<QLayoutItem *, QRect> itemToPos;
-    int idx = 0;
-    while (idx < layout->count()) {
-        int r, c, rs, cs;
-        layout->getItemPosition(idx, &r, &c, &rs, &cs);
-        if (r >= row) {
-            itemToPos[layout->takeAt(idx)] = QRect(r + 1, c, rs, cs);
-        } else {
-            idx++;
-        }
-    }
-
-    const QMap<QLayoutItem *, QRect>::ConstIterator icend =  itemToPos.constEnd();
-    for(QMap<QLayoutItem *, QRect>::ConstIterator it = itemToPos.constBegin(); it != icend; ++it) {
-        const QRect r = it.value();
-        layout->addItem(it.key(), r.x(), r.y(), r.width(), r.height());
-    }
-}
-
-void QtButtonPropertyBrowserPrivate::removeRow(QGridLayout *layout, int row) const
-{
-    QMap<QLayoutItem *, QRect> itemToPos;
-    int idx = 0;
-    while (idx < layout->count()) {
-        int r, c, rs, cs;
-        layout->getItemPosition(idx, &r, &c, &rs, &cs);
-        if (r > row) {
-            itemToPos[layout->takeAt(idx)] = QRect(r - 1, c, rs, cs);
-        } else {
-            idx++;
-        }
-    }
-
-    const QMap<QLayoutItem *, QRect>::ConstIterator icend =  itemToPos.constEnd();
-    for(QMap<QLayoutItem *, QRect>::ConstIterator it = itemToPos.constBegin(); it != icend; ++it) {
-        const QRect r = it.value();
-        layout->addItem(it.key(), r.x(), r.y(), r.width(), r.height());
-    }
-}
-
-void QtButtonPropertyBrowserPrivate::propertyChanged(QtBrowserItem *index)
-{
-    WidgetItem *item = m_indexToItem.value(index);
-
-    updateItem(item);
-}
-
-void QtButtonPropertyBrowserPrivate::updateItem(WidgetItem *item)
-{
-    QtProperty *property = m_itemToIndex[item]->property();
-    if (item->button) {
-        QFont font = item->button->font();
-        font.setUnderline(property->isModified());
-        item->button->setFont(font);
-        item->button->setText(property->propertyName());
-        item->button->setToolTip(property->toolTip());
-        item->button->setStatusTip(property->statusTip());
-        item->button->setWhatsThis(property->whatsThis());
-        item->button->setEnabled(property->isEnabled());
-    }
-    if (item->label) {
-        QFont font = item->label->font();
-        font.setUnderline(property->isModified());
-        item->label->setFont(font);
-        item->label->setText(property->propertyName());
-        item->label->setToolTip(property->toolTip());
-        item->label->setStatusTip(property->statusTip());
-        item->label->setWhatsThis(property->whatsThis());
-        item->label->setEnabled(property->isEnabled());
-    }
-    if (item->widgetLabel) {
-        QFont font = item->widgetLabel->font();
-        font.setUnderline(false);
-        item->widgetLabel->setFont(font);
-        item->widgetLabel->setText(property->valueText());
-        item->widgetLabel->setToolTip(property->valueText());
-        item->widgetLabel->setEnabled(property->isEnabled());
-    }
-    if (item->widget) {
-        QFont font = item->widget->font();
-        font.setUnderline(false);
-        item->widget->setFont(font);
-        item->widget->setEnabled(property->isEnabled());
-        item->widget->setToolTip(property->valueText());
-    }
-}
-
-
-
-/**
-    \class QtButtonPropertyBrowser
-
-    \brief The QtButtonPropertyBrowser class provides a drop down QToolButton
-    based property browser.
-
-    A property browser is a widget that enables the user to edit a
-    given set of properties. Each property is represented by a label
-    specifying the property's name, and an editing widget (e.g. a line
-    edit or a combobox) holding its value. A property can have zero or
-    more subproperties.
-
-    QtButtonPropertyBrowser provides drop down button for all nested
-    properties, i.e. subproperties are enclosed by a container associated with
-    the drop down button. The parent property's name is displayed as button text. For example:
-
-    \image qtbuttonpropertybrowser.png
-
-    Use the QtAbstractPropertyBrowser API to add, insert and remove
-    properties from an instance of the QtButtonPropertyBrowser
-    class. The properties themselves are created and managed by
-    implementations of the QtAbstractPropertyManager class.
-
-    \sa QtTreePropertyBrowser, QtAbstractPropertyBrowser
-*/
-
-/**
-    \fn void QtButtonPropertyBrowser::collapsed(QtBrowserItem *item)
-
-    This signal is emitted when the \a item is collapsed.
-
-    \sa expanded(), setExpanded()
-*/
-
-/**
-    \fn void QtButtonPropertyBrowser::expanded(QtBrowserItem *item)
-
-    This signal is emitted when the \a item is expanded.
-
-    \sa collapsed(), setExpanded()
-*/
-
-/**
-    Creates a property browser with the given \a parent.
-*/
-QtButtonPropertyBrowser::QtButtonPropertyBrowser(QWidget *parent)
-    : QtAbstractPropertyBrowser(parent)
-{
-    d_ptr = new QtButtonPropertyBrowserPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->init(this);
-}
-
-/**
-    Destroys this property browser.
-
-    Note that the properties that were inserted into this browser are
-    \e not destroyed since they may still be used in other
-    browsers. The properties are owned by the manager that created
-    them.
-
-    \sa QtProperty, QtAbstractPropertyManager
-*/
-QtButtonPropertyBrowser::~QtButtonPropertyBrowser()
-{
-    const QMap<QtButtonPropertyBrowserPrivate::WidgetItem *, QtBrowserItem *>::ConstIterator icend = d_ptr->m_itemToIndex.constEnd();
-    for (QMap<QtButtonPropertyBrowserPrivate::WidgetItem *, QtBrowserItem *>::ConstIterator  it =  d_ptr->m_itemToIndex.constBegin(); it != icend; ++it)
-        delete it.key();
-    delete d_ptr;
-}
-
-/**
-    \reimp
-*/
-void QtButtonPropertyBrowser::itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem)
-{
-    d_ptr->propertyInserted(item, afterItem);
-}
-
-/**
-    \reimp
-*/
-void QtButtonPropertyBrowser::itemRemoved(QtBrowserItem *item)
-{
-    d_ptr->propertyRemoved(item);
-}
-
-/**
-    \reimp
-*/
-void QtButtonPropertyBrowser::itemChanged(QtBrowserItem *item)
-{
-    d_ptr->propertyChanged(item);
-}
-
-/**
-    Sets the \a item to either collapse or expanded, depending on the value of \a expanded.
-
-    \sa isExpanded(), expanded(), collapsed()
-*/
-
-void QtButtonPropertyBrowser::setExpanded(QtBrowserItem *item, bool expanded)
-{
-    QtButtonPropertyBrowserPrivate::WidgetItem *itm = d_ptr->m_indexToItem.value(item);
-    if (itm)
-        d_ptr->setExpanded(itm, expanded);
-}
-
-/**
-    Returns true if the \a item is expanded; otherwise returns false.
-
-    \sa setExpanded()
-*/
-
-bool QtButtonPropertyBrowser::isExpanded(QtBrowserItem *item) const
-{
-    QtButtonPropertyBrowserPrivate::WidgetItem *itm = d_ptr->m_indexToItem.value(item);
-    if (itm)
-        return itm->expanded;
-    return false;
-}
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#include "moc_qtbuttonpropertybrowser.cpp"
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qtbuttonpropertybrowser.h"
+#include <QtCore/QSet>
+#include <QtGui/QGridLayout>
+#include <QtGui/QLabel>
+#include <QtCore/QTimer>
+#include <QtCore/QMap>
+#include <QtGui/QToolButton>
+#include <QtGui/QStyle>
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+class QtButtonPropertyBrowserPrivate
+{
+    QtButtonPropertyBrowser *q_ptr;
+    Q_DECLARE_PUBLIC(QtButtonPropertyBrowser)
+public:
+
+    void init(QWidget *parent);
+
+    void propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex);
+    void propertyRemoved(QtBrowserItem *index);
+    void propertyChanged(QtBrowserItem *index);
+    QWidget *createEditor(QtProperty *property, QWidget *parent) const
+        { return q_ptr->createEditor(property, parent); }
+
+    void slotEditorDestroyed();
+    void slotUpdate();
+    void slotToggled(bool checked);
+
+    struct WidgetItem
+    {
+        WidgetItem() : widget(0), label(0), widgetLabel(0),
+                button(0), container(0), layout(0), /*line(0), */parent(0), expanded(false) { }
+        QWidget *widget; // can be null
+        QLabel *label; // main label with property name
+        QLabel *widgetLabel; // label substitute showing the current value if there is no widget
+        QToolButton *button; // expandable button for items with children
+        QWidget *container; // container which is expanded when the button is clicked
+        QGridLayout *layout; // layout in container
+        WidgetItem *parent;
+        QList<WidgetItem *> children;
+        bool expanded;
+    };
+private:
+    void updateLater();
+    void updateItem(WidgetItem *item);
+    void insertRow(QGridLayout *layout, int row) const;
+    void removeRow(QGridLayout *layout, int row) const;
+    int gridRow(WidgetItem *item) const;
+    int gridSpan(WidgetItem *item) const;
+    void setExpanded(WidgetItem *item, bool expanded);
+    QToolButton *createButton(QWidget *panret = 0) const;
+
+    QMap<QtBrowserItem *, WidgetItem *> m_indexToItem;
+    QMap<WidgetItem *, QtBrowserItem *> m_itemToIndex;
+    QMap<QWidget *, WidgetItem *> m_widgetToItem;
+    QMap<QObject *, WidgetItem *> m_buttonToItem;
+    QGridLayout *m_mainLayout;
+    QList<WidgetItem *> m_children;
+    QList<WidgetItem *> m_recreateQueue;
+};
+
+QToolButton *QtButtonPropertyBrowserPrivate::createButton(QWidget *parent) const
+{
+    QToolButton *button = new QToolButton(parent);
+    button->setCheckable(true);
+    button->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed));
+    button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
+    button->setArrowType(Qt::DownArrow);
+    button->setIconSize(QSize(3, 16));
+    /*
+    QIcon icon;
+    icon.addPixmap(q_ptr->style()->standardPixmap(QStyle::SP_ArrowDown), QIcon::Normal, QIcon::Off);
+    icon.addPixmap(q_ptr->style()->standardPixmap(QStyle::SP_ArrowUp), QIcon::Normal, QIcon::On);
+    button->setIcon(icon);
+    */
+    return button;
+}
+
+int QtButtonPropertyBrowserPrivate::gridRow(WidgetItem *item) const
+{
+    QList<WidgetItem *> siblings;
+    if (item->parent)
+        siblings = item->parent->children;
+    else
+        siblings = m_children;
+
+    int row = 0;
+    QListIterator<WidgetItem *> it(siblings);
+    while (it.hasNext()) {
+        WidgetItem *sibling = it.next();
+        if (sibling == item)
+            return row;
+        row += gridSpan(sibling);
+    }
+    return -1;
+}
+
+int QtButtonPropertyBrowserPrivate::gridSpan(WidgetItem *item) const
+{
+    if (item->container && item->expanded)
+        return 2;
+    return 1;
+}
+
+void QtButtonPropertyBrowserPrivate::init(QWidget *parent)
+{
+    m_mainLayout = new QGridLayout();
+    parent->setLayout(m_mainLayout);
+    QLayoutItem *item = new QSpacerItem(0, 0,
+                QSizePolicy::Fixed, QSizePolicy::Expanding);
+    m_mainLayout->addItem(item, 0, 0);
+}
+
+void QtButtonPropertyBrowserPrivate::slotEditorDestroyed()
+{
+    QWidget *editor = qobject_cast<QWidget *>(q_ptr->sender());
+    if (!editor)
+        return;
+    if (!m_widgetToItem.contains(editor))
+        return;
+    m_widgetToItem[editor]->widget = 0;
+    m_widgetToItem.remove(editor);
+}
+
+void QtButtonPropertyBrowserPrivate::slotUpdate()
+{
+    QListIterator<WidgetItem *> itItem(m_recreateQueue);
+    while (itItem.hasNext()) {
+        WidgetItem *item = itItem.next();
+
+        WidgetItem *parent = item->parent;
+        QWidget *w = 0;
+        QGridLayout *l = 0;
+        const int oldRow = gridRow(item);
+        if (parent) {
+            w = parent->container;
+            l = parent->layout;
+        } else {
+            w = q_ptr;
+            l = m_mainLayout;
+        }
+
+        int span = 1;
+        if (!item->widget && !item->widgetLabel)
+            span = 2;
+        item->label = new QLabel(w);
+        item->label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
+        l->addWidget(item->label, oldRow, 0, 1, span);
+
+        updateItem(item);
+    }
+    m_recreateQueue.clear();
+}
+
+void QtButtonPropertyBrowserPrivate::setExpanded(WidgetItem *item, bool expanded)
+{
+    if (item->expanded == expanded)
+        return;
+
+    if (!item->container)
+        return;
+
+    item->expanded = expanded;
+    const int row = gridRow(item);
+    WidgetItem *parent = item->parent;
+    QGridLayout *l = 0;
+    if (parent)
+        l = parent->layout;
+    else
+        l = m_mainLayout;
+
+    if (expanded) {
+        insertRow(l, row + 1);
+        l->addWidget(item->container, row + 1, 0, 1, 2);
+        item->container->show();
+    } else {
+        l->removeWidget(item->container);
+        item->container->hide();
+        removeRow(l, row + 1);
+    }
+
+    item->button->setChecked(expanded);
+    item->button->setArrowType(expanded ? Qt::UpArrow : Qt::DownArrow);
+}
+
+void QtButtonPropertyBrowserPrivate::slotToggled(bool checked)
+{
+    WidgetItem *item = m_buttonToItem.value(q_ptr->sender());
+    if (!item)
+        return;
+
+    setExpanded(item, checked);
+
+    if (checked)
+        emit q_ptr->expanded(m_itemToIndex.value(item));
+    else
+        emit q_ptr->collapsed(m_itemToIndex.value(item));
+}
+
+void QtButtonPropertyBrowserPrivate::updateLater()
+{
+    QTimer::singleShot(0, q_ptr, SLOT(slotUpdate()));
+}
+
+void QtButtonPropertyBrowserPrivate::propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex)
+{
+    WidgetItem *afterItem = m_indexToItem.value(afterIndex);
+    WidgetItem *parentItem = m_indexToItem.value(index->parent());
+
+    WidgetItem *newItem = new WidgetItem();
+    newItem->parent = parentItem;
+
+    QGridLayout *layout = 0;
+    QWidget *parentWidget = 0;
+    int row = -1;
+    if (!afterItem) {
+        row = 0;
+        if (parentItem)
+            parentItem->children.insert(0, newItem);
+        else
+            m_children.insert(0, newItem);
+    } else {
+        row = gridRow(afterItem) + gridSpan(afterItem);
+        if (parentItem)
+            parentItem->children.insert(parentItem->children.indexOf(afterItem) + 1, newItem);
+        else
+            m_children.insert(m_children.indexOf(afterItem) + 1, newItem);
+    }
+
+    if (!parentItem) {
+        layout = m_mainLayout;
+        parentWidget = q_ptr;
+    } else {
+        if (!parentItem->container) {
+            m_recreateQueue.removeAll(parentItem);
+            WidgetItem *grandParent = parentItem->parent;
+            QWidget *w = 0;
+            QGridLayout *l = 0;
+            const int oldRow = gridRow(parentItem);
+            if (grandParent) {
+                w = grandParent->container;
+                l = grandParent->layout;
+            } else {
+                w = q_ptr;
+                l = m_mainLayout;
+            }
+            QFrame *container = new QFrame();
+            container->setFrameShape(QFrame::Panel);
+            container->setFrameShadow(QFrame::Raised);
+            parentItem->container = container;
+            parentItem->button = createButton();
+            m_buttonToItem[parentItem->button] = parentItem;
+            q_ptr->connect(parentItem->button, SIGNAL(toggled(bool)), q_ptr, SLOT(slotToggled(bool)));
+            parentItem->layout = new QGridLayout();
+            container->setLayout(parentItem->layout);
+            if (parentItem->label) {
+                l->removeWidget(parentItem->label);
+                delete parentItem->label;
+                parentItem->label = 0;
+            }
+            int span = 1;
+            if (!parentItem->widget && !parentItem->widgetLabel)
+                span = 2;
+            l->addWidget(parentItem->button, oldRow, 0, 1, span);
+            updateItem(parentItem);
+        }
+        layout = parentItem->layout;
+        parentWidget = parentItem->container;
+    }
+
+    newItem->label = new QLabel(parentWidget);
+    newItem->label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
+    newItem->widget = createEditor(index->property(), parentWidget);
+    if (newItem->widget) {
+        QObject::connect(newItem->widget, SIGNAL(destroyed()), q_ptr, SLOT(slotEditorDestroyed()));
+        m_widgetToItem[newItem->widget] = newItem;
+    } else if (index->property()->hasValue()) {
+        newItem->widgetLabel = new QLabel(parentWidget);
+        newItem->widgetLabel->setSizePolicy(QSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed));
+    }
+
+    insertRow(layout, row);
+    int span = 1;
+    if (newItem->widget)
+        layout->addWidget(newItem->widget, row, 1);
+    else if (newItem->widgetLabel)
+        layout->addWidget(newItem->widgetLabel, row, 1);
+    else
+        span = 2;
+    layout->addWidget(newItem->label, row, 0, span, 1);
+
+    m_itemToIndex[newItem] = index;
+    m_indexToItem[index] = newItem;
+
+    updateItem(newItem);
+}
+
+void QtButtonPropertyBrowserPrivate::propertyRemoved(QtBrowserItem *index)
+{
+    WidgetItem *item = m_indexToItem.value(index);
+
+    m_indexToItem.remove(index);
+    m_itemToIndex.remove(item);
+
+    WidgetItem *parentItem = item->parent;
+
+    const int row = gridRow(item);
+
+    if (parentItem)
+        parentItem->children.removeAt(parentItem->children.indexOf(item));
+    else
+        m_children.removeAt(m_children.indexOf(item));
+
+    const int colSpan = gridSpan(item);
+
+    m_buttonToItem.remove(item->button);
+
+    if (item->widget)
+        delete item->widget;
+    if (item->label)
+        delete item->label;
+    if (item->widgetLabel)
+        delete item->widgetLabel;
+    if (item->button)
+        delete item->button;
+    if (item->container)
+        delete item->container;
+
+    if (!parentItem) {
+        removeRow(m_mainLayout, row);
+        if (colSpan > 1)
+            removeRow(m_mainLayout, row);
+    } else if (parentItem->children.count() != 0) {
+        removeRow(parentItem->layout, row);
+        if (colSpan > 1)
+            removeRow(parentItem->layout, row);
+    } else {
+        const WidgetItem *grandParent = parentItem->parent;
+        QGridLayout *l = 0;
+        if (grandParent) {
+            l = grandParent->layout;
+        } else {
+            l = m_mainLayout;
+        }
+
+        const int parentRow = gridRow(parentItem);
+        const int parentSpan = gridSpan(parentItem);
+
+        l->removeWidget(parentItem->button);
+        l->removeWidget(parentItem->container);
+        delete parentItem->button;
+        delete parentItem->container;
+        parentItem->button = 0;
+        parentItem->container = 0;
+        parentItem->layout = 0;
+        if (!m_recreateQueue.contains(parentItem))
+            m_recreateQueue.append(parentItem);
+        if (parentSpan > 1)
+            removeRow(l, parentRow + 1);
+
+        updateLater();
+    }
+    m_recreateQueue.removeAll(item);
+
+    delete item;
+}
+
+void QtButtonPropertyBrowserPrivate::insertRow(QGridLayout *layout, int row) const
+{
+    QMap<QLayoutItem *, QRect> itemToPos;
+    int idx = 0;
+    while (idx < layout->count()) {
+        int r, c, rs, cs;
+        layout->getItemPosition(idx, &r, &c, &rs, &cs);
+        if (r >= row) {
+            itemToPos[layout->takeAt(idx)] = QRect(r + 1, c, rs, cs);
+        } else {
+            idx++;
+        }
+    }
+
+    const QMap<QLayoutItem *, QRect>::ConstIterator icend =  itemToPos.constEnd();
+    for(QMap<QLayoutItem *, QRect>::ConstIterator it = itemToPos.constBegin(); it != icend; ++it) {
+        const QRect r = it.value();
+        layout->addItem(it.key(), r.x(), r.y(), r.width(), r.height());
+    }
+}
+
+void QtButtonPropertyBrowserPrivate::removeRow(QGridLayout *layout, int row) const
+{
+    QMap<QLayoutItem *, QRect> itemToPos;
+    int idx = 0;
+    while (idx < layout->count()) {
+        int r, c, rs, cs;
+        layout->getItemPosition(idx, &r, &c, &rs, &cs);
+        if (r > row) {
+            itemToPos[layout->takeAt(idx)] = QRect(r - 1, c, rs, cs);
+        } else {
+            idx++;
+        }
+    }
+
+    const QMap<QLayoutItem *, QRect>::ConstIterator icend =  itemToPos.constEnd();
+    for(QMap<QLayoutItem *, QRect>::ConstIterator it = itemToPos.constBegin(); it != icend; ++it) {
+        const QRect r = it.value();
+        layout->addItem(it.key(), r.x(), r.y(), r.width(), r.height());
+    }
+}
+
+void QtButtonPropertyBrowserPrivate::propertyChanged(QtBrowserItem *index)
+{
+    WidgetItem *item = m_indexToItem.value(index);
+
+    updateItem(item);
+}
+
+void QtButtonPropertyBrowserPrivate::updateItem(WidgetItem *item)
+{
+    QtProperty *property = m_itemToIndex[item]->property();
+    if (item->button) {
+        QFont font = item->button->font();
+        font.setUnderline(property->isModified());
+        item->button->setFont(font);
+        item->button->setText(property->propertyName());
+        item->button->setToolTip(property->toolTip());
+        item->button->setStatusTip(property->statusTip());
+        item->button->setWhatsThis(property->whatsThis());
+        item->button->setEnabled(property->isEnabled());
+    }
+    if (item->label) {
+        QFont font = item->label->font();
+        font.setUnderline(property->isModified());
+        item->label->setFont(font);
+        item->label->setText(property->propertyName());
+        item->label->setToolTip(property->toolTip());
+        item->label->setStatusTip(property->statusTip());
+        item->label->setWhatsThis(property->whatsThis());
+        item->label->setEnabled(property->isEnabled());
+    }
+    if (item->widgetLabel) {
+        QFont font = item->widgetLabel->font();
+        font.setUnderline(false);
+        item->widgetLabel->setFont(font);
+        item->widgetLabel->setText(property->valueText());
+        item->widgetLabel->setToolTip(property->valueText());
+        item->widgetLabel->setEnabled(property->isEnabled());
+    }
+    if (item->widget) {
+        QFont font = item->widget->font();
+        font.setUnderline(false);
+        item->widget->setFont(font);
+        item->widget->setEnabled(property->isEnabled());
+        item->widget->setToolTip(property->valueText());
+    }
+}
+
+
+
+/**
+    \class QtButtonPropertyBrowser
+
+    \brief The QtButtonPropertyBrowser class provides a drop down QToolButton
+    based property browser.
+
+    A property browser is a widget that enables the user to edit a
+    given set of properties. Each property is represented by a label
+    specifying the property's name, and an editing widget (e.g. a line
+    edit or a combobox) holding its value. A property can have zero or
+    more subproperties.
+
+    QtButtonPropertyBrowser provides drop down button for all nested
+    properties, i.e. subproperties are enclosed by a container associated with
+    the drop down button. The parent property's name is displayed as button text. For example:
+
+    \image qtbuttonpropertybrowser.png
+
+    Use the QtAbstractPropertyBrowser API to add, insert and remove
+    properties from an instance of the QtButtonPropertyBrowser
+    class. The properties themselves are created and managed by
+    implementations of the QtAbstractPropertyManager class.
+
+    \sa QtTreePropertyBrowser, QtAbstractPropertyBrowser
+*/
+
+/**
+    \fn void QtButtonPropertyBrowser::collapsed(QtBrowserItem *item)
+
+    This signal is emitted when the \a item is collapsed.
+
+    \sa expanded(), setExpanded()
+*/
+
+/**
+    \fn void QtButtonPropertyBrowser::expanded(QtBrowserItem *item)
+
+    This signal is emitted when the \a item is expanded.
+
+    \sa collapsed(), setExpanded()
+*/
+
+/**
+    Creates a property browser with the given \a parent.
+*/
+QtButtonPropertyBrowser::QtButtonPropertyBrowser(QWidget *parent)
+    : QtAbstractPropertyBrowser(parent)
+{
+    d_ptr = new QtButtonPropertyBrowserPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->init(this);
+}
+
+/**
+    Destroys this property browser.
+
+    Note that the properties that were inserted into this browser are
+    \e not destroyed since they may still be used in other
+    browsers. The properties are owned by the manager that created
+    them.
+
+    \sa QtProperty, QtAbstractPropertyManager
+*/
+QtButtonPropertyBrowser::~QtButtonPropertyBrowser()
+{
+    const QMap<QtButtonPropertyBrowserPrivate::WidgetItem *, QtBrowserItem *>::ConstIterator icend = d_ptr->m_itemToIndex.constEnd();
+    for (QMap<QtButtonPropertyBrowserPrivate::WidgetItem *, QtBrowserItem *>::ConstIterator  it =  d_ptr->m_itemToIndex.constBegin(); it != icend; ++it)
+        delete it.key();
+    delete d_ptr;
+}
+
+/**
+    \reimp
+*/
+void QtButtonPropertyBrowser::itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem)
+{
+    d_ptr->propertyInserted(item, afterItem);
+}
+
+/**
+    \reimp
+*/
+void QtButtonPropertyBrowser::itemRemoved(QtBrowserItem *item)
+{
+    d_ptr->propertyRemoved(item);
+}
+
+/**
+    \reimp
+*/
+void QtButtonPropertyBrowser::itemChanged(QtBrowserItem *item)
+{
+    d_ptr->propertyChanged(item);
+}
+
+/**
+    Sets the \a item to either collapse or expanded, depending on the value of \a expanded.
+
+    \sa isExpanded(), expanded(), collapsed()
+*/
+
+void QtButtonPropertyBrowser::setExpanded(QtBrowserItem *item, bool expanded)
+{
+    QtButtonPropertyBrowserPrivate::WidgetItem *itm = d_ptr->m_indexToItem.value(item);
+    if (itm)
+        d_ptr->setExpanded(itm, expanded);
+}
+
+/**
+    Returns true if the \a item is expanded; otherwise returns false.
+
+    \sa setExpanded()
+*/
+
+bool QtButtonPropertyBrowser::isExpanded(QtBrowserItem *item) const
+{
+    QtButtonPropertyBrowserPrivate::WidgetItem *itm = d_ptr->m_indexToItem.value(item);
+    if (itm)
+        return itm->expanded;
+    return false;
+}
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#include "moc_qtbuttonpropertybrowser.cpp"
diff --git a/Code/Mantid/QtPropertyBrowser/src/qtbuttonpropertybrowser.h b/Code/Mantid/QtPropertyBrowser/src/qtbuttonpropertybrowser.h
index efb0caee180f19b32d291110519024bd4f146f8f..518e047e862b17256c6c9820ac5a895172170bc3 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qtbuttonpropertybrowser.h
+++ b/Code/Mantid/QtPropertyBrowser/src/qtbuttonpropertybrowser.h
@@ -1,135 +1,135 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QTBUTTONPROPERTYBROWSER_H
-#define QTBUTTONPROPERTYBROWSER_H
-
-#include "qtpropertybrowser.h"
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-class QtButtonPropertyBrowserPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtButtonPropertyBrowser : public QtAbstractPropertyBrowser
-{
-    Q_OBJECT
-public:
-
-    QtButtonPropertyBrowser(QWidget *parent = 0);
-    ~QtButtonPropertyBrowser();
-
-    void setExpanded(QtBrowserItem *item, bool expanded);
-    bool isExpanded(QtBrowserItem *item) const;
-
-Q_SIGNALS:
-
-    void collapsed(QtBrowserItem *item);
-    void expanded(QtBrowserItem *item);
-
-protected:
-    virtual void itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem);
-    virtual void itemRemoved(QtBrowserItem *item);
-    virtual void itemChanged(QtBrowserItem *item);
-
-private:
-
-    QtButtonPropertyBrowserPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtButtonPropertyBrowser)
-    Q_DISABLE_COPY(QtButtonPropertyBrowser)
-    Q_PRIVATE_SLOT(d_func(), void slotUpdate())
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed())
-    Q_PRIVATE_SLOT(d_func(), void slotToggled(bool))
-
-};
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#endif
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QTBUTTONPROPERTYBROWSER_H
+#define QTBUTTONPROPERTYBROWSER_H
+
+#include "qtpropertybrowser.h"
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+class QtButtonPropertyBrowserPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtButtonPropertyBrowser : public QtAbstractPropertyBrowser
+{
+    Q_OBJECT
+public:
+
+    QtButtonPropertyBrowser(QWidget *parent = 0);
+    ~QtButtonPropertyBrowser();
+
+    void setExpanded(QtBrowserItem *item, bool expanded);
+    bool isExpanded(QtBrowserItem *item) const;
+
+Q_SIGNALS:
+
+    void collapsed(QtBrowserItem *item);
+    void expanded(QtBrowserItem *item);
+
+protected:
+    virtual void itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem);
+    virtual void itemRemoved(QtBrowserItem *item);
+    virtual void itemChanged(QtBrowserItem *item);
+
+private:
+
+    QtButtonPropertyBrowserPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtButtonPropertyBrowser)
+    Q_DISABLE_COPY(QtButtonPropertyBrowser)
+    Q_PRIVATE_SLOT(d_func(), void slotUpdate())
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed())
+    Q_PRIVATE_SLOT(d_func(), void slotToggled(bool))
+
+};
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#endif
diff --git a/Code/Mantid/QtPropertyBrowser/src/qteditorfactory.cpp b/Code/Mantid/QtPropertyBrowser/src/qteditorfactory.cpp
index fe97eab9df4a4254086c0bc7976c84857b7e1fef..e4a6c3110b2143785fcc4137a3e205e8236af391 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qteditorfactory.cpp
+++ b/Code/Mantid/QtPropertyBrowser/src/qteditorfactory.cpp
@@ -1,2592 +1,2592 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qteditorfactory.h"
-#include "qtpropertybrowserutils_p.h"
-#include <QtGui/QSpinBox>
-#include <QtGui/QScrollBar>
-#include <QtGui/QComboBox>
-#include <QtGui/QAbstractItemView>
-#include <QtGui/QLineEdit>
-#include <QtGui/QDateTimeEdit>
-#include <QtGui/QHBoxLayout>
-#include <QtGui/QMenu>
-#include <QtGui/QKeyEvent>
-#include <QtGui/QApplication>
-#include <QtGui/QLabel>
-#include <QtGui/QToolButton>
-#include <QtGui/QColorDialog>
-#include <QtGui/QFontDialog>
-#include <QtGui/QSpacerItem>
-#include <QtCore/QMap>
-
-#if defined(Q_CC_MSVC)
-#    pragma warning(disable: 4786) /* MS VS 6: truncating debug info after 255 characters */
-#endif
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-// Set a hard coded left margin to account for the indentation
-// of the tree view icon when switching to an editor
-
-static inline void setupTreeViewEditorMargin(QLayout *lt)
-{
-    enum { DecorationMargin = 4 };
-    if (QApplication::layoutDirection() == Qt::LeftToRight)
-        lt->setContentsMargins(DecorationMargin, 0, 0, 0);
-    else
-        lt->setContentsMargins(0, 0, DecorationMargin, 0);
-}
-
-// ---------- EditorFactoryPrivate :
-// Base class for editor factory private classes. Manages mapping of properties to editors and vice versa.
-
-template <class Editor>
-class EditorFactoryPrivate
-{
-public:
-
-    typedef QList<Editor *> EditorList;
-    typedef QMap<QtProperty *, EditorList> PropertyToEditorListMap;
-    typedef QMap<Editor *, QtProperty *> EditorToPropertyMap;
-
-    Editor *createEditor(QtProperty *property, QWidget *parent);
-    void initializeEditor(QtProperty *property, Editor *e);
-    void slotEditorDestroyed(QObject *object);
-
-    PropertyToEditorListMap  m_createdEditors;
-    EditorToPropertyMap m_editorToProperty;
-};
-
-template <class Editor>
-Editor *EditorFactoryPrivate<Editor>::createEditor(QtProperty *property, QWidget *parent)
-{
-    Editor *editor = new Editor(parent);
-    initializeEditor(property, editor);
-    return editor;
-}
-
-template <class Editor>
-void EditorFactoryPrivate<Editor>::initializeEditor(QtProperty *property, Editor *editor)
-{
-    Q_TYPENAME PropertyToEditorListMap::iterator it = m_createdEditors.find(property);
-    if (it == m_createdEditors.end())
-        it = m_createdEditors.insert(property, EditorList());
-    it.value().append(editor);
-    m_editorToProperty.insert(editor, property);
-}
-
-template <class Editor>
-void EditorFactoryPrivate<Editor>::slotEditorDestroyed(QObject *object)
-{
-    const Q_TYPENAME EditorToPropertyMap::iterator ecend = m_editorToProperty.end();
-    for (Q_TYPENAME EditorToPropertyMap::iterator itEditor = m_editorToProperty.begin(); itEditor !=  ecend; ++itEditor) {
-        if (itEditor.key() == object) {
-            Editor *editor = itEditor.key();
-            QtProperty *property = itEditor.value();
-            const Q_TYPENAME PropertyToEditorListMap::iterator pit = m_createdEditors.find(property);
-            if (pit != m_createdEditors.end()) {
-                pit.value().removeAll(editor);
-                if (pit.value().empty())
-                    m_createdEditors.erase(pit);
-            }
-            m_editorToProperty.erase(itEditor);
-            return;
-        }
-    }
-}
-
-// ------------ QtSpinBoxFactory
-
-class QtSpinBoxFactoryPrivate : public EditorFactoryPrivate<QSpinBox>
-{
-    QtSpinBoxFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtSpinBoxFactory)
-public:
-
-    void slotPropertyChanged(QtProperty *property, int value);
-    void slotRangeChanged(QtProperty *property, int min, int max);
-    void slotSingleStepChanged(QtProperty *property, int step);
-    void slotSetValue(int value);
-};
-
-void QtSpinBoxFactoryPrivate::slotPropertyChanged(QtProperty *property, int value)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-    QListIterator<QSpinBox *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QSpinBox *editor = itEditor.next();
-        if (editor->value() != value) {
-            editor->blockSignals(true);
-            editor->setValue(value);
-            editor->blockSignals(false);
-        }
-    }
-}
-
-void QtSpinBoxFactoryPrivate::slotRangeChanged(QtProperty *property, int min, int max)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QtIntPropertyManager *manager = q_ptr->propertyManager(property);
-    if (!manager)
-        return;
-
-    QListIterator<QSpinBox *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QSpinBox *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setRange(min, max);
-        editor->setValue(manager->value(property));
-        editor->blockSignals(false);
-    }
-}
-
-void QtSpinBoxFactoryPrivate::slotSingleStepChanged(QtProperty *property, int step)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-    QListIterator<QSpinBox *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QSpinBox *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setSingleStep(step);
-        editor->blockSignals(false);
-    }
-}
-
-void QtSpinBoxFactoryPrivate::slotSetValue(int value)
-{
-    QObject *object = q_ptr->sender();
-    const QMap<QSpinBox *, QtProperty *>::ConstIterator  ecend = m_editorToProperty.constEnd();
-    for (QMap<QSpinBox *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor !=  ecend; ++itEditor) {
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtIntPropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-    }
-}
-
-/**
-    \class QtSpinBoxFactory
-
-    \brief The QtSpinBoxFactory class provides QSpinBox widgets for
-    properties created by QtIntPropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtIntPropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtSpinBoxFactory::QtSpinBoxFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtIntPropertyManager>(parent)
-{
-    d_ptr = new QtSpinBoxFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtSpinBoxFactory::~QtSpinBoxFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtSpinBoxFactory::connectPropertyManager(QtIntPropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotPropertyChanged(QtProperty *, int)));
-    connect(manager, SIGNAL(rangeChanged(QtProperty *, int, int)),
-                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
-    connect(manager, SIGNAL(singleStepChanged(QtProperty *, int)),
-                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtSpinBoxFactory::createEditor(QtIntPropertyManager *manager, QtProperty *property,
-        QWidget *parent)
-{
-    QSpinBox *editor = d_ptr->createEditor(property, parent);
-    editor->setSingleStep(manager->singleStep(property));
-    editor->setRange(manager->minimum(property), manager->maximum(property));
-    editor->setValue(manager->value(property));
-    editor->setKeyboardTracking(false);
-
-    connect(editor, SIGNAL(valueChanged(int)), this, SLOT(slotSetValue(int)));
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtSpinBoxFactory::disconnectPropertyManager(QtIntPropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotPropertyChanged(QtProperty *, int)));
-    disconnect(manager, SIGNAL(rangeChanged(QtProperty *, int, int)),
-                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
-    disconnect(manager, SIGNAL(singleStepChanged(QtProperty *, int)),
-                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
-}
-
-// QtSliderFactory
-
-class QtSliderFactoryPrivate : public EditorFactoryPrivate<QSlider>
-{
-    QtSliderFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtSliderFactory)
-public:
-    void slotPropertyChanged(QtProperty *property, int value);
-    void slotRangeChanged(QtProperty *property, int min, int max);
-    void slotSingleStepChanged(QtProperty *property, int step);
-    void slotSetValue(int value);
-};
-
-void QtSliderFactoryPrivate::slotPropertyChanged(QtProperty *property, int value)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-    QListIterator<QSlider *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QSlider *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setValue(value);
-        editor->blockSignals(false);
-    }
-}
-
-void QtSliderFactoryPrivate::slotRangeChanged(QtProperty *property, int min, int max)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QtIntPropertyManager *manager = q_ptr->propertyManager(property);
-    if (!manager)
-        return;
-
-    QListIterator<QSlider *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QSlider *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setRange(min, max);
-        editor->setValue(manager->value(property));
-        editor->blockSignals(false);
-    }
-}
-
-void QtSliderFactoryPrivate::slotSingleStepChanged(QtProperty *property, int step)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-    QListIterator<QSlider *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QSlider *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setSingleStep(step);
-        editor->blockSignals(false);
-    }
-}
-
-void QtSliderFactoryPrivate::slotSetValue(int value)
-{
-    QObject *object = q_ptr->sender();
-    const QMap<QSlider *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
-    for (QMap<QSlider *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor ) {
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtIntPropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-    }
-}
-
-/**
-    \class QtSliderFactory
-
-    \brief The QtSliderFactory class provides QSlider widgets for
-    properties created by QtIntPropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtIntPropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtSliderFactory::QtSliderFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtIntPropertyManager>(parent)
-{
-    d_ptr = new QtSliderFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtSliderFactory::~QtSliderFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtSliderFactory::connectPropertyManager(QtIntPropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotPropertyChanged(QtProperty *, int)));
-    connect(manager, SIGNAL(rangeChanged(QtProperty *, int, int)),
-                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
-    connect(manager, SIGNAL(singleStepChanged(QtProperty *, int)),
-                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtSliderFactory::createEditor(QtIntPropertyManager *manager, QtProperty *property,
-        QWidget *parent)
-{
-    QSlider *editor = new QSlider(Qt::Horizontal, parent);
-    d_ptr->initializeEditor(property, editor);
-    editor->setSingleStep(manager->singleStep(property));
-    editor->setRange(manager->minimum(property), manager->maximum(property));
-    editor->setValue(manager->value(property));
-
-    connect(editor, SIGNAL(valueChanged(int)), this, SLOT(slotSetValue(int)));
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtSliderFactory::disconnectPropertyManager(QtIntPropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotPropertyChanged(QtProperty *, int)));
-    disconnect(manager, SIGNAL(rangeChanged(QtProperty *, int, int)),
-                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
-    disconnect(manager, SIGNAL(singleStepChanged(QtProperty *, int)),
-                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
-}
-
-// QtSliderFactory
-
-class QtScrollBarFactoryPrivate : public  EditorFactoryPrivate<QScrollBar>
-{
-    QtScrollBarFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtScrollBarFactory)
-public:
-    void slotPropertyChanged(QtProperty *property, int value);
-    void slotRangeChanged(QtProperty *property, int min, int max);
-    void slotSingleStepChanged(QtProperty *property, int step);
-    void slotSetValue(int value);
-};
-
-void QtScrollBarFactoryPrivate::slotPropertyChanged(QtProperty *property, int value)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QListIterator<QScrollBar *> itEditor( m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QScrollBar *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setValue(value);
-        editor->blockSignals(false);
-    }
-}
-
-void QtScrollBarFactoryPrivate::slotRangeChanged(QtProperty *property, int min, int max)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QtIntPropertyManager *manager = q_ptr->propertyManager(property);
-    if (!manager)
-        return;
-
-    QListIterator<QScrollBar *> itEditor( m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QScrollBar *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setRange(min, max);
-        editor->setValue(manager->value(property));
-        editor->blockSignals(false);
-    }
-}
-
-void QtScrollBarFactoryPrivate::slotSingleStepChanged(QtProperty *property, int step)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-    QListIterator<QScrollBar *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QScrollBar *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setSingleStep(step);
-        editor->blockSignals(false);
-    }
-}
-
-void QtScrollBarFactoryPrivate::slotSetValue(int value)
-{
-    QObject *object = q_ptr->sender();
-    const QMap<QScrollBar *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
-    for (QMap<QScrollBar *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtIntPropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-}
-
-/**
-    \class QtScrollBarFactory
-
-    \brief The QtScrollBarFactory class provides QScrollBar widgets for
-    properties created by QtIntPropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtIntPropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtScrollBarFactory::QtScrollBarFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtIntPropertyManager>(parent)
-{
-    d_ptr = new QtScrollBarFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtScrollBarFactory::~QtScrollBarFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtScrollBarFactory::connectPropertyManager(QtIntPropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotPropertyChanged(QtProperty *, int)));
-    connect(manager, SIGNAL(rangeChanged(QtProperty *, int, int)),
-                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
-    connect(manager, SIGNAL(singleStepChanged(QtProperty *, int)),
-                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtScrollBarFactory::createEditor(QtIntPropertyManager *manager, QtProperty *property,
-        QWidget *parent)
-{
-    QScrollBar *editor = new QScrollBar(Qt::Horizontal, parent);
-    d_ptr->initializeEditor(property, editor);
-    editor->setSingleStep(manager->singleStep(property));
-    editor->setRange(manager->minimum(property), manager->maximum(property));
-    editor->setValue(manager->value(property));
-    connect(editor, SIGNAL(valueChanged(int)), this, SLOT(slotSetValue(int)));
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtScrollBarFactory::disconnectPropertyManager(QtIntPropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotPropertyChanged(QtProperty *, int)));
-    disconnect(manager, SIGNAL(rangeChanged(QtProperty *, int, int)),
-                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
-    disconnect(manager, SIGNAL(singleStepChanged(QtProperty *, int)),
-                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
-}
-
-// QtCheckBoxFactory
-
-class QtCheckBoxFactoryPrivate : public EditorFactoryPrivate<QtBoolEdit>
-{
-    QtCheckBoxFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtCheckBoxFactory)
-public:
-    void slotPropertyChanged(QtProperty *property, bool value);
-    void slotSetValue(bool value);
-};
-
-void QtCheckBoxFactoryPrivate::slotPropertyChanged(QtProperty *property, bool value)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QListIterator<QtBoolEdit *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QtBoolEdit *editor = itEditor.next();
-        editor->blockCheckBoxSignals(true);
-        editor->setChecked(value);
-        editor->blockCheckBoxSignals(false);
-    }
-}
-
-void QtCheckBoxFactoryPrivate::slotSetValue(bool value)
-{
-    QObject *object = q_ptr->sender();
-
-    const QMap<QtBoolEdit *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
-    for (QMap<QtBoolEdit *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend;  ++itEditor)
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtBoolPropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-}
-
-/**
-    \class QtCheckBoxFactory
-
-    \brief The QtCheckBoxFactory class provides QCheckBox widgets for
-    properties created by QtBoolPropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtBoolPropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtCheckBoxFactory::QtCheckBoxFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtBoolPropertyManager>(parent)
-{
-    d_ptr = new QtCheckBoxFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtCheckBoxFactory::~QtCheckBoxFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtCheckBoxFactory::connectPropertyManager(QtBoolPropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, bool)),
-                this, SLOT(slotPropertyChanged(QtProperty *, bool)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtCheckBoxFactory::createEditor(QtBoolPropertyManager *manager, QtProperty *property,
-        QWidget *parent)
-{
-    QtBoolEdit *editor = d_ptr->createEditor(property, parent);
-    editor->setChecked(manager->value(property));
-
-    connect(editor, SIGNAL(toggled(bool)), this, SLOT(slotSetValue(bool)));
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtCheckBoxFactory::disconnectPropertyManager(QtBoolPropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, bool)),
-                this, SLOT(slotPropertyChanged(QtProperty *, bool)));
-}
-
-// QtDoubleSpinBoxFactory
-
-class QtDoubleSpinBoxFactoryPrivate : public EditorFactoryPrivate<QDoubleSpinBox>
-{
-    QtDoubleSpinBoxFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtDoubleSpinBoxFactory)
-public:
-
-    void slotPropertyChanged(QtProperty *property, double value);
-    void slotRangeChanged(QtProperty *property, double min, double max);
-    void slotSingleStepChanged(QtProperty *property, double step);
-    void slotDecimalsChanged(QtProperty *property, int prec);
-    void slotSetValue(double value);
-};
-
-void QtDoubleSpinBoxFactoryPrivate::slotPropertyChanged(QtProperty *property, double value)
-{
-    QList<QDoubleSpinBox *> editors = m_createdEditors[property];
-    QListIterator<QDoubleSpinBox *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QDoubleSpinBox *editor = itEditor.next();
-        if (editor->value() != value) {
-            editor->blockSignals(true);
-            editor->setValue(value);
-            editor->blockSignals(false);
-        }
-    }
-}
-
-void QtDoubleSpinBoxFactoryPrivate::slotRangeChanged(QtProperty *property,
-            double min, double max)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QtDoublePropertyManager *manager = q_ptr->propertyManager(property);
-    if (!manager)
-        return;
-
-    QList<QDoubleSpinBox *> editors = m_createdEditors[property];
-    QListIterator<QDoubleSpinBox *> itEditor(editors);
-    while (itEditor.hasNext()) {
-        QDoubleSpinBox *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setRange(min, max);
-        editor->setValue(manager->value(property));
-        editor->blockSignals(false);
-    }
-}
-
-void QtDoubleSpinBoxFactoryPrivate::slotSingleStepChanged(QtProperty *property, double step)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QtDoublePropertyManager *manager = q_ptr->propertyManager(property);
-    if (!manager)
-        return;
-
-    QList<QDoubleSpinBox *> editors = m_createdEditors[property];
-    QListIterator<QDoubleSpinBox *> itEditor(editors);
-    while (itEditor.hasNext()) {
-        QDoubleSpinBox *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setSingleStep(step);
-        editor->blockSignals(false);
-    }
-}
-
-void QtDoubleSpinBoxFactoryPrivate::slotDecimalsChanged(QtProperty *property, int prec)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QtDoublePropertyManager *manager = q_ptr->propertyManager(property);
-    if (!manager)
-        return;
-
-    QList<QDoubleSpinBox *> editors = m_createdEditors[property];
-    QListIterator<QDoubleSpinBox *> itEditor(editors);
-    while (itEditor.hasNext()) {
-        QDoubleSpinBox *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setDecimals(prec);
-        editor->setValue(manager->value(property));
-        editor->blockSignals(false);
-    }
-}
-
-void QtDoubleSpinBoxFactoryPrivate::slotSetValue(double value)
-{
-    QObject *object = q_ptr->sender();
-    const QMap<QDoubleSpinBox *, QtProperty *>::ConstIterator itcend = m_editorToProperty.constEnd();
-    for (QMap<QDoubleSpinBox *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != itcend; ++itEditor) {
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtDoublePropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-    }
-}
-
-/** \class QtDoubleSpinBoxFactory
-
-    \brief The QtDoubleSpinBoxFactory class provides QDoubleSpinBox
-    widgets for properties created by QtDoublePropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtDoublePropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtDoubleSpinBoxFactory::QtDoubleSpinBoxFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtDoublePropertyManager>(parent)
-{
-    d_ptr = new QtDoubleSpinBoxFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtDoubleSpinBoxFactory::~QtDoubleSpinBoxFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtDoubleSpinBoxFactory::connectPropertyManager(QtDoublePropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, double)),
-                this, SLOT(slotPropertyChanged(QtProperty *, double)));
-    connect(manager, SIGNAL(rangeChanged(QtProperty *, double, double)),
-                this, SLOT(slotRangeChanged(QtProperty *, double, double)));
-    connect(manager, SIGNAL(singleStepChanged(QtProperty *, double)),
-                this, SLOT(slotSingleStepChanged(QtProperty *, double)));
-    connect(manager, SIGNAL(decimalsChanged(QtProperty *, int)),
-                this, SLOT(slotDecimalsChanged(QtProperty *, int)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtDoubleSpinBoxFactory::createEditor(QtDoublePropertyManager *manager,
-        QtProperty *property, QWidget *parent)
-{
-    QDoubleSpinBox *editor = d_ptr->createEditor(property, parent);
-    editor->setSingleStep(manager->singleStep(property));
-    editor->setDecimals(manager->decimals(property));
-    editor->setRange(manager->minimum(property), manager->maximum(property));
-    editor->setValue(manager->value(property));
-    editor->setKeyboardTracking(false);
-
-    connect(editor, SIGNAL(valueChanged(double)), this, SLOT(slotSetValue(double)));
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtDoubleSpinBoxFactory::disconnectPropertyManager(QtDoublePropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, double)),
-                this, SLOT(slotPropertyChanged(QtProperty *, double)));
-    disconnect(manager, SIGNAL(rangeChanged(QtProperty *, double, double)),
-                this, SLOT(slotRangeChanged(QtProperty *, double, double)));
-    disconnect(manager, SIGNAL(singleStepChanged(QtProperty *, double)),
-                this, SLOT(slotSingleStepChanged(QtProperty *, double)));
-    disconnect(manager, SIGNAL(decimalsChanged(QtProperty *, int)),
-                this, SLOT(slotDecimalsChanged(QtProperty *, int)));
-}
-
-// QtLineEditFactory
-
-class QtLineEditFactoryPrivate : public EditorFactoryPrivate<QLineEdit>
-{
-    QtLineEditFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtLineEditFactory)
-public:
-
-    void slotPropertyChanged(QtProperty *property, const QString &value);
-    void slotRegExpChanged(QtProperty *property, const QRegExp &regExp);
-    void slotSetValue(const QString &value);
-};
-
-void QtLineEditFactoryPrivate::slotPropertyChanged(QtProperty *property,
-                const QString &value)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QListIterator<QLineEdit *> itEditor( m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QLineEdit *editor = itEditor.next();
-        if (editor->text() != value)
-            editor->setText(value);
-    }
-}
-
-void QtLineEditFactoryPrivate::slotRegExpChanged(QtProperty *property,
-            const QRegExp &regExp)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QtStringPropertyManager *manager = q_ptr->propertyManager(property);
-    if (!manager)
-        return;
-
-    QListIterator<QLineEdit *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QLineEdit *editor = itEditor.next();
-        editor->blockSignals(true);
-        const QValidator *oldValidator = editor->validator();
-        QValidator *newValidator = 0;
-        if (regExp.isValid()) {
-            newValidator = new QRegExpValidator(regExp, editor);
-        }
-        editor->setValidator(newValidator);
-        if (oldValidator)
-            delete oldValidator;
-        editor->blockSignals(false);
-    }
-}
-
-void QtLineEditFactoryPrivate::slotSetValue(const QString &value)
-{
-    QObject *object = q_ptr->sender();
-    const QMap<QLineEdit *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
-    for (QMap<QLineEdit *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtStringPropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-}
-
-/**
-    \class QtLineEditFactory
-
-    \brief The QtLineEditFactory class provides QLineEdit widgets for
-    properties created by QtStringPropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtStringPropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtLineEditFactory::QtLineEditFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtStringPropertyManager>(parent)
-{
-    d_ptr = new QtLineEditFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtLineEditFactory::~QtLineEditFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtLineEditFactory::connectPropertyManager(QtStringPropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, const QString &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QString &)));
-    connect(manager, SIGNAL(regExpChanged(QtProperty *, const QRegExp &)),
-                this, SLOT(slotRegExpChanged(QtProperty *, const QRegExp &)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtLineEditFactory::createEditor(QtStringPropertyManager *manager,
-        QtProperty *property, QWidget *parent)
-{
-
-    QLineEdit *editor = d_ptr->createEditor(property, parent);
-    QRegExp regExp = manager->regExp(property);
-    if (regExp.isValid()) {
-        QValidator *validator = new QRegExpValidator(regExp, editor);
-        editor->setValidator(validator);
-    }
-    editor->setText(manager->value(property));
-
-    connect(editor, SIGNAL(textEdited(const QString &)),
-                this, SLOT(slotSetValue(const QString &)));
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtLineEditFactory::disconnectPropertyManager(QtStringPropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QString &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QString &)));
-    disconnect(manager, SIGNAL(regExpChanged(QtProperty *, const QRegExp &)),
-                this, SLOT(slotRegExpChanged(QtProperty *, const QRegExp &)));
-}
-
-// QtDateEditFactory
-
-class QtDateEditFactoryPrivate : public EditorFactoryPrivate<QDateEdit>
-{
-    QtDateEditFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtDateEditFactory)
-public:
-
-    void slotPropertyChanged(QtProperty *property, const QDate &value);
-    void slotRangeChanged(QtProperty *property, const QDate &min, const QDate &max);
-    void slotSetValue(const QDate &value);
-};
-
-void QtDateEditFactoryPrivate::slotPropertyChanged(QtProperty *property, const QDate &value)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-    QListIterator<QDateEdit *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QDateEdit *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setDate(value);
-        editor->blockSignals(false);
-    }
-}
-
-void QtDateEditFactoryPrivate::slotRangeChanged(QtProperty *property,
-                const QDate &min, const QDate &max)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QtDatePropertyManager *manager = q_ptr->propertyManager(property);
-    if (!manager)
-        return;
-
-    QListIterator<QDateEdit *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QDateEdit *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setDateRange(min, max);
-        editor->setDate(manager->value(property));
-        editor->blockSignals(false);
-    }
-}
-
-void QtDateEditFactoryPrivate::slotSetValue(const QDate &value)
-{
-    QObject *object = q_ptr->sender();
-    const QMap<QDateEdit *, QtProperty *>::ConstIterator  ecend = m_editorToProperty.constEnd();
-    for (QMap<QDateEdit *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtDatePropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-}
-
-/**
-    \class QtDateEditFactory
-
-    \brief The QtDateEditFactory class provides QDateEdit widgets for
-    properties created by QtDatePropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtDatePropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtDateEditFactory::QtDateEditFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtDatePropertyManager>(parent)
-{
-    d_ptr = new QtDateEditFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtDateEditFactory::~QtDateEditFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtDateEditFactory::connectPropertyManager(QtDatePropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, const QDate &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QDate &)));
-    connect(manager, SIGNAL(rangeChanged(QtProperty *, const QDate &, const QDate &)),
-                this, SLOT(slotRangeChanged(QtProperty *, const QDate &, const QDate &)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtDateEditFactory::createEditor(QtDatePropertyManager *manager, QtProperty *property,
-        QWidget *parent)
-{
-    QDateEdit *editor = d_ptr->createEditor(property, parent);
-    editor->setCalendarPopup(true);
-    editor->setDateRange(manager->minimum(property), manager->maximum(property));
-    editor->setDate(manager->value(property));
-
-    connect(editor, SIGNAL(dateChanged(const QDate &)),
-                this, SLOT(slotSetValue(const QDate &)));
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtDateEditFactory::disconnectPropertyManager(QtDatePropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QDate &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QDate &)));
-    disconnect(manager, SIGNAL(rangeChanged(QtProperty *, const QDate &, const QDate &)),
-                this, SLOT(slotRangeChanged(QtProperty *, const QDate &, const QDate &)));
-}
-
-// QtTimeEditFactory
-
-class QtTimeEditFactoryPrivate : public EditorFactoryPrivate<QTimeEdit>
-{
-    QtTimeEditFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtTimeEditFactory)
-public:
-
-    void slotPropertyChanged(QtProperty *property, const QTime &value);
-    void slotSetValue(const QTime &value);
-};
-
-void QtTimeEditFactoryPrivate::slotPropertyChanged(QtProperty *property, const QTime &value)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-    QListIterator<QTimeEdit *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QTimeEdit *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setTime(value);
-        editor->blockSignals(false);
-    }
-}
-
-void QtTimeEditFactoryPrivate::slotSetValue(const QTime &value)
-{
-    QObject *object = q_ptr->sender();
-    const  QMap<QTimeEdit *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
-    for (QMap<QTimeEdit *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtTimePropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-}
-
-/**
-    \class QtTimeEditFactory
-
-    \brief The QtTimeEditFactory class provides QTimeEdit widgets for
-    properties created by QtTimePropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtTimePropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtTimeEditFactory::QtTimeEditFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtTimePropertyManager>(parent)
-{
-    d_ptr = new QtTimeEditFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtTimeEditFactory::~QtTimeEditFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtTimeEditFactory::connectPropertyManager(QtTimePropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, const QTime &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QTime &)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtTimeEditFactory::createEditor(QtTimePropertyManager *manager, QtProperty *property,
-        QWidget *parent)
-{
-    QTimeEdit *editor = d_ptr->createEditor(property, parent);
-    editor->setTime(manager->value(property));
-
-    connect(editor, SIGNAL(timeChanged(const QTime &)),
-                this, SLOT(slotSetValue(const QTime &)));
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtTimeEditFactory::disconnectPropertyManager(QtTimePropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QTime &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QTime &)));
-}
-
-// QtDateTimeEditFactory
-
-class QtDateTimeEditFactoryPrivate : public EditorFactoryPrivate<QDateTimeEdit>
-{
-    QtDateTimeEditFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtDateTimeEditFactory)
-public:
-
-    void slotPropertyChanged(QtProperty *property, const QDateTime &value);
-    void slotSetValue(const QDateTime &value);
-
-};
-
-void QtDateTimeEditFactoryPrivate::slotPropertyChanged(QtProperty *property,
-            const QDateTime &value)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QListIterator<QDateTimeEdit *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QDateTimeEdit *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setDateTime(value);
-        editor->blockSignals(false);
-    }
-}
-
-void QtDateTimeEditFactoryPrivate::slotSetValue(const QDateTime &value)
-{
-    QObject *object = q_ptr->sender();
-    const  QMap<QDateTimeEdit *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
-    for (QMap<QDateTimeEdit *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend;  ++itEditor)
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtDateTimePropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-}
-
-/**
-    \class QtDateTimeEditFactory
-
-    \brief The QtDateTimeEditFactory class provides QDateTimeEdit
-    widgets for properties created by QtDateTimePropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtDateTimePropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtDateTimeEditFactory::QtDateTimeEditFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtDateTimePropertyManager>(parent)
-{
-    d_ptr = new QtDateTimeEditFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtDateTimeEditFactory::~QtDateTimeEditFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtDateTimeEditFactory::connectPropertyManager(QtDateTimePropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, const QDateTime &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QDateTime &)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtDateTimeEditFactory::createEditor(QtDateTimePropertyManager *manager,
-        QtProperty *property, QWidget *parent)
-{
-    QDateTimeEdit *editor =  d_ptr->createEditor(property, parent);
-    editor->setDateTime(manager->value(property));
-
-    connect(editor, SIGNAL(dateTimeChanged(const QDateTime &)),
-                this, SLOT(slotSetValue(const QDateTime &)));
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtDateTimeEditFactory::disconnectPropertyManager(QtDateTimePropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QDateTime &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QDateTime &)));
-}
-
-// QtKeySequenceEditorFactory
-
-class QtKeySequenceEditorFactoryPrivate : public EditorFactoryPrivate<QtKeySequenceEdit>
-{
-    QtKeySequenceEditorFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtKeySequenceEditorFactory)
-public:
-
-    void slotPropertyChanged(QtProperty *property, const QKeySequence &value);
-    void slotSetValue(const QKeySequence &value);
-};
-
-void QtKeySequenceEditorFactoryPrivate::slotPropertyChanged(QtProperty *property,
-            const QKeySequence &value)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QListIterator<QtKeySequenceEdit *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QtKeySequenceEdit *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setKeySequence(value);
-        editor->blockSignals(false);
-    }
-}
-
-void QtKeySequenceEditorFactoryPrivate::slotSetValue(const QKeySequence &value)
-{
-    QObject *object = q_ptr->sender();
-    const  QMap<QtKeySequenceEdit *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
-    for (QMap<QtKeySequenceEdit *, QtProperty *>::ConstIterator itEditor =  m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtKeySequencePropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-}
-
-/**
-    \class QtKeySequenceEditorFactory
-
-    \brief The QtKeySequenceEditorFactory class provides editor
-    widgets for properties created by QtKeySequencePropertyManager objects.
-
-    \sa QtAbstractEditorFactory
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtKeySequenceEditorFactory::QtKeySequenceEditorFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtKeySequencePropertyManager>(parent)
-{
-    d_ptr = new QtKeySequenceEditorFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtKeySequenceEditorFactory::~QtKeySequenceEditorFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtKeySequenceEditorFactory::connectPropertyManager(QtKeySequencePropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, const QKeySequence &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QKeySequence &)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtKeySequenceEditorFactory::createEditor(QtKeySequencePropertyManager *manager,
-        QtProperty *property, QWidget *parent)
-{
-    QtKeySequenceEdit *editor = d_ptr->createEditor(property, parent);
-    editor->setKeySequence(manager->value(property));
-
-    connect(editor, SIGNAL(keySequenceChanged(const QKeySequence &)),
-                this, SLOT(slotSetValue(const QKeySequence &)));
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtKeySequenceEditorFactory::disconnectPropertyManager(QtKeySequencePropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QKeySequence &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QKeySequence &)));
-}
-
-// QtCharEdit
-
-class QtCharEdit : public QWidget
-{
-    Q_OBJECT
-public:
-    QtCharEdit(QWidget *parent = 0);
-
-    QChar value() const;
-    bool eventFilter(QObject *o, QEvent *e);
-public Q_SLOTS:
-    void setValue(const QChar &value);
-Q_SIGNALS:
-    void valueChanged(const QChar &value);
-protected:
-    void focusInEvent(QFocusEvent *e);
-    void focusOutEvent(QFocusEvent *e);
-    void keyPressEvent(QKeyEvent *e);
-    void keyReleaseEvent(QKeyEvent *e);
-    bool event(QEvent *e);
-private slots:
-    void slotClearChar();
-private:
-    void handleKeyEvent(QKeyEvent *e);
-
-    QChar m_value;
-    QLineEdit *m_lineEdit;
-};
-
-QtCharEdit::QtCharEdit(QWidget *parent)
-    : QWidget(parent),  m_lineEdit(new QLineEdit(this))
-{
-    QHBoxLayout *layout = new QHBoxLayout(this);
-    layout->addWidget(m_lineEdit);
-    layout->setMargin(0);
-    m_lineEdit->installEventFilter(this);
-    m_lineEdit->setReadOnly(true);
-    m_lineEdit->setFocusProxy(this);
-    setFocusPolicy(m_lineEdit->focusPolicy());
-    setAttribute(Qt::WA_InputMethodEnabled);
-}
-
-bool QtCharEdit::eventFilter(QObject *o, QEvent *e)
-{
-    if (o == m_lineEdit && e->type() == QEvent::ContextMenu) {
-        QContextMenuEvent *c = static_cast<QContextMenuEvent *>(e);
-        QMenu *menu = m_lineEdit->createStandardContextMenu();
-        QList<QAction *> actions = menu->actions();
-        QListIterator<QAction *> itAction(actions);
-        while (itAction.hasNext()) {
-            QAction *action = itAction.next();
-            action->setShortcut(QKeySequence());
-            QString actionString = action->text();
-            const int pos = actionString.lastIndexOf(QLatin1Char('\t'));
-            if (pos > 0)
-                actionString = actionString.remove(pos, actionString.length() - pos);
-            action->setText(actionString);
-        }
-        QAction *actionBefore = 0;
-        if (actions.count() > 0)
-            actionBefore = actions[0];
-        QAction *clearAction = new QAction(tr("Clear Char"), menu);
-        menu->insertAction(actionBefore, clearAction);
-        menu->insertSeparator(actionBefore);
-        clearAction->setEnabled(!m_value.isNull());
-        connect(clearAction, SIGNAL(triggered()), this, SLOT(slotClearChar()));
-        menu->exec(c->globalPos());
-        delete menu;
-        e->accept();
-        return true;
-    }
-
-    return QWidget::eventFilter(o, e);
-}
-
-void QtCharEdit::slotClearChar()
-{
-    if (m_value.isNull())
-        return;
-    setValue(QChar());
-    emit valueChanged(m_value);
-}
-
-void QtCharEdit::handleKeyEvent(QKeyEvent *e)
-{
-    const int key = e->key();
-    switch (key) {
-    case Qt::Key_Control:
-    case Qt::Key_Shift:
-    case Qt::Key_Meta:
-    case Qt::Key_Alt:
-    case Qt::Key_Super_L:
-    case Qt::Key_Return:
-        return;
-    default:
-        break;
-    }
-
-    const QString text = e->text();
-    if (text.count() != 1)
-        return;
-
-    const QChar c = text.at(0);
-    if (!c.isPrint())
-        return;
-
-    if (m_value == c)
-        return;
-
-    m_value = c;
-    const QString str = m_value.isNull() ? QString() : QString(m_value);
-    m_lineEdit->setText(str);
-    e->accept();
-    emit valueChanged(m_value);
-}
-
-void QtCharEdit::setValue(const QChar &value)
-{
-    if (value == m_value)
-        return;
-
-    m_value = value;
-    QString str = value.isNull() ? QString() : QString(value);
-    m_lineEdit->setText(str);
-}
-
-QChar QtCharEdit::value() const
-{
-    return m_value;
-}
-
-void QtCharEdit::focusInEvent(QFocusEvent *e)
-{
-    m_lineEdit->event(e);
-    m_lineEdit->selectAll();
-    QWidget::focusInEvent(e);
-}
-
-void QtCharEdit::focusOutEvent(QFocusEvent *e)
-{
-    m_lineEdit->event(e);
-    QWidget::focusOutEvent(e);
-}
-
-void QtCharEdit::keyPressEvent(QKeyEvent *e)
-{
-    handleKeyEvent(e);
-    e->accept();
-}
-
-void QtCharEdit::keyReleaseEvent(QKeyEvent *e)
-{
-    m_lineEdit->event(e);
-}
-
-bool QtCharEdit::event(QEvent *e)
-{
-    switch(e->type()) {
-    case QEvent::Shortcut:
-    case QEvent::ShortcutOverride:
-    case QEvent::KeyRelease:
-        e->accept();
-        return true;
-    default:
-        break;
-    }
-    return QWidget::event(e);
-}
-
-// QtCharEditorFactory
-
-class QtCharEditorFactoryPrivate : public EditorFactoryPrivate<QtCharEdit>
-{
-    QtCharEditorFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtCharEditorFactory)
-public:
-
-    void slotPropertyChanged(QtProperty *property, const QChar &value);
-    void slotSetValue(const QChar &value);
-
-};
-
-void QtCharEditorFactoryPrivate::slotPropertyChanged(QtProperty *property,
-            const QChar &value)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QListIterator<QtCharEdit *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QtCharEdit *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setValue(value);
-        editor->blockSignals(false);
-    }
-}
-
-void QtCharEditorFactoryPrivate::slotSetValue(const QChar &value)
-{
-    QObject *object = q_ptr->sender();
-    const QMap<QtCharEdit *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
-    for (QMap<QtCharEdit *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend;  ++itEditor)
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtCharPropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-}
-
-/**
-    \class QtCharEditorFactory
-
-    \brief The QtCharEditorFactory class provides editor
-    widgets for properties created by QtCharPropertyManager objects.
-
-    \sa QtAbstractEditorFactory
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtCharEditorFactory::QtCharEditorFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtCharPropertyManager>(parent)
-{
-    d_ptr = new QtCharEditorFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtCharEditorFactory::~QtCharEditorFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtCharEditorFactory::connectPropertyManager(QtCharPropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, const QChar &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QChar &)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtCharEditorFactory::createEditor(QtCharPropertyManager *manager,
-        QtProperty *property, QWidget *parent)
-{
-    QtCharEdit *editor = d_ptr->createEditor(property, parent);
-    editor->setValue(manager->value(property));
-
-    connect(editor, SIGNAL(valueChanged(const QChar &)),
-                this, SLOT(slotSetValue(const QChar &)));
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtCharEditorFactory::disconnectPropertyManager(QtCharPropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QChar &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QChar &)));
-}
-
-// QtEnumEditorFactory
-
-class QtEnumEditorFactoryPrivate : public EditorFactoryPrivate<QComboBox>
-{
-    QtEnumEditorFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtEnumEditorFactory)
-public:
-
-    void slotPropertyChanged(QtProperty *property, int value);
-    void slotEnumNamesChanged(QtProperty *property, const QStringList &);
-    void slotEnumIconsChanged(QtProperty *property, const QMap<int, QIcon> &);
-    void slotSetValue(int value);
-};
-
-void QtEnumEditorFactoryPrivate::slotPropertyChanged(QtProperty *property, int value)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QListIterator<QComboBox *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QComboBox *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->setCurrentIndex(value);
-        editor->blockSignals(false);
-    }
-}
-
-void QtEnumEditorFactoryPrivate::slotEnumNamesChanged(QtProperty *property,
-                const QStringList &enumNames)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QtEnumPropertyManager *manager = q_ptr->propertyManager(property);
-    if (!manager)
-        return;
-
-    QMap<int, QIcon> enumIcons = manager->enumIcons(property);
-
-    QListIterator<QComboBox *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QComboBox *editor = itEditor.next();
-        editor->blockSignals(true);
-        editor->clear();
-        editor->addItems(enumNames);
-        const int nameCount = enumNames.count();
-        for (int i = 0; i < nameCount; i++)
-            editor->setItemIcon(i, enumIcons.value(i));
-        editor->setCurrentIndex(manager->value(property));
-        editor->blockSignals(false);
-    }
-}
-
-void QtEnumEditorFactoryPrivate::slotEnumIconsChanged(QtProperty *property,
-                const QMap<int, QIcon> &enumIcons)
-{
-    if (!m_createdEditors.contains(property))
-        return;
-
-    QtEnumPropertyManager *manager = q_ptr->propertyManager(property);
-    if (!manager)
-        return;
-
-    const QStringList enumNames = manager->enumNames(property);
-    QListIterator<QComboBox *> itEditor(m_createdEditors[property]);
-    while (itEditor.hasNext()) {
-        QComboBox *editor = itEditor.next();
-        editor->blockSignals(true);
-        const int nameCount = enumNames.count();
-        for (int i = 0; i < nameCount; i++)
-            editor->setItemIcon(i, enumIcons.value(i));
-        editor->setCurrentIndex(manager->value(property));
-        editor->blockSignals(false);
-    }
-}
-
-void QtEnumEditorFactoryPrivate::slotSetValue(int value)
-{
-    QObject *object = q_ptr->sender();
-    const  QMap<QComboBox *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
-    for (QMap<QComboBox *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtEnumPropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-}
-
-/**
-    \class QtEnumEditorFactory
-
-    \brief The QtEnumEditorFactory class provides QComboBox widgets for
-    properties created by QtEnumPropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtEnumPropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtEnumEditorFactory::QtEnumEditorFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtEnumPropertyManager>(parent)
-{
-    d_ptr = new QtEnumEditorFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtEnumEditorFactory::~QtEnumEditorFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtEnumEditorFactory::connectPropertyManager(QtEnumPropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotPropertyChanged(QtProperty *, int)));
-    connect(manager, SIGNAL(enumNamesChanged(QtProperty *, const QStringList &)),
-                this, SLOT(slotEnumNamesChanged(QtProperty *, const QStringList &)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtEnumEditorFactory::createEditor(QtEnumPropertyManager *manager, QtProperty *property,
-        QWidget *parent)
-{
-    QComboBox *editor = d_ptr->createEditor(property, parent);
-    editor->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed);
-    editor->view()->setTextElideMode(Qt::ElideRight);
-    QStringList enumNames = manager->enumNames(property);
-    editor->addItems(enumNames);
-    QMap<int, QIcon> enumIcons = manager->enumIcons(property);
-    const int enumNamesCount = enumNames.count();
-    for (int i = 0; i < enumNamesCount; i++)
-        editor->setItemIcon(i, enumIcons.value(i));
-    editor->setCurrentIndex(manager->value(property));
-
-    connect(editor, SIGNAL(currentIndexChanged(int)), this, SLOT(slotSetValue(int)));
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtEnumEditorFactory::disconnectPropertyManager(QtEnumPropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotPropertyChanged(QtProperty *, int)));
-    disconnect(manager, SIGNAL(enumNamesChanged(QtProperty *, const QStringList &)),
-                this, SLOT(slotEnumNamesChanged(QtProperty *, const QStringList &)));
-}
-
-// QtCursorEditorFactory
-
-Q_GLOBAL_STATIC(QtCursorDatabase, cursorDatabase)
-
-class QtCursorEditorFactoryPrivate
-{
-    QtCursorEditorFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtCursorEditorFactory)
-public:
-    QtCursorEditorFactoryPrivate();
-
-    void slotPropertyChanged(QtProperty *property, const QCursor &cursor);
-    void slotEnumChanged(QtProperty *property, int value);
-    void slotEditorDestroyed(QObject *object);
-
-    QtEnumEditorFactory *m_enumEditorFactory;
-    QtEnumPropertyManager *m_enumPropertyManager;
-
-    QMap<QtProperty *, QtProperty *> m_propertyToEnum;
-    QMap<QtProperty *, QtProperty *> m_enumToProperty;
-    QMap<QtProperty *, QList<QWidget *> > m_enumToEditors;
-    QMap<QWidget *, QtProperty *> m_editorToEnum;
-    bool m_updatingEnum;
-};
-
-QtCursorEditorFactoryPrivate::QtCursorEditorFactoryPrivate()
-    : m_updatingEnum(false)
-{
-
-}
-
-void QtCursorEditorFactoryPrivate::slotPropertyChanged(QtProperty *property, const QCursor &cursor)
-{
-    // update enum property
-    QtProperty *enumProp = m_propertyToEnum.value(property);
-    if (!enumProp)
-        return;
-
-    m_updatingEnum = true;
-    m_enumPropertyManager->setValue(enumProp, cursorDatabase()->cursorToValue(cursor));
-    m_updatingEnum = false;
-}
-
-void QtCursorEditorFactoryPrivate::slotEnumChanged(QtProperty *property, int value)
-{
-    if (m_updatingEnum)
-        return;
-    // update cursor property
-    QtProperty *prop = m_enumToProperty.value(property);
-    if (!prop)
-        return;
-    QtCursorPropertyManager *cursorManager = q_ptr->propertyManager(prop);
-    if (!cursorManager)
-        return;
-#ifndef QT_NO_CURSOR
-    cursorManager->setValue(prop, QCursor(cursorDatabase()->valueToCursor(value)));
-#endif
-}
-
-void QtCursorEditorFactoryPrivate::slotEditorDestroyed(QObject *object)
-{
-    // remove from m_editorToEnum map;
-    // remove from m_enumToEditors map;
-    // if m_enumToEditors doesn't contains more editors delete enum property;
-    const  QMap<QWidget *, QtProperty *>::ConstIterator ecend = m_editorToEnum.constEnd();
-    for (QMap<QWidget *, QtProperty *>::ConstIterator itEditor = m_editorToEnum.constBegin(); itEditor != ecend; ++itEditor)
-        if (itEditor.key() == object) {
-            QWidget *editor = itEditor.key();
-            QtProperty *enumProp = itEditor.value();
-            m_editorToEnum.remove(editor);
-            m_enumToEditors[enumProp].removeAll(editor);
-            if (m_enumToEditors[enumProp].isEmpty()) {
-                m_enumToEditors.remove(enumProp);
-                QtProperty *property = m_enumToProperty.value(enumProp);
-                m_enumToProperty.remove(enumProp);
-                m_propertyToEnum.remove(property);
-                delete enumProp;
-            }
-            return;
-        }
-}
-
-/**
-    \class QtCursorEditorFactory
-
-    \brief The QtCursorEditorFactory class provides QComboBox widgets for
-    properties created by QtCursorPropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtCursorPropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtCursorEditorFactory::QtCursorEditorFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtCursorPropertyManager>(parent)
-{
-    d_ptr = new QtCursorEditorFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_enumEditorFactory = new QtEnumEditorFactory(this);
-    d_ptr->m_enumPropertyManager = new QtEnumPropertyManager(this);
-    connect(d_ptr->m_enumPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotEnumChanged(QtProperty *, int)));
-    d_ptr->m_enumEditorFactory->addPropertyManager(d_ptr->m_enumPropertyManager);
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtCursorEditorFactory::~QtCursorEditorFactory()
-{
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtCursorEditorFactory::connectPropertyManager(QtCursorPropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty *, const QCursor &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QCursor &)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtCursorEditorFactory::createEditor(QtCursorPropertyManager *manager, QtProperty *property,
-        QWidget *parent)
-{
-    QtProperty *enumProp = 0;
-    if (d_ptr->m_propertyToEnum.contains(property)) {
-        enumProp = d_ptr->m_propertyToEnum[property];
-    } else {
-        enumProp = d_ptr->m_enumPropertyManager->addProperty(property->propertyName());
-        d_ptr->m_enumPropertyManager->setEnumNames(enumProp, cursorDatabase()->cursorShapeNames());
-        d_ptr->m_enumPropertyManager->setEnumIcons(enumProp, cursorDatabase()->cursorShapeIcons());
-#ifndef QT_NO_CURSOR
-        d_ptr->m_enumPropertyManager->setValue(enumProp, cursorDatabase()->cursorToValue(manager->value(property)));
-#endif
-        d_ptr->m_propertyToEnum[property] = enumProp;
-        d_ptr->m_enumToProperty[enumProp] = property;
-    }
-    QtAbstractEditorFactoryBase *af = d_ptr->m_enumEditorFactory;
-    QWidget *editor = af->createEditor(enumProp, parent);
-    d_ptr->m_enumToEditors[enumProp].append(editor);
-    d_ptr->m_editorToEnum[editor] = enumProp;
-    connect(editor, SIGNAL(destroyed(QObject *)),
-                this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtCursorEditorFactory::disconnectPropertyManager(QtCursorPropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QCursor &)),
-                this, SLOT(slotPropertyChanged(QtProperty *, const QCursor &)));
-}
-
-// QtColorEditWidget
-
-class QtColorEditWidget : public QWidget {
-    Q_OBJECT
-
-public:
-    QtColorEditWidget(QWidget *parent);
-
-    bool eventFilter(QObject *obj, QEvent *ev);
-
-public Q_SLOTS:
-    void setValue(const QColor &value);
-
-private Q_SLOTS:
-    void buttonClicked();
-
-Q_SIGNALS:
-    void valueChanged(const QColor &value);
-
-private:
-    QColor m_color;
-    QLabel *m_pixmapLabel;
-    QLabel *m_label;
-    QToolButton *m_button;
-};
-
-QtColorEditWidget::QtColorEditWidget(QWidget *parent) :
-    QWidget(parent),
-    m_pixmapLabel(new QLabel),
-    m_label(new QLabel),
-    m_button(new QToolButton)
-{
-    QHBoxLayout *lt = new QHBoxLayout(this);
-    setupTreeViewEditorMargin(lt);
-    lt->setSpacing(0);
-    lt->addWidget(m_pixmapLabel);
-    lt->addWidget(m_label);
-    lt->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Ignored));
-
-    m_button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Ignored);
-    m_button->setFixedWidth(20);
-    setFocusProxy(m_button);
-    setFocusPolicy(m_button->focusPolicy());
-    m_button->setText(tr("..."));
-    m_button->installEventFilter(this);
-    connect(m_button, SIGNAL(clicked()), this, SLOT(buttonClicked()));
-    lt->addWidget(m_button);
-    m_pixmapLabel->setPixmap(QtPropertyBrowserUtils::brushValuePixmap(QBrush(m_color)));
-    m_label->setText(QtPropertyBrowserUtils::colorValueText(m_color));
-}
-
-void QtColorEditWidget::setValue(const QColor &c)
-{
-    if (m_color != c) {
-        m_color = c;
-        m_pixmapLabel->setPixmap(QtPropertyBrowserUtils::brushValuePixmap(QBrush(c)));
-        m_label->setText(QtPropertyBrowserUtils::colorValueText(c));
-    }
-}
-
-void QtColorEditWidget::buttonClicked()
-{
-    bool ok = false;
-    QRgb oldRgba = m_color.rgba();
-    QRgb newRgba = QColorDialog::getRgba(oldRgba, &ok, this);
-    if (ok && newRgba != oldRgba) {
-        setValue(QColor::fromRgba(newRgba));
-        emit valueChanged(m_color);
-    }
-}
-
-bool QtColorEditWidget::eventFilter(QObject *obj, QEvent *ev)
-{
-    if (obj == m_button) {
-        switch (ev->type()) {
-        case QEvent::KeyPress:
-        case QEvent::KeyRelease: { // Prevent the QToolButton from handling Enter/Escape meant control the delegate
-            switch (static_cast<const QKeyEvent*>(ev)->key()) {
-            case Qt::Key_Escape:
-            case Qt::Key_Enter:
-            case Qt::Key_Return:
-                ev->ignore();
-                return true;
-            default:
-                break;
-            }
-        }
-            break;
-        default:
-            break;
-        }
-    }
-    return QWidget::eventFilter(obj, ev);
-}
-
-// QtColorEditorFactoryPrivate
-
-class QtColorEditorFactoryPrivate : public EditorFactoryPrivate<QtColorEditWidget>
-{
-    QtColorEditorFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtColorEditorFactory)
-public:
-
-    void slotPropertyChanged(QtProperty *property, const QColor &value);
-    void slotSetValue(const QColor &value);
-};
-
-void QtColorEditorFactoryPrivate::slotPropertyChanged(QtProperty *property,
-                const QColor &value)
-{
-    const PropertyToEditorListMap::iterator it = m_createdEditors.find(property);
-    if (it == m_createdEditors.end())
-        return;
-    QListIterator<QtColorEditWidget *> itEditor(it.value());
-
-    while (itEditor.hasNext())
-        itEditor.next()->setValue(value);
-}
-
-void QtColorEditorFactoryPrivate::slotSetValue(const QColor &value)
-{
-    QObject *object = q_ptr->sender();
-    const EditorToPropertyMap::ConstIterator ecend = m_editorToProperty.constEnd();
-    for (EditorToPropertyMap::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtColorPropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-}
-
-/**
-    \class QtColorEditorFactory
-
-    \brief The QtColorEditorFactory class provides color editing  for
-    properties created by QtColorPropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtColorPropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtColorEditorFactory::QtColorEditorFactory(QObject *parent) :
-    QtAbstractEditorFactory<QtColorPropertyManager>(parent),
-    d_ptr(new QtColorEditorFactoryPrivate())
-{
-    d_ptr->q_ptr = this;
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtColorEditorFactory::~QtColorEditorFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtColorEditorFactory::connectPropertyManager(QtColorPropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty*,QColor)),
-            this, SLOT(slotPropertyChanged(QtProperty*,QColor)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtColorEditorFactory::createEditor(QtColorPropertyManager *manager,
-        QtProperty *property, QWidget *parent)
-{
-    QtColorEditWidget *editor = d_ptr->createEditor(property, parent);
-    editor->setValue(manager->value(property));
-    connect(editor, SIGNAL(valueChanged(QColor)), this, SLOT(slotSetValue(QColor)));
-    connect(editor, SIGNAL(destroyed(QObject *)), this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtColorEditorFactory::disconnectPropertyManager(QtColorPropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty*,QColor)), this, SLOT(slotPropertyChanged(QtProperty*,QColor)));
-}
-
-// QtFontEditWidget
-
-class QtFontEditWidget : public QWidget {
-    Q_OBJECT
-
-public:
-    QtFontEditWidget(QWidget *parent);
-
-    bool eventFilter(QObject *obj, QEvent *ev);
-
-public Q_SLOTS:
-    void setValue(const QFont &value);
-
-private Q_SLOTS:
-    void buttonClicked();
-
-Q_SIGNALS:
-    void valueChanged(const QFont &value);
-
-private:
-    QFont m_font;
-    QLabel *m_pixmapLabel;
-    QLabel *m_label;
-    QToolButton *m_button;
-};
-
-QtFontEditWidget::QtFontEditWidget(QWidget *parent) :
-    QWidget(parent),
-    m_pixmapLabel(new QLabel),
-    m_label(new QLabel),
-    m_button(new QToolButton)
-{
-    QHBoxLayout *lt = new QHBoxLayout(this);
-    setupTreeViewEditorMargin(lt);
-    lt->setSpacing(0);
-    lt->addWidget(m_pixmapLabel);
-    lt->addWidget(m_label);
-    lt->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Ignored));
-
-    m_button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Ignored);
-    m_button->setFixedWidth(20);
-    setFocusProxy(m_button);
-    setFocusPolicy(m_button->focusPolicy());
-    m_button->setText(tr("..."));
-    m_button->installEventFilter(this);
-    connect(m_button, SIGNAL(clicked()), this, SLOT(buttonClicked()));
-    lt->addWidget(m_button);
-    m_pixmapLabel->setPixmap(QtPropertyBrowserUtils::fontValuePixmap(m_font));
-    m_label->setText(QtPropertyBrowserUtils::fontValueText(m_font));
-}
-
-void QtFontEditWidget::setValue(const QFont &f)
-{
-    if (m_font != f) {
-        m_font = f;
-        m_pixmapLabel->setPixmap(QtPropertyBrowserUtils::fontValuePixmap(f));
-        m_label->setText(QtPropertyBrowserUtils::fontValueText(f));
-    }
-}
-
-void QtFontEditWidget::buttonClicked()
-{
-    bool ok = false;
-    QFont newFont = QFontDialog::getFont(&ok, m_font, this, tr("Select Font"));
-    if (ok && newFont != m_font) {
-        QFont f = m_font;
-        // prevent mask for unchanged attributes, don't change other attributes (like kerning, etc...)
-        if (m_font.family() != newFont.family())
-            f.setFamily(newFont.family());
-        if (m_font.pointSize() != newFont.pointSize())
-            f.setPointSize(newFont.pointSize());
-        if (m_font.bold() != newFont.bold())
-            f.setBold(newFont.bold());
-        if (m_font.italic() != newFont.italic())
-            f.setItalic(newFont.italic());
-        if (m_font.underline() != newFont.underline())
-            f.setUnderline(newFont.underline());
-        if (m_font.strikeOut() != newFont.strikeOut())
-            f.setStrikeOut(newFont.strikeOut());
-        setValue(f);
-        emit valueChanged(m_font);
-    }
-}
-
-bool QtFontEditWidget::eventFilter(QObject *obj, QEvent *ev)
-{
-    if (obj == m_button) {
-        switch (ev->type()) {
-        case QEvent::KeyPress:
-        case QEvent::KeyRelease: { // Prevent the QToolButton from handling Enter/Escape meant control the delegate
-            switch (static_cast<const QKeyEvent*>(ev)->key()) {
-            case Qt::Key_Escape:
-            case Qt::Key_Enter:
-            case Qt::Key_Return:
-                ev->ignore();
-                return true;
-            default:
-                break;
-            }
-        }
-            break;
-        default:
-            break;
-        }
-    }
-    return QWidget::eventFilter(obj, ev);
-}
-
-// QtFontEditorFactoryPrivate
-
-class QtFontEditorFactoryPrivate : public EditorFactoryPrivate<QtFontEditWidget>
-{
-    QtFontEditorFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtFontEditorFactory)
-public:
-
-    void slotPropertyChanged(QtProperty *property, const QFont &value);
-    void slotSetValue(const QFont &value);
-};
-
-void QtFontEditorFactoryPrivate::slotPropertyChanged(QtProperty *property,
-                const QFont &value)
-{
-    const PropertyToEditorListMap::iterator it = m_createdEditors.find(property);
-    if (it == m_createdEditors.end())
-        return;
-    QListIterator<QtFontEditWidget *> itEditor(it.value());
-
-    while (itEditor.hasNext())
-        itEditor.next()->setValue(value);
-}
-
-void QtFontEditorFactoryPrivate::slotSetValue(const QFont &value)
-{
-    QObject *object = q_ptr->sender();
-    const EditorToPropertyMap::ConstIterator ecend = m_editorToProperty.constEnd();
-    for (EditorToPropertyMap::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
-        if (itEditor.key() == object) {
-            QtProperty *property = itEditor.value();
-            QtFontPropertyManager *manager = q_ptr->propertyManager(property);
-            if (!manager)
-                return;
-            manager->setValue(property, value);
-            return;
-        }
-}
-
-/**
-    \class QtFontEditorFactory
-
-    \brief The QtFontEditorFactory class provides font editing for
-    properties created by QtFontPropertyManager objects.
-
-    \sa QtAbstractEditorFactory, QtFontPropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtFontEditorFactory::QtFontEditorFactory(QObject *parent) :
-    QtAbstractEditorFactory<QtFontPropertyManager>(parent),
-    d_ptr(new QtFontEditorFactoryPrivate())
-{
-    d_ptr->q_ptr = this;
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtFontEditorFactory::~QtFontEditorFactory()
-{
-    qDeleteAll(d_ptr->m_editorToProperty.keys());
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtFontEditorFactory::connectPropertyManager(QtFontPropertyManager *manager)
-{
-    connect(manager, SIGNAL(valueChanged(QtProperty*,QFont)),
-            this, SLOT(slotPropertyChanged(QtProperty*,QFont)));
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtFontEditorFactory::createEditor(QtFontPropertyManager *manager,
-        QtProperty *property, QWidget *parent)
-{
-    QtFontEditWidget *editor = d_ptr->createEditor(property, parent);
-    editor->setValue(manager->value(property));
-    connect(editor, SIGNAL(valueChanged(QFont)), this, SLOT(slotSetValue(QFont)));
-    connect(editor, SIGNAL(destroyed(QObject *)), this, SLOT(slotEditorDestroyed(QObject *)));
-    return editor;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtFontEditorFactory::disconnectPropertyManager(QtFontPropertyManager *manager)
-{
-    disconnect(manager, SIGNAL(valueChanged(QtProperty*,QFont)), this, SLOT(slotPropertyChanged(QtProperty*,QFont)));
-}
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#include "moc_qteditorfactory.cpp"
-#include "qteditorfactory.moc"
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qteditorfactory.h"
+#include "qtpropertybrowserutils_p.h"
+#include <QtGui/QSpinBox>
+#include <QtGui/QScrollBar>
+#include <QtGui/QComboBox>
+#include <QtGui/QAbstractItemView>
+#include <QtGui/QLineEdit>
+#include <QtGui/QDateTimeEdit>
+#include <QtGui/QHBoxLayout>
+#include <QtGui/QMenu>
+#include <QtGui/QKeyEvent>
+#include <QtGui/QApplication>
+#include <QtGui/QLabel>
+#include <QtGui/QToolButton>
+#include <QtGui/QColorDialog>
+#include <QtGui/QFontDialog>
+#include <QtGui/QSpacerItem>
+#include <QtCore/QMap>
+
+#if defined(Q_CC_MSVC)
+#    pragma warning(disable: 4786) /* MS VS 6: truncating debug info after 255 characters */
+#endif
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+// Set a hard coded left margin to account for the indentation
+// of the tree view icon when switching to an editor
+
+static inline void setupTreeViewEditorMargin(QLayout *lt)
+{
+    enum { DecorationMargin = 4 };
+    if (QApplication::layoutDirection() == Qt::LeftToRight)
+        lt->setContentsMargins(DecorationMargin, 0, 0, 0);
+    else
+        lt->setContentsMargins(0, 0, DecorationMargin, 0);
+}
+
+// ---------- EditorFactoryPrivate :
+// Base class for editor factory private classes. Manages mapping of properties to editors and vice versa.
+
+template <class Editor>
+class EditorFactoryPrivate
+{
+public:
+
+    typedef QList<Editor *> EditorList;
+    typedef QMap<QtProperty *, EditorList> PropertyToEditorListMap;
+    typedef QMap<Editor *, QtProperty *> EditorToPropertyMap;
+
+    Editor *createEditor(QtProperty *property, QWidget *parent);
+    void initializeEditor(QtProperty *property, Editor *e);
+    void slotEditorDestroyed(QObject *object);
+
+    PropertyToEditorListMap  m_createdEditors;
+    EditorToPropertyMap m_editorToProperty;
+};
+
+template <class Editor>
+Editor *EditorFactoryPrivate<Editor>::createEditor(QtProperty *property, QWidget *parent)
+{
+    Editor *editor = new Editor(parent);
+    initializeEditor(property, editor);
+    return editor;
+}
+
+template <class Editor>
+void EditorFactoryPrivate<Editor>::initializeEditor(QtProperty *property, Editor *editor)
+{
+    Q_TYPENAME PropertyToEditorListMap::iterator it = m_createdEditors.find(property);
+    if (it == m_createdEditors.end())
+        it = m_createdEditors.insert(property, EditorList());
+    it.value().append(editor);
+    m_editorToProperty.insert(editor, property);
+}
+
+template <class Editor>
+void EditorFactoryPrivate<Editor>::slotEditorDestroyed(QObject *object)
+{
+    const Q_TYPENAME EditorToPropertyMap::iterator ecend = m_editorToProperty.end();
+    for (Q_TYPENAME EditorToPropertyMap::iterator itEditor = m_editorToProperty.begin(); itEditor !=  ecend; ++itEditor) {
+        if (itEditor.key() == object) {
+            Editor *editor = itEditor.key();
+            QtProperty *property = itEditor.value();
+            const Q_TYPENAME PropertyToEditorListMap::iterator pit = m_createdEditors.find(property);
+            if (pit != m_createdEditors.end()) {
+                pit.value().removeAll(editor);
+                if (pit.value().empty())
+                    m_createdEditors.erase(pit);
+            }
+            m_editorToProperty.erase(itEditor);
+            return;
+        }
+    }
+}
+
+// ------------ QtSpinBoxFactory
+
+class QtSpinBoxFactoryPrivate : public EditorFactoryPrivate<QSpinBox>
+{
+    QtSpinBoxFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtSpinBoxFactory)
+public:
+
+    void slotPropertyChanged(QtProperty *property, int value);
+    void slotRangeChanged(QtProperty *property, int min, int max);
+    void slotSingleStepChanged(QtProperty *property, int step);
+    void slotSetValue(int value);
+};
+
+void QtSpinBoxFactoryPrivate::slotPropertyChanged(QtProperty *property, int value)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+    QListIterator<QSpinBox *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QSpinBox *editor = itEditor.next();
+        if (editor->value() != value) {
+            editor->blockSignals(true);
+            editor->setValue(value);
+            editor->blockSignals(false);
+        }
+    }
+}
+
+void QtSpinBoxFactoryPrivate::slotRangeChanged(QtProperty *property, int min, int max)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QtIntPropertyManager *manager = q_ptr->propertyManager(property);
+    if (!manager)
+        return;
+
+    QListIterator<QSpinBox *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QSpinBox *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setRange(min, max);
+        editor->setValue(manager->value(property));
+        editor->blockSignals(false);
+    }
+}
+
+void QtSpinBoxFactoryPrivate::slotSingleStepChanged(QtProperty *property, int step)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+    QListIterator<QSpinBox *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QSpinBox *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setSingleStep(step);
+        editor->blockSignals(false);
+    }
+}
+
+void QtSpinBoxFactoryPrivate::slotSetValue(int value)
+{
+    QObject *object = q_ptr->sender();
+    const QMap<QSpinBox *, QtProperty *>::ConstIterator  ecend = m_editorToProperty.constEnd();
+    for (QMap<QSpinBox *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor !=  ecend; ++itEditor) {
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtIntPropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+    }
+}
+
+/**
+    \class QtSpinBoxFactory
+
+    \brief The QtSpinBoxFactory class provides QSpinBox widgets for
+    properties created by QtIntPropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtIntPropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtSpinBoxFactory::QtSpinBoxFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtIntPropertyManager>(parent)
+{
+    d_ptr = new QtSpinBoxFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtSpinBoxFactory::~QtSpinBoxFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtSpinBoxFactory::connectPropertyManager(QtIntPropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotPropertyChanged(QtProperty *, int)));
+    connect(manager, SIGNAL(rangeChanged(QtProperty *, int, int)),
+                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
+    connect(manager, SIGNAL(singleStepChanged(QtProperty *, int)),
+                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtSpinBoxFactory::createEditor(QtIntPropertyManager *manager, QtProperty *property,
+        QWidget *parent)
+{
+    QSpinBox *editor = d_ptr->createEditor(property, parent);
+    editor->setSingleStep(manager->singleStep(property));
+    editor->setRange(manager->minimum(property), manager->maximum(property));
+    editor->setValue(manager->value(property));
+    editor->setKeyboardTracking(false);
+
+    connect(editor, SIGNAL(valueChanged(int)), this, SLOT(slotSetValue(int)));
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtSpinBoxFactory::disconnectPropertyManager(QtIntPropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotPropertyChanged(QtProperty *, int)));
+    disconnect(manager, SIGNAL(rangeChanged(QtProperty *, int, int)),
+                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
+    disconnect(manager, SIGNAL(singleStepChanged(QtProperty *, int)),
+                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
+}
+
+// QtSliderFactory
+
+class QtSliderFactoryPrivate : public EditorFactoryPrivate<QSlider>
+{
+    QtSliderFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtSliderFactory)
+public:
+    void slotPropertyChanged(QtProperty *property, int value);
+    void slotRangeChanged(QtProperty *property, int min, int max);
+    void slotSingleStepChanged(QtProperty *property, int step);
+    void slotSetValue(int value);
+};
+
+void QtSliderFactoryPrivate::slotPropertyChanged(QtProperty *property, int value)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+    QListIterator<QSlider *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QSlider *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setValue(value);
+        editor->blockSignals(false);
+    }
+}
+
+void QtSliderFactoryPrivate::slotRangeChanged(QtProperty *property, int min, int max)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QtIntPropertyManager *manager = q_ptr->propertyManager(property);
+    if (!manager)
+        return;
+
+    QListIterator<QSlider *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QSlider *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setRange(min, max);
+        editor->setValue(manager->value(property));
+        editor->blockSignals(false);
+    }
+}
+
+void QtSliderFactoryPrivate::slotSingleStepChanged(QtProperty *property, int step)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+    QListIterator<QSlider *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QSlider *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setSingleStep(step);
+        editor->blockSignals(false);
+    }
+}
+
+void QtSliderFactoryPrivate::slotSetValue(int value)
+{
+    QObject *object = q_ptr->sender();
+    const QMap<QSlider *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
+    for (QMap<QSlider *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor ) {
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtIntPropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+    }
+}
+
+/**
+    \class QtSliderFactory
+
+    \brief The QtSliderFactory class provides QSlider widgets for
+    properties created by QtIntPropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtIntPropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtSliderFactory::QtSliderFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtIntPropertyManager>(parent)
+{
+    d_ptr = new QtSliderFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtSliderFactory::~QtSliderFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtSliderFactory::connectPropertyManager(QtIntPropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotPropertyChanged(QtProperty *, int)));
+    connect(manager, SIGNAL(rangeChanged(QtProperty *, int, int)),
+                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
+    connect(manager, SIGNAL(singleStepChanged(QtProperty *, int)),
+                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtSliderFactory::createEditor(QtIntPropertyManager *manager, QtProperty *property,
+        QWidget *parent)
+{
+    QSlider *editor = new QSlider(Qt::Horizontal, parent);
+    d_ptr->initializeEditor(property, editor);
+    editor->setSingleStep(manager->singleStep(property));
+    editor->setRange(manager->minimum(property), manager->maximum(property));
+    editor->setValue(manager->value(property));
+
+    connect(editor, SIGNAL(valueChanged(int)), this, SLOT(slotSetValue(int)));
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtSliderFactory::disconnectPropertyManager(QtIntPropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotPropertyChanged(QtProperty *, int)));
+    disconnect(manager, SIGNAL(rangeChanged(QtProperty *, int, int)),
+                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
+    disconnect(manager, SIGNAL(singleStepChanged(QtProperty *, int)),
+                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
+}
+
+// QtSliderFactory
+
+class QtScrollBarFactoryPrivate : public  EditorFactoryPrivate<QScrollBar>
+{
+    QtScrollBarFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtScrollBarFactory)
+public:
+    void slotPropertyChanged(QtProperty *property, int value);
+    void slotRangeChanged(QtProperty *property, int min, int max);
+    void slotSingleStepChanged(QtProperty *property, int step);
+    void slotSetValue(int value);
+};
+
+void QtScrollBarFactoryPrivate::slotPropertyChanged(QtProperty *property, int value)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QListIterator<QScrollBar *> itEditor( m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QScrollBar *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setValue(value);
+        editor->blockSignals(false);
+    }
+}
+
+void QtScrollBarFactoryPrivate::slotRangeChanged(QtProperty *property, int min, int max)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QtIntPropertyManager *manager = q_ptr->propertyManager(property);
+    if (!manager)
+        return;
+
+    QListIterator<QScrollBar *> itEditor( m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QScrollBar *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setRange(min, max);
+        editor->setValue(manager->value(property));
+        editor->blockSignals(false);
+    }
+}
+
+void QtScrollBarFactoryPrivate::slotSingleStepChanged(QtProperty *property, int step)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+    QListIterator<QScrollBar *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QScrollBar *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setSingleStep(step);
+        editor->blockSignals(false);
+    }
+}
+
+void QtScrollBarFactoryPrivate::slotSetValue(int value)
+{
+    QObject *object = q_ptr->sender();
+    const QMap<QScrollBar *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
+    for (QMap<QScrollBar *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtIntPropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+}
+
+/**
+    \class QtScrollBarFactory
+
+    \brief The QtScrollBarFactory class provides QScrollBar widgets for
+    properties created by QtIntPropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtIntPropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtScrollBarFactory::QtScrollBarFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtIntPropertyManager>(parent)
+{
+    d_ptr = new QtScrollBarFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtScrollBarFactory::~QtScrollBarFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtScrollBarFactory::connectPropertyManager(QtIntPropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotPropertyChanged(QtProperty *, int)));
+    connect(manager, SIGNAL(rangeChanged(QtProperty *, int, int)),
+                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
+    connect(manager, SIGNAL(singleStepChanged(QtProperty *, int)),
+                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtScrollBarFactory::createEditor(QtIntPropertyManager *manager, QtProperty *property,
+        QWidget *parent)
+{
+    QScrollBar *editor = new QScrollBar(Qt::Horizontal, parent);
+    d_ptr->initializeEditor(property, editor);
+    editor->setSingleStep(manager->singleStep(property));
+    editor->setRange(manager->minimum(property), manager->maximum(property));
+    editor->setValue(manager->value(property));
+    connect(editor, SIGNAL(valueChanged(int)), this, SLOT(slotSetValue(int)));
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtScrollBarFactory::disconnectPropertyManager(QtIntPropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotPropertyChanged(QtProperty *, int)));
+    disconnect(manager, SIGNAL(rangeChanged(QtProperty *, int, int)),
+                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
+    disconnect(manager, SIGNAL(singleStepChanged(QtProperty *, int)),
+                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
+}
+
+// QtCheckBoxFactory
+
+class QtCheckBoxFactoryPrivate : public EditorFactoryPrivate<QtBoolEdit>
+{
+    QtCheckBoxFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtCheckBoxFactory)
+public:
+    void slotPropertyChanged(QtProperty *property, bool value);
+    void slotSetValue(bool value);
+};
+
+void QtCheckBoxFactoryPrivate::slotPropertyChanged(QtProperty *property, bool value)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QListIterator<QtBoolEdit *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QtBoolEdit *editor = itEditor.next();
+        editor->blockCheckBoxSignals(true);
+        editor->setChecked(value);
+        editor->blockCheckBoxSignals(false);
+    }
+}
+
+void QtCheckBoxFactoryPrivate::slotSetValue(bool value)
+{
+    QObject *object = q_ptr->sender();
+
+    const QMap<QtBoolEdit *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
+    for (QMap<QtBoolEdit *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend;  ++itEditor)
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtBoolPropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+}
+
+/**
+    \class QtCheckBoxFactory
+
+    \brief The QtCheckBoxFactory class provides QCheckBox widgets for
+    properties created by QtBoolPropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtBoolPropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtCheckBoxFactory::QtCheckBoxFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtBoolPropertyManager>(parent)
+{
+    d_ptr = new QtCheckBoxFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtCheckBoxFactory::~QtCheckBoxFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtCheckBoxFactory::connectPropertyManager(QtBoolPropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, bool)),
+                this, SLOT(slotPropertyChanged(QtProperty *, bool)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtCheckBoxFactory::createEditor(QtBoolPropertyManager *manager, QtProperty *property,
+        QWidget *parent)
+{
+    QtBoolEdit *editor = d_ptr->createEditor(property, parent);
+    editor->setChecked(manager->value(property));
+
+    connect(editor, SIGNAL(toggled(bool)), this, SLOT(slotSetValue(bool)));
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtCheckBoxFactory::disconnectPropertyManager(QtBoolPropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, bool)),
+                this, SLOT(slotPropertyChanged(QtProperty *, bool)));
+}
+
+// QtDoubleSpinBoxFactory
+
+class QtDoubleSpinBoxFactoryPrivate : public EditorFactoryPrivate<QDoubleSpinBox>
+{
+    QtDoubleSpinBoxFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtDoubleSpinBoxFactory)
+public:
+
+    void slotPropertyChanged(QtProperty *property, double value);
+    void slotRangeChanged(QtProperty *property, double min, double max);
+    void slotSingleStepChanged(QtProperty *property, double step);
+    void slotDecimalsChanged(QtProperty *property, int prec);
+    void slotSetValue(double value);
+};
+
+void QtDoubleSpinBoxFactoryPrivate::slotPropertyChanged(QtProperty *property, double value)
+{
+    QList<QDoubleSpinBox *> editors = m_createdEditors[property];
+    QListIterator<QDoubleSpinBox *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QDoubleSpinBox *editor = itEditor.next();
+        if (editor->value() != value) {
+            editor->blockSignals(true);
+            editor->setValue(value);
+            editor->blockSignals(false);
+        }
+    }
+}
+
+void QtDoubleSpinBoxFactoryPrivate::slotRangeChanged(QtProperty *property,
+            double min, double max)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QtDoublePropertyManager *manager = q_ptr->propertyManager(property);
+    if (!manager)
+        return;
+
+    QList<QDoubleSpinBox *> editors = m_createdEditors[property];
+    QListIterator<QDoubleSpinBox *> itEditor(editors);
+    while (itEditor.hasNext()) {
+        QDoubleSpinBox *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setRange(min, max);
+        editor->setValue(manager->value(property));
+        editor->blockSignals(false);
+    }
+}
+
+void QtDoubleSpinBoxFactoryPrivate::slotSingleStepChanged(QtProperty *property, double step)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QtDoublePropertyManager *manager = q_ptr->propertyManager(property);
+    if (!manager)
+        return;
+
+    QList<QDoubleSpinBox *> editors = m_createdEditors[property];
+    QListIterator<QDoubleSpinBox *> itEditor(editors);
+    while (itEditor.hasNext()) {
+        QDoubleSpinBox *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setSingleStep(step);
+        editor->blockSignals(false);
+    }
+}
+
+void QtDoubleSpinBoxFactoryPrivate::slotDecimalsChanged(QtProperty *property, int prec)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QtDoublePropertyManager *manager = q_ptr->propertyManager(property);
+    if (!manager)
+        return;
+
+    QList<QDoubleSpinBox *> editors = m_createdEditors[property];
+    QListIterator<QDoubleSpinBox *> itEditor(editors);
+    while (itEditor.hasNext()) {
+        QDoubleSpinBox *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setDecimals(prec);
+        editor->setValue(manager->value(property));
+        editor->blockSignals(false);
+    }
+}
+
+void QtDoubleSpinBoxFactoryPrivate::slotSetValue(double value)
+{
+    QObject *object = q_ptr->sender();
+    const QMap<QDoubleSpinBox *, QtProperty *>::ConstIterator itcend = m_editorToProperty.constEnd();
+    for (QMap<QDoubleSpinBox *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != itcend; ++itEditor) {
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtDoublePropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+    }
+}
+
+/** \class QtDoubleSpinBoxFactory
+
+    \brief The QtDoubleSpinBoxFactory class provides QDoubleSpinBox
+    widgets for properties created by QtDoublePropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtDoublePropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtDoubleSpinBoxFactory::QtDoubleSpinBoxFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtDoublePropertyManager>(parent)
+{
+    d_ptr = new QtDoubleSpinBoxFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtDoubleSpinBoxFactory::~QtDoubleSpinBoxFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtDoubleSpinBoxFactory::connectPropertyManager(QtDoublePropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, double)),
+                this, SLOT(slotPropertyChanged(QtProperty *, double)));
+    connect(manager, SIGNAL(rangeChanged(QtProperty *, double, double)),
+                this, SLOT(slotRangeChanged(QtProperty *, double, double)));
+    connect(manager, SIGNAL(singleStepChanged(QtProperty *, double)),
+                this, SLOT(slotSingleStepChanged(QtProperty *, double)));
+    connect(manager, SIGNAL(decimalsChanged(QtProperty *, int)),
+                this, SLOT(slotDecimalsChanged(QtProperty *, int)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtDoubleSpinBoxFactory::createEditor(QtDoublePropertyManager *manager,
+        QtProperty *property, QWidget *parent)
+{
+    QDoubleSpinBox *editor = d_ptr->createEditor(property, parent);
+    editor->setSingleStep(manager->singleStep(property));
+    editor->setDecimals(manager->decimals(property));
+    editor->setRange(manager->minimum(property), manager->maximum(property));
+    editor->setValue(manager->value(property));
+    editor->setKeyboardTracking(false);
+
+    connect(editor, SIGNAL(valueChanged(double)), this, SLOT(slotSetValue(double)));
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtDoubleSpinBoxFactory::disconnectPropertyManager(QtDoublePropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, double)),
+                this, SLOT(slotPropertyChanged(QtProperty *, double)));
+    disconnect(manager, SIGNAL(rangeChanged(QtProperty *, double, double)),
+                this, SLOT(slotRangeChanged(QtProperty *, double, double)));
+    disconnect(manager, SIGNAL(singleStepChanged(QtProperty *, double)),
+                this, SLOT(slotSingleStepChanged(QtProperty *, double)));
+    disconnect(manager, SIGNAL(decimalsChanged(QtProperty *, int)),
+                this, SLOT(slotDecimalsChanged(QtProperty *, int)));
+}
+
+// QtLineEditFactory
+
+class QtLineEditFactoryPrivate : public EditorFactoryPrivate<QLineEdit>
+{
+    QtLineEditFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtLineEditFactory)
+public:
+
+    void slotPropertyChanged(QtProperty *property, const QString &value);
+    void slotRegExpChanged(QtProperty *property, const QRegExp &regExp);
+    void slotSetValue(const QString &value);
+};
+
+void QtLineEditFactoryPrivate::slotPropertyChanged(QtProperty *property,
+                const QString &value)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QListIterator<QLineEdit *> itEditor( m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QLineEdit *editor = itEditor.next();
+        if (editor->text() != value)
+            editor->setText(value);
+    }
+}
+
+void QtLineEditFactoryPrivate::slotRegExpChanged(QtProperty *property,
+            const QRegExp &regExp)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QtStringPropertyManager *manager = q_ptr->propertyManager(property);
+    if (!manager)
+        return;
+
+    QListIterator<QLineEdit *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QLineEdit *editor = itEditor.next();
+        editor->blockSignals(true);
+        const QValidator *oldValidator = editor->validator();
+        QValidator *newValidator = 0;
+        if (regExp.isValid()) {
+            newValidator = new QRegExpValidator(regExp, editor);
+        }
+        editor->setValidator(newValidator);
+        if (oldValidator)
+            delete oldValidator;
+        editor->blockSignals(false);
+    }
+}
+
+void QtLineEditFactoryPrivate::slotSetValue(const QString &value)
+{
+    QObject *object = q_ptr->sender();
+    const QMap<QLineEdit *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
+    for (QMap<QLineEdit *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtStringPropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+}
+
+/**
+    \class QtLineEditFactory
+
+    \brief The QtLineEditFactory class provides QLineEdit widgets for
+    properties created by QtStringPropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtStringPropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtLineEditFactory::QtLineEditFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtStringPropertyManager>(parent)
+{
+    d_ptr = new QtLineEditFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtLineEditFactory::~QtLineEditFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtLineEditFactory::connectPropertyManager(QtStringPropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, const QString &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QString &)));
+    connect(manager, SIGNAL(regExpChanged(QtProperty *, const QRegExp &)),
+                this, SLOT(slotRegExpChanged(QtProperty *, const QRegExp &)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtLineEditFactory::createEditor(QtStringPropertyManager *manager,
+        QtProperty *property, QWidget *parent)
+{
+
+    QLineEdit *editor = d_ptr->createEditor(property, parent);
+    QRegExp regExp = manager->regExp(property);
+    if (regExp.isValid()) {
+        QValidator *validator = new QRegExpValidator(regExp, editor);
+        editor->setValidator(validator);
+    }
+    editor->setText(manager->value(property));
+
+    connect(editor, SIGNAL(textEdited(const QString &)),
+                this, SLOT(slotSetValue(const QString &)));
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtLineEditFactory::disconnectPropertyManager(QtStringPropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QString &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QString &)));
+    disconnect(manager, SIGNAL(regExpChanged(QtProperty *, const QRegExp &)),
+                this, SLOT(slotRegExpChanged(QtProperty *, const QRegExp &)));
+}
+
+// QtDateEditFactory
+
+class QtDateEditFactoryPrivate : public EditorFactoryPrivate<QDateEdit>
+{
+    QtDateEditFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtDateEditFactory)
+public:
+
+    void slotPropertyChanged(QtProperty *property, const QDate &value);
+    void slotRangeChanged(QtProperty *property, const QDate &min, const QDate &max);
+    void slotSetValue(const QDate &value);
+};
+
+void QtDateEditFactoryPrivate::slotPropertyChanged(QtProperty *property, const QDate &value)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+    QListIterator<QDateEdit *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QDateEdit *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setDate(value);
+        editor->blockSignals(false);
+    }
+}
+
+void QtDateEditFactoryPrivate::slotRangeChanged(QtProperty *property,
+                const QDate &min, const QDate &max)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QtDatePropertyManager *manager = q_ptr->propertyManager(property);
+    if (!manager)
+        return;
+
+    QListIterator<QDateEdit *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QDateEdit *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setDateRange(min, max);
+        editor->setDate(manager->value(property));
+        editor->blockSignals(false);
+    }
+}
+
+void QtDateEditFactoryPrivate::slotSetValue(const QDate &value)
+{
+    QObject *object = q_ptr->sender();
+    const QMap<QDateEdit *, QtProperty *>::ConstIterator  ecend = m_editorToProperty.constEnd();
+    for (QMap<QDateEdit *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtDatePropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+}
+
+/**
+    \class QtDateEditFactory
+
+    \brief The QtDateEditFactory class provides QDateEdit widgets for
+    properties created by QtDatePropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtDatePropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtDateEditFactory::QtDateEditFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtDatePropertyManager>(parent)
+{
+    d_ptr = new QtDateEditFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtDateEditFactory::~QtDateEditFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtDateEditFactory::connectPropertyManager(QtDatePropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, const QDate &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QDate &)));
+    connect(manager, SIGNAL(rangeChanged(QtProperty *, const QDate &, const QDate &)),
+                this, SLOT(slotRangeChanged(QtProperty *, const QDate &, const QDate &)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtDateEditFactory::createEditor(QtDatePropertyManager *manager, QtProperty *property,
+        QWidget *parent)
+{
+    QDateEdit *editor = d_ptr->createEditor(property, parent);
+    editor->setCalendarPopup(true);
+    editor->setDateRange(manager->minimum(property), manager->maximum(property));
+    editor->setDate(manager->value(property));
+
+    connect(editor, SIGNAL(dateChanged(const QDate &)),
+                this, SLOT(slotSetValue(const QDate &)));
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtDateEditFactory::disconnectPropertyManager(QtDatePropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QDate &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QDate &)));
+    disconnect(manager, SIGNAL(rangeChanged(QtProperty *, const QDate &, const QDate &)),
+                this, SLOT(slotRangeChanged(QtProperty *, const QDate &, const QDate &)));
+}
+
+// QtTimeEditFactory
+
+class QtTimeEditFactoryPrivate : public EditorFactoryPrivate<QTimeEdit>
+{
+    QtTimeEditFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtTimeEditFactory)
+public:
+
+    void slotPropertyChanged(QtProperty *property, const QTime &value);
+    void slotSetValue(const QTime &value);
+};
+
+void QtTimeEditFactoryPrivate::slotPropertyChanged(QtProperty *property, const QTime &value)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+    QListIterator<QTimeEdit *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QTimeEdit *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setTime(value);
+        editor->blockSignals(false);
+    }
+}
+
+void QtTimeEditFactoryPrivate::slotSetValue(const QTime &value)
+{
+    QObject *object = q_ptr->sender();
+    const  QMap<QTimeEdit *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
+    for (QMap<QTimeEdit *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtTimePropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+}
+
+/**
+    \class QtTimeEditFactory
+
+    \brief The QtTimeEditFactory class provides QTimeEdit widgets for
+    properties created by QtTimePropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtTimePropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtTimeEditFactory::QtTimeEditFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtTimePropertyManager>(parent)
+{
+    d_ptr = new QtTimeEditFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtTimeEditFactory::~QtTimeEditFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtTimeEditFactory::connectPropertyManager(QtTimePropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, const QTime &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QTime &)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtTimeEditFactory::createEditor(QtTimePropertyManager *manager, QtProperty *property,
+        QWidget *parent)
+{
+    QTimeEdit *editor = d_ptr->createEditor(property, parent);
+    editor->setTime(manager->value(property));
+
+    connect(editor, SIGNAL(timeChanged(const QTime &)),
+                this, SLOT(slotSetValue(const QTime &)));
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtTimeEditFactory::disconnectPropertyManager(QtTimePropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QTime &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QTime &)));
+}
+
+// QtDateTimeEditFactory
+
+class QtDateTimeEditFactoryPrivate : public EditorFactoryPrivate<QDateTimeEdit>
+{
+    QtDateTimeEditFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtDateTimeEditFactory)
+public:
+
+    void slotPropertyChanged(QtProperty *property, const QDateTime &value);
+    void slotSetValue(const QDateTime &value);
+
+};
+
+void QtDateTimeEditFactoryPrivate::slotPropertyChanged(QtProperty *property,
+            const QDateTime &value)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QListIterator<QDateTimeEdit *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QDateTimeEdit *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setDateTime(value);
+        editor->blockSignals(false);
+    }
+}
+
+void QtDateTimeEditFactoryPrivate::slotSetValue(const QDateTime &value)
+{
+    QObject *object = q_ptr->sender();
+    const  QMap<QDateTimeEdit *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
+    for (QMap<QDateTimeEdit *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend;  ++itEditor)
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtDateTimePropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+}
+
+/**
+    \class QtDateTimeEditFactory
+
+    \brief The QtDateTimeEditFactory class provides QDateTimeEdit
+    widgets for properties created by QtDateTimePropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtDateTimePropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtDateTimeEditFactory::QtDateTimeEditFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtDateTimePropertyManager>(parent)
+{
+    d_ptr = new QtDateTimeEditFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtDateTimeEditFactory::~QtDateTimeEditFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtDateTimeEditFactory::connectPropertyManager(QtDateTimePropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, const QDateTime &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QDateTime &)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtDateTimeEditFactory::createEditor(QtDateTimePropertyManager *manager,
+        QtProperty *property, QWidget *parent)
+{
+    QDateTimeEdit *editor =  d_ptr->createEditor(property, parent);
+    editor->setDateTime(manager->value(property));
+
+    connect(editor, SIGNAL(dateTimeChanged(const QDateTime &)),
+                this, SLOT(slotSetValue(const QDateTime &)));
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtDateTimeEditFactory::disconnectPropertyManager(QtDateTimePropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QDateTime &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QDateTime &)));
+}
+
+// QtKeySequenceEditorFactory
+
+class QtKeySequenceEditorFactoryPrivate : public EditorFactoryPrivate<QtKeySequenceEdit>
+{
+    QtKeySequenceEditorFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtKeySequenceEditorFactory)
+public:
+
+    void slotPropertyChanged(QtProperty *property, const QKeySequence &value);
+    void slotSetValue(const QKeySequence &value);
+};
+
+void QtKeySequenceEditorFactoryPrivate::slotPropertyChanged(QtProperty *property,
+            const QKeySequence &value)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QListIterator<QtKeySequenceEdit *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QtKeySequenceEdit *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setKeySequence(value);
+        editor->blockSignals(false);
+    }
+}
+
+void QtKeySequenceEditorFactoryPrivate::slotSetValue(const QKeySequence &value)
+{
+    QObject *object = q_ptr->sender();
+    const  QMap<QtKeySequenceEdit *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
+    for (QMap<QtKeySequenceEdit *, QtProperty *>::ConstIterator itEditor =  m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtKeySequencePropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+}
+
+/**
+    \class QtKeySequenceEditorFactory
+
+    \brief The QtKeySequenceEditorFactory class provides editor
+    widgets for properties created by QtKeySequencePropertyManager objects.
+
+    \sa QtAbstractEditorFactory
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtKeySequenceEditorFactory::QtKeySequenceEditorFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtKeySequencePropertyManager>(parent)
+{
+    d_ptr = new QtKeySequenceEditorFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtKeySequenceEditorFactory::~QtKeySequenceEditorFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtKeySequenceEditorFactory::connectPropertyManager(QtKeySequencePropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, const QKeySequence &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QKeySequence &)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtKeySequenceEditorFactory::createEditor(QtKeySequencePropertyManager *manager,
+        QtProperty *property, QWidget *parent)
+{
+    QtKeySequenceEdit *editor = d_ptr->createEditor(property, parent);
+    editor->setKeySequence(manager->value(property));
+
+    connect(editor, SIGNAL(keySequenceChanged(const QKeySequence &)),
+                this, SLOT(slotSetValue(const QKeySequence &)));
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtKeySequenceEditorFactory::disconnectPropertyManager(QtKeySequencePropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QKeySequence &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QKeySequence &)));
+}
+
+// QtCharEdit
+
+class QtCharEdit : public QWidget
+{
+    Q_OBJECT
+public:
+    QtCharEdit(QWidget *parent = 0);
+
+    QChar value() const;
+    bool eventFilter(QObject *o, QEvent *e);
+public Q_SLOTS:
+    void setValue(const QChar &value);
+Q_SIGNALS:
+    void valueChanged(const QChar &value);
+protected:
+    void focusInEvent(QFocusEvent *e);
+    void focusOutEvent(QFocusEvent *e);
+    void keyPressEvent(QKeyEvent *e);
+    void keyReleaseEvent(QKeyEvent *e);
+    bool event(QEvent *e);
+private slots:
+    void slotClearChar();
+private:
+    void handleKeyEvent(QKeyEvent *e);
+
+    QChar m_value;
+    QLineEdit *m_lineEdit;
+};
+
+QtCharEdit::QtCharEdit(QWidget *parent)
+    : QWidget(parent),  m_lineEdit(new QLineEdit(this))
+{
+    QHBoxLayout *layout = new QHBoxLayout(this);
+    layout->addWidget(m_lineEdit);
+    layout->setMargin(0);
+    m_lineEdit->installEventFilter(this);
+    m_lineEdit->setReadOnly(true);
+    m_lineEdit->setFocusProxy(this);
+    setFocusPolicy(m_lineEdit->focusPolicy());
+    setAttribute(Qt::WA_InputMethodEnabled);
+}
+
+bool QtCharEdit::eventFilter(QObject *o, QEvent *e)
+{
+    if (o == m_lineEdit && e->type() == QEvent::ContextMenu) {
+        QContextMenuEvent *c = static_cast<QContextMenuEvent *>(e);
+        QMenu *menu = m_lineEdit->createStandardContextMenu();
+        QList<QAction *> actions = menu->actions();
+        QListIterator<QAction *> itAction(actions);
+        while (itAction.hasNext()) {
+            QAction *action = itAction.next();
+            action->setShortcut(QKeySequence());
+            QString actionString = action->text();
+            const int pos = actionString.lastIndexOf(QLatin1Char('\t'));
+            if (pos > 0)
+                actionString = actionString.remove(pos, actionString.length() - pos);
+            action->setText(actionString);
+        }
+        QAction *actionBefore = 0;
+        if (actions.count() > 0)
+            actionBefore = actions[0];
+        QAction *clearAction = new QAction(tr("Clear Char"), menu);
+        menu->insertAction(actionBefore, clearAction);
+        menu->insertSeparator(actionBefore);
+        clearAction->setEnabled(!m_value.isNull());
+        connect(clearAction, SIGNAL(triggered()), this, SLOT(slotClearChar()));
+        menu->exec(c->globalPos());
+        delete menu;
+        e->accept();
+        return true;
+    }
+
+    return QWidget::eventFilter(o, e);
+}
+
+void QtCharEdit::slotClearChar()
+{
+    if (m_value.isNull())
+        return;
+    setValue(QChar());
+    emit valueChanged(m_value);
+}
+
+void QtCharEdit::handleKeyEvent(QKeyEvent *e)
+{
+    const int key = e->key();
+    switch (key) {
+    case Qt::Key_Control:
+    case Qt::Key_Shift:
+    case Qt::Key_Meta:
+    case Qt::Key_Alt:
+    case Qt::Key_Super_L:
+    case Qt::Key_Return:
+        return;
+    default:
+        break;
+    }
+
+    const QString text = e->text();
+    if (text.count() != 1)
+        return;
+
+    const QChar c = text.at(0);
+    if (!c.isPrint())
+        return;
+
+    if (m_value == c)
+        return;
+
+    m_value = c;
+    const QString str = m_value.isNull() ? QString() : QString(m_value);
+    m_lineEdit->setText(str);
+    e->accept();
+    emit valueChanged(m_value);
+}
+
+void QtCharEdit::setValue(const QChar &value)
+{
+    if (value == m_value)
+        return;
+
+    m_value = value;
+    QString str = value.isNull() ? QString() : QString(value);
+    m_lineEdit->setText(str);
+}
+
+QChar QtCharEdit::value() const
+{
+    return m_value;
+}
+
+void QtCharEdit::focusInEvent(QFocusEvent *e)
+{
+    m_lineEdit->event(e);
+    m_lineEdit->selectAll();
+    QWidget::focusInEvent(e);
+}
+
+void QtCharEdit::focusOutEvent(QFocusEvent *e)
+{
+    m_lineEdit->event(e);
+    QWidget::focusOutEvent(e);
+}
+
+void QtCharEdit::keyPressEvent(QKeyEvent *e)
+{
+    handleKeyEvent(e);
+    e->accept();
+}
+
+void QtCharEdit::keyReleaseEvent(QKeyEvent *e)
+{
+    m_lineEdit->event(e);
+}
+
+bool QtCharEdit::event(QEvent *e)
+{
+    switch(e->type()) {
+    case QEvent::Shortcut:
+    case QEvent::ShortcutOverride:
+    case QEvent::KeyRelease:
+        e->accept();
+        return true;
+    default:
+        break;
+    }
+    return QWidget::event(e);
+}
+
+// QtCharEditorFactory
+
+class QtCharEditorFactoryPrivate : public EditorFactoryPrivate<QtCharEdit>
+{
+    QtCharEditorFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtCharEditorFactory)
+public:
+
+    void slotPropertyChanged(QtProperty *property, const QChar &value);
+    void slotSetValue(const QChar &value);
+
+};
+
+void QtCharEditorFactoryPrivate::slotPropertyChanged(QtProperty *property,
+            const QChar &value)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QListIterator<QtCharEdit *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QtCharEdit *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setValue(value);
+        editor->blockSignals(false);
+    }
+}
+
+void QtCharEditorFactoryPrivate::slotSetValue(const QChar &value)
+{
+    QObject *object = q_ptr->sender();
+    const QMap<QtCharEdit *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
+    for (QMap<QtCharEdit *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend;  ++itEditor)
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtCharPropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+}
+
+/**
+    \class QtCharEditorFactory
+
+    \brief The QtCharEditorFactory class provides editor
+    widgets for properties created by QtCharPropertyManager objects.
+
+    \sa QtAbstractEditorFactory
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtCharEditorFactory::QtCharEditorFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtCharPropertyManager>(parent)
+{
+    d_ptr = new QtCharEditorFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtCharEditorFactory::~QtCharEditorFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtCharEditorFactory::connectPropertyManager(QtCharPropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, const QChar &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QChar &)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtCharEditorFactory::createEditor(QtCharPropertyManager *manager,
+        QtProperty *property, QWidget *parent)
+{
+    QtCharEdit *editor = d_ptr->createEditor(property, parent);
+    editor->setValue(manager->value(property));
+
+    connect(editor, SIGNAL(valueChanged(const QChar &)),
+                this, SLOT(slotSetValue(const QChar &)));
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtCharEditorFactory::disconnectPropertyManager(QtCharPropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QChar &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QChar &)));
+}
+
+// QtEnumEditorFactory
+
+class QtEnumEditorFactoryPrivate : public EditorFactoryPrivate<QComboBox>
+{
+    QtEnumEditorFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtEnumEditorFactory)
+public:
+
+    void slotPropertyChanged(QtProperty *property, int value);
+    void slotEnumNamesChanged(QtProperty *property, const QStringList &);
+    void slotEnumIconsChanged(QtProperty *property, const QMap<int, QIcon> &);
+    void slotSetValue(int value);
+};
+
+void QtEnumEditorFactoryPrivate::slotPropertyChanged(QtProperty *property, int value)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QListIterator<QComboBox *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QComboBox *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->setCurrentIndex(value);
+        editor->blockSignals(false);
+    }
+}
+
+void QtEnumEditorFactoryPrivate::slotEnumNamesChanged(QtProperty *property,
+                const QStringList &enumNames)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QtEnumPropertyManager *manager = q_ptr->propertyManager(property);
+    if (!manager)
+        return;
+
+    QMap<int, QIcon> enumIcons = manager->enumIcons(property);
+
+    QListIterator<QComboBox *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QComboBox *editor = itEditor.next();
+        editor->blockSignals(true);
+        editor->clear();
+        editor->addItems(enumNames);
+        const int nameCount = enumNames.count();
+        for (int i = 0; i < nameCount; i++)
+            editor->setItemIcon(i, enumIcons.value(i));
+        editor->setCurrentIndex(manager->value(property));
+        editor->blockSignals(false);
+    }
+}
+
+void QtEnumEditorFactoryPrivate::slotEnumIconsChanged(QtProperty *property,
+                const QMap<int, QIcon> &enumIcons)
+{
+    if (!m_createdEditors.contains(property))
+        return;
+
+    QtEnumPropertyManager *manager = q_ptr->propertyManager(property);
+    if (!manager)
+        return;
+
+    const QStringList enumNames = manager->enumNames(property);
+    QListIterator<QComboBox *> itEditor(m_createdEditors[property]);
+    while (itEditor.hasNext()) {
+        QComboBox *editor = itEditor.next();
+        editor->blockSignals(true);
+        const int nameCount = enumNames.count();
+        for (int i = 0; i < nameCount; i++)
+            editor->setItemIcon(i, enumIcons.value(i));
+        editor->setCurrentIndex(manager->value(property));
+        editor->blockSignals(false);
+    }
+}
+
+void QtEnumEditorFactoryPrivate::slotSetValue(int value)
+{
+    QObject *object = q_ptr->sender();
+    const  QMap<QComboBox *, QtProperty *>::ConstIterator ecend = m_editorToProperty.constEnd();
+    for (QMap<QComboBox *, QtProperty *>::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtEnumPropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+}
+
+/**
+    \class QtEnumEditorFactory
+
+    \brief The QtEnumEditorFactory class provides QComboBox widgets for
+    properties created by QtEnumPropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtEnumPropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtEnumEditorFactory::QtEnumEditorFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtEnumPropertyManager>(parent)
+{
+    d_ptr = new QtEnumEditorFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtEnumEditorFactory::~QtEnumEditorFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtEnumEditorFactory::connectPropertyManager(QtEnumPropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotPropertyChanged(QtProperty *, int)));
+    connect(manager, SIGNAL(enumNamesChanged(QtProperty *, const QStringList &)),
+                this, SLOT(slotEnumNamesChanged(QtProperty *, const QStringList &)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtEnumEditorFactory::createEditor(QtEnumPropertyManager *manager, QtProperty *property,
+        QWidget *parent)
+{
+    QComboBox *editor = d_ptr->createEditor(property, parent);
+    editor->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed);
+    editor->view()->setTextElideMode(Qt::ElideRight);
+    QStringList enumNames = manager->enumNames(property);
+    editor->addItems(enumNames);
+    QMap<int, QIcon> enumIcons = manager->enumIcons(property);
+    const int enumNamesCount = enumNames.count();
+    for (int i = 0; i < enumNamesCount; i++)
+        editor->setItemIcon(i, enumIcons.value(i));
+    editor->setCurrentIndex(manager->value(property));
+
+    connect(editor, SIGNAL(currentIndexChanged(int)), this, SLOT(slotSetValue(int)));
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtEnumEditorFactory::disconnectPropertyManager(QtEnumPropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotPropertyChanged(QtProperty *, int)));
+    disconnect(manager, SIGNAL(enumNamesChanged(QtProperty *, const QStringList &)),
+                this, SLOT(slotEnumNamesChanged(QtProperty *, const QStringList &)));
+}
+
+// QtCursorEditorFactory
+
+Q_GLOBAL_STATIC(QtCursorDatabase, cursorDatabase)
+
+class QtCursorEditorFactoryPrivate
+{
+    QtCursorEditorFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtCursorEditorFactory)
+public:
+    QtCursorEditorFactoryPrivate();
+
+    void slotPropertyChanged(QtProperty *property, const QCursor &cursor);
+    void slotEnumChanged(QtProperty *property, int value);
+    void slotEditorDestroyed(QObject *object);
+
+    QtEnumEditorFactory *m_enumEditorFactory;
+    QtEnumPropertyManager *m_enumPropertyManager;
+
+    QMap<QtProperty *, QtProperty *> m_propertyToEnum;
+    QMap<QtProperty *, QtProperty *> m_enumToProperty;
+    QMap<QtProperty *, QList<QWidget *> > m_enumToEditors;
+    QMap<QWidget *, QtProperty *> m_editorToEnum;
+    bool m_updatingEnum;
+};
+
+QtCursorEditorFactoryPrivate::QtCursorEditorFactoryPrivate()
+    : m_updatingEnum(false)
+{
+
+}
+
+void QtCursorEditorFactoryPrivate::slotPropertyChanged(QtProperty *property, const QCursor &cursor)
+{
+    // update enum property
+    QtProperty *enumProp = m_propertyToEnum.value(property);
+    if (!enumProp)
+        return;
+
+    m_updatingEnum = true;
+    m_enumPropertyManager->setValue(enumProp, cursorDatabase()->cursorToValue(cursor));
+    m_updatingEnum = false;
+}
+
+void QtCursorEditorFactoryPrivate::slotEnumChanged(QtProperty *property, int value)
+{
+    if (m_updatingEnum)
+        return;
+    // update cursor property
+    QtProperty *prop = m_enumToProperty.value(property);
+    if (!prop)
+        return;
+    QtCursorPropertyManager *cursorManager = q_ptr->propertyManager(prop);
+    if (!cursorManager)
+        return;
+#ifndef QT_NO_CURSOR
+    cursorManager->setValue(prop, QCursor(cursorDatabase()->valueToCursor(value)));
+#endif
+}
+
+void QtCursorEditorFactoryPrivate::slotEditorDestroyed(QObject *object)
+{
+    // remove from m_editorToEnum map;
+    // remove from m_enumToEditors map;
+    // if m_enumToEditors doesn't contains more editors delete enum property;
+    const  QMap<QWidget *, QtProperty *>::ConstIterator ecend = m_editorToEnum.constEnd();
+    for (QMap<QWidget *, QtProperty *>::ConstIterator itEditor = m_editorToEnum.constBegin(); itEditor != ecend; ++itEditor)
+        if (itEditor.key() == object) {
+            QWidget *editor = itEditor.key();
+            QtProperty *enumProp = itEditor.value();
+            m_editorToEnum.remove(editor);
+            m_enumToEditors[enumProp].removeAll(editor);
+            if (m_enumToEditors[enumProp].isEmpty()) {
+                m_enumToEditors.remove(enumProp);
+                QtProperty *property = m_enumToProperty.value(enumProp);
+                m_enumToProperty.remove(enumProp);
+                m_propertyToEnum.remove(property);
+                delete enumProp;
+            }
+            return;
+        }
+}
+
+/**
+    \class QtCursorEditorFactory
+
+    \brief The QtCursorEditorFactory class provides QComboBox widgets for
+    properties created by QtCursorPropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtCursorPropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtCursorEditorFactory::QtCursorEditorFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtCursorPropertyManager>(parent)
+{
+    d_ptr = new QtCursorEditorFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_enumEditorFactory = new QtEnumEditorFactory(this);
+    d_ptr->m_enumPropertyManager = new QtEnumPropertyManager(this);
+    connect(d_ptr->m_enumPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotEnumChanged(QtProperty *, int)));
+    d_ptr->m_enumEditorFactory->addPropertyManager(d_ptr->m_enumPropertyManager);
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtCursorEditorFactory::~QtCursorEditorFactory()
+{
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtCursorEditorFactory::connectPropertyManager(QtCursorPropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty *, const QCursor &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QCursor &)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtCursorEditorFactory::createEditor(QtCursorPropertyManager *manager, QtProperty *property,
+        QWidget *parent)
+{
+    QtProperty *enumProp = 0;
+    if (d_ptr->m_propertyToEnum.contains(property)) {
+        enumProp = d_ptr->m_propertyToEnum[property];
+    } else {
+        enumProp = d_ptr->m_enumPropertyManager->addProperty(property->propertyName());
+        d_ptr->m_enumPropertyManager->setEnumNames(enumProp, cursorDatabase()->cursorShapeNames());
+        d_ptr->m_enumPropertyManager->setEnumIcons(enumProp, cursorDatabase()->cursorShapeIcons());
+#ifndef QT_NO_CURSOR
+        d_ptr->m_enumPropertyManager->setValue(enumProp, cursorDatabase()->cursorToValue(manager->value(property)));
+#endif
+        d_ptr->m_propertyToEnum[property] = enumProp;
+        d_ptr->m_enumToProperty[enumProp] = property;
+    }
+    QtAbstractEditorFactoryBase *af = d_ptr->m_enumEditorFactory;
+    QWidget *editor = af->createEditor(enumProp, parent);
+    d_ptr->m_enumToEditors[enumProp].append(editor);
+    d_ptr->m_editorToEnum[editor] = enumProp;
+    connect(editor, SIGNAL(destroyed(QObject *)),
+                this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtCursorEditorFactory::disconnectPropertyManager(QtCursorPropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty *, const QCursor &)),
+                this, SLOT(slotPropertyChanged(QtProperty *, const QCursor &)));
+}
+
+// QtColorEditWidget
+
+class QtColorEditWidget : public QWidget {
+    Q_OBJECT
+
+public:
+    QtColorEditWidget(QWidget *parent);
+
+    bool eventFilter(QObject *obj, QEvent *ev);
+
+public Q_SLOTS:
+    void setValue(const QColor &value);
+
+private Q_SLOTS:
+    void buttonClicked();
+
+Q_SIGNALS:
+    void valueChanged(const QColor &value);
+
+private:
+    QColor m_color;
+    QLabel *m_pixmapLabel;
+    QLabel *m_label;
+    QToolButton *m_button;
+};
+
+QtColorEditWidget::QtColorEditWidget(QWidget *parent) :
+    QWidget(parent),
+    m_pixmapLabel(new QLabel),
+    m_label(new QLabel),
+    m_button(new QToolButton)
+{
+    QHBoxLayout *lt = new QHBoxLayout(this);
+    setupTreeViewEditorMargin(lt);
+    lt->setSpacing(0);
+    lt->addWidget(m_pixmapLabel);
+    lt->addWidget(m_label);
+    lt->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Ignored));
+
+    m_button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Ignored);
+    m_button->setFixedWidth(20);
+    setFocusProxy(m_button);
+    setFocusPolicy(m_button->focusPolicy());
+    m_button->setText(tr("..."));
+    m_button->installEventFilter(this);
+    connect(m_button, SIGNAL(clicked()), this, SLOT(buttonClicked()));
+    lt->addWidget(m_button);
+    m_pixmapLabel->setPixmap(QtPropertyBrowserUtils::brushValuePixmap(QBrush(m_color)));
+    m_label->setText(QtPropertyBrowserUtils::colorValueText(m_color));
+}
+
+void QtColorEditWidget::setValue(const QColor &c)
+{
+    if (m_color != c) {
+        m_color = c;
+        m_pixmapLabel->setPixmap(QtPropertyBrowserUtils::brushValuePixmap(QBrush(c)));
+        m_label->setText(QtPropertyBrowserUtils::colorValueText(c));
+    }
+}
+
+void QtColorEditWidget::buttonClicked()
+{
+    bool ok = false;
+    QRgb oldRgba = m_color.rgba();
+    QRgb newRgba = QColorDialog::getRgba(oldRgba, &ok, this);
+    if (ok && newRgba != oldRgba) {
+        setValue(QColor::fromRgba(newRgba));
+        emit valueChanged(m_color);
+    }
+}
+
+bool QtColorEditWidget::eventFilter(QObject *obj, QEvent *ev)
+{
+    if (obj == m_button) {
+        switch (ev->type()) {
+        case QEvent::KeyPress:
+        case QEvent::KeyRelease: { // Prevent the QToolButton from handling Enter/Escape meant control the delegate
+            switch (static_cast<const QKeyEvent*>(ev)->key()) {
+            case Qt::Key_Escape:
+            case Qt::Key_Enter:
+            case Qt::Key_Return:
+                ev->ignore();
+                return true;
+            default:
+                break;
+            }
+        }
+            break;
+        default:
+            break;
+        }
+    }
+    return QWidget::eventFilter(obj, ev);
+}
+
+// QtColorEditorFactoryPrivate
+
+class QtColorEditorFactoryPrivate : public EditorFactoryPrivate<QtColorEditWidget>
+{
+    QtColorEditorFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtColorEditorFactory)
+public:
+
+    void slotPropertyChanged(QtProperty *property, const QColor &value);
+    void slotSetValue(const QColor &value);
+};
+
+void QtColorEditorFactoryPrivate::slotPropertyChanged(QtProperty *property,
+                const QColor &value)
+{
+    const PropertyToEditorListMap::iterator it = m_createdEditors.find(property);
+    if (it == m_createdEditors.end())
+        return;
+    QListIterator<QtColorEditWidget *> itEditor(it.value());
+
+    while (itEditor.hasNext())
+        itEditor.next()->setValue(value);
+}
+
+void QtColorEditorFactoryPrivate::slotSetValue(const QColor &value)
+{
+    QObject *object = q_ptr->sender();
+    const EditorToPropertyMap::ConstIterator ecend = m_editorToProperty.constEnd();
+    for (EditorToPropertyMap::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtColorPropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+}
+
+/**
+    \class QtColorEditorFactory
+
+    \brief The QtColorEditorFactory class provides color editing  for
+    properties created by QtColorPropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtColorPropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtColorEditorFactory::QtColorEditorFactory(QObject *parent) :
+    QtAbstractEditorFactory<QtColorPropertyManager>(parent),
+    d_ptr(new QtColorEditorFactoryPrivate())
+{
+    d_ptr->q_ptr = this;
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtColorEditorFactory::~QtColorEditorFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtColorEditorFactory::connectPropertyManager(QtColorPropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty*,QColor)),
+            this, SLOT(slotPropertyChanged(QtProperty*,QColor)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtColorEditorFactory::createEditor(QtColorPropertyManager *manager,
+        QtProperty *property, QWidget *parent)
+{
+    QtColorEditWidget *editor = d_ptr->createEditor(property, parent);
+    editor->setValue(manager->value(property));
+    connect(editor, SIGNAL(valueChanged(QColor)), this, SLOT(slotSetValue(QColor)));
+    connect(editor, SIGNAL(destroyed(QObject *)), this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtColorEditorFactory::disconnectPropertyManager(QtColorPropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty*,QColor)), this, SLOT(slotPropertyChanged(QtProperty*,QColor)));
+}
+
+// QtFontEditWidget
+
+class QtFontEditWidget : public QWidget {
+    Q_OBJECT
+
+public:
+    QtFontEditWidget(QWidget *parent);
+
+    bool eventFilter(QObject *obj, QEvent *ev);
+
+public Q_SLOTS:
+    void setValue(const QFont &value);
+
+private Q_SLOTS:
+    void buttonClicked();
+
+Q_SIGNALS:
+    void valueChanged(const QFont &value);
+
+private:
+    QFont m_font;
+    QLabel *m_pixmapLabel;
+    QLabel *m_label;
+    QToolButton *m_button;
+};
+
+QtFontEditWidget::QtFontEditWidget(QWidget *parent) :
+    QWidget(parent),
+    m_pixmapLabel(new QLabel),
+    m_label(new QLabel),
+    m_button(new QToolButton)
+{
+    QHBoxLayout *lt = new QHBoxLayout(this);
+    setupTreeViewEditorMargin(lt);
+    lt->setSpacing(0);
+    lt->addWidget(m_pixmapLabel);
+    lt->addWidget(m_label);
+    lt->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Ignored));
+
+    m_button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Ignored);
+    m_button->setFixedWidth(20);
+    setFocusProxy(m_button);
+    setFocusPolicy(m_button->focusPolicy());
+    m_button->setText(tr("..."));
+    m_button->installEventFilter(this);
+    connect(m_button, SIGNAL(clicked()), this, SLOT(buttonClicked()));
+    lt->addWidget(m_button);
+    m_pixmapLabel->setPixmap(QtPropertyBrowserUtils::fontValuePixmap(m_font));
+    m_label->setText(QtPropertyBrowserUtils::fontValueText(m_font));
+}
+
+void QtFontEditWidget::setValue(const QFont &f)
+{
+    if (m_font != f) {
+        m_font = f;
+        m_pixmapLabel->setPixmap(QtPropertyBrowserUtils::fontValuePixmap(f));
+        m_label->setText(QtPropertyBrowserUtils::fontValueText(f));
+    }
+}
+
+void QtFontEditWidget::buttonClicked()
+{
+    bool ok = false;
+    QFont newFont = QFontDialog::getFont(&ok, m_font, this, tr("Select Font"));
+    if (ok && newFont != m_font) {
+        QFont f = m_font;
+        // prevent mask for unchanged attributes, don't change other attributes (like kerning, etc...)
+        if (m_font.family() != newFont.family())
+            f.setFamily(newFont.family());
+        if (m_font.pointSize() != newFont.pointSize())
+            f.setPointSize(newFont.pointSize());
+        if (m_font.bold() != newFont.bold())
+            f.setBold(newFont.bold());
+        if (m_font.italic() != newFont.italic())
+            f.setItalic(newFont.italic());
+        if (m_font.underline() != newFont.underline())
+            f.setUnderline(newFont.underline());
+        if (m_font.strikeOut() != newFont.strikeOut())
+            f.setStrikeOut(newFont.strikeOut());
+        setValue(f);
+        emit valueChanged(m_font);
+    }
+}
+
+bool QtFontEditWidget::eventFilter(QObject *obj, QEvent *ev)
+{
+    if (obj == m_button) {
+        switch (ev->type()) {
+        case QEvent::KeyPress:
+        case QEvent::KeyRelease: { // Prevent the QToolButton from handling Enter/Escape meant control the delegate
+            switch (static_cast<const QKeyEvent*>(ev)->key()) {
+            case Qt::Key_Escape:
+            case Qt::Key_Enter:
+            case Qt::Key_Return:
+                ev->ignore();
+                return true;
+            default:
+                break;
+            }
+        }
+            break;
+        default:
+            break;
+        }
+    }
+    return QWidget::eventFilter(obj, ev);
+}
+
+// QtFontEditorFactoryPrivate
+
+class QtFontEditorFactoryPrivate : public EditorFactoryPrivate<QtFontEditWidget>
+{
+    QtFontEditorFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtFontEditorFactory)
+public:
+
+    void slotPropertyChanged(QtProperty *property, const QFont &value);
+    void slotSetValue(const QFont &value);
+};
+
+void QtFontEditorFactoryPrivate::slotPropertyChanged(QtProperty *property,
+                const QFont &value)
+{
+    const PropertyToEditorListMap::iterator it = m_createdEditors.find(property);
+    if (it == m_createdEditors.end())
+        return;
+    QListIterator<QtFontEditWidget *> itEditor(it.value());
+
+    while (itEditor.hasNext())
+        itEditor.next()->setValue(value);
+}
+
+void QtFontEditorFactoryPrivate::slotSetValue(const QFont &value)
+{
+    QObject *object = q_ptr->sender();
+    const EditorToPropertyMap::ConstIterator ecend = m_editorToProperty.constEnd();
+    for (EditorToPropertyMap::ConstIterator itEditor = m_editorToProperty.constBegin(); itEditor != ecend; ++itEditor)
+        if (itEditor.key() == object) {
+            QtProperty *property = itEditor.value();
+            QtFontPropertyManager *manager = q_ptr->propertyManager(property);
+            if (!manager)
+                return;
+            manager->setValue(property, value);
+            return;
+        }
+}
+
+/**
+    \class QtFontEditorFactory
+
+    \brief The QtFontEditorFactory class provides font editing for
+    properties created by QtFontPropertyManager objects.
+
+    \sa QtAbstractEditorFactory, QtFontPropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtFontEditorFactory::QtFontEditorFactory(QObject *parent) :
+    QtAbstractEditorFactory<QtFontPropertyManager>(parent),
+    d_ptr(new QtFontEditorFactoryPrivate())
+{
+    d_ptr->q_ptr = this;
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtFontEditorFactory::~QtFontEditorFactory()
+{
+    qDeleteAll(d_ptr->m_editorToProperty.keys());
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtFontEditorFactory::connectPropertyManager(QtFontPropertyManager *manager)
+{
+    connect(manager, SIGNAL(valueChanged(QtProperty*,QFont)),
+            this, SLOT(slotPropertyChanged(QtProperty*,QFont)));
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtFontEditorFactory::createEditor(QtFontPropertyManager *manager,
+        QtProperty *property, QWidget *parent)
+{
+    QtFontEditWidget *editor = d_ptr->createEditor(property, parent);
+    editor->setValue(manager->value(property));
+    connect(editor, SIGNAL(valueChanged(QFont)), this, SLOT(slotSetValue(QFont)));
+    connect(editor, SIGNAL(destroyed(QObject *)), this, SLOT(slotEditorDestroyed(QObject *)));
+    return editor;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtFontEditorFactory::disconnectPropertyManager(QtFontPropertyManager *manager)
+{
+    disconnect(manager, SIGNAL(valueChanged(QtProperty*,QFont)), this, SLOT(slotPropertyChanged(QtProperty*,QFont)));
+}
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#include "moc_qteditorfactory.cpp"
+#include "qteditorfactory.moc"
diff --git a/Code/Mantid/QtPropertyBrowser/src/qteditorfactory.h b/Code/Mantid/QtPropertyBrowser/src/qteditorfactory.h
index d965aeb9d5926122cd763d9549fa9392b6cc83f5..ad49615bb65dd9764c00c29c015af2fb6cdfa550 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qteditorfactory.h
+++ b/Code/Mantid/QtPropertyBrowser/src/qteditorfactory.h
@@ -1,447 +1,447 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QTEDITORFACTORY_H
-#define QTEDITORFACTORY_H
-
-#include "qtpropertymanager.h"
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-class QtSpinBoxFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtSpinBoxFactory : public QtAbstractEditorFactory<QtIntPropertyManager>
-{
-    Q_OBJECT
-public:
-    QtSpinBoxFactory(QObject *parent = 0);
-    ~QtSpinBoxFactory();
-protected:
-    void connectPropertyManager(QtIntPropertyManager *manager);
-    QWidget *createEditor(QtIntPropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtIntPropertyManager *manager);
-private:
-    QtSpinBoxFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtSpinBoxFactory)
-    Q_DISABLE_COPY(QtSpinBoxFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, int, int))
-    Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(int))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtSliderFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtSliderFactory : public QtAbstractEditorFactory<QtIntPropertyManager>
-{
-    Q_OBJECT
-public:
-    QtSliderFactory(QObject *parent = 0);
-    ~QtSliderFactory();
-protected:
-    void connectPropertyManager(QtIntPropertyManager *manager);
-    QWidget *createEditor(QtIntPropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtIntPropertyManager *manager);
-private:
-    QtSliderFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtSliderFactory)
-    Q_DISABLE_COPY(QtSliderFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, int, int))
-    Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(int))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtScrollBarFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtScrollBarFactory : public QtAbstractEditorFactory<QtIntPropertyManager>
-{
-    Q_OBJECT
-public:
-    QtScrollBarFactory(QObject *parent = 0);
-    ~QtScrollBarFactory();
-protected:
-    void connectPropertyManager(QtIntPropertyManager *manager);
-    QWidget *createEditor(QtIntPropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtIntPropertyManager *manager);
-private:
-    QtScrollBarFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtScrollBarFactory)
-    Q_DISABLE_COPY(QtScrollBarFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, int, int))
-    Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(int))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtCheckBoxFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtCheckBoxFactory : public QtAbstractEditorFactory<QtBoolPropertyManager>
-{
-    Q_OBJECT
-public:
-    QtCheckBoxFactory(QObject *parent = 0);
-    ~QtCheckBoxFactory();
-protected:
-    void connectPropertyManager(QtBoolPropertyManager *manager);
-    QWidget *createEditor(QtBoolPropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtBoolPropertyManager *manager);
-private:
-    QtCheckBoxFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtCheckBoxFactory)
-    Q_DISABLE_COPY(QtCheckBoxFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, bool))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(bool))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtDoubleSpinBoxFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtDoubleSpinBoxFactory : public QtAbstractEditorFactory<QtDoublePropertyManager>
-{
-    Q_OBJECT
-public:
-    QtDoubleSpinBoxFactory(QObject *parent = 0);
-    ~QtDoubleSpinBoxFactory();
-protected:
-    void connectPropertyManager(QtDoublePropertyManager *manager);
-    QWidget *createEditor(QtDoublePropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtDoublePropertyManager *manager);
-private:
-    QtDoubleSpinBoxFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtDoubleSpinBoxFactory)
-    Q_DISABLE_COPY(QtDoubleSpinBoxFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, double))
-    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, double, double))
-    Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, double))
-    Q_PRIVATE_SLOT(d_func(), void slotDecimalsChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(double))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtLineEditFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtLineEditFactory : public QtAbstractEditorFactory<QtStringPropertyManager>
-{
-    Q_OBJECT
-public:
-    QtLineEditFactory(QObject *parent = 0);
-    ~QtLineEditFactory();
-protected:
-    void connectPropertyManager(QtStringPropertyManager *manager);
-    QWidget *createEditor(QtStringPropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtStringPropertyManager *manager);
-private:
-    QtLineEditFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtLineEditFactory)
-    Q_DISABLE_COPY(QtLineEditFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QString &))
-    Q_PRIVATE_SLOT(d_func(), void slotRegExpChanged(QtProperty *, const QRegExp &))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QString &))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtDateEditFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtDateEditFactory : public QtAbstractEditorFactory<QtDatePropertyManager>
-{
-    Q_OBJECT
-public:
-    QtDateEditFactory(QObject *parent = 0);
-    ~QtDateEditFactory();
-protected:
-    void connectPropertyManager(QtDatePropertyManager *manager);
-    QWidget *createEditor(QtDatePropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtDatePropertyManager *manager);
-private:
-    QtDateEditFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtDateEditFactory)
-    Q_DISABLE_COPY(QtDateEditFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QDate &))
-    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *,
-                        const QDate &, const QDate &))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QDate &))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtTimeEditFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtTimeEditFactory : public QtAbstractEditorFactory<QtTimePropertyManager>
-{
-    Q_OBJECT
-public:
-    QtTimeEditFactory(QObject *parent = 0);
-    ~QtTimeEditFactory();
-protected:
-    void connectPropertyManager(QtTimePropertyManager *manager);
-    QWidget *createEditor(QtTimePropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtTimePropertyManager *manager);
-private:
-    QtTimeEditFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtTimeEditFactory)
-    Q_DISABLE_COPY(QtTimeEditFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QTime &))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QTime &))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtDateTimeEditFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtDateTimeEditFactory : public QtAbstractEditorFactory<QtDateTimePropertyManager>
-{
-    Q_OBJECT
-public:
-    QtDateTimeEditFactory(QObject *parent = 0);
-    ~QtDateTimeEditFactory();
-protected:
-    void connectPropertyManager(QtDateTimePropertyManager *manager);
-    QWidget *createEditor(QtDateTimePropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtDateTimePropertyManager *manager);
-private:
-    QtDateTimeEditFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtDateTimeEditFactory)
-    Q_DISABLE_COPY(QtDateTimeEditFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QDateTime &))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QDateTime &))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtKeySequenceEditorFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtKeySequenceEditorFactory : public QtAbstractEditorFactory<QtKeySequencePropertyManager>
-{
-    Q_OBJECT
-public:
-    QtKeySequenceEditorFactory(QObject *parent = 0);
-    ~QtKeySequenceEditorFactory();
-protected:
-    void connectPropertyManager(QtKeySequencePropertyManager *manager);
-    QWidget *createEditor(QtKeySequencePropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtKeySequencePropertyManager *manager);
-private:
-    QtKeySequenceEditorFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtKeySequenceEditorFactory)
-    Q_DISABLE_COPY(QtKeySequenceEditorFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QKeySequence &))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QKeySequence &))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtCharEditorFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtCharEditorFactory : public QtAbstractEditorFactory<QtCharPropertyManager>
-{
-    Q_OBJECT
-public:
-    QtCharEditorFactory(QObject *parent = 0);
-    ~QtCharEditorFactory();
-protected:
-    void connectPropertyManager(QtCharPropertyManager *manager);
-    QWidget *createEditor(QtCharPropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtCharPropertyManager *manager);
-private:
-    QtCharEditorFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtCharEditorFactory)
-    Q_DISABLE_COPY(QtCharEditorFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QChar &))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QChar &))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtEnumEditorFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtEnumEditorFactory : public QtAbstractEditorFactory<QtEnumPropertyManager>
-{
-    Q_OBJECT
-public:
-    QtEnumEditorFactory(QObject *parent = 0);
-    ~QtEnumEditorFactory();
-protected:
-    void connectPropertyManager(QtEnumPropertyManager *manager);
-    QWidget *createEditor(QtEnumPropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtEnumPropertyManager *manager);
-private:
-    QtEnumEditorFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtEnumEditorFactory)
-    Q_DISABLE_COPY(QtEnumEditorFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotEnumNamesChanged(QtProperty *,
-                        const QStringList &))
-    Q_PRIVATE_SLOT(d_func(), void slotEnumIconsChanged(QtProperty *,
-                        const QMap<int, QIcon> &))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(int))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtCursorEditorFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtCursorEditorFactory : public QtAbstractEditorFactory<QtCursorPropertyManager>
-{
-    Q_OBJECT
-public:
-    QtCursorEditorFactory(QObject *parent = 0);
-    ~QtCursorEditorFactory();
-protected:
-    void connectPropertyManager(QtCursorPropertyManager *manager);
-    QWidget *createEditor(QtCursorPropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtCursorPropertyManager *manager);
-private:
-    QtCursorEditorFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtCursorEditorFactory)
-    Q_DISABLE_COPY(QtCursorEditorFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QCursor &))
-    Q_PRIVATE_SLOT(d_func(), void slotEnumChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-};
-
-class QtColorEditorFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtColorEditorFactory : public QtAbstractEditorFactory<QtColorPropertyManager>
-{
-    Q_OBJECT
-public:
-    QtColorEditorFactory(QObject *parent = 0);
-    ~QtColorEditorFactory();
-protected:
-    void connectPropertyManager(QtColorPropertyManager *manager);
-    QWidget *createEditor(QtColorPropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtColorPropertyManager *manager);
-private:
-    QtColorEditorFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtColorEditorFactory)
-    Q_DISABLE_COPY(QtColorEditorFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QColor &))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QColor &))
-};
-
-class QtFontEditorFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtFontEditorFactory : public QtAbstractEditorFactory<QtFontPropertyManager>
-{
-    Q_OBJECT
-public:
-    QtFontEditorFactory(QObject *parent = 0);
-    ~QtFontEditorFactory();
-protected:
-    void connectPropertyManager(QtFontPropertyManager *manager);
-    QWidget *createEditor(QtFontPropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtFontPropertyManager *manager);
-private:
-    QtFontEditorFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtFontEditorFactory)
-    Q_DISABLE_COPY(QtFontEditorFactory)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QFont &))
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
-    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QFont &))
-};
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#endif
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QTEDITORFACTORY_H
+#define QTEDITORFACTORY_H
+
+#include "qtpropertymanager.h"
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+class QtSpinBoxFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtSpinBoxFactory : public QtAbstractEditorFactory<QtIntPropertyManager>
+{
+    Q_OBJECT
+public:
+    QtSpinBoxFactory(QObject *parent = 0);
+    ~QtSpinBoxFactory();
+protected:
+    void connectPropertyManager(QtIntPropertyManager *manager);
+    QWidget *createEditor(QtIntPropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtIntPropertyManager *manager);
+private:
+    QtSpinBoxFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtSpinBoxFactory)
+    Q_DISABLE_COPY(QtSpinBoxFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, int, int))
+    Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(int))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtSliderFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtSliderFactory : public QtAbstractEditorFactory<QtIntPropertyManager>
+{
+    Q_OBJECT
+public:
+    QtSliderFactory(QObject *parent = 0);
+    ~QtSliderFactory();
+protected:
+    void connectPropertyManager(QtIntPropertyManager *manager);
+    QWidget *createEditor(QtIntPropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtIntPropertyManager *manager);
+private:
+    QtSliderFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtSliderFactory)
+    Q_DISABLE_COPY(QtSliderFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, int, int))
+    Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(int))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtScrollBarFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtScrollBarFactory : public QtAbstractEditorFactory<QtIntPropertyManager>
+{
+    Q_OBJECT
+public:
+    QtScrollBarFactory(QObject *parent = 0);
+    ~QtScrollBarFactory();
+protected:
+    void connectPropertyManager(QtIntPropertyManager *manager);
+    QWidget *createEditor(QtIntPropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtIntPropertyManager *manager);
+private:
+    QtScrollBarFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtScrollBarFactory)
+    Q_DISABLE_COPY(QtScrollBarFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, int, int))
+    Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(int))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtCheckBoxFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtCheckBoxFactory : public QtAbstractEditorFactory<QtBoolPropertyManager>
+{
+    Q_OBJECT
+public:
+    QtCheckBoxFactory(QObject *parent = 0);
+    ~QtCheckBoxFactory();
+protected:
+    void connectPropertyManager(QtBoolPropertyManager *manager);
+    QWidget *createEditor(QtBoolPropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtBoolPropertyManager *manager);
+private:
+    QtCheckBoxFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtCheckBoxFactory)
+    Q_DISABLE_COPY(QtCheckBoxFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, bool))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(bool))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtDoubleSpinBoxFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtDoubleSpinBoxFactory : public QtAbstractEditorFactory<QtDoublePropertyManager>
+{
+    Q_OBJECT
+public:
+    QtDoubleSpinBoxFactory(QObject *parent = 0);
+    ~QtDoubleSpinBoxFactory();
+protected:
+    void connectPropertyManager(QtDoublePropertyManager *manager);
+    QWidget *createEditor(QtDoublePropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtDoublePropertyManager *manager);
+private:
+    QtDoubleSpinBoxFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtDoubleSpinBoxFactory)
+    Q_DISABLE_COPY(QtDoubleSpinBoxFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, double))
+    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, double, double))
+    Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, double))
+    Q_PRIVATE_SLOT(d_func(), void slotDecimalsChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(double))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtLineEditFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtLineEditFactory : public QtAbstractEditorFactory<QtStringPropertyManager>
+{
+    Q_OBJECT
+public:
+    QtLineEditFactory(QObject *parent = 0);
+    ~QtLineEditFactory();
+protected:
+    void connectPropertyManager(QtStringPropertyManager *manager);
+    QWidget *createEditor(QtStringPropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtStringPropertyManager *manager);
+private:
+    QtLineEditFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtLineEditFactory)
+    Q_DISABLE_COPY(QtLineEditFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QString &))
+    Q_PRIVATE_SLOT(d_func(), void slotRegExpChanged(QtProperty *, const QRegExp &))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QString &))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtDateEditFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtDateEditFactory : public QtAbstractEditorFactory<QtDatePropertyManager>
+{
+    Q_OBJECT
+public:
+    QtDateEditFactory(QObject *parent = 0);
+    ~QtDateEditFactory();
+protected:
+    void connectPropertyManager(QtDatePropertyManager *manager);
+    QWidget *createEditor(QtDatePropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtDatePropertyManager *manager);
+private:
+    QtDateEditFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtDateEditFactory)
+    Q_DISABLE_COPY(QtDateEditFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QDate &))
+    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *,
+                        const QDate &, const QDate &))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QDate &))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtTimeEditFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtTimeEditFactory : public QtAbstractEditorFactory<QtTimePropertyManager>
+{
+    Q_OBJECT
+public:
+    QtTimeEditFactory(QObject *parent = 0);
+    ~QtTimeEditFactory();
+protected:
+    void connectPropertyManager(QtTimePropertyManager *manager);
+    QWidget *createEditor(QtTimePropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtTimePropertyManager *manager);
+private:
+    QtTimeEditFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtTimeEditFactory)
+    Q_DISABLE_COPY(QtTimeEditFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QTime &))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QTime &))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtDateTimeEditFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtDateTimeEditFactory : public QtAbstractEditorFactory<QtDateTimePropertyManager>
+{
+    Q_OBJECT
+public:
+    QtDateTimeEditFactory(QObject *parent = 0);
+    ~QtDateTimeEditFactory();
+protected:
+    void connectPropertyManager(QtDateTimePropertyManager *manager);
+    QWidget *createEditor(QtDateTimePropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtDateTimePropertyManager *manager);
+private:
+    QtDateTimeEditFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtDateTimeEditFactory)
+    Q_DISABLE_COPY(QtDateTimeEditFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QDateTime &))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QDateTime &))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtKeySequenceEditorFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtKeySequenceEditorFactory : public QtAbstractEditorFactory<QtKeySequencePropertyManager>
+{
+    Q_OBJECT
+public:
+    QtKeySequenceEditorFactory(QObject *parent = 0);
+    ~QtKeySequenceEditorFactory();
+protected:
+    void connectPropertyManager(QtKeySequencePropertyManager *manager);
+    QWidget *createEditor(QtKeySequencePropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtKeySequencePropertyManager *manager);
+private:
+    QtKeySequenceEditorFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtKeySequenceEditorFactory)
+    Q_DISABLE_COPY(QtKeySequenceEditorFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QKeySequence &))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QKeySequence &))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtCharEditorFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtCharEditorFactory : public QtAbstractEditorFactory<QtCharPropertyManager>
+{
+    Q_OBJECT
+public:
+    QtCharEditorFactory(QObject *parent = 0);
+    ~QtCharEditorFactory();
+protected:
+    void connectPropertyManager(QtCharPropertyManager *manager);
+    QWidget *createEditor(QtCharPropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtCharPropertyManager *manager);
+private:
+    QtCharEditorFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtCharEditorFactory)
+    Q_DISABLE_COPY(QtCharEditorFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QChar &))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QChar &))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtEnumEditorFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtEnumEditorFactory : public QtAbstractEditorFactory<QtEnumPropertyManager>
+{
+    Q_OBJECT
+public:
+    QtEnumEditorFactory(QObject *parent = 0);
+    ~QtEnumEditorFactory();
+protected:
+    void connectPropertyManager(QtEnumPropertyManager *manager);
+    QWidget *createEditor(QtEnumPropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtEnumPropertyManager *manager);
+private:
+    QtEnumEditorFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtEnumEditorFactory)
+    Q_DISABLE_COPY(QtEnumEditorFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotEnumNamesChanged(QtProperty *,
+                        const QStringList &))
+    Q_PRIVATE_SLOT(d_func(), void slotEnumIconsChanged(QtProperty *,
+                        const QMap<int, QIcon> &))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(int))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtCursorEditorFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtCursorEditorFactory : public QtAbstractEditorFactory<QtCursorPropertyManager>
+{
+    Q_OBJECT
+public:
+    QtCursorEditorFactory(QObject *parent = 0);
+    ~QtCursorEditorFactory();
+protected:
+    void connectPropertyManager(QtCursorPropertyManager *manager);
+    QWidget *createEditor(QtCursorPropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtCursorPropertyManager *manager);
+private:
+    QtCursorEditorFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtCursorEditorFactory)
+    Q_DISABLE_COPY(QtCursorEditorFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QCursor &))
+    Q_PRIVATE_SLOT(d_func(), void slotEnumChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+};
+
+class QtColorEditorFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtColorEditorFactory : public QtAbstractEditorFactory<QtColorPropertyManager>
+{
+    Q_OBJECT
+public:
+    QtColorEditorFactory(QObject *parent = 0);
+    ~QtColorEditorFactory();
+protected:
+    void connectPropertyManager(QtColorPropertyManager *manager);
+    QWidget *createEditor(QtColorPropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtColorPropertyManager *manager);
+private:
+    QtColorEditorFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtColorEditorFactory)
+    Q_DISABLE_COPY(QtColorEditorFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QColor &))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QColor &))
+};
+
+class QtFontEditorFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtFontEditorFactory : public QtAbstractEditorFactory<QtFontPropertyManager>
+{
+    Q_OBJECT
+public:
+    QtFontEditorFactory(QObject *parent = 0);
+    ~QtFontEditorFactory();
+protected:
+    void connectPropertyManager(QtFontPropertyManager *manager);
+    QWidget *createEditor(QtFontPropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtFontPropertyManager *manager);
+private:
+    QtFontEditorFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtFontEditorFactory)
+    Q_DISABLE_COPY(QtFontEditorFactory)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyChanged(QtProperty *, const QFont &))
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed(QObject *))
+    Q_PRIVATE_SLOT(d_func(), void slotSetValue(const QFont &))
+};
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#endif
diff --git a/Code/Mantid/QtPropertyBrowser/src/qtgroupboxpropertybrowser.cpp b/Code/Mantid/QtPropertyBrowser/src/qtgroupboxpropertybrowser.cpp
index 93323ea89df33963e521c94d5f7cf63e1c4e0113..9eb3b7db1f8f8dcf6c2e5ae660fc02ccb7bf8543 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qtgroupboxpropertybrowser.cpp
+++ b/Code/Mantid/QtPropertyBrowser/src/qtgroupboxpropertybrowser.cpp
@@ -1,578 +1,578 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qtgroupboxpropertybrowser.h"
-#include <QtCore/QSet>
-#include <QtGui/QGridLayout>
-#include <QtGui/QLabel>
-#include <QtGui/QGroupBox>
-#include <QtCore/QTimer>
-#include <QtCore/QMap>
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-class QtGroupBoxPropertyBrowserPrivate
-{
-    QtGroupBoxPropertyBrowser *q_ptr;
-    Q_DECLARE_PUBLIC(QtGroupBoxPropertyBrowser)
-public:
-
-    void init(QWidget *parent);
-
-    void propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex);
-    void propertyRemoved(QtBrowserItem *index);
-    void propertyChanged(QtBrowserItem *index);
-    QWidget *createEditor(QtProperty *property, QWidget *parent) const
-        { return q_ptr->createEditor(property, parent); }
-
-    void slotEditorDestroyed();
-    void slotUpdate();
-
-    struct WidgetItem
-    {
-        WidgetItem() : widget(0), label(0), widgetLabel(0),
-                groupBox(0), layout(0), line(0), parent(0) { }
-        QWidget *widget; // can be null
-        QLabel *label;
-        QLabel *widgetLabel;
-        QGroupBox *groupBox;
-        QGridLayout *layout;
-        QFrame *line;
-        WidgetItem *parent;
-        QList<WidgetItem *> children;
-    };
-private:
-    void updateLater();
-    void updateItem(WidgetItem *item);
-    void insertRow(QGridLayout *layout, int row) const;
-    void removeRow(QGridLayout *layout, int row) const;
-
-    bool hasHeader(WidgetItem *item) const;
-
-    QMap<QtBrowserItem *, WidgetItem *> m_indexToItem;
-    QMap<WidgetItem *, QtBrowserItem *> m_itemToIndex;
-    QMap<QWidget *, WidgetItem *> m_widgetToItem;
-    QGridLayout *m_mainLayout;
-    QList<WidgetItem *> m_children;
-    QList<WidgetItem *> m_recreateQueue;
-};
-
-void QtGroupBoxPropertyBrowserPrivate::init(QWidget *parent)
-{
-    m_mainLayout = new QGridLayout();
-    parent->setLayout(m_mainLayout);
-    QLayoutItem *item = new QSpacerItem(0, 0,
-                QSizePolicy::Fixed, QSizePolicy::Expanding);
-    m_mainLayout->addItem(item, 0, 0);
-}
-
-void QtGroupBoxPropertyBrowserPrivate::slotEditorDestroyed()
-{
-    QWidget *editor = qobject_cast<QWidget *>(q_ptr->sender());
-    if (!editor)
-        return;
-    if (!m_widgetToItem.contains(editor))
-        return;
-    m_widgetToItem[editor]->widget = 0;
-    m_widgetToItem.remove(editor);
-}
-
-void QtGroupBoxPropertyBrowserPrivate::slotUpdate()
-{
-    QListIterator<WidgetItem *> itItem(m_recreateQueue);
-    while (itItem.hasNext()) {
-        WidgetItem *item = itItem.next();
-
-        WidgetItem *par = item->parent;
-        QWidget *w = 0;
-        QGridLayout *l = 0;
-        int oldRow = -1;
-        if (!par) {
-            w = q_ptr;
-            l = m_mainLayout;
-            oldRow = m_children.indexOf(item);
-        } else {
-            w = par->groupBox;
-            l = par->layout;
-            oldRow = par->children.indexOf(item);
-            if (hasHeader(par))
-                oldRow += 2;
-        }
-
-        if (item->widget) {
-            item->widget->setParent(w);
-        } else if (item->widgetLabel) {
-            item->widgetLabel->setParent(w);
-        } else {
-            item->widgetLabel = new QLabel(w);
-        }
-        int span = 1;
-        if (item->widget)
-            l->addWidget(item->widget, oldRow, 1, 1, 1);
-        else if (item->widgetLabel)
-            l->addWidget(item->widgetLabel, oldRow, 1, 1, 1);
-        else
-            span = 2;
-        item->label = new QLabel(w);
-        item->label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
-        l->addWidget(item->label, oldRow, 0, 1, span);
-
-        updateItem(item);
-    }
-    m_recreateQueue.clear();
-}
-
-void QtGroupBoxPropertyBrowserPrivate::updateLater()
-{
-    QTimer::singleShot(0, q_ptr, SLOT(slotUpdate()));
-}
-
-void QtGroupBoxPropertyBrowserPrivate::propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex)
-{
-    WidgetItem *afterItem = m_indexToItem.value(afterIndex);
-    WidgetItem *parentItem = m_indexToItem.value(index->parent());
-
-    WidgetItem *newItem = new WidgetItem();
-    newItem->parent = parentItem;
-
-    QGridLayout *layout = 0;
-    QWidget *parentWidget = 0;
-    int row = -1;
-    if (!afterItem) {
-        row = 0;
-        if (parentItem)
-            parentItem->children.insert(0, newItem);
-        else
-            m_children.insert(0, newItem);
-    } else {
-        if (parentItem) {
-            row = parentItem->children.indexOf(afterItem) + 1;
-            parentItem->children.insert(row, newItem);
-        } else {
-            row = m_children.indexOf(afterItem) + 1;
-            m_children.insert(row, newItem);
-        }
-    }
-    if (parentItem && hasHeader(parentItem))
-        row += 2;
-
-    if (!parentItem) {
-        layout = m_mainLayout;
-        parentWidget = q_ptr;;
-    } else {
-        if (!parentItem->groupBox) {
-            m_recreateQueue.removeAll(parentItem);
-            WidgetItem *par = parentItem->parent;
-            QWidget *w = 0;
-            QGridLayout *l = 0;
-            int oldRow = -1;
-            if (!par) {
-                w = q_ptr;
-                l = m_mainLayout;
-                oldRow = m_children.indexOf(parentItem);
-            } else {
-                w = par->groupBox;
-                l = par->layout;
-                oldRow = par->children.indexOf(parentItem);
-                if (hasHeader(par))
-                    oldRow += 2;
-            }
-            parentItem->groupBox = new QGroupBox(w);
-            parentItem->layout = new QGridLayout();
-            parentItem->groupBox->setLayout(parentItem->layout);
-            if (parentItem->label) {
-                l->removeWidget(parentItem->label);
-                delete parentItem->label;
-                parentItem->label = 0;
-            }
-            if (parentItem->widget) {
-                l->removeWidget(parentItem->widget);
-                parentItem->widget->setParent(parentItem->groupBox);
-                parentItem->layout->addWidget(parentItem->widget, 0, 0, 1, 2);
-                parentItem->line = new QFrame(parentItem->groupBox);
-            } else if (parentItem->widgetLabel) {
-                l->removeWidget(parentItem->widgetLabel);
-                delete parentItem->widgetLabel;
-                parentItem->widgetLabel = 0;
-            }
-            if (parentItem->line) {
-                parentItem->line->setFrameShape(QFrame::HLine);
-                parentItem->line->setFrameShadow(QFrame::Sunken);
-                parentItem->layout->addWidget(parentItem->line, 1, 0, 1, 2);
-            }
-            l->addWidget(parentItem->groupBox, oldRow, 0, 1, 2);
-            updateItem(parentItem);
-        }
-        layout = parentItem->layout;
-        parentWidget = parentItem->groupBox;
-    }
-
-    newItem->label = new QLabel(parentWidget);
-    newItem->label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
-    newItem->widget = createEditor(index->property(), parentWidget);
-    if (!newItem->widget) {
-        newItem->widgetLabel = new QLabel(parentWidget);
-    } else {
-        QObject::connect(newItem->widget, SIGNAL(destroyed()), q_ptr, SLOT(slotEditorDestroyed()));
-        m_widgetToItem[newItem->widget] = newItem;
-    }
-
-    insertRow(layout, row);
-    int span = 1;
-    if (newItem->widget)
-        layout->addWidget(newItem->widget, row, 1);
-    else if (newItem->widgetLabel)
-        layout->addWidget(newItem->widgetLabel, row, 1);
-    else
-        span = 2;
-    layout->addWidget(newItem->label, row, 0, 1, span);
-
-    m_itemToIndex[newItem] = index;
-    m_indexToItem[index] = newItem;
-
-    updateItem(newItem);
-}
-
-void QtGroupBoxPropertyBrowserPrivate::propertyRemoved(QtBrowserItem *index)
-{
-    WidgetItem *item = m_indexToItem.value(index);
-
-    m_indexToItem.remove(index);
-    m_itemToIndex.remove(item);
-
-    WidgetItem *parentItem = item->parent;
-
-    int row = -1;
-
-    if (parentItem) {
-        row = parentItem->children.indexOf(item);
-        parentItem->children.removeAt(row);
-        if (hasHeader(parentItem))
-            row += 2;
-    } else {
-        row = m_children.indexOf(item);
-        m_children.removeAt(row);
-    }
-
-    if (item->widget)
-        delete item->widget;
-    if (item->label)
-        delete item->label;
-    if (item->widgetLabel)
-        delete item->widgetLabel;
-    if (item->groupBox)
-        delete item->groupBox;
-
-    if (!parentItem) {
-        removeRow(m_mainLayout, row);
-    } else if (parentItem->children.count() != 0) {
-        removeRow(parentItem->layout, row);
-    } else {
-        WidgetItem *par = parentItem->parent;
-        QWidget *w = 0;
-        QGridLayout *l = 0;
-        int oldRow = -1;
-        if (!par) {
-            w = q_ptr;
-            l = m_mainLayout;
-            oldRow = m_children.indexOf(parentItem);
-        } else {
-            w = par->groupBox;
-            l = par->layout;
-            oldRow = par->children.indexOf(parentItem);
-            if (hasHeader(par))
-                oldRow += 2;
-        }
-
-        if (parentItem->widget) {
-            parentItem->widget->hide();
-            parentItem->widget->setParent(0);
-        } else if (parentItem->widgetLabel) {
-            parentItem->widgetLabel->hide();
-            parentItem->widgetLabel->setParent(0);
-        } else {
-            //parentItem->widgetLabel = new QLabel(w);
-        }
-        l->removeWidget(parentItem->groupBox);
-        delete parentItem->groupBox;
-        parentItem->groupBox = 0;
-        parentItem->line = 0;
-        parentItem->layout = 0;
-        if (!m_recreateQueue.contains(parentItem))
-            m_recreateQueue.append(parentItem);
-        updateLater();
-    }
-    m_recreateQueue.removeAll(item);
-
-    delete item;
-}
-
-void QtGroupBoxPropertyBrowserPrivate::insertRow(QGridLayout *layout, int row) const
-{
-    QMap<QLayoutItem *, QRect> itemToPos;
-    int idx = 0;
-    while (idx < layout->count()) {
-        int r, c, rs, cs;
-        layout->getItemPosition(idx, &r, &c, &rs, &cs);
-        if (r >= row) {
-            itemToPos[layout->takeAt(idx)] = QRect(r + 1, c, rs, cs);
-        } else {
-            idx++;
-        }
-    }
-
-    const QMap<QLayoutItem *, QRect>::ConstIterator icend = itemToPos.constEnd();
-    for (QMap<QLayoutItem *, QRect>::ConstIterator it = itemToPos.constBegin(); it != icend; ++it) {
-        const QRect r = it.value();
-        layout->addItem(it.key(), r.x(), r.y(), r.width(), r.height());
-    }
-}
-
-void QtGroupBoxPropertyBrowserPrivate::removeRow(QGridLayout *layout, int row) const
-{
-    QMap<QLayoutItem *, QRect> itemToPos;
-    int idx = 0;
-    while (idx < layout->count()) {
-        int r, c, rs, cs;
-        layout->getItemPosition(idx, &r, &c, &rs, &cs);
-        if (r > row) {
-            itemToPos[layout->takeAt(idx)] = QRect(r - 1, c, rs, cs);
-        } else {
-            idx++;
-        }
-    }
-
-    const QMap<QLayoutItem *, QRect>::ConstIterator icend = itemToPos.constEnd();
-    for (QMap<QLayoutItem *, QRect>::ConstIterator it = itemToPos.constBegin(); it != icend; ++it) {
-        const QRect r = it.value();
-        layout->addItem(it.key(), r.x(), r.y(), r.width(), r.height());
-    }
-}
-
-bool QtGroupBoxPropertyBrowserPrivate::hasHeader(WidgetItem *item) const
-{
-    if (item->widget)
-        return true;
-    return false;
-}
-
-void QtGroupBoxPropertyBrowserPrivate::propertyChanged(QtBrowserItem *index)
-{
-    WidgetItem *item = m_indexToItem.value(index);
-
-    updateItem(item);
-}
-
-void QtGroupBoxPropertyBrowserPrivate::updateItem(WidgetItem *item)
-{
-    QtProperty *property = m_itemToIndex[item]->property();
-    if (item->groupBox) {
-        QFont font = item->groupBox->font();
-        font.setUnderline(property->isModified());
-        item->groupBox->setFont(font);
-        item->groupBox->setTitle(property->propertyName());
-        item->groupBox->setToolTip(property->toolTip());
-        item->groupBox->setStatusTip(property->statusTip());
-        item->groupBox->setWhatsThis(property->whatsThis());
-        item->groupBox->setEnabled(property->isEnabled());
-    }
-    if (item->label) {
-        QFont font = item->label->font();
-        font.setUnderline(property->isModified());
-        item->label->setFont(font);
-        item->label->setText(property->propertyName());
-        item->label->setToolTip(property->toolTip());
-        item->label->setStatusTip(property->statusTip());
-        item->label->setWhatsThis(property->whatsThis());
-        item->label->setEnabled(property->isEnabled());
-    }
-    if (item->widgetLabel) {
-        QFont font = item->widgetLabel->font();
-        font.setUnderline(false);
-        item->widgetLabel->setFont(font);
-        item->widgetLabel->setText(property->valueText());
-        item->widgetLabel->setEnabled(property->isEnabled());
-    }
-    if (item->widget) {
-        QFont font = item->widget->font();
-        font.setUnderline(false);
-        item->widget->setFont(font);
-        item->widget->setEnabled(property->isEnabled());
-        item->widget->setToolTip(property->valueText());
-    }
-    //item->setIcon(1, property->valueIcon());
-}
-
-
-
-/**
-    \class QtGroupBoxPropertyBrowser
-
-    \brief The QtGroupBoxPropertyBrowser class provides a QGroupBox
-    based property browser.
-
-    A property browser is a widget that enables the user to edit a
-    given set of properties. Each property is represented by a label
-    specifying the property's name, and an editing widget (e.g. a line
-    edit or a combobox) holding its value. A property can have zero or
-    more subproperties.
-
-    QtGroupBoxPropertyBrowser provides group boxes for all nested
-    properties, i.e. subproperties are enclosed by a group box with
-    the parent property's name as its title. For example:
-
-    \image qtgroupboxpropertybrowser.png
-
-    Use the QtAbstractPropertyBrowser API to add, insert and remove
-    properties from an instance of the QtGroupBoxPropertyBrowser
-    class. The properties themselves are created and managed by
-    implementations of the QtAbstractPropertyManager class.
-
-    \sa QtTreePropertyBrowser, QtAbstractPropertyBrowser
-*/
-
-/**
-    Creates a property browser with the given \a parent.
-*/
-QtGroupBoxPropertyBrowser::QtGroupBoxPropertyBrowser(QWidget *parent)
-    : QtAbstractPropertyBrowser(parent)
-{
-    d_ptr = new QtGroupBoxPropertyBrowserPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->init(this);
-}
-
-/**
-    Destroys this property browser.
-
-    Note that the properties that were inserted into this browser are
-    \e not destroyed since they may still be used in other
-    browsers. The properties are owned by the manager that created
-    them.
-
-    \sa QtProperty, QtAbstractPropertyManager
-*/
-QtGroupBoxPropertyBrowser::~QtGroupBoxPropertyBrowser()
-{
-    const QMap<QtGroupBoxPropertyBrowserPrivate::WidgetItem *, QtBrowserItem *>::ConstIterator icend = d_ptr->m_itemToIndex.constEnd();
-    for (QMap<QtGroupBoxPropertyBrowserPrivate::WidgetItem *, QtBrowserItem *>::ConstIterator it = d_ptr->m_itemToIndex.constBegin(); it != icend; ++it)
-        delete it.key();
-    delete d_ptr;
-}
-
-/**
-    \reimp
-*/
-void QtGroupBoxPropertyBrowser::itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem)
-{
-    d_ptr->propertyInserted(item, afterItem);
-}
-
-/**
-    \reimp
-*/
-void QtGroupBoxPropertyBrowser::itemRemoved(QtBrowserItem *item)
-{
-    d_ptr->propertyRemoved(item);
-}
-
-/**
-    \reimp
-*/
-void QtGroupBoxPropertyBrowser::itemChanged(QtBrowserItem *item)
-{
-    d_ptr->propertyChanged(item);
-}
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#include "moc_qtgroupboxpropertybrowser.cpp"
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qtgroupboxpropertybrowser.h"
+#include <QtCore/QSet>
+#include <QtGui/QGridLayout>
+#include <QtGui/QLabel>
+#include <QtGui/QGroupBox>
+#include <QtCore/QTimer>
+#include <QtCore/QMap>
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+class QtGroupBoxPropertyBrowserPrivate
+{
+    QtGroupBoxPropertyBrowser *q_ptr;
+    Q_DECLARE_PUBLIC(QtGroupBoxPropertyBrowser)
+public:
+
+    void init(QWidget *parent);
+
+    void propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex);
+    void propertyRemoved(QtBrowserItem *index);
+    void propertyChanged(QtBrowserItem *index);
+    QWidget *createEditor(QtProperty *property, QWidget *parent) const
+        { return q_ptr->createEditor(property, parent); }
+
+    void slotEditorDestroyed();
+    void slotUpdate();
+
+    struct WidgetItem
+    {
+        WidgetItem() : widget(0), label(0), widgetLabel(0),
+                groupBox(0), layout(0), line(0), parent(0) { }
+        QWidget *widget; // can be null
+        QLabel *label;
+        QLabel *widgetLabel;
+        QGroupBox *groupBox;
+        QGridLayout *layout;
+        QFrame *line;
+        WidgetItem *parent;
+        QList<WidgetItem *> children;
+    };
+private:
+    void updateLater();
+    void updateItem(WidgetItem *item);
+    void insertRow(QGridLayout *layout, int row) const;
+    void removeRow(QGridLayout *layout, int row) const;
+
+    bool hasHeader(WidgetItem *item) const;
+
+    QMap<QtBrowserItem *, WidgetItem *> m_indexToItem;
+    QMap<WidgetItem *, QtBrowserItem *> m_itemToIndex;
+    QMap<QWidget *, WidgetItem *> m_widgetToItem;
+    QGridLayout *m_mainLayout;
+    QList<WidgetItem *> m_children;
+    QList<WidgetItem *> m_recreateQueue;
+};
+
+void QtGroupBoxPropertyBrowserPrivate::init(QWidget *parent)
+{
+    m_mainLayout = new QGridLayout();
+    parent->setLayout(m_mainLayout);
+    QLayoutItem *item = new QSpacerItem(0, 0,
+                QSizePolicy::Fixed, QSizePolicy::Expanding);
+    m_mainLayout->addItem(item, 0, 0);
+}
+
+void QtGroupBoxPropertyBrowserPrivate::slotEditorDestroyed()
+{
+    QWidget *editor = qobject_cast<QWidget *>(q_ptr->sender());
+    if (!editor)
+        return;
+    if (!m_widgetToItem.contains(editor))
+        return;
+    m_widgetToItem[editor]->widget = 0;
+    m_widgetToItem.remove(editor);
+}
+
+void QtGroupBoxPropertyBrowserPrivate::slotUpdate()
+{
+    QListIterator<WidgetItem *> itItem(m_recreateQueue);
+    while (itItem.hasNext()) {
+        WidgetItem *item = itItem.next();
+
+        WidgetItem *par = item->parent;
+        QWidget *w = 0;
+        QGridLayout *l = 0;
+        int oldRow = -1;
+        if (!par) {
+            w = q_ptr;
+            l = m_mainLayout;
+            oldRow = m_children.indexOf(item);
+        } else {
+            w = par->groupBox;
+            l = par->layout;
+            oldRow = par->children.indexOf(item);
+            if (hasHeader(par))
+                oldRow += 2;
+        }
+
+        if (item->widget) {
+            item->widget->setParent(w);
+        } else if (item->widgetLabel) {
+            item->widgetLabel->setParent(w);
+        } else {
+            item->widgetLabel = new QLabel(w);
+        }
+        int span = 1;
+        if (item->widget)
+            l->addWidget(item->widget, oldRow, 1, 1, 1);
+        else if (item->widgetLabel)
+            l->addWidget(item->widgetLabel, oldRow, 1, 1, 1);
+        else
+            span = 2;
+        item->label = new QLabel(w);
+        item->label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
+        l->addWidget(item->label, oldRow, 0, 1, span);
+
+        updateItem(item);
+    }
+    m_recreateQueue.clear();
+}
+
+void QtGroupBoxPropertyBrowserPrivate::updateLater()
+{
+    QTimer::singleShot(0, q_ptr, SLOT(slotUpdate()));
+}
+
+void QtGroupBoxPropertyBrowserPrivate::propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex)
+{
+    WidgetItem *afterItem = m_indexToItem.value(afterIndex);
+    WidgetItem *parentItem = m_indexToItem.value(index->parent());
+
+    WidgetItem *newItem = new WidgetItem();
+    newItem->parent = parentItem;
+
+    QGridLayout *layout = 0;
+    QWidget *parentWidget = 0;
+    int row = -1;
+    if (!afterItem) {
+        row = 0;
+        if (parentItem)
+            parentItem->children.insert(0, newItem);
+        else
+            m_children.insert(0, newItem);
+    } else {
+        if (parentItem) {
+            row = parentItem->children.indexOf(afterItem) + 1;
+            parentItem->children.insert(row, newItem);
+        } else {
+            row = m_children.indexOf(afterItem) + 1;
+            m_children.insert(row, newItem);
+        }
+    }
+    if (parentItem && hasHeader(parentItem))
+        row += 2;
+
+    if (!parentItem) {
+        layout = m_mainLayout;
+        parentWidget = q_ptr;;
+    } else {
+        if (!parentItem->groupBox) {
+            m_recreateQueue.removeAll(parentItem);
+            WidgetItem *par = parentItem->parent;
+            QWidget *w = 0;
+            QGridLayout *l = 0;
+            int oldRow = -1;
+            if (!par) {
+                w = q_ptr;
+                l = m_mainLayout;
+                oldRow = m_children.indexOf(parentItem);
+            } else {
+                w = par->groupBox;
+                l = par->layout;
+                oldRow = par->children.indexOf(parentItem);
+                if (hasHeader(par))
+                    oldRow += 2;
+            }
+            parentItem->groupBox = new QGroupBox(w);
+            parentItem->layout = new QGridLayout();
+            parentItem->groupBox->setLayout(parentItem->layout);
+            if (parentItem->label) {
+                l->removeWidget(parentItem->label);
+                delete parentItem->label;
+                parentItem->label = 0;
+            }
+            if (parentItem->widget) {
+                l->removeWidget(parentItem->widget);
+                parentItem->widget->setParent(parentItem->groupBox);
+                parentItem->layout->addWidget(parentItem->widget, 0, 0, 1, 2);
+                parentItem->line = new QFrame(parentItem->groupBox);
+            } else if (parentItem->widgetLabel) {
+                l->removeWidget(parentItem->widgetLabel);
+                delete parentItem->widgetLabel;
+                parentItem->widgetLabel = 0;
+            }
+            if (parentItem->line) {
+                parentItem->line->setFrameShape(QFrame::HLine);
+                parentItem->line->setFrameShadow(QFrame::Sunken);
+                parentItem->layout->addWidget(parentItem->line, 1, 0, 1, 2);
+            }
+            l->addWidget(parentItem->groupBox, oldRow, 0, 1, 2);
+            updateItem(parentItem);
+        }
+        layout = parentItem->layout;
+        parentWidget = parentItem->groupBox;
+    }
+
+    newItem->label = new QLabel(parentWidget);
+    newItem->label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
+    newItem->widget = createEditor(index->property(), parentWidget);
+    if (!newItem->widget) {
+        newItem->widgetLabel = new QLabel(parentWidget);
+    } else {
+        QObject::connect(newItem->widget, SIGNAL(destroyed()), q_ptr, SLOT(slotEditorDestroyed()));
+        m_widgetToItem[newItem->widget] = newItem;
+    }
+
+    insertRow(layout, row);
+    int span = 1;
+    if (newItem->widget)
+        layout->addWidget(newItem->widget, row, 1);
+    else if (newItem->widgetLabel)
+        layout->addWidget(newItem->widgetLabel, row, 1);
+    else
+        span = 2;
+    layout->addWidget(newItem->label, row, 0, 1, span);
+
+    m_itemToIndex[newItem] = index;
+    m_indexToItem[index] = newItem;
+
+    updateItem(newItem);
+}
+
+void QtGroupBoxPropertyBrowserPrivate::propertyRemoved(QtBrowserItem *index)
+{
+    WidgetItem *item = m_indexToItem.value(index);
+
+    m_indexToItem.remove(index);
+    m_itemToIndex.remove(item);
+
+    WidgetItem *parentItem = item->parent;
+
+    int row = -1;
+
+    if (parentItem) {
+        row = parentItem->children.indexOf(item);
+        parentItem->children.removeAt(row);
+        if (hasHeader(parentItem))
+            row += 2;
+    } else {
+        row = m_children.indexOf(item);
+        m_children.removeAt(row);
+    }
+
+    if (item->widget)
+        delete item->widget;
+    if (item->label)
+        delete item->label;
+    if (item->widgetLabel)
+        delete item->widgetLabel;
+    if (item->groupBox)
+        delete item->groupBox;
+
+    if (!parentItem) {
+        removeRow(m_mainLayout, row);
+    } else if (parentItem->children.count() != 0) {
+        removeRow(parentItem->layout, row);
+    } else {
+        WidgetItem *par = parentItem->parent;
+        QWidget *w = 0;
+        QGridLayout *l = 0;
+        int oldRow = -1;
+        if (!par) {
+            w = q_ptr;
+            l = m_mainLayout;
+            oldRow = m_children.indexOf(parentItem);
+        } else {
+            w = par->groupBox;
+            l = par->layout;
+            oldRow = par->children.indexOf(parentItem);
+            if (hasHeader(par))
+                oldRow += 2;
+        }
+
+        if (parentItem->widget) {
+            parentItem->widget->hide();
+            parentItem->widget->setParent(0);
+        } else if (parentItem->widgetLabel) {
+            parentItem->widgetLabel->hide();
+            parentItem->widgetLabel->setParent(0);
+        } else {
+            //parentItem->widgetLabel = new QLabel(w);
+        }
+        l->removeWidget(parentItem->groupBox);
+        delete parentItem->groupBox;
+        parentItem->groupBox = 0;
+        parentItem->line = 0;
+        parentItem->layout = 0;
+        if (!m_recreateQueue.contains(parentItem))
+            m_recreateQueue.append(parentItem);
+        updateLater();
+    }
+    m_recreateQueue.removeAll(item);
+
+    delete item;
+}
+
+void QtGroupBoxPropertyBrowserPrivate::insertRow(QGridLayout *layout, int row) const
+{
+    QMap<QLayoutItem *, QRect> itemToPos;
+    int idx = 0;
+    while (idx < layout->count()) {
+        int r, c, rs, cs;
+        layout->getItemPosition(idx, &r, &c, &rs, &cs);
+        if (r >= row) {
+            itemToPos[layout->takeAt(idx)] = QRect(r + 1, c, rs, cs);
+        } else {
+            idx++;
+        }
+    }
+
+    const QMap<QLayoutItem *, QRect>::ConstIterator icend = itemToPos.constEnd();
+    for (QMap<QLayoutItem *, QRect>::ConstIterator it = itemToPos.constBegin(); it != icend; ++it) {
+        const QRect r = it.value();
+        layout->addItem(it.key(), r.x(), r.y(), r.width(), r.height());
+    }
+}
+
+void QtGroupBoxPropertyBrowserPrivate::removeRow(QGridLayout *layout, int row) const
+{
+    QMap<QLayoutItem *, QRect> itemToPos;
+    int idx = 0;
+    while (idx < layout->count()) {
+        int r, c, rs, cs;
+        layout->getItemPosition(idx, &r, &c, &rs, &cs);
+        if (r > row) {
+            itemToPos[layout->takeAt(idx)] = QRect(r - 1, c, rs, cs);
+        } else {
+            idx++;
+        }
+    }
+
+    const QMap<QLayoutItem *, QRect>::ConstIterator icend = itemToPos.constEnd();
+    for (QMap<QLayoutItem *, QRect>::ConstIterator it = itemToPos.constBegin(); it != icend; ++it) {
+        const QRect r = it.value();
+        layout->addItem(it.key(), r.x(), r.y(), r.width(), r.height());
+    }
+}
+
+bool QtGroupBoxPropertyBrowserPrivate::hasHeader(WidgetItem *item) const
+{
+    if (item->widget)
+        return true;
+    return false;
+}
+
+void QtGroupBoxPropertyBrowserPrivate::propertyChanged(QtBrowserItem *index)
+{
+    WidgetItem *item = m_indexToItem.value(index);
+
+    updateItem(item);
+}
+
+void QtGroupBoxPropertyBrowserPrivate::updateItem(WidgetItem *item)
+{
+    QtProperty *property = m_itemToIndex[item]->property();
+    if (item->groupBox) {
+        QFont font = item->groupBox->font();
+        font.setUnderline(property->isModified());
+        item->groupBox->setFont(font);
+        item->groupBox->setTitle(property->propertyName());
+        item->groupBox->setToolTip(property->toolTip());
+        item->groupBox->setStatusTip(property->statusTip());
+        item->groupBox->setWhatsThis(property->whatsThis());
+        item->groupBox->setEnabled(property->isEnabled());
+    }
+    if (item->label) {
+        QFont font = item->label->font();
+        font.setUnderline(property->isModified());
+        item->label->setFont(font);
+        item->label->setText(property->propertyName());
+        item->label->setToolTip(property->toolTip());
+        item->label->setStatusTip(property->statusTip());
+        item->label->setWhatsThis(property->whatsThis());
+        item->label->setEnabled(property->isEnabled());
+    }
+    if (item->widgetLabel) {
+        QFont font = item->widgetLabel->font();
+        font.setUnderline(false);
+        item->widgetLabel->setFont(font);
+        item->widgetLabel->setText(property->valueText());
+        item->widgetLabel->setEnabled(property->isEnabled());
+    }
+    if (item->widget) {
+        QFont font = item->widget->font();
+        font.setUnderline(false);
+        item->widget->setFont(font);
+        item->widget->setEnabled(property->isEnabled());
+        item->widget->setToolTip(property->valueText());
+    }
+    //item->setIcon(1, property->valueIcon());
+}
+
+
+
+/**
+    \class QtGroupBoxPropertyBrowser
+
+    \brief The QtGroupBoxPropertyBrowser class provides a QGroupBox
+    based property browser.
+
+    A property browser is a widget that enables the user to edit a
+    given set of properties. Each property is represented by a label
+    specifying the property's name, and an editing widget (e.g. a line
+    edit or a combobox) holding its value. A property can have zero or
+    more subproperties.
+
+    QtGroupBoxPropertyBrowser provides group boxes for all nested
+    properties, i.e. subproperties are enclosed by a group box with
+    the parent property's name as its title. For example:
+
+    \image qtgroupboxpropertybrowser.png
+
+    Use the QtAbstractPropertyBrowser API to add, insert and remove
+    properties from an instance of the QtGroupBoxPropertyBrowser
+    class. The properties themselves are created and managed by
+    implementations of the QtAbstractPropertyManager class.
+
+    \sa QtTreePropertyBrowser, QtAbstractPropertyBrowser
+*/
+
+/**
+    Creates a property browser with the given \a parent.
+*/
+QtGroupBoxPropertyBrowser::QtGroupBoxPropertyBrowser(QWidget *parent)
+    : QtAbstractPropertyBrowser(parent)
+{
+    d_ptr = new QtGroupBoxPropertyBrowserPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->init(this);
+}
+
+/**
+    Destroys this property browser.
+
+    Note that the properties that were inserted into this browser are
+    \e not destroyed since they may still be used in other
+    browsers. The properties are owned by the manager that created
+    them.
+
+    \sa QtProperty, QtAbstractPropertyManager
+*/
+QtGroupBoxPropertyBrowser::~QtGroupBoxPropertyBrowser()
+{
+    const QMap<QtGroupBoxPropertyBrowserPrivate::WidgetItem *, QtBrowserItem *>::ConstIterator icend = d_ptr->m_itemToIndex.constEnd();
+    for (QMap<QtGroupBoxPropertyBrowserPrivate::WidgetItem *, QtBrowserItem *>::ConstIterator it = d_ptr->m_itemToIndex.constBegin(); it != icend; ++it)
+        delete it.key();
+    delete d_ptr;
+}
+
+/**
+    \reimp
+*/
+void QtGroupBoxPropertyBrowser::itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem)
+{
+    d_ptr->propertyInserted(item, afterItem);
+}
+
+/**
+    \reimp
+*/
+void QtGroupBoxPropertyBrowser::itemRemoved(QtBrowserItem *item)
+{
+    d_ptr->propertyRemoved(item);
+}
+
+/**
+    \reimp
+*/
+void QtGroupBoxPropertyBrowser::itemChanged(QtBrowserItem *item)
+{
+    d_ptr->propertyChanged(item);
+}
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#include "moc_qtgroupboxpropertybrowser.cpp"
diff --git a/Code/Mantid/QtPropertyBrowser/src/qtgroupboxpropertybrowser.h b/Code/Mantid/QtPropertyBrowser/src/qtgroupboxpropertybrowser.h
index 6b13fb40e4afafdc818ef32463977fddfcc9813e..075f3286e75d0e13a8944b5a8e8c36f39514da6e 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qtgroupboxpropertybrowser.h
+++ b/Code/Mantid/QtPropertyBrowser/src/qtgroupboxpropertybrowser.h
@@ -1,126 +1,126 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QTGROUPBOXPROPERTYBROWSER_H
-#define QTGROUPBOXPROPERTYBROWSER_H
-
-#include "qtpropertybrowser.h"
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-class QtGroupBoxPropertyBrowserPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtGroupBoxPropertyBrowser : public QtAbstractPropertyBrowser
-{
-    Q_OBJECT
-public:
-
-    QtGroupBoxPropertyBrowser(QWidget *parent = 0);
-    ~QtGroupBoxPropertyBrowser();
-
-protected:
-    virtual void itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem);
-    virtual void itemRemoved(QtBrowserItem *item);
-    virtual void itemChanged(QtBrowserItem *item);
-
-private:
-
-    QtGroupBoxPropertyBrowserPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtGroupBoxPropertyBrowser)
-    Q_DISABLE_COPY(QtGroupBoxPropertyBrowser)
-    Q_PRIVATE_SLOT(d_func(), void slotUpdate())
-    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed())
-
-};
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#endif
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QTGROUPBOXPROPERTYBROWSER_H
+#define QTGROUPBOXPROPERTYBROWSER_H
+
+#include "qtpropertybrowser.h"
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+class QtGroupBoxPropertyBrowserPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtGroupBoxPropertyBrowser : public QtAbstractPropertyBrowser
+{
+    Q_OBJECT
+public:
+
+    QtGroupBoxPropertyBrowser(QWidget *parent = 0);
+    ~QtGroupBoxPropertyBrowser();
+
+protected:
+    virtual void itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem);
+    virtual void itemRemoved(QtBrowserItem *item);
+    virtual void itemChanged(QtBrowserItem *item);
+
+private:
+
+    QtGroupBoxPropertyBrowserPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtGroupBoxPropertyBrowser)
+    Q_DISABLE_COPY(QtGroupBoxPropertyBrowser)
+    Q_PRIVATE_SLOT(d_func(), void slotUpdate())
+    Q_PRIVATE_SLOT(d_func(), void slotEditorDestroyed())
+
+};
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#endif
diff --git a/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowser.cpp b/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowser.cpp
index fdaeb0999a8a34417d99ae40de16e6ed3e8d8853..f38d0230ae103673212edec018aff471e2346b40 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowser.cpp
+++ b/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowser.cpp
@@ -1,2028 +1,2028 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qtpropertybrowser.h"
-#include <QtCore/QSet>
-#include <QtCore/QMap>
-#include <QtGui/QIcon>
-
-#if defined(Q_CC_MSVC)
-#    pragma warning(disable: 4786) /* MS VS 6: truncating debug info after 255 characters */
-#endif
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-class QtPropertyPrivate
-{
-public:
-    QtPropertyPrivate(QtAbstractPropertyManager *manager) : m_enabled(true), m_modified(false), m_manager(manager) {}
-    QtProperty *q_ptr;
-
-    QSet<QtProperty *> m_parentItems;
-    QList<QtProperty *> m_subItems;
-
-    QString m_toolTip;
-    QString m_statusTip;
-    QString m_whatsThis;
-    QString m_name;
-    bool m_enabled;
-    bool m_modified;
-
-    QtAbstractPropertyManager * const m_manager;
-};
-
-class QtAbstractPropertyManagerPrivate
-{
-    QtAbstractPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtAbstractPropertyManager)
-public:
-    void propertyDestroyed(QtProperty *property);
-    void propertyChanged(QtProperty *property) const;
-    void propertyRemoved(QtProperty *property,
-                QtProperty *parentProperty) const;
-    void propertyInserted(QtProperty *property, QtProperty *parentProperty,
-                QtProperty *afterProperty) const;
-
-    QSet<QtProperty *> m_properties;
-};
-
-/**
-    \class QtProperty
-
-    \brief The QtProperty class encapsulates an instance of a property.
-
-    Properties are created by objects of QtAbstractPropertyManager
-    subclasses; a manager can create properties of a given type, and
-    is used in conjunction with the QtAbstractPropertyBrowser class. A
-    property is always owned by the manager that created it, which can
-    be retrieved using the propertyManager() function.
-
-    QtProperty contains the most common property attributes, and
-    provides functions for retrieving as well as setting their values:
-
-    \table
-    \header \o Getter \o Setter
-    \row
-    \o propertyName() \o setPropertyName()
-    \row
-    \o statusTip() \o setStatusTip()
-    \row
-    \o toolTip() \o setToolTip()
-    \row
-    \o whatsThis() \o setWhatsThis()
-    \row
-    \o isEnabled() \o setEnabled()
-    \row
-    \o isModified() \o setModified()
-    \row
-    \o valueText() \o Nop
-    \row
-    \o valueIcon() \o Nop
-    \endtable
-
-    It is also possible to nest properties: QtProperty provides the
-    addSubProperty(), insertSubProperty() and removeSubProperty() functions to
-    manipulate the set of subproperties. Use the subProperties()
-    function to retrieve a property's current set of subproperties.
-    Note that nested properties are not owned by the parent property,
-    i.e. each subproperty is owned by the manager that created it.
-
-    \sa QtAbstractPropertyManager, QtBrowserItem
-*/
-
-/**
-    Creates a property with the given \a manager.
-
-    This constructor is only useful when creating a custom QtProperty
-    subclass (e.g. QtVariantProperty). To create a regular QtProperty
-    object, use the QtAbstractPropertyManager::addProperty()
-    function instead.
-
-    \sa QtAbstractPropertyManager::addProperty()
-*/
-QtProperty::QtProperty(QtAbstractPropertyManager *manager)
-{
-    d_ptr = new QtPropertyPrivate(manager);
-    d_ptr->q_ptr = this;
-}
-
-/**
-    Destroys this property.
-
-    Note that subproperties are detached but not destroyed, i.e. they
-    can still be used in another context.
-
-    \sa QtAbstractPropertyManager::clear()
-
-*/
-QtProperty::~QtProperty()
-{
-    QSetIterator<QtProperty *> itParent(d_ptr->m_parentItems);
-    while (itParent.hasNext()) {
-        QtProperty *property = itParent.next();
-        property->d_ptr->m_manager->d_ptr->propertyRemoved(this, property);
-    }
-
-    d_ptr->m_manager->d_ptr->propertyDestroyed(this);
-
-    QListIterator<QtProperty *> itChild(d_ptr->m_subItems);
-    while (itChild.hasNext()) {
-        QtProperty *property = itChild.next();
-        property->d_ptr->m_parentItems.remove(this);
-    }
-
-    itParent.toFront();
-    while (itParent.hasNext()) {
-        QtProperty *property = itParent.next();
-        property->d_ptr->m_subItems.removeAll(this);
-    }
-    delete d_ptr;
-}
-
-/**
-    Returns the set of subproperties.
-
-    Note that subproperties are not owned by \e this property, but by
-    the manager that created them.
-
-    \sa insertSubProperty(), removeSubProperty()
-*/
-QList<QtProperty *> QtProperty::subProperties() const
-{
-    return d_ptr->m_subItems;
-}
-
-/**
-    Returns a pointer to the manager that owns this property.
-*/
-QtAbstractPropertyManager *QtProperty::propertyManager() const
-{
-    return d_ptr->m_manager;
-}
-
-/**
-    Returns the property's  tool tip.
-
-    \sa setToolTip()
-*/
-QString QtProperty::toolTip() const
-{
-    return d_ptr->m_toolTip;
-}
-
-/**
-    Returns the property's status tip.
-
-    \sa setStatusTip()
-*/
-QString QtProperty::statusTip() const
-{
-    return d_ptr->m_statusTip;
-}
-
-/**
-    Returns the property's "What's This" help text.
-
-    \sa setWhatsThis()
-*/
-QString QtProperty::whatsThis() const
-{
-    return d_ptr->m_whatsThis;
-}
-
-/**
-    Returns the property's name.
-
-    \sa setPropertyName()
-*/
-QString QtProperty::propertyName() const
-{
-    return d_ptr->m_name;
-}
-
-/**
-    Returns whether the property is enabled.
-
-    \sa setEnabled()
-*/
-bool QtProperty::isEnabled() const
-{
-    return d_ptr->m_enabled;
-}
-
-/**
-    Returns whether the property is modified.
-
-    \sa setModified()
-*/
-bool QtProperty::isModified() const
-{
-    return d_ptr->m_modified;
-}
-
-/**
-    Returns whether the property has a value.
-
-    \sa QtAbstractPropertyManager::hasValue()
-*/
-bool QtProperty::hasValue() const
-{
-    return d_ptr->m_manager->hasValue(this);
-}
-
-/**
-    Returns an icon representing the current state of this property.
-
-    If the given property type can not generate such an icon, this
-    function returns an invalid icon.
-
-    \sa QtAbstractPropertyManager::valueIcon()
-*/
-QIcon QtProperty::valueIcon() const
-{
-    return d_ptr->m_manager->valueIcon(this);
-}
-
-/**
-    Returns a string representing the current state of this property.
-
-    If the given property type can not generate such a string, this
-    function returns an empty string.
-
-    \sa QtAbstractPropertyManager::valueText()
-*/
-QString QtProperty::valueText() const
-{
-    return d_ptr->m_manager->valueText(this);
-}
-
-/**
-    Sets the property's tool tip to the given \a text.
-
-    \sa toolTip()
-*/
-void QtProperty::setToolTip(const QString &text)
-{
-    if (d_ptr->m_toolTip == text)
-        return;
-
-    d_ptr->m_toolTip = text;
-    propertyChanged();
-}
-
-/**
-    Sets the property's status tip to the given \a text.
-
-    \sa statusTip()
-*/
-void QtProperty::setStatusTip(const QString &text)
-{
-    if (d_ptr->m_statusTip == text)
-        return;
-
-    d_ptr->m_statusTip = text;
-    propertyChanged();
-}
-
-/**
-    Sets the property's "What's This" help text to the given \a text.
-
-    \sa whatsThis()
-*/
-void QtProperty::setWhatsThis(const QString &text)
-{
-    if (d_ptr->m_whatsThis == text)
-        return;
-
-    d_ptr->m_whatsThis = text;
-    propertyChanged();
-}
-
-/**
-    \fn void QtProperty::setPropertyName(const QString &name)
-
-    Sets the property's  name to the given \a name.
-
-    \sa propertyName()
-*/
-void QtProperty::setPropertyName(const QString &text)
-{
-    if (d_ptr->m_name == text)
-        return;
-
-    d_ptr->m_name = text;
-    propertyChanged();
-}
-
-/**
-    Enables or disables the property according to the passed \a enable value.
-
-    \sa isEnabled()
-*/
-void QtProperty::setEnabled(bool enable)
-{
-    if (d_ptr->m_enabled == enable)
-        return;
-
-    d_ptr->m_enabled = enable;
-    propertyChanged();
-}
-
-/**
-    Sets the property's modified state according to the passed \a modified value.
-
-    \sa isModified()
-*/
-void QtProperty::setModified(bool modified)
-{
-    if (d_ptr->m_modified == modified)
-        return;
-
-    d_ptr->m_modified = modified;
-    propertyChanged();
-}
-
-/**
-    Appends the given \a property to this property's subproperties.
-
-    If the given \a property already is added, this function does
-    nothing.
-
-    \sa insertSubProperty(), removeSubProperty()
-*/
-void QtProperty::addSubProperty(QtProperty *property)
-{
-    QtProperty *after = 0;
-    if (d_ptr->m_subItems.count() > 0)
-        after = d_ptr->m_subItems.last();
-    insertSubProperty(property, after);
-}
-
-/**
-    \fn void QtProperty::insertSubProperty(QtProperty *property, QtProperty *precedingProperty)
-
-    Inserts the given \a property after the specified \a
-    precedingProperty into this property's list of subproperties.  If
-    \a precedingProperty is 0, the specified \a property is inserted
-    at the beginning of the list.
-
-    If the given \a property already is inserted, this function does
-    nothing.
-
-    \sa addSubProperty(), removeSubProperty()
-*/
-void QtProperty::insertSubProperty(QtProperty *property,
-            QtProperty *afterProperty)
-{
-    if (!property)
-        return;
-
-    if (property == this)
-        return;
-
-    // traverse all children of item. if this item is a child of item then cannot add.
-    QList<QtProperty *> pendingList = property->subProperties();
-    QMap<QtProperty *, bool> visited;
-    while (!pendingList.isEmpty()) {
-        QtProperty *i = pendingList.first();
-        if (i == this)
-            return;
-        pendingList.removeFirst();
-        if (visited.contains(i))
-            continue;
-        visited[i] = true;
-        pendingList += i->subProperties();
-    }
-
-    pendingList = subProperties();
-    int pos = 0;
-    int newPos = 0;
-    QtProperty *properAfterProperty = 0;
-    while (pos < pendingList.count()) {
-        QtProperty *i = pendingList.at(pos);
-        if (i == property)
-            return; // if item is already inserted in this item then cannot add.
-        if (i == afterProperty) {
-            newPos = pos + 1;
-            properAfterProperty = afterProperty;
-        }
-        pos++;
-    }
-
-    d_ptr->m_subItems.insert(newPos, property);
-    property->d_ptr->m_parentItems.insert(this);
-
-    d_ptr->m_manager->d_ptr->propertyInserted(property, this, properAfterProperty);
-}
-
-/**
-    Removes the given \a property from the list of subproperties
-    without deleting it.
-
-    \sa addSubProperty(), insertSubProperty()
-*/
-void QtProperty::removeSubProperty(QtProperty *property)
-{
-    if (!property)
-        return;
-
-    d_ptr->m_manager->d_ptr->propertyRemoved(property, this);
-
-    QList<QtProperty *> pendingList = subProperties();
-    int pos = 0;
-    while (pos < pendingList.count()) {
-        if (pendingList.at(pos) == property) {
-            d_ptr->m_subItems.removeAt(pos);
-            property->d_ptr->m_parentItems.remove(this);
-
-            return;
-        }
-        pos++;
-    }
-}
-
-/**
-    \internal
-*/
-void QtProperty::propertyChanged()
-{
-    d_ptr->m_manager->d_ptr->propertyChanged(this);
-}
-
-////////////////////////////////
-
-void QtAbstractPropertyManagerPrivate::propertyDestroyed(QtProperty *property)
-{
-    if (m_properties.contains(property)) {
-        emit q_ptr->propertyDestroyed(property);
-        q_ptr->uninitializeProperty(property);
-        m_properties.remove(property);
-    }
-}
-
-void QtAbstractPropertyManagerPrivate::propertyChanged(QtProperty *property) const
-{
-    emit q_ptr->propertyChanged(property);
-}
-
-void QtAbstractPropertyManagerPrivate::propertyRemoved(QtProperty *property,
-            QtProperty *parentProperty) const
-{
-    emit q_ptr->propertyRemoved(property, parentProperty);
-}
-
-void QtAbstractPropertyManagerPrivate::propertyInserted(QtProperty *property,
-            QtProperty *parentProperty, QtProperty *afterProperty) const
-{
-    emit q_ptr->propertyInserted(property, parentProperty, afterProperty);
-}
-
-/**
-    \class QtAbstractPropertyManager
-
-    \brief The QtAbstractPropertyManager provides an interface for
-    property managers.
-
-    A manager can create and manage properties of a given type, and is
-    used in conjunction with the QtAbstractPropertyBrowser class.
-
-    When using a property browser widget, the properties are created
-    and managed by implementations of the QtAbstractPropertyManager
-    class. To ensure that the properties' values will be displayed
-    using suitable editing widgets, the managers are associated with
-    objects of QtAbstractEditorFactory subclasses. The property browser
-    will use these associations to determine which factories it should
-    use to create the preferred editing widgets.
-
-    The QtAbstractPropertyManager class provides common functionality
-    like creating a property using the addProperty() function, and
-    retrieving the properties created by the manager using the
-    properties() function. The class also provides signals that are
-    emitted when the manager's properties change: propertyInserted(),
-    propertyRemoved(), propertyChanged() and propertyDestroyed().
-
-    QtAbstractPropertyManager subclasses are supposed to provide their
-    own type specific API. Note that several ready-made
-    implementations are available:
-
-    \list
-    \o QtBoolPropertyManager
-    \o QtColorPropertyManager
-    \o QtDatePropertyManager
-    \o QtDateTimePropertyManager
-    \o QtDoublePropertyManager
-    \o QtEnumPropertyManager
-    \o QtFlagPropertyManager
-    \o QtFontPropertyManager
-    \o QtGroupPropertyManager
-    \o QtIntPropertyManager
-    \o QtPointPropertyManager
-    \o QtRectPropertyManager
-    \o QtSizePropertyManager
-    \o QtSizePolicyPropertyManager
-    \o QtStringPropertyManager
-    \o QtTimePropertyManager
-    \o QtVariantPropertyManager
-    \endlist
-
-    \sa QtAbstractEditorFactoryBase, QtAbstractPropertyBrowser, QtProperty
-*/
-
-/**
-    \fn void QtAbstractPropertyManager::propertyInserted(QtProperty *newProperty,
-                QtProperty *parentProperty, QtProperty *precedingProperty)
-
-    This signal is emitted when a new subproperty is inserted into an
-    existing property, passing pointers to the \a newProperty, \a
-    parentProperty and \a precedingProperty as parameters.
-
-    If \a precedingProperty is 0, the \a newProperty was inserted at
-    the beginning of the \a parentProperty's subproperties list.
-
-    Note that signal is emitted only if the \a parentProperty is created
-    by this manager.
-
-    \sa QtAbstractPropertyBrowser::itemInserted()
-*/
-
-/**
-    \fn void QtAbstractPropertyManager::propertyChanged(QtProperty *property)
-
-    This signal is emitted whenever a property's data changes, passing
-    a pointer to the \a property as parameter.
-
-    Note that signal is only emitted for properties that are created by
-    this manager.
-
-    \sa QtAbstractPropertyBrowser::itemChanged()
-*/
-
-/**
-    \fn void QtAbstractPropertyManager::propertyRemoved(QtProperty *property, QtProperty *parent)
-
-    This signal is emitted when a subproperty is removed, passing
-    pointers to the removed \a property and the \a parent property as
-    parameters.
-
-    Note that signal is emitted only when the \a parent property is
-    created by this manager.
-
-    \sa QtAbstractPropertyBrowser::itemRemoved()
-*/
-
-/**
-    \fn void QtAbstractPropertyManager::propertyDestroyed(QtProperty *property)
-
-    This signal is emitted when the specified \a property is about to
-    be destroyed.
-
-    Note that signal is only emitted for properties that are created
-    by this manager.
-
-    \sa clear(), uninitializeProperty()
-*/
-
-/**
-    \fn void QtAbstractPropertyBrowser::currentItemChanged(QtBrowserItem *current)
-
-    This signal is emitted when the current item changes. The current item is specified by \a current.
-
-    \sa QtAbstractPropertyBrowser::setCurrentItem()
-*/
-
-/**
-    Creates an abstract property manager with the given \a parent.
-*/
-QtAbstractPropertyManager::QtAbstractPropertyManager(QObject *parent)
-    : QObject(parent)
-{
-    d_ptr = new QtAbstractPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys the manager. All properties created by the manager are
-    destroyed.
-*/
-QtAbstractPropertyManager::~QtAbstractPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Destroys all the properties that this manager has created.
-
-    \sa propertyDestroyed(), uninitializeProperty()
-*/
-void QtAbstractPropertyManager::clear() const
-{
-    while (!properties().isEmpty()) {
-        QSetIterator<QtProperty *> itProperty(properties());
-        QtProperty *prop = itProperty.next();
-        delete prop;
-    }
-}
-
-/**
-    Returns the set of properties created by this manager.
-
-    \sa addProperty()
-*/
-QSet<QtProperty *> QtAbstractPropertyManager::properties() const
-{
-    return d_ptr->m_properties;
-}
-
-/**
-    Returns whether the given \a property has a value.
-
-    The default implementation of this function returns true.
-
-    \sa QtProperty::hasValue()
-*/
-bool QtAbstractPropertyManager::hasValue(const QtProperty *property) const
-{
-    Q_UNUSED(property)
-    return true;
-}
-
-/**
-    Returns an icon representing the current state of the given \a
-    property.
-
-    The default implementation of this function returns an invalid
-    icon.
-
-    \sa QtProperty::valueIcon()
-*/
-QIcon QtAbstractPropertyManager::valueIcon(const QtProperty *property) const
-{
-    Q_UNUSED(property)
-    return QIcon();
-}
-
-/**
-    Returns a string representing the current state of the given \a
-    property.
-
-    The default implementation of this function returns an empty
-    string.
-
-    \sa QtProperty::valueText()
-*/
-QString QtAbstractPropertyManager::valueText(const QtProperty *property) const
-{
-    Q_UNUSED(property)
-    return QString();
-}
-
-/**
-    Creates a property with the given \a name which then is owned by this manager.
-
-    Internally, this function calls the createProperty() and
-    initializeProperty() functions.
-
-    \sa initializeProperty(), properties()
-*/
-QtProperty *QtAbstractPropertyManager::addProperty(const QString &name)
-{
-    QtProperty *property = createProperty();
-    if (property) {
-        property->setPropertyName(name);
-        d_ptr->m_properties.insert(property);
-        initializeProperty(property);
-    }
-    return property;
-}
-
-/**
-    Creates a property.
-
-    The base implementation produce QtProperty instances; Reimplement
-    this function to make this manager produce objects of a QtProperty
-    subclass.
-
-    \sa addProperty(), initializeProperty()
-*/
-QtProperty *QtAbstractPropertyManager::createProperty()
-{
-    return new QtProperty(this);
-}
-
-/**
-    \fn void QtAbstractPropertyManager::initializeProperty(QtProperty *property) = 0
-
-    This function is called whenever a new valid property pointer has
-    been created, passing the pointer as parameter.
-
-    The purpose is to let the manager know that the \a property has
-    been created so that it can provide additional attributes for the
-    new property, e.g. QtIntPropertyManager adds \l
-    {QtIntPropertyManager::value()}{value}, \l
-    {QtIntPropertyManager::minimum()}{minimum} and \l
-    {QtIntPropertyManager::maximum()}{maximum} attributes. Since each manager
-    subclass adds type specific attributes, this function is pure
-    virtual and must be reimplemented when deriving from the
-    QtAbstractPropertyManager class.
-
-    \sa addProperty(), createProperty()
-*/
-
-/**
-    This function is called just before the specified \a property is destroyed.
-
-    The purpose is to let the property manager know that the \a
-    property is being destroyed so that it can remove the property's
-    additional attributes.
-
-    \sa clear(),  propertyDestroyed()
-*/
-void QtAbstractPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    Q_UNUSED(property)
-}
-
-////////////////////////////////////
-
-/**
-    \class QtAbstractEditorFactoryBase
-
-    \brief The QtAbstractEditorFactoryBase provides an interface for
-    editor factories.
-
-    An editor factory is a class that is able to create an editing
-    widget of a specified type (e.g. line edits or comboboxes) for a
-    given QtProperty object, and it is used in conjunction with the
-    QtAbstractPropertyManager and QtAbstractPropertyBrowser classes.
-
-    When using a property browser widget, the properties are created
-    and managed by implementations of the QtAbstractPropertyManager
-    class. To ensure that the properties' values will be displayed
-    using suitable editing widgets, the managers are associated with
-    objects of QtAbstractEditorFactory subclasses. The property browser
-    will use these associations to determine which factories it should
-    use to create the preferred editing widgets.
-
-    Typically, an editor factory is created by subclassing the
-    QtAbstractEditorFactory template class which inherits
-    QtAbstractEditorFactoryBase. But note that several ready-made
-    implementations are available:
-
-    \list
-    \o QtCheckBoxFactory
-    \o QtDateEditFactory
-    \o QtDateTimeEditFactory
-    \o QtDoubleSpinBoxFactory
-    \o QtEnumEditorFactory
-    \o QtLineEditFactory
-    \o QtScrollBarFactory
-    \o QtSliderFactory
-    \o QtSpinBoxFactory
-    \o QtTimeEditFactory
-    \o QtVariantEditorFactory
-    \endlist
-
-    \sa QtAbstractPropertyManager, QtAbstractPropertyBrowser
-*/
-
-/**
-    \fn virtual QWidget *QtAbstractEditorFactoryBase::createEditor(QtProperty *property,
-        QWidget *parent) = 0
-
-    Creates an editing widget (with the given \a parent) for the given
-    \a property.
-
-    This function is reimplemented in QtAbstractEditorFactory template class
-    which also provides a pure virtual convenience overload of this
-    function enabling access to the property's manager.
-
-    \sa  QtAbstractEditorFactory::createEditor()
-*/
-
-/**
-    \fn QtAbstractEditorFactoryBase::QtAbstractEditorFactoryBase(QObject *parent = 0)
-
-    Creates an abstract editor factory with the given \a parent.
-*/
-
-/**
-    \fn virtual void QtAbstractEditorFactoryBase::breakConnection(QtAbstractPropertyManager *manager) = 0
-
-    \internal
-
-    Detaches property manager from factory.
-    This method is reimplemented in QtAbstractEditorFactory template subclass.
-    You don't need to reimplement it in your subclasses. Instead implement more convenient
-    QtAbstractEditorFactory::disconnectPropertyManager() which gives you access to particular manager subclass.
-*/
-
-/**
-    \fn virtual void QtAbstractEditorFactoryBase::managerDestroyed(QObject *manager) = 0
-
-    \internal
-
-    This method is called when property manager is being destroyed.
-    Basically it notifies factory not to produce editors for properties owned by \a manager.
-    You don't need to reimplement it in your subclass. This method is implemented in
-    QtAbstractEditorFactory template subclass.
-*/
-
-/**
-    \class QtAbstractEditorFactory
-
-    \brief The QtAbstractEditorFactory is the base template class for editor
-    factories.
-
-    An editor factory is a class that is able to create an editing
-    widget of a specified type (e.g. line edits or comboboxes) for a
-    given QtProperty object, and it is used in conjunction with the
-    QtAbstractPropertyManager and QtAbstractPropertyBrowser classes.
-
-    Note that the QtAbstractEditorFactory functions are using the
-    PropertyManager template argument class which can be any
-    QtAbstractPropertyManager subclass. For example:
-
-    \code
-        QtSpinBoxFactory *factory;
-        QSet<QtIntPropertyManager *> managers = factory->propertyManagers();
-    \endcode
-
-    Note that QtSpinBoxFactory by definition creates editing widgets
-    \e only for properties created by QtIntPropertyManager.
-
-    When using a property browser widget, the properties are created
-    and managed by implementations of the QtAbstractPropertyManager
-    class. To ensure that the properties' values will be displayed
-    using suitable editing widgets, the managers are associated with
-    objects of QtAbstractEditorFactory subclasses. The property browser will
-    use these associations to determine which factories it should use
-    to create the preferred editing widgets.
-
-    A QtAbstractEditorFactory object is capable of producing editors for
-    several property managers at the same time. To create an
-    association between this factory and a given manager, use the
-    addPropertyManager() function. Use the removePropertyManager() function to make
-    this factory stop producing editors for a given property
-    manager. Use the propertyManagers() function to retrieve the set of
-    managers currently associated with this factory.
-
-    Several ready-made implementations of the QtAbstractEditorFactory class
-    are available:
-
-    \list
-    \o QtCheckBoxFactory
-    \o QtDateEditFactory
-    \o QtDateTimeEditFactory
-    \o QtDoubleSpinBoxFactory
-    \o QtEnumEditorFactory
-    \o QtLineEditFactory
-    \o QtScrollBarFactory
-    \o QtSliderFactory
-    \o QtSpinBoxFactory
-    \o QtTimeEditFactory
-    \o QtVariantEditorFactory
-    \endlist
-
-    When deriving from the QtAbstractEditorFactory class, several pure virtual
-    functions must be implemented: the connectPropertyManager() function is
-    used by the factory to connect to the given manager's signals, the
-    createEditor() function is supposed to create an editor for the
-    given property controlled by the given manager, and finally the
-    disconnectPropertyManager() function is used by the factory to disconnect
-    from the specified manager's signals.
-
-    \sa QtAbstractEditorFactoryBase, QtAbstractPropertyManager
-*/
-
-/**
-    \fn QtAbstractEditorFactory::QtAbstractEditorFactory(QObject *parent = 0)
-
-    Creates an editor factory with the given \a parent.
-
-    \sa addPropertyManager()
-*/
-
-/**
-    \fn QWidget *QtAbstractEditorFactory::createEditor(QtProperty *property, QWidget *parent)
-
-    Creates an editing widget (with the given \a parent) for the given
-    \a property.
-*/
-
-/**
-    \fn void QtAbstractEditorFactory::addPropertyManager(PropertyManager *manager)
-
-    Adds the given \a manager to this factory's set of managers,
-    making this factory produce editing widgets for properties created
-    by the given manager.
-
-    The PropertyManager type is a template argument class, and represents the chosen
-    QtAbstractPropertyManager subclass.
-
-    \sa propertyManagers(), removePropertyManager()
-*/
-
-/**
-    \fn void QtAbstractEditorFactory::removePropertyManager(PropertyManager *manager)
-
-    Removes the given \a manager from this factory's set of
-    managers. The PropertyManager type is a template argument class, and may be
-    any QtAbstractPropertyManager subclass.
-
-    \sa propertyManagers(), addPropertyManager()
-*/
-
-/**
-    \fn virtual void QtAbstractEditorFactory::connectPropertyManager(PropertyManager *manager) = 0
-
-    Connects this factory to the given \a manager's signals.  The
-    PropertyManager type is a template argument class, and represents
-    the chosen QtAbstractPropertyManager subclass.
-
-    This function is used internally by the addPropertyManager() function, and
-    makes it possible to update an editing widget when the associated
-    property's data changes. This is typically done in custom slots
-    responding to the signals emitted by the property's manager,
-    e.g. QtIntPropertyManager::valueChanged() and
-    QtIntPropertyManager::rangeChanged().
-
-    \sa propertyManagers(), disconnectPropertyManager()
-*/
-
-/**
-    \fn virtual QWidget *QtAbstractEditorFactory::createEditor(PropertyManager *manager, QtProperty *property,
-                QWidget *parent) = 0
-
-    Creates an editing widget with the given \a parent for the
-    specified \a property created by the given \a manager. The
-    PropertyManager type is a template argument class, and represents
-    the chosen QtAbstractPropertyManager subclass.
-
-    This function must be implemented in derived classes: It is
-    recommended to store a pointer to the widget and map it to the
-    given \a property, since the widget must be updated whenever the
-    associated property's data changes. This is typically done in
-    custom slots responding to the signals emitted by the property's
-    manager, e.g. QtIntPropertyManager::valueChanged() and
-    QtIntPropertyManager::rangeChanged().
-
-    \sa connectPropertyManager()
-*/
-
-/**
-    \fn virtual void QtAbstractEditorFactory::disconnectPropertyManager(PropertyManager *manager) = 0
-
-    Disconnects this factory from the given \a manager's signals. The
-    PropertyManager type is a template argument class, and represents
-    the chosen QtAbstractPropertyManager subclass.
-
-    This function is used internally by the removePropertyManager() function.
-
-    \sa propertyManagers(), connectPropertyManager()
-*/
-
-/**
-    \fn QSet<PropertyManager *> QtAbstractEditorFactory::propertyManagers() const
-
-    Returns the factory's set of associated managers.  The
-    PropertyManager type is a template argument class, and represents
-    the chosen QtAbstractPropertyManager subclass.
-
-    \sa addPropertyManager(), removePropertyManager()
-*/
-
-/**
-    \fn PropertyManager *QtAbstractEditorFactory::propertyManager(QtProperty *property) const
-
-    Returns the property manager for the given \a property, or 0 if
-    the given \a property doesn't belong to any of this factory's
-    registered managers.
-
-    The PropertyManager type is a template argument class, and represents the chosen
-    QtAbstractPropertyManager subclass.
-
-    \sa propertyManagers()
-*/
-
-/**
-    \fn virtual void QtAbstractEditorFactory::managerDestroyed(QObject *manager)
-
-    \internal
-    \reimp
-*/
-
-////////////////////////////////////
-class QtBrowserItemPrivate
-{
-public:
-    QtBrowserItemPrivate(QtAbstractPropertyBrowser *browser, QtProperty *property, QtBrowserItem *parent)
-        : m_browser(browser), m_property(property), m_parent(parent), q_ptr(0) {}
-
-    void addChild(QtBrowserItem *index, QtBrowserItem *after);
-    void removeChild(QtBrowserItem *index);
-
-    QtAbstractPropertyBrowser * const m_browser;
-    QtProperty *m_property;
-    QtBrowserItem *m_parent;
-
-    QtBrowserItem *q_ptr;
-
-    QList<QtBrowserItem *> m_children;
-
-};
-
-void QtBrowserItemPrivate::addChild(QtBrowserItem *index, QtBrowserItem *after)
-{
-    if (m_children.contains(index))
-        return;
-    int idx = m_children.indexOf(after) + 1; // we insert after returned idx, if it was -1 then we set idx to 0;
-    m_children.insert(idx, index);
-}
-
-void QtBrowserItemPrivate::removeChild(QtBrowserItem *index)
-{
-    m_children.removeAll(index);
-}
-
-
-/**
-    \class QtBrowserItem
-
-    \brief The QtBrowserItem class represents a property in
-    a property browser instance.
-
-    Browser items are created whenever a QtProperty is inserted to the
-    property browser. A QtBrowserItem uniquely identifies a
-    browser's item. Thus, if the same QtProperty is inserted multiple
-    times, each occurrence gets its own unique QtBrowserItem. The
-    items are owned by QtAbstractPropertyBrowser and automatically
-    deleted when they are removed from the browser.
-
-    You can traverse a browser's properties by calling parent() and
-    children(). The property and the browser associated with an item
-    are available as property() and browser().
-
-    \sa QtAbstractPropertyBrowser, QtProperty
-*/
-
-/**
-    Returns the property which is accosiated with this item. Note that
-    several items can be associated with the same property instance in
-    the same property browser.
-
-    \sa QtAbstractPropertyBrowser::items()
-*/
-
-QtProperty *QtBrowserItem::property() const
-{
-    return d_ptr->m_property;
-}
-
-/**
-    Returns the parent item of \e this item. Returns 0 if \e this item
-    is associated with top-level property in item's property browser.
-
-    \sa children()
-*/
-
-QtBrowserItem *QtBrowserItem::parent() const
-{
-    return d_ptr->m_parent;
-}
-
-/**
-    Returns the children items of \e this item. The properties
-    reproduced from children items are always the same as
-    reproduced from associated property' children, for example:
-
-    \code
-        QtBrowserItem *item;
-        QList<QtBrowserItem *> childrenItems = item->children();
-
-        QList<QtProperty *> childrenProperties = item->property()->subProperties();
-    \endcode
-
-    The \e childrenItems list represents the same list as \e childrenProperties.
-*/
-
-QList<QtBrowserItem *> QtBrowserItem::children() const
-{
-    return d_ptr->m_children;
-}
-
-/**
-    Returns the property browser which owns \e this item.
-*/
-
-QtAbstractPropertyBrowser *QtBrowserItem::browser() const
-{
-    return d_ptr->m_browser;
-}
-
-QtBrowserItem::QtBrowserItem(QtAbstractPropertyBrowser *browser, QtProperty *property, QtBrowserItem *parent)
-{
-    d_ptr = new QtBrowserItemPrivate(browser, property, parent);
-    d_ptr->q_ptr = this;
-}
-
-QtBrowserItem::~QtBrowserItem()
-{
-    delete d_ptr;
-}
-
-
-////////////////////////////////////
-
-typedef QMap<QtAbstractPropertyBrowser *, QMap<QtAbstractPropertyManager *,
-                            QtAbstractEditorFactoryBase *> > Map1;
-typedef QMap<QtAbstractPropertyManager *, QMap<QtAbstractEditorFactoryBase *,
-                            QList<QtAbstractPropertyBrowser *> > > Map2;
-Q_GLOBAL_STATIC(Map1, m_viewToManagerToFactory)
-Q_GLOBAL_STATIC(Map2, m_managerToFactoryToViews)
-
-class QtAbstractPropertyBrowserPrivate
-{
-    QtAbstractPropertyBrowser *q_ptr;
-    Q_DECLARE_PUBLIC(QtAbstractPropertyBrowser)
-public:
-    QtAbstractPropertyBrowserPrivate();
-
-    void insertSubTree(QtProperty *property,
-            QtProperty *parentProperty);
-    void removeSubTree(QtProperty *property,
-            QtProperty *parentProperty);
-    void createBrowserIndexes(QtProperty *property, QtProperty *parentProperty, QtProperty *afterProperty);
-    void removeBrowserIndexes(QtProperty *property, QtProperty *parentProperty);
-    QtBrowserItem *createBrowserIndex(QtProperty *property, QtBrowserItem *parentIndex, QtBrowserItem *afterIndex);
-    void removeBrowserIndex(QtBrowserItem *index);
-    void clearIndex(QtBrowserItem *index);
-
-    void slotPropertyInserted(QtProperty *property,
-            QtProperty *parentProperty, QtProperty *afterProperty);
-    void slotPropertyRemoved(QtProperty *property, QtProperty *parentProperty);
-    void slotPropertyDestroyed(QtProperty *property);
-    void slotPropertyDataChanged(QtProperty *property);
-
-    QList<QtProperty *> m_subItems;
-    QMap<QtAbstractPropertyManager *, QList<QtProperty *> > m_managerToProperties;
-    QMap<QtProperty *, QList<QtProperty *> > m_propertyToParents;
-
-    QMap<QtProperty *, QtBrowserItem *> m_topLevelPropertyToIndex;
-    QList<QtBrowserItem *> m_topLevelIndexes;
-    QMap<QtProperty *, QList<QtBrowserItem *> > m_propertyToIndexes;
-
-    QtBrowserItem *m_currentItem;
-};
-
-QtAbstractPropertyBrowserPrivate::QtAbstractPropertyBrowserPrivate() :
-   m_currentItem(0)
-{
-}
-
-void QtAbstractPropertyBrowserPrivate::insertSubTree(QtProperty *property,
-            QtProperty *parentProperty)
-{
-    if (m_propertyToParents.contains(property)) {
-        // property was already inserted, so its manager is connected
-        // and all its children are inserted and theirs managers are connected
-        // we just register new parent (parent has to be new).
-        m_propertyToParents[property].append(parentProperty);
-        // don't need to update m_managerToProperties map since
-        // m_managerToProperties[manager] already contains property.
-        return;
-    }
-    QtAbstractPropertyManager *manager = property->propertyManager();
-    if (m_managerToProperties[manager].isEmpty()) {
-        // connect manager's signals
-        q_ptr->connect(manager, SIGNAL(propertyInserted(QtProperty *,
-                            QtProperty *, QtProperty *)),
-                q_ptr, SLOT(slotPropertyInserted(QtProperty *,
-                            QtProperty *, QtProperty *)));
-        q_ptr->connect(manager, SIGNAL(propertyRemoved(QtProperty *,
-                            QtProperty *)),
-                q_ptr, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-        q_ptr->connect(manager, SIGNAL(propertyDestroyed(QtProperty *)),
-                q_ptr, SLOT(slotPropertyDestroyed(QtProperty *)));
-        q_ptr->connect(manager, SIGNAL(propertyChanged(QtProperty *)),
-                q_ptr, SLOT(slotPropertyDataChanged(QtProperty *)));
-    }
-    m_managerToProperties[manager].append(property);
-    m_propertyToParents[property].append(parentProperty);
-
-    QList<QtProperty *> subList = property->subProperties();
-    QListIterator<QtProperty *> itSub(subList);
-    while (itSub.hasNext()) {
-        QtProperty *subProperty = itSub.next();
-        insertSubTree(subProperty, property);
-    }
-}
-
-void QtAbstractPropertyBrowserPrivate::removeSubTree(QtProperty *property,
-            QtProperty *parentProperty)
-{
-    if (!m_propertyToParents.contains(property)) {
-        // ASSERT
-        return;
-    }
-
-    m_propertyToParents[property].removeAll(parentProperty);
-    if (!m_propertyToParents[property].isEmpty())
-        return;
-
-    m_propertyToParents.remove(property);
-    QtAbstractPropertyManager *manager = property->propertyManager();
-    m_managerToProperties[manager].removeAll(property);
-    if (m_managerToProperties[manager].isEmpty()) {
-        // disconnect manager's signals
-        q_ptr->disconnect(manager, SIGNAL(propertyInserted(QtProperty *,
-                            QtProperty *, QtProperty *)),
-                q_ptr, SLOT(slotPropertyInserted(QtProperty *,
-                            QtProperty *, QtProperty *)));
-        q_ptr->disconnect(manager, SIGNAL(propertyRemoved(QtProperty *,
-                            QtProperty *)),
-                q_ptr, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-        q_ptr->disconnect(manager, SIGNAL(propertyDestroyed(QtProperty *)),
-                q_ptr, SLOT(slotPropertyDestroyed(QtProperty *)));
-        q_ptr->disconnect(manager, SIGNAL(propertyChanged(QtProperty *)),
-                q_ptr, SLOT(slotPropertyDataChanged(QtProperty *)));
-
-        m_managerToProperties.remove(manager);
-    }
-
-    QList<QtProperty *> subList = property->subProperties();
-    QListIterator<QtProperty *> itSub(subList);
-    while (itSub.hasNext()) {
-        QtProperty *subProperty = itSub.next();
-        removeSubTree(subProperty, property);
-    }
-}
-
-void QtAbstractPropertyBrowserPrivate::createBrowserIndexes(QtProperty *property, QtProperty *parentProperty, QtProperty *afterProperty)
-{
-    QMap<QtBrowserItem *, QtBrowserItem *> parentToAfter;
-    if (afterProperty) {
-        QMap<QtProperty *, QList<QtBrowserItem *> >::ConstIterator it =
-            m_propertyToIndexes.find(afterProperty);
-        if (it == m_propertyToIndexes.constEnd())
-            return;
-
-        QList<QtBrowserItem *> indexes = it.value();
-        QListIterator<QtBrowserItem *> itIndex(indexes);
-        while (itIndex.hasNext()) {
-            QtBrowserItem *idx = itIndex.next();
-            QtBrowserItem *parentIdx = idx->parent();
-            if ((parentProperty && parentIdx && parentIdx->property() == parentProperty) || (!parentProperty && !parentIdx))
-                parentToAfter[idx->parent()] = idx;
-        }
-    } else if (parentProperty) {
-        QMap<QtProperty *, QList<QtBrowserItem *> >::ConstIterator it =
-                m_propertyToIndexes.find(parentProperty);
-        if (it == m_propertyToIndexes.constEnd())
-            return;
-
-        QList<QtBrowserItem *> indexes = it.value();
-        QListIterator<QtBrowserItem *> itIndex(indexes);
-        while (itIndex.hasNext()) {
-            QtBrowserItem *idx = itIndex.next();
-            parentToAfter[idx] = 0;
-        }
-    } else {
-        parentToAfter[0] = 0;
-    }
-
-    const QMap<QtBrowserItem *, QtBrowserItem *>::ConstIterator pcend = parentToAfter.constEnd();
-    for (QMap<QtBrowserItem *, QtBrowserItem *>::ConstIterator it = parentToAfter.constBegin(); it != pcend; ++it)
-        createBrowserIndex(property, it.key(), it.value());
-}
-
-QtBrowserItem *QtAbstractPropertyBrowserPrivate::createBrowserIndex(QtProperty *property,
-        QtBrowserItem *parentIndex, QtBrowserItem *afterIndex)
-{
-    QtBrowserItem *newIndex = new QtBrowserItem(q_ptr, property, parentIndex);
-    if (parentIndex) {
-        parentIndex->d_ptr->addChild(newIndex, afterIndex);
-    } else {
-        m_topLevelPropertyToIndex[property] = newIndex;
-        m_topLevelIndexes.insert(m_topLevelIndexes.indexOf(afterIndex) + 1, newIndex);
-    }
-    m_propertyToIndexes[property].append(newIndex);
-
-    q_ptr->itemInserted(newIndex, afterIndex);
-
-    QList<QtProperty *> subItems = property->subProperties();
-    QListIterator<QtProperty *> itChild(subItems);
-    QtBrowserItem *afterChild = 0;
-    while (itChild.hasNext()) {
-        QtProperty *child = itChild.next();
-        afterChild = createBrowserIndex(child, newIndex, afterChild);
-    }
-    return newIndex;
-}
-
-void QtAbstractPropertyBrowserPrivate::removeBrowserIndexes(QtProperty *property, QtProperty *parentProperty)
-{
-    QList<QtBrowserItem *> toRemove;
-    QMap<QtProperty *, QList<QtBrowserItem *> >::ConstIterator it =
-        m_propertyToIndexes.find(property);
-    if (it == m_propertyToIndexes.constEnd())
-        return;
-
-    QList<QtBrowserItem *> indexes = it.value();
-    QListIterator<QtBrowserItem *> itIndex(indexes);
-    while (itIndex.hasNext()) {
-        QtBrowserItem *idx = itIndex.next();
-        QtBrowserItem *parentIdx = idx->parent();
-        if ((parentProperty && parentIdx && parentIdx->property() == parentProperty) || (!parentProperty && !parentIdx))
-            toRemove.append(idx);
-    }
-
-    QListIterator<QtBrowserItem *> itRemove(toRemove);
-    while (itRemove.hasNext()) {
-        QtBrowserItem *index = itRemove.next();
-        removeBrowserIndex(index);
-    }
-}
-
-void QtAbstractPropertyBrowserPrivate::removeBrowserIndex(QtBrowserItem *index)
-{
-    QList<QtBrowserItem *> children = index->children();
-    for (int i = children.count(); i > 0; i--) {
-        removeBrowserIndex(children.at(i - 1));
-    }
-
-    q_ptr->itemRemoved(index);
-
-    if (index->parent()) {
-        index->parent()->d_ptr->removeChild(index);
-    } else {
-        m_topLevelPropertyToIndex.remove(index->property());
-        m_topLevelIndexes.removeAll(index);
-    }
-
-    QtProperty *property = index->property();
-
-    m_propertyToIndexes[property].removeAll(index);
-    if (m_propertyToIndexes[property].isEmpty())
-        m_propertyToIndexes.remove(property);
-
-    delete index;
-}
-
-void QtAbstractPropertyBrowserPrivate::clearIndex(QtBrowserItem *index)
-{
-    QList<QtBrowserItem *> children = index->children();
-    QListIterator<QtBrowserItem *> itChild(children);
-    while (itChild.hasNext()) {
-        clearIndex(itChild.next());
-    }
-    delete index;
-}
-
-void QtAbstractPropertyBrowserPrivate::slotPropertyInserted(QtProperty *property,
-        QtProperty *parentProperty, QtProperty *afterProperty)
-{
-    if (!m_propertyToParents.contains(parentProperty))
-        return;
-    createBrowserIndexes(property, parentProperty, afterProperty);
-    insertSubTree(property, parentProperty);
-    //q_ptr->propertyInserted(property, parentProperty, afterProperty);
-}
-
-void QtAbstractPropertyBrowserPrivate::slotPropertyRemoved(QtProperty *property,
-        QtProperty *parentProperty)
-{
-    if (!m_propertyToParents.contains(parentProperty))
-        return;
-    removeSubTree(property, parentProperty); // this line should be probably moved down after propertyRemoved call
-    //q_ptr->propertyRemoved(property, parentProperty);
-    removeBrowserIndexes(property, parentProperty);
-}
-
-void QtAbstractPropertyBrowserPrivate::slotPropertyDestroyed(QtProperty *property)
-{
-    if (!m_subItems.contains(property))
-        return;
-    q_ptr->removeProperty(property);
-}
-
-void QtAbstractPropertyBrowserPrivate::slotPropertyDataChanged(QtProperty *property)
-{
-    if (!m_propertyToParents.contains(property))
-        return;
-
-    QMap<QtProperty *, QList<QtBrowserItem *> >::ConstIterator it =
-            m_propertyToIndexes.find(property);
-    if (it == m_propertyToIndexes.constEnd())
-        return;
-
-    QList<QtBrowserItem *> indexes = it.value();
-    QListIterator<QtBrowserItem *> itIndex(indexes);
-    while (itIndex.hasNext()) {
-        QtBrowserItem *idx = itIndex.next();
-        q_ptr->itemChanged(idx);
-    }
-    //q_ptr->propertyChanged(property);
-}
-
-/**
-    \class QtAbstractPropertyBrowser
-
-    \brief QtAbstractPropertyBrowser provides a base class for
-    implementing property browsers.
-
-    A property browser is a widget that enables the user to edit a
-    given set of properties.  Each property is represented by a label
-    specifying the property's name, and an editing widget (e.g. a line
-    edit or a combobox) holding its value. A property can have zero or
-    more subproperties.
-
-    \image qtpropertybrowser.png
-
-    The top level properties can be retrieved using the
-    properties() function. To traverse each property's
-    subproperties, use the QtProperty::subProperties() function. In
-    addition, the set of top level properties can be manipulated using
-    the addProperty(), insertProperty() and removeProperty()
-    functions. Note that the QtProperty class provides a corresponding
-    set of functions making it possible to manipulate the set of
-    subproperties as well.
-
-    To remove all the properties from the property browser widget, use
-    the clear() function. This function will clear the editor, but it
-    will not delete the properties since they can still be used in
-    other editors.
-
-    The properties themselves are created and managed by
-    implementations of the QtAbstractPropertyManager class. A manager
-    can handle (i.e. create and manage) properties of a given type. In
-    the property browser the managers are associated with
-    implementations of the QtAbstractEditorFactory: A factory is a
-    class able to create an editing widget of a specified type.
-
-    When using a property browser widget, managers must be created for
-    each of the required property types before the properties
-    themselves can be created. To ensure that the properties' values
-    will be displayed using suitable editing widgets, the managers
-    must be associated with objects of the preferred factory
-    implementations using the setFactoryForManager() function. The
-    property browser will use these associations to determine which
-    factory it should use to create the preferred editing widget.
-
-    Note that a factory can be associated with many managers, but a
-    manager can only be associated with one single factory within the
-    context of a single property browser.  The associations between
-    managers and factories can at any time be removed using the
-    unsetFactoryForManager() function.
-
-    Whenever the property data changes or a property is inserted or
-    removed, the itemChanged(), itemInserted() or
-    itemRemoved() functions are called, respectively. These
-    functions must be reimplemented in derived classes in order to
-    update the property browser widget. Be aware that some property
-    instances can appear several times in an abstract tree
-    structure. For example:
-
-    \table 100%
-    \row
-    \o
-    \code
-        QtProperty *property1, *property2, *property3;
-
-        property2->addSubProperty(property1);
-        property3->addSubProperty(property2);
-
-        QtAbstractPropertyBrowser *editor;
-
-        editor->addProperty(property1);
-        editor->addProperty(property2);
-        editor->addProperty(property3);
-    \endcode
-    \o  \image qtpropertybrowser-duplicate.png
-    \endtable
-
-    The addProperty() function returns a QtBrowserItem that uniquely
-    identifies the created item.
-
-    To make a property editable in the property browser, the
-    createEditor() function must be called to provide the
-    property with a suitable editing widget.
-
-    Note that there are two ready-made property browser
-    implementations:
-
-    \list
-        \o QtGroupBoxPropertyBrowser
-        \o QtTreePropertyBrowser
-    \endlist
-
-    \sa QtAbstractPropertyManager, QtAbstractEditorFactoryBase
-*/
-
-/**
-    \fn void QtAbstractPropertyBrowser::setFactoryForManager(PropertyManager *manager,
-                    QtAbstractEditorFactory<PropertyManager> *factory)
-
-    Connects the given \a manager to the given \a factory, ensuring
-    that properties of the \a manager's type will be displayed with an
-    editing widget suitable for their value.
-
-    For example:
-
-    \code
-        QtIntPropertyManager *intManager;
-        QtDoublePropertyManager *doubleManager;
-
-        QtProperty *myInteger = intManager->addProperty();
-        QtProperty *myDouble = doubleManager->addProperty();
-
-        QtSpinBoxFactory  *spinBoxFactory;
-        QtDoubleSpinBoxFactory *doubleSpinBoxFactory;
-
-        QtAbstractPropertyBrowser *editor;
-        editor->setFactoryForManager(intManager, spinBoxFactory);
-        editor->setFactoryForManager(doubleManager, doubleSpinBoxFactory);
-
-        editor->addProperty(myInteger);
-        editor->addProperty(myDouble);
-    \endcode
-
-    In this example the \c myInteger property's value is displayed
-    with a QSpinBox widget, while the \c myDouble property's value is
-    displayed with a QDoubleSpinBox widget.
-
-    Note that a factory can be associated with many managers, but a
-    manager can only be associated with one single factory.  If the
-    given \a manager already is associated with another factory, the
-    old association is broken before the new one established.
-
-    This function ensures that the given \a manager and the given \a
-    factory are compatible, and it automatically calls the
-    QtAbstractEditorFactory::addPropertyManager() function if necessary.
-
-    \sa unsetFactoryForManager()
-*/
-
-/**
-    \fn virtual void QtAbstractPropertyBrowser::itemInserted(QtBrowserItem *insertedItem,
-        QtBrowserItem *precedingItem) = 0
-
-    This function is called to update the widget whenever a property
-    is inserted or added to the property browser, passing pointers to
-    the \a insertedItem of property and the specified
-    \a precedingItem as parameters.
-
-    If \a precedingItem is 0, the \a insertedItem was put at
-    the beginning of its parent item's list of subproperties. If
-    the parent of \a insertedItem is 0, the \a insertedItem was added as a top
-    level property of \e this property browser.
-
-    This function must be reimplemented in derived classes. Note that
-    if the \a insertedItem's property has subproperties, this
-    method will be called for those properties as soon as the current call is finished.
-
-    \sa insertProperty(), addProperty()
-*/
-
-/**
-    \fn virtual void QtAbstractPropertyBrowser::itemRemoved(QtBrowserItem *item) = 0
-
-    This function is called to update the widget whenever a property
-    is removed from the property browser, passing the pointer to the
-    \a item of the property as parameters. The passed \a item is
-    deleted just after this call is finished.
-
-    If the the parent of \a item is 0, the removed \a item was a
-    top level property in this editor.
-
-    This function must be reimplemented in derived classes. Note that
-    if the removed \a item's property has subproperties, this
-    method will be called for those properties just before the current call is started.
-
-    \sa removeProperty()
-*/
-
-/**
-    \fn virtual void QtAbstractPropertyBrowser::itemChanged(QtBrowserItem *item) = 0
-
-    This function is called whenever a property's data changes,
-    passing a pointer to the \a item of property as parameter.
-
-    This function must be reimplemented in derived classes in order to
-    update the property browser widget whenever a property's name,
-    tool tip, status tip, "what's this" text, value text or value icon
-    changes.
-
-    Note that if the property browser contains several occurrences of
-    the same property, this method will be called once for each
-    occurrence (with a different item each time).
-
-    \sa QtProperty, items()
-*/
-
-/**
-    Creates an abstract property browser with the given \a parent.
-*/
-QtAbstractPropertyBrowser::QtAbstractPropertyBrowser(QWidget *parent)
-    : QWidget(parent)
-{
-    d_ptr = new QtAbstractPropertyBrowserPrivate;
-    d_ptr->q_ptr = this;
-
-}
-
-/**
-    Destroys the property browser, and destroys all the items that were
-    created by this property browser.
-
-    Note that the properties that were displayed in the editor are not
-    deleted since they still can be used in other editors. Neither
-    does the destructor delete the property managers and editor
-    factories that were used by this property browser widget unless
-    this widget was their parent.
-
-    \sa QtAbstractPropertyManager::~QtAbstractPropertyManager()
-*/
-QtAbstractPropertyBrowser::~QtAbstractPropertyBrowser()
-{
-    QList<QtBrowserItem *> indexes = topLevelItems();
-    QListIterator<QtBrowserItem *> itItem(indexes);
-    while (itItem.hasNext())
-        d_ptr->clearIndex(itItem.next());
-    delete d_ptr;
-}
-
-/**
-    Returns the property browser's list of top level properties.
-
-    To traverse the subproperties, use the QtProperty::subProperties()
-    function.
-
-    \sa addProperty(), insertProperty(), removeProperty()
-*/
-QList<QtProperty *> QtAbstractPropertyBrowser::properties() const
-{
-    return d_ptr->m_subItems;
-}
-
-/**
-    Returns the property browser's list of all items associated
-    with the given \a property.
-
-    There is one item per instance of the property in the browser.
-
-    \sa topLevelItem()
-*/
-
-QList<QtBrowserItem *> QtAbstractPropertyBrowser::items(QtProperty *property) const
-{
-    return d_ptr->m_propertyToIndexes.value(property);
-}
-
-/**
-    Returns the top-level items associated with the given \a property.
-
-    Returns 0 if \a property wasn't inserted into this property
-    browser or isn't a top-level one.
-
-    \sa topLevelItems(), items()
-*/
-
-QtBrowserItem *QtAbstractPropertyBrowser::topLevelItem(QtProperty *property) const
-{
-    return d_ptr->m_topLevelPropertyToIndex.value(property);
-}
-
-/**
-    Returns the list of top-level items.
-
-    \sa topLevelItem()
-*/
-
-QList<QtBrowserItem *> QtAbstractPropertyBrowser::topLevelItems() const
-{
-    return d_ptr->m_topLevelIndexes;
-}
-
-/**
-    Removes all the properties from the editor, but does not delete
-    them since they can still be used in other editors.
-
-    \sa removeProperty(), QtAbstractPropertyManager::clear()
-*/
-void QtAbstractPropertyBrowser::clear()
-{
-    QList<QtProperty *> subList = properties();
-    QListIterator<QtProperty *> itSub(subList);
-    itSub.toBack();
-    while (itSub.hasPrevious()) {
-        QtProperty *property = itSub.previous();
-        removeProperty(property);
-    }
-}
-
-/**
-    Appends the given \a property (and its subproperties) to the
-    property browser's list of top level properties. Returns the item
-    created by property browser which is associated with the \a property.
-    In order to get all children items created by the property
-    browser in this call, the returned item should be traversed.
-
-    If the specified \a property is already added, this function does
-    nothing and returns 0.
-
-    \sa insertProperty(), QtProperty::addSubProperty(), properties()
-*/
-QtBrowserItem *QtAbstractPropertyBrowser::addProperty(QtProperty *property)
-{
-    QtProperty *afterProperty = 0;
-    if (d_ptr->m_subItems.count() > 0)
-        afterProperty = d_ptr->m_subItems.last();
-    return insertProperty(property, afterProperty);
-}
-
-/**
-    \fn QtBrowserItem *QtAbstractPropertyBrowser::insertProperty(QtProperty *property,
-            QtProperty *afterProperty)
-
-    Inserts the given \a property (and its subproperties) after
-    the specified \a afterProperty in the browser's list of top
-    level properties. Returns item created by property browser which
-    is associated with the \a property. In order to get all children items
-    created by the property browser in this call returned item should be traversed.
-
-    If the specified \a afterProperty is 0, the given \a property is
-    inserted at the beginning of the list.  If \a property is
-    already inserted, this function does nothing and returns 0.
-
-    \sa addProperty(), QtProperty::insertSubProperty(), properties()
-*/
-QtBrowserItem *QtAbstractPropertyBrowser::insertProperty(QtProperty *property,
-            QtProperty *afterProperty)
-{
-    if (!property)
-        return 0;
-
-    // if item is already inserted in this item then cannot add.
-    QList<QtProperty *> pendingList = properties();
-    int pos = 0;
-    int newPos = 0;
-    QtProperty *properAfterProperty = 0;
-    while (pos < pendingList.count()) {
-        QtProperty *prop = pendingList.at(pos);
-        if (prop == property)
-            return 0;
-        if (prop == afterProperty) {
-            newPos = pos + 1;
-            properAfterProperty = afterProperty;
-        }
-        pos++;
-    }
-    d_ptr->createBrowserIndexes(property, 0, afterProperty);
-
-    // traverse inserted subtree and connect to manager's signals
-    d_ptr->insertSubTree(property, 0);
-
-    d_ptr->m_subItems.insert(newPos, property);
-    //propertyInserted(property, 0, properAfterProperty);
-    return topLevelItem(property);
-}
-
-/**
-    Removes the specified \a property (and its subproperties) from the
-    property browser's list of top level properties. All items
-    that were associated with the given \a property and its children
-    are deleted.
-
-    Note that the properties are \e not deleted since they can still
-    be used in other editors.
-
-    \sa clear(), QtProperty::removeSubProperty(), properties()
-*/
-void QtAbstractPropertyBrowser::removeProperty(QtProperty *property)
-{
-    if (!property)
-        return;
-
-    QList<QtProperty *> pendingList = properties();
-    int pos = 0;
-    while (pos < pendingList.count()) {
-        if (pendingList.at(pos) == property) {
-            d_ptr->m_subItems.removeAt(pos); //perhaps this two lines
-            d_ptr->removeSubTree(property, 0); //should be moved down after propertyRemoved call.
-            //propertyRemoved(property, 0);
-
-            d_ptr->removeBrowserIndexes(property, 0);
-
-            // when item is deleted, item will call removeItem for top level items,
-            // and itemRemoved for nested items.
-
-            return;
-        }
-        pos++;
-    }
-}
-
-/**
-    Creates an editing widget (with the given \a parent) for the given
-    \a property according to the previously established associations
-    between property managers and editor factories.
-
-    If the property is created by a property manager which was not
-    associated with any of the existing factories in \e this property
-    editor, the function returns 0.
-
-    To make a property editable in the property browser, the
-    createEditor() function must be called to provide the
-    property with a suitable editing widget.
-
-    Reimplement this function to provide additional decoration for the
-    editing widgets created by the installed factories.
-
-    \sa setFactoryForManager()
-*/
-QWidget *QtAbstractPropertyBrowser::createEditor(QtProperty *property,
-                QWidget *parent)
-{
-    QtAbstractEditorFactoryBase *factory = 0;
-    QtAbstractPropertyManager *manager = property->propertyManager();
-
-    if (m_viewToManagerToFactory()->contains(this) &&
-        (*m_viewToManagerToFactory())[this].contains(manager)) {
-        factory = (*m_viewToManagerToFactory())[this][manager];
-    }
-
-    if (!factory)
-        return 0;
-    return factory->createEditor(property, parent);
-}
-
-bool QtAbstractPropertyBrowser::addFactory(QtAbstractPropertyManager *abstractManager,
-            QtAbstractEditorFactoryBase *abstractFactory)
-{
-    bool connectNeeded = false;
-    if (!m_managerToFactoryToViews()->contains(abstractManager) ||
-        !(*m_managerToFactoryToViews())[abstractManager].contains(abstractFactory)) {
-        connectNeeded = true;
-    } else if ((*m_managerToFactoryToViews())[abstractManager][abstractFactory]
-                    .contains(this)) {
-        return connectNeeded;
-    }
-
-    if (m_viewToManagerToFactory()->contains(this) &&
-        (*m_viewToManagerToFactory())[this].contains(abstractManager)) {
-        unsetFactoryForManager(abstractManager);
-    }
-
-    (*m_managerToFactoryToViews())[abstractManager][abstractFactory].append(this);
-    (*m_viewToManagerToFactory())[this][abstractManager] = abstractFactory;
-
-    return connectNeeded;
-}
-
-/**
-    Removes the association between the given \a manager and the
-    factory bound to it, automatically calling the
-    QtAbstractEditorFactory::removePropertyManager() function if necessary.
-
-    \sa setFactoryForManager()
-*/
-void QtAbstractPropertyBrowser::unsetFactoryForManager(QtAbstractPropertyManager *manager)
-{
-    if (!m_viewToManagerToFactory()->contains(this) ||
-        !(*m_viewToManagerToFactory())[this].contains(manager)) {
-        return;
-    }
-
-    QtAbstractEditorFactoryBase *abstractFactory =
-                (*m_viewToManagerToFactory())[this][manager];
-    (*m_viewToManagerToFactory())[this].remove(manager);
-    if ((*m_viewToManagerToFactory())[this].isEmpty()) {
-        (*m_viewToManagerToFactory()).remove(this);
-    }
-
-    (*m_managerToFactoryToViews())[manager][abstractFactory].removeAll(this);
-    if ((*m_managerToFactoryToViews())[manager][abstractFactory].isEmpty()) {
-        (*m_managerToFactoryToViews())[manager].remove(abstractFactory);
-        abstractFactory->breakConnection(manager);
-        if ((*m_managerToFactoryToViews())[manager].isEmpty()) {
-            (*m_managerToFactoryToViews()).remove(manager);
-        }
-    }
-}
-
-/**
-    Returns the current item in the property browser.
-
-    \sa setCurrentItem()
-*/
-QtBrowserItem *QtAbstractPropertyBrowser::currentItem() const
-{
-    return d_ptr->m_currentItem;
-}
-
-/**
-    Sets the current item in the property browser to \a item.
-
-    \sa currentItem(), currentItemChanged()
-*/
-void QtAbstractPropertyBrowser::setCurrentItem(QtBrowserItem *item)
-{
-    QtBrowserItem *oldItem = d_ptr->m_currentItem;
-    d_ptr->m_currentItem = item;
-    if (oldItem != item)
-        emit  currentItemChanged(item);
-}
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#include "moc_qtpropertybrowser.cpp"
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qtpropertybrowser.h"
+#include <QtCore/QSet>
+#include <QtCore/QMap>
+#include <QtGui/QIcon>
+
+#if defined(Q_CC_MSVC)
+#    pragma warning(disable: 4786) /* MS VS 6: truncating debug info after 255 characters */
+#endif
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+class QtPropertyPrivate
+{
+public:
+    QtPropertyPrivate(QtAbstractPropertyManager *manager) : m_enabled(true), m_modified(false), m_manager(manager) {}
+    QtProperty *q_ptr;
+
+    QSet<QtProperty *> m_parentItems;
+    QList<QtProperty *> m_subItems;
+
+    QString m_toolTip;
+    QString m_statusTip;
+    QString m_whatsThis;
+    QString m_name;
+    bool m_enabled;
+    bool m_modified;
+
+    QtAbstractPropertyManager * const m_manager;
+};
+
+class QtAbstractPropertyManagerPrivate
+{
+    QtAbstractPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtAbstractPropertyManager)
+public:
+    void propertyDestroyed(QtProperty *property);
+    void propertyChanged(QtProperty *property) const;
+    void propertyRemoved(QtProperty *property,
+                QtProperty *parentProperty) const;
+    void propertyInserted(QtProperty *property, QtProperty *parentProperty,
+                QtProperty *afterProperty) const;
+
+    QSet<QtProperty *> m_properties;
+};
+
+/**
+    \class QtProperty
+
+    \brief The QtProperty class encapsulates an instance of a property.
+
+    Properties are created by objects of QtAbstractPropertyManager
+    subclasses; a manager can create properties of a given type, and
+    is used in conjunction with the QtAbstractPropertyBrowser class. A
+    property is always owned by the manager that created it, which can
+    be retrieved using the propertyManager() function.
+
+    QtProperty contains the most common property attributes, and
+    provides functions for retrieving as well as setting their values:
+
+    \table
+    \header \o Getter \o Setter
+    \row
+    \o propertyName() \o setPropertyName()
+    \row
+    \o statusTip() \o setStatusTip()
+    \row
+    \o toolTip() \o setToolTip()
+    \row
+    \o whatsThis() \o setWhatsThis()
+    \row
+    \o isEnabled() \o setEnabled()
+    \row
+    \o isModified() \o setModified()
+    \row
+    \o valueText() \o Nop
+    \row
+    \o valueIcon() \o Nop
+    \endtable
+
+    It is also possible to nest properties: QtProperty provides the
+    addSubProperty(), insertSubProperty() and removeSubProperty() functions to
+    manipulate the set of subproperties. Use the subProperties()
+    function to retrieve a property's current set of subproperties.
+    Note that nested properties are not owned by the parent property,
+    i.e. each subproperty is owned by the manager that created it.
+
+    \sa QtAbstractPropertyManager, QtBrowserItem
+*/
+
+/**
+    Creates a property with the given \a manager.
+
+    This constructor is only useful when creating a custom QtProperty
+    subclass (e.g. QtVariantProperty). To create a regular QtProperty
+    object, use the QtAbstractPropertyManager::addProperty()
+    function instead.
+
+    \sa QtAbstractPropertyManager::addProperty()
+*/
+QtProperty::QtProperty(QtAbstractPropertyManager *manager)
+{
+    d_ptr = new QtPropertyPrivate(manager);
+    d_ptr->q_ptr = this;
+}
+
+/**
+    Destroys this property.
+
+    Note that subproperties are detached but not destroyed, i.e. they
+    can still be used in another context.
+
+    \sa QtAbstractPropertyManager::clear()
+
+*/
+QtProperty::~QtProperty()
+{
+    QSetIterator<QtProperty *> itParent(d_ptr->m_parentItems);
+    while (itParent.hasNext()) {
+        QtProperty *property = itParent.next();
+        property->d_ptr->m_manager->d_ptr->propertyRemoved(this, property);
+    }
+
+    d_ptr->m_manager->d_ptr->propertyDestroyed(this);
+
+    QListIterator<QtProperty *> itChild(d_ptr->m_subItems);
+    while (itChild.hasNext()) {
+        QtProperty *property = itChild.next();
+        property->d_ptr->m_parentItems.remove(this);
+    }
+
+    itParent.toFront();
+    while (itParent.hasNext()) {
+        QtProperty *property = itParent.next();
+        property->d_ptr->m_subItems.removeAll(this);
+    }
+    delete d_ptr;
+}
+
+/**
+    Returns the set of subproperties.
+
+    Note that subproperties are not owned by \e this property, but by
+    the manager that created them.
+
+    \sa insertSubProperty(), removeSubProperty()
+*/
+QList<QtProperty *> QtProperty::subProperties() const
+{
+    return d_ptr->m_subItems;
+}
+
+/**
+    Returns a pointer to the manager that owns this property.
+*/
+QtAbstractPropertyManager *QtProperty::propertyManager() const
+{
+    return d_ptr->m_manager;
+}
+
+/**
+    Returns the property's  tool tip.
+
+    \sa setToolTip()
+*/
+QString QtProperty::toolTip() const
+{
+    return d_ptr->m_toolTip;
+}
+
+/**
+    Returns the property's status tip.
+
+    \sa setStatusTip()
+*/
+QString QtProperty::statusTip() const
+{
+    return d_ptr->m_statusTip;
+}
+
+/**
+    Returns the property's "What's This" help text.
+
+    \sa setWhatsThis()
+*/
+QString QtProperty::whatsThis() const
+{
+    return d_ptr->m_whatsThis;
+}
+
+/**
+    Returns the property's name.
+
+    \sa setPropertyName()
+*/
+QString QtProperty::propertyName() const
+{
+    return d_ptr->m_name;
+}
+
+/**
+    Returns whether the property is enabled.
+
+    \sa setEnabled()
+*/
+bool QtProperty::isEnabled() const
+{
+    return d_ptr->m_enabled;
+}
+
+/**
+    Returns whether the property is modified.
+
+    \sa setModified()
+*/
+bool QtProperty::isModified() const
+{
+    return d_ptr->m_modified;
+}
+
+/**
+    Returns whether the property has a value.
+
+    \sa QtAbstractPropertyManager::hasValue()
+*/
+bool QtProperty::hasValue() const
+{
+    return d_ptr->m_manager->hasValue(this);
+}
+
+/**
+    Returns an icon representing the current state of this property.
+
+    If the given property type can not generate such an icon, this
+    function returns an invalid icon.
+
+    \sa QtAbstractPropertyManager::valueIcon()
+*/
+QIcon QtProperty::valueIcon() const
+{
+    return d_ptr->m_manager->valueIcon(this);
+}
+
+/**
+    Returns a string representing the current state of this property.
+
+    If the given property type can not generate such a string, this
+    function returns an empty string.
+
+    \sa QtAbstractPropertyManager::valueText()
+*/
+QString QtProperty::valueText() const
+{
+    return d_ptr->m_manager->valueText(this);
+}
+
+/**
+    Sets the property's tool tip to the given \a text.
+
+    \sa toolTip()
+*/
+void QtProperty::setToolTip(const QString &text)
+{
+    if (d_ptr->m_toolTip == text)
+        return;
+
+    d_ptr->m_toolTip = text;
+    propertyChanged();
+}
+
+/**
+    Sets the property's status tip to the given \a text.
+
+    \sa statusTip()
+*/
+void QtProperty::setStatusTip(const QString &text)
+{
+    if (d_ptr->m_statusTip == text)
+        return;
+
+    d_ptr->m_statusTip = text;
+    propertyChanged();
+}
+
+/**
+    Sets the property's "What's This" help text to the given \a text.
+
+    \sa whatsThis()
+*/
+void QtProperty::setWhatsThis(const QString &text)
+{
+    if (d_ptr->m_whatsThis == text)
+        return;
+
+    d_ptr->m_whatsThis = text;
+    propertyChanged();
+}
+
+/**
+    \fn void QtProperty::setPropertyName(const QString &name)
+
+    Sets the property's  name to the given \a name.
+
+    \sa propertyName()
+*/
+void QtProperty::setPropertyName(const QString &text)
+{
+    if (d_ptr->m_name == text)
+        return;
+
+    d_ptr->m_name = text;
+    propertyChanged();
+}
+
+/**
+    Enables or disables the property according to the passed \a enable value.
+
+    \sa isEnabled()
+*/
+void QtProperty::setEnabled(bool enable)
+{
+    if (d_ptr->m_enabled == enable)
+        return;
+
+    d_ptr->m_enabled = enable;
+    propertyChanged();
+}
+
+/**
+    Sets the property's modified state according to the passed \a modified value.
+
+    \sa isModified()
+*/
+void QtProperty::setModified(bool modified)
+{
+    if (d_ptr->m_modified == modified)
+        return;
+
+    d_ptr->m_modified = modified;
+    propertyChanged();
+}
+
+/**
+    Appends the given \a property to this property's subproperties.
+
+    If the given \a property already is added, this function does
+    nothing.
+
+    \sa insertSubProperty(), removeSubProperty()
+*/
+void QtProperty::addSubProperty(QtProperty *property)
+{
+    QtProperty *after = 0;
+    if (d_ptr->m_subItems.count() > 0)
+        after = d_ptr->m_subItems.last();
+    insertSubProperty(property, after);
+}
+
+/**
+    \fn void QtProperty::insertSubProperty(QtProperty *property, QtProperty *precedingProperty)
+
+    Inserts the given \a property after the specified \a
+    precedingProperty into this property's list of subproperties.  If
+    \a precedingProperty is 0, the specified \a property is inserted
+    at the beginning of the list.
+
+    If the given \a property already is inserted, this function does
+    nothing.
+
+    \sa addSubProperty(), removeSubProperty()
+*/
+void QtProperty::insertSubProperty(QtProperty *property,
+            QtProperty *afterProperty)
+{
+    if (!property)
+        return;
+
+    if (property == this)
+        return;
+
+    // traverse all children of item. if this item is a child of item then cannot add.
+    QList<QtProperty *> pendingList = property->subProperties();
+    QMap<QtProperty *, bool> visited;
+    while (!pendingList.isEmpty()) {
+        QtProperty *i = pendingList.first();
+        if (i == this)
+            return;
+        pendingList.removeFirst();
+        if (visited.contains(i))
+            continue;
+        visited[i] = true;
+        pendingList += i->subProperties();
+    }
+
+    pendingList = subProperties();
+    int pos = 0;
+    int newPos = 0;
+    QtProperty *properAfterProperty = 0;
+    while (pos < pendingList.count()) {
+        QtProperty *i = pendingList.at(pos);
+        if (i == property)
+            return; // if item is already inserted in this item then cannot add.
+        if (i == afterProperty) {
+            newPos = pos + 1;
+            properAfterProperty = afterProperty;
+        }
+        pos++;
+    }
+
+    d_ptr->m_subItems.insert(newPos, property);
+    property->d_ptr->m_parentItems.insert(this);
+
+    d_ptr->m_manager->d_ptr->propertyInserted(property, this, properAfterProperty);
+}
+
+/**
+    Removes the given \a property from the list of subproperties
+    without deleting it.
+
+    \sa addSubProperty(), insertSubProperty()
+*/
+void QtProperty::removeSubProperty(QtProperty *property)
+{
+    if (!property)
+        return;
+
+    d_ptr->m_manager->d_ptr->propertyRemoved(property, this);
+
+    QList<QtProperty *> pendingList = subProperties();
+    int pos = 0;
+    while (pos < pendingList.count()) {
+        if (pendingList.at(pos) == property) {
+            d_ptr->m_subItems.removeAt(pos);
+            property->d_ptr->m_parentItems.remove(this);
+
+            return;
+        }
+        pos++;
+    }
+}
+
+/**
+    \internal
+*/
+void QtProperty::propertyChanged()
+{
+    d_ptr->m_manager->d_ptr->propertyChanged(this);
+}
+
+////////////////////////////////
+
+void QtAbstractPropertyManagerPrivate::propertyDestroyed(QtProperty *property)
+{
+    if (m_properties.contains(property)) {
+        emit q_ptr->propertyDestroyed(property);
+        q_ptr->uninitializeProperty(property);
+        m_properties.remove(property);
+    }
+}
+
+void QtAbstractPropertyManagerPrivate::propertyChanged(QtProperty *property) const
+{
+    emit q_ptr->propertyChanged(property);
+}
+
+void QtAbstractPropertyManagerPrivate::propertyRemoved(QtProperty *property,
+            QtProperty *parentProperty) const
+{
+    emit q_ptr->propertyRemoved(property, parentProperty);
+}
+
+void QtAbstractPropertyManagerPrivate::propertyInserted(QtProperty *property,
+            QtProperty *parentProperty, QtProperty *afterProperty) const
+{
+    emit q_ptr->propertyInserted(property, parentProperty, afterProperty);
+}
+
+/**
+    \class QtAbstractPropertyManager
+
+    \brief The QtAbstractPropertyManager provides an interface for
+    property managers.
+
+    A manager can create and manage properties of a given type, and is
+    used in conjunction with the QtAbstractPropertyBrowser class.
+
+    When using a property browser widget, the properties are created
+    and managed by implementations of the QtAbstractPropertyManager
+    class. To ensure that the properties' values will be displayed
+    using suitable editing widgets, the managers are associated with
+    objects of QtAbstractEditorFactory subclasses. The property browser
+    will use these associations to determine which factories it should
+    use to create the preferred editing widgets.
+
+    The QtAbstractPropertyManager class provides common functionality
+    like creating a property using the addProperty() function, and
+    retrieving the properties created by the manager using the
+    properties() function. The class also provides signals that are
+    emitted when the manager's properties change: propertyInserted(),
+    propertyRemoved(), propertyChanged() and propertyDestroyed().
+
+    QtAbstractPropertyManager subclasses are supposed to provide their
+    own type specific API. Note that several ready-made
+    implementations are available:
+
+    \list
+    \o QtBoolPropertyManager
+    \o QtColorPropertyManager
+    \o QtDatePropertyManager
+    \o QtDateTimePropertyManager
+    \o QtDoublePropertyManager
+    \o QtEnumPropertyManager
+    \o QtFlagPropertyManager
+    \o QtFontPropertyManager
+    \o QtGroupPropertyManager
+    \o QtIntPropertyManager
+    \o QtPointPropertyManager
+    \o QtRectPropertyManager
+    \o QtSizePropertyManager
+    \o QtSizePolicyPropertyManager
+    \o QtStringPropertyManager
+    \o QtTimePropertyManager
+    \o QtVariantPropertyManager
+    \endlist
+
+    \sa QtAbstractEditorFactoryBase, QtAbstractPropertyBrowser, QtProperty
+*/
+
+/**
+    \fn void QtAbstractPropertyManager::propertyInserted(QtProperty *newProperty,
+                QtProperty *parentProperty, QtProperty *precedingProperty)
+
+    This signal is emitted when a new subproperty is inserted into an
+    existing property, passing pointers to the \a newProperty, \a
+    parentProperty and \a precedingProperty as parameters.
+
+    If \a precedingProperty is 0, the \a newProperty was inserted at
+    the beginning of the \a parentProperty's subproperties list.
+
+    Note that signal is emitted only if the \a parentProperty is created
+    by this manager.
+
+    \sa QtAbstractPropertyBrowser::itemInserted()
+*/
+
+/**
+    \fn void QtAbstractPropertyManager::propertyChanged(QtProperty *property)
+
+    This signal is emitted whenever a property's data changes, passing
+    a pointer to the \a property as parameter.
+
+    Note that signal is only emitted for properties that are created by
+    this manager.
+
+    \sa QtAbstractPropertyBrowser::itemChanged()
+*/
+
+/**
+    \fn void QtAbstractPropertyManager::propertyRemoved(QtProperty *property, QtProperty *parent)
+
+    This signal is emitted when a subproperty is removed, passing
+    pointers to the removed \a property and the \a parent property as
+    parameters.
+
+    Note that signal is emitted only when the \a parent property is
+    created by this manager.
+
+    \sa QtAbstractPropertyBrowser::itemRemoved()
+*/
+
+/**
+    \fn void QtAbstractPropertyManager::propertyDestroyed(QtProperty *property)
+
+    This signal is emitted when the specified \a property is about to
+    be destroyed.
+
+    Note that signal is only emitted for properties that are created
+    by this manager.
+
+    \sa clear(), uninitializeProperty()
+*/
+
+/**
+    \fn void QtAbstractPropertyBrowser::currentItemChanged(QtBrowserItem *current)
+
+    This signal is emitted when the current item changes. The current item is specified by \a current.
+
+    \sa QtAbstractPropertyBrowser::setCurrentItem()
+*/
+
+/**
+    Creates an abstract property manager with the given \a parent.
+*/
+QtAbstractPropertyManager::QtAbstractPropertyManager(QObject *parent)
+    : QObject(parent)
+{
+    d_ptr = new QtAbstractPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys the manager. All properties created by the manager are
+    destroyed.
+*/
+QtAbstractPropertyManager::~QtAbstractPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Destroys all the properties that this manager has created.
+
+    \sa propertyDestroyed(), uninitializeProperty()
+*/
+void QtAbstractPropertyManager::clear() const
+{
+    while (!properties().isEmpty()) {
+        QSetIterator<QtProperty *> itProperty(properties());
+        QtProperty *prop = itProperty.next();
+        delete prop;
+    }
+}
+
+/**
+    Returns the set of properties created by this manager.
+
+    \sa addProperty()
+*/
+QSet<QtProperty *> QtAbstractPropertyManager::properties() const
+{
+    return d_ptr->m_properties;
+}
+
+/**
+    Returns whether the given \a property has a value.
+
+    The default implementation of this function returns true.
+
+    \sa QtProperty::hasValue()
+*/
+bool QtAbstractPropertyManager::hasValue(const QtProperty *property) const
+{
+    Q_UNUSED(property)
+    return true;
+}
+
+/**
+    Returns an icon representing the current state of the given \a
+    property.
+
+    The default implementation of this function returns an invalid
+    icon.
+
+    \sa QtProperty::valueIcon()
+*/
+QIcon QtAbstractPropertyManager::valueIcon(const QtProperty *property) const
+{
+    Q_UNUSED(property)
+    return QIcon();
+}
+
+/**
+    Returns a string representing the current state of the given \a
+    property.
+
+    The default implementation of this function returns an empty
+    string.
+
+    \sa QtProperty::valueText()
+*/
+QString QtAbstractPropertyManager::valueText(const QtProperty *property) const
+{
+    Q_UNUSED(property)
+    return QString();
+}
+
+/**
+    Creates a property with the given \a name which then is owned by this manager.
+
+    Internally, this function calls the createProperty() and
+    initializeProperty() functions.
+
+    \sa initializeProperty(), properties()
+*/
+QtProperty *QtAbstractPropertyManager::addProperty(const QString &name)
+{
+    QtProperty *property = createProperty();
+    if (property) {
+        property->setPropertyName(name);
+        d_ptr->m_properties.insert(property);
+        initializeProperty(property);
+    }
+    return property;
+}
+
+/**
+    Creates a property.
+
+    The base implementation produce QtProperty instances; Reimplement
+    this function to make this manager produce objects of a QtProperty
+    subclass.
+
+    \sa addProperty(), initializeProperty()
+*/
+QtProperty *QtAbstractPropertyManager::createProperty()
+{
+    return new QtProperty(this);
+}
+
+/**
+    \fn void QtAbstractPropertyManager::initializeProperty(QtProperty *property) = 0
+
+    This function is called whenever a new valid property pointer has
+    been created, passing the pointer as parameter.
+
+    The purpose is to let the manager know that the \a property has
+    been created so that it can provide additional attributes for the
+    new property, e.g. QtIntPropertyManager adds \l
+    {QtIntPropertyManager::value()}{value}, \l
+    {QtIntPropertyManager::minimum()}{minimum} and \l
+    {QtIntPropertyManager::maximum()}{maximum} attributes. Since each manager
+    subclass adds type specific attributes, this function is pure
+    virtual and must be reimplemented when deriving from the
+    QtAbstractPropertyManager class.
+
+    \sa addProperty(), createProperty()
+*/
+
+/**
+    This function is called just before the specified \a property is destroyed.
+
+    The purpose is to let the property manager know that the \a
+    property is being destroyed so that it can remove the property's
+    additional attributes.
+
+    \sa clear(),  propertyDestroyed()
+*/
+void QtAbstractPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    Q_UNUSED(property)
+}
+
+////////////////////////////////////
+
+/**
+    \class QtAbstractEditorFactoryBase
+
+    \brief The QtAbstractEditorFactoryBase provides an interface for
+    editor factories.
+
+    An editor factory is a class that is able to create an editing
+    widget of a specified type (e.g. line edits or comboboxes) for a
+    given QtProperty object, and it is used in conjunction with the
+    QtAbstractPropertyManager and QtAbstractPropertyBrowser classes.
+
+    When using a property browser widget, the properties are created
+    and managed by implementations of the QtAbstractPropertyManager
+    class. To ensure that the properties' values will be displayed
+    using suitable editing widgets, the managers are associated with
+    objects of QtAbstractEditorFactory subclasses. The property browser
+    will use these associations to determine which factories it should
+    use to create the preferred editing widgets.
+
+    Typically, an editor factory is created by subclassing the
+    QtAbstractEditorFactory template class which inherits
+    QtAbstractEditorFactoryBase. But note that several ready-made
+    implementations are available:
+
+    \list
+    \o QtCheckBoxFactory
+    \o QtDateEditFactory
+    \o QtDateTimeEditFactory
+    \o QtDoubleSpinBoxFactory
+    \o QtEnumEditorFactory
+    \o QtLineEditFactory
+    \o QtScrollBarFactory
+    \o QtSliderFactory
+    \o QtSpinBoxFactory
+    \o QtTimeEditFactory
+    \o QtVariantEditorFactory
+    \endlist
+
+    \sa QtAbstractPropertyManager, QtAbstractPropertyBrowser
+*/
+
+/**
+    \fn virtual QWidget *QtAbstractEditorFactoryBase::createEditor(QtProperty *property,
+        QWidget *parent) = 0
+
+    Creates an editing widget (with the given \a parent) for the given
+    \a property.
+
+    This function is reimplemented in QtAbstractEditorFactory template class
+    which also provides a pure virtual convenience overload of this
+    function enabling access to the property's manager.
+
+    \sa  QtAbstractEditorFactory::createEditor()
+*/
+
+/**
+    \fn QtAbstractEditorFactoryBase::QtAbstractEditorFactoryBase(QObject *parent = 0)
+
+    Creates an abstract editor factory with the given \a parent.
+*/
+
+/**
+    \fn virtual void QtAbstractEditorFactoryBase::breakConnection(QtAbstractPropertyManager *manager) = 0
+
+    \internal
+
+    Detaches property manager from factory.
+    This method is reimplemented in QtAbstractEditorFactory template subclass.
+    You don't need to reimplement it in your subclasses. Instead implement more convenient
+    QtAbstractEditorFactory::disconnectPropertyManager() which gives you access to particular manager subclass.
+*/
+
+/**
+    \fn virtual void QtAbstractEditorFactoryBase::managerDestroyed(QObject *manager) = 0
+
+    \internal
+
+    This method is called when property manager is being destroyed.
+    Basically it notifies factory not to produce editors for properties owned by \a manager.
+    You don't need to reimplement it in your subclass. This method is implemented in
+    QtAbstractEditorFactory template subclass.
+*/
+
+/**
+    \class QtAbstractEditorFactory
+
+    \brief The QtAbstractEditorFactory is the base template class for editor
+    factories.
+
+    An editor factory is a class that is able to create an editing
+    widget of a specified type (e.g. line edits or comboboxes) for a
+    given QtProperty object, and it is used in conjunction with the
+    QtAbstractPropertyManager and QtAbstractPropertyBrowser classes.
+
+    Note that the QtAbstractEditorFactory functions are using the
+    PropertyManager template argument class which can be any
+    QtAbstractPropertyManager subclass. For example:
+
+    \code
+        QtSpinBoxFactory *factory;
+        QSet<QtIntPropertyManager *> managers = factory->propertyManagers();
+    \endcode
+
+    Note that QtSpinBoxFactory by definition creates editing widgets
+    \e only for properties created by QtIntPropertyManager.
+
+    When using a property browser widget, the properties are created
+    and managed by implementations of the QtAbstractPropertyManager
+    class. To ensure that the properties' values will be displayed
+    using suitable editing widgets, the managers are associated with
+    objects of QtAbstractEditorFactory subclasses. The property browser will
+    use these associations to determine which factories it should use
+    to create the preferred editing widgets.
+
+    A QtAbstractEditorFactory object is capable of producing editors for
+    several property managers at the same time. To create an
+    association between this factory and a given manager, use the
+    addPropertyManager() function. Use the removePropertyManager() function to make
+    this factory stop producing editors for a given property
+    manager. Use the propertyManagers() function to retrieve the set of
+    managers currently associated with this factory.
+
+    Several ready-made implementations of the QtAbstractEditorFactory class
+    are available:
+
+    \list
+    \o QtCheckBoxFactory
+    \o QtDateEditFactory
+    \o QtDateTimeEditFactory
+    \o QtDoubleSpinBoxFactory
+    \o QtEnumEditorFactory
+    \o QtLineEditFactory
+    \o QtScrollBarFactory
+    \o QtSliderFactory
+    \o QtSpinBoxFactory
+    \o QtTimeEditFactory
+    \o QtVariantEditorFactory
+    \endlist
+
+    When deriving from the QtAbstractEditorFactory class, several pure virtual
+    functions must be implemented: the connectPropertyManager() function is
+    used by the factory to connect to the given manager's signals, the
+    createEditor() function is supposed to create an editor for the
+    given property controlled by the given manager, and finally the
+    disconnectPropertyManager() function is used by the factory to disconnect
+    from the specified manager's signals.
+
+    \sa QtAbstractEditorFactoryBase, QtAbstractPropertyManager
+*/
+
+/**
+    \fn QtAbstractEditorFactory::QtAbstractEditorFactory(QObject *parent = 0)
+
+    Creates an editor factory with the given \a parent.
+
+    \sa addPropertyManager()
+*/
+
+/**
+    \fn QWidget *QtAbstractEditorFactory::createEditor(QtProperty *property, QWidget *parent)
+
+    Creates an editing widget (with the given \a parent) for the given
+    \a property.
+*/
+
+/**
+    \fn void QtAbstractEditorFactory::addPropertyManager(PropertyManager *manager)
+
+    Adds the given \a manager to this factory's set of managers,
+    making this factory produce editing widgets for properties created
+    by the given manager.
+
+    The PropertyManager type is a template argument class, and represents the chosen
+    QtAbstractPropertyManager subclass.
+
+    \sa propertyManagers(), removePropertyManager()
+*/
+
+/**
+    \fn void QtAbstractEditorFactory::removePropertyManager(PropertyManager *manager)
+
+    Removes the given \a manager from this factory's set of
+    managers. The PropertyManager type is a template argument class, and may be
+    any QtAbstractPropertyManager subclass.
+
+    \sa propertyManagers(), addPropertyManager()
+*/
+
+/**
+    \fn virtual void QtAbstractEditorFactory::connectPropertyManager(PropertyManager *manager) = 0
+
+    Connects this factory to the given \a manager's signals.  The
+    PropertyManager type is a template argument class, and represents
+    the chosen QtAbstractPropertyManager subclass.
+
+    This function is used internally by the addPropertyManager() function, and
+    makes it possible to update an editing widget when the associated
+    property's data changes. This is typically done in custom slots
+    responding to the signals emitted by the property's manager,
+    e.g. QtIntPropertyManager::valueChanged() and
+    QtIntPropertyManager::rangeChanged().
+
+    \sa propertyManagers(), disconnectPropertyManager()
+*/
+
+/**
+    \fn virtual QWidget *QtAbstractEditorFactory::createEditor(PropertyManager *manager, QtProperty *property,
+                QWidget *parent) = 0
+
+    Creates an editing widget with the given \a parent for the
+    specified \a property created by the given \a manager. The
+    PropertyManager type is a template argument class, and represents
+    the chosen QtAbstractPropertyManager subclass.
+
+    This function must be implemented in derived classes: It is
+    recommended to store a pointer to the widget and map it to the
+    given \a property, since the widget must be updated whenever the
+    associated property's data changes. This is typically done in
+    custom slots responding to the signals emitted by the property's
+    manager, e.g. QtIntPropertyManager::valueChanged() and
+    QtIntPropertyManager::rangeChanged().
+
+    \sa connectPropertyManager()
+*/
+
+/**
+    \fn virtual void QtAbstractEditorFactory::disconnectPropertyManager(PropertyManager *manager) = 0
+
+    Disconnects this factory from the given \a manager's signals. The
+    PropertyManager type is a template argument class, and represents
+    the chosen QtAbstractPropertyManager subclass.
+
+    This function is used internally by the removePropertyManager() function.
+
+    \sa propertyManagers(), connectPropertyManager()
+*/
+
+/**
+    \fn QSet<PropertyManager *> QtAbstractEditorFactory::propertyManagers() const
+
+    Returns the factory's set of associated managers.  The
+    PropertyManager type is a template argument class, and represents
+    the chosen QtAbstractPropertyManager subclass.
+
+    \sa addPropertyManager(), removePropertyManager()
+*/
+
+/**
+    \fn PropertyManager *QtAbstractEditorFactory::propertyManager(QtProperty *property) const
+
+    Returns the property manager for the given \a property, or 0 if
+    the given \a property doesn't belong to any of this factory's
+    registered managers.
+
+    The PropertyManager type is a template argument class, and represents the chosen
+    QtAbstractPropertyManager subclass.
+
+    \sa propertyManagers()
+*/
+
+/**
+    \fn virtual void QtAbstractEditorFactory::managerDestroyed(QObject *manager)
+
+    \internal
+    \reimp
+*/
+
+////////////////////////////////////
+class QtBrowserItemPrivate
+{
+public:
+    QtBrowserItemPrivate(QtAbstractPropertyBrowser *browser, QtProperty *property, QtBrowserItem *parent)
+        : m_browser(browser), m_property(property), m_parent(parent), q_ptr(0) {}
+
+    void addChild(QtBrowserItem *index, QtBrowserItem *after);
+    void removeChild(QtBrowserItem *index);
+
+    QtAbstractPropertyBrowser * const m_browser;
+    QtProperty *m_property;
+    QtBrowserItem *m_parent;
+
+    QtBrowserItem *q_ptr;
+
+    QList<QtBrowserItem *> m_children;
+
+};
+
+void QtBrowserItemPrivate::addChild(QtBrowserItem *index, QtBrowserItem *after)
+{
+    if (m_children.contains(index))
+        return;
+    int idx = m_children.indexOf(after) + 1; // we insert after returned idx, if it was -1 then we set idx to 0;
+    m_children.insert(idx, index);
+}
+
+void QtBrowserItemPrivate::removeChild(QtBrowserItem *index)
+{
+    m_children.removeAll(index);
+}
+
+
+/**
+    \class QtBrowserItem
+
+    \brief The QtBrowserItem class represents a property in
+    a property browser instance.
+
+    Browser items are created whenever a QtProperty is inserted to the
+    property browser. A QtBrowserItem uniquely identifies a
+    browser's item. Thus, if the same QtProperty is inserted multiple
+    times, each occurrence gets its own unique QtBrowserItem. The
+    items are owned by QtAbstractPropertyBrowser and automatically
+    deleted when they are removed from the browser.
+
+    You can traverse a browser's properties by calling parent() and
+    children(). The property and the browser associated with an item
+    are available as property() and browser().
+
+    \sa QtAbstractPropertyBrowser, QtProperty
+*/
+
+/**
+    Returns the property which is accosiated with this item. Note that
+    several items can be associated with the same property instance in
+    the same property browser.
+
+    \sa QtAbstractPropertyBrowser::items()
+*/
+
+QtProperty *QtBrowserItem::property() const
+{
+    return d_ptr->m_property;
+}
+
+/**
+    Returns the parent item of \e this item. Returns 0 if \e this item
+    is associated with top-level property in item's property browser.
+
+    \sa children()
+*/
+
+QtBrowserItem *QtBrowserItem::parent() const
+{
+    return d_ptr->m_parent;
+}
+
+/**
+    Returns the children items of \e this item. The properties
+    reproduced from children items are always the same as
+    reproduced from associated property' children, for example:
+
+    \code
+        QtBrowserItem *item;
+        QList<QtBrowserItem *> childrenItems = item->children();
+
+        QList<QtProperty *> childrenProperties = item->property()->subProperties();
+    \endcode
+
+    The \e childrenItems list represents the same list as \e childrenProperties.
+*/
+
+QList<QtBrowserItem *> QtBrowserItem::children() const
+{
+    return d_ptr->m_children;
+}
+
+/**
+    Returns the property browser which owns \e this item.
+*/
+
+QtAbstractPropertyBrowser *QtBrowserItem::browser() const
+{
+    return d_ptr->m_browser;
+}
+
+QtBrowserItem::QtBrowserItem(QtAbstractPropertyBrowser *browser, QtProperty *property, QtBrowserItem *parent)
+{
+    d_ptr = new QtBrowserItemPrivate(browser, property, parent);
+    d_ptr->q_ptr = this;
+}
+
+QtBrowserItem::~QtBrowserItem()
+{
+    delete d_ptr;
+}
+
+
+////////////////////////////////////
+
+typedef QMap<QtAbstractPropertyBrowser *, QMap<QtAbstractPropertyManager *,
+                            QtAbstractEditorFactoryBase *> > Map1;
+typedef QMap<QtAbstractPropertyManager *, QMap<QtAbstractEditorFactoryBase *,
+                            QList<QtAbstractPropertyBrowser *> > > Map2;
+Q_GLOBAL_STATIC(Map1, m_viewToManagerToFactory)
+Q_GLOBAL_STATIC(Map2, m_managerToFactoryToViews)
+
+class QtAbstractPropertyBrowserPrivate
+{
+    QtAbstractPropertyBrowser *q_ptr;
+    Q_DECLARE_PUBLIC(QtAbstractPropertyBrowser)
+public:
+    QtAbstractPropertyBrowserPrivate();
+
+    void insertSubTree(QtProperty *property,
+            QtProperty *parentProperty);
+    void removeSubTree(QtProperty *property,
+            QtProperty *parentProperty);
+    void createBrowserIndexes(QtProperty *property, QtProperty *parentProperty, QtProperty *afterProperty);
+    void removeBrowserIndexes(QtProperty *property, QtProperty *parentProperty);
+    QtBrowserItem *createBrowserIndex(QtProperty *property, QtBrowserItem *parentIndex, QtBrowserItem *afterIndex);
+    void removeBrowserIndex(QtBrowserItem *index);
+    void clearIndex(QtBrowserItem *index);
+
+    void slotPropertyInserted(QtProperty *property,
+            QtProperty *parentProperty, QtProperty *afterProperty);
+    void slotPropertyRemoved(QtProperty *property, QtProperty *parentProperty);
+    void slotPropertyDestroyed(QtProperty *property);
+    void slotPropertyDataChanged(QtProperty *property);
+
+    QList<QtProperty *> m_subItems;
+    QMap<QtAbstractPropertyManager *, QList<QtProperty *> > m_managerToProperties;
+    QMap<QtProperty *, QList<QtProperty *> > m_propertyToParents;
+
+    QMap<QtProperty *, QtBrowserItem *> m_topLevelPropertyToIndex;
+    QList<QtBrowserItem *> m_topLevelIndexes;
+    QMap<QtProperty *, QList<QtBrowserItem *> > m_propertyToIndexes;
+
+    QtBrowserItem *m_currentItem;
+};
+
+QtAbstractPropertyBrowserPrivate::QtAbstractPropertyBrowserPrivate() :
+   m_currentItem(0)
+{
+}
+
+void QtAbstractPropertyBrowserPrivate::insertSubTree(QtProperty *property,
+            QtProperty *parentProperty)
+{
+    if (m_propertyToParents.contains(property)) {
+        // property was already inserted, so its manager is connected
+        // and all its children are inserted and theirs managers are connected
+        // we just register new parent (parent has to be new).
+        m_propertyToParents[property].append(parentProperty);
+        // don't need to update m_managerToProperties map since
+        // m_managerToProperties[manager] already contains property.
+        return;
+    }
+    QtAbstractPropertyManager *manager = property->propertyManager();
+    if (m_managerToProperties[manager].isEmpty()) {
+        // connect manager's signals
+        q_ptr->connect(manager, SIGNAL(propertyInserted(QtProperty *,
+                            QtProperty *, QtProperty *)),
+                q_ptr, SLOT(slotPropertyInserted(QtProperty *,
+                            QtProperty *, QtProperty *)));
+        q_ptr->connect(manager, SIGNAL(propertyRemoved(QtProperty *,
+                            QtProperty *)),
+                q_ptr, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+        q_ptr->connect(manager, SIGNAL(propertyDestroyed(QtProperty *)),
+                q_ptr, SLOT(slotPropertyDestroyed(QtProperty *)));
+        q_ptr->connect(manager, SIGNAL(propertyChanged(QtProperty *)),
+                q_ptr, SLOT(slotPropertyDataChanged(QtProperty *)));
+    }
+    m_managerToProperties[manager].append(property);
+    m_propertyToParents[property].append(parentProperty);
+
+    QList<QtProperty *> subList = property->subProperties();
+    QListIterator<QtProperty *> itSub(subList);
+    while (itSub.hasNext()) {
+        QtProperty *subProperty = itSub.next();
+        insertSubTree(subProperty, property);
+    }
+}
+
+void QtAbstractPropertyBrowserPrivate::removeSubTree(QtProperty *property,
+            QtProperty *parentProperty)
+{
+    if (!m_propertyToParents.contains(property)) {
+        // ASSERT
+        return;
+    }
+
+    m_propertyToParents[property].removeAll(parentProperty);
+    if (!m_propertyToParents[property].isEmpty())
+        return;
+
+    m_propertyToParents.remove(property);
+    QtAbstractPropertyManager *manager = property->propertyManager();
+    m_managerToProperties[manager].removeAll(property);
+    if (m_managerToProperties[manager].isEmpty()) {
+        // disconnect manager's signals
+        q_ptr->disconnect(manager, SIGNAL(propertyInserted(QtProperty *,
+                            QtProperty *, QtProperty *)),
+                q_ptr, SLOT(slotPropertyInserted(QtProperty *,
+                            QtProperty *, QtProperty *)));
+        q_ptr->disconnect(manager, SIGNAL(propertyRemoved(QtProperty *,
+                            QtProperty *)),
+                q_ptr, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+        q_ptr->disconnect(manager, SIGNAL(propertyDestroyed(QtProperty *)),
+                q_ptr, SLOT(slotPropertyDestroyed(QtProperty *)));
+        q_ptr->disconnect(manager, SIGNAL(propertyChanged(QtProperty *)),
+                q_ptr, SLOT(slotPropertyDataChanged(QtProperty *)));
+
+        m_managerToProperties.remove(manager);
+    }
+
+    QList<QtProperty *> subList = property->subProperties();
+    QListIterator<QtProperty *> itSub(subList);
+    while (itSub.hasNext()) {
+        QtProperty *subProperty = itSub.next();
+        removeSubTree(subProperty, property);
+    }
+}
+
+void QtAbstractPropertyBrowserPrivate::createBrowserIndexes(QtProperty *property, QtProperty *parentProperty, QtProperty *afterProperty)
+{
+    QMap<QtBrowserItem *, QtBrowserItem *> parentToAfter;
+    if (afterProperty) {
+        QMap<QtProperty *, QList<QtBrowserItem *> >::ConstIterator it =
+            m_propertyToIndexes.find(afterProperty);
+        if (it == m_propertyToIndexes.constEnd())
+            return;
+
+        QList<QtBrowserItem *> indexes = it.value();
+        QListIterator<QtBrowserItem *> itIndex(indexes);
+        while (itIndex.hasNext()) {
+            QtBrowserItem *idx = itIndex.next();
+            QtBrowserItem *parentIdx = idx->parent();
+            if ((parentProperty && parentIdx && parentIdx->property() == parentProperty) || (!parentProperty && !parentIdx))
+                parentToAfter[idx->parent()] = idx;
+        }
+    } else if (parentProperty) {
+        QMap<QtProperty *, QList<QtBrowserItem *> >::ConstIterator it =
+                m_propertyToIndexes.find(parentProperty);
+        if (it == m_propertyToIndexes.constEnd())
+            return;
+
+        QList<QtBrowserItem *> indexes = it.value();
+        QListIterator<QtBrowserItem *> itIndex(indexes);
+        while (itIndex.hasNext()) {
+            QtBrowserItem *idx = itIndex.next();
+            parentToAfter[idx] = 0;
+        }
+    } else {
+        parentToAfter[0] = 0;
+    }
+
+    const QMap<QtBrowserItem *, QtBrowserItem *>::ConstIterator pcend = parentToAfter.constEnd();
+    for (QMap<QtBrowserItem *, QtBrowserItem *>::ConstIterator it = parentToAfter.constBegin(); it != pcend; ++it)
+        createBrowserIndex(property, it.key(), it.value());
+}
+
+QtBrowserItem *QtAbstractPropertyBrowserPrivate::createBrowserIndex(QtProperty *property,
+        QtBrowserItem *parentIndex, QtBrowserItem *afterIndex)
+{
+    QtBrowserItem *newIndex = new QtBrowserItem(q_ptr, property, parentIndex);
+    if (parentIndex) {
+        parentIndex->d_ptr->addChild(newIndex, afterIndex);
+    } else {
+        m_topLevelPropertyToIndex[property] = newIndex;
+        m_topLevelIndexes.insert(m_topLevelIndexes.indexOf(afterIndex) + 1, newIndex);
+    }
+    m_propertyToIndexes[property].append(newIndex);
+
+    q_ptr->itemInserted(newIndex, afterIndex);
+
+    QList<QtProperty *> subItems = property->subProperties();
+    QListIterator<QtProperty *> itChild(subItems);
+    QtBrowserItem *afterChild = 0;
+    while (itChild.hasNext()) {
+        QtProperty *child = itChild.next();
+        afterChild = createBrowserIndex(child, newIndex, afterChild);
+    }
+    return newIndex;
+}
+
+void QtAbstractPropertyBrowserPrivate::removeBrowserIndexes(QtProperty *property, QtProperty *parentProperty)
+{
+    QList<QtBrowserItem *> toRemove;
+    QMap<QtProperty *, QList<QtBrowserItem *> >::ConstIterator it =
+        m_propertyToIndexes.find(property);
+    if (it == m_propertyToIndexes.constEnd())
+        return;
+
+    QList<QtBrowserItem *> indexes = it.value();
+    QListIterator<QtBrowserItem *> itIndex(indexes);
+    while (itIndex.hasNext()) {
+        QtBrowserItem *idx = itIndex.next();
+        QtBrowserItem *parentIdx = idx->parent();
+        if ((parentProperty && parentIdx && parentIdx->property() == parentProperty) || (!parentProperty && !parentIdx))
+            toRemove.append(idx);
+    }
+
+    QListIterator<QtBrowserItem *> itRemove(toRemove);
+    while (itRemove.hasNext()) {
+        QtBrowserItem *index = itRemove.next();
+        removeBrowserIndex(index);
+    }
+}
+
+void QtAbstractPropertyBrowserPrivate::removeBrowserIndex(QtBrowserItem *index)
+{
+    QList<QtBrowserItem *> children = index->children();
+    for (int i = children.count(); i > 0; i--) {
+        removeBrowserIndex(children.at(i - 1));
+    }
+
+    q_ptr->itemRemoved(index);
+
+    if (index->parent()) {
+        index->parent()->d_ptr->removeChild(index);
+    } else {
+        m_topLevelPropertyToIndex.remove(index->property());
+        m_topLevelIndexes.removeAll(index);
+    }
+
+    QtProperty *property = index->property();
+
+    m_propertyToIndexes[property].removeAll(index);
+    if (m_propertyToIndexes[property].isEmpty())
+        m_propertyToIndexes.remove(property);
+
+    delete index;
+}
+
+void QtAbstractPropertyBrowserPrivate::clearIndex(QtBrowserItem *index)
+{
+    QList<QtBrowserItem *> children = index->children();
+    QListIterator<QtBrowserItem *> itChild(children);
+    while (itChild.hasNext()) {
+        clearIndex(itChild.next());
+    }
+    delete index;
+}
+
+void QtAbstractPropertyBrowserPrivate::slotPropertyInserted(QtProperty *property,
+        QtProperty *parentProperty, QtProperty *afterProperty)
+{
+    if (!m_propertyToParents.contains(parentProperty))
+        return;
+    createBrowserIndexes(property, parentProperty, afterProperty);
+    insertSubTree(property, parentProperty);
+    //q_ptr->propertyInserted(property, parentProperty, afterProperty);
+}
+
+void QtAbstractPropertyBrowserPrivate::slotPropertyRemoved(QtProperty *property,
+        QtProperty *parentProperty)
+{
+    if (!m_propertyToParents.contains(parentProperty))
+        return;
+    removeSubTree(property, parentProperty); // this line should be probably moved down after propertyRemoved call
+    //q_ptr->propertyRemoved(property, parentProperty);
+    removeBrowserIndexes(property, parentProperty);
+}
+
+void QtAbstractPropertyBrowserPrivate::slotPropertyDestroyed(QtProperty *property)
+{
+    if (!m_subItems.contains(property))
+        return;
+    q_ptr->removeProperty(property);
+}
+
+void QtAbstractPropertyBrowserPrivate::slotPropertyDataChanged(QtProperty *property)
+{
+    if (!m_propertyToParents.contains(property))
+        return;
+
+    QMap<QtProperty *, QList<QtBrowserItem *> >::ConstIterator it =
+            m_propertyToIndexes.find(property);
+    if (it == m_propertyToIndexes.constEnd())
+        return;
+
+    QList<QtBrowserItem *> indexes = it.value();
+    QListIterator<QtBrowserItem *> itIndex(indexes);
+    while (itIndex.hasNext()) {
+        QtBrowserItem *idx = itIndex.next();
+        q_ptr->itemChanged(idx);
+    }
+    //q_ptr->propertyChanged(property);
+}
+
+/**
+    \class QtAbstractPropertyBrowser
+
+    \brief QtAbstractPropertyBrowser provides a base class for
+    implementing property browsers.
+
+    A property browser is a widget that enables the user to edit a
+    given set of properties.  Each property is represented by a label
+    specifying the property's name, and an editing widget (e.g. a line
+    edit or a combobox) holding its value. A property can have zero or
+    more subproperties.
+
+    \image qtpropertybrowser.png
+
+    The top level properties can be retrieved using the
+    properties() function. To traverse each property's
+    subproperties, use the QtProperty::subProperties() function. In
+    addition, the set of top level properties can be manipulated using
+    the addProperty(), insertProperty() and removeProperty()
+    functions. Note that the QtProperty class provides a corresponding
+    set of functions making it possible to manipulate the set of
+    subproperties as well.
+
+    To remove all the properties from the property browser widget, use
+    the clear() function. This function will clear the editor, but it
+    will not delete the properties since they can still be used in
+    other editors.
+
+    The properties themselves are created and managed by
+    implementations of the QtAbstractPropertyManager class. A manager
+    can handle (i.e. create and manage) properties of a given type. In
+    the property browser the managers are associated with
+    implementations of the QtAbstractEditorFactory: A factory is a
+    class able to create an editing widget of a specified type.
+
+    When using a property browser widget, managers must be created for
+    each of the required property types before the properties
+    themselves can be created. To ensure that the properties' values
+    will be displayed using suitable editing widgets, the managers
+    must be associated with objects of the preferred factory
+    implementations using the setFactoryForManager() function. The
+    property browser will use these associations to determine which
+    factory it should use to create the preferred editing widget.
+
+    Note that a factory can be associated with many managers, but a
+    manager can only be associated with one single factory within the
+    context of a single property browser.  The associations between
+    managers and factories can at any time be removed using the
+    unsetFactoryForManager() function.
+
+    Whenever the property data changes or a property is inserted or
+    removed, the itemChanged(), itemInserted() or
+    itemRemoved() functions are called, respectively. These
+    functions must be reimplemented in derived classes in order to
+    update the property browser widget. Be aware that some property
+    instances can appear several times in an abstract tree
+    structure. For example:
+
+    \table 100%
+    \row
+    \o
+    \code
+        QtProperty *property1, *property2, *property3;
+
+        property2->addSubProperty(property1);
+        property3->addSubProperty(property2);
+
+        QtAbstractPropertyBrowser *editor;
+
+        editor->addProperty(property1);
+        editor->addProperty(property2);
+        editor->addProperty(property3);
+    \endcode
+    \o  \image qtpropertybrowser-duplicate.png
+    \endtable
+
+    The addProperty() function returns a QtBrowserItem that uniquely
+    identifies the created item.
+
+    To make a property editable in the property browser, the
+    createEditor() function must be called to provide the
+    property with a suitable editing widget.
+
+    Note that there are two ready-made property browser
+    implementations:
+
+    \list
+        \o QtGroupBoxPropertyBrowser
+        \o QtTreePropertyBrowser
+    \endlist
+
+    \sa QtAbstractPropertyManager, QtAbstractEditorFactoryBase
+*/
+
+/**
+    \fn void QtAbstractPropertyBrowser::setFactoryForManager(PropertyManager *manager,
+                    QtAbstractEditorFactory<PropertyManager> *factory)
+
+    Connects the given \a manager to the given \a factory, ensuring
+    that properties of the \a manager's type will be displayed with an
+    editing widget suitable for their value.
+
+    For example:
+
+    \code
+        QtIntPropertyManager *intManager;
+        QtDoublePropertyManager *doubleManager;
+
+        QtProperty *myInteger = intManager->addProperty();
+        QtProperty *myDouble = doubleManager->addProperty();
+
+        QtSpinBoxFactory  *spinBoxFactory;
+        QtDoubleSpinBoxFactory *doubleSpinBoxFactory;
+
+        QtAbstractPropertyBrowser *editor;
+        editor->setFactoryForManager(intManager, spinBoxFactory);
+        editor->setFactoryForManager(doubleManager, doubleSpinBoxFactory);
+
+        editor->addProperty(myInteger);
+        editor->addProperty(myDouble);
+    \endcode
+
+    In this example the \c myInteger property's value is displayed
+    with a QSpinBox widget, while the \c myDouble property's value is
+    displayed with a QDoubleSpinBox widget.
+
+    Note that a factory can be associated with many managers, but a
+    manager can only be associated with one single factory.  If the
+    given \a manager already is associated with another factory, the
+    old association is broken before the new one established.
+
+    This function ensures that the given \a manager and the given \a
+    factory are compatible, and it automatically calls the
+    QtAbstractEditorFactory::addPropertyManager() function if necessary.
+
+    \sa unsetFactoryForManager()
+*/
+
+/**
+    \fn virtual void QtAbstractPropertyBrowser::itemInserted(QtBrowserItem *insertedItem,
+        QtBrowserItem *precedingItem) = 0
+
+    This function is called to update the widget whenever a property
+    is inserted or added to the property browser, passing pointers to
+    the \a insertedItem of property and the specified
+    \a precedingItem as parameters.
+
+    If \a precedingItem is 0, the \a insertedItem was put at
+    the beginning of its parent item's list of subproperties. If
+    the parent of \a insertedItem is 0, the \a insertedItem was added as a top
+    level property of \e this property browser.
+
+    This function must be reimplemented in derived classes. Note that
+    if the \a insertedItem's property has subproperties, this
+    method will be called for those properties as soon as the current call is finished.
+
+    \sa insertProperty(), addProperty()
+*/
+
+/**
+    \fn virtual void QtAbstractPropertyBrowser::itemRemoved(QtBrowserItem *item) = 0
+
+    This function is called to update the widget whenever a property
+    is removed from the property browser, passing the pointer to the
+    \a item of the property as parameters. The passed \a item is
+    deleted just after this call is finished.
+
+    If the the parent of \a item is 0, the removed \a item was a
+    top level property in this editor.
+
+    This function must be reimplemented in derived classes. Note that
+    if the removed \a item's property has subproperties, this
+    method will be called for those properties just before the current call is started.
+
+    \sa removeProperty()
+*/
+
+/**
+    \fn virtual void QtAbstractPropertyBrowser::itemChanged(QtBrowserItem *item) = 0
+
+    This function is called whenever a property's data changes,
+    passing a pointer to the \a item of property as parameter.
+
+    This function must be reimplemented in derived classes in order to
+    update the property browser widget whenever a property's name,
+    tool tip, status tip, "what's this" text, value text or value icon
+    changes.
+
+    Note that if the property browser contains several occurrences of
+    the same property, this method will be called once for each
+    occurrence (with a different item each time).
+
+    \sa QtProperty, items()
+*/
+
+/**
+    Creates an abstract property browser with the given \a parent.
+*/
+QtAbstractPropertyBrowser::QtAbstractPropertyBrowser(QWidget *parent)
+    : QWidget(parent)
+{
+    d_ptr = new QtAbstractPropertyBrowserPrivate;
+    d_ptr->q_ptr = this;
+
+}
+
+/**
+    Destroys the property browser, and destroys all the items that were
+    created by this property browser.
+
+    Note that the properties that were displayed in the editor are not
+    deleted since they still can be used in other editors. Neither
+    does the destructor delete the property managers and editor
+    factories that were used by this property browser widget unless
+    this widget was their parent.
+
+    \sa QtAbstractPropertyManager::~QtAbstractPropertyManager()
+*/
+QtAbstractPropertyBrowser::~QtAbstractPropertyBrowser()
+{
+    QList<QtBrowserItem *> indexes = topLevelItems();
+    QListIterator<QtBrowserItem *> itItem(indexes);
+    while (itItem.hasNext())
+        d_ptr->clearIndex(itItem.next());
+    delete d_ptr;
+}
+
+/**
+    Returns the property browser's list of top level properties.
+
+    To traverse the subproperties, use the QtProperty::subProperties()
+    function.
+
+    \sa addProperty(), insertProperty(), removeProperty()
+*/
+QList<QtProperty *> QtAbstractPropertyBrowser::properties() const
+{
+    return d_ptr->m_subItems;
+}
+
+/**
+    Returns the property browser's list of all items associated
+    with the given \a property.
+
+    There is one item per instance of the property in the browser.
+
+    \sa topLevelItem()
+*/
+
+QList<QtBrowserItem *> QtAbstractPropertyBrowser::items(QtProperty *property) const
+{
+    return d_ptr->m_propertyToIndexes.value(property);
+}
+
+/**
+    Returns the top-level items associated with the given \a property.
+
+    Returns 0 if \a property wasn't inserted into this property
+    browser or isn't a top-level one.
+
+    \sa topLevelItems(), items()
+*/
+
+QtBrowserItem *QtAbstractPropertyBrowser::topLevelItem(QtProperty *property) const
+{
+    return d_ptr->m_topLevelPropertyToIndex.value(property);
+}
+
+/**
+    Returns the list of top-level items.
+
+    \sa topLevelItem()
+*/
+
+QList<QtBrowserItem *> QtAbstractPropertyBrowser::topLevelItems() const
+{
+    return d_ptr->m_topLevelIndexes;
+}
+
+/**
+    Removes all the properties from the editor, but does not delete
+    them since they can still be used in other editors.
+
+    \sa removeProperty(), QtAbstractPropertyManager::clear()
+*/
+void QtAbstractPropertyBrowser::clear()
+{
+    QList<QtProperty *> subList = properties();
+    QListIterator<QtProperty *> itSub(subList);
+    itSub.toBack();
+    while (itSub.hasPrevious()) {
+        QtProperty *property = itSub.previous();
+        removeProperty(property);
+    }
+}
+
+/**
+    Appends the given \a property (and its subproperties) to the
+    property browser's list of top level properties. Returns the item
+    created by property browser which is associated with the \a property.
+    In order to get all children items created by the property
+    browser in this call, the returned item should be traversed.
+
+    If the specified \a property is already added, this function does
+    nothing and returns 0.
+
+    \sa insertProperty(), QtProperty::addSubProperty(), properties()
+*/
+QtBrowserItem *QtAbstractPropertyBrowser::addProperty(QtProperty *property)
+{
+    QtProperty *afterProperty = 0;
+    if (d_ptr->m_subItems.count() > 0)
+        afterProperty = d_ptr->m_subItems.last();
+    return insertProperty(property, afterProperty);
+}
+
+/**
+    \fn QtBrowserItem *QtAbstractPropertyBrowser::insertProperty(QtProperty *property,
+            QtProperty *afterProperty)
+
+    Inserts the given \a property (and its subproperties) after
+    the specified \a afterProperty in the browser's list of top
+    level properties. Returns item created by property browser which
+    is associated with the \a property. In order to get all children items
+    created by the property browser in this call returned item should be traversed.
+
+    If the specified \a afterProperty is 0, the given \a property is
+    inserted at the beginning of the list.  If \a property is
+    already inserted, this function does nothing and returns 0.
+
+    \sa addProperty(), QtProperty::insertSubProperty(), properties()
+*/
+QtBrowserItem *QtAbstractPropertyBrowser::insertProperty(QtProperty *property,
+            QtProperty *afterProperty)
+{
+    if (!property)
+        return 0;
+
+    // if item is already inserted in this item then cannot add.
+    QList<QtProperty *> pendingList = properties();
+    int pos = 0;
+    int newPos = 0;
+    QtProperty *properAfterProperty = 0;
+    while (pos < pendingList.count()) {
+        QtProperty *prop = pendingList.at(pos);
+        if (prop == property)
+            return 0;
+        if (prop == afterProperty) {
+            newPos = pos + 1;
+            properAfterProperty = afterProperty;
+        }
+        pos++;
+    }
+    d_ptr->createBrowserIndexes(property, 0, afterProperty);
+
+    // traverse inserted subtree and connect to manager's signals
+    d_ptr->insertSubTree(property, 0);
+
+    d_ptr->m_subItems.insert(newPos, property);
+    //propertyInserted(property, 0, properAfterProperty);
+    return topLevelItem(property);
+}
+
+/**
+    Removes the specified \a property (and its subproperties) from the
+    property browser's list of top level properties. All items
+    that were associated with the given \a property and its children
+    are deleted.
+
+    Note that the properties are \e not deleted since they can still
+    be used in other editors.
+
+    \sa clear(), QtProperty::removeSubProperty(), properties()
+*/
+void QtAbstractPropertyBrowser::removeProperty(QtProperty *property)
+{
+    if (!property)
+        return;
+
+    QList<QtProperty *> pendingList = properties();
+    int pos = 0;
+    while (pos < pendingList.count()) {
+        if (pendingList.at(pos) == property) {
+            d_ptr->m_subItems.removeAt(pos); //perhaps this two lines
+            d_ptr->removeSubTree(property, 0); //should be moved down after propertyRemoved call.
+            //propertyRemoved(property, 0);
+
+            d_ptr->removeBrowserIndexes(property, 0);
+
+            // when item is deleted, item will call removeItem for top level items,
+            // and itemRemoved for nested items.
+
+            return;
+        }
+        pos++;
+    }
+}
+
+/**
+    Creates an editing widget (with the given \a parent) for the given
+    \a property according to the previously established associations
+    between property managers and editor factories.
+
+    If the property is created by a property manager which was not
+    associated with any of the existing factories in \e this property
+    editor, the function returns 0.
+
+    To make a property editable in the property browser, the
+    createEditor() function must be called to provide the
+    property with a suitable editing widget.
+
+    Reimplement this function to provide additional decoration for the
+    editing widgets created by the installed factories.
+
+    \sa setFactoryForManager()
+*/
+QWidget *QtAbstractPropertyBrowser::createEditor(QtProperty *property,
+                QWidget *parent)
+{
+    QtAbstractEditorFactoryBase *factory = 0;
+    QtAbstractPropertyManager *manager = property->propertyManager();
+
+    if (m_viewToManagerToFactory()->contains(this) &&
+        (*m_viewToManagerToFactory())[this].contains(manager)) {
+        factory = (*m_viewToManagerToFactory())[this][manager];
+    }
+
+    if (!factory)
+        return 0;
+    return factory->createEditor(property, parent);
+}
+
+bool QtAbstractPropertyBrowser::addFactory(QtAbstractPropertyManager *abstractManager,
+            QtAbstractEditorFactoryBase *abstractFactory)
+{
+    bool connectNeeded = false;
+    if (!m_managerToFactoryToViews()->contains(abstractManager) ||
+        !(*m_managerToFactoryToViews())[abstractManager].contains(abstractFactory)) {
+        connectNeeded = true;
+    } else if ((*m_managerToFactoryToViews())[abstractManager][abstractFactory]
+                    .contains(this)) {
+        return connectNeeded;
+    }
+
+    if (m_viewToManagerToFactory()->contains(this) &&
+        (*m_viewToManagerToFactory())[this].contains(abstractManager)) {
+        unsetFactoryForManager(abstractManager);
+    }
+
+    (*m_managerToFactoryToViews())[abstractManager][abstractFactory].append(this);
+    (*m_viewToManagerToFactory())[this][abstractManager] = abstractFactory;
+
+    return connectNeeded;
+}
+
+/**
+    Removes the association between the given \a manager and the
+    factory bound to it, automatically calling the
+    QtAbstractEditorFactory::removePropertyManager() function if necessary.
+
+    \sa setFactoryForManager()
+*/
+void QtAbstractPropertyBrowser::unsetFactoryForManager(QtAbstractPropertyManager *manager)
+{
+    if (!m_viewToManagerToFactory()->contains(this) ||
+        !(*m_viewToManagerToFactory())[this].contains(manager)) {
+        return;
+    }
+
+    QtAbstractEditorFactoryBase *abstractFactory =
+                (*m_viewToManagerToFactory())[this][manager];
+    (*m_viewToManagerToFactory())[this].remove(manager);
+    if ((*m_viewToManagerToFactory())[this].isEmpty()) {
+        (*m_viewToManagerToFactory()).remove(this);
+    }
+
+    (*m_managerToFactoryToViews())[manager][abstractFactory].removeAll(this);
+    if ((*m_managerToFactoryToViews())[manager][abstractFactory].isEmpty()) {
+        (*m_managerToFactoryToViews())[manager].remove(abstractFactory);
+        abstractFactory->breakConnection(manager);
+        if ((*m_managerToFactoryToViews())[manager].isEmpty()) {
+            (*m_managerToFactoryToViews()).remove(manager);
+        }
+    }
+}
+
+/**
+    Returns the current item in the property browser.
+
+    \sa setCurrentItem()
+*/
+QtBrowserItem *QtAbstractPropertyBrowser::currentItem() const
+{
+    return d_ptr->m_currentItem;
+}
+
+/**
+    Sets the current item in the property browser to \a item.
+
+    \sa currentItem(), currentItemChanged()
+*/
+void QtAbstractPropertyBrowser::setCurrentItem(QtBrowserItem *item)
+{
+    QtBrowserItem *oldItem = d_ptr->m_currentItem;
+    d_ptr->m_currentItem = item;
+    if (oldItem != item)
+        emit  currentItemChanged(item);
+}
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#include "moc_qtpropertybrowser.cpp"
diff --git a/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowser.h b/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowser.h
index f964d54b6ddd17b4f990eae44937ac241895496b..544f7765f19b125e3b6b8c62067ceea48fe6de2e 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowser.h
+++ b/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowser.h
@@ -1,376 +1,376 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QTPROPERTYBROWSER_H
-#define QTPROPERTYBROWSER_H
-
-#include <QtGui/QWidget>
-#include <QtCore/QSet>
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-#if defined(Q_WS_WIN)
-#  if !defined(QT_QTPROPERTYBROWSER_EXPORT) && !defined(QT_QTPROPERTYBROWSER_IMPORT)
-#    define QT_QTPROPERTYBROWSER_EXPORT
-#  elif defined(QT_QTPROPERTYBROWSER_IMPORT)
-#    if defined(QT_QTPROPERTYBROWSER_EXPORT)
-#      undef QT_QTPROPERTYBROWSER_EXPORT
-#    endif
-#    define QT_QTPROPERTYBROWSER_EXPORT __declspec(dllimport)
-#  elif defined(QT_QTPROPERTYBROWSER_EXPORT)
-#    undef QT_QTPROPERTYBROWSER_EXPORT
-#    define QT_QTPROPERTYBROWSER_EXPORT __declspec(dllexport)
-#  endif
-#else
-#  define QT_QTPROPERTYBROWSER_EXPORT
-#endif
-
-
-class QtAbstractPropertyManager;
-class QtPropertyPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtProperty
-{
-public:
-    virtual ~QtProperty();
-
-    QList<QtProperty *> subProperties() const;
-
-    QtAbstractPropertyManager *propertyManager() const;
-
-    QString toolTip() const;
-    QString statusTip() const;
-    QString whatsThis() const;
-    QString propertyName() const;
-    bool isEnabled() const;
-    bool isModified() const;
-
-    bool hasValue() const;
-    QIcon valueIcon() const;
-    QString valueText() const;
-
-    void setToolTip(const QString &text);
-    void setStatusTip(const QString &text);
-    void setWhatsThis(const QString &text);
-    void setPropertyName(const QString &text);
-    void setEnabled(bool enable);
-    void setModified(bool modified);
-
-    void addSubProperty(QtProperty *property);
-    void insertSubProperty(QtProperty *property, QtProperty *afterProperty);
-    void removeSubProperty(QtProperty *property);
-protected:
-    explicit QtProperty(QtAbstractPropertyManager *manager);
-    void propertyChanged();
-private:
-    friend class QtAbstractPropertyManager;
-    QtPropertyPrivate *d_ptr;
-};
-
-class QtAbstractPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtAbstractPropertyManager : public QObject
-{
-    Q_OBJECT
-public:
-
-    explicit QtAbstractPropertyManager(QObject *parent = 0);
-    ~QtAbstractPropertyManager();
-
-    QSet<QtProperty *> properties() const;
-    void clear() const;
-
-    QtProperty *addProperty(const QString &name = QString());
-Q_SIGNALS:
-
-    void propertyInserted(QtProperty *property,
-                QtProperty *parent, QtProperty *after);
-    void propertyChanged(QtProperty *property);
-    void propertyRemoved(QtProperty *property, QtProperty *parent);
-    void propertyDestroyed(QtProperty *property);
-protected:
-    virtual bool hasValue(const QtProperty *property) const;
-    virtual QIcon valueIcon(const QtProperty *property) const;
-    virtual QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property) = 0;
-    virtual void uninitializeProperty(QtProperty *property);
-    virtual QtProperty *createProperty();
-private:
-    friend class QtProperty;
-    QtAbstractPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtAbstractPropertyManager)
-    Q_DISABLE_COPY(QtAbstractPropertyManager)
-};
-
-class QT_QTPROPERTYBROWSER_EXPORT QtAbstractEditorFactoryBase : public QObject
-{
-    Q_OBJECT
-public:
-    virtual QWidget *createEditor(QtProperty *property, QWidget *parent) = 0;
-protected:
-    explicit QtAbstractEditorFactoryBase(QObject *parent = 0)
-        : QObject(parent) {}
-
-    virtual void breakConnection(QtAbstractPropertyManager *manager) = 0;
-protected Q_SLOTS:
-    virtual void managerDestroyed(QObject *manager) = 0;
-
-    friend class QtAbstractPropertyBrowser;
-};
-
-template <class PropertyManager>
-class QtAbstractEditorFactory : public QtAbstractEditorFactoryBase
-{
-public:
-    explicit QtAbstractEditorFactory(QObject *parent) : QtAbstractEditorFactoryBase(parent) {}
-    QWidget *createEditor(QtProperty *property, QWidget *parent)
-    {
-        QSetIterator<PropertyManager *> it(m_managers);
-        while (it.hasNext()) {
-            PropertyManager *manager = it.next();
-            if (manager == property->propertyManager()) {
-                return createEditor(manager, property, parent);
-            }
-        }
-        return 0;
-    }
-    void addPropertyManager(PropertyManager *manager)
-    {
-        if (m_managers.contains(manager))
-            return;
-        m_managers.insert(manager);
-        connectPropertyManager(manager);
-        connect(manager, SIGNAL(destroyed(QObject *)),
-                    this, SLOT(managerDestroyed(QObject *)));
-    }
-    void removePropertyManager(PropertyManager *manager)
-    {
-        if (!m_managers.contains(manager))
-            return;
-        disconnect(manager, SIGNAL(destroyed(QObject *)),
-                    this, SLOT(managerDestroyed(QObject *)));
-        disconnectPropertyManager(manager);
-        m_managers.remove(manager);
-    }
-    QSet<PropertyManager *> propertyManagers() const
-    {
-        return m_managers;
-    }
-    PropertyManager *propertyManager(QtProperty *property) const
-    {
-        QtAbstractPropertyManager *manager = property->propertyManager();
-        QSetIterator<PropertyManager *> itManager(m_managers);
-        while (itManager.hasNext()) {
-            PropertyManager *m = itManager.next();
-            if (m == manager) {
-                return m;
-            }
-        }
-        return 0;
-    }
-protected:
-    virtual void connectPropertyManager(PropertyManager *manager) = 0;
-    virtual QWidget *createEditor(PropertyManager *manager, QtProperty *property,
-                QWidget *parent) = 0;
-    virtual void disconnectPropertyManager(PropertyManager *manager) = 0;
-    void managerDestroyed(QObject *manager)
-    {
-        QSetIterator<PropertyManager *> it(m_managers);
-        while (it.hasNext()) {
-            PropertyManager *m = it.next();
-            if (m == manager) {
-                m_managers.remove(m);
-                return;
-            }
-        }
-    }
-private:
-    void breakConnection(QtAbstractPropertyManager *manager)
-    {
-        QSetIterator<PropertyManager *> it(m_managers);
-        while (it.hasNext()) {
-            PropertyManager *m = it.next();
-            if (m == manager) {
-                removePropertyManager(m);
-                return;
-            }
-        }
-    }
-private:
-    QSet<PropertyManager *> m_managers;
-    friend class QtAbstractPropertyEditor;
-};
-
-class QtAbstractPropertyBrowser;
-class QtBrowserItemPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtBrowserItem
-{
-public:
-    QtProperty *property() const;
-    QtBrowserItem *parent() const;
-    QList<QtBrowserItem *> children() const;
-    QtAbstractPropertyBrowser *browser() const;
-private:
-    explicit QtBrowserItem(QtAbstractPropertyBrowser *browser, QtProperty *property, QtBrowserItem *parent);
-    ~QtBrowserItem();
-    QtBrowserItemPrivate *d_ptr;
-    friend class QtAbstractPropertyBrowserPrivate;
-};
-
-class QtAbstractPropertyBrowserPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtAbstractPropertyBrowser : public QWidget
-{
-    Q_OBJECT
-public:
-
-    explicit QtAbstractPropertyBrowser(QWidget *parent = 0);
-    ~QtAbstractPropertyBrowser();
-
-    QList<QtProperty *> properties() const;
-    QList<QtBrowserItem *> items(QtProperty *property) const;
-    QtBrowserItem *topLevelItem(QtProperty *property) const;
-    QList<QtBrowserItem *> topLevelItems() const;
-    void clear();
-
-    template <class PropertyManager>
-    void setFactoryForManager(PropertyManager *manager,
-                    QtAbstractEditorFactory<PropertyManager> *factory) {
-        QtAbstractPropertyManager *abstractManager = manager;
-        QtAbstractEditorFactoryBase *abstractFactory = factory;
-
-        if (addFactory(abstractManager, abstractFactory))
-            factory->addPropertyManager(manager);
-    }
-
-    void unsetFactoryForManager(QtAbstractPropertyManager *manager);
-
-    QtBrowserItem *currentItem() const;
-    void setCurrentItem(QtBrowserItem *);
-
-Q_SIGNALS:
-    void currentItemChanged(QtBrowserItem *);
-
-public Q_SLOTS:
-
-    QtBrowserItem *addProperty(QtProperty *property);
-    QtBrowserItem *insertProperty(QtProperty *property, QtProperty *afterProperty);
-    void removeProperty(QtProperty *property);
-
-protected:
-
-    virtual void itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem) = 0;
-    virtual void itemRemoved(QtBrowserItem *item) = 0;
-    // can be tooltip, statustip, whatsthis, name, icon, text.
-    virtual void itemChanged(QtBrowserItem *item) = 0;
-
-    virtual QWidget *createEditor(QtProperty *property, QWidget *parent);
-private:
-
-    bool addFactory(QtAbstractPropertyManager *abstractManager,
-                QtAbstractEditorFactoryBase *abstractFactory);
-
-    QtAbstractPropertyBrowserPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtAbstractPropertyBrowser)
-    Q_DISABLE_COPY(QtAbstractPropertyBrowser)
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyInserted(QtProperty *,
-                            QtProperty *, QtProperty *))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyRemoved(QtProperty *,
-                            QtProperty *))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDataChanged(QtProperty *))
-
-};
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#endif // QTPROPERTYBROWSER_H
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QTPROPERTYBROWSER_H
+#define QTPROPERTYBROWSER_H
+
+#include <QtGui/QWidget>
+#include <QtCore/QSet>
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+#if defined(Q_WS_WIN)
+#  if !defined(QT_QTPROPERTYBROWSER_EXPORT) && !defined(QT_QTPROPERTYBROWSER_IMPORT)
+#    define QT_QTPROPERTYBROWSER_EXPORT
+#  elif defined(QT_QTPROPERTYBROWSER_IMPORT)
+#    if defined(QT_QTPROPERTYBROWSER_EXPORT)
+#      undef QT_QTPROPERTYBROWSER_EXPORT
+#    endif
+#    define QT_QTPROPERTYBROWSER_EXPORT __declspec(dllimport)
+#  elif defined(QT_QTPROPERTYBROWSER_EXPORT)
+#    undef QT_QTPROPERTYBROWSER_EXPORT
+#    define QT_QTPROPERTYBROWSER_EXPORT __declspec(dllexport)
+#  endif
+#else
+#  define QT_QTPROPERTYBROWSER_EXPORT
+#endif
+
+
+class QtAbstractPropertyManager;
+class QtPropertyPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtProperty
+{
+public:
+    virtual ~QtProperty();
+
+    QList<QtProperty *> subProperties() const;
+
+    QtAbstractPropertyManager *propertyManager() const;
+
+    QString toolTip() const;
+    QString statusTip() const;
+    QString whatsThis() const;
+    QString propertyName() const;
+    bool isEnabled() const;
+    bool isModified() const;
+
+    bool hasValue() const;
+    QIcon valueIcon() const;
+    QString valueText() const;
+
+    void setToolTip(const QString &text);
+    void setStatusTip(const QString &text);
+    void setWhatsThis(const QString &text);
+    void setPropertyName(const QString &text);
+    void setEnabled(bool enable);
+    void setModified(bool modified);
+
+    void addSubProperty(QtProperty *property);
+    void insertSubProperty(QtProperty *property, QtProperty *afterProperty);
+    void removeSubProperty(QtProperty *property);
+protected:
+    explicit QtProperty(QtAbstractPropertyManager *manager);
+    void propertyChanged();
+private:
+    friend class QtAbstractPropertyManager;
+    QtPropertyPrivate *d_ptr;
+};
+
+class QtAbstractPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtAbstractPropertyManager : public QObject
+{
+    Q_OBJECT
+public:
+
+    explicit QtAbstractPropertyManager(QObject *parent = 0);
+    ~QtAbstractPropertyManager();
+
+    QSet<QtProperty *> properties() const;
+    void clear() const;
+
+    QtProperty *addProperty(const QString &name = QString());
+Q_SIGNALS:
+
+    void propertyInserted(QtProperty *property,
+                QtProperty *parent, QtProperty *after);
+    void propertyChanged(QtProperty *property);
+    void propertyRemoved(QtProperty *property, QtProperty *parent);
+    void propertyDestroyed(QtProperty *property);
+protected:
+    virtual bool hasValue(const QtProperty *property) const;
+    virtual QIcon valueIcon(const QtProperty *property) const;
+    virtual QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property) = 0;
+    virtual void uninitializeProperty(QtProperty *property);
+    virtual QtProperty *createProperty();
+private:
+    friend class QtProperty;
+    QtAbstractPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtAbstractPropertyManager)
+    Q_DISABLE_COPY(QtAbstractPropertyManager)
+};
+
+class QT_QTPROPERTYBROWSER_EXPORT QtAbstractEditorFactoryBase : public QObject
+{
+    Q_OBJECT
+public:
+    virtual QWidget *createEditor(QtProperty *property, QWidget *parent) = 0;
+protected:
+    explicit QtAbstractEditorFactoryBase(QObject *parent = 0)
+        : QObject(parent) {}
+
+    virtual void breakConnection(QtAbstractPropertyManager *manager) = 0;
+protected Q_SLOTS:
+    virtual void managerDestroyed(QObject *manager) = 0;
+
+    friend class QtAbstractPropertyBrowser;
+};
+
+template <class PropertyManager>
+class QtAbstractEditorFactory : public QtAbstractEditorFactoryBase
+{
+public:
+    explicit QtAbstractEditorFactory(QObject *parent) : QtAbstractEditorFactoryBase(parent) {}
+    QWidget *createEditor(QtProperty *property, QWidget *parent)
+    {
+        QSetIterator<PropertyManager *> it(m_managers);
+        while (it.hasNext()) {
+            PropertyManager *manager = it.next();
+            if (manager == property->propertyManager()) {
+                return createEditor(manager, property, parent);
+            }
+        }
+        return 0;
+    }
+    void addPropertyManager(PropertyManager *manager)
+    {
+        if (m_managers.contains(manager))
+            return;
+        m_managers.insert(manager);
+        connectPropertyManager(manager);
+        connect(manager, SIGNAL(destroyed(QObject *)),
+                    this, SLOT(managerDestroyed(QObject *)));
+    }
+    void removePropertyManager(PropertyManager *manager)
+    {
+        if (!m_managers.contains(manager))
+            return;
+        disconnect(manager, SIGNAL(destroyed(QObject *)),
+                    this, SLOT(managerDestroyed(QObject *)));
+        disconnectPropertyManager(manager);
+        m_managers.remove(manager);
+    }
+    QSet<PropertyManager *> propertyManagers() const
+    {
+        return m_managers;
+    }
+    PropertyManager *propertyManager(QtProperty *property) const
+    {
+        QtAbstractPropertyManager *manager = property->propertyManager();
+        QSetIterator<PropertyManager *> itManager(m_managers);
+        while (itManager.hasNext()) {
+            PropertyManager *m = itManager.next();
+            if (m == manager) {
+                return m;
+            }
+        }
+        return 0;
+    }
+protected:
+    virtual void connectPropertyManager(PropertyManager *manager) = 0;
+    virtual QWidget *createEditor(PropertyManager *manager, QtProperty *property,
+                QWidget *parent) = 0;
+    virtual void disconnectPropertyManager(PropertyManager *manager) = 0;
+    void managerDestroyed(QObject *manager)
+    {
+        QSetIterator<PropertyManager *> it(m_managers);
+        while (it.hasNext()) {
+            PropertyManager *m = it.next();
+            if (m == manager) {
+                m_managers.remove(m);
+                return;
+            }
+        }
+    }
+private:
+    void breakConnection(QtAbstractPropertyManager *manager)
+    {
+        QSetIterator<PropertyManager *> it(m_managers);
+        while (it.hasNext()) {
+            PropertyManager *m = it.next();
+            if (m == manager) {
+                removePropertyManager(m);
+                return;
+            }
+        }
+    }
+private:
+    QSet<PropertyManager *> m_managers;
+    friend class QtAbstractPropertyEditor;
+};
+
+class QtAbstractPropertyBrowser;
+class QtBrowserItemPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtBrowserItem
+{
+public:
+    QtProperty *property() const;
+    QtBrowserItem *parent() const;
+    QList<QtBrowserItem *> children() const;
+    QtAbstractPropertyBrowser *browser() const;
+private:
+    explicit QtBrowserItem(QtAbstractPropertyBrowser *browser, QtProperty *property, QtBrowserItem *parent);
+    ~QtBrowserItem();
+    QtBrowserItemPrivate *d_ptr;
+    friend class QtAbstractPropertyBrowserPrivate;
+};
+
+class QtAbstractPropertyBrowserPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtAbstractPropertyBrowser : public QWidget
+{
+    Q_OBJECT
+public:
+
+    explicit QtAbstractPropertyBrowser(QWidget *parent = 0);
+    ~QtAbstractPropertyBrowser();
+
+    QList<QtProperty *> properties() const;
+    QList<QtBrowserItem *> items(QtProperty *property) const;
+    QtBrowserItem *topLevelItem(QtProperty *property) const;
+    QList<QtBrowserItem *> topLevelItems() const;
+    void clear();
+
+    template <class PropertyManager>
+    void setFactoryForManager(PropertyManager *manager,
+                    QtAbstractEditorFactory<PropertyManager> *factory) {
+        QtAbstractPropertyManager *abstractManager = manager;
+        QtAbstractEditorFactoryBase *abstractFactory = factory;
+
+        if (addFactory(abstractManager, abstractFactory))
+            factory->addPropertyManager(manager);
+    }
+
+    void unsetFactoryForManager(QtAbstractPropertyManager *manager);
+
+    QtBrowserItem *currentItem() const;
+    void setCurrentItem(QtBrowserItem *);
+
+Q_SIGNALS:
+    void currentItemChanged(QtBrowserItem *);
+
+public Q_SLOTS:
+
+    QtBrowserItem *addProperty(QtProperty *property);
+    QtBrowserItem *insertProperty(QtProperty *property, QtProperty *afterProperty);
+    void removeProperty(QtProperty *property);
+
+protected:
+
+    virtual void itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem) = 0;
+    virtual void itemRemoved(QtBrowserItem *item) = 0;
+    // can be tooltip, statustip, whatsthis, name, icon, text.
+    virtual void itemChanged(QtBrowserItem *item) = 0;
+
+    virtual QWidget *createEditor(QtProperty *property, QWidget *parent);
+private:
+
+    bool addFactory(QtAbstractPropertyManager *abstractManager,
+                QtAbstractEditorFactoryBase *abstractFactory);
+
+    QtAbstractPropertyBrowserPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtAbstractPropertyBrowser)
+    Q_DISABLE_COPY(QtAbstractPropertyBrowser)
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyInserted(QtProperty *,
+                            QtProperty *, QtProperty *))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyRemoved(QtProperty *,
+                            QtProperty *))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDataChanged(QtProperty *))
+
+};
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#endif // QTPROPERTYBROWSER_H
diff --git a/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowserutils.cpp b/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowserutils.cpp
index bf0eefa63de3f02898832135731fefb7d41d9746..d9c296a728e2fddc1f9686c395d59e421f7fc503 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowserutils.cpp
+++ b/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowserutils.cpp
@@ -1,480 +1,480 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qtpropertybrowserutils_p.h"
-#include <QtGui/QApplication>
-#include <QtGui/QPainter>
-#include <QtGui/QHBoxLayout>
-#include <QtGui/QMouseEvent>
-#include <QtGui/QCheckBox>
-#include <QtGui/QLineEdit>
-#include <QtGui/QMenu>
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-QtCursorDatabase::QtCursorDatabase()
-{
-    appendCursor(Qt::ArrowCursor, QApplication::translate("QtCursorDatabase", "Arrow", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-arrow.png")));
-    appendCursor(Qt::UpArrowCursor, QApplication::translate("QtCursorDatabase", "Up Arrow", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-uparrow.png")));
-    appendCursor(Qt::CrossCursor, QApplication::translate("QtCursorDatabase", "Cross", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-cross.png")));
-    appendCursor(Qt::WaitCursor, QApplication::translate("QtCursorDatabase", "Wait", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-wait.png")));
-    appendCursor(Qt::IBeamCursor, QApplication::translate("QtCursorDatabase", "IBeam", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-ibeam.png")));
-    appendCursor(Qt::SizeVerCursor, QApplication::translate("QtCursorDatabase", "Size Vertical", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizev.png")));
-    appendCursor(Qt::SizeHorCursor, QApplication::translate("QtCursorDatabase", "Size Horizontal", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizeh.png")));
-    appendCursor(Qt::SizeFDiagCursor, QApplication::translate("QtCursorDatabase", "Size Backslash", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizef.png")));
-    appendCursor(Qt::SizeBDiagCursor, QApplication::translate("QtCursorDatabase", "Size Slash", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizeb.png")));
-    appendCursor(Qt::SizeAllCursor, QApplication::translate("QtCursorDatabase", "Size All", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizeall.png")));
-    appendCursor(Qt::BlankCursor, QApplication::translate("QtCursorDatabase", "Blank", 0,
-                        QApplication::UnicodeUTF8), QIcon());
-    appendCursor(Qt::SplitVCursor, QApplication::translate("QtCursorDatabase", "Split Vertical", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-vsplit.png")));
-    appendCursor(Qt::SplitHCursor, QApplication::translate("QtCursorDatabase", "Split Horizontal", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-hsplit.png")));
-    appendCursor(Qt::PointingHandCursor, QApplication::translate("QtCursorDatabase", "Pointing Hand", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-hand.png")));
-    appendCursor(Qt::ForbiddenCursor, QApplication::translate("QtCursorDatabase", "Forbidden", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-forbidden.png")));
-    appendCursor(Qt::OpenHandCursor, QApplication::translate("QtCursorDatabase", "Open Hand", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-openhand.png")));
-    appendCursor(Qt::ClosedHandCursor, QApplication::translate("QtCursorDatabase", "Closed Hand", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-closedhand.png")));
-    appendCursor(Qt::WhatsThisCursor, QApplication::translate("QtCursorDatabase", "What's This", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-whatsthis.png")));
-    appendCursor(Qt::BusyCursor, QApplication::translate("QtCursorDatabase", "Busy", 0,
-                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-busy.png")));
-}
-
-void QtCursorDatabase::appendCursor(Qt::CursorShape shape, const QString &name, const QIcon &icon)
-{
-    if (m_cursorShapeToValue.contains(shape))
-        return;
-    int value = m_cursorNames.count();
-    m_cursorNames.append(name);
-    m_cursorIcons[value] = icon;
-    m_valueToCursorShape[value] = shape;
-    m_cursorShapeToValue[shape] = value;
-}
-
-QStringList QtCursorDatabase::cursorShapeNames() const
-{
-    return m_cursorNames;
-}
-
-QMap<int, QIcon> QtCursorDatabase::cursorShapeIcons() const
-{
-    return m_cursorIcons;
-}
-
-QString QtCursorDatabase::cursorToShapeName(const QCursor &cursor) const
-{
-    int val = cursorToValue(cursor);
-    if (val >= 0)
-        return m_cursorNames.at(val);
-    return QString();
-}
-
-QIcon QtCursorDatabase::cursorToShapeIcon(const QCursor &cursor) const
-{
-    int val = cursorToValue(cursor);
-    return m_cursorIcons.value(val);
-}
-
-int QtCursorDatabase::cursorToValue(const QCursor &cursor) const
-{
-#ifndef QT_NO_CURSOR
-    Qt::CursorShape shape = cursor.shape();
-    if (m_cursorShapeToValue.contains(shape))
-        return m_cursorShapeToValue[shape];
-#endif
-    return -1;
-}
-
-#ifndef QT_NO_CURSOR
-QCursor QtCursorDatabase::valueToCursor(int value) const
-{
-    if (m_valueToCursorShape.contains(value))
-        return QCursor(m_valueToCursorShape[value]);
-    return QCursor();
-}
-#endif
-
-QPixmap QtPropertyBrowserUtils::brushValuePixmap(const QBrush &b)
-{
-    QImage img(16, 16, QImage::Format_ARGB32_Premultiplied);
-    img.fill(0);
-
-    QPainter painter(&img);
-    painter.setCompositionMode(QPainter::CompositionMode_Source);
-    painter.fillRect(0, 0, img.width(), img.height(), b);
-    QColor color = b.color();
-    if (color.alpha() != 255) { // indicate alpha by an inset
-        QBrush  opaqueBrush = b;
-        color.setAlpha(255);
-        opaqueBrush.setColor(color);
-        painter.fillRect(img.width() / 4, img.height() / 4,
-                         img.width() / 2, img.height() / 2, opaqueBrush);
-    }
-    painter.end();
-    return QPixmap::fromImage(img);
-}
-
-QIcon QtPropertyBrowserUtils::brushValueIcon(const QBrush &b)
-{
-    return QIcon(brushValuePixmap(b));
-}
-
-QString QtPropertyBrowserUtils::colorValueText(const QColor &c)
-{
-    return QApplication::translate("QtPropertyBrowserUtils", "[%1, %2, %3] (%4)", 0, QApplication::UnicodeUTF8)
-                                  .arg(QString::number(c.red()))
-                                  .arg(QString::number(c.green()))
-                                  .arg(QString::number(c.blue()))
-                                  .arg(QString::number(c.alpha()));
-}
-
-QPixmap QtPropertyBrowserUtils::fontValuePixmap(const QFont &font)
-{
-    QFont f = font;
-    QImage img(16, 16, QImage::Format_ARGB32_Premultiplied);
-    img.fill(0);
-    QPainter p(&img);
-    p.setRenderHint(QPainter::TextAntialiasing, true);
-    p.setRenderHint(QPainter::Antialiasing, true);
-    f.setPointSize(13);
-    p.setFont(f);
-    QTextOption t;
-    t.setAlignment(Qt::AlignCenter);
-    p.drawText(QRect(0, 0, 16, 16), QString(QLatin1Char('A')), t);
-    return QPixmap::fromImage(img);
-}
-
-QIcon QtPropertyBrowserUtils::fontValueIcon(const QFont &f)
-{
-    return QIcon(fontValuePixmap(f));
-}
-
-QString QtPropertyBrowserUtils::fontValueText(const QFont &f)
-{
-    return QApplication::translate("QtPropertyBrowserUtils", "[%1, %2]", 0, QApplication::UnicodeUTF8)
-                                  .arg(f.family())
-                                  .arg(f.pointSize());
-}
-
-
-QtBoolEdit::QtBoolEdit(QWidget *parent) :
-    QWidget(parent),
-    m_checkBox(new QCheckBox(this)),
-    m_textVisible(true)
-{
-    QHBoxLayout *lt = new QHBoxLayout;
-    if (QApplication::layoutDirection() == Qt::LeftToRight)
-        lt->setContentsMargins(4, 0, 0, 0);
-    else
-        lt->setContentsMargins(0, 0, 4, 0);
-    lt->addWidget(m_checkBox);
-    setLayout(lt);
-    connect(m_checkBox, SIGNAL(toggled(bool)), this, SIGNAL(toggled(bool)));
-    setFocusProxy(m_checkBox);
-    m_checkBox->setText(tr("True"));
-}
-
-void QtBoolEdit::setTextVisible(bool textVisible)
-{
-    if (m_textVisible == textVisible)
-        return;
-
-    m_textVisible = textVisible;
-    if (m_textVisible)
-        m_checkBox->setText(isChecked() ? tr("True") : tr("False"));
-    else
-        m_checkBox->setText(QString());
-}
-
-Qt::CheckState QtBoolEdit::checkState() const
-{
-    return m_checkBox->checkState();
-}
-
-void QtBoolEdit::setCheckState(Qt::CheckState state)
-{
-    m_checkBox->setCheckState(state);
-}
-
-bool QtBoolEdit::isChecked() const
-{
-    return m_checkBox->isChecked();
-}
-
-void QtBoolEdit::setChecked(bool c)
-{
-    m_checkBox->setChecked(c);
-    if (!m_textVisible)
-        return;
-    m_checkBox->setText(isChecked() ? tr("True") : tr("False"));
-}
-
-bool QtBoolEdit::blockCheckBoxSignals(bool block)
-{
-    return m_checkBox->blockSignals(block);
-}
-
-void QtBoolEdit::mousePressEvent(QMouseEvent *event)
-{
-    if (event->buttons() == Qt::LeftButton) {
-        m_checkBox->click();
-        event->accept();
-    } else {
-        QWidget::mousePressEvent(event);
-    }
-}
-
-
-QtKeySequenceEdit::QtKeySequenceEdit(QWidget *parent)
-    : QWidget(parent), m_num(0), m_lineEdit(new QLineEdit(this))
-{
-    QHBoxLayout *layout = new QHBoxLayout(this);
-    layout->addWidget(m_lineEdit);
-    layout->setMargin(0);
-    m_lineEdit->installEventFilter(this);
-    m_lineEdit->setReadOnly(true);
-    m_lineEdit->setFocusProxy(this);
-    setFocusPolicy(m_lineEdit->focusPolicy());
-    setAttribute(Qt::WA_InputMethodEnabled);
-}
-
-bool QtKeySequenceEdit::eventFilter(QObject *o, QEvent *e)
-{
-    if (o == m_lineEdit && e->type() == QEvent::ContextMenu) {
-        QContextMenuEvent *c = static_cast<QContextMenuEvent *>(e);
-        QMenu *menu = m_lineEdit->createStandardContextMenu();
-        const QList<QAction *> actions = menu->actions();
-        QListIterator<QAction *> itAction(actions);
-        while (itAction.hasNext()) {
-            QAction *action = itAction.next();
-            action->setShortcut(QKeySequence());
-            QString actionString = action->text();
-            const int pos = actionString.lastIndexOf(QLatin1Char('\t'));
-            if (pos > 0)
-                actionString.remove(pos, actionString.length() - pos);
-            action->setText(actionString);
-        }
-        QAction *actionBefore = 0;
-        if (actions.count() > 0)
-            actionBefore = actions[0];
-        QAction *clearAction = new QAction(tr("Clear Shortcut"), menu);
-        menu->insertAction(actionBefore, clearAction);
-        menu->insertSeparator(actionBefore);
-        clearAction->setEnabled(!m_keySequence.isEmpty());
-        connect(clearAction, SIGNAL(triggered()), this, SLOT(slotClearShortcut()));
-        menu->exec(c->globalPos());
-        delete menu;
-        e->accept();
-        return true;
-    }
-
-    return QWidget::eventFilter(o, e);
-}
-
-void QtKeySequenceEdit::slotClearShortcut()
-{
-    if (m_keySequence.isEmpty())
-        return;
-    setKeySequence(QKeySequence());
-    emit keySequenceChanged(m_keySequence);
-}
-
-void QtKeySequenceEdit::handleKeyEvent(QKeyEvent *e)
-{
-    int nextKey = e->key();
-    if (nextKey == Qt::Key_Control || nextKey == Qt::Key_Shift ||
-            nextKey == Qt::Key_Meta || nextKey == Qt::Key_Alt ||
-            nextKey == Qt::Key_Super_L || nextKey == Qt::Key_AltGr)
-        return;
-
-    nextKey |= translateModifiers(e->modifiers(), e->text());
-    int k0 = m_keySequence[0];
-    int k1 = m_keySequence[1];
-    int k2 = m_keySequence[2];
-    int k3 = m_keySequence[3];
-    switch (m_num) {
-        case 0: k0 = nextKey; k1 = 0; k2 = 0; k3 = 0; break;
-        case 1: k1 = nextKey; k2 = 0; k3 = 0; break;
-        case 2: k2 = nextKey; k3 = 0; break;
-        case 3: k3 = nextKey; break;
-        default: break;
-    }
-    ++m_num;
-    if (m_num > 3)
-        m_num = 0;
-    m_keySequence = QKeySequence(k0, k1, k2, k3);
-    m_lineEdit->setText(m_keySequence.toString(QKeySequence::NativeText));
-    e->accept();
-    emit keySequenceChanged(m_keySequence);
-}
-
-void QtKeySequenceEdit::setKeySequence(const QKeySequence &sequence)
-{
-    if (sequence == m_keySequence)
-        return;
-    m_num = 0;
-    m_keySequence = sequence;
-    m_lineEdit->setText(m_keySequence.toString(QKeySequence::NativeText));
-}
-
-QKeySequence QtKeySequenceEdit::keySequence() const
-{
-    return m_keySequence;
-}
-
-int QtKeySequenceEdit::translateModifiers(Qt::KeyboardModifiers state, const QString &text) const
-{
-    int result = 0;
-    if ((state & Qt::ShiftModifier) && (text.size() == 0 || !text.at(0).isPrint() || text.at(0).isLetter() || text.at(0).isSpace()))
-        result |= Qt::SHIFT;
-    if (state & Qt::ControlModifier)
-        result |= Qt::CTRL;
-    if (state & Qt::MetaModifier)
-        result |= Qt::META;
-    if (state & Qt::AltModifier)
-        result |= Qt::ALT;
-    return result;
-}
-
-void QtKeySequenceEdit::focusInEvent(QFocusEvent *e)
-{
-    m_lineEdit->event(e);
-    m_lineEdit->selectAll();
-    QWidget::focusInEvent(e);
-}
-
-void QtKeySequenceEdit::focusOutEvent(QFocusEvent *e)
-{
-    m_num = 0;
-    m_lineEdit->event(e);
-    QWidget::focusOutEvent(e);
-}
-
-void QtKeySequenceEdit::keyPressEvent(QKeyEvent *e)
-{
-    handleKeyEvent(e);
-    e->accept();
-}
-
-void QtKeySequenceEdit::keyReleaseEvent(QKeyEvent *e)
-{
-    m_lineEdit->event(e);
-}
-
-bool QtKeySequenceEdit::event(QEvent *e)
-{
-    if (e->type() == QEvent::Shortcut ||
-            e->type() == QEvent::ShortcutOverride  ||
-            e->type() == QEvent::KeyRelease) {
-        e->accept();
-        return true;
-    }
-    return QWidget::event(e);
-}
-
-
-
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qtpropertybrowserutils_p.h"
+#include <QtGui/QApplication>
+#include <QtGui/QPainter>
+#include <QtGui/QHBoxLayout>
+#include <QtGui/QMouseEvent>
+#include <QtGui/QCheckBox>
+#include <QtGui/QLineEdit>
+#include <QtGui/QMenu>
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+QtCursorDatabase::QtCursorDatabase()
+{
+    appendCursor(Qt::ArrowCursor, QApplication::translate("QtCursorDatabase", "Arrow", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-arrow.png")));
+    appendCursor(Qt::UpArrowCursor, QApplication::translate("QtCursorDatabase", "Up Arrow", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-uparrow.png")));
+    appendCursor(Qt::CrossCursor, QApplication::translate("QtCursorDatabase", "Cross", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-cross.png")));
+    appendCursor(Qt::WaitCursor, QApplication::translate("QtCursorDatabase", "Wait", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-wait.png")));
+    appendCursor(Qt::IBeamCursor, QApplication::translate("QtCursorDatabase", "IBeam", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-ibeam.png")));
+    appendCursor(Qt::SizeVerCursor, QApplication::translate("QtCursorDatabase", "Size Vertical", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizev.png")));
+    appendCursor(Qt::SizeHorCursor, QApplication::translate("QtCursorDatabase", "Size Horizontal", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizeh.png")));
+    appendCursor(Qt::SizeFDiagCursor, QApplication::translate("QtCursorDatabase", "Size Backslash", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizef.png")));
+    appendCursor(Qt::SizeBDiagCursor, QApplication::translate("QtCursorDatabase", "Size Slash", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizeb.png")));
+    appendCursor(Qt::SizeAllCursor, QApplication::translate("QtCursorDatabase", "Size All", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-sizeall.png")));
+    appendCursor(Qt::BlankCursor, QApplication::translate("QtCursorDatabase", "Blank", 0,
+                        QApplication::UnicodeUTF8), QIcon());
+    appendCursor(Qt::SplitVCursor, QApplication::translate("QtCursorDatabase", "Split Vertical", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-vsplit.png")));
+    appendCursor(Qt::SplitHCursor, QApplication::translate("QtCursorDatabase", "Split Horizontal", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-hsplit.png")));
+    appendCursor(Qt::PointingHandCursor, QApplication::translate("QtCursorDatabase", "Pointing Hand", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-hand.png")));
+    appendCursor(Qt::ForbiddenCursor, QApplication::translate("QtCursorDatabase", "Forbidden", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-forbidden.png")));
+    appendCursor(Qt::OpenHandCursor, QApplication::translate("QtCursorDatabase", "Open Hand", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-openhand.png")));
+    appendCursor(Qt::ClosedHandCursor, QApplication::translate("QtCursorDatabase", "Closed Hand", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-closedhand.png")));
+    appendCursor(Qt::WhatsThisCursor, QApplication::translate("QtCursorDatabase", "What's This", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-whatsthis.png")));
+    appendCursor(Qt::BusyCursor, QApplication::translate("QtCursorDatabase", "Busy", 0,
+                        QApplication::UnicodeUTF8), QIcon(QLatin1String(":/trolltech/qtpropertybrowser/images/cursor-busy.png")));
+}
+
+void QtCursorDatabase::appendCursor(Qt::CursorShape shape, const QString &name, const QIcon &icon)
+{
+    if (m_cursorShapeToValue.contains(shape))
+        return;
+    int value = m_cursorNames.count();
+    m_cursorNames.append(name);
+    m_cursorIcons[value] = icon;
+    m_valueToCursorShape[value] = shape;
+    m_cursorShapeToValue[shape] = value;
+}
+
+QStringList QtCursorDatabase::cursorShapeNames() const
+{
+    return m_cursorNames;
+}
+
+QMap<int, QIcon> QtCursorDatabase::cursorShapeIcons() const
+{
+    return m_cursorIcons;
+}
+
+QString QtCursorDatabase::cursorToShapeName(const QCursor &cursor) const
+{
+    int val = cursorToValue(cursor);
+    if (val >= 0)
+        return m_cursorNames.at(val);
+    return QString();
+}
+
+QIcon QtCursorDatabase::cursorToShapeIcon(const QCursor &cursor) const
+{
+    int val = cursorToValue(cursor);
+    return m_cursorIcons.value(val);
+}
+
+int QtCursorDatabase::cursorToValue(const QCursor &cursor) const
+{
+#ifndef QT_NO_CURSOR
+    Qt::CursorShape shape = cursor.shape();
+    if (m_cursorShapeToValue.contains(shape))
+        return m_cursorShapeToValue[shape];
+#endif
+    return -1;
+}
+
+#ifndef QT_NO_CURSOR
+QCursor QtCursorDatabase::valueToCursor(int value) const
+{
+    if (m_valueToCursorShape.contains(value))
+        return QCursor(m_valueToCursorShape[value]);
+    return QCursor();
+}
+#endif
+
+QPixmap QtPropertyBrowserUtils::brushValuePixmap(const QBrush &b)
+{
+    QImage img(16, 16, QImage::Format_ARGB32_Premultiplied);
+    img.fill(0);
+
+    QPainter painter(&img);
+    painter.setCompositionMode(QPainter::CompositionMode_Source);
+    painter.fillRect(0, 0, img.width(), img.height(), b);
+    QColor color = b.color();
+    if (color.alpha() != 255) { // indicate alpha by an inset
+        QBrush  opaqueBrush = b;
+        color.setAlpha(255);
+        opaqueBrush.setColor(color);
+        painter.fillRect(img.width() / 4, img.height() / 4,
+                         img.width() / 2, img.height() / 2, opaqueBrush);
+    }
+    painter.end();
+    return QPixmap::fromImage(img);
+}
+
+QIcon QtPropertyBrowserUtils::brushValueIcon(const QBrush &b)
+{
+    return QIcon(brushValuePixmap(b));
+}
+
+QString QtPropertyBrowserUtils::colorValueText(const QColor &c)
+{
+    return QApplication::translate("QtPropertyBrowserUtils", "[%1, %2, %3] (%4)", 0, QApplication::UnicodeUTF8)
+                                  .arg(QString::number(c.red()))
+                                  .arg(QString::number(c.green()))
+                                  .arg(QString::number(c.blue()))
+                                  .arg(QString::number(c.alpha()));
+}
+
+QPixmap QtPropertyBrowserUtils::fontValuePixmap(const QFont &font)
+{
+    QFont f = font;
+    QImage img(16, 16, QImage::Format_ARGB32_Premultiplied);
+    img.fill(0);
+    QPainter p(&img);
+    p.setRenderHint(QPainter::TextAntialiasing, true);
+    p.setRenderHint(QPainter::Antialiasing, true);
+    f.setPointSize(13);
+    p.setFont(f);
+    QTextOption t;
+    t.setAlignment(Qt::AlignCenter);
+    p.drawText(QRect(0, 0, 16, 16), QString(QLatin1Char('A')), t);
+    return QPixmap::fromImage(img);
+}
+
+QIcon QtPropertyBrowserUtils::fontValueIcon(const QFont &f)
+{
+    return QIcon(fontValuePixmap(f));
+}
+
+QString QtPropertyBrowserUtils::fontValueText(const QFont &f)
+{
+    return QApplication::translate("QtPropertyBrowserUtils", "[%1, %2]", 0, QApplication::UnicodeUTF8)
+                                  .arg(f.family())
+                                  .arg(f.pointSize());
+}
+
+
+QtBoolEdit::QtBoolEdit(QWidget *parent) :
+    QWidget(parent),
+    m_checkBox(new QCheckBox(this)),
+    m_textVisible(true)
+{
+    QHBoxLayout *lt = new QHBoxLayout;
+    if (QApplication::layoutDirection() == Qt::LeftToRight)
+        lt->setContentsMargins(4, 0, 0, 0);
+    else
+        lt->setContentsMargins(0, 0, 4, 0);
+    lt->addWidget(m_checkBox);
+    setLayout(lt);
+    connect(m_checkBox, SIGNAL(toggled(bool)), this, SIGNAL(toggled(bool)));
+    setFocusProxy(m_checkBox);
+    m_checkBox->setText(tr("True"));
+}
+
+void QtBoolEdit::setTextVisible(bool textVisible)
+{
+    if (m_textVisible == textVisible)
+        return;
+
+    m_textVisible = textVisible;
+    if (m_textVisible)
+        m_checkBox->setText(isChecked() ? tr("True") : tr("False"));
+    else
+        m_checkBox->setText(QString());
+}
+
+Qt::CheckState QtBoolEdit::checkState() const
+{
+    return m_checkBox->checkState();
+}
+
+void QtBoolEdit::setCheckState(Qt::CheckState state)
+{
+    m_checkBox->setCheckState(state);
+}
+
+bool QtBoolEdit::isChecked() const
+{
+    return m_checkBox->isChecked();
+}
+
+void QtBoolEdit::setChecked(bool c)
+{
+    m_checkBox->setChecked(c);
+    if (!m_textVisible)
+        return;
+    m_checkBox->setText(isChecked() ? tr("True") : tr("False"));
+}
+
+bool QtBoolEdit::blockCheckBoxSignals(bool block)
+{
+    return m_checkBox->blockSignals(block);
+}
+
+void QtBoolEdit::mousePressEvent(QMouseEvent *event)
+{
+    if (event->buttons() == Qt::LeftButton) {
+        m_checkBox->click();
+        event->accept();
+    } else {
+        QWidget::mousePressEvent(event);
+    }
+}
+
+
+QtKeySequenceEdit::QtKeySequenceEdit(QWidget *parent)
+    : QWidget(parent), m_num(0), m_lineEdit(new QLineEdit(this))
+{
+    QHBoxLayout *layout = new QHBoxLayout(this);
+    layout->addWidget(m_lineEdit);
+    layout->setMargin(0);
+    m_lineEdit->installEventFilter(this);
+    m_lineEdit->setReadOnly(true);
+    m_lineEdit->setFocusProxy(this);
+    setFocusPolicy(m_lineEdit->focusPolicy());
+    setAttribute(Qt::WA_InputMethodEnabled);
+}
+
+bool QtKeySequenceEdit::eventFilter(QObject *o, QEvent *e)
+{
+    if (o == m_lineEdit && e->type() == QEvent::ContextMenu) {
+        QContextMenuEvent *c = static_cast<QContextMenuEvent *>(e);
+        QMenu *menu = m_lineEdit->createStandardContextMenu();
+        const QList<QAction *> actions = menu->actions();
+        QListIterator<QAction *> itAction(actions);
+        while (itAction.hasNext()) {
+            QAction *action = itAction.next();
+            action->setShortcut(QKeySequence());
+            QString actionString = action->text();
+            const int pos = actionString.lastIndexOf(QLatin1Char('\t'));
+            if (pos > 0)
+                actionString.remove(pos, actionString.length() - pos);
+            action->setText(actionString);
+        }
+        QAction *actionBefore = 0;
+        if (actions.count() > 0)
+            actionBefore = actions[0];
+        QAction *clearAction = new QAction(tr("Clear Shortcut"), menu);
+        menu->insertAction(actionBefore, clearAction);
+        menu->insertSeparator(actionBefore);
+        clearAction->setEnabled(!m_keySequence.isEmpty());
+        connect(clearAction, SIGNAL(triggered()), this, SLOT(slotClearShortcut()));
+        menu->exec(c->globalPos());
+        delete menu;
+        e->accept();
+        return true;
+    }
+
+    return QWidget::eventFilter(o, e);
+}
+
+void QtKeySequenceEdit::slotClearShortcut()
+{
+    if (m_keySequence.isEmpty())
+        return;
+    setKeySequence(QKeySequence());
+    emit keySequenceChanged(m_keySequence);
+}
+
+void QtKeySequenceEdit::handleKeyEvent(QKeyEvent *e)
+{
+    int nextKey = e->key();
+    if (nextKey == Qt::Key_Control || nextKey == Qt::Key_Shift ||
+            nextKey == Qt::Key_Meta || nextKey == Qt::Key_Alt ||
+            nextKey == Qt::Key_Super_L || nextKey == Qt::Key_AltGr)
+        return;
+
+    nextKey |= translateModifiers(e->modifiers(), e->text());
+    int k0 = m_keySequence[0];
+    int k1 = m_keySequence[1];
+    int k2 = m_keySequence[2];
+    int k3 = m_keySequence[3];
+    switch (m_num) {
+        case 0: k0 = nextKey; k1 = 0; k2 = 0; k3 = 0; break;
+        case 1: k1 = nextKey; k2 = 0; k3 = 0; break;
+        case 2: k2 = nextKey; k3 = 0; break;
+        case 3: k3 = nextKey; break;
+        default: break;
+    }
+    ++m_num;
+    if (m_num > 3)
+        m_num = 0;
+    m_keySequence = QKeySequence(k0, k1, k2, k3);
+    m_lineEdit->setText(m_keySequence.toString(QKeySequence::NativeText));
+    e->accept();
+    emit keySequenceChanged(m_keySequence);
+}
+
+void QtKeySequenceEdit::setKeySequence(const QKeySequence &sequence)
+{
+    if (sequence == m_keySequence)
+        return;
+    m_num = 0;
+    m_keySequence = sequence;
+    m_lineEdit->setText(m_keySequence.toString(QKeySequence::NativeText));
+}
+
+QKeySequence QtKeySequenceEdit::keySequence() const
+{
+    return m_keySequence;
+}
+
+int QtKeySequenceEdit::translateModifiers(Qt::KeyboardModifiers state, const QString &text) const
+{
+    int result = 0;
+    if ((state & Qt::ShiftModifier) && (text.size() == 0 || !text.at(0).isPrint() || text.at(0).isLetter() || text.at(0).isSpace()))
+        result |= Qt::SHIFT;
+    if (state & Qt::ControlModifier)
+        result |= Qt::CTRL;
+    if (state & Qt::MetaModifier)
+        result |= Qt::META;
+    if (state & Qt::AltModifier)
+        result |= Qt::ALT;
+    return result;
+}
+
+void QtKeySequenceEdit::focusInEvent(QFocusEvent *e)
+{
+    m_lineEdit->event(e);
+    m_lineEdit->selectAll();
+    QWidget::focusInEvent(e);
+}
+
+void QtKeySequenceEdit::focusOutEvent(QFocusEvent *e)
+{
+    m_num = 0;
+    m_lineEdit->event(e);
+    QWidget::focusOutEvent(e);
+}
+
+void QtKeySequenceEdit::keyPressEvent(QKeyEvent *e)
+{
+    handleKeyEvent(e);
+    e->accept();
+}
+
+void QtKeySequenceEdit::keyReleaseEvent(QKeyEvent *e)
+{
+    m_lineEdit->event(e);
+}
+
+bool QtKeySequenceEdit::event(QEvent *e)
+{
+    if (e->type() == QEvent::Shortcut ||
+            e->type() == QEvent::ShortcutOverride  ||
+            e->type() == QEvent::KeyRelease) {
+        e->accept();
+        return true;
+    }
+    return QWidget::event(e);
+}
+
+
+
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
diff --git a/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowserutils_p.h b/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowserutils_p.h
index 5ef579e5d5d4253d4f95aeefbd84d63e5ae1dc6e..dca4b8c37b30fcf8c880243c57be5dc7b2181eb5 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowserutils_p.h
+++ b/Code/Mantid/QtPropertyBrowser/src/qtpropertybrowserutils_p.h
@@ -1,207 +1,207 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//
-//  W A R N I N G
-//  -------------
-//
-// This file is not part of the Qt API.  It exists for the convenience
-// of Qt Designer.  This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#ifndef QTPROPERTYBROWSERUTILS_H
-#define QTPROPERTYBROWSERUTILS_H
-
-#include <QtCore/QMap>
-#include <QtGui/QIcon>
-#include <QtGui/QWidget>
-#include <QtCore/QStringList>
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-class QMouseEvent;
-class QCheckBox;
-class QLineEdit;
-
-class QtCursorDatabase
-{
-public:
-    QtCursorDatabase();
-
-    QStringList cursorShapeNames() const;
-    QMap<int, QIcon> cursorShapeIcons() const;
-    QString cursorToShapeName(const QCursor &cursor) const;
-    QIcon cursorToShapeIcon(const QCursor &cursor) const;
-    int cursorToValue(const QCursor &cursor) const;
-#ifndef QT_NO_CURSOR
-    QCursor valueToCursor(int value) const;
-#endif
-private:
-    void appendCursor(Qt::CursorShape shape, const QString &name, const QIcon &icon);
-    QStringList m_cursorNames;
-    QMap<int, QIcon> m_cursorIcons;
-    QMap<int, Qt::CursorShape> m_valueToCursorShape;
-    QMap<Qt::CursorShape, int> m_cursorShapeToValue;
-};
-
-class QtPropertyBrowserUtils
-{
-public:
-    static QPixmap brushValuePixmap(const QBrush &b);
-    static QIcon brushValueIcon(const QBrush &b);
-    static QString colorValueText(const QColor &c);
-    static QPixmap fontValuePixmap(const QFont &f);
-    static QIcon fontValueIcon(const QFont &f);
-    static QString fontValueText(const QFont &f);
-};
-
-class QtBoolEdit : public QWidget {
-    Q_OBJECT
-public:
-    QtBoolEdit(QWidget *parent = 0);
-
-    bool textVisible() const { return m_textVisible; }
-    void setTextVisible(bool textVisible);
-
-    Qt::CheckState checkState() const;
-    void setCheckState(Qt::CheckState state);
-
-    bool isChecked() const;
-    void setChecked(bool c);
-
-    bool blockCheckBoxSignals(bool block);
-
-Q_SIGNALS:
-    void toggled(bool);
-
-protected:
-    void mousePressEvent(QMouseEvent * event);
-
-private:
-    QCheckBox *m_checkBox;
-    bool m_textVisible;
-};
-
-class QtKeySequenceEdit : public QWidget
-{
-    Q_OBJECT
-public:
-    QtKeySequenceEdit(QWidget *parent = 0);
-
-    QKeySequence keySequence() const;
-    bool eventFilter(QObject *o, QEvent *e);
-public Q_SLOTS:
-    void setKeySequence(const QKeySequence &sequence);
-Q_SIGNALS:
-    void keySequenceChanged(const QKeySequence &sequence);
-protected:
-    void focusInEvent(QFocusEvent *e);
-    void focusOutEvent(QFocusEvent *e);
-    void keyPressEvent(QKeyEvent *e);
-    void keyReleaseEvent(QKeyEvent *e);
-    bool event(QEvent *e);
-private slots:
-    void slotClearShortcut();
-private:
-    void handleKeyEvent(QKeyEvent *e);
-    int translateModifiers(Qt::KeyboardModifiers state, const QString &text) const;
-
-    int m_num;
-    QKeySequence m_keySequence;
-    QLineEdit *m_lineEdit;
-};
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#endif
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+//
+//  W A R N I N G
+//  -------------
+//
+// This file is not part of the Qt API.  It exists for the convenience
+// of Qt Designer.  This header
+// file may change from version to version without notice, or even be removed.
+//
+// We mean it.
+//
+
+#ifndef QTPROPERTYBROWSERUTILS_H
+#define QTPROPERTYBROWSERUTILS_H
+
+#include <QtCore/QMap>
+#include <QtGui/QIcon>
+#include <QtGui/QWidget>
+#include <QtCore/QStringList>
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+class QMouseEvent;
+class QCheckBox;
+class QLineEdit;
+
+class QtCursorDatabase
+{
+public:
+    QtCursorDatabase();
+
+    QStringList cursorShapeNames() const;
+    QMap<int, QIcon> cursorShapeIcons() const;
+    QString cursorToShapeName(const QCursor &cursor) const;
+    QIcon cursorToShapeIcon(const QCursor &cursor) const;
+    int cursorToValue(const QCursor &cursor) const;
+#ifndef QT_NO_CURSOR
+    QCursor valueToCursor(int value) const;
+#endif
+private:
+    void appendCursor(Qt::CursorShape shape, const QString &name, const QIcon &icon);
+    QStringList m_cursorNames;
+    QMap<int, QIcon> m_cursorIcons;
+    QMap<int, Qt::CursorShape> m_valueToCursorShape;
+    QMap<Qt::CursorShape, int> m_cursorShapeToValue;
+};
+
+class QtPropertyBrowserUtils
+{
+public:
+    static QPixmap brushValuePixmap(const QBrush &b);
+    static QIcon brushValueIcon(const QBrush &b);
+    static QString colorValueText(const QColor &c);
+    static QPixmap fontValuePixmap(const QFont &f);
+    static QIcon fontValueIcon(const QFont &f);
+    static QString fontValueText(const QFont &f);
+};
+
+class QtBoolEdit : public QWidget {
+    Q_OBJECT
+public:
+    QtBoolEdit(QWidget *parent = 0);
+
+    bool textVisible() const { return m_textVisible; }
+    void setTextVisible(bool textVisible);
+
+    Qt::CheckState checkState() const;
+    void setCheckState(Qt::CheckState state);
+
+    bool isChecked() const;
+    void setChecked(bool c);
+
+    bool blockCheckBoxSignals(bool block);
+
+Q_SIGNALS:
+    void toggled(bool);
+
+protected:
+    void mousePressEvent(QMouseEvent * event);
+
+private:
+    QCheckBox *m_checkBox;
+    bool m_textVisible;
+};
+
+class QtKeySequenceEdit : public QWidget
+{
+    Q_OBJECT
+public:
+    QtKeySequenceEdit(QWidget *parent = 0);
+
+    QKeySequence keySequence() const;
+    bool eventFilter(QObject *o, QEvent *e);
+public Q_SLOTS:
+    void setKeySequence(const QKeySequence &sequence);
+Q_SIGNALS:
+    void keySequenceChanged(const QKeySequence &sequence);
+protected:
+    void focusInEvent(QFocusEvent *e);
+    void focusOutEvent(QFocusEvent *e);
+    void keyPressEvent(QKeyEvent *e);
+    void keyReleaseEvent(QKeyEvent *e);
+    bool event(QEvent *e);
+private slots:
+    void slotClearShortcut();
+private:
+    void handleKeyEvent(QKeyEvent *e);
+    int translateModifiers(Qt::KeyboardModifiers state, const QString &text) const;
+
+    int m_num;
+    QKeySequence m_keySequence;
+    QLineEdit *m_lineEdit;
+};
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#endif
diff --git a/Code/Mantid/QtPropertyBrowser/src/qtpropertymanager.cpp b/Code/Mantid/QtPropertyBrowser/src/qtpropertymanager.cpp
index 375bf88e33a868cdce36b0db3de7d7d424ea9ac1..e969faa99d92652342f22f88ae009732507f2696 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qtpropertymanager.cpp
+++ b/Code/Mantid/QtPropertyBrowser/src/qtpropertymanager.cpp
@@ -1,6473 +1,6473 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qtpropertymanager.h"
-#include "qtpropertybrowserutils_p.h"
-#include <QtCore/QDateTime>
-#include <QtCore/QLocale>
-#include <QtCore/QMap>
-#include <QtCore/QTimer>
-#include <QtGui/QIcon>
-#include <QtCore/QMetaEnum>
-#include <QtGui/QFontDatabase>
-#include <QtGui/QStyleOption>
-#include <QtGui/QStyle>
-#include <QtGui/QApplication>
-#include <QtGui/QPainter>
-#include <QtGui/QLabel>
-
-#include <limits.h>
-#include <float.h>
-#include <math.h>
-
-#if defined(Q_CC_MSVC)
-#    pragma warning(disable: 4786) /* MS VS 6: truncating debug info after 255 characters */
-#endif
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-template <class PrivateData, class Value>
-static void setSimpleMinimumData(PrivateData *data, const Value &minVal)
-{
-    data->minVal = minVal;
-    if (data->maxVal < data->minVal)
-        data->maxVal = data->minVal;
-
-    if (data->val < data->minVal)
-        data->val = data->minVal;
-}
-
-template <class PrivateData, class Value>
-static void setSimpleMaximumData(PrivateData *data, const Value &maxVal)
-{
-    data->maxVal = maxVal;
-    if (data->minVal > data->maxVal)
-        data->minVal = data->maxVal;
-
-    if (data->val > data->maxVal)
-        data->val = data->maxVal;
-}
-
-template <class PrivateData, class Value>
-static void setSizeMinimumData(PrivateData *data, const Value &newMinVal)
-{
-    data->minVal = newMinVal;
-    if (data->maxVal.width() < data->minVal.width())
-        data->maxVal.setWidth(data->minVal.width());
-    if (data->maxVal.height() < data->minVal.height())
-        data->maxVal.setHeight(data->minVal.height());
-
-    if (data->val.width() < data->minVal.width())
-        data->val.setWidth(data->minVal.width());
-    if (data->val.height() < data->minVal.height())
-        data->val.setHeight(data->minVal.height());
-}
-
-template <class PrivateData, class Value>
-static void setSizeMaximumData(PrivateData *data, const Value &newMaxVal)
-{
-    data->maxVal = newMaxVal;
-    if (data->minVal.width() > data->maxVal.width())
-        data->minVal.setWidth(data->maxVal.width());
-    if (data->minVal.height() > data->maxVal.height())
-        data->minVal.setHeight(data->maxVal.height());
-
-    if (data->val.width() > data->maxVal.width())
-        data->val.setWidth(data->maxVal.width());
-    if (data->val.height() > data->maxVal.height())
-        data->val.setHeight(data->maxVal.height());
-}
-
-template <class SizeValue>
-static SizeValue qBoundSize(const SizeValue &minVal, const SizeValue &val, const SizeValue &maxVal)
-{
-    SizeValue croppedVal = val;
-    if (minVal.width() > val.width())
-        croppedVal.setWidth(minVal.width());
-    else if (maxVal.width() < val.width())
-        croppedVal.setWidth(maxVal.width());
-
-    if (minVal.height() > val.height())
-        croppedVal.setHeight(minVal.height());
-    else if (maxVal.height() < val.height())
-        croppedVal.setHeight(maxVal.height());
-
-    return croppedVal;
-}
-
-// Match the exact signature of qBound for VS 6.
-QSize qBound(QSize minVal, QSize val, QSize maxVal)
-{
-    return qBoundSize(minVal, val, maxVal);
-}
-
-QSizeF qBound(QSizeF minVal, QSizeF val, QSizeF maxVal)
-{
-    return qBoundSize(minVal, val, maxVal);
-}
-
-namespace {
-
-namespace {
-template <class Value>
-void orderBorders(Value &minVal, Value &maxVal)
-{
-    if (minVal > maxVal)
-        qSwap(minVal, maxVal);
-}
-
-template <class Value>
-static void orderSizeBorders(Value &minVal, Value &maxVal)
-{
-    Value fromSize = minVal;
-    Value toSize = maxVal;
-    if (fromSize.width() > toSize.width()) {
-        fromSize.setWidth(maxVal.width());
-        toSize.setWidth(minVal.width());
-    }
-    if (fromSize.height() > toSize.height()) {
-        fromSize.setHeight(maxVal.height());
-        toSize.setHeight(minVal.height());
-    }
-    minVal = fromSize;
-    maxVal = toSize;
-}
-
-void orderBorders(QSize &minVal, QSize &maxVal)
-{
-    orderSizeBorders(minVal, maxVal);
-}
-
-void orderBorders(QSizeF &minVal, QSizeF &maxVal)
-{
-    orderSizeBorders(minVal, maxVal);
-}
-
-}
-}
-////////
-
-template <class Value, class PrivateData>
-static Value getData(const QMap<const QtProperty *, PrivateData> &propertyMap,
-            Value PrivateData::*data,
-            const QtProperty *property, const Value &defaultValue = Value())
-{
-    typedef QMap<const QtProperty *, PrivateData> PropertyToData;
-    typedef Q_TYPENAME PropertyToData::const_iterator PropertyToDataConstIterator;
-    const PropertyToDataConstIterator it = propertyMap.constFind(property);
-    if (it == propertyMap.constEnd())
-        return defaultValue;
-    return it.value().*data;
-}
-
-template <class Value, class PrivateData>
-static Value getValue(const QMap<const QtProperty *, PrivateData> &propertyMap,
-            const QtProperty *property, const Value &defaultValue = Value())
-{
-    return getData<Value>(propertyMap, &PrivateData::val, property, defaultValue);
-}
-
-template <class Value, class PrivateData>
-static Value getMinimum(const QMap<const QtProperty *, PrivateData> &propertyMap,
-            const QtProperty *property, const Value &defaultValue = Value())
-{
-    return getData<Value>(propertyMap, &PrivateData::minVal, property, defaultValue);
-}
-
-template <class Value, class PrivateData>
-static Value getMaximum(const QMap<const QtProperty *, PrivateData> &propertyMap,
-            const QtProperty *property, const Value &defaultValue = Value())
-{
-    return getData<Value>(propertyMap, &PrivateData::maxVal, property, defaultValue);
-}
-
-template <class ValueChangeParameter, class Value, class PropertyManager>
-static void setSimpleValue(QMap<const QtProperty *, Value> &propertyMap,
-            PropertyManager *manager,
-            void (PropertyManager::*propertyChangedSignal)(QtProperty *),
-            void (PropertyManager::*valueChangedSignal)(QtProperty *, ValueChangeParameter),
-            QtProperty *property, const Value &val)
-{
-    typedef QMap<const QtProperty *, Value> PropertyToData;
-    typedef Q_TYPENAME PropertyToData::iterator PropertyToDataIterator;
-    const PropertyToDataIterator it = propertyMap.find(property);
-    if (it == propertyMap.end())
-        return;
-
-    if (it.value() == val)
-        return;
-
-    it.value() = val;
-
-    emit (manager->*propertyChangedSignal)(property);
-    emit (manager->*valueChangedSignal)(property, val);
-}
-
-template <class ValueChangeParameter, class PropertyManagerPrivate, class PropertyManager, class Value>
-static void setValueInRange(PropertyManager *manager, PropertyManagerPrivate *managerPrivate,
-            void (PropertyManager::*propertyChangedSignal)(QtProperty *),
-            void (PropertyManager::*valueChangedSignal)(QtProperty *, ValueChangeParameter),
-            QtProperty *property, const Value &val,
-            void (PropertyManagerPrivate::*setSubPropertyValue)(QtProperty *, ValueChangeParameter))
-{
-    typedef Q_TYPENAME PropertyManagerPrivate::Data PrivateData;
-    typedef QMap<const QtProperty *, PrivateData> PropertyToData;
-    typedef Q_TYPENAME PropertyToData::iterator PropertyToDataIterator;
-    const PropertyToDataIterator it = managerPrivate->m_values.find(property);
-    if (it == managerPrivate->m_values.end())
-        return;
-
-    PrivateData &data = it.value();
-
-    if (data.val == val)
-        return;
-
-    const Value oldVal = data.val;
-
-    data.val = qBound(data.minVal, val, data.maxVal);
-
-    if (data.val == oldVal)
-        return;
-
-    if (setSubPropertyValue)
-        (managerPrivate->*setSubPropertyValue)(property, data.val);
-
-    emit (manager->*propertyChangedSignal)(property);
-    emit (manager->*valueChangedSignal)(property, data.val);
-}
-
-template <class ValueChangeParameter, class PropertyManagerPrivate, class PropertyManager, class Value>
-static void setBorderValues(PropertyManager *manager, PropertyManagerPrivate *managerPrivate,
-            void (PropertyManager::*propertyChangedSignal)(QtProperty *),
-            void (PropertyManager::*valueChangedSignal)(QtProperty *, ValueChangeParameter),
-            void (PropertyManager::*rangeChangedSignal)(QtProperty *, ValueChangeParameter, ValueChangeParameter),
-            QtProperty *property, const Value &minVal, const Value &maxVal,
-            void (PropertyManagerPrivate::*setSubPropertyRange)(QtProperty *,
-                    ValueChangeParameter, ValueChangeParameter, ValueChangeParameter))
-{
-    typedef Q_TYPENAME PropertyManagerPrivate::Data PrivateData;
-    typedef QMap<const QtProperty *, PrivateData> PropertyToData;
-    typedef Q_TYPENAME PropertyToData::iterator PropertyToDataIterator;
-    const PropertyToDataIterator it = managerPrivate->m_values.find(property);
-    if (it == managerPrivate->m_values.end())
-        return;
-
-    Value fromVal = minVal;
-    Value toVal = maxVal;
-    orderBorders(fromVal, toVal);
-
-    PrivateData &data = it.value();
-
-    if (data.minVal == fromVal && data.maxVal == toVal)
-        return;
-
-    const Value oldVal = data.val;
-
-    data.setMinimumValue(fromVal);
-    data.setMaximumValue(toVal);
-
-    emit (manager->*rangeChangedSignal)(property, data.minVal, data.maxVal);
-
-    if (setSubPropertyRange)
-        (managerPrivate->*setSubPropertyRange)(property, data.minVal, data.maxVal, data.val);
-
-    if (data.val == oldVal)
-        return;
-
-    emit (manager->*propertyChangedSignal)(property);
-    emit (manager->*valueChangedSignal)(property, data.val);
-}
-
-template <class ValueChangeParameter, class PropertyManagerPrivate, class PropertyManager, class Value, class PrivateData>
-static void setBorderValue(PropertyManager *manager, PropertyManagerPrivate *managerPrivate,
-            void (PropertyManager::*propertyChangedSignal)(QtProperty *),
-            void (PropertyManager::*valueChangedSignal)(QtProperty *, ValueChangeParameter),
-            void (PropertyManager::*rangeChangedSignal)(QtProperty *, ValueChangeParameter, ValueChangeParameter),
-            QtProperty *property,
-            Value (PrivateData::*getRangeVal)() const,
-            void (PrivateData::*setRangeVal)(ValueChangeParameter), const Value &borderVal,
-            void (PropertyManagerPrivate::*setSubPropertyRange)(QtProperty *,
-                    ValueChangeParameter, ValueChangeParameter, ValueChangeParameter))
-{
-    typedef QMap<const QtProperty *, PrivateData> PropertyToData;
-    typedef Q_TYPENAME PropertyToData::iterator PropertyToDataIterator;
-    const PropertyToDataIterator it = managerPrivate->m_values.find(property);
-    if (it == managerPrivate->m_values.end())
-        return;
-
-    PrivateData &data = it.value();
-
-    if ((data.*getRangeVal)() == borderVal)
-        return;
-
-    const Value oldVal = data.val;
-
-    (data.*setRangeVal)(borderVal);
-
-    emit (manager->*rangeChangedSignal)(property, data.minVal, data.maxVal);
-
-    if (setSubPropertyRange)
-        (managerPrivate->*setSubPropertyRange)(property, data.minVal, data.maxVal, data.val);
-
-    if (data.val == oldVal)
-        return;
-
-    emit (manager->*propertyChangedSignal)(property);
-    emit (manager->*valueChangedSignal)(property, data.val);
-}
-
-template <class ValueChangeParameter, class PropertyManagerPrivate, class PropertyManager, class Value, class PrivateData>
-static void setMinimumValue(PropertyManager *manager, PropertyManagerPrivate *managerPrivate,
-            void (PropertyManager::*propertyChangedSignal)(QtProperty *),
-            void (PropertyManager::*valueChangedSignal)(QtProperty *, ValueChangeParameter),
-            void (PropertyManager::*rangeChangedSignal)(QtProperty *, ValueChangeParameter, ValueChangeParameter),
-            QtProperty *property, const Value &minVal)
-{
-    void (PropertyManagerPrivate::*setSubPropertyRange)(QtProperty *,
-                    ValueChangeParameter, ValueChangeParameter, ValueChangeParameter) = 0;
-    setBorderValue<ValueChangeParameter, PropertyManagerPrivate, PropertyManager, Value, PrivateData>(manager, managerPrivate,
-            propertyChangedSignal, valueChangedSignal, rangeChangedSignal,
-            property, &PropertyManagerPrivate::Data::minimumValue, &PropertyManagerPrivate::Data::setMinimumValue, minVal, setSubPropertyRange);
-}
-
-template <class ValueChangeParameter, class PropertyManagerPrivate, class PropertyManager, class Value, class PrivateData>
-static void setMaximumValue(PropertyManager *manager, PropertyManagerPrivate *managerPrivate,
-            void (PropertyManager::*propertyChangedSignal)(QtProperty *),
-            void (PropertyManager::*valueChangedSignal)(QtProperty *, ValueChangeParameter),
-            void (PropertyManager::*rangeChangedSignal)(QtProperty *, ValueChangeParameter, ValueChangeParameter),
-            QtProperty *property, const Value &maxVal)
-{
-    void (PropertyManagerPrivate::*setSubPropertyRange)(QtProperty *,
-                    ValueChangeParameter, ValueChangeParameter, ValueChangeParameter) = 0;
-    setBorderValue<ValueChangeParameter, PropertyManagerPrivate, PropertyManager, Value, PrivateData>(manager, managerPrivate,
-            propertyChangedSignal, valueChangedSignal, rangeChangedSignal,
-            property, &PropertyManagerPrivate::Data::maximumValue, &PropertyManagerPrivate::Data::setMaximumValue, maxVal, setSubPropertyRange);
-}
-
-class QtMetaEnumWrapper : public QObject
-{
-    Q_OBJECT
-    Q_PROPERTY(QSizePolicy::Policy policy READ policy)
-public:
-    QSizePolicy::Policy policy() const { return QSizePolicy::Ignored; }
-private:
-    QtMetaEnumWrapper(QObject *parent) : QObject(parent) {}
-};
-
-class QtMetaEnumProvider
-{
-public:
-    QtMetaEnumProvider();
-
-    QStringList policyEnumNames() const { return m_policyEnumNames; }
-    QStringList languageEnumNames() const { return m_languageEnumNames; }
-    QStringList countryEnumNames(QLocale::Language language) const { return m_countryEnumNames.value(language); }
-
-    QSizePolicy::Policy indexToSizePolicy(int index) const;
-    int sizePolicyToIndex(QSizePolicy::Policy policy) const;
-
-    void indexToLocale(int languageIndex, int countryIndex, QLocale::Language *language, QLocale::Country *country) const;
-    void localeToIndex(QLocale::Language language, QLocale::Country country, int *languageIndex, int *countryIndex) const;
-
-private:
-    void initLocale();
-
-    QStringList m_policyEnumNames;
-    QStringList m_languageEnumNames;
-    QMap<QLocale::Language, QStringList> m_countryEnumNames;
-    QMap<int, QLocale::Language> m_indexToLanguage;
-    QMap<QLocale::Language, int> m_languageToIndex;
-    QMap<int, QMap<int, QLocale::Country> > m_indexToCountry;
-    QMap<QLocale::Language, QMap<QLocale::Country, int> > m_countryToIndex;
-    QMetaEnum m_policyEnum;
-};
-
-#if QT_VERSION < 0x040300
-
-static QList<QLocale::Country> countriesForLanguage(QLocale::Language language)
-{
-    QList<QLocale::Country> countries;
-    QLocale::Country country = QLocale::AnyCountry;
-    while (country <= QLocale::LastCountry) {
-        QLocale locale(language, country);
-        if (locale.language() == language && !countries.contains(locale.country()))
-            countries << locale.country();
-        country = (QLocale::Country)((uint)country + 1); // ++country
-    }
-    return countries;
-}
-
-#endif
-
-static QList<QLocale::Country> sortCountries(const QList<QLocale::Country> &countries)
-{
-    QMultiMap<QString, QLocale::Country> nameToCountry;
-    QListIterator<QLocale::Country> itCountry(countries);
-    while (itCountry.hasNext()) {
-        QLocale::Country country = itCountry.next();
-        nameToCountry.insert(QLocale::countryToString(country), country);
-    }
-    return nameToCountry.values();
-}
-
-void QtMetaEnumProvider::initLocale()
-{
-    QMultiMap<QString, QLocale::Language> nameToLanguage;
-    QLocale::Language language = QLocale::C;
-    while (language <= QLocale::LastLanguage) {
-        QLocale locale(language);
-        if (locale.language() == language)
-            nameToLanguage.insert(QLocale::languageToString(language), language);
-        language = (QLocale::Language)((uint)language + 1); // ++language
-    }
-
-    const QLocale system = QLocale::system();
-    if (!nameToLanguage.contains(QLocale::languageToString(system.language())))
-        nameToLanguage.insert(QLocale::languageToString(system.language()), system.language());
-
-    QList<QLocale::Language> languages = nameToLanguage.values();
-    QListIterator<QLocale::Language> itLang(languages);
-    while (itLang.hasNext()) {
-        QLocale::Language language = itLang.next();
-        QList<QLocale::Country> countries;
-#if QT_VERSION < 0x040300
-        countries = countriesForLanguage(language);
-#else
-        countries = QLocale::countriesForLanguage(language);
-#endif
-        if (countries.isEmpty() && language == system.language())
-            countries << system.country();
-
-        if (!countries.isEmpty() && !m_languageToIndex.contains(language)) {
-            countries = sortCountries(countries);
-            int langIdx = m_languageEnumNames.count();
-            m_indexToLanguage[langIdx] = language;
-            m_languageToIndex[language] = langIdx;
-            QStringList countryNames;
-            QListIterator<QLocale::Country> it(countries);
-            int countryIdx = 0;
-            while (it.hasNext()) {
-                QLocale::Country country = it.next();
-                countryNames << QLocale::countryToString(country);
-                m_indexToCountry[langIdx][countryIdx] = country;
-                m_countryToIndex[language][country] = countryIdx;
-                ++countryIdx;
-            }
-            m_languageEnumNames << QLocale::languageToString(language);
-            m_countryEnumNames[language] = countryNames;
-        }
-    }
-}
-
-QtMetaEnumProvider::QtMetaEnumProvider()
-{
-    QMetaProperty p;
-
-    p = QtMetaEnumWrapper::staticMetaObject.property(
-                QtMetaEnumWrapper::staticMetaObject.propertyOffset() + 0);
-    m_policyEnum = p.enumerator();
-    const int keyCount = m_policyEnum.keyCount();
-    for (int i = 0; i < keyCount; i++)
-        m_policyEnumNames << QLatin1String(m_policyEnum.key(i));
-
-    initLocale();
-}
-
-QSizePolicy::Policy QtMetaEnumProvider::indexToSizePolicy(int index) const
-{
-    return static_cast<QSizePolicy::Policy>(m_policyEnum.value(index));
-}
-
-int QtMetaEnumProvider::sizePolicyToIndex(QSizePolicy::Policy policy) const
-{
-     const int keyCount = m_policyEnum.keyCount();
-    for (int i = 0; i < keyCount; i++)
-        if (indexToSizePolicy(i) == policy)
-            return i;
-    return -1;
-}
-
-void QtMetaEnumProvider::indexToLocale(int languageIndex, int countryIndex, QLocale::Language *language, QLocale::Country *country) const
-{
-    QLocale::Language l = QLocale::C;
-    QLocale::Country c = QLocale::AnyCountry;
-    if (m_indexToLanguage.contains(languageIndex)) {
-        l = m_indexToLanguage[languageIndex];
-        if (m_indexToCountry.contains(languageIndex) && m_indexToCountry[languageIndex].contains(countryIndex))
-            c = m_indexToCountry[languageIndex][countryIndex];
-    }
-    if (language)
-        *language = l;
-    if (country)
-        *country = c;
-}
-
-void QtMetaEnumProvider::localeToIndex(QLocale::Language language, QLocale::Country country, int *languageIndex, int *countryIndex) const
-{
-    int l = -1;
-    int c = -1;
-    if (m_languageToIndex.contains(language)) {
-        l = m_languageToIndex[language];
-        if (m_countryToIndex.contains(language) && m_countryToIndex[language].contains(country))
-            c = m_countryToIndex[language][country];
-    }
-
-    if (languageIndex)
-        *languageIndex = l;
-    if (countryIndex)
-        *countryIndex = c;
-}
-
-Q_GLOBAL_STATIC(QtMetaEnumProvider, metaEnumProvider)
-
-// QtGroupPropertyManager
-
-/**
-    \class QtGroupPropertyManager
-
-    \brief The QtGroupPropertyManager provides and manages group properties.
-
-    This class is intended to provide a grouping element without any value.
-
-    \sa QtAbstractPropertyManager
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtGroupPropertyManager::QtGroupPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtGroupPropertyManager::~QtGroupPropertyManager()
-{
-
-}
-
-/**
-    \reimp
-*/
-bool QtGroupPropertyManager::hasValue(const QtProperty *property) const
-{
-    Q_UNUSED(property)
-    return false;
-}
-
-/**
-    \reimp
-*/
-void QtGroupPropertyManager::initializeProperty(QtProperty *property)
-{
-    Q_UNUSED(property)
-}
-
-/**
-    \reimp
-*/
-void QtGroupPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    Q_UNUSED(property)
-}
-
-// QtIntPropertyManager
-
-class QtIntPropertyManagerPrivate
-{
-    QtIntPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtIntPropertyManager)
-public:
-
-    struct Data
-    {
-        Data() : val(0), minVal(-INT_MAX), maxVal(INT_MAX), singleStep(1) {}
-        int val;
-        int minVal;
-        int maxVal;
-        int singleStep;
-        int minimumValue() const { return minVal; }
-        int maximumValue() const { return maxVal; }
-        void setMinimumValue(int newMinVal) { setSimpleMinimumData(this, newMinVal); }
-        void setMaximumValue(int newMaxVal) { setSimpleMaximumData(this, newMaxVal); }
-    };
-
-    typedef QMap<const QtProperty *, Data> PropertyValueMap;
-    PropertyValueMap m_values;
-};
-
-/**
-    \class QtIntPropertyManager
-
-    \brief The QtIntPropertyManager provides and manages int properties.
-
-    An int property has a current value, and a range specifying the
-    valid values. The range is defined by a minimum and a maximum
-    value.
-
-    The property's value and range can be retrieved using the value(),
-    minimum() and maximum() functions, and can be set using the
-    setValue(), setMinimum() and setMaximum() slots. Alternatively,
-    the range can be defined in one go using the setRange() slot.
-
-    In addition, QtIntPropertyManager provides the valueChanged() signal which
-    is emitted whenever a property created by this manager changes,
-    and the rangeChanged() signal which is emitted whenever such a
-    property changes its range of valid values.
-
-    \sa QtAbstractPropertyManager, QtSpinBoxFactory, QtSliderFactory, QtScrollBarFactory
-*/
-
-/**
-    \fn void QtIntPropertyManager::valueChanged(QtProperty *property, int value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    \fn void QtIntPropertyManager::rangeChanged(QtProperty *property, int minimum, int maximum)
-
-    This signal is emitted whenever a property created by this manager
-    changes its range of valid values, passing a pointer to the
-    \a property and the new \a minimum and \a maximum values.
-
-    \sa setRange()
-*/
-
-/**
-    \fn void QtIntPropertyManager::singleStepChanged(QtProperty *property, int step)
-
-    This signal is emitted whenever a property created by this manager
-    changes its single step property, passing a pointer to the
-    \a property and the new \a step value
-
-    \sa setSingleStep()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtIntPropertyManager::QtIntPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtIntPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtIntPropertyManager::~QtIntPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given property is not managed by this manager, this
-    function returns 0.
-
-    \sa setValue()
-*/
-int QtIntPropertyManager::value(const QtProperty *property) const
-{
-    return getValue<int>(d_ptr->m_values, property, 0);
-}
-
-/**
-    Returns the given \a property's minimum value.
-
-    \sa setMinimum(), maximum(), setRange()
-*/
-int QtIntPropertyManager::minimum(const QtProperty *property) const
-{
-    return getMinimum<int>(d_ptr->m_values, property, 0);
-}
-
-/**
-    Returns the given \a property's maximum value.
-
-    \sa setMaximum(), minimum(), setRange()
-*/
-int QtIntPropertyManager::maximum(const QtProperty *property) const
-{
-    return getMaximum<int>(d_ptr->m_values, property, 0);
-}
-
-/**
-    Returns the given \a property's step value.
-
-    The step is typically used to increment or decrement a property value while pressing an arrow key.
-
-    \sa setSingleStep()
-*/
-int QtIntPropertyManager::singleStep(const QtProperty *property) const
-{
-    return getData<int>(d_ptr->m_values, &QtIntPropertyManagerPrivate::Data::singleStep, property, 0);
-}
-
-/**
-    \reimp
-*/
-QString QtIntPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtIntPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    return QString::number(it.value().val);
-}
-
-/**
-    \fn void QtIntPropertyManager::setValue(QtProperty *property, int value)
-
-    Sets the value of the given \a property to \a value.
-
-    If the specified \a value is not valid according to the given \a
-    property's range, the \a value is adjusted to the nearest valid
-    value within the range.
-
-    \sa value(), setRange(), valueChanged()
-*/
-void QtIntPropertyManager::setValue(QtProperty *property, int val)
-{
-    void (QtIntPropertyManagerPrivate::*setSubPropertyValue)(QtProperty *, int) = 0;
-    setValueInRange<int, QtIntPropertyManagerPrivate, QtIntPropertyManager, int>(this, d_ptr,
-                &QtIntPropertyManager::propertyChanged,
-                &QtIntPropertyManager::valueChanged,
-                property, val, setSubPropertyValue);
-}
-
-/**
-    Sets the minimum value for the given \a property to \a minVal.
-
-    When setting the minimum value, the maximum and current values are
-    adjusted if necessary (ensuring that the range remains valid and
-    that the current value is within the range).
-
-    \sa minimum(), setRange(), rangeChanged()
-*/
-void QtIntPropertyManager::setMinimum(QtProperty *property, int minVal)
-{
-    setMinimumValue<int, QtIntPropertyManagerPrivate, QtIntPropertyManager, int, QtIntPropertyManagerPrivate::Data>(this, d_ptr,
-                &QtIntPropertyManager::propertyChanged,
-                &QtIntPropertyManager::valueChanged,
-                &QtIntPropertyManager::rangeChanged,
-                property, minVal);
-}
-
-/**
-    Sets the maximum value for the given \a property to \a maxVal.
-
-    When setting maximum value, the minimum and current values are
-    adjusted if necessary (ensuring that the range remains valid and
-    that the current value is within the range).
-
-    \sa maximum(), setRange(), rangeChanged()
-*/
-void QtIntPropertyManager::setMaximum(QtProperty *property, int maxVal)
-{
-    setMaximumValue<int, QtIntPropertyManagerPrivate, QtIntPropertyManager, int, QtIntPropertyManagerPrivate::Data>(this, d_ptr,
-                &QtIntPropertyManager::propertyChanged,
-                &QtIntPropertyManager::valueChanged,
-                &QtIntPropertyManager::rangeChanged,
-                property, maxVal);
-}
-
-/**
-    \fn void QtIntPropertyManager::setRange(QtProperty *property, int minimum, int maximum)
-
-    Sets the range of valid values.
-
-    This is a convenience function defining the range of valid values
-    in one go; setting the \a minimum and \a maximum values for the
-    given \a property with a single function call.
-
-    When setting a new range, the current value is adjusted if
-    necessary (ensuring that the value remains within range).
-
-    \sa setMinimum(), setMaximum(), rangeChanged()
-*/
-void QtIntPropertyManager::setRange(QtProperty *property, int minVal, int maxVal)
-{
-    void (QtIntPropertyManagerPrivate::*setSubPropertyRange)(QtProperty *, int, int, int) = 0;
-    setBorderValues<int, QtIntPropertyManagerPrivate, QtIntPropertyManager, int>(this, d_ptr,
-                &QtIntPropertyManager::propertyChanged,
-                &QtIntPropertyManager::valueChanged,
-                &QtIntPropertyManager::rangeChanged,
-                property, minVal, maxVal, setSubPropertyRange);
-}
-
-/**
-    Sets the step value for the given \a property to \a step.
-
-    The step is typically used to increment or decrement a property value while pressing an arrow key.
-
-    \sa singleStep()
-*/
-void QtIntPropertyManager::setSingleStep(QtProperty *property, int step)
-{
-    const QtIntPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtIntPropertyManagerPrivate::Data data = it.value();
-
-    if (step < 0)
-        step = 0;
-
-    if (data.singleStep == step)
-        return;
-
-    data.singleStep = step;
-
-    it.value() = data;
-
-    emit singleStepChanged(property, data.singleStep);
-}
-
-/**
-    \reimp
-*/
-void QtIntPropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QtIntPropertyManagerPrivate::Data();
-}
-
-/**
-    \reimp
-*/
-void QtIntPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    d_ptr->m_values.remove(property);
-}
-
-// QtDoublePropertyManager
-
-class QtDoublePropertyManagerPrivate
-{
-    QtDoublePropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtDoublePropertyManager)
-public:
-
-    struct Data
-    {
-        Data() : val(0), minVal(-INT_MAX), maxVal(INT_MAX), singleStep(1), decimals(2) {}
-        double val;
-        double minVal;
-        double maxVal;
-        double singleStep;
-        int decimals;
-        double minimumValue() const { return minVal; }
-        double maximumValue() const { return maxVal; }
-        void setMinimumValue(double newMinVal) { setSimpleMinimumData(this, newMinVal); }
-        void setMaximumValue(double newMaxVal) { setSimpleMaximumData(this, newMaxVal); }
-    };
-
-    typedef QMap<const QtProperty *, Data> PropertyValueMap;
-    PropertyValueMap m_values;
-};
-
-/**
-    \class QtDoublePropertyManager
-
-    \brief The QtDoublePropertyManager provides and manages double properties.
-
-    A double property has a current value, and a range specifying the
-    valid values. The range is defined by a minimum and a maximum
-    value.
-
-    The property's value and range can be retrieved using the value(),
-    minimum() and maximum() functions, and can be set using the
-    setValue(), setMinimum() and setMaximum() slots.
-    Alternatively, the range can be defined in one go using the
-    setRange() slot.
-
-    In addition, QtDoublePropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes, and the rangeChanged() signal which is emitted whenever
-    such a property changes its range of valid values.
-
-    \sa QtAbstractPropertyManager, QtDoubleSpinBoxFactory
-*/
-
-/**
-    \fn void QtDoublePropertyManager::valueChanged(QtProperty *property, double value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    \fn void QtDoublePropertyManager::rangeChanged(QtProperty *property, double minimum, double maximum)
-
-    This signal is emitted whenever a property created by this manager
-    changes its range of valid values, passing a pointer to the
-    \a property and the new \a minimum and \a maximum values
-
-    \sa setRange()
-*/
-
-/**
-    \fn void QtDoublePropertyManager::decimalsChanged(QtProperty *property, int prec)
-
-    This signal is emitted whenever a property created by this manager
-    changes its precision of value, passing a pointer to the
-    \a property and the new \a prec value
-
-    \sa setDecimals()
-*/
-
-/**
-    \fn void QtDoublePropertyManager::singleStepChanged(QtProperty *property, double step)
-
-    This signal is emitted whenever a property created by this manager
-    changes its single step property, passing a pointer to the
-    \a property and the new \a step value
-
-    \sa setSingleStep()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtDoublePropertyManager::QtDoublePropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtDoublePropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-}
-
-/**
-    Destroys  this manager, and all the properties it has created.
-*/
-QtDoublePropertyManager::~QtDoublePropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given property is not managed by this manager, this
-    function returns 0.
-
-    \sa setValue()
-*/
-double QtDoublePropertyManager::value(const QtProperty *property) const
-{
-    return getValue<double>(d_ptr->m_values, property, 0.0);
-}
-
-/**
-    Returns the given \a property's minimum value.
-
-    \sa maximum(), setRange()
-*/
-double QtDoublePropertyManager::minimum(const QtProperty *property) const
-{
-    return getMinimum<double>(d_ptr->m_values, property, 0.0);
-}
-
-/**
-    Returns the given \a property's maximum value.
-
-    \sa minimum(), setRange()
-*/
-double QtDoublePropertyManager::maximum(const QtProperty *property) const
-{
-    return getMaximum<double>(d_ptr->m_values, property, 0.0);
-}
-
-/**
-    Returns the given \a property's step value.
-
-    The step is typically used to increment or decrement a property value while pressing an arrow key.
-
-    \sa setSingleStep()
-*/
-double QtDoublePropertyManager::singleStep(const QtProperty *property) const
-{
-    return getData<double>(d_ptr->m_values, &QtDoublePropertyManagerPrivate::Data::singleStep, property, 0);
-}
-
-/**
-    Returns the given \a property's precision, in decimals.
-
-    \sa setDecimals()
-*/
-int QtDoublePropertyManager::decimals(const QtProperty *property) const
-{
-    return getData<int>(d_ptr->m_values, &QtDoublePropertyManagerPrivate::Data::decimals, property, 0);
-}
-
-/**
-    \reimp
-*/
-QString QtDoublePropertyManager::valueText(const QtProperty *property) const
-{
-    const QtDoublePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    double absVal = fabs(it.value().val);
-    char format = absVal > 1e5 || (absVal != 0 && absVal < 1e-5) ? 'e' : 'f';
-    return QString::number(it.value().val,format , it.value().decimals);
-}
-
-/**
-    \fn void QtDoublePropertyManager::setValue(QtProperty *property, double value)
-
-    Sets the value of the given \a property to \a value.
-
-    If the specified \a value is not valid according to the given
-    \a property's range, the \a value is adjusted to the nearest valid value
-    within the range.
-
-    \sa value(), setRange(), valueChanged()
-*/
-void QtDoublePropertyManager::setValue(QtProperty *property, double val)
-{
-    void (QtDoublePropertyManagerPrivate::*setSubPropertyValue)(QtProperty *, double) = 0;
-    setValueInRange<double, QtDoublePropertyManagerPrivate, QtDoublePropertyManager, double>(this, d_ptr,
-                &QtDoublePropertyManager::propertyChanged,
-                &QtDoublePropertyManager::valueChanged,
-                property, val, setSubPropertyValue);
-}
-
-/**
-    Sets the step value for the given \a property to \a step.
-
-    The step is typically used to increment or decrement a property value while pressing an arrow key.
-
-    \sa singleStep()
-*/
-void QtDoublePropertyManager::setSingleStep(QtProperty *property, double step)
-{
-    const QtDoublePropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtDoublePropertyManagerPrivate::Data data = it.value();
-
-    if (step < 0)
-        step = 0;
-
-    if (data.singleStep == step)
-        return;
-
-    data.singleStep = step;
-
-    it.value() = data;
-
-    emit singleStepChanged(property, data.singleStep);
-}
-
-/**
-    \fn void QtDoublePropertyManager::setDecimals(QtProperty *property, int prec)
-
-    Sets the precision of the given \a property to \a prec.
-
-    The valid decimal range is 0-13. The default is 2.
-
-    \sa decimals()
-*/
-void QtDoublePropertyManager::setDecimals(QtProperty *property, int prec)
-{
-    const QtDoublePropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtDoublePropertyManagerPrivate::Data data = it.value();
-
-    if (prec > 13)
-        prec = 13;
-    else if (prec < 0)
-        prec = 0;
-
-    if (data.decimals == prec)
-        return;
-
-    data.decimals = prec;
-
-    it.value() = data;
-
-    emit decimalsChanged(property, data.decimals);
-}
-
-/**
-    Sets the minimum value for the given \a property to \a minVal.
-
-    When setting the minimum value, the maximum and current values are
-    adjusted if necessary (ensuring that the range remains valid and
-    that the current value is within in the range).
-
-    \sa minimum(), setRange(), rangeChanged()
-*/
-void QtDoublePropertyManager::setMinimum(QtProperty *property, double minVal)
-{
-    setMinimumValue<double, QtDoublePropertyManagerPrivate, QtDoublePropertyManager, double, QtDoublePropertyManagerPrivate::Data>(this, d_ptr,
-                &QtDoublePropertyManager::propertyChanged,
-                &QtDoublePropertyManager::valueChanged,
-                &QtDoublePropertyManager::rangeChanged,
-                property, minVal);
-}
-
-/**
-    Sets the maximum value for the given \a property to \a maxVal.
-
-    When setting the maximum value, the minimum and current values are
-    adjusted if necessary (ensuring that the range remains valid and
-    that the current value is within in the range).
-
-    \sa maximum(), setRange(), rangeChanged()
-*/
-void QtDoublePropertyManager::setMaximum(QtProperty *property, double maxVal)
-{
-    setMaximumValue<double, QtDoublePropertyManagerPrivate, QtDoublePropertyManager, double, QtDoublePropertyManagerPrivate::Data>(this, d_ptr,
-                &QtDoublePropertyManager::propertyChanged,
-                &QtDoublePropertyManager::valueChanged,
-                &QtDoublePropertyManager::rangeChanged,
-                property, maxVal);
-}
-
-/**
-    \fn void QtDoublePropertyManager::setRange(QtProperty *property, double minimum, double maximum)
-
-    Sets the range of valid values.
-
-    This is a convenience function defining the range of valid values
-    in one go; setting the \a minimum and \a maximum values for the
-    given \a property with a single function call.
-
-    When setting a new range, the current value is adjusted if
-    necessary (ensuring that the value remains within range).
-
-    \sa setMinimum(), setMaximum(), rangeChanged()
-*/
-void QtDoublePropertyManager::setRange(QtProperty *property, double minVal, double maxVal)
-{
-    void (QtDoublePropertyManagerPrivate::*setSubPropertyRange)(QtProperty *, double, double, double) = 0;
-    setBorderValues<double, QtDoublePropertyManagerPrivate, QtDoublePropertyManager, double>(this, d_ptr,
-                &QtDoublePropertyManager::propertyChanged,
-                &QtDoublePropertyManager::valueChanged,
-                &QtDoublePropertyManager::rangeChanged,
-                property, minVal, maxVal, setSubPropertyRange);
-}
-
-/**
-    \reimp
-*/
-void QtDoublePropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QtDoublePropertyManagerPrivate::Data();
-}
-
-/**
-    \reimp
-*/
-void QtDoublePropertyManager::uninitializeProperty(QtProperty *property)
-{
-    d_ptr->m_values.remove(property);
-}
-
-// QtStringPropertyManager
-
-class QtStringPropertyManagerPrivate
-{
-    QtStringPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtStringPropertyManager)
-public:
-
-    struct Data
-    {
-        Data() : regExp(QString(QLatin1Char('*')),  Qt::CaseSensitive, QRegExp::Wildcard)
-        {
-        }
-        QString val;
-        QRegExp regExp;
-    };
-
-    typedef QMap<const QtProperty *, Data> PropertyValueMap;
-    QMap<const QtProperty *, Data> m_values;
-};
-
-/**
-    \class QtStringPropertyManager
-
-    \brief The QtStringPropertyManager provides and manages QString properties.
-
-    A string property's value can be retrieved using the value()
-    function, and set using the setValue() slot.
-
-    The current value can be checked against a regular expression. To
-    set the regular expression use the setRegExp() slot, use the
-    regExp() function to retrieve the currently set expression.
-
-    In addition, QtStringPropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes, and the regExpChanged() signal which is emitted whenever
-    such a property changes its currently set regular expression.
-
-    \sa QtAbstractPropertyManager, QtLineEditFactory
-*/
-
-/**
-    \fn void QtStringPropertyManager::valueChanged(QtProperty *property, const QString &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the
-    new \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    \fn void QtStringPropertyManager::regExpChanged(QtProperty *property, const QRegExp &regExp)
-
-    This signal is emitted whenever a property created by this manager
-    changes its currenlty set regular expression, passing a pointer to
-    the \a property and the new \a regExp as parameters.
-
-    \sa setRegExp()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtStringPropertyManager::QtStringPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtStringPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtStringPropertyManager::~QtStringPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given property is not managed by this manager, this
-    function returns an empty string.
-
-    \sa setValue()
-*/
-QString QtStringPropertyManager::value(const QtProperty *property) const
-{
-    return getValue<QString>(d_ptr->m_values, property);
-}
-
-/**
-    Returns the given \a property's currently set regular expression.
-
-    If the given \a property is not managed by this manager, this
-    function returns an empty expression.
-
-    \sa setRegExp()
-*/
-QRegExp QtStringPropertyManager::regExp(const QtProperty *property) const
-{
-    return getData<QRegExp>(d_ptr->m_values, &QtStringPropertyManagerPrivate::Data::regExp, property, QRegExp());
-}
-
-/**
-    \reimp
-*/
-QString QtStringPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtStringPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    return it.value().val;
-}
-
-/**
-    \fn void QtStringPropertyManager::setValue(QtProperty *property, const QString &value)
-
-    Sets the value of the given \a property to \a value.
-
-    If the specified \a value doesn't match the given \a property's
-    regular expression, this function does nothing.
-
-    \sa value(), setRegExp(), valueChanged()
-*/
-void QtStringPropertyManager::setValue(QtProperty *property, const QString &val)
-{
-    const QtStringPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtStringPropertyManagerPrivate::Data data = it.value();
-
-    if (data.val == val)
-        return;
-
-    if (data.regExp.isValid() && !data.regExp.exactMatch(val))
-        return;
-
-    data.val = val;
-
-    it.value() = data;
-
-    emit propertyChanged(property);
-    emit valueChanged(property, data.val);
-}
-
-/**
-    Sets the regular expression of the given \a property to \a regExp.
-
-    \sa regExp(), setValue(), regExpChanged()
-*/
-void QtStringPropertyManager::setRegExp(QtProperty *property, const QRegExp &regExp)
-{
-    const QtStringPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtStringPropertyManagerPrivate::Data data = it.value() ;
-
-    if (data.regExp == regExp)
-        return;
-
-    data.regExp = regExp;
-
-    it.value() = data;
-
-    emit regExpChanged(property, data.regExp);
-}
-
-/**
-    \reimp
-*/
-void QtStringPropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QtStringPropertyManagerPrivate::Data();
-}
-
-/**
-    \reimp
-*/
-void QtStringPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    d_ptr->m_values.remove(property);
-}
-
-// QtBoolPropertyManager
-
-class QtBoolPropertyManagerPrivate
-{
-    QtBoolPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtBoolPropertyManager)
-public:
-
-    QMap<const QtProperty *, bool> m_values;
-};
-
-/**
-    \class QtBoolPropertyManager
-
-    \brief The QtBoolPropertyManager class provides and manages boolean properties.
-
-    The property's value can be retrieved using the value() function,
-    and set using the setValue() slot.
-
-    In addition, QtBoolPropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes.
-
-    \sa QtAbstractPropertyManager, QtCheckBoxFactory
-*/
-
-/**
-    \fn void QtBoolPropertyManager::valueChanged(QtProperty *property, bool value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the
-    new \a value as parameters.
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtBoolPropertyManager::QtBoolPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtBoolPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtBoolPropertyManager::~QtBoolPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by \e this manager, this
-    function returns false.
-
-    \sa setValue()
-*/
-bool QtBoolPropertyManager::value(const QtProperty *property) const
-{
-    return d_ptr->m_values.value(property, false);
-}
-
-/**
-    \reimp
-*/
-QString QtBoolPropertyManager::valueText(const QtProperty *property) const
-{
-    const QMap<const QtProperty *, bool>::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-
-    static const QString trueText = tr("True");
-    static const QString falseText = tr("False");
-    return it.value() ? trueText : falseText;
-}
-
-// Return an icon containing a check box indicator
-static QIcon drawCheckBox(bool value)
-{
-    QStyleOptionButton opt;
-    opt.state |= value ? QStyle::State_On : QStyle::State_Off;
-    opt.state |= QStyle::State_Enabled;
-    const QStyle *style = QApplication::style();
-    // Figure out size of an indicator and make sure it is not scaled down in a list view item
-    // by making the pixmap as big as a list view icon and centering the indicator in it.
-    // (if it is smaller, it can't be helped)
-    const int indicatorWidth = style->pixelMetric(QStyle::PM_IndicatorWidth, &opt);
-    const int indicatorHeight = style->pixelMetric(QStyle::PM_IndicatorHeight, &opt);
-    const int listViewIconSize = indicatorWidth;
-    const int pixmapWidth = indicatorWidth;
-    const int pixmapHeight = qMax(indicatorHeight, listViewIconSize);
-
-    opt.rect = QRect(0, 0, indicatorWidth, indicatorHeight);
-    QPixmap pixmap = QPixmap(pixmapWidth, pixmapHeight);
-    pixmap.fill(Qt::transparent);
-    {
-        // Center?
-        const int xoff = (pixmapWidth  > indicatorWidth)  ? (pixmapWidth  - indicatorWidth)  / 2 : 0;
-        const int yoff = (pixmapHeight > indicatorHeight) ? (pixmapHeight - indicatorHeight) / 2 : 0;
-        QPainter painter(&pixmap);
-        painter.translate(xoff, yoff);
-        style->drawPrimitive(QStyle::PE_IndicatorCheckBox, &opt, &painter);
-    }
-    return QIcon(pixmap);
-}
-
-/**
-    \reimp
-*/
-QIcon QtBoolPropertyManager::valueIcon(const QtProperty *property) const
-{
-    const QMap<const QtProperty *, bool>::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QIcon();
-
-    static const QIcon checkedIcon = drawCheckBox(true);
-    static const QIcon uncheckedIcon = drawCheckBox(false);
-    return it.value() ? checkedIcon : uncheckedIcon;
-}
-
-/**
-    \fn void QtBoolPropertyManager::setValue(QtProperty *property, bool value)
-
-    Sets the value of the given \a property to \a value.
-
-    \sa value()
-*/
-void QtBoolPropertyManager::setValue(QtProperty *property, bool val)
-{
-    setSimpleValue<bool, bool, QtBoolPropertyManager>(d_ptr->m_values, this,
-                &QtBoolPropertyManager::propertyChanged,
-                &QtBoolPropertyManager::valueChanged,
-                property, val);
-}
-
-/**
-    \reimp
-*/
-void QtBoolPropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = false;
-}
-
-/**
-    \reimp
-*/
-void QtBoolPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    d_ptr->m_values.remove(property);
-}
-
-// QtDatePropertyManager
-
-class QtDatePropertyManagerPrivate
-{
-    QtDatePropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtDatePropertyManager)
-public:
-
-    struct Data
-    {
-        Data() : val(QDate::currentDate()), minVal(QDate(1752, 9, 14)),
-                maxVal(QDate(7999, 12, 31)) {}
-        QDate val;
-        QDate minVal;
-        QDate maxVal;
-        QDate minimumValue() const { return minVal; }
-        QDate maximumValue() const { return maxVal; }
-        void setMinimumValue(const QDate &newMinVal) { setSimpleMinimumData(this, newMinVal); }
-        void setMaximumValue(const QDate &newMaxVal) { setSimpleMaximumData(this, newMaxVal); }
-    };
-
-    QString m_format;
-
-    typedef QMap<const QtProperty *, Data> PropertyValueMap;
-    QMap<const QtProperty *, Data> m_values;
-};
-
-/**
-    \class QtDatePropertyManager
-
-    \brief The QtDatePropertyManager provides and manages QDate properties.
-
-    A date property has a current value, and a range specifying the
-    valid dates. The range is defined by a minimum and a maximum
-    value.
-
-    The property's values can be retrieved using the minimum(),
-    maximum() and value() functions, and can be set using the
-    setMinimum(), setMaximum() and setValue() slots. Alternatively,
-    the range can be defined in one go using the setRange() slot.
-
-    In addition, QtDatePropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes, and the rangeChanged() signal which is emitted whenever
-    such a property changes its range of valid dates.
-
-    \sa QtAbstractPropertyManager, QtDateEditFactory, QtDateTimePropertyManager
-*/
-
-/**
-    \fn void QtDatePropertyManager::valueChanged(QtProperty *property, const QDate &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    \fn void QtDatePropertyManager::rangeChanged(QtProperty *property, const QDate &minimum, const QDate &maximum)
-
-    This signal is emitted whenever a property created by this manager
-    changes its range of valid dates, passing a pointer to the \a
-    property and the new \a minimum and \a maximum dates.
-
-    \sa setRange()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtDatePropertyManager::QtDatePropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtDatePropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    QLocale loc;
-    d_ptr->m_format = loc.dateFormat(QLocale::ShortFormat);
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtDatePropertyManager::~QtDatePropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by \e this manager, this
-    function returns an invalid date.
-
-    \sa setValue()
-*/
-QDate QtDatePropertyManager::value(const QtProperty *property) const
-{
-    return getValue<QDate>(d_ptr->m_values, property);
-}
-
-/**
-    Returns the given \a  property's  minimum date.
-
-    \sa maximum(), setRange()
-*/
-QDate QtDatePropertyManager::minimum(const QtProperty *property) const
-{
-    return getMinimum<QDate>(d_ptr->m_values, property);
-}
-
-/**
-    Returns the given \a property's maximum date.
-
-    \sa minimum(), setRange()
-*/
-QDate QtDatePropertyManager::maximum(const QtProperty *property) const
-{
-    return getMaximum<QDate>(d_ptr->m_values, property);
-}
-
-/**
-    \reimp
-*/
-QString QtDatePropertyManager::valueText(const QtProperty *property) const
-{
-    const QtDatePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    return it.value().val.toString(d_ptr->m_format);
-}
-
-/**
-    \fn void QtDatePropertyManager::setValue(QtProperty *property, const QDate &value)
-
-    Sets the value of the given \a property to \a value.
-
-    If the specified \a value is not a valid date according to the
-    given \a property's range, the value is adjusted to the nearest
-    valid value within the range.
-
-    \sa value(), setRange(), valueChanged()
-*/
-void QtDatePropertyManager::setValue(QtProperty *property, const QDate &val)
-{
-    void (QtDatePropertyManagerPrivate::*setSubPropertyValue)(QtProperty *, const QDate &) = 0;
-    setValueInRange<const QDate &, QtDatePropertyManagerPrivate, QtDatePropertyManager, const QDate>(this, d_ptr,
-                &QtDatePropertyManager::propertyChanged,
-                &QtDatePropertyManager::valueChanged,
-                property, val, setSubPropertyValue);
-}
-
-/**
-    Sets the minimum value for the given \a property to \a minVal.
-
-    When setting the minimum value, the maximum and current values are
-    adjusted if necessary (ensuring that the range remains valid and
-    that the current value is within in the range).
-
-    \sa minimum(), setRange()
-*/
-void QtDatePropertyManager::setMinimum(QtProperty *property, const QDate &minVal)
-{
-    setMinimumValue<const QDate &, QtDatePropertyManagerPrivate, QtDatePropertyManager, QDate, QtDatePropertyManagerPrivate::Data>(this, d_ptr,
-                &QtDatePropertyManager::propertyChanged,
-                &QtDatePropertyManager::valueChanged,
-                &QtDatePropertyManager::rangeChanged,
-                property, minVal);
-}
-
-/**
-    Sets the maximum value for the given \a property to \a maxVal.
-
-    When setting the maximum value, the minimum and current
-    values are adjusted if necessary (ensuring that the range remains
-    valid and that the current value is within in the range).
-
-    \sa maximum(), setRange()
-*/
-void QtDatePropertyManager::setMaximum(QtProperty *property, const QDate &maxVal)
-{
-    setMaximumValue<const QDate &, QtDatePropertyManagerPrivate, QtDatePropertyManager, QDate, QtDatePropertyManagerPrivate::Data>(this, d_ptr,
-                &QtDatePropertyManager::propertyChanged,
-                &QtDatePropertyManager::valueChanged,
-                &QtDatePropertyManager::rangeChanged,
-                property, maxVal);
-}
-
-/**
-    \fn void QtDatePropertyManager::setRange(QtProperty *property, const QDate &minimum, const QDate &maximum)
-
-    Sets the range of valid dates.
-
-    This is a convenience function defining the range of valid dates
-    in one go; setting the \a minimum and \a maximum values for the
-    given \a property with a single function call.
-
-    When setting a new date range, the current value is adjusted if
-    necessary (ensuring that the value remains in date range).
-
-    \sa setMinimum(), setMaximum(), rangeChanged()
-*/
-void QtDatePropertyManager::setRange(QtProperty *property, const QDate &minVal, const QDate &maxVal)
-{
-    void (QtDatePropertyManagerPrivate::*setSubPropertyRange)(QtProperty *, const QDate &,
-          const QDate &, const QDate &) = 0;
-    setBorderValues<const QDate &, QtDatePropertyManagerPrivate, QtDatePropertyManager, QDate>(this, d_ptr,
-                &QtDatePropertyManager::propertyChanged,
-                &QtDatePropertyManager::valueChanged,
-                &QtDatePropertyManager::rangeChanged,
-                property, minVal, maxVal, setSubPropertyRange);
-}
-
-/**
-    \reimp
-*/
-void QtDatePropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QtDatePropertyManagerPrivate::Data();
-}
-
-/**
-    \reimp
-*/
-void QtDatePropertyManager::uninitializeProperty(QtProperty *property)
-{
-    d_ptr->m_values.remove(property);
-}
-
-// QtTimePropertyManager
-
-class QtTimePropertyManagerPrivate
-{
-    QtTimePropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtTimePropertyManager)
-public:
-
-    QString m_format;
-
-    typedef QMap<const QtProperty *, QTime> PropertyValueMap;
-    PropertyValueMap m_values;
-};
-
-/**
-    \class QtTimePropertyManager
-
-    \brief The QtTimePropertyManager provides and manages QTime properties.
-
-    A time property's value can be retrieved using the value()
-    function, and set using the setValue() slot.
-
-    In addition, QtTimePropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes.
-
-    \sa QtAbstractPropertyManager, QtTimeEditFactory
-*/
-
-/**
-    \fn void QtTimePropertyManager::valueChanged(QtProperty *property, const QTime &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the
-    new \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtTimePropertyManager::QtTimePropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtTimePropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    QLocale loc;
-    d_ptr->m_format = loc.timeFormat(QLocale::ShortFormat);
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtTimePropertyManager::~QtTimePropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given property is not managed by this manager, this
-    function returns an invalid time object.
-
-    \sa setValue()
-*/
-QTime QtTimePropertyManager::value(const QtProperty *property) const
-{
-    return d_ptr->m_values.value(property, QTime());
-}
-
-/**
-    \reimp
-*/
-QString QtTimePropertyManager::valueText(const QtProperty *property) const
-{
-   const QtTimePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    return it.value().toString(d_ptr->m_format);
-}
-
-/**
-    \fn void QtTimePropertyManager::setValue(QtProperty *property, const QTime &value)
-
-    Sets the value of the given \a property to \a value.
-
-    \sa value(), valueChanged()
-*/
-void QtTimePropertyManager::setValue(QtProperty *property, const QTime &val)
-{
-    setSimpleValue<const QTime &, QTime, QtTimePropertyManager>(d_ptr->m_values, this,
-                &QtTimePropertyManager::propertyChanged,
-                &QtTimePropertyManager::valueChanged,
-                property, val);
-}
-
-/**
-    \reimp
-*/
-void QtTimePropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QTime::currentTime();
-}
-
-/**
-    \reimp
-*/
-void QtTimePropertyManager::uninitializeProperty(QtProperty *property)
-{
-    d_ptr->m_values.remove(property);
-}
-
-// QtDateTimePropertyManager
-
-class QtDateTimePropertyManagerPrivate
-{
-    QtDateTimePropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtDateTimePropertyManager)
-public:
-
-    QString m_format;
-
-    typedef QMap<const QtProperty *, QDateTime> PropertyValueMap;
-    PropertyValueMap m_values;
-};
-
-/** \class QtDateTimePropertyManager
-
-    \brief The QtDateTimePropertyManager provides and manages QDateTime properties.
-
-    A date and time property has a current value which can be
-    retrieved using the value() function, and set using the setValue()
-    slot. In addition, QtDateTimePropertyManager provides the
-    valueChanged() signal which is emitted whenever a property created
-    by this manager changes.
-
-    \sa QtAbstractPropertyManager, QtDateTimeEditFactory, QtDatePropertyManager
-*/
-
-/**
-    \fn void QtDateTimePropertyManager::valueChanged(QtProperty *property, const QDateTime &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtDateTimePropertyManager::QtDateTimePropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtDateTimePropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    QLocale loc;
-    d_ptr->m_format = loc.dateFormat(QLocale::ShortFormat);
-    d_ptr->m_format += QLatin1Char(' ');
-    d_ptr->m_format += loc.timeFormat(QLocale::ShortFormat);
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtDateTimePropertyManager::~QtDateTimePropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by this manager, this
-    function returns an invalid QDateTime object.
-
-    \sa setValue()
-*/
-QDateTime QtDateTimePropertyManager::value(const QtProperty *property) const
-{
-    return d_ptr->m_values.value(property, QDateTime());
-}
-
-/**
-    \reimp
-*/
-QString QtDateTimePropertyManager::valueText(const QtProperty *property) const
-{
-   const QtDateTimePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    return it.value().toString(d_ptr->m_format);
-}
-
-/**
-    \fn void QtDateTimePropertyManager::setValue(QtProperty *property, const QDateTime &value)
-
-    Sets the value of the given \a property to \a value.
-
-    \sa value(), valueChanged()
-*/
-void QtDateTimePropertyManager::setValue(QtProperty *property, const QDateTime &val)
-{
-    setSimpleValue<const QDateTime &, QDateTime, QtDateTimePropertyManager>(d_ptr->m_values, this,
-                &QtDateTimePropertyManager::propertyChanged,
-                &QtDateTimePropertyManager::valueChanged,
-                property, val);
-}
-
-/**
-    \reimp
-*/
-void QtDateTimePropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QDateTime::currentDateTime();
-}
-
-/**
-    \reimp
-*/
-void QtDateTimePropertyManager::uninitializeProperty(QtProperty *property)
-{
-    d_ptr->m_values.remove(property);
-}
-
-// QtKeySequencePropertyManager
-
-class QtKeySequencePropertyManagerPrivate
-{
-    QtKeySequencePropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtKeySequencePropertyManager)
-public:
-
-    QString m_format;
-
-    typedef QMap<const QtProperty *, QKeySequence> PropertyValueMap;
-    PropertyValueMap m_values;
-};
-
-/** \class QtKeySequencePropertyManager
-
-    \brief The QtKeySequencePropertyManager provides and manages QKeySequence properties.
-
-    A key sequence's value can be retrieved using the value()
-    function, and set using the setValue() slot.
-
-    In addition, QtKeySequencePropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes.
-
-    \sa QtAbstractPropertyManager
-*/
-
-/**
-    \fn void QtKeySequencePropertyManager::valueChanged(QtProperty *property, const QKeySequence &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtKeySequencePropertyManager::QtKeySequencePropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtKeySequencePropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtKeySequencePropertyManager::~QtKeySequencePropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by this manager, this
-    function returns an empty QKeySequence object.
-
-    \sa setValue()
-*/
-QKeySequence QtKeySequencePropertyManager::value(const QtProperty *property) const
-{
-    return d_ptr->m_values.value(property, QKeySequence());
-}
-
-/**
-    \reimp
-*/
-QString QtKeySequencePropertyManager::valueText(const QtProperty *property) const
-{
-    const QtKeySequencePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    return it.value().toString(QKeySequence::NativeText);
-}
-
-/**
-    \fn void QtKeySequencePropertyManager::setValue(QtProperty *property, const QKeySequence &value)
-
-    Sets the value of the given \a property to \a value.
-
-    \sa value(), valueChanged()
-*/
-void QtKeySequencePropertyManager::setValue(QtProperty *property, const QKeySequence &val)
-{
-    setSimpleValue<const QKeySequence &, QKeySequence, QtKeySequencePropertyManager>(d_ptr->m_values, this,
-                &QtKeySequencePropertyManager::propertyChanged,
-                &QtKeySequencePropertyManager::valueChanged,
-                property, val);
-}
-
-/**
-    \reimp
-*/
-void QtKeySequencePropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QKeySequence();
-}
-
-/**
-    \reimp
-*/
-void QtKeySequencePropertyManager::uninitializeProperty(QtProperty *property)
-{
-    d_ptr->m_values.remove(property);
-}
-
-// QtCharPropertyManager
-
-class QtCharPropertyManagerPrivate
-{
-    QtCharPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtCharPropertyManager)
-public:
-
-    typedef QMap<const QtProperty *, QChar> PropertyValueMap;
-    PropertyValueMap m_values;
-};
-
-/** \class QtCharPropertyManager
-
-    \brief The QtCharPropertyManager provides and manages QChar properties.
-
-    A char's value can be retrieved using the value()
-    function, and set using the setValue() slot.
-
-    In addition, QtCharPropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes.
-
-    \sa QtAbstractPropertyManager
-*/
-
-/**
-    \fn void QtCharPropertyManager::valueChanged(QtProperty *property, const QChar &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtCharPropertyManager::QtCharPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtCharPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtCharPropertyManager::~QtCharPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by this manager, this
-    function returns an null QChar object.
-
-    \sa setValue()
-*/
-QChar QtCharPropertyManager::value(const QtProperty *property) const
-{
-    return d_ptr->m_values.value(property, QChar());
-}
-
-/**
-    \reimp
-*/
-QString QtCharPropertyManager::valueText(const QtProperty *property) const
-{
-   const QtCharPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    const QChar c = it.value();
-    return c.isNull() ? QString() : QString(c);
-}
-
-/**
-    \fn void QtCharPropertyManager::setValue(QtProperty *property, const QChar &value)
-
-    Sets the value of the given \a property to \a value.
-
-    \sa value(), valueChanged()
-*/
-void QtCharPropertyManager::setValue(QtProperty *property, const QChar &val)
-{
-    setSimpleValue<const QChar &, QChar, QtCharPropertyManager>(d_ptr->m_values, this,
-                &QtCharPropertyManager::propertyChanged,
-                &QtCharPropertyManager::valueChanged,
-                property, val);
-}
-
-/**
-    \reimp
-*/
-void QtCharPropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QChar();
-}
-
-/**
-    \reimp
-*/
-void QtCharPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    d_ptr->m_values.remove(property);
-}
-
-// QtLocalePropertyManager
-
-class QtLocalePropertyManagerPrivate
-{
-    QtLocalePropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtLocalePropertyManager)
-public:
-
-    QtLocalePropertyManagerPrivate();
-
-    void slotEnumChanged(QtProperty *property, int value);
-    void slotPropertyDestroyed(QtProperty *property);
-
-    typedef QMap<const QtProperty *, QLocale> PropertyValueMap;
-    PropertyValueMap m_values;
-
-    QtEnumPropertyManager *m_enumPropertyManager;
-
-    QMap<const QtProperty *, QtProperty *> m_propertyToLanguage;
-    QMap<const QtProperty *, QtProperty *> m_propertyToCountry;
-
-    QMap<const QtProperty *, QtProperty *> m_languageToProperty;
-    QMap<const QtProperty *, QtProperty *> m_countryToProperty;
-};
-
-QtLocalePropertyManagerPrivate::QtLocalePropertyManagerPrivate()
-{
-}
-
-void QtLocalePropertyManagerPrivate::slotEnumChanged(QtProperty *property, int value)
-{
-    if (QtProperty *prop = m_languageToProperty.value(property, 0)) {
-        const QLocale loc = m_values[prop];
-        QLocale::Language newLanguage = loc.language();
-        QLocale::Country newCountry = loc.country();
-        metaEnumProvider()->indexToLocale(value, 0, &newLanguage, 0);
-        QLocale newLoc(newLanguage, newCountry);
-        q_ptr->setValue(prop, newLoc);
-    } else if (QtProperty *prop = m_countryToProperty.value(property, 0)) {
-        const QLocale loc = m_values[prop];
-        QLocale::Language newLanguage = loc.language();
-        QLocale::Country newCountry = loc.country();
-        metaEnumProvider()->indexToLocale(m_enumPropertyManager->value(m_propertyToLanguage.value(prop)), value, &newLanguage, &newCountry);
-        QLocale newLoc(newLanguage, newCountry);
-        q_ptr->setValue(prop, newLoc);
-    }
-}
-
-void QtLocalePropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
-{
-    if (QtProperty *subProp = m_languageToProperty.value(property, 0)) {
-        m_propertyToLanguage[subProp] = 0;
-        m_languageToProperty.remove(property);
-    } else if (QtProperty *subProp = m_countryToProperty.value(property, 0)) {
-        m_propertyToCountry[subProp] = 0;
-        m_countryToProperty.remove(property);
-    }
-}
-
-/**
-    \class QtLocalePropertyManager
-
-    \brief The QtLocalePropertyManager provides and manages QLocale properties.
-
-    A locale property has nested \e language and \e country
-    subproperties. The top-level property's value can be retrieved
-    using the value() function, and set using the setValue() slot.
-
-    The subproperties are created by QtEnumPropertyManager object.
-    These submanager can be retrieved using the subEnumPropertyManager()
-    function. In order to provide editing widgets for the subproperties
-    in a property browser widget, this manager must be associated with editor factory.
-
-    In addition, QtLocalePropertyManager provides the valueChanged()
-    signal which is emitted whenever a property created by this
-    manager changes.
-
-    \sa QtAbstractPropertyManager, QtEnumPropertyManager
-*/
-
-/**
-    \fn void QtLocalePropertyManager::valueChanged(QtProperty *property, const QLocale &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the
-    new \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtLocalePropertyManager::QtLocalePropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtLocalePropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_enumPropertyManager = new QtEnumPropertyManager(this);
-    connect(d_ptr->m_enumPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotEnumChanged(QtProperty *, int)));
-
-    connect(d_ptr->m_enumPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtLocalePropertyManager::~QtLocalePropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the manager that creates the nested \e language
-    and \e country subproperties.
-
-    In order to provide editing widgets for the mentioned subproperties
-    in a property browser widget, this manager must be associated with
-    an editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtEnumPropertyManager *QtLocalePropertyManager::subEnumPropertyManager() const
-{
-    return d_ptr->m_enumPropertyManager;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given property is not managed by this manager, this
-    function returns the default locale.
-
-    \sa setValue()
-*/
-QLocale QtLocalePropertyManager::value(const QtProperty *property) const
-{
-    return d_ptr->m_values.value(property, QLocale());
-}
-
-/**
-    \reimp
-*/
-QString QtLocalePropertyManager::valueText(const QtProperty *property) const
-{
-    const QtLocalePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-
-    QLocale loc = it.value();
-
-    int langIdx = 0;
-    int countryIdx = 0;
-    metaEnumProvider()->localeToIndex(loc.language(), loc.country(), &langIdx, &countryIdx);
-    QString str = tr("%1, %2")
-            .arg(metaEnumProvider()->languageEnumNames().at(langIdx))
-            .arg(metaEnumProvider()->countryEnumNames(loc.language()).at(countryIdx));
-    return str;
-}
-
-/**
-    \fn void QtLocalePropertyManager::setValue(QtProperty *property, const QLocale &value)
-
-    Sets the value of the given \a property to \a value. Nested
-    properties are updated automatically.
-
-    \sa value(), valueChanged()
-*/
-void QtLocalePropertyManager::setValue(QtProperty *property, const QLocale &val)
-{
-    const QtLocalePropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    const QLocale loc = it.value();
-    if (loc == val)
-        return;
-
-    it.value() = val;
-
-    int langIdx = 0;
-    int countryIdx = 0;
-    metaEnumProvider()->localeToIndex(val.language(), val.country(), &langIdx, &countryIdx);
-    if (loc.language() != val.language()) {
-        d_ptr->m_enumPropertyManager->setValue(d_ptr->m_propertyToLanguage.value(property), langIdx);
-        d_ptr->m_enumPropertyManager->setEnumNames(d_ptr->m_propertyToCountry.value(property),
-                    metaEnumProvider()->countryEnumNames(val.language()));
-    }
-    d_ptr->m_enumPropertyManager->setValue(d_ptr->m_propertyToCountry.value(property), countryIdx);
-
-    emit propertyChanged(property);
-    emit valueChanged(property, val);
-}
-
-/**
-    \reimp
-*/
-void QtLocalePropertyManager::initializeProperty(QtProperty *property)
-{
-    QLocale val;
-    d_ptr->m_values[property] = val;
-
-    int langIdx = 0;
-    int countryIdx = 0;
-    metaEnumProvider()->localeToIndex(val.language(), val.country(), &langIdx, &countryIdx);
-
-    QtProperty *languageProp = d_ptr->m_enumPropertyManager->addProperty();
-    languageProp->setPropertyName(tr("Language"));
-    d_ptr->m_enumPropertyManager->setEnumNames(languageProp, metaEnumProvider()->languageEnumNames());
-    d_ptr->m_enumPropertyManager->setValue(languageProp, langIdx);
-    d_ptr->m_propertyToLanguage[property] = languageProp;
-    d_ptr->m_languageToProperty[languageProp] = property;
-    property->addSubProperty(languageProp);
-
-    QtProperty *countryProp = d_ptr->m_enumPropertyManager->addProperty();
-    countryProp->setPropertyName(tr("Country"));
-    d_ptr->m_enumPropertyManager->setEnumNames(countryProp, metaEnumProvider()->countryEnumNames(val.language()));
-    d_ptr->m_enumPropertyManager->setValue(countryProp, countryIdx);
-    d_ptr->m_propertyToCountry[property] = countryProp;
-    d_ptr->m_countryToProperty[countryProp] = property;
-    property->addSubProperty(countryProp);
-}
-
-/**
-    \reimp
-*/
-void QtLocalePropertyManager::uninitializeProperty(QtProperty *property)
-{
-    QtProperty *languageProp = d_ptr->m_propertyToLanguage[property];
-    if (languageProp) {
-        d_ptr->m_languageToProperty.remove(languageProp);
-        delete languageProp;
-    }
-    d_ptr->m_propertyToLanguage.remove(property);
-
-    QtProperty *countryProp = d_ptr->m_propertyToCountry[property];
-    if (countryProp) {
-        d_ptr->m_countryToProperty.remove(countryProp);
-        delete countryProp;
-    }
-    d_ptr->m_propertyToCountry.remove(property);
-
-    d_ptr->m_values.remove(property);
-}
-
-// QtPointPropertyManager
-
-class QtPointPropertyManagerPrivate
-{
-    QtPointPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtPointPropertyManager)
-public:
-
-    void slotIntChanged(QtProperty *property, int value);
-    void slotPropertyDestroyed(QtProperty *property);
-
-    typedef QMap<const QtProperty *, QPoint> PropertyValueMap;
-    PropertyValueMap m_values;
-
-    QtIntPropertyManager *m_intPropertyManager;
-
-    QMap<const QtProperty *, QtProperty *> m_propertyToX;
-    QMap<const QtProperty *, QtProperty *> m_propertyToY;
-
-    QMap<const QtProperty *, QtProperty *> m_xToProperty;
-    QMap<const QtProperty *, QtProperty *> m_yToProperty;
-};
-
-void QtPointPropertyManagerPrivate::slotIntChanged(QtProperty *property, int value)
-{
-    if (QtProperty *xprop = m_xToProperty.value(property, 0)) {
-        QPoint p = m_values[xprop];
-        p.setX(value);
-        q_ptr->setValue(xprop, p);
-    } else if (QtProperty *yprop = m_yToProperty.value(property, 0)) {
-        QPoint p = m_values[yprop];
-        p.setY(value);
-        q_ptr->setValue(yprop, p);
-    }
-}
-
-void QtPointPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
-{
-    if (QtProperty *pointProp = m_xToProperty.value(property, 0)) {
-        m_propertyToX[pointProp] = 0;
-        m_xToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_yToProperty.value(property, 0)) {
-        m_propertyToY[pointProp] = 0;
-        m_yToProperty.remove(property);
-    }
-}
-
-/** \class QtPointPropertyManager
-
-    \brief The QtPointPropertyManager provides and manages QPoint properties.
-
-    A point property has nested \e x and \e y subproperties. The
-    top-level property's value can be retrieved using the value()
-    function, and set using the setValue() slot.
-
-    The subproperties are created by a QtIntPropertyManager object. This
-    manager can be retrieved using the subIntPropertyManager() function. In
-    order to provide editing widgets for the subproperties in a
-    property browser widget, this manager must be associated with an
-    editor factory.
-
-    In addition, QtPointPropertyManager provides the valueChanged() signal which
-    is emitted whenever a property created by this manager changes.
-
-    \sa QtAbstractPropertyManager, QtIntPropertyManager, QtPointFPropertyManager
-*/
-
-/**
-    \fn void QtPointPropertyManager::valueChanged(QtProperty *property, const QPoint &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the
-    new \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtPointPropertyManager::QtPointPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtPointPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_intPropertyManager = new QtIntPropertyManager(this);
-    connect(d_ptr->m_intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotIntChanged(QtProperty *, int)));
-    connect(d_ptr->m_intPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtPointPropertyManager::~QtPointPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the manager that creates the nested \e x and \e y
-    subproperties.
-
-    In order to provide editing widgets for the subproperties in a
-    property browser widget, this manager must be associated with an
-    editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtIntPropertyManager *QtPointPropertyManager::subIntPropertyManager() const
-{
-    return d_ptr->m_intPropertyManager;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by this manager, this
-    function returns a point with coordinates (0, 0).
-
-    \sa setValue()
-*/
-QPoint QtPointPropertyManager::value(const QtProperty *property) const
-{
-    return d_ptr->m_values.value(property, QPoint());
-}
-
-/**
-    \reimp
-*/
-QString QtPointPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtPointPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    const QPoint v = it.value();
-    return QString(tr("(%1, %2)").arg(QString::number(v.x()))
-                                 .arg(QString::number(v.y())));
-}
-
-/**
-    \fn void QtPointPropertyManager::setValue(QtProperty *property, const QPoint &value)
-
-    Sets the value of the given \a property to \a value. Nested
-    properties are updated automatically.
-
-    \sa value(), valueChanged()
-*/
-void QtPointPropertyManager::setValue(QtProperty *property, const QPoint &val)
-{
-    const QtPointPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    if (it.value() == val)
-        return;
-
-    it.value() = val;
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToX[property], val.x());
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToY[property], val.y());
-
-    emit propertyChanged(property);
-    emit valueChanged(property, val);
-}
-
-/**
-    \reimp
-*/
-void QtPointPropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QPoint(0, 0);
-
-    QtProperty *xProp = d_ptr->m_intPropertyManager->addProperty();
-    xProp->setPropertyName(tr("X"));
-    d_ptr->m_intPropertyManager->setValue(xProp, 0);
-    d_ptr->m_propertyToX[property] = xProp;
-    d_ptr->m_xToProperty[xProp] = property;
-    property->addSubProperty(xProp);
-
-    QtProperty *yProp = d_ptr->m_intPropertyManager->addProperty();
-    yProp->setPropertyName(tr("Y"));
-    d_ptr->m_intPropertyManager->setValue(yProp, 0);
-    d_ptr->m_propertyToY[property] = yProp;
-    d_ptr->m_yToProperty[yProp] = property;
-    property->addSubProperty(yProp);
-}
-
-/**
-    \reimp
-*/
-void QtPointPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    QtProperty *xProp = d_ptr->m_propertyToX[property];
-    if (xProp) {
-        d_ptr->m_xToProperty.remove(xProp);
-        delete xProp;
-    }
-    d_ptr->m_propertyToX.remove(property);
-
-    QtProperty *yProp = d_ptr->m_propertyToY[property];
-    if (yProp) {
-        d_ptr->m_yToProperty.remove(yProp);
-        delete yProp;
-    }
-    d_ptr->m_propertyToY.remove(property);
-
-    d_ptr->m_values.remove(property);
-}
-
-// QtPointFPropertyManager
-
-class QtPointFPropertyManagerPrivate
-{
-    QtPointFPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtPointFPropertyManager)
-public:
-
-    struct Data
-    {
-        Data() : decimals(2) {}
-        QPointF val;
-        int decimals;
-    };
-
-    void slotDoubleChanged(QtProperty *property, double value);
-    void slotPropertyDestroyed(QtProperty *property);
-
-    typedef QMap<const QtProperty *, Data> PropertyValueMap;
-    PropertyValueMap m_values;
-
-    QtDoublePropertyManager *m_doublePropertyManager;
-
-    QMap<const QtProperty *, QtProperty *> m_propertyToX;
-    QMap<const QtProperty *, QtProperty *> m_propertyToY;
-
-    QMap<const QtProperty *, QtProperty *> m_xToProperty;
-    QMap<const QtProperty *, QtProperty *> m_yToProperty;
-};
-
-void QtPointFPropertyManagerPrivate::slotDoubleChanged(QtProperty *property, double value)
-{
-    if (QtProperty *prop = m_xToProperty.value(property, 0)) {
-        QPointF p = m_values[prop].val;
-        p.setX(value);
-        q_ptr->setValue(prop, p);
-    } else if (QtProperty *prop = m_yToProperty.value(property, 0)) {
-        QPointF p = m_values[prop].val;
-        p.setY(value);
-        q_ptr->setValue(prop, p);
-    }
-}
-
-void QtPointFPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
-{
-    if (QtProperty *pointProp  = m_xToProperty.value(property, 0)) {
-        m_propertyToX[pointProp] = 0;
-        m_xToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_yToProperty.value(property, 0)) {
-        m_propertyToY[pointProp] = 0;
-        m_yToProperty.remove(property);
-    }
-}
-
-/** \class QtPointFPropertyManager
-
-    \brief The QtPointFPropertyManager provides and manages QPointF properties.
-
-    A point property has nested \e x and \e y subproperties. The
-    top-level property's value can be retrieved using the value()
-    function, and set using the setValue() slot.
-
-    The subproperties are created by a QtDoublePropertyManager object. This
-    manager can be retrieved using the subDoublePropertyManager() function. In
-    order to provide editing widgets for the subproperties in a
-    property browser widget, this manager must be associated with an
-    editor factory.
-
-    In addition, QtPointFPropertyManager provides the valueChanged() signal which
-    is emitted whenever a property created by this manager changes.
-
-    \sa QtAbstractPropertyManager, QtDoublePropertyManager, QtPointPropertyManager
-*/
-
-/**
-    \fn void QtPointFPropertyManager::valueChanged(QtProperty *property, const QPointF &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the
-    new \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    \fn void QtPointFPropertyManager::decimalsChanged(QtProperty *property, int prec)
-
-    This signal is emitted whenever a property created by this manager
-    changes its precision of value, passing a pointer to the
-    \a property and the new \a prec value
-
-    \sa setDecimals()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtPointFPropertyManager::QtPointFPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtPointFPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_doublePropertyManager = new QtDoublePropertyManager(this);
-    connect(d_ptr->m_doublePropertyManager, SIGNAL(valueChanged(QtProperty *, double)),
-                this, SLOT(slotDoubleChanged(QtProperty *, double)));
-    connect(d_ptr->m_doublePropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtPointFPropertyManager::~QtPointFPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the manager that creates the nested \e x and \e y
-    subproperties.
-
-    In order to provide editing widgets for the subproperties in a
-    property browser widget, this manager must be associated with an
-    editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtDoublePropertyManager *QtPointFPropertyManager::subDoublePropertyManager() const
-{
-    return d_ptr->m_doublePropertyManager;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by this manager, this
-    function returns a point with coordinates (0, 0).
-
-    \sa setValue()
-*/
-QPointF QtPointFPropertyManager::value(const QtProperty *property) const
-{
-    return getValue<QPointF>(d_ptr->m_values, property);
-}
-
-/**
-    Returns the given \a property's precision, in decimals.
-
-    \sa setDecimals()
-*/
-int QtPointFPropertyManager::decimals(const QtProperty *property) const
-{
-    return getData<int>(d_ptr->m_values, &QtPointFPropertyManagerPrivate::Data::decimals, property, 0);
-}
-
-/**
-    \reimp
-*/
-QString QtPointFPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtPointFPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    const QPointF v = it.value().val;
-    const int dec =  it.value().decimals;
-    return QString(tr("(%1, %2)").arg(QString::number(v.x(), 'f', dec))
-                                 .arg(QString::number(v.y(), 'f', dec)));
-}
-
-/**
-    \fn void QtPointFPropertyManager::setValue(QtProperty *property, const QPointF &value)
-
-    Sets the value of the given \a property to \a value. Nested
-    properties are updated automatically.
-
-    \sa value(), valueChanged()
-*/
-void QtPointFPropertyManager::setValue(QtProperty *property, const QPointF &val)
-{
-    const QtPointFPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    if (it.value().val == val)
-        return;
-
-    it.value().val = val;
-    d_ptr->m_doublePropertyManager->setValue(d_ptr->m_propertyToX[property], val.x());
-    d_ptr->m_doublePropertyManager->setValue(d_ptr->m_propertyToY[property], val.y());
-
-    emit propertyChanged(property);
-    emit valueChanged(property, val);
-}
-
-/**
-    \fn void QtPointFPropertyManager::setDecimals(QtProperty *property, int prec)
-
-    Sets the precision of the given \a property to \a prec.
-
-    The valid decimal range is 0-13. The default is 2.
-
-    \sa decimals()
-*/
-void QtPointFPropertyManager::setDecimals(QtProperty *property, int prec)
-{
-    const QtPointFPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtPointFPropertyManagerPrivate::Data data = it.value();
-
-    if (prec > 13)
-        prec = 13;
-    else if (prec < 0)
-        prec = 0;
-
-    if (data.decimals == prec)
-        return;
-
-    data.decimals = prec;
-    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToX[property], prec);
-    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToY[property], prec);
-
-    it.value() = data;
-
-    emit decimalsChanged(property, data.decimals);
-}
-
-/**
-    \reimp
-*/
-void QtPointFPropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QtPointFPropertyManagerPrivate::Data();
-
-    QtProperty *xProp = d_ptr->m_doublePropertyManager->addProperty();
-    xProp->setPropertyName(tr("X"));
-    d_ptr->m_doublePropertyManager->setDecimals(xProp, decimals(property));
-    d_ptr->m_doublePropertyManager->setValue(xProp, 0);
-    d_ptr->m_propertyToX[property] = xProp;
-    d_ptr->m_xToProperty[xProp] = property;
-    property->addSubProperty(xProp);
-
-    QtProperty *yProp = d_ptr->m_doublePropertyManager->addProperty();
-    yProp->setPropertyName(tr("Y"));
-    d_ptr->m_doublePropertyManager->setDecimals(yProp, decimals(property));
-    d_ptr->m_doublePropertyManager->setValue(yProp, 0);
-    d_ptr->m_propertyToY[property] = yProp;
-    d_ptr->m_yToProperty[yProp] = property;
-    property->addSubProperty(yProp);
-}
-
-/**
-    \reimp
-*/
-void QtPointFPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    QtProperty *xProp = d_ptr->m_propertyToX[property];
-    if (xProp) {
-        d_ptr->m_xToProperty.remove(xProp);
-        delete xProp;
-    }
-    d_ptr->m_propertyToX.remove(property);
-
-    QtProperty *yProp = d_ptr->m_propertyToY[property];
-    if (yProp) {
-        d_ptr->m_yToProperty.remove(yProp);
-        delete yProp;
-    }
-    d_ptr->m_propertyToY.remove(property);
-
-    d_ptr->m_values.remove(property);
-}
-
-// QtSizePropertyManager
-
-class QtSizePropertyManagerPrivate
-{
-    QtSizePropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtSizePropertyManager)
-public:
-
-    void slotIntChanged(QtProperty *property, int value);
-    void slotPropertyDestroyed(QtProperty *property);
-    void setValue(QtProperty *property, const QSize &val);
-    void setRange(QtProperty *property,
-                const QSize &minVal, const QSize &maxVal, const QSize &val);
-
-    struct Data
-    {
-        Data() : val(QSize(0, 0)), minVal(QSize(0, 0)), maxVal(QSize(INT_MAX, INT_MAX)) {}
-        QSize val;
-        QSize minVal;
-        QSize maxVal;
-        QSize minimumValue() const { return minVal; }
-        QSize maximumValue() const { return maxVal; }
-        void setMinimumValue(const QSize &newMinVal) { setSizeMinimumData(this, newMinVal); }
-        void setMaximumValue(const QSize &newMaxVal) { setSizeMaximumData(this, newMaxVal); }
-    };
-
-    typedef QMap<const QtProperty *, Data> PropertyValueMap;
-    PropertyValueMap m_values;
-
-    QtIntPropertyManager *m_intPropertyManager;
-
-    QMap<const QtProperty *, QtProperty *> m_propertyToW;
-    QMap<const QtProperty *, QtProperty *> m_propertyToH;
-
-    QMap<const QtProperty *, QtProperty *> m_wToProperty;
-    QMap<const QtProperty *, QtProperty *> m_hToProperty;
-};
-
-void QtSizePropertyManagerPrivate::slotIntChanged(QtProperty *property, int value)
-{
-    if (QtProperty *prop = m_wToProperty.value(property, 0)) {
-        QSize s = m_values[prop].val;
-        s.setWidth(value);
-        q_ptr->setValue(prop, s);
-    } else if (QtProperty *prop = m_hToProperty.value(property, 0)) {
-        QSize s = m_values[prop].val;
-        s.setHeight(value);
-        q_ptr->setValue(prop, s);
-    }
-}
-
-void QtSizePropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
-{
-    if (QtProperty *pointProp = m_wToProperty.value(property, 0)) {
-        m_propertyToW[pointProp] = 0;
-        m_wToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_hToProperty.value(property, 0)) {
-        m_propertyToH[pointProp] = 0;
-        m_hToProperty.remove(property);
-    }
-}
-
-void QtSizePropertyManagerPrivate::setValue(QtProperty *property, const QSize &val)
-{
-    m_intPropertyManager->setValue(m_propertyToW.value(property), val.width());
-    m_intPropertyManager->setValue(m_propertyToH.value(property), val.height());
-}
-
-void QtSizePropertyManagerPrivate::setRange(QtProperty *property,
-                const QSize &minVal, const QSize &maxVal, const QSize &val)
-{
-    QtProperty *wProperty = m_propertyToW.value(property);
-    QtProperty *hProperty = m_propertyToH.value(property);
-    m_intPropertyManager->setRange(wProperty, minVal.width(), maxVal.width());
-    m_intPropertyManager->setValue(wProperty, val.width());
-    m_intPropertyManager->setRange(hProperty, minVal.height(), maxVal.height());
-    m_intPropertyManager->setValue(hProperty, val.height());
-}
-
-/**
-    \class QtSizePropertyManager
-
-    \brief The QtSizePropertyManager provides and manages QSize properties.
-
-    A size property has nested \e width and \e height
-    subproperties. The top-level property's value can be retrieved
-    using the value() function, and set using the setValue() slot.
-
-    The subproperties are created by a QtIntPropertyManager object. This
-    manager can be retrieved using the subIntPropertyManager() function. In
-    order to provide editing widgets for the subproperties in a
-    property browser widget, this manager must be associated with an
-    editor factory.
-
-    A size property also has a range of valid values defined by a
-    minimum size and a maximum size. These sizes can be retrieved
-    using the minimum() and the maximum() functions, and set using the
-    setMinimum() and setMaximum() slots. Alternatively, the range can
-    be defined in one go using the setRange() slot.
-
-    In addition, QtSizePropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes, and the rangeChanged() signal which is emitted whenever
-    such a property changes its range of valid sizes.
-
-    \sa QtAbstractPropertyManager, QtIntPropertyManager, QtSizeFPropertyManager
-*/
-
-/**
-    \fn void QtSizePropertyManager::valueChanged(QtProperty *property, const QSize &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    \fn void QtSizePropertyManager::rangeChanged(QtProperty *property, const QSize &minimum, const QSize &maximum)
-
-    This signal is emitted whenever a property created by this manager
-    changes its range of valid sizes, passing a pointer to the \a
-    property and the new \a minimum and \a maximum sizes.
-
-    \sa setRange()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtSizePropertyManager::QtSizePropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtSizePropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_intPropertyManager = new QtIntPropertyManager(this);
-    connect(d_ptr->m_intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotIntChanged(QtProperty *, int)));
-    connect(d_ptr->m_intPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtSizePropertyManager::~QtSizePropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the manager that creates the nested \e width and \e height
-    subproperties.
-
-    In order to provide editing widgets for the \e width and \e height
-    properties in a property browser widget, this manager must be
-    associated with an editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtIntPropertyManager *QtSizePropertyManager::subIntPropertyManager() const
-{
-    return d_ptr->m_intPropertyManager;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by this manager, this
-    function returns an invalid size
-
-    \sa setValue()
-*/
-QSize QtSizePropertyManager::value(const QtProperty *property) const
-{
-    return getValue<QSize>(d_ptr->m_values, property);
-}
-
-/**
-    Returns the given \a property's minimum size value.
-
-    \sa setMinimum(), maximum(), setRange()
-*/
-QSize QtSizePropertyManager::minimum(const QtProperty *property) const
-{
-    return getMinimum<QSize>(d_ptr->m_values, property);
-}
-
-/**
-    Returns the given \a property's maximum size value.
-
-    \sa setMaximum(), minimum(), setRange()
-*/
-QSize QtSizePropertyManager::maximum(const QtProperty *property) const
-{
-    return getMaximum<QSize>(d_ptr->m_values, property);
-}
-
-/**
-    \reimp
-*/
-QString QtSizePropertyManager::valueText(const QtProperty *property) const
-{
-    const QtSizePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    const QSize v = it.value().val;
-    return QString(tr("%1 x %2").arg(QString::number(v.width()))
-                                .arg(QString::number(v.height())));
-}
-
-/**
-    \fn void QtSizePropertyManager::setValue(QtProperty *property, const QSize &value)
-
-    Sets the value of the given \a property to \a value.
-
-    If the specified \a value is not valid according to the given \a
-    property's size range, the \a value is adjusted to the nearest
-    valid value within the size range.
-
-    \sa value(), setRange(), valueChanged()
-*/
-void QtSizePropertyManager::setValue(QtProperty *property, const QSize &val)
-{
-    setValueInRange<const QSize &, QtSizePropertyManagerPrivate, QtSizePropertyManager, const QSize>(this, d_ptr,
-                &QtSizePropertyManager::propertyChanged,
-                &QtSizePropertyManager::valueChanged,
-                property, val, &QtSizePropertyManagerPrivate::setValue);
-}
-
-/**
-    Sets the minimum size value for the given \a property to \a minVal.
-
-    When setting the minimum size value, the maximum and current
-    values are adjusted if necessary (ensuring that the size range
-    remains valid and that the current value is within the range).
-
-    \sa minimum(), setRange(), rangeChanged()
-*/
-void QtSizePropertyManager::setMinimum(QtProperty *property, const QSize &minVal)
-{
-    setBorderValue<const QSize &, QtSizePropertyManagerPrivate, QtSizePropertyManager, QSize, QtSizePropertyManagerPrivate::Data>(this, d_ptr,
-                &QtSizePropertyManager::propertyChanged,
-                &QtSizePropertyManager::valueChanged,
-                &QtSizePropertyManager::rangeChanged,
-                property,
-                &QtSizePropertyManagerPrivate::Data::minimumValue,
-                &QtSizePropertyManagerPrivate::Data::setMinimumValue,
-                minVal, &QtSizePropertyManagerPrivate::setRange);
-}
-
-/**
-    Sets the maximum size value for the given \a property to \a maxVal.
-
-    When setting the maximum size value, the minimum and current
-    values are adjusted if necessary (ensuring that the size range
-    remains valid and that the current value is within the range).
-
-    \sa maximum(), setRange(), rangeChanged()
-*/
-void QtSizePropertyManager::setMaximum(QtProperty *property, const QSize &maxVal)
-{
-    setBorderValue<const QSize &, QtSizePropertyManagerPrivate, QtSizePropertyManager, QSize, QtSizePropertyManagerPrivate::Data>(this, d_ptr,
-                &QtSizePropertyManager::propertyChanged,
-                &QtSizePropertyManager::valueChanged,
-                &QtSizePropertyManager::rangeChanged,
-                property,
-                &QtSizePropertyManagerPrivate::Data::maximumValue,
-                &QtSizePropertyManagerPrivate::Data::setMaximumValue,
-                maxVal, &QtSizePropertyManagerPrivate::setRange);
-}
-
-/**
-    \fn void QtSizePropertyManager::setRange(QtProperty *property, const QSize &minimum, const QSize &maximum)
-
-    Sets the range of valid values.
-
-    This is a convenience function defining the range of valid values
-    in one go; setting the \a minimum and \a maximum values for the
-    given \a property with a single function call.
-
-    When setting a new range, the current value is adjusted if
-    necessary (ensuring that the value remains within the range).
-
-    \sa  setMinimum(), setMaximum(), rangeChanged()
-*/
-void QtSizePropertyManager::setRange(QtProperty *property, const QSize &minVal, const QSize &maxVal)
-{
-    setBorderValues<const QSize &, QtSizePropertyManagerPrivate, QtSizePropertyManager, QSize>(this, d_ptr,
-                &QtSizePropertyManager::propertyChanged,
-                &QtSizePropertyManager::valueChanged,
-                &QtSizePropertyManager::rangeChanged,
-                property, minVal, maxVal, &QtSizePropertyManagerPrivate::setRange);
-}
-
-/**
-    \reimp
-*/
-void QtSizePropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QtSizePropertyManagerPrivate::Data();
-
-    QtProperty *wProp = d_ptr->m_intPropertyManager->addProperty();
-    wProp->setPropertyName(tr("Width"));
-    d_ptr->m_intPropertyManager->setValue(wProp, 0);
-    d_ptr->m_intPropertyManager->setMinimum(wProp, 0);
-    d_ptr->m_propertyToW[property] = wProp;
-    d_ptr->m_wToProperty[wProp] = property;
-    property->addSubProperty(wProp);
-
-    QtProperty *hProp = d_ptr->m_intPropertyManager->addProperty();
-    hProp->setPropertyName(tr("Height"));
-    d_ptr->m_intPropertyManager->setValue(hProp, 0);
-    d_ptr->m_intPropertyManager->setMinimum(hProp, 0);
-    d_ptr->m_propertyToH[property] = hProp;
-    d_ptr->m_hToProperty[hProp] = property;
-    property->addSubProperty(hProp);
-}
-
-/**
-    \reimp
-*/
-void QtSizePropertyManager::uninitializeProperty(QtProperty *property)
-{
-    QtProperty *wProp = d_ptr->m_propertyToW[property];
-    if (wProp) {
-        d_ptr->m_wToProperty.remove(wProp);
-        delete wProp;
-    }
-    d_ptr->m_propertyToW.remove(property);
-
-    QtProperty *hProp = d_ptr->m_propertyToH[property];
-    if (hProp) {
-        d_ptr->m_hToProperty.remove(hProp);
-        delete hProp;
-    }
-    d_ptr->m_propertyToH.remove(property);
-
-    d_ptr->m_values.remove(property);
-}
-
-// QtSizeFPropertyManager
-
-class QtSizeFPropertyManagerPrivate
-{
-    QtSizeFPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtSizeFPropertyManager)
-public:
-
-    void slotDoubleChanged(QtProperty *property, double value);
-    void slotPropertyDestroyed(QtProperty *property);
-    void setValue(QtProperty *property, const QSizeF &val);
-    void setRange(QtProperty *property,
-                const QSizeF &minVal, const QSizeF &maxVal, const QSizeF &val);
-
-    struct Data
-    {
-        Data() : val(QSizeF(0, 0)), minVal(QSizeF(0, 0)), maxVal(QSizeF(INT_MAX, INT_MAX)), decimals(2) {}
-        QSizeF val;
-        QSizeF minVal;
-        QSizeF maxVal;
-        int decimals;
-        QSizeF minimumValue() const { return minVal; }
-        QSizeF maximumValue() const { return maxVal; }
-        void setMinimumValue(const QSizeF &newMinVal) { setSizeMinimumData(this, newMinVal); }
-        void setMaximumValue(const QSizeF &newMaxVal) { setSizeMaximumData(this, newMaxVal); }
-    };
-
-    typedef QMap<const QtProperty *, Data> PropertyValueMap;
-    PropertyValueMap m_values;
-
-    QtDoublePropertyManager *m_doublePropertyManager;
-
-    QMap<const QtProperty *, QtProperty *> m_propertyToW;
-    QMap<const QtProperty *, QtProperty *> m_propertyToH;
-
-    QMap<const QtProperty *, QtProperty *> m_wToProperty;
-    QMap<const QtProperty *, QtProperty *> m_hToProperty;
-};
-
-void QtSizeFPropertyManagerPrivate::slotDoubleChanged(QtProperty *property, double value)
-{
-    if (QtProperty *prop = m_wToProperty.value(property, 0)) {
-        QSizeF s = m_values[prop].val;
-        s.setWidth(value);
-        q_ptr->setValue(prop, s);
-    } else if (QtProperty *prop = m_hToProperty.value(property, 0)) {
-        QSizeF s = m_values[prop].val;
-        s.setHeight(value);
-        q_ptr->setValue(prop, s);
-    }
-}
-
-void QtSizeFPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
-{
-    if (QtProperty *pointProp = m_wToProperty.value(property, 0)) {
-        m_propertyToW[pointProp] = 0;
-        m_wToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_hToProperty.value(property, 0)) {
-        m_propertyToH[pointProp] = 0;
-        m_hToProperty.remove(property);
-    }
-}
-
-void QtSizeFPropertyManagerPrivate::setValue(QtProperty *property, const QSizeF &val)
-{
-    m_doublePropertyManager->setValue(m_propertyToW.value(property), val.width());
-    m_doublePropertyManager->setValue(m_propertyToH.value(property), val.height());
-}
-
-void QtSizeFPropertyManagerPrivate::setRange(QtProperty *property,
-                const QSizeF &minVal, const QSizeF &maxVal, const QSizeF &val)
-{
-    m_doublePropertyManager->setRange(m_propertyToW[property], minVal.width(), maxVal.width());
-    m_doublePropertyManager->setValue(m_propertyToW[property], val.width());
-    m_doublePropertyManager->setRange(m_propertyToH[property], minVal.height(), maxVal.height());
-    m_doublePropertyManager->setValue(m_propertyToH[property], val.height());
-}
-
-/**
-    \class QtSizeFPropertyManager
-
-    \brief The QtSizeFPropertyManager provides and manages QSizeF properties.
-
-    A size property has nested \e width and \e height
-    subproperties. The top-level property's value can be retrieved
-    using the value() function, and set using the setValue() slot.
-
-    The subproperties are created by a QtDoublePropertyManager object. This
-    manager can be retrieved using the subDoublePropertyManager() function. In
-    order to provide editing widgets for the subproperties in a
-    property browser widget, this manager must be associated with an
-    editor factory.
-
-    A size property also has a range of valid values defined by a
-    minimum size and a maximum size. These sizes can be retrieved
-    using the minimum() and the maximum() functions, and set using the
-    setMinimum() and setMaximum() slots. Alternatively, the range can
-    be defined in one go using the setRange() slot.
-
-    In addition, QtSizeFPropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes, and the rangeChanged() signal which is emitted whenever
-    such a property changes its range of valid sizes.
-
-    \sa QtAbstractPropertyManager, QtDoublePropertyManager, QtSizePropertyManager
-*/
-
-/**
-    \fn void QtSizeFPropertyManager::valueChanged(QtProperty *property, const QSizeF &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    \fn void QtSizeFPropertyManager::rangeChanged(QtProperty *property, const QSizeF &minimum, const QSizeF &maximum)
-
-    This signal is emitted whenever a property created by this manager
-    changes its range of valid sizes, passing a pointer to the \a
-    property and the new \a minimum and \a maximum sizes.
-
-    \sa setRange()
-*/
-
-/**
-    \fn void QtSizeFPropertyManager::decimalsChanged(QtProperty *property, int prec)
-
-    This signal is emitted whenever a property created by this manager
-    changes its precision of value, passing a pointer to the
-    \a property and the new \a prec value
-
-    \sa setDecimals()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtSizeFPropertyManager::QtSizeFPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtSizeFPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_doublePropertyManager = new QtDoublePropertyManager(this);
-    connect(d_ptr->m_doublePropertyManager, SIGNAL(valueChanged(QtProperty *, double)),
-                this, SLOT(slotDoubleChanged(QtProperty *, double)));
-    connect(d_ptr->m_doublePropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtSizeFPropertyManager::~QtSizeFPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the manager that creates the nested \e width and \e height
-    subproperties.
-
-    In order to provide editing widgets for the \e width and \e height
-    properties in a property browser widget, this manager must be
-    associated with an editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtDoublePropertyManager *QtSizeFPropertyManager::subDoublePropertyManager() const
-{
-    return d_ptr->m_doublePropertyManager;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by this manager, this
-    function returns an invalid size
-
-    \sa setValue()
-*/
-QSizeF QtSizeFPropertyManager::value(const QtProperty *property) const
-{
-    return getValue<QSizeF>(d_ptr->m_values, property);
-}
-
-/**
-    Returns the given \a property's precision, in decimals.
-
-    \sa setDecimals()
-*/
-int QtSizeFPropertyManager::decimals(const QtProperty *property) const
-{
-    return getData<int>(d_ptr->m_values, &QtSizeFPropertyManagerPrivate::Data::decimals, property, 0);
-}
-
-/**
-    Returns the given \a property's minimum size value.
-
-    \sa setMinimum(), maximum(), setRange()
-*/
-QSizeF QtSizeFPropertyManager::minimum(const QtProperty *property) const
-{
-    return getMinimum<QSizeF>(d_ptr->m_values, property);
-}
-
-/**
-    Returns the given \a property's maximum size value.
-
-    \sa setMaximum(), minimum(), setRange()
-*/
-QSizeF QtSizeFPropertyManager::maximum(const QtProperty *property) const
-{
-    return getMaximum<QSizeF>(d_ptr->m_values, property);
-}
-
-/**
-    \reimp
-*/
-QString QtSizeFPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtSizeFPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    const QSizeF v = it.value().val;
-    const int dec = it.value().decimals;
-    return QString(tr("%1 x %2").arg(QString::number(v.width(), 'f', dec))
-                                .arg(QString::number(v.height(), 'f', dec)));
-}
-
-/**
-    \fn void QtSizeFPropertyManager::setValue(QtProperty *property, const QSizeF &value)
-
-    Sets the value of the given \a property to \a value.
-
-    If the specified \a value is not valid according to the given \a
-    property's size range, the \a value is adjusted to the nearest
-    valid value within the size range.
-
-    \sa value(), setRange(), valueChanged()
-*/
-void QtSizeFPropertyManager::setValue(QtProperty *property, const QSizeF &val)
-{
-    setValueInRange<const QSizeF &, QtSizeFPropertyManagerPrivate, QtSizeFPropertyManager, QSizeF>(this, d_ptr,
-                &QtSizeFPropertyManager::propertyChanged,
-                &QtSizeFPropertyManager::valueChanged,
-                property, val, &QtSizeFPropertyManagerPrivate::setValue);
-}
-
-/**
-    \fn void QtSizeFPropertyManager::setDecimals(QtProperty *property, int prec)
-
-    Sets the precision of the given \a property to \a prec.
-
-    The valid decimal range is 0-13. The default is 2.
-
-    \sa decimals()
-*/
-void QtSizeFPropertyManager::setDecimals(QtProperty *property, int prec)
-{
-    const QtSizeFPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtSizeFPropertyManagerPrivate::Data data = it.value();
-
-    if (prec > 13)
-        prec = 13;
-    else if (prec < 0)
-        prec = 0;
-
-    if (data.decimals == prec)
-        return;
-
-    data.decimals = prec;
-    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToW[property], prec);
-    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToH[property], prec);
-
-    it.value() = data;
-
-    emit decimalsChanged(property, data.decimals);
-}
-
-/**
-    Sets the minimum size value for the given \a property to \a minVal.
-
-    When setting the minimum size value, the maximum and current
-    values are adjusted if necessary (ensuring that the size range
-    remains valid and that the current value is within the range).
-
-    \sa minimum(), setRange(), rangeChanged()
-*/
-void QtSizeFPropertyManager::setMinimum(QtProperty *property, const QSizeF &minVal)
-{
-    setBorderValue<const QSizeF &, QtSizeFPropertyManagerPrivate, QtSizeFPropertyManager, QSizeF, QtSizeFPropertyManagerPrivate::Data>(this, d_ptr,
-                &QtSizeFPropertyManager::propertyChanged,
-                &QtSizeFPropertyManager::valueChanged,
-                &QtSizeFPropertyManager::rangeChanged,
-                property,
-                &QtSizeFPropertyManagerPrivate::Data::minimumValue,
-                &QtSizeFPropertyManagerPrivate::Data::setMinimumValue,
-                minVal, &QtSizeFPropertyManagerPrivate::setRange);
-}
-
-/**
-    Sets the maximum size value for the given \a property to \a maxVal.
-
-    When setting the maximum size value, the minimum and current
-    values are adjusted if necessary (ensuring that the size range
-    remains valid and that the current value is within the range).
-
-    \sa maximum(), setRange(), rangeChanged()
-*/
-void QtSizeFPropertyManager::setMaximum(QtProperty *property, const QSizeF &maxVal)
-{
-    setBorderValue<const QSizeF &, QtSizeFPropertyManagerPrivate, QtSizeFPropertyManager, QSizeF, QtSizeFPropertyManagerPrivate::Data>(this, d_ptr,
-                &QtSizeFPropertyManager::propertyChanged,
-                &QtSizeFPropertyManager::valueChanged,
-                &QtSizeFPropertyManager::rangeChanged,
-                property,
-                &QtSizeFPropertyManagerPrivate::Data::maximumValue,
-                &QtSizeFPropertyManagerPrivate::Data::setMaximumValue,
-                maxVal, &QtSizeFPropertyManagerPrivate::setRange);
-}
-
-/**
-    \fn void QtSizeFPropertyManager::setRange(QtProperty *property, const QSizeF &minimum, const QSizeF &maximum)
-
-    Sets the range of valid values.
-
-    This is a convenience function defining the range of valid values
-    in one go; setting the \a minimum and \a maximum values for the
-    given \a property with a single function call.
-
-    When setting a new range, the current value is adjusted if
-    necessary (ensuring that the value remains within the range).
-
-    \sa  setMinimum(), setMaximum(), rangeChanged()
-*/
-void QtSizeFPropertyManager::setRange(QtProperty *property, const QSizeF &minVal, const QSizeF &maxVal)
-{
-    setBorderValues<const QSizeF &, QtSizeFPropertyManagerPrivate, QtSizeFPropertyManager, QSizeF>(this, d_ptr,
-                &QtSizeFPropertyManager::propertyChanged,
-                &QtSizeFPropertyManager::valueChanged,
-                &QtSizeFPropertyManager::rangeChanged,
-                property, minVal, maxVal, &QtSizeFPropertyManagerPrivate::setRange);
-}
-
-/**
-    \reimp
-*/
-void QtSizeFPropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QtSizeFPropertyManagerPrivate::Data();
-
-    QtProperty *wProp = d_ptr->m_doublePropertyManager->addProperty();
-    wProp->setPropertyName(tr("Width"));
-    d_ptr->m_doublePropertyManager->setDecimals(wProp, decimals(property));
-    d_ptr->m_doublePropertyManager->setValue(wProp, 0);
-    d_ptr->m_doublePropertyManager->setMinimum(wProp, 0);
-    d_ptr->m_propertyToW[property] = wProp;
-    d_ptr->m_wToProperty[wProp] = property;
-    property->addSubProperty(wProp);
-
-    QtProperty *hProp = d_ptr->m_doublePropertyManager->addProperty();
-    hProp->setPropertyName(tr("Height"));
-    d_ptr->m_doublePropertyManager->setDecimals(hProp, decimals(property));
-    d_ptr->m_doublePropertyManager->setValue(hProp, 0);
-    d_ptr->m_doublePropertyManager->setMinimum(hProp, 0);
-    d_ptr->m_propertyToH[property] = hProp;
-    d_ptr->m_hToProperty[hProp] = property;
-    property->addSubProperty(hProp);
-}
-
-/**
-    \reimp
-*/
-void QtSizeFPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    QtProperty *wProp = d_ptr->m_propertyToW[property];
-    if (wProp) {
-        d_ptr->m_wToProperty.remove(wProp);
-        delete wProp;
-    }
-    d_ptr->m_propertyToW.remove(property);
-
-    QtProperty *hProp = d_ptr->m_propertyToH[property];
-    if (hProp) {
-        d_ptr->m_hToProperty.remove(hProp);
-        delete hProp;
-    }
-    d_ptr->m_propertyToH.remove(property);
-
-    d_ptr->m_values.remove(property);
-}
-
-// QtRectPropertyManager
-
-class QtRectPropertyManagerPrivate
-{
-    QtRectPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtRectPropertyManager)
-public:
-
-    void slotIntChanged(QtProperty *property, int value);
-    void slotPropertyDestroyed(QtProperty *property);
-    void setConstraint(QtProperty *property, const QRect &constraint, const QRect &val);
-
-    struct Data
-    {
-        Data() : val(0, 0, 0, 0) {}
-        QRect val;
-        QRect constraint;
-    };
-
-    typedef QMap<const QtProperty *, Data> PropertyValueMap;
-    PropertyValueMap m_values;
-
-    QtIntPropertyManager *m_intPropertyManager;
-
-    QMap<const QtProperty *, QtProperty *> m_propertyToX;
-    QMap<const QtProperty *, QtProperty *> m_propertyToY;
-    QMap<const QtProperty *, QtProperty *> m_propertyToW;
-    QMap<const QtProperty *, QtProperty *> m_propertyToH;
-
-    QMap<const QtProperty *, QtProperty *> m_xToProperty;
-    QMap<const QtProperty *, QtProperty *> m_yToProperty;
-    QMap<const QtProperty *, QtProperty *> m_wToProperty;
-    QMap<const QtProperty *, QtProperty *> m_hToProperty;
-};
-
-void QtRectPropertyManagerPrivate::slotIntChanged(QtProperty *property, int value)
-{
-    if (QtProperty *prop = m_xToProperty.value(property, 0)) {
-        QRect r = m_values[prop].val;
-        r.moveLeft(value);
-        q_ptr->setValue(prop, r);
-    } else if (QtProperty *prop = m_yToProperty.value(property)) {
-        QRect r = m_values[prop].val;
-        r.moveTop(value);
-        q_ptr->setValue(prop, r);
-    } else if (QtProperty *prop = m_wToProperty.value(property, 0)) {
-        Data data = m_values[prop];
-        QRect r = data.val;
-        r.setWidth(value);
-        if (!data.constraint.isNull() && data.constraint.x() + data.constraint.width() < r.x() + r.width()) {
-            r.moveLeft(data.constraint.left() + data.constraint.width() - r.width());
-        }
-        q_ptr->setValue(prop, r);
-    } else if (QtProperty *prop = m_hToProperty.value(property, 0)) {
-        Data data = m_values[prop];
-        QRect r = data.val;
-        r.setHeight(value);
-        if (!data.constraint.isNull() && data.constraint.y() + data.constraint.height() < r.y() + r.height()) {
-            r.moveTop(data.constraint.top() + data.constraint.height() - r.height());
-        }
-        q_ptr->setValue(prop, r);
-    }
-}
-
-void QtRectPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
-{
-    if (QtProperty *pointProp = m_xToProperty.value(property, 0)) {
-        m_propertyToX[pointProp] = 0;
-        m_xToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_yToProperty.value(property, 0)) {
-        m_propertyToY[pointProp] = 0;
-        m_yToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_wToProperty.value(property, 0)) {
-        m_propertyToW[pointProp] = 0;
-        m_wToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_hToProperty.value(property, 0)) {
-        m_propertyToH[pointProp] = 0;
-        m_hToProperty.remove(property);
-    }
-}
-
-void QtRectPropertyManagerPrivate::setConstraint(QtProperty *property,
-            const QRect &constraint, const QRect &val)
-{
-    const bool isNull = constraint.isNull();
-    const int left   = isNull ? INT_MIN : constraint.left();
-    const int right  = isNull ? INT_MAX : constraint.left() + constraint.width();
-    const int top    = isNull ? INT_MIN : constraint.top();
-    const int bottom = isNull ? INT_MAX : constraint.top() + constraint.height();
-    const int width  = isNull ? INT_MAX : constraint.width();
-    const int height = isNull ? INT_MAX : constraint.height();
-
-    m_intPropertyManager->setRange(m_propertyToX[property], left, right);
-    m_intPropertyManager->setRange(m_propertyToY[property], top, bottom);
-    m_intPropertyManager->setRange(m_propertyToW[property], 0, width);
-    m_intPropertyManager->setRange(m_propertyToH[property], 0, height);
-
-    m_intPropertyManager->setValue(m_propertyToX[property], val.x());
-    m_intPropertyManager->setValue(m_propertyToY[property], val.y());
-    m_intPropertyManager->setValue(m_propertyToW[property], val.width());
-    m_intPropertyManager->setValue(m_propertyToH[property], val.height());
-}
-
-/**
-    \class QtRectPropertyManager
-
-    \brief The QtRectPropertyManager provides and manages QRect properties.
-
-    A rectangle property has nested \e x, \e y, \e width and \e height
-    subproperties. The top-level property's value can be retrieved
-    using the value() function, and set using the setValue() slot.
-
-    The subproperties are created by a QtIntPropertyManager object. This
-    manager can be retrieved using the subIntPropertyManager() function. In
-    order to provide editing widgets for the subproperties in a
-    property browser widget, this manager must be associated with an
-    editor factory.
-
-    A rectangle property also has a constraint rectangle which can be
-    retrieved using the constraint() function, and set using the
-    setConstraint() slot.
-
-    In addition, QtRectPropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes, and the constraintChanged() signal which is emitted
-    whenever such a property changes its constraint rectangle.
-
-    \sa QtAbstractPropertyManager, QtIntPropertyManager, QtRectFPropertyManager
-*/
-
-/**
-    \fn void QtRectPropertyManager::valueChanged(QtProperty *property, const QRect &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    \fn void QtRectPropertyManager::constraintChanged(QtProperty *property, const QRect &constraint)
-
-    This signal is emitted whenever property changes its constraint
-    rectangle, passing a pointer to the \a property and the new \a
-    constraint rectangle as parameters.
-
-    \sa setConstraint()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtRectPropertyManager::QtRectPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtRectPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_intPropertyManager = new QtIntPropertyManager(this);
-    connect(d_ptr->m_intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotIntChanged(QtProperty *, int)));
-    connect(d_ptr->m_intPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtRectPropertyManager::~QtRectPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the manager that creates the nested \e x, \e y, \e width
-    and \e height subproperties.
-
-    In order to provide editing widgets for the mentioned
-    subproperties in a property browser widget, this manager must be
-    associated with an editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtIntPropertyManager *QtRectPropertyManager::subIntPropertyManager() const
-{
-    return d_ptr->m_intPropertyManager;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by this manager, this
-    function returns an invalid rectangle.
-
-    \sa setValue(), constraint()
-*/
-QRect QtRectPropertyManager::value(const QtProperty *property) const
-{
-    return getValue<QRect>(d_ptr->m_values, property);
-}
-
-/**
-    Returns the given \a property's constraining rectangle. If returned value is null QRect it means there is no constraint applied.
-
-    \sa value(), setConstraint()
-*/
-QRect QtRectPropertyManager::constraint(const QtProperty *property) const
-{
-    return getData<QRect>(d_ptr->m_values, &QtRectPropertyManagerPrivate::Data::constraint, property, QRect());
-}
-
-/**
-    \reimp
-*/
-QString QtRectPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtRectPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    const QRect v = it.value().val;
-    return QString(tr("[(%1, %2), %3 x %4]").arg(QString::number(v.x()))
-                                .arg(QString::number(v.y()))
-                                .arg(QString::number(v.width()))
-                                .arg(QString::number(v.height())));
-}
-
-/**
-    \fn void QtRectPropertyManager::setValue(QtProperty *property, const QRect &value)
-
-    Sets the value of the given \a property to \a value. Nested
-    properties are updated automatically.
-
-    If the specified \a value is not inside the given \a property's
-    constraining rectangle, the value is adjusted accordingly to fit
-    within the constraint.
-
-    \sa value(), setConstraint(), valueChanged()
-*/
-void QtRectPropertyManager::setValue(QtProperty *property, const QRect &val)
-{
-    const QtRectPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtRectPropertyManagerPrivate::Data data = it.value();
-
-    QRect newRect = val.normalized();
-    if (!data.constraint.isNull() && !data.constraint.contains(newRect)) {
-        const QRect r1 = data.constraint;
-        const QRect r2 = newRect;
-        newRect.setLeft(qMax(r1.left(), r2.left()));
-        newRect.setRight(qMin(r1.right(), r2.right()));
-        newRect.setTop(qMax(r1.top(), r2.top()));
-        newRect.setBottom(qMin(r1.bottom(), r2.bottom()));
-        if (newRect.width() < 0 || newRect.height() < 0)
-            return;
-    }
-
-    if (data.val == newRect)
-        return;
-
-    data.val = newRect;
-
-    it.value() = data;
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToX[property], newRect.x());
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToY[property], newRect.y());
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToW[property], newRect.width());
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToH[property], newRect.height());
-
-    emit propertyChanged(property);
-    emit valueChanged(property, data.val);
-}
-
-/**
-    Sets the given \a property's constraining rectangle to \a
-    constraint.
-
-    When setting the constraint, the current value is adjusted if
-    necessary (ensuring that the current rectangle value is inside the
-    constraint). In order to reset the constraint pass a null QRect value.
-
-    \sa setValue(), constraint(), constraintChanged()
-*/
-void QtRectPropertyManager::setConstraint(QtProperty *property, const QRect &constraint)
-{
-    const QtRectPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtRectPropertyManagerPrivate::Data data = it.value();
-
-    QRect newConstraint = constraint.normalized();
-    if (data.constraint == newConstraint)
-        return;
-
-    const QRect oldVal = data.val;
-
-    data.constraint = newConstraint;
-
-    if (!data.constraint.isNull() && !data.constraint.contains(oldVal)) {
-        QRect r1 = data.constraint;
-        QRect r2 = data.val;
-
-        if (r2.width() > r1.width())
-            r2.setWidth(r1.width());
-        if (r2.height() > r1.height())
-            r2.setHeight(r1.height());
-        if (r2.left() < r1.left())
-            r2.moveLeft(r1.left());
-        else if (r2.right() > r1.right())
-            r2.moveRight(r1.right());
-        if (r2.top() < r1.top())
-            r2.moveTop(r1.top());
-        else if (r2.bottom() > r1.bottom())
-            r2.moveBottom(r1.bottom());
-
-        data.val = r2;
-    }
-
-    it.value() = data;
-
-    emit constraintChanged(property, data.constraint);
-
-    d_ptr->setConstraint(property, data.constraint, data.val);
-
-    if (data.val == oldVal)
-        return;
-
-    emit propertyChanged(property);
-    emit valueChanged(property, data.val);
-}
-
-/**
-    \reimp
-*/
-void QtRectPropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QtRectPropertyManagerPrivate::Data();
-
-    QtProperty *xProp = d_ptr->m_intPropertyManager->addProperty();
-    xProp->setPropertyName(tr("X"));
-    d_ptr->m_intPropertyManager->setValue(xProp, 0);
-    d_ptr->m_propertyToX[property] = xProp;
-    d_ptr->m_xToProperty[xProp] = property;
-    property->addSubProperty(xProp);
-
-    QtProperty *yProp = d_ptr->m_intPropertyManager->addProperty();
-    yProp->setPropertyName(tr("Y"));
-    d_ptr->m_intPropertyManager->setValue(yProp, 0);
-    d_ptr->m_propertyToY[property] = yProp;
-    d_ptr->m_yToProperty[yProp] = property;
-    property->addSubProperty(yProp);
-
-    QtProperty *wProp = d_ptr->m_intPropertyManager->addProperty();
-    wProp->setPropertyName(tr("Width"));
-    d_ptr->m_intPropertyManager->setValue(wProp, 0);
-    d_ptr->m_intPropertyManager->setMinimum(wProp, 0);
-    d_ptr->m_propertyToW[property] = wProp;
-    d_ptr->m_wToProperty[wProp] = property;
-    property->addSubProperty(wProp);
-
-    QtProperty *hProp = d_ptr->m_intPropertyManager->addProperty();
-    hProp->setPropertyName(tr("Height"));
-    d_ptr->m_intPropertyManager->setValue(hProp, 0);
-    d_ptr->m_intPropertyManager->setMinimum(hProp, 0);
-    d_ptr->m_propertyToH[property] = hProp;
-    d_ptr->m_hToProperty[hProp] = property;
-    property->addSubProperty(hProp);
-}
-
-/**
-    \reimp
-*/
-void QtRectPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    QtProperty *xProp = d_ptr->m_propertyToX[property];
-    if (xProp) {
-        d_ptr->m_xToProperty.remove(xProp);
-        delete xProp;
-    }
-    d_ptr->m_propertyToX.remove(property);
-
-    QtProperty *yProp = d_ptr->m_propertyToY[property];
-    if (yProp) {
-        d_ptr->m_yToProperty.remove(yProp);
-        delete yProp;
-    }
-    d_ptr->m_propertyToY.remove(property);
-
-    QtProperty *wProp = d_ptr->m_propertyToW[property];
-    if (wProp) {
-        d_ptr->m_wToProperty.remove(wProp);
-        delete wProp;
-    }
-    d_ptr->m_propertyToW.remove(property);
-
-    QtProperty *hProp = d_ptr->m_propertyToH[property];
-    if (hProp) {
-        d_ptr->m_hToProperty.remove(hProp);
-        delete hProp;
-    }
-    d_ptr->m_propertyToH.remove(property);
-
-    d_ptr->m_values.remove(property);
-}
-
-// QtRectFPropertyManager
-
-class QtRectFPropertyManagerPrivate
-{
-    QtRectFPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtRectFPropertyManager)
-public:
-
-    void slotDoubleChanged(QtProperty *property, double value);
-    void slotPropertyDestroyed(QtProperty *property);
-    void setConstraint(QtProperty *property, const QRectF &constraint, const QRectF &val);
-
-    struct Data
-    {
-        Data() : val(0, 0, 0, 0), decimals(2) {}
-        QRectF val;
-        QRectF constraint;
-        int decimals;
-    };
-
-    typedef QMap<const QtProperty *, Data> PropertyValueMap;
-    PropertyValueMap m_values;
-
-    QtDoublePropertyManager *m_doublePropertyManager;
-
-    QMap<const QtProperty *, QtProperty *> m_propertyToX;
-    QMap<const QtProperty *, QtProperty *> m_propertyToY;
-    QMap<const QtProperty *, QtProperty *> m_propertyToW;
-    QMap<const QtProperty *, QtProperty *> m_propertyToH;
-
-    QMap<const QtProperty *, QtProperty *> m_xToProperty;
-    QMap<const QtProperty *, QtProperty *> m_yToProperty;
-    QMap<const QtProperty *, QtProperty *> m_wToProperty;
-    QMap<const QtProperty *, QtProperty *> m_hToProperty;
-};
-
-void QtRectFPropertyManagerPrivate::slotDoubleChanged(QtProperty *property, double value)
-{
-    if (QtProperty *prop = m_xToProperty.value(property, 0)) {
-        QRectF r = m_values[prop].val;
-        r.moveLeft(value);
-        q_ptr->setValue(prop, r);
-    } else if (QtProperty *prop = m_yToProperty.value(property, 0)) {
-        QRectF r = m_values[prop].val;
-        r.moveTop(value);
-        q_ptr->setValue(prop, r);
-    } else if (QtProperty *prop = m_wToProperty.value(property, 0)) {
-        Data data = m_values[prop];
-        QRectF r = data.val;
-        r.setWidth(value);
-        if (!data.constraint.isNull() && data.constraint.x() + data.constraint.width() < r.x() + r.width()) {
-            r.moveLeft(data.constraint.left() + data.constraint.width() - r.width());
-        }
-        q_ptr->setValue(prop, r);
-    } else if (QtProperty *prop = m_hToProperty.value(property, 0)) {
-        Data data = m_values[prop];
-        QRectF r = data.val;
-        r.setHeight(value);
-        if (!data.constraint.isNull() && data.constraint.y() + data.constraint.height() < r.y() + r.height()) {
-            r.moveTop(data.constraint.top() + data.constraint.height() - r.height());
-        }
-        q_ptr->setValue(prop, r);
-    }
-}
-
-void QtRectFPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
-{
-    if (QtProperty *pointProp = m_xToProperty.value(property, 0)) {
-        m_propertyToX[pointProp] = 0;
-        m_xToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_yToProperty.value(property, 0)) {
-        m_propertyToY[pointProp] = 0;
-        m_yToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_wToProperty.value(property, 0)) {
-        m_propertyToW[pointProp] = 0;
-        m_wToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_hToProperty.value(property, 0)) {
-        m_propertyToH[pointProp] = 0;
-        m_hToProperty.remove(property);
-    }
-}
-
-void QtRectFPropertyManagerPrivate::setConstraint(QtProperty *property,
-            const QRectF &constraint, const QRectF &val)
-{
-    const bool isNull = constraint.isNull();
-    const float left   = isNull ? FLT_MIN : constraint.left();
-    const float right  = isNull ? FLT_MAX : constraint.left() + constraint.width();
-    const float top    = isNull ? FLT_MIN : constraint.top();
-    const float bottom = isNull ? FLT_MAX : constraint.top() + constraint.height();
-    const float width  = isNull ? FLT_MAX : constraint.width();
-    const float height = isNull ? FLT_MAX : constraint.height();
-
-    m_doublePropertyManager->setRange(m_propertyToX[property], left, right);
-    m_doublePropertyManager->setRange(m_propertyToY[property], top, bottom);
-    m_doublePropertyManager->setRange(m_propertyToW[property], 0, width);
-    m_doublePropertyManager->setRange(m_propertyToH[property], 0, height);
-
-    m_doublePropertyManager->setValue(m_propertyToX[property], val.x());
-    m_doublePropertyManager->setValue(m_propertyToY[property], val.y());
-    m_doublePropertyManager->setValue(m_propertyToW[property], val.width());
-    m_doublePropertyManager->setValue(m_propertyToH[property], val.height());
-}
-
-/**
-    \class QtRectFPropertyManager
-
-    \brief The QtRectFPropertyManager provides and manages QRectF properties.
-
-    A rectangle property has nested \e x, \e y, \e width and \e height
-    subproperties. The top-level property's value can be retrieved
-    using the value() function, and set using the setValue() slot.
-
-    The subproperties are created by a QtDoublePropertyManager object. This
-    manager can be retrieved using the subDoublePropertyManager() function. In
-    order to provide editing widgets for the subproperties in a
-    property browser widget, this manager must be associated with an
-    editor factory.
-
-    A rectangle property also has a constraint rectangle which can be
-    retrieved using the constraint() function, and set using the
-    setConstraint() slot.
-
-    In addition, QtRectFPropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes, and the constraintChanged() signal which is emitted
-    whenever such a property changes its constraint rectangle.
-
-    \sa QtAbstractPropertyManager, QtDoublePropertyManager, QtRectPropertyManager
-*/
-
-/**
-    \fn void QtRectFPropertyManager::valueChanged(QtProperty *property, const QRectF &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    \fn void QtRectFPropertyManager::constraintChanged(QtProperty *property, const QRectF &constraint)
-
-    This signal is emitted whenever property changes its constraint
-    rectangle, passing a pointer to the \a property and the new \a
-    constraint rectangle as parameters.
-
-    \sa setConstraint()
-*/
-
-/**
-    \fn void QtRectFPropertyManager::decimalsChanged(QtProperty *property, int prec)
-
-    This signal is emitted whenever a property created by this manager
-    changes its precision of value, passing a pointer to the
-    \a property and the new \a prec value
-
-    \sa setDecimals()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtRectFPropertyManager::QtRectFPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtRectFPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_doublePropertyManager = new QtDoublePropertyManager(this);
-    connect(d_ptr->m_doublePropertyManager, SIGNAL(valueChanged(QtProperty *, double)),
-                this, SLOT(slotDoubleChanged(QtProperty *, double)));
-    connect(d_ptr->m_doublePropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtRectFPropertyManager::~QtRectFPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the manager that creates the nested \e x, \e y, \e width
-    and \e height subproperties.
-
-    In order to provide editing widgets for the mentioned
-    subproperties in a property browser widget, this manager must be
-    associated with an editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtDoublePropertyManager *QtRectFPropertyManager::subDoublePropertyManager() const
-{
-    return d_ptr->m_doublePropertyManager;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by this manager, this
-    function returns an invalid rectangle.
-
-    \sa setValue(), constraint()
-*/
-QRectF QtRectFPropertyManager::value(const QtProperty *property) const
-{
-    return getValue<QRectF>(d_ptr->m_values, property);
-}
-
-/**
-    Returns the given \a property's precision, in decimals.
-
-    \sa setDecimals()
-*/
-int QtRectFPropertyManager::decimals(const QtProperty *property) const
-{
-    return getData<int>(d_ptr->m_values, &QtRectFPropertyManagerPrivate::Data::decimals, property, 0);
-}
-
-/**
-    Returns the given \a property's constraining rectangle. If returned value is null QRectF it means there is no constraint applied.
-
-    \sa value(), setConstraint()
-*/
-QRectF QtRectFPropertyManager::constraint(const QtProperty *property) const
-{
-    return getData<QRectF>(d_ptr->m_values, &QtRectFPropertyManagerPrivate::Data::constraint, property, QRect());
-}
-
-/**
-    \reimp
-*/
-QString QtRectFPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtRectFPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-    const QRectF v = it.value().val;
-    const int dec = it.value().decimals;
-    return QString(tr("[(%1, %2), %3 x %4]").arg(QString::number(v.x(), 'f', dec))
-                                .arg(QString::number(v.y(), 'f', dec))
-                                .arg(QString::number(v.width(), 'f', dec))
-                                .arg(QString::number(v.height(), 'f', dec)));
-}
-
-/**
-    \fn void QtRectFPropertyManager::setValue(QtProperty *property, const QRectF &value)
-
-    Sets the value of the given \a property to \a value. Nested
-    properties are updated automatically.
-
-    If the specified \a value is not inside the given \a property's
-    constraining rectangle, the value is adjusted accordingly to fit
-    within the constraint.
-
-    \sa value(), setConstraint(), valueChanged()
-*/
-void QtRectFPropertyManager::setValue(QtProperty *property, const QRectF &val)
-{
-    const QtRectFPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtRectFPropertyManagerPrivate::Data data = it.value();
-
-    QRectF newRect = val.normalized();
-    if (!data.constraint.isNull() && !data.constraint.contains(newRect)) {
-        const QRectF r1 = data.constraint;
-        const QRectF r2 = newRect;
-        newRect.setLeft(qMax(r1.left(), r2.left()));
-        newRect.setRight(qMin(r1.right(), r2.right()));
-        newRect.setTop(qMax(r1.top(), r2.top()));
-        newRect.setBottom(qMin(r1.bottom(), r2.bottom()));
-        if (newRect.width() < 0 || newRect.height() < 0)
-            return;
-    }
-
-    if (data.val == newRect)
-        return;
-
-    data.val = newRect;
-
-    it.value() = data;
-    d_ptr->m_doublePropertyManager->setValue(d_ptr->m_propertyToX[property], newRect.x());
-    d_ptr->m_doublePropertyManager->setValue(d_ptr->m_propertyToY[property], newRect.y());
-    d_ptr->m_doublePropertyManager->setValue(d_ptr->m_propertyToW[property], newRect.width());
-    d_ptr->m_doublePropertyManager->setValue(d_ptr->m_propertyToH[property], newRect.height());
-
-    emit propertyChanged(property);
-    emit valueChanged(property, data.val);
-}
-
-/**
-    Sets the given \a property's constraining rectangle to \a
-    constraint.
-
-    When setting the constraint, the current value is adjusted if
-    necessary (ensuring that the current rectangle value is inside the
-    constraint). In order to reset the constraint pass a null QRectF value.
-
-    \sa setValue(), constraint(), constraintChanged()
-*/
-void QtRectFPropertyManager::setConstraint(QtProperty *property, const QRectF &constraint)
-{
-    const QtRectFPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtRectFPropertyManagerPrivate::Data data = it.value();
-
-    QRectF newConstraint = constraint.normalized();
-    if (data.constraint == newConstraint)
-        return;
-
-    const QRectF oldVal = data.val;
-
-    data.constraint = newConstraint;
-
-    if (!data.constraint.isNull() && !data.constraint.contains(oldVal)) {
-        QRectF r1 = data.constraint;
-        QRectF r2 = data.val;
-
-        if (r2.width() > r1.width())
-            r2.setWidth(r1.width());
-        if (r2.height() > r1.height())
-            r2.setHeight(r1.height());
-        if (r2.left() < r1.left())
-            r2.moveLeft(r1.left());
-        else if (r2.right() > r1.right())
-            r2.moveRight(r1.right());
-        if (r2.top() < r1.top())
-            r2.moveTop(r1.top());
-        else if (r2.bottom() > r1.bottom())
-            r2.moveBottom(r1.bottom());
-
-        data.val = r2;
-    }
-
-    it.value() = data;
-
-    emit constraintChanged(property, data.constraint);
-
-    d_ptr->setConstraint(property, data.constraint, data.val);
-
-    if (data.val == oldVal)
-        return;
-
-    emit propertyChanged(property);
-    emit valueChanged(property, data.val);
-}
-
-/**
-    \fn void QtRectFPropertyManager::setDecimals(QtProperty *property, int prec)
-
-    Sets the precision of the given \a property to \a prec.
-
-    The valid decimal range is 0-13. The default is 2.
-
-    \sa decimals()
-*/
-void QtRectFPropertyManager::setDecimals(QtProperty *property, int prec)
-{
-    const QtRectFPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtRectFPropertyManagerPrivate::Data data = it.value();
-
-    if (prec > 13)
-        prec = 13;
-    else if (prec < 0)
-        prec = 0;
-
-    if (data.decimals == prec)
-        return;
-
-    data.decimals = prec;
-    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToX[property], prec);
-    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToY[property], prec);
-    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToW[property], prec);
-    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToH[property], prec);
-
-    it.value() = data;
-
-    emit decimalsChanged(property, data.decimals);
-}
-
-/**
-    \reimp
-*/
-void QtRectFPropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QtRectFPropertyManagerPrivate::Data();
-
-    QtProperty *xProp = d_ptr->m_doublePropertyManager->addProperty();
-    xProp->setPropertyName(tr("X"));
-    d_ptr->m_doublePropertyManager->setDecimals(xProp, decimals(property));
-    d_ptr->m_doublePropertyManager->setValue(xProp, 0);
-    d_ptr->m_propertyToX[property] = xProp;
-    d_ptr->m_xToProperty[xProp] = property;
-    property->addSubProperty(xProp);
-
-    QtProperty *yProp = d_ptr->m_doublePropertyManager->addProperty();
-    yProp->setPropertyName(tr("Y"));
-    d_ptr->m_doublePropertyManager->setDecimals(yProp, decimals(property));
-    d_ptr->m_doublePropertyManager->setValue(yProp, 0);
-    d_ptr->m_propertyToY[property] = yProp;
-    d_ptr->m_yToProperty[yProp] = property;
-    property->addSubProperty(yProp);
-
-    QtProperty *wProp = d_ptr->m_doublePropertyManager->addProperty();
-    wProp->setPropertyName(tr("Width"));
-    d_ptr->m_doublePropertyManager->setDecimals(wProp, decimals(property));
-    d_ptr->m_doublePropertyManager->setValue(wProp, 0);
-    d_ptr->m_doublePropertyManager->setMinimum(wProp, 0);
-    d_ptr->m_propertyToW[property] = wProp;
-    d_ptr->m_wToProperty[wProp] = property;
-    property->addSubProperty(wProp);
-
-    QtProperty *hProp = d_ptr->m_doublePropertyManager->addProperty();
-    hProp->setPropertyName(tr("Height"));
-    d_ptr->m_doublePropertyManager->setDecimals(hProp, decimals(property));
-    d_ptr->m_doublePropertyManager->setValue(hProp, 0);
-    d_ptr->m_doublePropertyManager->setMinimum(hProp, 0);
-    d_ptr->m_propertyToH[property] = hProp;
-    d_ptr->m_hToProperty[hProp] = property;
-    property->addSubProperty(hProp);
-}
-
-/**
-    \reimp
-*/
-void QtRectFPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    QtProperty *xProp = d_ptr->m_propertyToX[property];
-    if (xProp) {
-        d_ptr->m_xToProperty.remove(xProp);
-        delete xProp;
-    }
-    d_ptr->m_propertyToX.remove(property);
-
-    QtProperty *yProp = d_ptr->m_propertyToY[property];
-    if (yProp) {
-        d_ptr->m_yToProperty.remove(yProp);
-        delete yProp;
-    }
-    d_ptr->m_propertyToY.remove(property);
-
-    QtProperty *wProp = d_ptr->m_propertyToW[property];
-    if (wProp) {
-        d_ptr->m_wToProperty.remove(wProp);
-        delete wProp;
-    }
-    d_ptr->m_propertyToW.remove(property);
-
-    QtProperty *hProp = d_ptr->m_propertyToH[property];
-    if (hProp) {
-        d_ptr->m_hToProperty.remove(hProp);
-        delete hProp;
-    }
-    d_ptr->m_propertyToH.remove(property);
-
-    d_ptr->m_values.remove(property);
-}
-
-// QtEnumPropertyManager
-
-class QtEnumPropertyManagerPrivate
-{
-    QtEnumPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtEnumPropertyManager)
-public:
-
-    struct Data
-    {
-        Data() : val(-1) {}
-        int val;
-        QStringList enumNames;
-        QMap<int, QIcon> enumIcons;
-    };
-
-    typedef QMap<const QtProperty *, Data> PropertyValueMap;
-    PropertyValueMap m_values;
-};
-
-/**
-    \class QtEnumPropertyManager
-
-    \brief The QtEnumPropertyManager provides and manages enum properties.
-
-    Each enum property has an associated list of enum names which can
-    be retrieved using the enumNames() function, and set using the
-    corresponding setEnumNames() function. An enum property's value is
-    represented by an index in this list, and can be retrieved and set
-    using the value() and setValue() slots respectively.
-
-    Each enum value can also have an associated icon. The mapping from
-    values to icons can be set using the setEnumIcons() function and
-    queried with the enumIcons() function.
-
-    In addition, QtEnumPropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes. The enumNamesChanged() or enumIconsChanged() signal is emitted
-    whenever the list of enum names or icons is altered.
-
-    \sa QtAbstractPropertyManager, QtEnumEditorFactory
-*/
-
-/**
-    \fn void QtEnumPropertyManager::valueChanged(QtProperty *property, int value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    \fn void QtEnumPropertyManager::enumNamesChanged(QtProperty *property, const QStringList &names)
-
-    This signal is emitted whenever a property created by this manager
-    changes its enum names, passing a pointer to the \a property and
-    the new \a names as parameters.
-
-    \sa setEnumNames()
-*/
-
-/**
-    \fn void QtEnumPropertyManager::enumIconsChanged(QtProperty *property, const QMap<int, QIcon> &icons)
-
-    This signal is emitted whenever a property created by this manager
-    changes its enum icons, passing a pointer to the \a property and
-    the new mapping of values to \a icons as parameters.
-
-    \sa setEnumIcons()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtEnumPropertyManager::QtEnumPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtEnumPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtEnumPropertyManager::~QtEnumPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the given \a property's value which is an index in the
-    list returned by enumNames()
-
-    If the given property is not managed by this manager, this
-    function returns -1.
-
-    \sa enumNames(), setValue()
-*/
-int QtEnumPropertyManager::value(const QtProperty *property) const
-{
-    return getValue<int>(d_ptr->m_values, property, -1);
-}
-
-/**
-    Returns the given \a property's list of enum names.
-
-    \sa value(), setEnumNames()
-*/
-QStringList QtEnumPropertyManager::enumNames(const QtProperty *property) const
-{
-    return getData<QStringList>(d_ptr->m_values, &QtEnumPropertyManagerPrivate::Data::enumNames, property, QStringList());
-}
-
-/**
-    Returns the given \a property's map of enum values to their icons.
-
-    \sa value(), setEnumIcons()
-*/
-QMap<int, QIcon> QtEnumPropertyManager::enumIcons(const QtProperty *property) const
-{
-    return getData<QMap<int, QIcon> >(d_ptr->m_values, &QtEnumPropertyManagerPrivate::Data::enumIcons, property, QMap<int, QIcon>());
-}
-
-/**
-    \reimp
-*/
-QString QtEnumPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtEnumPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-
-    const QtEnumPropertyManagerPrivate::Data &data = it.value();
-
-    const int v = data.val;
-    if (v >= 0 && v < data.enumNames.count())
-        return data.enumNames.at(v);
-    return QString();
-}
-
-/**
-    \reimp
-*/
-QIcon QtEnumPropertyManager::valueIcon(const QtProperty *property) const
-{
-    const QtEnumPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QIcon();
-
-    const QtEnumPropertyManagerPrivate::Data &data = it.value();
-
-    const int v = data.val;
-    return data.enumIcons.value(v);
-}
-
-/**
-    \fn void QtEnumPropertyManager::setValue(QtProperty *property, int value)
-
-    Sets the value of the given  \a property to \a value.
-
-    The specified \a value must be less than the size of the given \a
-    property's enumNames() list, and larger than (or equal to) 0.
-
-    \sa value(), valueChanged()
-*/
-void QtEnumPropertyManager::setValue(QtProperty *property, int val)
-{
-    const QtEnumPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtEnumPropertyManagerPrivate::Data data = it.value();
-
-    if (val >= data.enumNames.count())
-        return;
-
-    if (val < 0 && data.enumNames.count() > 0)
-        return;
-
-    if (val < 0)
-        val = -1;
-
-    if (data.val == val)
-        return;
-
-    data.val = val;
-
-    it.value() = data;
-
-    emit propertyChanged(property);
-    emit valueChanged(property, data.val);
-}
-
-/**
-    Sets the given \a property's list of enum names to \a
-    enumNames. The \a property's current value is reset to 0
-    indicating the first item of the list.
-
-    If the specified \a enumNames list is empty, the \a property's
-    current value is set to -1.
-
-    \sa enumNames(), enumNamesChanged()
-*/
-void QtEnumPropertyManager::setEnumNames(QtProperty *property, const QStringList &enumNames)
-{
-    const QtEnumPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtEnumPropertyManagerPrivate::Data data = it.value();
-
-    if (data.enumNames == enumNames)
-        return;
-
-    data.enumNames = enumNames;
-
-    data.val = -1;
-
-    if (enumNames.count() > 0)
-        data.val = 0;
-
-    it.value() = data;
-
-    emit enumNamesChanged(property, data.enumNames);
-
-    emit propertyChanged(property);
-    emit valueChanged(property, data.val);
-}
-
-/**
-    Sets the given \a property's map of enum values to their icons to \a
-    enumIcons.
-
-    Each enum value can have associated icon. This association is represented with passed \a enumIcons map.
-
-    \sa enumNames(), enumNamesChanged()
-*/
-void QtEnumPropertyManager::setEnumIcons(QtProperty *property, const QMap<int, QIcon> &enumIcons)
-{
-    const QtEnumPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    it.value().enumIcons = enumIcons;
-
-    emit enumIconsChanged(property, it.value().enumIcons);
-
-    emit propertyChanged(property);
-}
-
-/**
-    \reimp
-*/
-void QtEnumPropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QtEnumPropertyManagerPrivate::Data();
-}
-
-/**
-    \reimp
-*/
-void QtEnumPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    d_ptr->m_values.remove(property);
-}
-
-// QtFlagPropertyManager
-
-class QtFlagPropertyManagerPrivate
-{
-    QtFlagPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtFlagPropertyManager)
-public:
-
-    void slotBoolChanged(QtProperty *property, bool value);
-    void slotPropertyDestroyed(QtProperty *property);
-
-    struct Data
-    {
-        Data() : val(-1) {}
-        int val;
-        QStringList flagNames;
-    };
-
-    typedef QMap<const QtProperty *, Data> PropertyValueMap;
-    PropertyValueMap m_values;
-
-    QtBoolPropertyManager *m_boolPropertyManager;
-
-    QMap<const QtProperty *, QList<QtProperty *> > m_propertyToFlags;
-
-    QMap<const QtProperty *, QtProperty *> m_flagToProperty;
-};
-
-void QtFlagPropertyManagerPrivate::slotBoolChanged(QtProperty *property, bool value)
-{
-    QtProperty *prop = m_flagToProperty.value(property, 0);
-    if (prop == 0)
-        return;
-
-    QListIterator<QtProperty *> itProp(m_propertyToFlags[prop]);
-    int level = 0;
-    while (itProp.hasNext()) {
-        QtProperty *p = itProp.next();
-        if (p == property) {
-            int v = m_values[prop].val;
-            if (value) {
-                v |= (1 << level);
-            } else {
-                v &= ~(1 << level);
-            }
-            q_ptr->setValue(prop, v);
-            return;
-        }
-        level++;
-    }
-}
-
-void QtFlagPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
-{
-    QtProperty *flagProperty = m_flagToProperty.value(property, 0);
-    if (flagProperty == 0)
-        return;
-
-    m_propertyToFlags[flagProperty].replace(m_propertyToFlags[flagProperty].indexOf(property), 0);
-    m_flagToProperty.remove(property);
-}
-
-/**
-    \class QtFlagPropertyManager
-
-    \brief The QtFlagPropertyManager provides and manages flag properties.
-
-    Each flag property has an associated list of flag names which can
-    be retrieved using the flagNames() function, and set using the
-    corresponding setFlagNames() function.
-
-    The flag manager provides properties with nested boolean
-    subproperties representing each flag, i.e. a flag property's value
-    is the binary combination of the subproperties' values. A
-    property's value can be retrieved and set using the value() and
-    setValue() slots respectively. The combination of flags is represented
-    by single int value - that's why it's possible to store up to
-    32 independent flags in one flag property.
-
-    The subproperties are created by a QtBoolPropertyManager object. This
-    manager can be retrieved using the subBoolPropertyManager() function. In
-    order to provide editing widgets for the subproperties in a
-    property browser widget, this manager must be associated with an
-    editor factory.
-
-    In addition, QtFlagPropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes, and the flagNamesChanged() signal which is emitted
-    whenever the list of flag names is altered.
-
-    \sa QtAbstractPropertyManager, QtBoolPropertyManager
-*/
-
-/**
-    \fn void QtFlagPropertyManager::valueChanged(QtProperty *property, int value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a  property and the new
-    \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    \fn void QtFlagPropertyManager::flagNamesChanged(QtProperty *property, const QStringList &names)
-
-    This signal is emitted whenever a property created by this manager
-    changes its flag names, passing a pointer to the \a property and the
-    new \a names as parameters.
-
-    \sa setFlagNames()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtFlagPropertyManager::QtFlagPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtFlagPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_boolPropertyManager = new QtBoolPropertyManager(this);
-    connect(d_ptr->m_boolPropertyManager, SIGNAL(valueChanged(QtProperty *, bool)),
-                this, SLOT(slotBoolChanged(QtProperty *, bool)));
-    connect(d_ptr->m_boolPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtFlagPropertyManager::~QtFlagPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the manager that produces the nested boolean subproperties
-    representing each flag.
-
-    In order to provide editing widgets for the subproperties in a
-    property browser widget, this manager must be associated with an
-    editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtBoolPropertyManager *QtFlagPropertyManager::subBoolPropertyManager() const
-{
-    return d_ptr->m_boolPropertyManager;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given property is not managed by this manager, this
-    function returns 0.
-
-    \sa flagNames(), setValue()
-*/
-int QtFlagPropertyManager::value(const QtProperty *property) const
-{
-    return getValue<int>(d_ptr->m_values, property, 0);
-}
-
-/**
-    Returns the given \a property's list of flag names.
-
-    \sa value(), setFlagNames()
-*/
-QStringList QtFlagPropertyManager::flagNames(const QtProperty *property) const
-{
-    return getData<QStringList>(d_ptr->m_values, &QtFlagPropertyManagerPrivate::Data::flagNames, property, QStringList());
-}
-
-/**
-    \reimp
-*/
-QString QtFlagPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtFlagPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-
-    const QtFlagPropertyManagerPrivate::Data &data = it.value();
-
-    QString str;
-    int level = 0;
-    const QChar bar = QLatin1Char('|');
-    const QStringList::const_iterator fncend = data.flagNames.constEnd();
-    for (QStringList::const_iterator it =  data.flagNames.constBegin(); it != fncend; ++it) {
-        if (data.val & (1 << level)) {
-            if (!str.isEmpty())
-                str += bar;
-            str += *it;
-        }
-
-        level++;
-    }
-    return str;
-}
-
-/**
-    \fn void QtFlagPropertyManager::setValue(QtProperty *property, int value)
-
-    Sets the value of the given \a property to \a value. Nested
-    properties are updated automatically.
-
-    The specified \a value must be less than the binary combination of
-    the property's flagNames() list size (i.e. less than 2\sup n,
-    where \c n is the size of the list) and larger than (or equal to)
-    0.
-
-    \sa value(), valueChanged()
-*/
-void QtFlagPropertyManager::setValue(QtProperty *property, int val)
-{
-    const QtFlagPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtFlagPropertyManagerPrivate::Data data = it.value();
-
-    if (data.val == val)
-        return;
-
-    if (val > (1 << data.flagNames.count()) - 1)
-        return;
-
-    if (val < 0)
-        return;
-
-    data.val = val;
-
-    it.value() = data;
-
-    QListIterator<QtProperty *> itProp(d_ptr->m_propertyToFlags[property]);
-    int level = 0;
-    while (itProp.hasNext()) {
-        QtProperty *prop = itProp.next();
-        if (prop)
-            d_ptr->m_boolPropertyManager->setValue(prop, val & (1 << level));
-        level++;
-    }
-
-    emit propertyChanged(property);
-    emit valueChanged(property, data.val);
-}
-
-/**
-    Sets the given \a property's list of flag names to \a flagNames. The
-    property's current value is reset to 0 indicating the first item
-    of the list.
-
-    \sa flagNames(), flagNamesChanged()
-*/
-void QtFlagPropertyManager::setFlagNames(QtProperty *property, const QStringList &flagNames)
-{
-    const QtFlagPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    QtFlagPropertyManagerPrivate::Data data = it.value();
-
-    if (data.flagNames == flagNames)
-        return;
-
-    data.flagNames = flagNames;
-    data.val = 0;
-
-    it.value() = data;
-
-    QListIterator<QtProperty *> itProp(d_ptr->m_propertyToFlags[property]);
-    while (itProp.hasNext()) {
-        QtProperty *prop = itProp.next();
-        if (prop) {
-            delete prop;
-            d_ptr->m_flagToProperty.remove(prop);
-        }
-    }
-    d_ptr->m_propertyToFlags[property].clear();
-
-    QStringListIterator itFlag(flagNames);
-    while (itFlag.hasNext()) {
-        const QString flagName = itFlag.next();
-        QtProperty *prop = d_ptr->m_boolPropertyManager->addProperty();
-        prop->setPropertyName(flagName);
-        property->addSubProperty(prop);
-        d_ptr->m_propertyToFlags[property].append(prop);
-        d_ptr->m_flagToProperty[prop] = property;
-    }
-
-    emit flagNamesChanged(property, data.flagNames);
-
-    emit propertyChanged(property);
-    emit valueChanged(property, data.val);
-}
-
-/**
-    \reimp
-*/
-void QtFlagPropertyManager::initializeProperty(QtProperty *property)
-{
-    d_ptr->m_values[property] = QtFlagPropertyManagerPrivate::Data();
-
-    d_ptr->m_propertyToFlags[property] = QList<QtProperty *>();
-}
-
-/**
-    \reimp
-*/
-void QtFlagPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    QListIterator<QtProperty *> itProp(d_ptr->m_propertyToFlags[property]);
-    while (itProp.hasNext()) {
-        QtProperty *prop = itProp.next();
-        if (prop) {
-            delete prop;
-            d_ptr->m_flagToProperty.remove(prop);
-        }
-    }
-    d_ptr->m_propertyToFlags.remove(property);
-
-    d_ptr->m_values.remove(property);
-}
-
-// QtSizePolicyPropertyManager
-
-class QtSizePolicyPropertyManagerPrivate
-{
-    QtSizePolicyPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtSizePolicyPropertyManager)
-public:
-
-    QtSizePolicyPropertyManagerPrivate();
-
-    void slotIntChanged(QtProperty *property, int value);
-    void slotEnumChanged(QtProperty *property, int value);
-    void slotPropertyDestroyed(QtProperty *property);
-
-    typedef QMap<const QtProperty *, QSizePolicy> PropertyValueMap;
-    PropertyValueMap m_values;
-
-    QtIntPropertyManager *m_intPropertyManager;
-    QtEnumPropertyManager *m_enumPropertyManager;
-
-    QMap<const QtProperty *, QtProperty *> m_propertyToHPolicy;
-    QMap<const QtProperty *, QtProperty *> m_propertyToVPolicy;
-    QMap<const QtProperty *, QtProperty *> m_propertyToHStretch;
-    QMap<const QtProperty *, QtProperty *> m_propertyToVStretch;
-
-    QMap<const QtProperty *, QtProperty *> m_hPolicyToProperty;
-    QMap<const QtProperty *, QtProperty *> m_vPolicyToProperty;
-    QMap<const QtProperty *, QtProperty *> m_hStretchToProperty;
-    QMap<const QtProperty *, QtProperty *> m_vStretchToProperty;
-};
-
-QtSizePolicyPropertyManagerPrivate::QtSizePolicyPropertyManagerPrivate()
-{
-}
-
-void QtSizePolicyPropertyManagerPrivate::slotIntChanged(QtProperty *property, int value)
-{
-    if (QtProperty *prop = m_hStretchToProperty.value(property, 0)) {
-        QSizePolicy sp = m_values[prop];
-        sp.setHorizontalStretch(value);
-        q_ptr->setValue(prop, sp);
-    } else if (QtProperty *prop = m_vStretchToProperty.value(property, 0)) {
-        QSizePolicy sp = m_values[prop];
-        sp.setVerticalStretch(value);
-        q_ptr->setValue(prop, sp);
-    }
-}
-
-void QtSizePolicyPropertyManagerPrivate::slotEnumChanged(QtProperty *property, int value)
-{
-    if (QtProperty *prop = m_hPolicyToProperty.value(property, 0)) {
-        QSizePolicy sp = m_values[prop];
-        sp.setHorizontalPolicy(metaEnumProvider()->indexToSizePolicy(value));
-        q_ptr->setValue(prop, sp);
-    } else if (QtProperty *prop = m_vPolicyToProperty.value(property, 0)) {
-        QSizePolicy sp = m_values[prop];
-        sp.setVerticalPolicy(metaEnumProvider()->indexToSizePolicy(value));
-        q_ptr->setValue(prop, sp);
-    }
-}
-
-void QtSizePolicyPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
-{
-    if (QtProperty *pointProp = m_hStretchToProperty.value(property, 0)) {
-        m_propertyToHStretch[pointProp] = 0;
-        m_hStretchToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_vStretchToProperty.value(property, 0)) {
-        m_propertyToVStretch[pointProp] = 0;
-        m_vStretchToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_hPolicyToProperty.value(property, 0)) {
-        m_propertyToHPolicy[pointProp] = 0;
-        m_hPolicyToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_vPolicyToProperty.value(property, 0)) {
-        m_propertyToVPolicy[pointProp] = 0;
-        m_vPolicyToProperty.remove(property);
-    }
-}
-
-/**
-    \class QtSizePolicyPropertyManager
-
-    \brief The QtSizePolicyPropertyManager provides and manages QSizePolicy properties.
-
-    A size policy property has nested \e horizontalPolicy, \e
-    verticalPolicy, \e horizontalStretch and \e verticalStretch
-    subproperties. The top-level property's value can be retrieved
-    using the value() function, and set using the setValue() slot.
-
-    The subproperties are created by QtIntPropertyManager and QtEnumPropertyManager
-    objects. These managers can be retrieved using the subIntPropertyManager()
-    and subEnumPropertyManager() functions respectively. In order to provide
-    editing widgets for the subproperties in a property browser widget,
-    these managers must be associated with editor factories.
-
-    In addition, QtSizePolicyPropertyManager provides the valueChanged()
-    signal which is emitted whenever a property created by this
-    manager changes.
-
-    \sa QtAbstractPropertyManager, QtIntPropertyManager, QtEnumPropertyManager
-*/
-
-/**
-    \fn void QtSizePolicyPropertyManager::valueChanged(QtProperty *property, const QSizePolicy &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the
-    new \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtSizePolicyPropertyManager::QtSizePolicyPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtSizePolicyPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_intPropertyManager = new QtIntPropertyManager(this);
-    connect(d_ptr->m_intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotIntChanged(QtProperty *, int)));
-    d_ptr->m_enumPropertyManager = new QtEnumPropertyManager(this);
-    connect(d_ptr->m_enumPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotEnumChanged(QtProperty *, int)));
-
-    connect(d_ptr->m_intPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-    connect(d_ptr->m_enumPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtSizePolicyPropertyManager::~QtSizePolicyPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the manager that creates the nested \e horizontalStretch
-    and \e verticalStretch subproperties.
-
-    In order to provide editing widgets for the mentioned subproperties
-    in a property browser widget, this manager must be associated with
-    an editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtIntPropertyManager *QtSizePolicyPropertyManager::subIntPropertyManager() const
-{
-    return d_ptr->m_intPropertyManager;
-}
-
-/**
-    Returns the manager that creates the nested \e horizontalPolicy
-    and \e verticalPolicy subproperties.
-
-    In order to provide editing widgets for the mentioned subproperties
-    in a property browser widget, this manager must be associated with
-    an editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtEnumPropertyManager *QtSizePolicyPropertyManager::subEnumPropertyManager() const
-{
-    return d_ptr->m_enumPropertyManager;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given property is not managed by this manager, this
-    function returns the default size policy.
-
-    \sa setValue()
-*/
-QSizePolicy QtSizePolicyPropertyManager::value(const QtProperty *property) const
-{
-    return d_ptr->m_values.value(property, QSizePolicy());
-}
-
-/**
-    \reimp
-*/
-QString QtSizePolicyPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtSizePolicyPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-
-    const QSizePolicy sp = it.value();
-    const QtMetaEnumProvider *mep = metaEnumProvider();
-    const int hIndex = mep->sizePolicyToIndex(sp.horizontalPolicy());
-    const int vIndex = mep->sizePolicyToIndex(sp.verticalPolicy());
-    //! Unknown size policy on reading invalid uic3 files
-    const QString hPolicy = hIndex != -1 ? mep->policyEnumNames().at(hIndex) : tr("<Invalid>");
-    const QString vPolicy = vIndex != -1 ? mep->policyEnumNames().at(vIndex) : tr("<Invalid>");
-    const QString str = tr("[%1, %2, %3, %4]").arg(hPolicy, vPolicy).arg(sp.horizontalStretch()).arg(sp.verticalStretch());
-    return str;
-}
-
-/**
-    \fn void QtSizePolicyPropertyManager::setValue(QtProperty *property, const QSizePolicy &value)
-
-    Sets the value of the given \a property to \a value. Nested
-    properties are updated automatically.
-
-    \sa value(), valueChanged()
-*/
-void QtSizePolicyPropertyManager::setValue(QtProperty *property, const QSizePolicy &val)
-{
-    const QtSizePolicyPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    if (it.value() == val)
-        return;
-
-    it.value() = val;
-
-    d_ptr->m_enumPropertyManager->setValue(d_ptr->m_propertyToHPolicy[property],
-                metaEnumProvider()->sizePolicyToIndex(val.horizontalPolicy()));
-    d_ptr->m_enumPropertyManager->setValue(d_ptr->m_propertyToVPolicy[property],
-                metaEnumProvider()->sizePolicyToIndex(val.verticalPolicy()));
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToHStretch[property],
-                val.horizontalStretch());
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToVStretch[property],
-                val.verticalStretch());
-
-    emit propertyChanged(property);
-    emit valueChanged(property, val);
-}
-
-/**
-    \reimp
-*/
-void QtSizePolicyPropertyManager::initializeProperty(QtProperty *property)
-{
-    QSizePolicy val;
-    d_ptr->m_values[property] = val;
-
-    QtProperty *hPolicyProp = d_ptr->m_enumPropertyManager->addProperty();
-    hPolicyProp->setPropertyName(tr("Horizontal Policy"));
-    d_ptr->m_enumPropertyManager->setEnumNames(hPolicyProp, metaEnumProvider()->policyEnumNames());
-    d_ptr->m_enumPropertyManager->setValue(hPolicyProp,
-                metaEnumProvider()->sizePolicyToIndex(val.horizontalPolicy()));
-    d_ptr->m_propertyToHPolicy[property] = hPolicyProp;
-    d_ptr->m_hPolicyToProperty[hPolicyProp] = property;
-    property->addSubProperty(hPolicyProp);
-
-    QtProperty *vPolicyProp = d_ptr->m_enumPropertyManager->addProperty();
-    vPolicyProp->setPropertyName(tr("Vertical Policy"));
-    d_ptr->m_enumPropertyManager->setEnumNames(vPolicyProp, metaEnumProvider()->policyEnumNames());
-    d_ptr->m_enumPropertyManager->setValue(vPolicyProp,
-                metaEnumProvider()->sizePolicyToIndex(val.verticalPolicy()));
-    d_ptr->m_propertyToVPolicy[property] = vPolicyProp;
-    d_ptr->m_vPolicyToProperty[vPolicyProp] = property;
-    property->addSubProperty(vPolicyProp);
-
-    QtProperty *hStretchProp = d_ptr->m_intPropertyManager->addProperty();
-    hStretchProp->setPropertyName(tr("Horizontal Stretch"));
-    d_ptr->m_intPropertyManager->setValue(hStretchProp, val.horizontalStretch());
-    d_ptr->m_intPropertyManager->setRange(hStretchProp, 0, 0xff);
-    d_ptr->m_propertyToHStretch[property] = hStretchProp;
-    d_ptr->m_hStretchToProperty[hStretchProp] = property;
-    property->addSubProperty(hStretchProp);
-
-    QtProperty *vStretchProp = d_ptr->m_intPropertyManager->addProperty();
-    vStretchProp->setPropertyName(tr("Vertical Stretch"));
-    d_ptr->m_intPropertyManager->setValue(vStretchProp, val.verticalStretch());
-    d_ptr->m_intPropertyManager->setRange(vStretchProp, 0, 0xff);
-    d_ptr->m_propertyToVStretch[property] = vStretchProp;
-    d_ptr->m_vStretchToProperty[vStretchProp] = property;
-    property->addSubProperty(vStretchProp);
-
-}
-
-/**
-    \reimp
-*/
-void QtSizePolicyPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    QtProperty *hPolicyProp = d_ptr->m_propertyToHPolicy[property];
-    if (hPolicyProp) {
-        d_ptr->m_hPolicyToProperty.remove(hPolicyProp);
-        delete hPolicyProp;
-    }
-    d_ptr->m_propertyToHPolicy.remove(property);
-
-    QtProperty *vPolicyProp = d_ptr->m_propertyToVPolicy[property];
-    if (vPolicyProp) {
-        d_ptr->m_vPolicyToProperty.remove(vPolicyProp);
-        delete vPolicyProp;
-    }
-    d_ptr->m_propertyToVPolicy.remove(property);
-
-    QtProperty *hStretchProp = d_ptr->m_propertyToHStretch[property];
-    if (hStretchProp) {
-        d_ptr->m_hStretchToProperty.remove(hStretchProp);
-        delete hStretchProp;
-    }
-    d_ptr->m_propertyToHStretch.remove(property);
-
-    QtProperty *vStretchProp = d_ptr->m_propertyToVStretch[property];
-    if (vStretchProp) {
-        d_ptr->m_vStretchToProperty.remove(vStretchProp);
-        delete vStretchProp;
-    }
-    d_ptr->m_propertyToVStretch.remove(property);
-
-    d_ptr->m_values.remove(property);
-}
-
-// QtFontPropertyManager:
-// QtFontPropertyManagerPrivate has a mechanism for reacting
-// to QApplication::fontDatabaseChanged() [4.5], which is emitted
-// when someone loads an application font. The signals are compressed
-// using a timer with interval 0, which then causes the family
-// enumeration manager to re-set its strings and index values
-// for each property.
-
-Q_GLOBAL_STATIC(QFontDatabase, fontDatabase)
-
-class QtFontPropertyManagerPrivate
-{
-    QtFontPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtFontPropertyManager)
-public:
-
-    QtFontPropertyManagerPrivate();
-
-    void slotIntChanged(QtProperty *property, int value);
-    void slotEnumChanged(QtProperty *property, int value);
-    void slotBoolChanged(QtProperty *property, bool value);
-    void slotPropertyDestroyed(QtProperty *property);
-    void slotFontDatabaseChanged();
-    void slotFontDatabaseDelayedChange();
-
-    QStringList m_familyNames;
-
-    typedef QMap<const QtProperty *, QFont> PropertyValueMap;
-    PropertyValueMap m_values;
-
-    QtIntPropertyManager *m_intPropertyManager;
-    QtEnumPropertyManager *m_enumPropertyManager;
-    QtBoolPropertyManager *m_boolPropertyManager;
-
-    QMap<const QtProperty *, QtProperty *> m_propertyToFamily;
-    QMap<const QtProperty *, QtProperty *> m_propertyToPointSize;
-    QMap<const QtProperty *, QtProperty *> m_propertyToBold;
-    QMap<const QtProperty *, QtProperty *> m_propertyToItalic;
-    QMap<const QtProperty *, QtProperty *> m_propertyToUnderline;
-    QMap<const QtProperty *, QtProperty *> m_propertyToStrikeOut;
-    QMap<const QtProperty *, QtProperty *> m_propertyToKerning;
-
-    QMap<const QtProperty *, QtProperty *> m_familyToProperty;
-    QMap<const QtProperty *, QtProperty *> m_pointSizeToProperty;
-    QMap<const QtProperty *, QtProperty *> m_boldToProperty;
-    QMap<const QtProperty *, QtProperty *> m_italicToProperty;
-    QMap<const QtProperty *, QtProperty *> m_underlineToProperty;
-    QMap<const QtProperty *, QtProperty *> m_strikeOutToProperty;
-    QMap<const QtProperty *, QtProperty *> m_kerningToProperty;
-
-    bool m_settingValue;
-    QTimer *m_fontDatabaseChangeTimer;
-};
-
-QtFontPropertyManagerPrivate::QtFontPropertyManagerPrivate() :
-    m_settingValue(false),
-    m_fontDatabaseChangeTimer(0)
-{
-}
-
-void QtFontPropertyManagerPrivate::slotIntChanged(QtProperty *property, int value)
-{
-    if (m_settingValue)
-        return;
-    if (QtProperty *prop = m_pointSizeToProperty.value(property, 0)) {
-        QFont f = m_values[prop];
-        f.setPointSize(value);
-        q_ptr->setValue(prop, f);
-    }
-}
-
-void QtFontPropertyManagerPrivate::slotEnumChanged(QtProperty *property, int value)
-{
-    if (m_settingValue)
-        return;
-    if (QtProperty *prop = m_familyToProperty.value(property, 0)) {
-        QFont f = m_values[prop];
-        f.setFamily(m_familyNames.at(value));
-        q_ptr->setValue(prop, f);
-    }
-}
-
-void QtFontPropertyManagerPrivate::slotBoolChanged(QtProperty *property, bool value)
-{
-    if (m_settingValue)
-        return;
-    if (QtProperty *prop = m_boldToProperty.value(property, 0)) {
-        QFont f = m_values[prop];
-        f.setBold(value);
-        q_ptr->setValue(prop, f);
-    } else if (QtProperty *prop = m_italicToProperty.value(property, 0)) {
-        QFont f = m_values[prop];
-        f.setItalic(value);
-        q_ptr->setValue(prop, f);
-    } else if (QtProperty *prop = m_underlineToProperty.value(property, 0)) {
-        QFont f = m_values[prop];
-        f.setUnderline(value);
-        q_ptr->setValue(prop, f);
-    } else if (QtProperty *prop = m_strikeOutToProperty.value(property, 0)) {
-        QFont f = m_values[prop];
-        f.setStrikeOut(value);
-        q_ptr->setValue(prop, f);
-    } else if (QtProperty *prop = m_kerningToProperty.value(property, 0)) {
-        QFont f = m_values[prop];
-        f.setKerning(value);
-        q_ptr->setValue(prop, f);
-    }
-}
-
-void QtFontPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
-{
-    if (QtProperty *pointProp = m_pointSizeToProperty.value(property, 0)) {
-        m_propertyToPointSize[pointProp] = 0;
-        m_pointSizeToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_familyToProperty.value(property, 0)) {
-        m_propertyToFamily[pointProp] = 0;
-        m_familyToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_boldToProperty.value(property, 0)) {
-        m_propertyToBold[pointProp] = 0;
-        m_boldToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_italicToProperty.value(property, 0)) {
-        m_propertyToItalic[pointProp] = 0;
-        m_italicToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_underlineToProperty.value(property, 0)) {
-        m_propertyToUnderline[pointProp] = 0;
-        m_underlineToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_strikeOutToProperty.value(property, 0)) {
-        m_propertyToStrikeOut[pointProp] = 0;
-        m_strikeOutToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_kerningToProperty.value(property, 0)) {
-        m_propertyToKerning[pointProp] = 0;
-        m_kerningToProperty.remove(property);
-    }
-}
-
-void  QtFontPropertyManagerPrivate::slotFontDatabaseChanged()
-{
-    if (!m_fontDatabaseChangeTimer) {
-        m_fontDatabaseChangeTimer = new QTimer(q_ptr);
-        m_fontDatabaseChangeTimer->setInterval(0);
-        m_fontDatabaseChangeTimer->setSingleShot(true);
-        QObject::connect(m_fontDatabaseChangeTimer, SIGNAL(timeout()), q_ptr, SLOT(slotFontDatabaseDelayedChange()));
-    }
-    if (!m_fontDatabaseChangeTimer->isActive())
-        m_fontDatabaseChangeTimer->start();
-}
-
-void QtFontPropertyManagerPrivate::slotFontDatabaseDelayedChange()
-{
-    typedef QMap<const QtProperty *, QtProperty *> PropertyPropertyMap;
-    // rescan available font names
-    const QStringList oldFamilies = m_familyNames;
-    m_familyNames = fontDatabase()->families();
-
-    // Adapt all existing properties
-    if (!m_propertyToFamily.empty()) {
-        PropertyPropertyMap::const_iterator cend = m_propertyToFamily.constEnd();
-        for (PropertyPropertyMap::const_iterator it = m_propertyToFamily.constBegin(); it != cend; ++it) {
-            QtProperty *familyProp = it.value();
-            const int oldIdx = m_enumPropertyManager->value(familyProp);
-            int newIdx = m_familyNames.indexOf(oldFamilies.at(oldIdx));
-            if (newIdx < 0)
-                newIdx = 0;
-            m_enumPropertyManager->setEnumNames(familyProp, m_familyNames);
-            m_enumPropertyManager->setValue(familyProp, newIdx);
-        }
-    }
-}
-
-/**
-    \class QtFontPropertyManager
-
-    \brief The QtFontPropertyManager provides and manages QFont properties.
-
-    A font property has nested \e family, \e pointSize, \e bold, \e
-    italic, \e underline, \e strikeOut and \e kerning subproperties. The top-level
-    property's value can be retrieved using the value() function, and
-    set using the setValue() slot.
-
-    The subproperties are created by QtIntPropertyManager, QtEnumPropertyManager and
-    QtBoolPropertyManager objects. These managers can be retrieved using the
-    corresponding subIntPropertyManager(), subEnumPropertyManager() and
-    subBoolPropertyManager() functions. In order to provide editing widgets
-    for the subproperties in a property browser widget, these managers
-    must be associated with editor factories.
-
-    In addition, QtFontPropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes.
-
-    \sa QtAbstractPropertyManager, QtEnumPropertyManager, QtIntPropertyManager, QtBoolPropertyManager
-*/
-
-/**
-    \fn void QtFontPropertyManager::valueChanged(QtProperty *property, const QFont &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the
-    new \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtFontPropertyManager::QtFontPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtFontPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-#if QT_VERSION >= 0x040500
-    QObject::connect(qApp, SIGNAL(fontDatabaseChanged()), this, SLOT(slotFontDatabaseChanged()));
-#endif
-
-    d_ptr->m_intPropertyManager = new QtIntPropertyManager(this);
-    connect(d_ptr->m_intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotIntChanged(QtProperty *, int)));
-    d_ptr->m_enumPropertyManager = new QtEnumPropertyManager(this);
-    connect(d_ptr->m_enumPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotEnumChanged(QtProperty *, int)));
-    d_ptr->m_boolPropertyManager = new QtBoolPropertyManager(this);
-    connect(d_ptr->m_boolPropertyManager, SIGNAL(valueChanged(QtProperty *, bool)),
-                this, SLOT(slotBoolChanged(QtProperty *, bool)));
-
-    connect(d_ptr->m_intPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-    connect(d_ptr->m_enumPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-    connect(d_ptr->m_boolPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtFontPropertyManager::~QtFontPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the manager that creates the \e pointSize subproperty.
-
-    In order to provide editing widgets for the \e pointSize property
-    in a property browser widget, this manager must be associated
-    with an editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtIntPropertyManager *QtFontPropertyManager::subIntPropertyManager() const
-{
-    return d_ptr->m_intPropertyManager;
-}
-
-/**
-    Returns the manager that create the \e family subproperty.
-
-    In order to provide editing widgets for the \e family property
-    in a property browser widget, this manager must be associated
-    with an editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtEnumPropertyManager *QtFontPropertyManager::subEnumPropertyManager() const
-{
-    return d_ptr->m_enumPropertyManager;
-}
-
-/**
-    Returns the manager that creates the  \e bold, \e italic, \e underline,
-    \e strikeOut and \e kerning subproperties.
-
-    In order to provide editing widgets for the mentioned properties
-    in a property browser widget, this manager must be associated with
-    an editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtBoolPropertyManager *QtFontPropertyManager::subBoolPropertyManager() const
-{
-    return d_ptr->m_boolPropertyManager;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given property is not managed by this manager, this
-    function returns a font object that uses the application's default
-    font.
-
-    \sa setValue()
-*/
-QFont QtFontPropertyManager::value(const QtProperty *property) const
-{
-    return d_ptr->m_values.value(property, QFont());
-}
-
-/**
-    \reimp
-*/
-QString QtFontPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtFontPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-
-    return QtPropertyBrowserUtils::fontValueText(it.value());
-}
-
-/**
-    \reimp
-*/
-QIcon QtFontPropertyManager::valueIcon(const QtProperty *property) const
-{
-    const QtFontPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QIcon();
-
-    return QtPropertyBrowserUtils::fontValueIcon(it.value());
-}
-
-/**
-    \fn void QtFontPropertyManager::setValue(QtProperty *property, const QFont &value)
-
-    Sets the value of the given \a property to \a value. Nested
-    properties are updated automatically.
-
-    \sa value(), valueChanged()
-*/
-void QtFontPropertyManager::setValue(QtProperty *property, const QFont &val)
-{
-    const QtFontPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    const QFont oldVal = it.value();
-    if (oldVal == val && oldVal.resolve() == val.resolve())
-        return;
-
-    it.value() = val;
-
-    int idx = d_ptr->m_familyNames.indexOf(val.family());
-    if (idx == -1)
-        idx = 0;
-    bool settingValue = d_ptr->m_settingValue;
-    d_ptr->m_settingValue = true;
-    d_ptr->m_enumPropertyManager->setValue(d_ptr->m_propertyToFamily[property], idx);
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToPointSize[property], val.pointSize());
-    d_ptr->m_boolPropertyManager->setValue(d_ptr->m_propertyToBold[property], val.bold());
-    d_ptr->m_boolPropertyManager->setValue(d_ptr->m_propertyToItalic[property], val.italic());
-    d_ptr->m_boolPropertyManager->setValue(d_ptr->m_propertyToUnderline[property], val.underline());
-    d_ptr->m_boolPropertyManager->setValue(d_ptr->m_propertyToStrikeOut[property], val.strikeOut());
-    d_ptr->m_boolPropertyManager->setValue(d_ptr->m_propertyToKerning[property], val.kerning());
-    d_ptr->m_settingValue = settingValue;
-
-    emit propertyChanged(property);
-    emit valueChanged(property, val);
-}
-
-/**
-    \reimp
-*/
-void QtFontPropertyManager::initializeProperty(QtProperty *property)
-{
-    QFont val;
-    d_ptr->m_values[property] = val;
-
-    QtProperty *familyProp = d_ptr->m_enumPropertyManager->addProperty();
-    familyProp->setPropertyName(tr("Family"));
-    if (d_ptr->m_familyNames.empty())
-        d_ptr->m_familyNames = fontDatabase()->families();
-    d_ptr->m_enumPropertyManager->setEnumNames(familyProp, d_ptr->m_familyNames);
-    int idx = d_ptr->m_familyNames.indexOf(val.family());
-    if (idx == -1)
-        idx = 0;
-    d_ptr->m_enumPropertyManager->setValue(familyProp, idx);
-    d_ptr->m_propertyToFamily[property] = familyProp;
-    d_ptr->m_familyToProperty[familyProp] = property;
-    property->addSubProperty(familyProp);
-
-    QtProperty *pointSizeProp = d_ptr->m_intPropertyManager->addProperty();
-    pointSizeProp->setPropertyName(tr("Point Size"));
-    d_ptr->m_intPropertyManager->setValue(pointSizeProp, val.pointSize());
-    d_ptr->m_intPropertyManager->setMinimum(pointSizeProp, 1);
-    d_ptr->m_propertyToPointSize[property] = pointSizeProp;
-    d_ptr->m_pointSizeToProperty[pointSizeProp] = property;
-    property->addSubProperty(pointSizeProp);
-
-    QtProperty *boldProp = d_ptr->m_boolPropertyManager->addProperty();
-    boldProp->setPropertyName(tr("Bold"));
-    d_ptr->m_boolPropertyManager->setValue(boldProp, val.bold());
-    d_ptr->m_propertyToBold[property] = boldProp;
-    d_ptr->m_boldToProperty[boldProp] = property;
-    property->addSubProperty(boldProp);
-
-    QtProperty *italicProp = d_ptr->m_boolPropertyManager->addProperty();
-    italicProp->setPropertyName(tr("Italic"));
-    d_ptr->m_boolPropertyManager->setValue(italicProp, val.italic());
-    d_ptr->m_propertyToItalic[property] = italicProp;
-    d_ptr->m_italicToProperty[italicProp] = property;
-    property->addSubProperty(italicProp);
-
-    QtProperty *underlineProp = d_ptr->m_boolPropertyManager->addProperty();
-    underlineProp->setPropertyName(tr("Underline"));
-    d_ptr->m_boolPropertyManager->setValue(underlineProp, val.underline());
-    d_ptr->m_propertyToUnderline[property] = underlineProp;
-    d_ptr->m_underlineToProperty[underlineProp] = property;
-    property->addSubProperty(underlineProp);
-
-    QtProperty *strikeOutProp = d_ptr->m_boolPropertyManager->addProperty();
-    strikeOutProp->setPropertyName(tr("Strikeout"));
-    d_ptr->m_boolPropertyManager->setValue(strikeOutProp, val.strikeOut());
-    d_ptr->m_propertyToStrikeOut[property] = strikeOutProp;
-    d_ptr->m_strikeOutToProperty[strikeOutProp] = property;
-    property->addSubProperty(strikeOutProp);
-
-    QtProperty *kerningProp = d_ptr->m_boolPropertyManager->addProperty();
-    kerningProp->setPropertyName(tr("Kerning"));
-    d_ptr->m_boolPropertyManager->setValue(kerningProp, val.kerning());
-    d_ptr->m_propertyToKerning[property] = kerningProp;
-    d_ptr->m_kerningToProperty[kerningProp] = property;
-    property->addSubProperty(kerningProp);
-}
-
-/**
-    \reimp
-*/
-void QtFontPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    QtProperty *familyProp = d_ptr->m_propertyToFamily[property];
-    if (familyProp) {
-        d_ptr->m_familyToProperty.remove(familyProp);
-        delete familyProp;
-    }
-    d_ptr->m_propertyToFamily.remove(property);
-
-    QtProperty *pointSizeProp = d_ptr->m_propertyToPointSize[property];
-    if (pointSizeProp) {
-        d_ptr->m_pointSizeToProperty.remove(pointSizeProp);
-        delete pointSizeProp;
-    }
-    d_ptr->m_propertyToPointSize.remove(property);
-
-    QtProperty *boldProp = d_ptr->m_propertyToBold[property];
-    if (boldProp) {
-        d_ptr->m_boldToProperty.remove(boldProp);
-        delete boldProp;
-    }
-    d_ptr->m_propertyToBold.remove(property);
-
-    QtProperty *italicProp = d_ptr->m_propertyToItalic[property];
-    if (italicProp) {
-        d_ptr->m_italicToProperty.remove(italicProp);
-        delete italicProp;
-    }
-    d_ptr->m_propertyToItalic.remove(property);
-
-    QtProperty *underlineProp = d_ptr->m_propertyToUnderline[property];
-    if (underlineProp) {
-        d_ptr->m_underlineToProperty.remove(underlineProp);
-        delete underlineProp;
-    }
-    d_ptr->m_propertyToUnderline.remove(property);
-
-    QtProperty *strikeOutProp = d_ptr->m_propertyToStrikeOut[property];
-    if (strikeOutProp) {
-        d_ptr->m_strikeOutToProperty.remove(strikeOutProp);
-        delete strikeOutProp;
-    }
-    d_ptr->m_propertyToStrikeOut.remove(property);
-
-    QtProperty *kerningProp = d_ptr->m_propertyToKerning[property];
-    if (kerningProp) {
-        d_ptr->m_kerningToProperty.remove(kerningProp);
-        delete kerningProp;
-    }
-    d_ptr->m_propertyToKerning.remove(property);
-
-    d_ptr->m_values.remove(property);
-}
-
-// QtColorPropertyManager
-
-class QtColorPropertyManagerPrivate
-{
-    QtColorPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtColorPropertyManager)
-public:
-
-    void slotIntChanged(QtProperty *property, int value);
-    void slotPropertyDestroyed(QtProperty *property);
-
-    typedef QMap<const QtProperty *, QColor> PropertyValueMap;
-    PropertyValueMap m_values;
-
-    QtIntPropertyManager *m_intPropertyManager;
-
-    QMap<const QtProperty *, QtProperty *> m_propertyToR;
-    QMap<const QtProperty *, QtProperty *> m_propertyToG;
-    QMap<const QtProperty *, QtProperty *> m_propertyToB;
-    QMap<const QtProperty *, QtProperty *> m_propertyToA;
-
-    QMap<const QtProperty *, QtProperty *> m_rToProperty;
-    QMap<const QtProperty *, QtProperty *> m_gToProperty;
-    QMap<const QtProperty *, QtProperty *> m_bToProperty;
-    QMap<const QtProperty *, QtProperty *> m_aToProperty;
-};
-
-void QtColorPropertyManagerPrivate::slotIntChanged(QtProperty *property, int value)
-{
-    if (QtProperty *prop = m_rToProperty.value(property, 0)) {
-        QColor c = m_values[prop];
-        c.setRed(value);
-        q_ptr->setValue(prop, c);
-    } else if (QtProperty *prop = m_gToProperty.value(property, 0)) {
-        QColor c = m_values[prop];
-        c.setGreen(value);
-        q_ptr->setValue(prop, c);
-    } else if (QtProperty *prop = m_bToProperty.value(property, 0)) {
-        QColor c = m_values[prop];
-        c.setBlue(value);
-        q_ptr->setValue(prop, c);
-    } else if (QtProperty *prop = m_aToProperty.value(property, 0)) {
-        QColor c = m_values[prop];
-        c.setAlpha(value);
-        q_ptr->setValue(prop, c);
-    }
-}
-
-void QtColorPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
-{
-    if (QtProperty *pointProp = m_rToProperty.value(property, 0)) {
-        m_propertyToR[pointProp] = 0;
-        m_rToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_gToProperty.value(property, 0)) {
-        m_propertyToG[pointProp] = 0;
-        m_gToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_bToProperty.value(property, 0)) {
-        m_propertyToB[pointProp] = 0;
-        m_bToProperty.remove(property);
-    } else if (QtProperty *pointProp = m_aToProperty.value(property, 0)) {
-        m_propertyToA[pointProp] = 0;
-        m_aToProperty.remove(property);
-    }
-}
-
-/**
-    \class QtColorPropertyManager
-
-    \brief The QtColorPropertyManager provides and manages QColor properties.
-
-    A color property has nested \e red, \e green and \e blue
-    subproperties. The top-level property's value can be retrieved
-    using the value() function, and set using the setValue() slot.
-
-    The subproperties are created by a QtIntPropertyManager object. This
-    manager can be retrieved using the subIntPropertyManager() function.  In
-    order to provide editing widgets for the subproperties in a
-    property browser widget, this manager must be associated with an
-    editor factory.
-
-    In addition, QtColorPropertyManager provides the valueChanged() signal
-    which is emitted whenever a property created by this manager
-    changes.
-
-    \sa QtAbstractPropertyManager, QtAbstractPropertyBrowser, QtIntPropertyManager
-*/
-
-/**
-    \fn void QtColorPropertyManager::valueChanged(QtProperty *property, const QColor &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtColorPropertyManager::QtColorPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtColorPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_intPropertyManager = new QtIntPropertyManager(this);
-    connect(d_ptr->m_intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotIntChanged(QtProperty *, int)));
-
-    connect(d_ptr->m_intPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
-                this, SLOT(slotPropertyDestroyed(QtProperty *)));
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtColorPropertyManager::~QtColorPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the manager that produces the nested \e red, \e green and
-    \e blue subproperties.
-
-    In order to provide editing widgets for the subproperties in a
-    property browser widget, this manager must be associated with an
-    editor factory.
-
-    \sa QtAbstractPropertyBrowser::setFactoryForManager()
-*/
-QtIntPropertyManager *QtColorPropertyManager::subIntPropertyManager() const
-{
-    return d_ptr->m_intPropertyManager;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by \e this manager, this
-    function returns an invalid color.
-
-    \sa setValue()
-*/
-QColor QtColorPropertyManager::value(const QtProperty *property) const
-{
-    return d_ptr->m_values.value(property, QColor());
-}
-
-/**
-    \reimp
-*/
-
-QString QtColorPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtColorPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-
-    return QtPropertyBrowserUtils::colorValueText(it.value());
-}
-
-/**
-    \reimp
-*/
-
-QIcon QtColorPropertyManager::valueIcon(const QtProperty *property) const
-{
-    const QtColorPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QIcon();
-    return QtPropertyBrowserUtils::brushValueIcon(QBrush(it.value()));
-}
-
-/**
-    \fn void QtColorPropertyManager::setValue(QtProperty *property, const QColor &value)
-
-    Sets the value of the given \a property to \a value.  Nested
-    properties are updated automatically.
-
-    \sa value(), valueChanged()
-*/
-void QtColorPropertyManager::setValue(QtProperty *property, const QColor &val)
-{
-    const QtColorPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    if (it.value() == val)
-        return;
-
-    it.value() = val;
-
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToR[property], val.red());
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToG[property], val.green());
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToB[property], val.blue());
-    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToA[property], val.alpha());
-
-    emit propertyChanged(property);
-    emit valueChanged(property, val);
-}
-
-/**
-    \reimp
-*/
-void QtColorPropertyManager::initializeProperty(QtProperty *property)
-{
-    QColor val;
-    d_ptr->m_values[property] = val;
-
-    QtProperty *rProp = d_ptr->m_intPropertyManager->addProperty();
-    rProp->setPropertyName(tr("Red"));
-    d_ptr->m_intPropertyManager->setValue(rProp, val.red());
-    d_ptr->m_intPropertyManager->setRange(rProp, 0, 0xFF);
-    d_ptr->m_propertyToR[property] = rProp;
-    d_ptr->m_rToProperty[rProp] = property;
-    property->addSubProperty(rProp);
-
-    QtProperty *gProp = d_ptr->m_intPropertyManager->addProperty();
-    gProp->setPropertyName(tr("Green"));
-    d_ptr->m_intPropertyManager->setValue(gProp, val.green());
-    d_ptr->m_intPropertyManager->setRange(gProp, 0, 0xFF);
-    d_ptr->m_propertyToG[property] = gProp;
-    d_ptr->m_gToProperty[gProp] = property;
-    property->addSubProperty(gProp);
-
-    QtProperty *bProp = d_ptr->m_intPropertyManager->addProperty();
-    bProp->setPropertyName(tr("Blue"));
-    d_ptr->m_intPropertyManager->setValue(bProp, val.blue());
-    d_ptr->m_intPropertyManager->setRange(bProp, 0, 0xFF);
-    d_ptr->m_propertyToB[property] = bProp;
-    d_ptr->m_bToProperty[bProp] = property;
-    property->addSubProperty(bProp);
-
-    QtProperty *aProp = d_ptr->m_intPropertyManager->addProperty();
-    aProp->setPropertyName(tr("Alpha"));
-    d_ptr->m_intPropertyManager->setValue(aProp, val.alpha());
-    d_ptr->m_intPropertyManager->setRange(aProp, 0, 0xFF);
-    d_ptr->m_propertyToA[property] = aProp;
-    d_ptr->m_aToProperty[aProp] = property;
-    property->addSubProperty(aProp);
-}
-
-/**
-    \reimp
-*/
-void QtColorPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    QtProperty *rProp = d_ptr->m_propertyToR[property];
-    if (rProp) {
-        d_ptr->m_rToProperty.remove(rProp);
-        delete rProp;
-    }
-    d_ptr->m_propertyToR.remove(property);
-
-    QtProperty *gProp = d_ptr->m_propertyToG[property];
-    if (gProp) {
-        d_ptr->m_gToProperty.remove(gProp);
-        delete gProp;
-    }
-    d_ptr->m_propertyToG.remove(property);
-
-    QtProperty *bProp = d_ptr->m_propertyToB[property];
-    if (bProp) {
-        d_ptr->m_bToProperty.remove(bProp);
-        delete bProp;
-    }
-    d_ptr->m_propertyToB.remove(property);
-
-    QtProperty *aProp = d_ptr->m_propertyToA[property];
-    if (aProp) {
-        d_ptr->m_aToProperty.remove(aProp);
-        delete aProp;
-    }
-    d_ptr->m_propertyToA.remove(property);
-
-    d_ptr->m_values.remove(property);
-}
-
-// QtCursorPropertyManager
-
-Q_GLOBAL_STATIC(QtCursorDatabase, cursorDatabase)
-
-class QtCursorPropertyManagerPrivate
-{
-    QtCursorPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtCursorPropertyManager)
-public:
-    typedef QMap<const QtProperty *, QCursor> PropertyValueMap;
-    PropertyValueMap m_values;
-};
-
-/**
-    \class QtCursorPropertyManager
-
-    \brief The QtCursorPropertyManager provides and manages QCursor properties.
-
-    A cursor property has a current value which can be
-    retrieved using the value() function, and set using the setValue()
-    slot. In addition, QtCursorPropertyManager provides the
-    valueChanged() signal which is emitted whenever a property created
-    by this manager changes.
-
-    \sa QtAbstractPropertyManager
-*/
-
-/**
-    \fn void QtCursorPropertyManager::valueChanged(QtProperty *property, const QCursor &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the new
-    \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtCursorPropertyManager::QtCursorPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtCursorPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtCursorPropertyManager::~QtCursorPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by this manager, this
-    function returns a default QCursor object.
-
-    \sa setValue()
-*/
-#ifndef QT_NO_CURSOR
-QCursor QtCursorPropertyManager::value(const QtProperty *property) const
-{
-    return d_ptr->m_values.value(property, QCursor());
-}
-#endif
-
-/**
-    \reimp
-*/
-QString QtCursorPropertyManager::valueText(const QtProperty *property) const
-{
-   const QtCursorPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QString();
-
-    return cursorDatabase()->cursorToShapeName(it.value());
-}
-
-/**
-    \reimp
-*/
-QIcon QtCursorPropertyManager::valueIcon(const QtProperty *property) const
-{
-    const QtCursorPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
-    if (it == d_ptr->m_values.constEnd())
-        return QIcon();
-
-    return cursorDatabase()->cursorToShapeIcon(it.value());
-}
-
-/**
-    \fn void QtCursorPropertyManager::setValue(QtProperty *property, const QCursor &value)
-
-    Sets the value of the given \a property to \a value.
-
-    \sa value(), valueChanged()
-*/
-void QtCursorPropertyManager::setValue(QtProperty *property, const QCursor &value)
-{
-#ifndef QT_NO_CURSOR
-    const QtCursorPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
-    if (it == d_ptr->m_values.end())
-        return;
-
-    if (it.value().shape() == value.shape() && value.shape() != Qt::BitmapCursor)
-        return;
-
-    it.value() = value;
-
-    emit propertyChanged(property);
-    emit valueChanged(property, value);
-#endif
-}
-
-/**
-    \reimp
-*/
-void QtCursorPropertyManager::initializeProperty(QtProperty *property)
-{
-#ifndef QT_NO_CURSOR
-    d_ptr->m_values[property] = QCursor();
-#endif
-}
-
-/**
-    \reimp
-*/
-void QtCursorPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    d_ptr->m_values.remove(property);
-}
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#include "moc_qtpropertymanager.cpp"
-#include "qtpropertymanager.moc"
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qtpropertymanager.h"
+#include "qtpropertybrowserutils_p.h"
+#include <QtCore/QDateTime>
+#include <QtCore/QLocale>
+#include <QtCore/QMap>
+#include <QtCore/QTimer>
+#include <QtGui/QIcon>
+#include <QtCore/QMetaEnum>
+#include <QtGui/QFontDatabase>
+#include <QtGui/QStyleOption>
+#include <QtGui/QStyle>
+#include <QtGui/QApplication>
+#include <QtGui/QPainter>
+#include <QtGui/QLabel>
+
+#include <limits.h>
+#include <float.h>
+#include <math.h>
+
+#if defined(Q_CC_MSVC)
+#    pragma warning(disable: 4786) /* MS VS 6: truncating debug info after 255 characters */
+#endif
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+template <class PrivateData, class Value>
+static void setSimpleMinimumData(PrivateData *data, const Value &minVal)
+{
+    data->minVal = minVal;
+    if (data->maxVal < data->minVal)
+        data->maxVal = data->minVal;
+
+    if (data->val < data->minVal)
+        data->val = data->minVal;
+}
+
+template <class PrivateData, class Value>
+static void setSimpleMaximumData(PrivateData *data, const Value &maxVal)
+{
+    data->maxVal = maxVal;
+    if (data->minVal > data->maxVal)
+        data->minVal = data->maxVal;
+
+    if (data->val > data->maxVal)
+        data->val = data->maxVal;
+}
+
+template <class PrivateData, class Value>
+static void setSizeMinimumData(PrivateData *data, const Value &newMinVal)
+{
+    data->minVal = newMinVal;
+    if (data->maxVal.width() < data->minVal.width())
+        data->maxVal.setWidth(data->minVal.width());
+    if (data->maxVal.height() < data->minVal.height())
+        data->maxVal.setHeight(data->minVal.height());
+
+    if (data->val.width() < data->minVal.width())
+        data->val.setWidth(data->minVal.width());
+    if (data->val.height() < data->minVal.height())
+        data->val.setHeight(data->minVal.height());
+}
+
+template <class PrivateData, class Value>
+static void setSizeMaximumData(PrivateData *data, const Value &newMaxVal)
+{
+    data->maxVal = newMaxVal;
+    if (data->minVal.width() > data->maxVal.width())
+        data->minVal.setWidth(data->maxVal.width());
+    if (data->minVal.height() > data->maxVal.height())
+        data->minVal.setHeight(data->maxVal.height());
+
+    if (data->val.width() > data->maxVal.width())
+        data->val.setWidth(data->maxVal.width());
+    if (data->val.height() > data->maxVal.height())
+        data->val.setHeight(data->maxVal.height());
+}
+
+template <class SizeValue>
+static SizeValue qBoundSize(const SizeValue &minVal, const SizeValue &val, const SizeValue &maxVal)
+{
+    SizeValue croppedVal = val;
+    if (minVal.width() > val.width())
+        croppedVal.setWidth(minVal.width());
+    else if (maxVal.width() < val.width())
+        croppedVal.setWidth(maxVal.width());
+
+    if (minVal.height() > val.height())
+        croppedVal.setHeight(minVal.height());
+    else if (maxVal.height() < val.height())
+        croppedVal.setHeight(maxVal.height());
+
+    return croppedVal;
+}
+
+// Match the exact signature of qBound for VS 6.
+QSize qBound(QSize minVal, QSize val, QSize maxVal)
+{
+    return qBoundSize(minVal, val, maxVal);
+}
+
+QSizeF qBound(QSizeF minVal, QSizeF val, QSizeF maxVal)
+{
+    return qBoundSize(minVal, val, maxVal);
+}
+
+namespace {
+
+namespace {
+template <class Value>
+void orderBorders(Value &minVal, Value &maxVal)
+{
+    if (minVal > maxVal)
+        qSwap(minVal, maxVal);
+}
+
+template <class Value>
+static void orderSizeBorders(Value &minVal, Value &maxVal)
+{
+    Value fromSize = minVal;
+    Value toSize = maxVal;
+    if (fromSize.width() > toSize.width()) {
+        fromSize.setWidth(maxVal.width());
+        toSize.setWidth(minVal.width());
+    }
+    if (fromSize.height() > toSize.height()) {
+        fromSize.setHeight(maxVal.height());
+        toSize.setHeight(minVal.height());
+    }
+    minVal = fromSize;
+    maxVal = toSize;
+}
+
+void orderBorders(QSize &minVal, QSize &maxVal)
+{
+    orderSizeBorders(minVal, maxVal);
+}
+
+void orderBorders(QSizeF &minVal, QSizeF &maxVal)
+{
+    orderSizeBorders(minVal, maxVal);
+}
+
+}
+}
+////////
+
+template <class Value, class PrivateData>
+static Value getData(const QMap<const QtProperty *, PrivateData> &propertyMap,
+            Value PrivateData::*data,
+            const QtProperty *property, const Value &defaultValue = Value())
+{
+    typedef QMap<const QtProperty *, PrivateData> PropertyToData;
+    typedef Q_TYPENAME PropertyToData::const_iterator PropertyToDataConstIterator;
+    const PropertyToDataConstIterator it = propertyMap.constFind(property);
+    if (it == propertyMap.constEnd())
+        return defaultValue;
+    return it.value().*data;
+}
+
+template <class Value, class PrivateData>
+static Value getValue(const QMap<const QtProperty *, PrivateData> &propertyMap,
+            const QtProperty *property, const Value &defaultValue = Value())
+{
+    return getData<Value>(propertyMap, &PrivateData::val, property, defaultValue);
+}
+
+template <class Value, class PrivateData>
+static Value getMinimum(const QMap<const QtProperty *, PrivateData> &propertyMap,
+            const QtProperty *property, const Value &defaultValue = Value())
+{
+    return getData<Value>(propertyMap, &PrivateData::minVal, property, defaultValue);
+}
+
+template <class Value, class PrivateData>
+static Value getMaximum(const QMap<const QtProperty *, PrivateData> &propertyMap,
+            const QtProperty *property, const Value &defaultValue = Value())
+{
+    return getData<Value>(propertyMap, &PrivateData::maxVal, property, defaultValue);
+}
+
+template <class ValueChangeParameter, class Value, class PropertyManager>
+static void setSimpleValue(QMap<const QtProperty *, Value> &propertyMap,
+            PropertyManager *manager,
+            void (PropertyManager::*propertyChangedSignal)(QtProperty *),
+            void (PropertyManager::*valueChangedSignal)(QtProperty *, ValueChangeParameter),
+            QtProperty *property, const Value &val)
+{
+    typedef QMap<const QtProperty *, Value> PropertyToData;
+    typedef Q_TYPENAME PropertyToData::iterator PropertyToDataIterator;
+    const PropertyToDataIterator it = propertyMap.find(property);
+    if (it == propertyMap.end())
+        return;
+
+    if (it.value() == val)
+        return;
+
+    it.value() = val;
+
+    emit (manager->*propertyChangedSignal)(property);
+    emit (manager->*valueChangedSignal)(property, val);
+}
+
+template <class ValueChangeParameter, class PropertyManagerPrivate, class PropertyManager, class Value>
+static void setValueInRange(PropertyManager *manager, PropertyManagerPrivate *managerPrivate,
+            void (PropertyManager::*propertyChangedSignal)(QtProperty *),
+            void (PropertyManager::*valueChangedSignal)(QtProperty *, ValueChangeParameter),
+            QtProperty *property, const Value &val,
+            void (PropertyManagerPrivate::*setSubPropertyValue)(QtProperty *, ValueChangeParameter))
+{
+    typedef Q_TYPENAME PropertyManagerPrivate::Data PrivateData;
+    typedef QMap<const QtProperty *, PrivateData> PropertyToData;
+    typedef Q_TYPENAME PropertyToData::iterator PropertyToDataIterator;
+    const PropertyToDataIterator it = managerPrivate->m_values.find(property);
+    if (it == managerPrivate->m_values.end())
+        return;
+
+    PrivateData &data = it.value();
+
+    if (data.val == val)
+        return;
+
+    const Value oldVal = data.val;
+
+    data.val = qBound(data.minVal, val, data.maxVal);
+
+    if (data.val == oldVal)
+        return;
+
+    if (setSubPropertyValue)
+        (managerPrivate->*setSubPropertyValue)(property, data.val);
+
+    emit (manager->*propertyChangedSignal)(property);
+    emit (manager->*valueChangedSignal)(property, data.val);
+}
+
+template <class ValueChangeParameter, class PropertyManagerPrivate, class PropertyManager, class Value>
+static void setBorderValues(PropertyManager *manager, PropertyManagerPrivate *managerPrivate,
+            void (PropertyManager::*propertyChangedSignal)(QtProperty *),
+            void (PropertyManager::*valueChangedSignal)(QtProperty *, ValueChangeParameter),
+            void (PropertyManager::*rangeChangedSignal)(QtProperty *, ValueChangeParameter, ValueChangeParameter),
+            QtProperty *property, const Value &minVal, const Value &maxVal,
+            void (PropertyManagerPrivate::*setSubPropertyRange)(QtProperty *,
+                    ValueChangeParameter, ValueChangeParameter, ValueChangeParameter))
+{
+    typedef Q_TYPENAME PropertyManagerPrivate::Data PrivateData;
+    typedef QMap<const QtProperty *, PrivateData> PropertyToData;
+    typedef Q_TYPENAME PropertyToData::iterator PropertyToDataIterator;
+    const PropertyToDataIterator it = managerPrivate->m_values.find(property);
+    if (it == managerPrivate->m_values.end())
+        return;
+
+    Value fromVal = minVal;
+    Value toVal = maxVal;
+    orderBorders(fromVal, toVal);
+
+    PrivateData &data = it.value();
+
+    if (data.minVal == fromVal && data.maxVal == toVal)
+        return;
+
+    const Value oldVal = data.val;
+
+    data.setMinimumValue(fromVal);
+    data.setMaximumValue(toVal);
+
+    emit (manager->*rangeChangedSignal)(property, data.minVal, data.maxVal);
+
+    if (setSubPropertyRange)
+        (managerPrivate->*setSubPropertyRange)(property, data.minVal, data.maxVal, data.val);
+
+    if (data.val == oldVal)
+        return;
+
+    emit (manager->*propertyChangedSignal)(property);
+    emit (manager->*valueChangedSignal)(property, data.val);
+}
+
+template <class ValueChangeParameter, class PropertyManagerPrivate, class PropertyManager, class Value, class PrivateData>
+static void setBorderValue(PropertyManager *manager, PropertyManagerPrivate *managerPrivate,
+            void (PropertyManager::*propertyChangedSignal)(QtProperty *),
+            void (PropertyManager::*valueChangedSignal)(QtProperty *, ValueChangeParameter),
+            void (PropertyManager::*rangeChangedSignal)(QtProperty *, ValueChangeParameter, ValueChangeParameter),
+            QtProperty *property,
+            Value (PrivateData::*getRangeVal)() const,
+            void (PrivateData::*setRangeVal)(ValueChangeParameter), const Value &borderVal,
+            void (PropertyManagerPrivate::*setSubPropertyRange)(QtProperty *,
+                    ValueChangeParameter, ValueChangeParameter, ValueChangeParameter))
+{
+    typedef QMap<const QtProperty *, PrivateData> PropertyToData;
+    typedef Q_TYPENAME PropertyToData::iterator PropertyToDataIterator;
+    const PropertyToDataIterator it = managerPrivate->m_values.find(property);
+    if (it == managerPrivate->m_values.end())
+        return;
+
+    PrivateData &data = it.value();
+
+    if ((data.*getRangeVal)() == borderVal)
+        return;
+
+    const Value oldVal = data.val;
+
+    (data.*setRangeVal)(borderVal);
+
+    emit (manager->*rangeChangedSignal)(property, data.minVal, data.maxVal);
+
+    if (setSubPropertyRange)
+        (managerPrivate->*setSubPropertyRange)(property, data.minVal, data.maxVal, data.val);
+
+    if (data.val == oldVal)
+        return;
+
+    emit (manager->*propertyChangedSignal)(property);
+    emit (manager->*valueChangedSignal)(property, data.val);
+}
+
+template <class ValueChangeParameter, class PropertyManagerPrivate, class PropertyManager, class Value, class PrivateData>
+static void setMinimumValue(PropertyManager *manager, PropertyManagerPrivate *managerPrivate,
+            void (PropertyManager::*propertyChangedSignal)(QtProperty *),
+            void (PropertyManager::*valueChangedSignal)(QtProperty *, ValueChangeParameter),
+            void (PropertyManager::*rangeChangedSignal)(QtProperty *, ValueChangeParameter, ValueChangeParameter),
+            QtProperty *property, const Value &minVal)
+{
+    void (PropertyManagerPrivate::*setSubPropertyRange)(QtProperty *,
+                    ValueChangeParameter, ValueChangeParameter, ValueChangeParameter) = 0;
+    setBorderValue<ValueChangeParameter, PropertyManagerPrivate, PropertyManager, Value, PrivateData>(manager, managerPrivate,
+            propertyChangedSignal, valueChangedSignal, rangeChangedSignal,
+            property, &PropertyManagerPrivate::Data::minimumValue, &PropertyManagerPrivate::Data::setMinimumValue, minVal, setSubPropertyRange);
+}
+
+template <class ValueChangeParameter, class PropertyManagerPrivate, class PropertyManager, class Value, class PrivateData>
+static void setMaximumValue(PropertyManager *manager, PropertyManagerPrivate *managerPrivate,
+            void (PropertyManager::*propertyChangedSignal)(QtProperty *),
+            void (PropertyManager::*valueChangedSignal)(QtProperty *, ValueChangeParameter),
+            void (PropertyManager::*rangeChangedSignal)(QtProperty *, ValueChangeParameter, ValueChangeParameter),
+            QtProperty *property, const Value &maxVal)
+{
+    void (PropertyManagerPrivate::*setSubPropertyRange)(QtProperty *,
+                    ValueChangeParameter, ValueChangeParameter, ValueChangeParameter) = 0;
+    setBorderValue<ValueChangeParameter, PropertyManagerPrivate, PropertyManager, Value, PrivateData>(manager, managerPrivate,
+            propertyChangedSignal, valueChangedSignal, rangeChangedSignal,
+            property, &PropertyManagerPrivate::Data::maximumValue, &PropertyManagerPrivate::Data::setMaximumValue, maxVal, setSubPropertyRange);
+}
+
+class QtMetaEnumWrapper : public QObject
+{
+    Q_OBJECT
+    Q_PROPERTY(QSizePolicy::Policy policy READ policy)
+public:
+    QSizePolicy::Policy policy() const { return QSizePolicy::Ignored; }
+private:
+    QtMetaEnumWrapper(QObject *parent) : QObject(parent) {}
+};
+
+class QtMetaEnumProvider
+{
+public:
+    QtMetaEnumProvider();
+
+    QStringList policyEnumNames() const { return m_policyEnumNames; }
+    QStringList languageEnumNames() const { return m_languageEnumNames; }
+    QStringList countryEnumNames(QLocale::Language language) const { return m_countryEnumNames.value(language); }
+
+    QSizePolicy::Policy indexToSizePolicy(int index) const;
+    int sizePolicyToIndex(QSizePolicy::Policy policy) const;
+
+    void indexToLocale(int languageIndex, int countryIndex, QLocale::Language *language, QLocale::Country *country) const;
+    void localeToIndex(QLocale::Language language, QLocale::Country country, int *languageIndex, int *countryIndex) const;
+
+private:
+    void initLocale();
+
+    QStringList m_policyEnumNames;
+    QStringList m_languageEnumNames;
+    QMap<QLocale::Language, QStringList> m_countryEnumNames;
+    QMap<int, QLocale::Language> m_indexToLanguage;
+    QMap<QLocale::Language, int> m_languageToIndex;
+    QMap<int, QMap<int, QLocale::Country> > m_indexToCountry;
+    QMap<QLocale::Language, QMap<QLocale::Country, int> > m_countryToIndex;
+    QMetaEnum m_policyEnum;
+};
+
+#if QT_VERSION < 0x040300
+
+static QList<QLocale::Country> countriesForLanguage(QLocale::Language language)
+{
+    QList<QLocale::Country> countries;
+    QLocale::Country country = QLocale::AnyCountry;
+    while (country <= QLocale::LastCountry) {
+        QLocale locale(language, country);
+        if (locale.language() == language && !countries.contains(locale.country()))
+            countries << locale.country();
+        country = (QLocale::Country)((uint)country + 1); // ++country
+    }
+    return countries;
+}
+
+#endif
+
+static QList<QLocale::Country> sortCountries(const QList<QLocale::Country> &countries)
+{
+    QMultiMap<QString, QLocale::Country> nameToCountry;
+    QListIterator<QLocale::Country> itCountry(countries);
+    while (itCountry.hasNext()) {
+        QLocale::Country country = itCountry.next();
+        nameToCountry.insert(QLocale::countryToString(country), country);
+    }
+    return nameToCountry.values();
+}
+
+void QtMetaEnumProvider::initLocale()
+{
+    QMultiMap<QString, QLocale::Language> nameToLanguage;
+    QLocale::Language language = QLocale::C;
+    while (language <= QLocale::LastLanguage) {
+        QLocale locale(language);
+        if (locale.language() == language)
+            nameToLanguage.insert(QLocale::languageToString(language), language);
+        language = (QLocale::Language)((uint)language + 1); // ++language
+    }
+
+    const QLocale system = QLocale::system();
+    if (!nameToLanguage.contains(QLocale::languageToString(system.language())))
+        nameToLanguage.insert(QLocale::languageToString(system.language()), system.language());
+
+    QList<QLocale::Language> languages = nameToLanguage.values();
+    QListIterator<QLocale::Language> itLang(languages);
+    while (itLang.hasNext()) {
+        QLocale::Language language = itLang.next();
+        QList<QLocale::Country> countries;
+#if QT_VERSION < 0x040300
+        countries = countriesForLanguage(language);
+#else
+        countries = QLocale::countriesForLanguage(language);
+#endif
+        if (countries.isEmpty() && language == system.language())
+            countries << system.country();
+
+        if (!countries.isEmpty() && !m_languageToIndex.contains(language)) {
+            countries = sortCountries(countries);
+            int langIdx = m_languageEnumNames.count();
+            m_indexToLanguage[langIdx] = language;
+            m_languageToIndex[language] = langIdx;
+            QStringList countryNames;
+            QListIterator<QLocale::Country> it(countries);
+            int countryIdx = 0;
+            while (it.hasNext()) {
+                QLocale::Country country = it.next();
+                countryNames << QLocale::countryToString(country);
+                m_indexToCountry[langIdx][countryIdx] = country;
+                m_countryToIndex[language][country] = countryIdx;
+                ++countryIdx;
+            }
+            m_languageEnumNames << QLocale::languageToString(language);
+            m_countryEnumNames[language] = countryNames;
+        }
+    }
+}
+
+QtMetaEnumProvider::QtMetaEnumProvider()
+{
+    QMetaProperty p;
+
+    p = QtMetaEnumWrapper::staticMetaObject.property(
+                QtMetaEnumWrapper::staticMetaObject.propertyOffset() + 0);
+    m_policyEnum = p.enumerator();
+    const int keyCount = m_policyEnum.keyCount();
+    for (int i = 0; i < keyCount; i++)
+        m_policyEnumNames << QLatin1String(m_policyEnum.key(i));
+
+    initLocale();
+}
+
+QSizePolicy::Policy QtMetaEnumProvider::indexToSizePolicy(int index) const
+{
+    return static_cast<QSizePolicy::Policy>(m_policyEnum.value(index));
+}
+
+int QtMetaEnumProvider::sizePolicyToIndex(QSizePolicy::Policy policy) const
+{
+     const int keyCount = m_policyEnum.keyCount();
+    for (int i = 0; i < keyCount; i++)
+        if (indexToSizePolicy(i) == policy)
+            return i;
+    return -1;
+}
+
+void QtMetaEnumProvider::indexToLocale(int languageIndex, int countryIndex, QLocale::Language *language, QLocale::Country *country) const
+{
+    QLocale::Language l = QLocale::C;
+    QLocale::Country c = QLocale::AnyCountry;
+    if (m_indexToLanguage.contains(languageIndex)) {
+        l = m_indexToLanguage[languageIndex];
+        if (m_indexToCountry.contains(languageIndex) && m_indexToCountry[languageIndex].contains(countryIndex))
+            c = m_indexToCountry[languageIndex][countryIndex];
+    }
+    if (language)
+        *language = l;
+    if (country)
+        *country = c;
+}
+
+void QtMetaEnumProvider::localeToIndex(QLocale::Language language, QLocale::Country country, int *languageIndex, int *countryIndex) const
+{
+    int l = -1;
+    int c = -1;
+    if (m_languageToIndex.contains(language)) {
+        l = m_languageToIndex[language];
+        if (m_countryToIndex.contains(language) && m_countryToIndex[language].contains(country))
+            c = m_countryToIndex[language][country];
+    }
+
+    if (languageIndex)
+        *languageIndex = l;
+    if (countryIndex)
+        *countryIndex = c;
+}
+
+Q_GLOBAL_STATIC(QtMetaEnumProvider, metaEnumProvider)
+
+// QtGroupPropertyManager
+
+/**
+    \class QtGroupPropertyManager
+
+    \brief The QtGroupPropertyManager provides and manages group properties.
+
+    This class is intended to provide a grouping element without any value.
+
+    \sa QtAbstractPropertyManager
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtGroupPropertyManager::QtGroupPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtGroupPropertyManager::~QtGroupPropertyManager()
+{
+
+}
+
+/**
+    \reimp
+*/
+bool QtGroupPropertyManager::hasValue(const QtProperty *property) const
+{
+    Q_UNUSED(property)
+    return false;
+}
+
+/**
+    \reimp
+*/
+void QtGroupPropertyManager::initializeProperty(QtProperty *property)
+{
+    Q_UNUSED(property)
+}
+
+/**
+    \reimp
+*/
+void QtGroupPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    Q_UNUSED(property)
+}
+
+// QtIntPropertyManager
+
+class QtIntPropertyManagerPrivate
+{
+    QtIntPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtIntPropertyManager)
+public:
+
+    struct Data
+    {
+        Data() : val(0), minVal(-INT_MAX), maxVal(INT_MAX), singleStep(1) {}
+        int val;
+        int minVal;
+        int maxVal;
+        int singleStep;
+        int minimumValue() const { return minVal; }
+        int maximumValue() const { return maxVal; }
+        void setMinimumValue(int newMinVal) { setSimpleMinimumData(this, newMinVal); }
+        void setMaximumValue(int newMaxVal) { setSimpleMaximumData(this, newMaxVal); }
+    };
+
+    typedef QMap<const QtProperty *, Data> PropertyValueMap;
+    PropertyValueMap m_values;
+};
+
+/**
+    \class QtIntPropertyManager
+
+    \brief The QtIntPropertyManager provides and manages int properties.
+
+    An int property has a current value, and a range specifying the
+    valid values. The range is defined by a minimum and a maximum
+    value.
+
+    The property's value and range can be retrieved using the value(),
+    minimum() and maximum() functions, and can be set using the
+    setValue(), setMinimum() and setMaximum() slots. Alternatively,
+    the range can be defined in one go using the setRange() slot.
+
+    In addition, QtIntPropertyManager provides the valueChanged() signal which
+    is emitted whenever a property created by this manager changes,
+    and the rangeChanged() signal which is emitted whenever such a
+    property changes its range of valid values.
+
+    \sa QtAbstractPropertyManager, QtSpinBoxFactory, QtSliderFactory, QtScrollBarFactory
+*/
+
+/**
+    \fn void QtIntPropertyManager::valueChanged(QtProperty *property, int value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    \fn void QtIntPropertyManager::rangeChanged(QtProperty *property, int minimum, int maximum)
+
+    This signal is emitted whenever a property created by this manager
+    changes its range of valid values, passing a pointer to the
+    \a property and the new \a minimum and \a maximum values.
+
+    \sa setRange()
+*/
+
+/**
+    \fn void QtIntPropertyManager::singleStepChanged(QtProperty *property, int step)
+
+    This signal is emitted whenever a property created by this manager
+    changes its single step property, passing a pointer to the
+    \a property and the new \a step value
+
+    \sa setSingleStep()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtIntPropertyManager::QtIntPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtIntPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtIntPropertyManager::~QtIntPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given property is not managed by this manager, this
+    function returns 0.
+
+    \sa setValue()
+*/
+int QtIntPropertyManager::value(const QtProperty *property) const
+{
+    return getValue<int>(d_ptr->m_values, property, 0);
+}
+
+/**
+    Returns the given \a property's minimum value.
+
+    \sa setMinimum(), maximum(), setRange()
+*/
+int QtIntPropertyManager::minimum(const QtProperty *property) const
+{
+    return getMinimum<int>(d_ptr->m_values, property, 0);
+}
+
+/**
+    Returns the given \a property's maximum value.
+
+    \sa setMaximum(), minimum(), setRange()
+*/
+int QtIntPropertyManager::maximum(const QtProperty *property) const
+{
+    return getMaximum<int>(d_ptr->m_values, property, 0);
+}
+
+/**
+    Returns the given \a property's step value.
+
+    The step is typically used to increment or decrement a property value while pressing an arrow key.
+
+    \sa setSingleStep()
+*/
+int QtIntPropertyManager::singleStep(const QtProperty *property) const
+{
+    return getData<int>(d_ptr->m_values, &QtIntPropertyManagerPrivate::Data::singleStep, property, 0);
+}
+
+/**
+    \reimp
+*/
+QString QtIntPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtIntPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    return QString::number(it.value().val);
+}
+
+/**
+    \fn void QtIntPropertyManager::setValue(QtProperty *property, int value)
+
+    Sets the value of the given \a property to \a value.
+
+    If the specified \a value is not valid according to the given \a
+    property's range, the \a value is adjusted to the nearest valid
+    value within the range.
+
+    \sa value(), setRange(), valueChanged()
+*/
+void QtIntPropertyManager::setValue(QtProperty *property, int val)
+{
+    void (QtIntPropertyManagerPrivate::*setSubPropertyValue)(QtProperty *, int) = 0;
+    setValueInRange<int, QtIntPropertyManagerPrivate, QtIntPropertyManager, int>(this, d_ptr,
+                &QtIntPropertyManager::propertyChanged,
+                &QtIntPropertyManager::valueChanged,
+                property, val, setSubPropertyValue);
+}
+
+/**
+    Sets the minimum value for the given \a property to \a minVal.
+
+    When setting the minimum value, the maximum and current values are
+    adjusted if necessary (ensuring that the range remains valid and
+    that the current value is within the range).
+
+    \sa minimum(), setRange(), rangeChanged()
+*/
+void QtIntPropertyManager::setMinimum(QtProperty *property, int minVal)
+{
+    setMinimumValue<int, QtIntPropertyManagerPrivate, QtIntPropertyManager, int, QtIntPropertyManagerPrivate::Data>(this, d_ptr,
+                &QtIntPropertyManager::propertyChanged,
+                &QtIntPropertyManager::valueChanged,
+                &QtIntPropertyManager::rangeChanged,
+                property, minVal);
+}
+
+/**
+    Sets the maximum value for the given \a property to \a maxVal.
+
+    When setting maximum value, the minimum and current values are
+    adjusted if necessary (ensuring that the range remains valid and
+    that the current value is within the range).
+
+    \sa maximum(), setRange(), rangeChanged()
+*/
+void QtIntPropertyManager::setMaximum(QtProperty *property, int maxVal)
+{
+    setMaximumValue<int, QtIntPropertyManagerPrivate, QtIntPropertyManager, int, QtIntPropertyManagerPrivate::Data>(this, d_ptr,
+                &QtIntPropertyManager::propertyChanged,
+                &QtIntPropertyManager::valueChanged,
+                &QtIntPropertyManager::rangeChanged,
+                property, maxVal);
+}
+
+/**
+    \fn void QtIntPropertyManager::setRange(QtProperty *property, int minimum, int maximum)
+
+    Sets the range of valid values.
+
+    This is a convenience function defining the range of valid values
+    in one go; setting the \a minimum and \a maximum values for the
+    given \a property with a single function call.
+
+    When setting a new range, the current value is adjusted if
+    necessary (ensuring that the value remains within range).
+
+    \sa setMinimum(), setMaximum(), rangeChanged()
+*/
+void QtIntPropertyManager::setRange(QtProperty *property, int minVal, int maxVal)
+{
+    void (QtIntPropertyManagerPrivate::*setSubPropertyRange)(QtProperty *, int, int, int) = 0;
+    setBorderValues<int, QtIntPropertyManagerPrivate, QtIntPropertyManager, int>(this, d_ptr,
+                &QtIntPropertyManager::propertyChanged,
+                &QtIntPropertyManager::valueChanged,
+                &QtIntPropertyManager::rangeChanged,
+                property, minVal, maxVal, setSubPropertyRange);
+}
+
+/**
+    Sets the step value for the given \a property to \a step.
+
+    The step is typically used to increment or decrement a property value while pressing an arrow key.
+
+    \sa singleStep()
+*/
+void QtIntPropertyManager::setSingleStep(QtProperty *property, int step)
+{
+    const QtIntPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtIntPropertyManagerPrivate::Data data = it.value();
+
+    if (step < 0)
+        step = 0;
+
+    if (data.singleStep == step)
+        return;
+
+    data.singleStep = step;
+
+    it.value() = data;
+
+    emit singleStepChanged(property, data.singleStep);
+}
+
+/**
+    \reimp
+*/
+void QtIntPropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QtIntPropertyManagerPrivate::Data();
+}
+
+/**
+    \reimp
+*/
+void QtIntPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    d_ptr->m_values.remove(property);
+}
+
+// QtDoublePropertyManager
+
+class QtDoublePropertyManagerPrivate
+{
+    QtDoublePropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtDoublePropertyManager)
+public:
+
+    struct Data
+    {
+        Data() : val(0), minVal(-INT_MAX), maxVal(INT_MAX), singleStep(1), decimals(2) {}
+        double val;
+        double minVal;
+        double maxVal;
+        double singleStep;
+        int decimals;
+        double minimumValue() const { return minVal; }
+        double maximumValue() const { return maxVal; }
+        void setMinimumValue(double newMinVal) { setSimpleMinimumData(this, newMinVal); }
+        void setMaximumValue(double newMaxVal) { setSimpleMaximumData(this, newMaxVal); }
+    };
+
+    typedef QMap<const QtProperty *, Data> PropertyValueMap;
+    PropertyValueMap m_values;
+};
+
+/**
+    \class QtDoublePropertyManager
+
+    \brief The QtDoublePropertyManager provides and manages double properties.
+
+    A double property has a current value, and a range specifying the
+    valid values. The range is defined by a minimum and a maximum
+    value.
+
+    The property's value and range can be retrieved using the value(),
+    minimum() and maximum() functions, and can be set using the
+    setValue(), setMinimum() and setMaximum() slots.
+    Alternatively, the range can be defined in one go using the
+    setRange() slot.
+
+    In addition, QtDoublePropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes, and the rangeChanged() signal which is emitted whenever
+    such a property changes its range of valid values.
+
+    \sa QtAbstractPropertyManager, QtDoubleSpinBoxFactory
+*/
+
+/**
+    \fn void QtDoublePropertyManager::valueChanged(QtProperty *property, double value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    \fn void QtDoublePropertyManager::rangeChanged(QtProperty *property, double minimum, double maximum)
+
+    This signal is emitted whenever a property created by this manager
+    changes its range of valid values, passing a pointer to the
+    \a property and the new \a minimum and \a maximum values
+
+    \sa setRange()
+*/
+
+/**
+    \fn void QtDoublePropertyManager::decimalsChanged(QtProperty *property, int prec)
+
+    This signal is emitted whenever a property created by this manager
+    changes its precision of value, passing a pointer to the
+    \a property and the new \a prec value
+
+    \sa setDecimals()
+*/
+
+/**
+    \fn void QtDoublePropertyManager::singleStepChanged(QtProperty *property, double step)
+
+    This signal is emitted whenever a property created by this manager
+    changes its single step property, passing a pointer to the
+    \a property and the new \a step value
+
+    \sa setSingleStep()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtDoublePropertyManager::QtDoublePropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtDoublePropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+}
+
+/**
+    Destroys  this manager, and all the properties it has created.
+*/
+QtDoublePropertyManager::~QtDoublePropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given property is not managed by this manager, this
+    function returns 0.
+
+    \sa setValue()
+*/
+double QtDoublePropertyManager::value(const QtProperty *property) const
+{
+    return getValue<double>(d_ptr->m_values, property, 0.0);
+}
+
+/**
+    Returns the given \a property's minimum value.
+
+    \sa maximum(), setRange()
+*/
+double QtDoublePropertyManager::minimum(const QtProperty *property) const
+{
+    return getMinimum<double>(d_ptr->m_values, property, 0.0);
+}
+
+/**
+    Returns the given \a property's maximum value.
+
+    \sa minimum(), setRange()
+*/
+double QtDoublePropertyManager::maximum(const QtProperty *property) const
+{
+    return getMaximum<double>(d_ptr->m_values, property, 0.0);
+}
+
+/**
+    Returns the given \a property's step value.
+
+    The step is typically used to increment or decrement a property value while pressing an arrow key.
+
+    \sa setSingleStep()
+*/
+double QtDoublePropertyManager::singleStep(const QtProperty *property) const
+{
+    return getData<double>(d_ptr->m_values, &QtDoublePropertyManagerPrivate::Data::singleStep, property, 0);
+}
+
+/**
+    Returns the given \a property's precision, in decimals.
+
+    \sa setDecimals()
+*/
+int QtDoublePropertyManager::decimals(const QtProperty *property) const
+{
+    return getData<int>(d_ptr->m_values, &QtDoublePropertyManagerPrivate::Data::decimals, property, 0);
+}
+
+/**
+    \reimp
+*/
+QString QtDoublePropertyManager::valueText(const QtProperty *property) const
+{
+    const QtDoublePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    double absVal = fabs(it.value().val);
+    char format = absVal > 1e5 || (absVal != 0 && absVal < 1e-5) ? 'e' : 'f';
+    return QString::number(it.value().val,format , it.value().decimals);
+}
+
+/**
+    \fn void QtDoublePropertyManager::setValue(QtProperty *property, double value)
+
+    Sets the value of the given \a property to \a value.
+
+    If the specified \a value is not valid according to the given
+    \a property's range, the \a value is adjusted to the nearest valid value
+    within the range.
+
+    \sa value(), setRange(), valueChanged()
+*/
+void QtDoublePropertyManager::setValue(QtProperty *property, double val)
+{
+    void (QtDoublePropertyManagerPrivate::*setSubPropertyValue)(QtProperty *, double) = 0;
+    setValueInRange<double, QtDoublePropertyManagerPrivate, QtDoublePropertyManager, double>(this, d_ptr,
+                &QtDoublePropertyManager::propertyChanged,
+                &QtDoublePropertyManager::valueChanged,
+                property, val, setSubPropertyValue);
+}
+
+/**
+    Sets the step value for the given \a property to \a step.
+
+    The step is typically used to increment or decrement a property value while pressing an arrow key.
+
+    \sa singleStep()
+*/
+void QtDoublePropertyManager::setSingleStep(QtProperty *property, double step)
+{
+    const QtDoublePropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtDoublePropertyManagerPrivate::Data data = it.value();
+
+    if (step < 0)
+        step = 0;
+
+    if (data.singleStep == step)
+        return;
+
+    data.singleStep = step;
+
+    it.value() = data;
+
+    emit singleStepChanged(property, data.singleStep);
+}
+
+/**
+    \fn void QtDoublePropertyManager::setDecimals(QtProperty *property, int prec)
+
+    Sets the precision of the given \a property to \a prec.
+
+    The valid decimal range is 0-13. The default is 2.
+
+    \sa decimals()
+*/
+void QtDoublePropertyManager::setDecimals(QtProperty *property, int prec)
+{
+    const QtDoublePropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtDoublePropertyManagerPrivate::Data data = it.value();
+
+    if (prec > 13)
+        prec = 13;
+    else if (prec < 0)
+        prec = 0;
+
+    if (data.decimals == prec)
+        return;
+
+    data.decimals = prec;
+
+    it.value() = data;
+
+    emit decimalsChanged(property, data.decimals);
+}
+
+/**
+    Sets the minimum value for the given \a property to \a minVal.
+
+    When setting the minimum value, the maximum and current values are
+    adjusted if necessary (ensuring that the range remains valid and
+    that the current value is within in the range).
+
+    \sa minimum(), setRange(), rangeChanged()
+*/
+void QtDoublePropertyManager::setMinimum(QtProperty *property, double minVal)
+{
+    setMinimumValue<double, QtDoublePropertyManagerPrivate, QtDoublePropertyManager, double, QtDoublePropertyManagerPrivate::Data>(this, d_ptr,
+                &QtDoublePropertyManager::propertyChanged,
+                &QtDoublePropertyManager::valueChanged,
+                &QtDoublePropertyManager::rangeChanged,
+                property, minVal);
+}
+
+/**
+    Sets the maximum value for the given \a property to \a maxVal.
+
+    When setting the maximum value, the minimum and current values are
+    adjusted if necessary (ensuring that the range remains valid and
+    that the current value is within in the range).
+
+    \sa maximum(), setRange(), rangeChanged()
+*/
+void QtDoublePropertyManager::setMaximum(QtProperty *property, double maxVal)
+{
+    setMaximumValue<double, QtDoublePropertyManagerPrivate, QtDoublePropertyManager, double, QtDoublePropertyManagerPrivate::Data>(this, d_ptr,
+                &QtDoublePropertyManager::propertyChanged,
+                &QtDoublePropertyManager::valueChanged,
+                &QtDoublePropertyManager::rangeChanged,
+                property, maxVal);
+}
+
+/**
+    \fn void QtDoublePropertyManager::setRange(QtProperty *property, double minimum, double maximum)
+
+    Sets the range of valid values.
+
+    This is a convenience function defining the range of valid values
+    in one go; setting the \a minimum and \a maximum values for the
+    given \a property with a single function call.
+
+    When setting a new range, the current value is adjusted if
+    necessary (ensuring that the value remains within range).
+
+    \sa setMinimum(), setMaximum(), rangeChanged()
+*/
+void QtDoublePropertyManager::setRange(QtProperty *property, double minVal, double maxVal)
+{
+    void (QtDoublePropertyManagerPrivate::*setSubPropertyRange)(QtProperty *, double, double, double) = 0;
+    setBorderValues<double, QtDoublePropertyManagerPrivate, QtDoublePropertyManager, double>(this, d_ptr,
+                &QtDoublePropertyManager::propertyChanged,
+                &QtDoublePropertyManager::valueChanged,
+                &QtDoublePropertyManager::rangeChanged,
+                property, minVal, maxVal, setSubPropertyRange);
+}
+
+/**
+    \reimp
+*/
+void QtDoublePropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QtDoublePropertyManagerPrivate::Data();
+}
+
+/**
+    \reimp
+*/
+void QtDoublePropertyManager::uninitializeProperty(QtProperty *property)
+{
+    d_ptr->m_values.remove(property);
+}
+
+// QtStringPropertyManager
+
+class QtStringPropertyManagerPrivate
+{
+    QtStringPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtStringPropertyManager)
+public:
+
+    struct Data
+    {
+        Data() : regExp(QString(QLatin1Char('*')),  Qt::CaseSensitive, QRegExp::Wildcard)
+        {
+        }
+        QString val;
+        QRegExp regExp;
+    };
+
+    typedef QMap<const QtProperty *, Data> PropertyValueMap;
+    QMap<const QtProperty *, Data> m_values;
+};
+
+/**
+    \class QtStringPropertyManager
+
+    \brief The QtStringPropertyManager provides and manages QString properties.
+
+    A string property's value can be retrieved using the value()
+    function, and set using the setValue() slot.
+
+    The current value can be checked against a regular expression. To
+    set the regular expression use the setRegExp() slot, use the
+    regExp() function to retrieve the currently set expression.
+
+    In addition, QtStringPropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes, and the regExpChanged() signal which is emitted whenever
+    such a property changes its currently set regular expression.
+
+    \sa QtAbstractPropertyManager, QtLineEditFactory
+*/
+
+/**
+    \fn void QtStringPropertyManager::valueChanged(QtProperty *property, const QString &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the
+    new \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    \fn void QtStringPropertyManager::regExpChanged(QtProperty *property, const QRegExp &regExp)
+
+    This signal is emitted whenever a property created by this manager
+    changes its currenlty set regular expression, passing a pointer to
+    the \a property and the new \a regExp as parameters.
+
+    \sa setRegExp()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtStringPropertyManager::QtStringPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtStringPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtStringPropertyManager::~QtStringPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given property is not managed by this manager, this
+    function returns an empty string.
+
+    \sa setValue()
+*/
+QString QtStringPropertyManager::value(const QtProperty *property) const
+{
+    return getValue<QString>(d_ptr->m_values, property);
+}
+
+/**
+    Returns the given \a property's currently set regular expression.
+
+    If the given \a property is not managed by this manager, this
+    function returns an empty expression.
+
+    \sa setRegExp()
+*/
+QRegExp QtStringPropertyManager::regExp(const QtProperty *property) const
+{
+    return getData<QRegExp>(d_ptr->m_values, &QtStringPropertyManagerPrivate::Data::regExp, property, QRegExp());
+}
+
+/**
+    \reimp
+*/
+QString QtStringPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtStringPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    return it.value().val;
+}
+
+/**
+    \fn void QtStringPropertyManager::setValue(QtProperty *property, const QString &value)
+
+    Sets the value of the given \a property to \a value.
+
+    If the specified \a value doesn't match the given \a property's
+    regular expression, this function does nothing.
+
+    \sa value(), setRegExp(), valueChanged()
+*/
+void QtStringPropertyManager::setValue(QtProperty *property, const QString &val)
+{
+    const QtStringPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtStringPropertyManagerPrivate::Data data = it.value();
+
+    if (data.val == val)
+        return;
+
+    if (data.regExp.isValid() && !data.regExp.exactMatch(val))
+        return;
+
+    data.val = val;
+
+    it.value() = data;
+
+    emit propertyChanged(property);
+    emit valueChanged(property, data.val);
+}
+
+/**
+    Sets the regular expression of the given \a property to \a regExp.
+
+    \sa regExp(), setValue(), regExpChanged()
+*/
+void QtStringPropertyManager::setRegExp(QtProperty *property, const QRegExp &regExp)
+{
+    const QtStringPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtStringPropertyManagerPrivate::Data data = it.value() ;
+
+    if (data.regExp == regExp)
+        return;
+
+    data.regExp = regExp;
+
+    it.value() = data;
+
+    emit regExpChanged(property, data.regExp);
+}
+
+/**
+    \reimp
+*/
+void QtStringPropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QtStringPropertyManagerPrivate::Data();
+}
+
+/**
+    \reimp
+*/
+void QtStringPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    d_ptr->m_values.remove(property);
+}
+
+// QtBoolPropertyManager
+
+class QtBoolPropertyManagerPrivate
+{
+    QtBoolPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtBoolPropertyManager)
+public:
+
+    QMap<const QtProperty *, bool> m_values;
+};
+
+/**
+    \class QtBoolPropertyManager
+
+    \brief The QtBoolPropertyManager class provides and manages boolean properties.
+
+    The property's value can be retrieved using the value() function,
+    and set using the setValue() slot.
+
+    In addition, QtBoolPropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes.
+
+    \sa QtAbstractPropertyManager, QtCheckBoxFactory
+*/
+
+/**
+    \fn void QtBoolPropertyManager::valueChanged(QtProperty *property, bool value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the
+    new \a value as parameters.
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtBoolPropertyManager::QtBoolPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtBoolPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtBoolPropertyManager::~QtBoolPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by \e this manager, this
+    function returns false.
+
+    \sa setValue()
+*/
+bool QtBoolPropertyManager::value(const QtProperty *property) const
+{
+    return d_ptr->m_values.value(property, false);
+}
+
+/**
+    \reimp
+*/
+QString QtBoolPropertyManager::valueText(const QtProperty *property) const
+{
+    const QMap<const QtProperty *, bool>::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+
+    static const QString trueText = tr("True");
+    static const QString falseText = tr("False");
+    return it.value() ? trueText : falseText;
+}
+
+// Return an icon containing a check box indicator
+static QIcon drawCheckBox(bool value)
+{
+    QStyleOptionButton opt;
+    opt.state |= value ? QStyle::State_On : QStyle::State_Off;
+    opt.state |= QStyle::State_Enabled;
+    const QStyle *style = QApplication::style();
+    // Figure out size of an indicator and make sure it is not scaled down in a list view item
+    // by making the pixmap as big as a list view icon and centering the indicator in it.
+    // (if it is smaller, it can't be helped)
+    const int indicatorWidth = style->pixelMetric(QStyle::PM_IndicatorWidth, &opt);
+    const int indicatorHeight = style->pixelMetric(QStyle::PM_IndicatorHeight, &opt);
+    const int listViewIconSize = indicatorWidth;
+    const int pixmapWidth = indicatorWidth;
+    const int pixmapHeight = qMax(indicatorHeight, listViewIconSize);
+
+    opt.rect = QRect(0, 0, indicatorWidth, indicatorHeight);
+    QPixmap pixmap = QPixmap(pixmapWidth, pixmapHeight);
+    pixmap.fill(Qt::transparent);
+    {
+        // Center?
+        const int xoff = (pixmapWidth  > indicatorWidth)  ? (pixmapWidth  - indicatorWidth)  / 2 : 0;
+        const int yoff = (pixmapHeight > indicatorHeight) ? (pixmapHeight - indicatorHeight) / 2 : 0;
+        QPainter painter(&pixmap);
+        painter.translate(xoff, yoff);
+        style->drawPrimitive(QStyle::PE_IndicatorCheckBox, &opt, &painter);
+    }
+    return QIcon(pixmap);
+}
+
+/**
+    \reimp
+*/
+QIcon QtBoolPropertyManager::valueIcon(const QtProperty *property) const
+{
+    const QMap<const QtProperty *, bool>::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QIcon();
+
+    static const QIcon checkedIcon = drawCheckBox(true);
+    static const QIcon uncheckedIcon = drawCheckBox(false);
+    return it.value() ? checkedIcon : uncheckedIcon;
+}
+
+/**
+    \fn void QtBoolPropertyManager::setValue(QtProperty *property, bool value)
+
+    Sets the value of the given \a property to \a value.
+
+    \sa value()
+*/
+void QtBoolPropertyManager::setValue(QtProperty *property, bool val)
+{
+    setSimpleValue<bool, bool, QtBoolPropertyManager>(d_ptr->m_values, this,
+                &QtBoolPropertyManager::propertyChanged,
+                &QtBoolPropertyManager::valueChanged,
+                property, val);
+}
+
+/**
+    \reimp
+*/
+void QtBoolPropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = false;
+}
+
+/**
+    \reimp
+*/
+void QtBoolPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    d_ptr->m_values.remove(property);
+}
+
+// QtDatePropertyManager
+
+class QtDatePropertyManagerPrivate
+{
+    QtDatePropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtDatePropertyManager)
+public:
+
+    struct Data
+    {
+        Data() : val(QDate::currentDate()), minVal(QDate(1752, 9, 14)),
+                maxVal(QDate(7999, 12, 31)) {}
+        QDate val;
+        QDate minVal;
+        QDate maxVal;
+        QDate minimumValue() const { return minVal; }
+        QDate maximumValue() const { return maxVal; }
+        void setMinimumValue(const QDate &newMinVal) { setSimpleMinimumData(this, newMinVal); }
+        void setMaximumValue(const QDate &newMaxVal) { setSimpleMaximumData(this, newMaxVal); }
+    };
+
+    QString m_format;
+
+    typedef QMap<const QtProperty *, Data> PropertyValueMap;
+    QMap<const QtProperty *, Data> m_values;
+};
+
+/**
+    \class QtDatePropertyManager
+
+    \brief The QtDatePropertyManager provides and manages QDate properties.
+
+    A date property has a current value, and a range specifying the
+    valid dates. The range is defined by a minimum and a maximum
+    value.
+
+    The property's values can be retrieved using the minimum(),
+    maximum() and value() functions, and can be set using the
+    setMinimum(), setMaximum() and setValue() slots. Alternatively,
+    the range can be defined in one go using the setRange() slot.
+
+    In addition, QtDatePropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes, and the rangeChanged() signal which is emitted whenever
+    such a property changes its range of valid dates.
+
+    \sa QtAbstractPropertyManager, QtDateEditFactory, QtDateTimePropertyManager
+*/
+
+/**
+    \fn void QtDatePropertyManager::valueChanged(QtProperty *property, const QDate &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    \fn void QtDatePropertyManager::rangeChanged(QtProperty *property, const QDate &minimum, const QDate &maximum)
+
+    This signal is emitted whenever a property created by this manager
+    changes its range of valid dates, passing a pointer to the \a
+    property and the new \a minimum and \a maximum dates.
+
+    \sa setRange()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtDatePropertyManager::QtDatePropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtDatePropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    QLocale loc;
+    d_ptr->m_format = loc.dateFormat(QLocale::ShortFormat);
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtDatePropertyManager::~QtDatePropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by \e this manager, this
+    function returns an invalid date.
+
+    \sa setValue()
+*/
+QDate QtDatePropertyManager::value(const QtProperty *property) const
+{
+    return getValue<QDate>(d_ptr->m_values, property);
+}
+
+/**
+    Returns the given \a  property's  minimum date.
+
+    \sa maximum(), setRange()
+*/
+QDate QtDatePropertyManager::minimum(const QtProperty *property) const
+{
+    return getMinimum<QDate>(d_ptr->m_values, property);
+}
+
+/**
+    Returns the given \a property's maximum date.
+
+    \sa minimum(), setRange()
+*/
+QDate QtDatePropertyManager::maximum(const QtProperty *property) const
+{
+    return getMaximum<QDate>(d_ptr->m_values, property);
+}
+
+/**
+    \reimp
+*/
+QString QtDatePropertyManager::valueText(const QtProperty *property) const
+{
+    const QtDatePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    return it.value().val.toString(d_ptr->m_format);
+}
+
+/**
+    \fn void QtDatePropertyManager::setValue(QtProperty *property, const QDate &value)
+
+    Sets the value of the given \a property to \a value.
+
+    If the specified \a value is not a valid date according to the
+    given \a property's range, the value is adjusted to the nearest
+    valid value within the range.
+
+    \sa value(), setRange(), valueChanged()
+*/
+void QtDatePropertyManager::setValue(QtProperty *property, const QDate &val)
+{
+    void (QtDatePropertyManagerPrivate::*setSubPropertyValue)(QtProperty *, const QDate &) = 0;
+    setValueInRange<const QDate &, QtDatePropertyManagerPrivate, QtDatePropertyManager, const QDate>(this, d_ptr,
+                &QtDatePropertyManager::propertyChanged,
+                &QtDatePropertyManager::valueChanged,
+                property, val, setSubPropertyValue);
+}
+
+/**
+    Sets the minimum value for the given \a property to \a minVal.
+
+    When setting the minimum value, the maximum and current values are
+    adjusted if necessary (ensuring that the range remains valid and
+    that the current value is within in the range).
+
+    \sa minimum(), setRange()
+*/
+void QtDatePropertyManager::setMinimum(QtProperty *property, const QDate &minVal)
+{
+    setMinimumValue<const QDate &, QtDatePropertyManagerPrivate, QtDatePropertyManager, QDate, QtDatePropertyManagerPrivate::Data>(this, d_ptr,
+                &QtDatePropertyManager::propertyChanged,
+                &QtDatePropertyManager::valueChanged,
+                &QtDatePropertyManager::rangeChanged,
+                property, minVal);
+}
+
+/**
+    Sets the maximum value for the given \a property to \a maxVal.
+
+    When setting the maximum value, the minimum and current
+    values are adjusted if necessary (ensuring that the range remains
+    valid and that the current value is within in the range).
+
+    \sa maximum(), setRange()
+*/
+void QtDatePropertyManager::setMaximum(QtProperty *property, const QDate &maxVal)
+{
+    setMaximumValue<const QDate &, QtDatePropertyManagerPrivate, QtDatePropertyManager, QDate, QtDatePropertyManagerPrivate::Data>(this, d_ptr,
+                &QtDatePropertyManager::propertyChanged,
+                &QtDatePropertyManager::valueChanged,
+                &QtDatePropertyManager::rangeChanged,
+                property, maxVal);
+}
+
+/**
+    \fn void QtDatePropertyManager::setRange(QtProperty *property, const QDate &minimum, const QDate &maximum)
+
+    Sets the range of valid dates.
+
+    This is a convenience function defining the range of valid dates
+    in one go; setting the \a minimum and \a maximum values for the
+    given \a property with a single function call.
+
+    When setting a new date range, the current value is adjusted if
+    necessary (ensuring that the value remains in date range).
+
+    \sa setMinimum(), setMaximum(), rangeChanged()
+*/
+void QtDatePropertyManager::setRange(QtProperty *property, const QDate &minVal, const QDate &maxVal)
+{
+    void (QtDatePropertyManagerPrivate::*setSubPropertyRange)(QtProperty *, const QDate &,
+          const QDate &, const QDate &) = 0;
+    setBorderValues<const QDate &, QtDatePropertyManagerPrivate, QtDatePropertyManager, QDate>(this, d_ptr,
+                &QtDatePropertyManager::propertyChanged,
+                &QtDatePropertyManager::valueChanged,
+                &QtDatePropertyManager::rangeChanged,
+                property, minVal, maxVal, setSubPropertyRange);
+}
+
+/**
+    \reimp
+*/
+void QtDatePropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QtDatePropertyManagerPrivate::Data();
+}
+
+/**
+    \reimp
+*/
+void QtDatePropertyManager::uninitializeProperty(QtProperty *property)
+{
+    d_ptr->m_values.remove(property);
+}
+
+// QtTimePropertyManager
+
+class QtTimePropertyManagerPrivate
+{
+    QtTimePropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtTimePropertyManager)
+public:
+
+    QString m_format;
+
+    typedef QMap<const QtProperty *, QTime> PropertyValueMap;
+    PropertyValueMap m_values;
+};
+
+/**
+    \class QtTimePropertyManager
+
+    \brief The QtTimePropertyManager provides and manages QTime properties.
+
+    A time property's value can be retrieved using the value()
+    function, and set using the setValue() slot.
+
+    In addition, QtTimePropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes.
+
+    \sa QtAbstractPropertyManager, QtTimeEditFactory
+*/
+
+/**
+    \fn void QtTimePropertyManager::valueChanged(QtProperty *property, const QTime &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the
+    new \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtTimePropertyManager::QtTimePropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtTimePropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    QLocale loc;
+    d_ptr->m_format = loc.timeFormat(QLocale::ShortFormat);
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtTimePropertyManager::~QtTimePropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given property is not managed by this manager, this
+    function returns an invalid time object.
+
+    \sa setValue()
+*/
+QTime QtTimePropertyManager::value(const QtProperty *property) const
+{
+    return d_ptr->m_values.value(property, QTime());
+}
+
+/**
+    \reimp
+*/
+QString QtTimePropertyManager::valueText(const QtProperty *property) const
+{
+   const QtTimePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    return it.value().toString(d_ptr->m_format);
+}
+
+/**
+    \fn void QtTimePropertyManager::setValue(QtProperty *property, const QTime &value)
+
+    Sets the value of the given \a property to \a value.
+
+    \sa value(), valueChanged()
+*/
+void QtTimePropertyManager::setValue(QtProperty *property, const QTime &val)
+{
+    setSimpleValue<const QTime &, QTime, QtTimePropertyManager>(d_ptr->m_values, this,
+                &QtTimePropertyManager::propertyChanged,
+                &QtTimePropertyManager::valueChanged,
+                property, val);
+}
+
+/**
+    \reimp
+*/
+void QtTimePropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QTime::currentTime();
+}
+
+/**
+    \reimp
+*/
+void QtTimePropertyManager::uninitializeProperty(QtProperty *property)
+{
+    d_ptr->m_values.remove(property);
+}
+
+// QtDateTimePropertyManager
+
+class QtDateTimePropertyManagerPrivate
+{
+    QtDateTimePropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtDateTimePropertyManager)
+public:
+
+    QString m_format;
+
+    typedef QMap<const QtProperty *, QDateTime> PropertyValueMap;
+    PropertyValueMap m_values;
+};
+
+/** \class QtDateTimePropertyManager
+
+    \brief The QtDateTimePropertyManager provides and manages QDateTime properties.
+
+    A date and time property has a current value which can be
+    retrieved using the value() function, and set using the setValue()
+    slot. In addition, QtDateTimePropertyManager provides the
+    valueChanged() signal which is emitted whenever a property created
+    by this manager changes.
+
+    \sa QtAbstractPropertyManager, QtDateTimeEditFactory, QtDatePropertyManager
+*/
+
+/**
+    \fn void QtDateTimePropertyManager::valueChanged(QtProperty *property, const QDateTime &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtDateTimePropertyManager::QtDateTimePropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtDateTimePropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    QLocale loc;
+    d_ptr->m_format = loc.dateFormat(QLocale::ShortFormat);
+    d_ptr->m_format += QLatin1Char(' ');
+    d_ptr->m_format += loc.timeFormat(QLocale::ShortFormat);
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtDateTimePropertyManager::~QtDateTimePropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by this manager, this
+    function returns an invalid QDateTime object.
+
+    \sa setValue()
+*/
+QDateTime QtDateTimePropertyManager::value(const QtProperty *property) const
+{
+    return d_ptr->m_values.value(property, QDateTime());
+}
+
+/**
+    \reimp
+*/
+QString QtDateTimePropertyManager::valueText(const QtProperty *property) const
+{
+   const QtDateTimePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    return it.value().toString(d_ptr->m_format);
+}
+
+/**
+    \fn void QtDateTimePropertyManager::setValue(QtProperty *property, const QDateTime &value)
+
+    Sets the value of the given \a property to \a value.
+
+    \sa value(), valueChanged()
+*/
+void QtDateTimePropertyManager::setValue(QtProperty *property, const QDateTime &val)
+{
+    setSimpleValue<const QDateTime &, QDateTime, QtDateTimePropertyManager>(d_ptr->m_values, this,
+                &QtDateTimePropertyManager::propertyChanged,
+                &QtDateTimePropertyManager::valueChanged,
+                property, val);
+}
+
+/**
+    \reimp
+*/
+void QtDateTimePropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QDateTime::currentDateTime();
+}
+
+/**
+    \reimp
+*/
+void QtDateTimePropertyManager::uninitializeProperty(QtProperty *property)
+{
+    d_ptr->m_values.remove(property);
+}
+
+// QtKeySequencePropertyManager
+
+class QtKeySequencePropertyManagerPrivate
+{
+    QtKeySequencePropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtKeySequencePropertyManager)
+public:
+
+    QString m_format;
+
+    typedef QMap<const QtProperty *, QKeySequence> PropertyValueMap;
+    PropertyValueMap m_values;
+};
+
+/** \class QtKeySequencePropertyManager
+
+    \brief The QtKeySequencePropertyManager provides and manages QKeySequence properties.
+
+    A key sequence's value can be retrieved using the value()
+    function, and set using the setValue() slot.
+
+    In addition, QtKeySequencePropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes.
+
+    \sa QtAbstractPropertyManager
+*/
+
+/**
+    \fn void QtKeySequencePropertyManager::valueChanged(QtProperty *property, const QKeySequence &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtKeySequencePropertyManager::QtKeySequencePropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtKeySequencePropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtKeySequencePropertyManager::~QtKeySequencePropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by this manager, this
+    function returns an empty QKeySequence object.
+
+    \sa setValue()
+*/
+QKeySequence QtKeySequencePropertyManager::value(const QtProperty *property) const
+{
+    return d_ptr->m_values.value(property, QKeySequence());
+}
+
+/**
+    \reimp
+*/
+QString QtKeySequencePropertyManager::valueText(const QtProperty *property) const
+{
+    const QtKeySequencePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    return it.value().toString(QKeySequence::NativeText);
+}
+
+/**
+    \fn void QtKeySequencePropertyManager::setValue(QtProperty *property, const QKeySequence &value)
+
+    Sets the value of the given \a property to \a value.
+
+    \sa value(), valueChanged()
+*/
+void QtKeySequencePropertyManager::setValue(QtProperty *property, const QKeySequence &val)
+{
+    setSimpleValue<const QKeySequence &, QKeySequence, QtKeySequencePropertyManager>(d_ptr->m_values, this,
+                &QtKeySequencePropertyManager::propertyChanged,
+                &QtKeySequencePropertyManager::valueChanged,
+                property, val);
+}
+
+/**
+    \reimp
+*/
+void QtKeySequencePropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QKeySequence();
+}
+
+/**
+    \reimp
+*/
+void QtKeySequencePropertyManager::uninitializeProperty(QtProperty *property)
+{
+    d_ptr->m_values.remove(property);
+}
+
+// QtCharPropertyManager
+
+class QtCharPropertyManagerPrivate
+{
+    QtCharPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtCharPropertyManager)
+public:
+
+    typedef QMap<const QtProperty *, QChar> PropertyValueMap;
+    PropertyValueMap m_values;
+};
+
+/** \class QtCharPropertyManager
+
+    \brief The QtCharPropertyManager provides and manages QChar properties.
+
+    A char's value can be retrieved using the value()
+    function, and set using the setValue() slot.
+
+    In addition, QtCharPropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes.
+
+    \sa QtAbstractPropertyManager
+*/
+
+/**
+    \fn void QtCharPropertyManager::valueChanged(QtProperty *property, const QChar &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtCharPropertyManager::QtCharPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtCharPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtCharPropertyManager::~QtCharPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by this manager, this
+    function returns an null QChar object.
+
+    \sa setValue()
+*/
+QChar QtCharPropertyManager::value(const QtProperty *property) const
+{
+    return d_ptr->m_values.value(property, QChar());
+}
+
+/**
+    \reimp
+*/
+QString QtCharPropertyManager::valueText(const QtProperty *property) const
+{
+   const QtCharPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    const QChar c = it.value();
+    return c.isNull() ? QString() : QString(c);
+}
+
+/**
+    \fn void QtCharPropertyManager::setValue(QtProperty *property, const QChar &value)
+
+    Sets the value of the given \a property to \a value.
+
+    \sa value(), valueChanged()
+*/
+void QtCharPropertyManager::setValue(QtProperty *property, const QChar &val)
+{
+    setSimpleValue<const QChar &, QChar, QtCharPropertyManager>(d_ptr->m_values, this,
+                &QtCharPropertyManager::propertyChanged,
+                &QtCharPropertyManager::valueChanged,
+                property, val);
+}
+
+/**
+    \reimp
+*/
+void QtCharPropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QChar();
+}
+
+/**
+    \reimp
+*/
+void QtCharPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    d_ptr->m_values.remove(property);
+}
+
+// QtLocalePropertyManager
+
+class QtLocalePropertyManagerPrivate
+{
+    QtLocalePropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtLocalePropertyManager)
+public:
+
+    QtLocalePropertyManagerPrivate();
+
+    void slotEnumChanged(QtProperty *property, int value);
+    void slotPropertyDestroyed(QtProperty *property);
+
+    typedef QMap<const QtProperty *, QLocale> PropertyValueMap;
+    PropertyValueMap m_values;
+
+    QtEnumPropertyManager *m_enumPropertyManager;
+
+    QMap<const QtProperty *, QtProperty *> m_propertyToLanguage;
+    QMap<const QtProperty *, QtProperty *> m_propertyToCountry;
+
+    QMap<const QtProperty *, QtProperty *> m_languageToProperty;
+    QMap<const QtProperty *, QtProperty *> m_countryToProperty;
+};
+
+QtLocalePropertyManagerPrivate::QtLocalePropertyManagerPrivate()
+{
+}
+
+void QtLocalePropertyManagerPrivate::slotEnumChanged(QtProperty *property, int value)
+{
+    if (QtProperty *prop = m_languageToProperty.value(property, 0)) {
+        const QLocale loc = m_values[prop];
+        QLocale::Language newLanguage = loc.language();
+        QLocale::Country newCountry = loc.country();
+        metaEnumProvider()->indexToLocale(value, 0, &newLanguage, 0);
+        QLocale newLoc(newLanguage, newCountry);
+        q_ptr->setValue(prop, newLoc);
+    } else if (QtProperty *prop = m_countryToProperty.value(property, 0)) {
+        const QLocale loc = m_values[prop];
+        QLocale::Language newLanguage = loc.language();
+        QLocale::Country newCountry = loc.country();
+        metaEnumProvider()->indexToLocale(m_enumPropertyManager->value(m_propertyToLanguage.value(prop)), value, &newLanguage, &newCountry);
+        QLocale newLoc(newLanguage, newCountry);
+        q_ptr->setValue(prop, newLoc);
+    }
+}
+
+void QtLocalePropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
+{
+    if (QtProperty *subProp = m_languageToProperty.value(property, 0)) {
+        m_propertyToLanguage[subProp] = 0;
+        m_languageToProperty.remove(property);
+    } else if (QtProperty *subProp = m_countryToProperty.value(property, 0)) {
+        m_propertyToCountry[subProp] = 0;
+        m_countryToProperty.remove(property);
+    }
+}
+
+/**
+    \class QtLocalePropertyManager
+
+    \brief The QtLocalePropertyManager provides and manages QLocale properties.
+
+    A locale property has nested \e language and \e country
+    subproperties. The top-level property's value can be retrieved
+    using the value() function, and set using the setValue() slot.
+
+    The subproperties are created by QtEnumPropertyManager object.
+    These submanager can be retrieved using the subEnumPropertyManager()
+    function. In order to provide editing widgets for the subproperties
+    in a property browser widget, this manager must be associated with editor factory.
+
+    In addition, QtLocalePropertyManager provides the valueChanged()
+    signal which is emitted whenever a property created by this
+    manager changes.
+
+    \sa QtAbstractPropertyManager, QtEnumPropertyManager
+*/
+
+/**
+    \fn void QtLocalePropertyManager::valueChanged(QtProperty *property, const QLocale &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the
+    new \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtLocalePropertyManager::QtLocalePropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtLocalePropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_enumPropertyManager = new QtEnumPropertyManager(this);
+    connect(d_ptr->m_enumPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotEnumChanged(QtProperty *, int)));
+
+    connect(d_ptr->m_enumPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtLocalePropertyManager::~QtLocalePropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the manager that creates the nested \e language
+    and \e country subproperties.
+
+    In order to provide editing widgets for the mentioned subproperties
+    in a property browser widget, this manager must be associated with
+    an editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtEnumPropertyManager *QtLocalePropertyManager::subEnumPropertyManager() const
+{
+    return d_ptr->m_enumPropertyManager;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given property is not managed by this manager, this
+    function returns the default locale.
+
+    \sa setValue()
+*/
+QLocale QtLocalePropertyManager::value(const QtProperty *property) const
+{
+    return d_ptr->m_values.value(property, QLocale());
+}
+
+/**
+    \reimp
+*/
+QString QtLocalePropertyManager::valueText(const QtProperty *property) const
+{
+    const QtLocalePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+
+    QLocale loc = it.value();
+
+    int langIdx = 0;
+    int countryIdx = 0;
+    metaEnumProvider()->localeToIndex(loc.language(), loc.country(), &langIdx, &countryIdx);
+    QString str = tr("%1, %2")
+            .arg(metaEnumProvider()->languageEnumNames().at(langIdx))
+            .arg(metaEnumProvider()->countryEnumNames(loc.language()).at(countryIdx));
+    return str;
+}
+
+/**
+    \fn void QtLocalePropertyManager::setValue(QtProperty *property, const QLocale &value)
+
+    Sets the value of the given \a property to \a value. Nested
+    properties are updated automatically.
+
+    \sa value(), valueChanged()
+*/
+void QtLocalePropertyManager::setValue(QtProperty *property, const QLocale &val)
+{
+    const QtLocalePropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    const QLocale loc = it.value();
+    if (loc == val)
+        return;
+
+    it.value() = val;
+
+    int langIdx = 0;
+    int countryIdx = 0;
+    metaEnumProvider()->localeToIndex(val.language(), val.country(), &langIdx, &countryIdx);
+    if (loc.language() != val.language()) {
+        d_ptr->m_enumPropertyManager->setValue(d_ptr->m_propertyToLanguage.value(property), langIdx);
+        d_ptr->m_enumPropertyManager->setEnumNames(d_ptr->m_propertyToCountry.value(property),
+                    metaEnumProvider()->countryEnumNames(val.language()));
+    }
+    d_ptr->m_enumPropertyManager->setValue(d_ptr->m_propertyToCountry.value(property), countryIdx);
+
+    emit propertyChanged(property);
+    emit valueChanged(property, val);
+}
+
+/**
+    \reimp
+*/
+void QtLocalePropertyManager::initializeProperty(QtProperty *property)
+{
+    QLocale val;
+    d_ptr->m_values[property] = val;
+
+    int langIdx = 0;
+    int countryIdx = 0;
+    metaEnumProvider()->localeToIndex(val.language(), val.country(), &langIdx, &countryIdx);
+
+    QtProperty *languageProp = d_ptr->m_enumPropertyManager->addProperty();
+    languageProp->setPropertyName(tr("Language"));
+    d_ptr->m_enumPropertyManager->setEnumNames(languageProp, metaEnumProvider()->languageEnumNames());
+    d_ptr->m_enumPropertyManager->setValue(languageProp, langIdx);
+    d_ptr->m_propertyToLanguage[property] = languageProp;
+    d_ptr->m_languageToProperty[languageProp] = property;
+    property->addSubProperty(languageProp);
+
+    QtProperty *countryProp = d_ptr->m_enumPropertyManager->addProperty();
+    countryProp->setPropertyName(tr("Country"));
+    d_ptr->m_enumPropertyManager->setEnumNames(countryProp, metaEnumProvider()->countryEnumNames(val.language()));
+    d_ptr->m_enumPropertyManager->setValue(countryProp, countryIdx);
+    d_ptr->m_propertyToCountry[property] = countryProp;
+    d_ptr->m_countryToProperty[countryProp] = property;
+    property->addSubProperty(countryProp);
+}
+
+/**
+    \reimp
+*/
+void QtLocalePropertyManager::uninitializeProperty(QtProperty *property)
+{
+    QtProperty *languageProp = d_ptr->m_propertyToLanguage[property];
+    if (languageProp) {
+        d_ptr->m_languageToProperty.remove(languageProp);
+        delete languageProp;
+    }
+    d_ptr->m_propertyToLanguage.remove(property);
+
+    QtProperty *countryProp = d_ptr->m_propertyToCountry[property];
+    if (countryProp) {
+        d_ptr->m_countryToProperty.remove(countryProp);
+        delete countryProp;
+    }
+    d_ptr->m_propertyToCountry.remove(property);
+
+    d_ptr->m_values.remove(property);
+}
+
+// QtPointPropertyManager
+
+class QtPointPropertyManagerPrivate
+{
+    QtPointPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtPointPropertyManager)
+public:
+
+    void slotIntChanged(QtProperty *property, int value);
+    void slotPropertyDestroyed(QtProperty *property);
+
+    typedef QMap<const QtProperty *, QPoint> PropertyValueMap;
+    PropertyValueMap m_values;
+
+    QtIntPropertyManager *m_intPropertyManager;
+
+    QMap<const QtProperty *, QtProperty *> m_propertyToX;
+    QMap<const QtProperty *, QtProperty *> m_propertyToY;
+
+    QMap<const QtProperty *, QtProperty *> m_xToProperty;
+    QMap<const QtProperty *, QtProperty *> m_yToProperty;
+};
+
+void QtPointPropertyManagerPrivate::slotIntChanged(QtProperty *property, int value)
+{
+    if (QtProperty *xprop = m_xToProperty.value(property, 0)) {
+        QPoint p = m_values[xprop];
+        p.setX(value);
+        q_ptr->setValue(xprop, p);
+    } else if (QtProperty *yprop = m_yToProperty.value(property, 0)) {
+        QPoint p = m_values[yprop];
+        p.setY(value);
+        q_ptr->setValue(yprop, p);
+    }
+}
+
+void QtPointPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
+{
+    if (QtProperty *pointProp = m_xToProperty.value(property, 0)) {
+        m_propertyToX[pointProp] = 0;
+        m_xToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_yToProperty.value(property, 0)) {
+        m_propertyToY[pointProp] = 0;
+        m_yToProperty.remove(property);
+    }
+}
+
+/** \class QtPointPropertyManager
+
+    \brief The QtPointPropertyManager provides and manages QPoint properties.
+
+    A point property has nested \e x and \e y subproperties. The
+    top-level property's value can be retrieved using the value()
+    function, and set using the setValue() slot.
+
+    The subproperties are created by a QtIntPropertyManager object. This
+    manager can be retrieved using the subIntPropertyManager() function. In
+    order to provide editing widgets for the subproperties in a
+    property browser widget, this manager must be associated with an
+    editor factory.
+
+    In addition, QtPointPropertyManager provides the valueChanged() signal which
+    is emitted whenever a property created by this manager changes.
+
+    \sa QtAbstractPropertyManager, QtIntPropertyManager, QtPointFPropertyManager
+*/
+
+/**
+    \fn void QtPointPropertyManager::valueChanged(QtProperty *property, const QPoint &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the
+    new \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtPointPropertyManager::QtPointPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtPointPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_intPropertyManager = new QtIntPropertyManager(this);
+    connect(d_ptr->m_intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotIntChanged(QtProperty *, int)));
+    connect(d_ptr->m_intPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtPointPropertyManager::~QtPointPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the manager that creates the nested \e x and \e y
+    subproperties.
+
+    In order to provide editing widgets for the subproperties in a
+    property browser widget, this manager must be associated with an
+    editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtIntPropertyManager *QtPointPropertyManager::subIntPropertyManager() const
+{
+    return d_ptr->m_intPropertyManager;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by this manager, this
+    function returns a point with coordinates (0, 0).
+
+    \sa setValue()
+*/
+QPoint QtPointPropertyManager::value(const QtProperty *property) const
+{
+    return d_ptr->m_values.value(property, QPoint());
+}
+
+/**
+    \reimp
+*/
+QString QtPointPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtPointPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    const QPoint v = it.value();
+    return QString(tr("(%1, %2)").arg(QString::number(v.x()))
+                                 .arg(QString::number(v.y())));
+}
+
+/**
+    \fn void QtPointPropertyManager::setValue(QtProperty *property, const QPoint &value)
+
+    Sets the value of the given \a property to \a value. Nested
+    properties are updated automatically.
+
+    \sa value(), valueChanged()
+*/
+void QtPointPropertyManager::setValue(QtProperty *property, const QPoint &val)
+{
+    const QtPointPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    if (it.value() == val)
+        return;
+
+    it.value() = val;
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToX[property], val.x());
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToY[property], val.y());
+
+    emit propertyChanged(property);
+    emit valueChanged(property, val);
+}
+
+/**
+    \reimp
+*/
+void QtPointPropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QPoint(0, 0);
+
+    QtProperty *xProp = d_ptr->m_intPropertyManager->addProperty();
+    xProp->setPropertyName(tr("X"));
+    d_ptr->m_intPropertyManager->setValue(xProp, 0);
+    d_ptr->m_propertyToX[property] = xProp;
+    d_ptr->m_xToProperty[xProp] = property;
+    property->addSubProperty(xProp);
+
+    QtProperty *yProp = d_ptr->m_intPropertyManager->addProperty();
+    yProp->setPropertyName(tr("Y"));
+    d_ptr->m_intPropertyManager->setValue(yProp, 0);
+    d_ptr->m_propertyToY[property] = yProp;
+    d_ptr->m_yToProperty[yProp] = property;
+    property->addSubProperty(yProp);
+}
+
+/**
+    \reimp
+*/
+void QtPointPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    QtProperty *xProp = d_ptr->m_propertyToX[property];
+    if (xProp) {
+        d_ptr->m_xToProperty.remove(xProp);
+        delete xProp;
+    }
+    d_ptr->m_propertyToX.remove(property);
+
+    QtProperty *yProp = d_ptr->m_propertyToY[property];
+    if (yProp) {
+        d_ptr->m_yToProperty.remove(yProp);
+        delete yProp;
+    }
+    d_ptr->m_propertyToY.remove(property);
+
+    d_ptr->m_values.remove(property);
+}
+
+// QtPointFPropertyManager
+
+class QtPointFPropertyManagerPrivate
+{
+    QtPointFPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtPointFPropertyManager)
+public:
+
+    struct Data
+    {
+        Data() : decimals(2) {}
+        QPointF val;
+        int decimals;
+    };
+
+    void slotDoubleChanged(QtProperty *property, double value);
+    void slotPropertyDestroyed(QtProperty *property);
+
+    typedef QMap<const QtProperty *, Data> PropertyValueMap;
+    PropertyValueMap m_values;
+
+    QtDoublePropertyManager *m_doublePropertyManager;
+
+    QMap<const QtProperty *, QtProperty *> m_propertyToX;
+    QMap<const QtProperty *, QtProperty *> m_propertyToY;
+
+    QMap<const QtProperty *, QtProperty *> m_xToProperty;
+    QMap<const QtProperty *, QtProperty *> m_yToProperty;
+};
+
+void QtPointFPropertyManagerPrivate::slotDoubleChanged(QtProperty *property, double value)
+{
+    if (QtProperty *prop = m_xToProperty.value(property, 0)) {
+        QPointF p = m_values[prop].val;
+        p.setX(value);
+        q_ptr->setValue(prop, p);
+    } else if (QtProperty *prop = m_yToProperty.value(property, 0)) {
+        QPointF p = m_values[prop].val;
+        p.setY(value);
+        q_ptr->setValue(prop, p);
+    }
+}
+
+void QtPointFPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
+{
+    if (QtProperty *pointProp  = m_xToProperty.value(property, 0)) {
+        m_propertyToX[pointProp] = 0;
+        m_xToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_yToProperty.value(property, 0)) {
+        m_propertyToY[pointProp] = 0;
+        m_yToProperty.remove(property);
+    }
+}
+
+/** \class QtPointFPropertyManager
+
+    \brief The QtPointFPropertyManager provides and manages QPointF properties.
+
+    A point property has nested \e x and \e y subproperties. The
+    top-level property's value can be retrieved using the value()
+    function, and set using the setValue() slot.
+
+    The subproperties are created by a QtDoublePropertyManager object. This
+    manager can be retrieved using the subDoublePropertyManager() function. In
+    order to provide editing widgets for the subproperties in a
+    property browser widget, this manager must be associated with an
+    editor factory.
+
+    In addition, QtPointFPropertyManager provides the valueChanged() signal which
+    is emitted whenever a property created by this manager changes.
+
+    \sa QtAbstractPropertyManager, QtDoublePropertyManager, QtPointPropertyManager
+*/
+
+/**
+    \fn void QtPointFPropertyManager::valueChanged(QtProperty *property, const QPointF &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the
+    new \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    \fn void QtPointFPropertyManager::decimalsChanged(QtProperty *property, int prec)
+
+    This signal is emitted whenever a property created by this manager
+    changes its precision of value, passing a pointer to the
+    \a property and the new \a prec value
+
+    \sa setDecimals()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtPointFPropertyManager::QtPointFPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtPointFPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_doublePropertyManager = new QtDoublePropertyManager(this);
+    connect(d_ptr->m_doublePropertyManager, SIGNAL(valueChanged(QtProperty *, double)),
+                this, SLOT(slotDoubleChanged(QtProperty *, double)));
+    connect(d_ptr->m_doublePropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtPointFPropertyManager::~QtPointFPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the manager that creates the nested \e x and \e y
+    subproperties.
+
+    In order to provide editing widgets for the subproperties in a
+    property browser widget, this manager must be associated with an
+    editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtDoublePropertyManager *QtPointFPropertyManager::subDoublePropertyManager() const
+{
+    return d_ptr->m_doublePropertyManager;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by this manager, this
+    function returns a point with coordinates (0, 0).
+
+    \sa setValue()
+*/
+QPointF QtPointFPropertyManager::value(const QtProperty *property) const
+{
+    return getValue<QPointF>(d_ptr->m_values, property);
+}
+
+/**
+    Returns the given \a property's precision, in decimals.
+
+    \sa setDecimals()
+*/
+int QtPointFPropertyManager::decimals(const QtProperty *property) const
+{
+    return getData<int>(d_ptr->m_values, &QtPointFPropertyManagerPrivate::Data::decimals, property, 0);
+}
+
+/**
+    \reimp
+*/
+QString QtPointFPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtPointFPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    const QPointF v = it.value().val;
+    const int dec =  it.value().decimals;
+    return QString(tr("(%1, %2)").arg(QString::number(v.x(), 'f', dec))
+                                 .arg(QString::number(v.y(), 'f', dec)));
+}
+
+/**
+    \fn void QtPointFPropertyManager::setValue(QtProperty *property, const QPointF &value)
+
+    Sets the value of the given \a property to \a value. Nested
+    properties are updated automatically.
+
+    \sa value(), valueChanged()
+*/
+void QtPointFPropertyManager::setValue(QtProperty *property, const QPointF &val)
+{
+    const QtPointFPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    if (it.value().val == val)
+        return;
+
+    it.value().val = val;
+    d_ptr->m_doublePropertyManager->setValue(d_ptr->m_propertyToX[property], val.x());
+    d_ptr->m_doublePropertyManager->setValue(d_ptr->m_propertyToY[property], val.y());
+
+    emit propertyChanged(property);
+    emit valueChanged(property, val);
+}
+
+/**
+    \fn void QtPointFPropertyManager::setDecimals(QtProperty *property, int prec)
+
+    Sets the precision of the given \a property to \a prec.
+
+    The valid decimal range is 0-13. The default is 2.
+
+    \sa decimals()
+*/
+void QtPointFPropertyManager::setDecimals(QtProperty *property, int prec)
+{
+    const QtPointFPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtPointFPropertyManagerPrivate::Data data = it.value();
+
+    if (prec > 13)
+        prec = 13;
+    else if (prec < 0)
+        prec = 0;
+
+    if (data.decimals == prec)
+        return;
+
+    data.decimals = prec;
+    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToX[property], prec);
+    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToY[property], prec);
+
+    it.value() = data;
+
+    emit decimalsChanged(property, data.decimals);
+}
+
+/**
+    \reimp
+*/
+void QtPointFPropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QtPointFPropertyManagerPrivate::Data();
+
+    QtProperty *xProp = d_ptr->m_doublePropertyManager->addProperty();
+    xProp->setPropertyName(tr("X"));
+    d_ptr->m_doublePropertyManager->setDecimals(xProp, decimals(property));
+    d_ptr->m_doublePropertyManager->setValue(xProp, 0);
+    d_ptr->m_propertyToX[property] = xProp;
+    d_ptr->m_xToProperty[xProp] = property;
+    property->addSubProperty(xProp);
+
+    QtProperty *yProp = d_ptr->m_doublePropertyManager->addProperty();
+    yProp->setPropertyName(tr("Y"));
+    d_ptr->m_doublePropertyManager->setDecimals(yProp, decimals(property));
+    d_ptr->m_doublePropertyManager->setValue(yProp, 0);
+    d_ptr->m_propertyToY[property] = yProp;
+    d_ptr->m_yToProperty[yProp] = property;
+    property->addSubProperty(yProp);
+}
+
+/**
+    \reimp
+*/
+void QtPointFPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    QtProperty *xProp = d_ptr->m_propertyToX[property];
+    if (xProp) {
+        d_ptr->m_xToProperty.remove(xProp);
+        delete xProp;
+    }
+    d_ptr->m_propertyToX.remove(property);
+
+    QtProperty *yProp = d_ptr->m_propertyToY[property];
+    if (yProp) {
+        d_ptr->m_yToProperty.remove(yProp);
+        delete yProp;
+    }
+    d_ptr->m_propertyToY.remove(property);
+
+    d_ptr->m_values.remove(property);
+}
+
+// QtSizePropertyManager
+
+class QtSizePropertyManagerPrivate
+{
+    QtSizePropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtSizePropertyManager)
+public:
+
+    void slotIntChanged(QtProperty *property, int value);
+    void slotPropertyDestroyed(QtProperty *property);
+    void setValue(QtProperty *property, const QSize &val);
+    void setRange(QtProperty *property,
+                const QSize &minVal, const QSize &maxVal, const QSize &val);
+
+    struct Data
+    {
+        Data() : val(QSize(0, 0)), minVal(QSize(0, 0)), maxVal(QSize(INT_MAX, INT_MAX)) {}
+        QSize val;
+        QSize minVal;
+        QSize maxVal;
+        QSize minimumValue() const { return minVal; }
+        QSize maximumValue() const { return maxVal; }
+        void setMinimumValue(const QSize &newMinVal) { setSizeMinimumData(this, newMinVal); }
+        void setMaximumValue(const QSize &newMaxVal) { setSizeMaximumData(this, newMaxVal); }
+    };
+
+    typedef QMap<const QtProperty *, Data> PropertyValueMap;
+    PropertyValueMap m_values;
+
+    QtIntPropertyManager *m_intPropertyManager;
+
+    QMap<const QtProperty *, QtProperty *> m_propertyToW;
+    QMap<const QtProperty *, QtProperty *> m_propertyToH;
+
+    QMap<const QtProperty *, QtProperty *> m_wToProperty;
+    QMap<const QtProperty *, QtProperty *> m_hToProperty;
+};
+
+void QtSizePropertyManagerPrivate::slotIntChanged(QtProperty *property, int value)
+{
+    if (QtProperty *prop = m_wToProperty.value(property, 0)) {
+        QSize s = m_values[prop].val;
+        s.setWidth(value);
+        q_ptr->setValue(prop, s);
+    } else if (QtProperty *prop = m_hToProperty.value(property, 0)) {
+        QSize s = m_values[prop].val;
+        s.setHeight(value);
+        q_ptr->setValue(prop, s);
+    }
+}
+
+void QtSizePropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
+{
+    if (QtProperty *pointProp = m_wToProperty.value(property, 0)) {
+        m_propertyToW[pointProp] = 0;
+        m_wToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_hToProperty.value(property, 0)) {
+        m_propertyToH[pointProp] = 0;
+        m_hToProperty.remove(property);
+    }
+}
+
+void QtSizePropertyManagerPrivate::setValue(QtProperty *property, const QSize &val)
+{
+    m_intPropertyManager->setValue(m_propertyToW.value(property), val.width());
+    m_intPropertyManager->setValue(m_propertyToH.value(property), val.height());
+}
+
+void QtSizePropertyManagerPrivate::setRange(QtProperty *property,
+                const QSize &minVal, const QSize &maxVal, const QSize &val)
+{
+    QtProperty *wProperty = m_propertyToW.value(property);
+    QtProperty *hProperty = m_propertyToH.value(property);
+    m_intPropertyManager->setRange(wProperty, minVal.width(), maxVal.width());
+    m_intPropertyManager->setValue(wProperty, val.width());
+    m_intPropertyManager->setRange(hProperty, minVal.height(), maxVal.height());
+    m_intPropertyManager->setValue(hProperty, val.height());
+}
+
+/**
+    \class QtSizePropertyManager
+
+    \brief The QtSizePropertyManager provides and manages QSize properties.
+
+    A size property has nested \e width and \e height
+    subproperties. The top-level property's value can be retrieved
+    using the value() function, and set using the setValue() slot.
+
+    The subproperties are created by a QtIntPropertyManager object. This
+    manager can be retrieved using the subIntPropertyManager() function. In
+    order to provide editing widgets for the subproperties in a
+    property browser widget, this manager must be associated with an
+    editor factory.
+
+    A size property also has a range of valid values defined by a
+    minimum size and a maximum size. These sizes can be retrieved
+    using the minimum() and the maximum() functions, and set using the
+    setMinimum() and setMaximum() slots. Alternatively, the range can
+    be defined in one go using the setRange() slot.
+
+    In addition, QtSizePropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes, and the rangeChanged() signal which is emitted whenever
+    such a property changes its range of valid sizes.
+
+    \sa QtAbstractPropertyManager, QtIntPropertyManager, QtSizeFPropertyManager
+*/
+
+/**
+    \fn void QtSizePropertyManager::valueChanged(QtProperty *property, const QSize &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    \fn void QtSizePropertyManager::rangeChanged(QtProperty *property, const QSize &minimum, const QSize &maximum)
+
+    This signal is emitted whenever a property created by this manager
+    changes its range of valid sizes, passing a pointer to the \a
+    property and the new \a minimum and \a maximum sizes.
+
+    \sa setRange()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtSizePropertyManager::QtSizePropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtSizePropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_intPropertyManager = new QtIntPropertyManager(this);
+    connect(d_ptr->m_intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotIntChanged(QtProperty *, int)));
+    connect(d_ptr->m_intPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtSizePropertyManager::~QtSizePropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the manager that creates the nested \e width and \e height
+    subproperties.
+
+    In order to provide editing widgets for the \e width and \e height
+    properties in a property browser widget, this manager must be
+    associated with an editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtIntPropertyManager *QtSizePropertyManager::subIntPropertyManager() const
+{
+    return d_ptr->m_intPropertyManager;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by this manager, this
+    function returns an invalid size
+
+    \sa setValue()
+*/
+QSize QtSizePropertyManager::value(const QtProperty *property) const
+{
+    return getValue<QSize>(d_ptr->m_values, property);
+}
+
+/**
+    Returns the given \a property's minimum size value.
+
+    \sa setMinimum(), maximum(), setRange()
+*/
+QSize QtSizePropertyManager::minimum(const QtProperty *property) const
+{
+    return getMinimum<QSize>(d_ptr->m_values, property);
+}
+
+/**
+    Returns the given \a property's maximum size value.
+
+    \sa setMaximum(), minimum(), setRange()
+*/
+QSize QtSizePropertyManager::maximum(const QtProperty *property) const
+{
+    return getMaximum<QSize>(d_ptr->m_values, property);
+}
+
+/**
+    \reimp
+*/
+QString QtSizePropertyManager::valueText(const QtProperty *property) const
+{
+    const QtSizePropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    const QSize v = it.value().val;
+    return QString(tr("%1 x %2").arg(QString::number(v.width()))
+                                .arg(QString::number(v.height())));
+}
+
+/**
+    \fn void QtSizePropertyManager::setValue(QtProperty *property, const QSize &value)
+
+    Sets the value of the given \a property to \a value.
+
+    If the specified \a value is not valid according to the given \a
+    property's size range, the \a value is adjusted to the nearest
+    valid value within the size range.
+
+    \sa value(), setRange(), valueChanged()
+*/
+void QtSizePropertyManager::setValue(QtProperty *property, const QSize &val)
+{
+    setValueInRange<const QSize &, QtSizePropertyManagerPrivate, QtSizePropertyManager, const QSize>(this, d_ptr,
+                &QtSizePropertyManager::propertyChanged,
+                &QtSizePropertyManager::valueChanged,
+                property, val, &QtSizePropertyManagerPrivate::setValue);
+}
+
+/**
+    Sets the minimum size value for the given \a property to \a minVal.
+
+    When setting the minimum size value, the maximum and current
+    values are adjusted if necessary (ensuring that the size range
+    remains valid and that the current value is within the range).
+
+    \sa minimum(), setRange(), rangeChanged()
+*/
+void QtSizePropertyManager::setMinimum(QtProperty *property, const QSize &minVal)
+{
+    setBorderValue<const QSize &, QtSizePropertyManagerPrivate, QtSizePropertyManager, QSize, QtSizePropertyManagerPrivate::Data>(this, d_ptr,
+                &QtSizePropertyManager::propertyChanged,
+                &QtSizePropertyManager::valueChanged,
+                &QtSizePropertyManager::rangeChanged,
+                property,
+                &QtSizePropertyManagerPrivate::Data::minimumValue,
+                &QtSizePropertyManagerPrivate::Data::setMinimumValue,
+                minVal, &QtSizePropertyManagerPrivate::setRange);
+}
+
+/**
+    Sets the maximum size value for the given \a property to \a maxVal.
+
+    When setting the maximum size value, the minimum and current
+    values are adjusted if necessary (ensuring that the size range
+    remains valid and that the current value is within the range).
+
+    \sa maximum(), setRange(), rangeChanged()
+*/
+void QtSizePropertyManager::setMaximum(QtProperty *property, const QSize &maxVal)
+{
+    setBorderValue<const QSize &, QtSizePropertyManagerPrivate, QtSizePropertyManager, QSize, QtSizePropertyManagerPrivate::Data>(this, d_ptr,
+                &QtSizePropertyManager::propertyChanged,
+                &QtSizePropertyManager::valueChanged,
+                &QtSizePropertyManager::rangeChanged,
+                property,
+                &QtSizePropertyManagerPrivate::Data::maximumValue,
+                &QtSizePropertyManagerPrivate::Data::setMaximumValue,
+                maxVal, &QtSizePropertyManagerPrivate::setRange);
+}
+
+/**
+    \fn void QtSizePropertyManager::setRange(QtProperty *property, const QSize &minimum, const QSize &maximum)
+
+    Sets the range of valid values.
+
+    This is a convenience function defining the range of valid values
+    in one go; setting the \a minimum and \a maximum values for the
+    given \a property with a single function call.
+
+    When setting a new range, the current value is adjusted if
+    necessary (ensuring that the value remains within the range).
+
+    \sa  setMinimum(), setMaximum(), rangeChanged()
+*/
+void QtSizePropertyManager::setRange(QtProperty *property, const QSize &minVal, const QSize &maxVal)
+{
+    setBorderValues<const QSize &, QtSizePropertyManagerPrivate, QtSizePropertyManager, QSize>(this, d_ptr,
+                &QtSizePropertyManager::propertyChanged,
+                &QtSizePropertyManager::valueChanged,
+                &QtSizePropertyManager::rangeChanged,
+                property, minVal, maxVal, &QtSizePropertyManagerPrivate::setRange);
+}
+
+/**
+    \reimp
+*/
+void QtSizePropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QtSizePropertyManagerPrivate::Data();
+
+    QtProperty *wProp = d_ptr->m_intPropertyManager->addProperty();
+    wProp->setPropertyName(tr("Width"));
+    d_ptr->m_intPropertyManager->setValue(wProp, 0);
+    d_ptr->m_intPropertyManager->setMinimum(wProp, 0);
+    d_ptr->m_propertyToW[property] = wProp;
+    d_ptr->m_wToProperty[wProp] = property;
+    property->addSubProperty(wProp);
+
+    QtProperty *hProp = d_ptr->m_intPropertyManager->addProperty();
+    hProp->setPropertyName(tr("Height"));
+    d_ptr->m_intPropertyManager->setValue(hProp, 0);
+    d_ptr->m_intPropertyManager->setMinimum(hProp, 0);
+    d_ptr->m_propertyToH[property] = hProp;
+    d_ptr->m_hToProperty[hProp] = property;
+    property->addSubProperty(hProp);
+}
+
+/**
+    \reimp
+*/
+void QtSizePropertyManager::uninitializeProperty(QtProperty *property)
+{
+    QtProperty *wProp = d_ptr->m_propertyToW[property];
+    if (wProp) {
+        d_ptr->m_wToProperty.remove(wProp);
+        delete wProp;
+    }
+    d_ptr->m_propertyToW.remove(property);
+
+    QtProperty *hProp = d_ptr->m_propertyToH[property];
+    if (hProp) {
+        d_ptr->m_hToProperty.remove(hProp);
+        delete hProp;
+    }
+    d_ptr->m_propertyToH.remove(property);
+
+    d_ptr->m_values.remove(property);
+}
+
+// QtSizeFPropertyManager
+
+class QtSizeFPropertyManagerPrivate
+{
+    QtSizeFPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtSizeFPropertyManager)
+public:
+
+    void slotDoubleChanged(QtProperty *property, double value);
+    void slotPropertyDestroyed(QtProperty *property);
+    void setValue(QtProperty *property, const QSizeF &val);
+    void setRange(QtProperty *property,
+                const QSizeF &minVal, const QSizeF &maxVal, const QSizeF &val);
+
+    struct Data
+    {
+        Data() : val(QSizeF(0, 0)), minVal(QSizeF(0, 0)), maxVal(QSizeF(INT_MAX, INT_MAX)), decimals(2) {}
+        QSizeF val;
+        QSizeF minVal;
+        QSizeF maxVal;
+        int decimals;
+        QSizeF minimumValue() const { return minVal; }
+        QSizeF maximumValue() const { return maxVal; }
+        void setMinimumValue(const QSizeF &newMinVal) { setSizeMinimumData(this, newMinVal); }
+        void setMaximumValue(const QSizeF &newMaxVal) { setSizeMaximumData(this, newMaxVal); }
+    };
+
+    typedef QMap<const QtProperty *, Data> PropertyValueMap;
+    PropertyValueMap m_values;
+
+    QtDoublePropertyManager *m_doublePropertyManager;
+
+    QMap<const QtProperty *, QtProperty *> m_propertyToW;
+    QMap<const QtProperty *, QtProperty *> m_propertyToH;
+
+    QMap<const QtProperty *, QtProperty *> m_wToProperty;
+    QMap<const QtProperty *, QtProperty *> m_hToProperty;
+};
+
+void QtSizeFPropertyManagerPrivate::slotDoubleChanged(QtProperty *property, double value)
+{
+    if (QtProperty *prop = m_wToProperty.value(property, 0)) {
+        QSizeF s = m_values[prop].val;
+        s.setWidth(value);
+        q_ptr->setValue(prop, s);
+    } else if (QtProperty *prop = m_hToProperty.value(property, 0)) {
+        QSizeF s = m_values[prop].val;
+        s.setHeight(value);
+        q_ptr->setValue(prop, s);
+    }
+}
+
+void QtSizeFPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
+{
+    if (QtProperty *pointProp = m_wToProperty.value(property, 0)) {
+        m_propertyToW[pointProp] = 0;
+        m_wToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_hToProperty.value(property, 0)) {
+        m_propertyToH[pointProp] = 0;
+        m_hToProperty.remove(property);
+    }
+}
+
+void QtSizeFPropertyManagerPrivate::setValue(QtProperty *property, const QSizeF &val)
+{
+    m_doublePropertyManager->setValue(m_propertyToW.value(property), val.width());
+    m_doublePropertyManager->setValue(m_propertyToH.value(property), val.height());
+}
+
+void QtSizeFPropertyManagerPrivate::setRange(QtProperty *property,
+                const QSizeF &minVal, const QSizeF &maxVal, const QSizeF &val)
+{
+    m_doublePropertyManager->setRange(m_propertyToW[property], minVal.width(), maxVal.width());
+    m_doublePropertyManager->setValue(m_propertyToW[property], val.width());
+    m_doublePropertyManager->setRange(m_propertyToH[property], minVal.height(), maxVal.height());
+    m_doublePropertyManager->setValue(m_propertyToH[property], val.height());
+}
+
+/**
+    \class QtSizeFPropertyManager
+
+    \brief The QtSizeFPropertyManager provides and manages QSizeF properties.
+
+    A size property has nested \e width and \e height
+    subproperties. The top-level property's value can be retrieved
+    using the value() function, and set using the setValue() slot.
+
+    The subproperties are created by a QtDoublePropertyManager object. This
+    manager can be retrieved using the subDoublePropertyManager() function. In
+    order to provide editing widgets for the subproperties in a
+    property browser widget, this manager must be associated with an
+    editor factory.
+
+    A size property also has a range of valid values defined by a
+    minimum size and a maximum size. These sizes can be retrieved
+    using the minimum() and the maximum() functions, and set using the
+    setMinimum() and setMaximum() slots. Alternatively, the range can
+    be defined in one go using the setRange() slot.
+
+    In addition, QtSizeFPropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes, and the rangeChanged() signal which is emitted whenever
+    such a property changes its range of valid sizes.
+
+    \sa QtAbstractPropertyManager, QtDoublePropertyManager, QtSizePropertyManager
+*/
+
+/**
+    \fn void QtSizeFPropertyManager::valueChanged(QtProperty *property, const QSizeF &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    \fn void QtSizeFPropertyManager::rangeChanged(QtProperty *property, const QSizeF &minimum, const QSizeF &maximum)
+
+    This signal is emitted whenever a property created by this manager
+    changes its range of valid sizes, passing a pointer to the \a
+    property and the new \a minimum and \a maximum sizes.
+
+    \sa setRange()
+*/
+
+/**
+    \fn void QtSizeFPropertyManager::decimalsChanged(QtProperty *property, int prec)
+
+    This signal is emitted whenever a property created by this manager
+    changes its precision of value, passing a pointer to the
+    \a property and the new \a prec value
+
+    \sa setDecimals()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtSizeFPropertyManager::QtSizeFPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtSizeFPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_doublePropertyManager = new QtDoublePropertyManager(this);
+    connect(d_ptr->m_doublePropertyManager, SIGNAL(valueChanged(QtProperty *, double)),
+                this, SLOT(slotDoubleChanged(QtProperty *, double)));
+    connect(d_ptr->m_doublePropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtSizeFPropertyManager::~QtSizeFPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the manager that creates the nested \e width and \e height
+    subproperties.
+
+    In order to provide editing widgets for the \e width and \e height
+    properties in a property browser widget, this manager must be
+    associated with an editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtDoublePropertyManager *QtSizeFPropertyManager::subDoublePropertyManager() const
+{
+    return d_ptr->m_doublePropertyManager;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by this manager, this
+    function returns an invalid size
+
+    \sa setValue()
+*/
+QSizeF QtSizeFPropertyManager::value(const QtProperty *property) const
+{
+    return getValue<QSizeF>(d_ptr->m_values, property);
+}
+
+/**
+    Returns the given \a property's precision, in decimals.
+
+    \sa setDecimals()
+*/
+int QtSizeFPropertyManager::decimals(const QtProperty *property) const
+{
+    return getData<int>(d_ptr->m_values, &QtSizeFPropertyManagerPrivate::Data::decimals, property, 0);
+}
+
+/**
+    Returns the given \a property's minimum size value.
+
+    \sa setMinimum(), maximum(), setRange()
+*/
+QSizeF QtSizeFPropertyManager::minimum(const QtProperty *property) const
+{
+    return getMinimum<QSizeF>(d_ptr->m_values, property);
+}
+
+/**
+    Returns the given \a property's maximum size value.
+
+    \sa setMaximum(), minimum(), setRange()
+*/
+QSizeF QtSizeFPropertyManager::maximum(const QtProperty *property) const
+{
+    return getMaximum<QSizeF>(d_ptr->m_values, property);
+}
+
+/**
+    \reimp
+*/
+QString QtSizeFPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtSizeFPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    const QSizeF v = it.value().val;
+    const int dec = it.value().decimals;
+    return QString(tr("%1 x %2").arg(QString::number(v.width(), 'f', dec))
+                                .arg(QString::number(v.height(), 'f', dec)));
+}
+
+/**
+    \fn void QtSizeFPropertyManager::setValue(QtProperty *property, const QSizeF &value)
+
+    Sets the value of the given \a property to \a value.
+
+    If the specified \a value is not valid according to the given \a
+    property's size range, the \a value is adjusted to the nearest
+    valid value within the size range.
+
+    \sa value(), setRange(), valueChanged()
+*/
+void QtSizeFPropertyManager::setValue(QtProperty *property, const QSizeF &val)
+{
+    setValueInRange<const QSizeF &, QtSizeFPropertyManagerPrivate, QtSizeFPropertyManager, QSizeF>(this, d_ptr,
+                &QtSizeFPropertyManager::propertyChanged,
+                &QtSizeFPropertyManager::valueChanged,
+                property, val, &QtSizeFPropertyManagerPrivate::setValue);
+}
+
+/**
+    \fn void QtSizeFPropertyManager::setDecimals(QtProperty *property, int prec)
+
+    Sets the precision of the given \a property to \a prec.
+
+    The valid decimal range is 0-13. The default is 2.
+
+    \sa decimals()
+*/
+void QtSizeFPropertyManager::setDecimals(QtProperty *property, int prec)
+{
+    const QtSizeFPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtSizeFPropertyManagerPrivate::Data data = it.value();
+
+    if (prec > 13)
+        prec = 13;
+    else if (prec < 0)
+        prec = 0;
+
+    if (data.decimals == prec)
+        return;
+
+    data.decimals = prec;
+    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToW[property], prec);
+    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToH[property], prec);
+
+    it.value() = data;
+
+    emit decimalsChanged(property, data.decimals);
+}
+
+/**
+    Sets the minimum size value for the given \a property to \a minVal.
+
+    When setting the minimum size value, the maximum and current
+    values are adjusted if necessary (ensuring that the size range
+    remains valid and that the current value is within the range).
+
+    \sa minimum(), setRange(), rangeChanged()
+*/
+void QtSizeFPropertyManager::setMinimum(QtProperty *property, const QSizeF &minVal)
+{
+    setBorderValue<const QSizeF &, QtSizeFPropertyManagerPrivate, QtSizeFPropertyManager, QSizeF, QtSizeFPropertyManagerPrivate::Data>(this, d_ptr,
+                &QtSizeFPropertyManager::propertyChanged,
+                &QtSizeFPropertyManager::valueChanged,
+                &QtSizeFPropertyManager::rangeChanged,
+                property,
+                &QtSizeFPropertyManagerPrivate::Data::minimumValue,
+                &QtSizeFPropertyManagerPrivate::Data::setMinimumValue,
+                minVal, &QtSizeFPropertyManagerPrivate::setRange);
+}
+
+/**
+    Sets the maximum size value for the given \a property to \a maxVal.
+
+    When setting the maximum size value, the minimum and current
+    values are adjusted if necessary (ensuring that the size range
+    remains valid and that the current value is within the range).
+
+    \sa maximum(), setRange(), rangeChanged()
+*/
+void QtSizeFPropertyManager::setMaximum(QtProperty *property, const QSizeF &maxVal)
+{
+    setBorderValue<const QSizeF &, QtSizeFPropertyManagerPrivate, QtSizeFPropertyManager, QSizeF, QtSizeFPropertyManagerPrivate::Data>(this, d_ptr,
+                &QtSizeFPropertyManager::propertyChanged,
+                &QtSizeFPropertyManager::valueChanged,
+                &QtSizeFPropertyManager::rangeChanged,
+                property,
+                &QtSizeFPropertyManagerPrivate::Data::maximumValue,
+                &QtSizeFPropertyManagerPrivate::Data::setMaximumValue,
+                maxVal, &QtSizeFPropertyManagerPrivate::setRange);
+}
+
+/**
+    \fn void QtSizeFPropertyManager::setRange(QtProperty *property, const QSizeF &minimum, const QSizeF &maximum)
+
+    Sets the range of valid values.
+
+    This is a convenience function defining the range of valid values
+    in one go; setting the \a minimum and \a maximum values for the
+    given \a property with a single function call.
+
+    When setting a new range, the current value is adjusted if
+    necessary (ensuring that the value remains within the range).
+
+    \sa  setMinimum(), setMaximum(), rangeChanged()
+*/
+void QtSizeFPropertyManager::setRange(QtProperty *property, const QSizeF &minVal, const QSizeF &maxVal)
+{
+    setBorderValues<const QSizeF &, QtSizeFPropertyManagerPrivate, QtSizeFPropertyManager, QSizeF>(this, d_ptr,
+                &QtSizeFPropertyManager::propertyChanged,
+                &QtSizeFPropertyManager::valueChanged,
+                &QtSizeFPropertyManager::rangeChanged,
+                property, minVal, maxVal, &QtSizeFPropertyManagerPrivate::setRange);
+}
+
+/**
+    \reimp
+*/
+void QtSizeFPropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QtSizeFPropertyManagerPrivate::Data();
+
+    QtProperty *wProp = d_ptr->m_doublePropertyManager->addProperty();
+    wProp->setPropertyName(tr("Width"));
+    d_ptr->m_doublePropertyManager->setDecimals(wProp, decimals(property));
+    d_ptr->m_doublePropertyManager->setValue(wProp, 0);
+    d_ptr->m_doublePropertyManager->setMinimum(wProp, 0);
+    d_ptr->m_propertyToW[property] = wProp;
+    d_ptr->m_wToProperty[wProp] = property;
+    property->addSubProperty(wProp);
+
+    QtProperty *hProp = d_ptr->m_doublePropertyManager->addProperty();
+    hProp->setPropertyName(tr("Height"));
+    d_ptr->m_doublePropertyManager->setDecimals(hProp, decimals(property));
+    d_ptr->m_doublePropertyManager->setValue(hProp, 0);
+    d_ptr->m_doublePropertyManager->setMinimum(hProp, 0);
+    d_ptr->m_propertyToH[property] = hProp;
+    d_ptr->m_hToProperty[hProp] = property;
+    property->addSubProperty(hProp);
+}
+
+/**
+    \reimp
+*/
+void QtSizeFPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    QtProperty *wProp = d_ptr->m_propertyToW[property];
+    if (wProp) {
+        d_ptr->m_wToProperty.remove(wProp);
+        delete wProp;
+    }
+    d_ptr->m_propertyToW.remove(property);
+
+    QtProperty *hProp = d_ptr->m_propertyToH[property];
+    if (hProp) {
+        d_ptr->m_hToProperty.remove(hProp);
+        delete hProp;
+    }
+    d_ptr->m_propertyToH.remove(property);
+
+    d_ptr->m_values.remove(property);
+}
+
+// QtRectPropertyManager
+
+class QtRectPropertyManagerPrivate
+{
+    QtRectPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtRectPropertyManager)
+public:
+
+    void slotIntChanged(QtProperty *property, int value);
+    void slotPropertyDestroyed(QtProperty *property);
+    void setConstraint(QtProperty *property, const QRect &constraint, const QRect &val);
+
+    struct Data
+    {
+        Data() : val(0, 0, 0, 0) {}
+        QRect val;
+        QRect constraint;
+    };
+
+    typedef QMap<const QtProperty *, Data> PropertyValueMap;
+    PropertyValueMap m_values;
+
+    QtIntPropertyManager *m_intPropertyManager;
+
+    QMap<const QtProperty *, QtProperty *> m_propertyToX;
+    QMap<const QtProperty *, QtProperty *> m_propertyToY;
+    QMap<const QtProperty *, QtProperty *> m_propertyToW;
+    QMap<const QtProperty *, QtProperty *> m_propertyToH;
+
+    QMap<const QtProperty *, QtProperty *> m_xToProperty;
+    QMap<const QtProperty *, QtProperty *> m_yToProperty;
+    QMap<const QtProperty *, QtProperty *> m_wToProperty;
+    QMap<const QtProperty *, QtProperty *> m_hToProperty;
+};
+
+void QtRectPropertyManagerPrivate::slotIntChanged(QtProperty *property, int value)
+{
+    if (QtProperty *prop = m_xToProperty.value(property, 0)) {
+        QRect r = m_values[prop].val;
+        r.moveLeft(value);
+        q_ptr->setValue(prop, r);
+    } else if (QtProperty *prop = m_yToProperty.value(property)) {
+        QRect r = m_values[prop].val;
+        r.moveTop(value);
+        q_ptr->setValue(prop, r);
+    } else if (QtProperty *prop = m_wToProperty.value(property, 0)) {
+        Data data = m_values[prop];
+        QRect r = data.val;
+        r.setWidth(value);
+        if (!data.constraint.isNull() && data.constraint.x() + data.constraint.width() < r.x() + r.width()) {
+            r.moveLeft(data.constraint.left() + data.constraint.width() - r.width());
+        }
+        q_ptr->setValue(prop, r);
+    } else if (QtProperty *prop = m_hToProperty.value(property, 0)) {
+        Data data = m_values[prop];
+        QRect r = data.val;
+        r.setHeight(value);
+        if (!data.constraint.isNull() && data.constraint.y() + data.constraint.height() < r.y() + r.height()) {
+            r.moveTop(data.constraint.top() + data.constraint.height() - r.height());
+        }
+        q_ptr->setValue(prop, r);
+    }
+}
+
+void QtRectPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
+{
+    if (QtProperty *pointProp = m_xToProperty.value(property, 0)) {
+        m_propertyToX[pointProp] = 0;
+        m_xToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_yToProperty.value(property, 0)) {
+        m_propertyToY[pointProp] = 0;
+        m_yToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_wToProperty.value(property, 0)) {
+        m_propertyToW[pointProp] = 0;
+        m_wToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_hToProperty.value(property, 0)) {
+        m_propertyToH[pointProp] = 0;
+        m_hToProperty.remove(property);
+    }
+}
+
+void QtRectPropertyManagerPrivate::setConstraint(QtProperty *property,
+            const QRect &constraint, const QRect &val)
+{
+    const bool isNull = constraint.isNull();
+    const int left   = isNull ? INT_MIN : constraint.left();
+    const int right  = isNull ? INT_MAX : constraint.left() + constraint.width();
+    const int top    = isNull ? INT_MIN : constraint.top();
+    const int bottom = isNull ? INT_MAX : constraint.top() + constraint.height();
+    const int width  = isNull ? INT_MAX : constraint.width();
+    const int height = isNull ? INT_MAX : constraint.height();
+
+    m_intPropertyManager->setRange(m_propertyToX[property], left, right);
+    m_intPropertyManager->setRange(m_propertyToY[property], top, bottom);
+    m_intPropertyManager->setRange(m_propertyToW[property], 0, width);
+    m_intPropertyManager->setRange(m_propertyToH[property], 0, height);
+
+    m_intPropertyManager->setValue(m_propertyToX[property], val.x());
+    m_intPropertyManager->setValue(m_propertyToY[property], val.y());
+    m_intPropertyManager->setValue(m_propertyToW[property], val.width());
+    m_intPropertyManager->setValue(m_propertyToH[property], val.height());
+}
+
+/**
+    \class QtRectPropertyManager
+
+    \brief The QtRectPropertyManager provides and manages QRect properties.
+
+    A rectangle property has nested \e x, \e y, \e width and \e height
+    subproperties. The top-level property's value can be retrieved
+    using the value() function, and set using the setValue() slot.
+
+    The subproperties are created by a QtIntPropertyManager object. This
+    manager can be retrieved using the subIntPropertyManager() function. In
+    order to provide editing widgets for the subproperties in a
+    property browser widget, this manager must be associated with an
+    editor factory.
+
+    A rectangle property also has a constraint rectangle which can be
+    retrieved using the constraint() function, and set using the
+    setConstraint() slot.
+
+    In addition, QtRectPropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes, and the constraintChanged() signal which is emitted
+    whenever such a property changes its constraint rectangle.
+
+    \sa QtAbstractPropertyManager, QtIntPropertyManager, QtRectFPropertyManager
+*/
+
+/**
+    \fn void QtRectPropertyManager::valueChanged(QtProperty *property, const QRect &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    \fn void QtRectPropertyManager::constraintChanged(QtProperty *property, const QRect &constraint)
+
+    This signal is emitted whenever property changes its constraint
+    rectangle, passing a pointer to the \a property and the new \a
+    constraint rectangle as parameters.
+
+    \sa setConstraint()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtRectPropertyManager::QtRectPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtRectPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_intPropertyManager = new QtIntPropertyManager(this);
+    connect(d_ptr->m_intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotIntChanged(QtProperty *, int)));
+    connect(d_ptr->m_intPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtRectPropertyManager::~QtRectPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the manager that creates the nested \e x, \e y, \e width
+    and \e height subproperties.
+
+    In order to provide editing widgets for the mentioned
+    subproperties in a property browser widget, this manager must be
+    associated with an editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtIntPropertyManager *QtRectPropertyManager::subIntPropertyManager() const
+{
+    return d_ptr->m_intPropertyManager;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by this manager, this
+    function returns an invalid rectangle.
+
+    \sa setValue(), constraint()
+*/
+QRect QtRectPropertyManager::value(const QtProperty *property) const
+{
+    return getValue<QRect>(d_ptr->m_values, property);
+}
+
+/**
+    Returns the given \a property's constraining rectangle. If returned value is null QRect it means there is no constraint applied.
+
+    \sa value(), setConstraint()
+*/
+QRect QtRectPropertyManager::constraint(const QtProperty *property) const
+{
+    return getData<QRect>(d_ptr->m_values, &QtRectPropertyManagerPrivate::Data::constraint, property, QRect());
+}
+
+/**
+    \reimp
+*/
+QString QtRectPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtRectPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    const QRect v = it.value().val;
+    return QString(tr("[(%1, %2), %3 x %4]").arg(QString::number(v.x()))
+                                .arg(QString::number(v.y()))
+                                .arg(QString::number(v.width()))
+                                .arg(QString::number(v.height())));
+}
+
+/**
+    \fn void QtRectPropertyManager::setValue(QtProperty *property, const QRect &value)
+
+    Sets the value of the given \a property to \a value. Nested
+    properties are updated automatically.
+
+    If the specified \a value is not inside the given \a property's
+    constraining rectangle, the value is adjusted accordingly to fit
+    within the constraint.
+
+    \sa value(), setConstraint(), valueChanged()
+*/
+void QtRectPropertyManager::setValue(QtProperty *property, const QRect &val)
+{
+    const QtRectPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtRectPropertyManagerPrivate::Data data = it.value();
+
+    QRect newRect = val.normalized();
+    if (!data.constraint.isNull() && !data.constraint.contains(newRect)) {
+        const QRect r1 = data.constraint;
+        const QRect r2 = newRect;
+        newRect.setLeft(qMax(r1.left(), r2.left()));
+        newRect.setRight(qMin(r1.right(), r2.right()));
+        newRect.setTop(qMax(r1.top(), r2.top()));
+        newRect.setBottom(qMin(r1.bottom(), r2.bottom()));
+        if (newRect.width() < 0 || newRect.height() < 0)
+            return;
+    }
+
+    if (data.val == newRect)
+        return;
+
+    data.val = newRect;
+
+    it.value() = data;
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToX[property], newRect.x());
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToY[property], newRect.y());
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToW[property], newRect.width());
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToH[property], newRect.height());
+
+    emit propertyChanged(property);
+    emit valueChanged(property, data.val);
+}
+
+/**
+    Sets the given \a property's constraining rectangle to \a
+    constraint.
+
+    When setting the constraint, the current value is adjusted if
+    necessary (ensuring that the current rectangle value is inside the
+    constraint). In order to reset the constraint pass a null QRect value.
+
+    \sa setValue(), constraint(), constraintChanged()
+*/
+void QtRectPropertyManager::setConstraint(QtProperty *property, const QRect &constraint)
+{
+    const QtRectPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtRectPropertyManagerPrivate::Data data = it.value();
+
+    QRect newConstraint = constraint.normalized();
+    if (data.constraint == newConstraint)
+        return;
+
+    const QRect oldVal = data.val;
+
+    data.constraint = newConstraint;
+
+    if (!data.constraint.isNull() && !data.constraint.contains(oldVal)) {
+        QRect r1 = data.constraint;
+        QRect r2 = data.val;
+
+        if (r2.width() > r1.width())
+            r2.setWidth(r1.width());
+        if (r2.height() > r1.height())
+            r2.setHeight(r1.height());
+        if (r2.left() < r1.left())
+            r2.moveLeft(r1.left());
+        else if (r2.right() > r1.right())
+            r2.moveRight(r1.right());
+        if (r2.top() < r1.top())
+            r2.moveTop(r1.top());
+        else if (r2.bottom() > r1.bottom())
+            r2.moveBottom(r1.bottom());
+
+        data.val = r2;
+    }
+
+    it.value() = data;
+
+    emit constraintChanged(property, data.constraint);
+
+    d_ptr->setConstraint(property, data.constraint, data.val);
+
+    if (data.val == oldVal)
+        return;
+
+    emit propertyChanged(property);
+    emit valueChanged(property, data.val);
+}
+
+/**
+    \reimp
+*/
+void QtRectPropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QtRectPropertyManagerPrivate::Data();
+
+    QtProperty *xProp = d_ptr->m_intPropertyManager->addProperty();
+    xProp->setPropertyName(tr("X"));
+    d_ptr->m_intPropertyManager->setValue(xProp, 0);
+    d_ptr->m_propertyToX[property] = xProp;
+    d_ptr->m_xToProperty[xProp] = property;
+    property->addSubProperty(xProp);
+
+    QtProperty *yProp = d_ptr->m_intPropertyManager->addProperty();
+    yProp->setPropertyName(tr("Y"));
+    d_ptr->m_intPropertyManager->setValue(yProp, 0);
+    d_ptr->m_propertyToY[property] = yProp;
+    d_ptr->m_yToProperty[yProp] = property;
+    property->addSubProperty(yProp);
+
+    QtProperty *wProp = d_ptr->m_intPropertyManager->addProperty();
+    wProp->setPropertyName(tr("Width"));
+    d_ptr->m_intPropertyManager->setValue(wProp, 0);
+    d_ptr->m_intPropertyManager->setMinimum(wProp, 0);
+    d_ptr->m_propertyToW[property] = wProp;
+    d_ptr->m_wToProperty[wProp] = property;
+    property->addSubProperty(wProp);
+
+    QtProperty *hProp = d_ptr->m_intPropertyManager->addProperty();
+    hProp->setPropertyName(tr("Height"));
+    d_ptr->m_intPropertyManager->setValue(hProp, 0);
+    d_ptr->m_intPropertyManager->setMinimum(hProp, 0);
+    d_ptr->m_propertyToH[property] = hProp;
+    d_ptr->m_hToProperty[hProp] = property;
+    property->addSubProperty(hProp);
+}
+
+/**
+    \reimp
+*/
+void QtRectPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    QtProperty *xProp = d_ptr->m_propertyToX[property];
+    if (xProp) {
+        d_ptr->m_xToProperty.remove(xProp);
+        delete xProp;
+    }
+    d_ptr->m_propertyToX.remove(property);
+
+    QtProperty *yProp = d_ptr->m_propertyToY[property];
+    if (yProp) {
+        d_ptr->m_yToProperty.remove(yProp);
+        delete yProp;
+    }
+    d_ptr->m_propertyToY.remove(property);
+
+    QtProperty *wProp = d_ptr->m_propertyToW[property];
+    if (wProp) {
+        d_ptr->m_wToProperty.remove(wProp);
+        delete wProp;
+    }
+    d_ptr->m_propertyToW.remove(property);
+
+    QtProperty *hProp = d_ptr->m_propertyToH[property];
+    if (hProp) {
+        d_ptr->m_hToProperty.remove(hProp);
+        delete hProp;
+    }
+    d_ptr->m_propertyToH.remove(property);
+
+    d_ptr->m_values.remove(property);
+}
+
+// QtRectFPropertyManager
+
+class QtRectFPropertyManagerPrivate
+{
+    QtRectFPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtRectFPropertyManager)
+public:
+
+    void slotDoubleChanged(QtProperty *property, double value);
+    void slotPropertyDestroyed(QtProperty *property);
+    void setConstraint(QtProperty *property, const QRectF &constraint, const QRectF &val);
+
+    struct Data
+    {
+        Data() : val(0, 0, 0, 0), decimals(2) {}
+        QRectF val;
+        QRectF constraint;
+        int decimals;
+    };
+
+    typedef QMap<const QtProperty *, Data> PropertyValueMap;
+    PropertyValueMap m_values;
+
+    QtDoublePropertyManager *m_doublePropertyManager;
+
+    QMap<const QtProperty *, QtProperty *> m_propertyToX;
+    QMap<const QtProperty *, QtProperty *> m_propertyToY;
+    QMap<const QtProperty *, QtProperty *> m_propertyToW;
+    QMap<const QtProperty *, QtProperty *> m_propertyToH;
+
+    QMap<const QtProperty *, QtProperty *> m_xToProperty;
+    QMap<const QtProperty *, QtProperty *> m_yToProperty;
+    QMap<const QtProperty *, QtProperty *> m_wToProperty;
+    QMap<const QtProperty *, QtProperty *> m_hToProperty;
+};
+
+void QtRectFPropertyManagerPrivate::slotDoubleChanged(QtProperty *property, double value)
+{
+    if (QtProperty *prop = m_xToProperty.value(property, 0)) {
+        QRectF r = m_values[prop].val;
+        r.moveLeft(value);
+        q_ptr->setValue(prop, r);
+    } else if (QtProperty *prop = m_yToProperty.value(property, 0)) {
+        QRectF r = m_values[prop].val;
+        r.moveTop(value);
+        q_ptr->setValue(prop, r);
+    } else if (QtProperty *prop = m_wToProperty.value(property, 0)) {
+        Data data = m_values[prop];
+        QRectF r = data.val;
+        r.setWidth(value);
+        if (!data.constraint.isNull() && data.constraint.x() + data.constraint.width() < r.x() + r.width()) {
+            r.moveLeft(data.constraint.left() + data.constraint.width() - r.width());
+        }
+        q_ptr->setValue(prop, r);
+    } else if (QtProperty *prop = m_hToProperty.value(property, 0)) {
+        Data data = m_values[prop];
+        QRectF r = data.val;
+        r.setHeight(value);
+        if (!data.constraint.isNull() && data.constraint.y() + data.constraint.height() < r.y() + r.height()) {
+            r.moveTop(data.constraint.top() + data.constraint.height() - r.height());
+        }
+        q_ptr->setValue(prop, r);
+    }
+}
+
+void QtRectFPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
+{
+    if (QtProperty *pointProp = m_xToProperty.value(property, 0)) {
+        m_propertyToX[pointProp] = 0;
+        m_xToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_yToProperty.value(property, 0)) {
+        m_propertyToY[pointProp] = 0;
+        m_yToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_wToProperty.value(property, 0)) {
+        m_propertyToW[pointProp] = 0;
+        m_wToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_hToProperty.value(property, 0)) {
+        m_propertyToH[pointProp] = 0;
+        m_hToProperty.remove(property);
+    }
+}
+
+void QtRectFPropertyManagerPrivate::setConstraint(QtProperty *property,
+            const QRectF &constraint, const QRectF &val)
+{
+    const bool isNull = constraint.isNull();
+    const float left   = isNull ? FLT_MIN : constraint.left();
+    const float right  = isNull ? FLT_MAX : constraint.left() + constraint.width();
+    const float top    = isNull ? FLT_MIN : constraint.top();
+    const float bottom = isNull ? FLT_MAX : constraint.top() + constraint.height();
+    const float width  = isNull ? FLT_MAX : constraint.width();
+    const float height = isNull ? FLT_MAX : constraint.height();
+
+    m_doublePropertyManager->setRange(m_propertyToX[property], left, right);
+    m_doublePropertyManager->setRange(m_propertyToY[property], top, bottom);
+    m_doublePropertyManager->setRange(m_propertyToW[property], 0, width);
+    m_doublePropertyManager->setRange(m_propertyToH[property], 0, height);
+
+    m_doublePropertyManager->setValue(m_propertyToX[property], val.x());
+    m_doublePropertyManager->setValue(m_propertyToY[property], val.y());
+    m_doublePropertyManager->setValue(m_propertyToW[property], val.width());
+    m_doublePropertyManager->setValue(m_propertyToH[property], val.height());
+}
+
+/**
+    \class QtRectFPropertyManager
+
+    \brief The QtRectFPropertyManager provides and manages QRectF properties.
+
+    A rectangle property has nested \e x, \e y, \e width and \e height
+    subproperties. The top-level property's value can be retrieved
+    using the value() function, and set using the setValue() slot.
+
+    The subproperties are created by a QtDoublePropertyManager object. This
+    manager can be retrieved using the subDoublePropertyManager() function. In
+    order to provide editing widgets for the subproperties in a
+    property browser widget, this manager must be associated with an
+    editor factory.
+
+    A rectangle property also has a constraint rectangle which can be
+    retrieved using the constraint() function, and set using the
+    setConstraint() slot.
+
+    In addition, QtRectFPropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes, and the constraintChanged() signal which is emitted
+    whenever such a property changes its constraint rectangle.
+
+    \sa QtAbstractPropertyManager, QtDoublePropertyManager, QtRectPropertyManager
+*/
+
+/**
+    \fn void QtRectFPropertyManager::valueChanged(QtProperty *property, const QRectF &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    \fn void QtRectFPropertyManager::constraintChanged(QtProperty *property, const QRectF &constraint)
+
+    This signal is emitted whenever property changes its constraint
+    rectangle, passing a pointer to the \a property and the new \a
+    constraint rectangle as parameters.
+
+    \sa setConstraint()
+*/
+
+/**
+    \fn void QtRectFPropertyManager::decimalsChanged(QtProperty *property, int prec)
+
+    This signal is emitted whenever a property created by this manager
+    changes its precision of value, passing a pointer to the
+    \a property and the new \a prec value
+
+    \sa setDecimals()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtRectFPropertyManager::QtRectFPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtRectFPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_doublePropertyManager = new QtDoublePropertyManager(this);
+    connect(d_ptr->m_doublePropertyManager, SIGNAL(valueChanged(QtProperty *, double)),
+                this, SLOT(slotDoubleChanged(QtProperty *, double)));
+    connect(d_ptr->m_doublePropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtRectFPropertyManager::~QtRectFPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the manager that creates the nested \e x, \e y, \e width
+    and \e height subproperties.
+
+    In order to provide editing widgets for the mentioned
+    subproperties in a property browser widget, this manager must be
+    associated with an editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtDoublePropertyManager *QtRectFPropertyManager::subDoublePropertyManager() const
+{
+    return d_ptr->m_doublePropertyManager;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by this manager, this
+    function returns an invalid rectangle.
+
+    \sa setValue(), constraint()
+*/
+QRectF QtRectFPropertyManager::value(const QtProperty *property) const
+{
+    return getValue<QRectF>(d_ptr->m_values, property);
+}
+
+/**
+    Returns the given \a property's precision, in decimals.
+
+    \sa setDecimals()
+*/
+int QtRectFPropertyManager::decimals(const QtProperty *property) const
+{
+    return getData<int>(d_ptr->m_values, &QtRectFPropertyManagerPrivate::Data::decimals, property, 0);
+}
+
+/**
+    Returns the given \a property's constraining rectangle. If returned value is null QRectF it means there is no constraint applied.
+
+    \sa value(), setConstraint()
+*/
+QRectF QtRectFPropertyManager::constraint(const QtProperty *property) const
+{
+    return getData<QRectF>(d_ptr->m_values, &QtRectFPropertyManagerPrivate::Data::constraint, property, QRect());
+}
+
+/**
+    \reimp
+*/
+QString QtRectFPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtRectFPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+    const QRectF v = it.value().val;
+    const int dec = it.value().decimals;
+    return QString(tr("[(%1, %2), %3 x %4]").arg(QString::number(v.x(), 'f', dec))
+                                .arg(QString::number(v.y(), 'f', dec))
+                                .arg(QString::number(v.width(), 'f', dec))
+                                .arg(QString::number(v.height(), 'f', dec)));
+}
+
+/**
+    \fn void QtRectFPropertyManager::setValue(QtProperty *property, const QRectF &value)
+
+    Sets the value of the given \a property to \a value. Nested
+    properties are updated automatically.
+
+    If the specified \a value is not inside the given \a property's
+    constraining rectangle, the value is adjusted accordingly to fit
+    within the constraint.
+
+    \sa value(), setConstraint(), valueChanged()
+*/
+void QtRectFPropertyManager::setValue(QtProperty *property, const QRectF &val)
+{
+    const QtRectFPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtRectFPropertyManagerPrivate::Data data = it.value();
+
+    QRectF newRect = val.normalized();
+    if (!data.constraint.isNull() && !data.constraint.contains(newRect)) {
+        const QRectF r1 = data.constraint;
+        const QRectF r2 = newRect;
+        newRect.setLeft(qMax(r1.left(), r2.left()));
+        newRect.setRight(qMin(r1.right(), r2.right()));
+        newRect.setTop(qMax(r1.top(), r2.top()));
+        newRect.setBottom(qMin(r1.bottom(), r2.bottom()));
+        if (newRect.width() < 0 || newRect.height() < 0)
+            return;
+    }
+
+    if (data.val == newRect)
+        return;
+
+    data.val = newRect;
+
+    it.value() = data;
+    d_ptr->m_doublePropertyManager->setValue(d_ptr->m_propertyToX[property], newRect.x());
+    d_ptr->m_doublePropertyManager->setValue(d_ptr->m_propertyToY[property], newRect.y());
+    d_ptr->m_doublePropertyManager->setValue(d_ptr->m_propertyToW[property], newRect.width());
+    d_ptr->m_doublePropertyManager->setValue(d_ptr->m_propertyToH[property], newRect.height());
+
+    emit propertyChanged(property);
+    emit valueChanged(property, data.val);
+}
+
+/**
+    Sets the given \a property's constraining rectangle to \a
+    constraint.
+
+    When setting the constraint, the current value is adjusted if
+    necessary (ensuring that the current rectangle value is inside the
+    constraint). In order to reset the constraint pass a null QRectF value.
+
+    \sa setValue(), constraint(), constraintChanged()
+*/
+void QtRectFPropertyManager::setConstraint(QtProperty *property, const QRectF &constraint)
+{
+    const QtRectFPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtRectFPropertyManagerPrivate::Data data = it.value();
+
+    QRectF newConstraint = constraint.normalized();
+    if (data.constraint == newConstraint)
+        return;
+
+    const QRectF oldVal = data.val;
+
+    data.constraint = newConstraint;
+
+    if (!data.constraint.isNull() && !data.constraint.contains(oldVal)) {
+        QRectF r1 = data.constraint;
+        QRectF r2 = data.val;
+
+        if (r2.width() > r1.width())
+            r2.setWidth(r1.width());
+        if (r2.height() > r1.height())
+            r2.setHeight(r1.height());
+        if (r2.left() < r1.left())
+            r2.moveLeft(r1.left());
+        else if (r2.right() > r1.right())
+            r2.moveRight(r1.right());
+        if (r2.top() < r1.top())
+            r2.moveTop(r1.top());
+        else if (r2.bottom() > r1.bottom())
+            r2.moveBottom(r1.bottom());
+
+        data.val = r2;
+    }
+
+    it.value() = data;
+
+    emit constraintChanged(property, data.constraint);
+
+    d_ptr->setConstraint(property, data.constraint, data.val);
+
+    if (data.val == oldVal)
+        return;
+
+    emit propertyChanged(property);
+    emit valueChanged(property, data.val);
+}
+
+/**
+    \fn void QtRectFPropertyManager::setDecimals(QtProperty *property, int prec)
+
+    Sets the precision of the given \a property to \a prec.
+
+    The valid decimal range is 0-13. The default is 2.
+
+    \sa decimals()
+*/
+void QtRectFPropertyManager::setDecimals(QtProperty *property, int prec)
+{
+    const QtRectFPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtRectFPropertyManagerPrivate::Data data = it.value();
+
+    if (prec > 13)
+        prec = 13;
+    else if (prec < 0)
+        prec = 0;
+
+    if (data.decimals == prec)
+        return;
+
+    data.decimals = prec;
+    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToX[property], prec);
+    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToY[property], prec);
+    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToW[property], prec);
+    d_ptr->m_doublePropertyManager->setDecimals(d_ptr->m_propertyToH[property], prec);
+
+    it.value() = data;
+
+    emit decimalsChanged(property, data.decimals);
+}
+
+/**
+    \reimp
+*/
+void QtRectFPropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QtRectFPropertyManagerPrivate::Data();
+
+    QtProperty *xProp = d_ptr->m_doublePropertyManager->addProperty();
+    xProp->setPropertyName(tr("X"));
+    d_ptr->m_doublePropertyManager->setDecimals(xProp, decimals(property));
+    d_ptr->m_doublePropertyManager->setValue(xProp, 0);
+    d_ptr->m_propertyToX[property] = xProp;
+    d_ptr->m_xToProperty[xProp] = property;
+    property->addSubProperty(xProp);
+
+    QtProperty *yProp = d_ptr->m_doublePropertyManager->addProperty();
+    yProp->setPropertyName(tr("Y"));
+    d_ptr->m_doublePropertyManager->setDecimals(yProp, decimals(property));
+    d_ptr->m_doublePropertyManager->setValue(yProp, 0);
+    d_ptr->m_propertyToY[property] = yProp;
+    d_ptr->m_yToProperty[yProp] = property;
+    property->addSubProperty(yProp);
+
+    QtProperty *wProp = d_ptr->m_doublePropertyManager->addProperty();
+    wProp->setPropertyName(tr("Width"));
+    d_ptr->m_doublePropertyManager->setDecimals(wProp, decimals(property));
+    d_ptr->m_doublePropertyManager->setValue(wProp, 0);
+    d_ptr->m_doublePropertyManager->setMinimum(wProp, 0);
+    d_ptr->m_propertyToW[property] = wProp;
+    d_ptr->m_wToProperty[wProp] = property;
+    property->addSubProperty(wProp);
+
+    QtProperty *hProp = d_ptr->m_doublePropertyManager->addProperty();
+    hProp->setPropertyName(tr("Height"));
+    d_ptr->m_doublePropertyManager->setDecimals(hProp, decimals(property));
+    d_ptr->m_doublePropertyManager->setValue(hProp, 0);
+    d_ptr->m_doublePropertyManager->setMinimum(hProp, 0);
+    d_ptr->m_propertyToH[property] = hProp;
+    d_ptr->m_hToProperty[hProp] = property;
+    property->addSubProperty(hProp);
+}
+
+/**
+    \reimp
+*/
+void QtRectFPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    QtProperty *xProp = d_ptr->m_propertyToX[property];
+    if (xProp) {
+        d_ptr->m_xToProperty.remove(xProp);
+        delete xProp;
+    }
+    d_ptr->m_propertyToX.remove(property);
+
+    QtProperty *yProp = d_ptr->m_propertyToY[property];
+    if (yProp) {
+        d_ptr->m_yToProperty.remove(yProp);
+        delete yProp;
+    }
+    d_ptr->m_propertyToY.remove(property);
+
+    QtProperty *wProp = d_ptr->m_propertyToW[property];
+    if (wProp) {
+        d_ptr->m_wToProperty.remove(wProp);
+        delete wProp;
+    }
+    d_ptr->m_propertyToW.remove(property);
+
+    QtProperty *hProp = d_ptr->m_propertyToH[property];
+    if (hProp) {
+        d_ptr->m_hToProperty.remove(hProp);
+        delete hProp;
+    }
+    d_ptr->m_propertyToH.remove(property);
+
+    d_ptr->m_values.remove(property);
+}
+
+// QtEnumPropertyManager
+
+class QtEnumPropertyManagerPrivate
+{
+    QtEnumPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtEnumPropertyManager)
+public:
+
+    struct Data
+    {
+        Data() : val(-1) {}
+        int val;
+        QStringList enumNames;
+        QMap<int, QIcon> enumIcons;
+    };
+
+    typedef QMap<const QtProperty *, Data> PropertyValueMap;
+    PropertyValueMap m_values;
+};
+
+/**
+    \class QtEnumPropertyManager
+
+    \brief The QtEnumPropertyManager provides and manages enum properties.
+
+    Each enum property has an associated list of enum names which can
+    be retrieved using the enumNames() function, and set using the
+    corresponding setEnumNames() function. An enum property's value is
+    represented by an index in this list, and can be retrieved and set
+    using the value() and setValue() slots respectively.
+
+    Each enum value can also have an associated icon. The mapping from
+    values to icons can be set using the setEnumIcons() function and
+    queried with the enumIcons() function.
+
+    In addition, QtEnumPropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes. The enumNamesChanged() or enumIconsChanged() signal is emitted
+    whenever the list of enum names or icons is altered.
+
+    \sa QtAbstractPropertyManager, QtEnumEditorFactory
+*/
+
+/**
+    \fn void QtEnumPropertyManager::valueChanged(QtProperty *property, int value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    \fn void QtEnumPropertyManager::enumNamesChanged(QtProperty *property, const QStringList &names)
+
+    This signal is emitted whenever a property created by this manager
+    changes its enum names, passing a pointer to the \a property and
+    the new \a names as parameters.
+
+    \sa setEnumNames()
+*/
+
+/**
+    \fn void QtEnumPropertyManager::enumIconsChanged(QtProperty *property, const QMap<int, QIcon> &icons)
+
+    This signal is emitted whenever a property created by this manager
+    changes its enum icons, passing a pointer to the \a property and
+    the new mapping of values to \a icons as parameters.
+
+    \sa setEnumIcons()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtEnumPropertyManager::QtEnumPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtEnumPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtEnumPropertyManager::~QtEnumPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the given \a property's value which is an index in the
+    list returned by enumNames()
+
+    If the given property is not managed by this manager, this
+    function returns -1.
+
+    \sa enumNames(), setValue()
+*/
+int QtEnumPropertyManager::value(const QtProperty *property) const
+{
+    return getValue<int>(d_ptr->m_values, property, -1);
+}
+
+/**
+    Returns the given \a property's list of enum names.
+
+    \sa value(), setEnumNames()
+*/
+QStringList QtEnumPropertyManager::enumNames(const QtProperty *property) const
+{
+    return getData<QStringList>(d_ptr->m_values, &QtEnumPropertyManagerPrivate::Data::enumNames, property, QStringList());
+}
+
+/**
+    Returns the given \a property's map of enum values to their icons.
+
+    \sa value(), setEnumIcons()
+*/
+QMap<int, QIcon> QtEnumPropertyManager::enumIcons(const QtProperty *property) const
+{
+    return getData<QMap<int, QIcon> >(d_ptr->m_values, &QtEnumPropertyManagerPrivate::Data::enumIcons, property, QMap<int, QIcon>());
+}
+
+/**
+    \reimp
+*/
+QString QtEnumPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtEnumPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+
+    const QtEnumPropertyManagerPrivate::Data &data = it.value();
+
+    const int v = data.val;
+    if (v >= 0 && v < data.enumNames.count())
+        return data.enumNames.at(v);
+    return QString();
+}
+
+/**
+    \reimp
+*/
+QIcon QtEnumPropertyManager::valueIcon(const QtProperty *property) const
+{
+    const QtEnumPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QIcon();
+
+    const QtEnumPropertyManagerPrivate::Data &data = it.value();
+
+    const int v = data.val;
+    return data.enumIcons.value(v);
+}
+
+/**
+    \fn void QtEnumPropertyManager::setValue(QtProperty *property, int value)
+
+    Sets the value of the given  \a property to \a value.
+
+    The specified \a value must be less than the size of the given \a
+    property's enumNames() list, and larger than (or equal to) 0.
+
+    \sa value(), valueChanged()
+*/
+void QtEnumPropertyManager::setValue(QtProperty *property, int val)
+{
+    const QtEnumPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtEnumPropertyManagerPrivate::Data data = it.value();
+
+    if (val >= data.enumNames.count())
+        return;
+
+    if (val < 0 && data.enumNames.count() > 0)
+        return;
+
+    if (val < 0)
+        val = -1;
+
+    if (data.val == val)
+        return;
+
+    data.val = val;
+
+    it.value() = data;
+
+    emit propertyChanged(property);
+    emit valueChanged(property, data.val);
+}
+
+/**
+    Sets the given \a property's list of enum names to \a
+    enumNames. The \a property's current value is reset to 0
+    indicating the first item of the list.
+
+    If the specified \a enumNames list is empty, the \a property's
+    current value is set to -1.
+
+    \sa enumNames(), enumNamesChanged()
+*/
+void QtEnumPropertyManager::setEnumNames(QtProperty *property, const QStringList &enumNames)
+{
+    const QtEnumPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtEnumPropertyManagerPrivate::Data data = it.value();
+
+    if (data.enumNames == enumNames)
+        return;
+
+    data.enumNames = enumNames;
+
+    data.val = -1;
+
+    if (enumNames.count() > 0)
+        data.val = 0;
+
+    it.value() = data;
+
+    emit enumNamesChanged(property, data.enumNames);
+
+    emit propertyChanged(property);
+    emit valueChanged(property, data.val);
+}
+
+/**
+    Sets the given \a property's map of enum values to their icons to \a
+    enumIcons.
+
+    Each enum value can have associated icon. This association is represented with passed \a enumIcons map.
+
+    \sa enumNames(), enumNamesChanged()
+*/
+void QtEnumPropertyManager::setEnumIcons(QtProperty *property, const QMap<int, QIcon> &enumIcons)
+{
+    const QtEnumPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    it.value().enumIcons = enumIcons;
+
+    emit enumIconsChanged(property, it.value().enumIcons);
+
+    emit propertyChanged(property);
+}
+
+/**
+    \reimp
+*/
+void QtEnumPropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QtEnumPropertyManagerPrivate::Data();
+}
+
+/**
+    \reimp
+*/
+void QtEnumPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    d_ptr->m_values.remove(property);
+}
+
+// QtFlagPropertyManager
+
+class QtFlagPropertyManagerPrivate
+{
+    QtFlagPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtFlagPropertyManager)
+public:
+
+    void slotBoolChanged(QtProperty *property, bool value);
+    void slotPropertyDestroyed(QtProperty *property);
+
+    struct Data
+    {
+        Data() : val(-1) {}
+        int val;
+        QStringList flagNames;
+    };
+
+    typedef QMap<const QtProperty *, Data> PropertyValueMap;
+    PropertyValueMap m_values;
+
+    QtBoolPropertyManager *m_boolPropertyManager;
+
+    QMap<const QtProperty *, QList<QtProperty *> > m_propertyToFlags;
+
+    QMap<const QtProperty *, QtProperty *> m_flagToProperty;
+};
+
+void QtFlagPropertyManagerPrivate::slotBoolChanged(QtProperty *property, bool value)
+{
+    QtProperty *prop = m_flagToProperty.value(property, 0);
+    if (prop == 0)
+        return;
+
+    QListIterator<QtProperty *> itProp(m_propertyToFlags[prop]);
+    int level = 0;
+    while (itProp.hasNext()) {
+        QtProperty *p = itProp.next();
+        if (p == property) {
+            int v = m_values[prop].val;
+            if (value) {
+                v |= (1 << level);
+            } else {
+                v &= ~(1 << level);
+            }
+            q_ptr->setValue(prop, v);
+            return;
+        }
+        level++;
+    }
+}
+
+void QtFlagPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
+{
+    QtProperty *flagProperty = m_flagToProperty.value(property, 0);
+    if (flagProperty == 0)
+        return;
+
+    m_propertyToFlags[flagProperty].replace(m_propertyToFlags[flagProperty].indexOf(property), 0);
+    m_flagToProperty.remove(property);
+}
+
+/**
+    \class QtFlagPropertyManager
+
+    \brief The QtFlagPropertyManager provides and manages flag properties.
+
+    Each flag property has an associated list of flag names which can
+    be retrieved using the flagNames() function, and set using the
+    corresponding setFlagNames() function.
+
+    The flag manager provides properties with nested boolean
+    subproperties representing each flag, i.e. a flag property's value
+    is the binary combination of the subproperties' values. A
+    property's value can be retrieved and set using the value() and
+    setValue() slots respectively. The combination of flags is represented
+    by single int value - that's why it's possible to store up to
+    32 independent flags in one flag property.
+
+    The subproperties are created by a QtBoolPropertyManager object. This
+    manager can be retrieved using the subBoolPropertyManager() function. In
+    order to provide editing widgets for the subproperties in a
+    property browser widget, this manager must be associated with an
+    editor factory.
+
+    In addition, QtFlagPropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes, and the flagNamesChanged() signal which is emitted
+    whenever the list of flag names is altered.
+
+    \sa QtAbstractPropertyManager, QtBoolPropertyManager
+*/
+
+/**
+    \fn void QtFlagPropertyManager::valueChanged(QtProperty *property, int value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a  property and the new
+    \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    \fn void QtFlagPropertyManager::flagNamesChanged(QtProperty *property, const QStringList &names)
+
+    This signal is emitted whenever a property created by this manager
+    changes its flag names, passing a pointer to the \a property and the
+    new \a names as parameters.
+
+    \sa setFlagNames()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtFlagPropertyManager::QtFlagPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtFlagPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_boolPropertyManager = new QtBoolPropertyManager(this);
+    connect(d_ptr->m_boolPropertyManager, SIGNAL(valueChanged(QtProperty *, bool)),
+                this, SLOT(slotBoolChanged(QtProperty *, bool)));
+    connect(d_ptr->m_boolPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtFlagPropertyManager::~QtFlagPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the manager that produces the nested boolean subproperties
+    representing each flag.
+
+    In order to provide editing widgets for the subproperties in a
+    property browser widget, this manager must be associated with an
+    editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtBoolPropertyManager *QtFlagPropertyManager::subBoolPropertyManager() const
+{
+    return d_ptr->m_boolPropertyManager;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given property is not managed by this manager, this
+    function returns 0.
+
+    \sa flagNames(), setValue()
+*/
+int QtFlagPropertyManager::value(const QtProperty *property) const
+{
+    return getValue<int>(d_ptr->m_values, property, 0);
+}
+
+/**
+    Returns the given \a property's list of flag names.
+
+    \sa value(), setFlagNames()
+*/
+QStringList QtFlagPropertyManager::flagNames(const QtProperty *property) const
+{
+    return getData<QStringList>(d_ptr->m_values, &QtFlagPropertyManagerPrivate::Data::flagNames, property, QStringList());
+}
+
+/**
+    \reimp
+*/
+QString QtFlagPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtFlagPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+
+    const QtFlagPropertyManagerPrivate::Data &data = it.value();
+
+    QString str;
+    int level = 0;
+    const QChar bar = QLatin1Char('|');
+    const QStringList::const_iterator fncend = data.flagNames.constEnd();
+    for (QStringList::const_iterator it =  data.flagNames.constBegin(); it != fncend; ++it) {
+        if (data.val & (1 << level)) {
+            if (!str.isEmpty())
+                str += bar;
+            str += *it;
+        }
+
+        level++;
+    }
+    return str;
+}
+
+/**
+    \fn void QtFlagPropertyManager::setValue(QtProperty *property, int value)
+
+    Sets the value of the given \a property to \a value. Nested
+    properties are updated automatically.
+
+    The specified \a value must be less than the binary combination of
+    the property's flagNames() list size (i.e. less than 2\sup n,
+    where \c n is the size of the list) and larger than (or equal to)
+    0.
+
+    \sa value(), valueChanged()
+*/
+void QtFlagPropertyManager::setValue(QtProperty *property, int val)
+{
+    const QtFlagPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtFlagPropertyManagerPrivate::Data data = it.value();
+
+    if (data.val == val)
+        return;
+
+    if (val > (1 << data.flagNames.count()) - 1)
+        return;
+
+    if (val < 0)
+        return;
+
+    data.val = val;
+
+    it.value() = data;
+
+    QListIterator<QtProperty *> itProp(d_ptr->m_propertyToFlags[property]);
+    int level = 0;
+    while (itProp.hasNext()) {
+        QtProperty *prop = itProp.next();
+        if (prop)
+            d_ptr->m_boolPropertyManager->setValue(prop, val & (1 << level));
+        level++;
+    }
+
+    emit propertyChanged(property);
+    emit valueChanged(property, data.val);
+}
+
+/**
+    Sets the given \a property's list of flag names to \a flagNames. The
+    property's current value is reset to 0 indicating the first item
+    of the list.
+
+    \sa flagNames(), flagNamesChanged()
+*/
+void QtFlagPropertyManager::setFlagNames(QtProperty *property, const QStringList &flagNames)
+{
+    const QtFlagPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    QtFlagPropertyManagerPrivate::Data data = it.value();
+
+    if (data.flagNames == flagNames)
+        return;
+
+    data.flagNames = flagNames;
+    data.val = 0;
+
+    it.value() = data;
+
+    QListIterator<QtProperty *> itProp(d_ptr->m_propertyToFlags[property]);
+    while (itProp.hasNext()) {
+        QtProperty *prop = itProp.next();
+        if (prop) {
+            delete prop;
+            d_ptr->m_flagToProperty.remove(prop);
+        }
+    }
+    d_ptr->m_propertyToFlags[property].clear();
+
+    QStringListIterator itFlag(flagNames);
+    while (itFlag.hasNext()) {
+        const QString flagName = itFlag.next();
+        QtProperty *prop = d_ptr->m_boolPropertyManager->addProperty();
+        prop->setPropertyName(flagName);
+        property->addSubProperty(prop);
+        d_ptr->m_propertyToFlags[property].append(prop);
+        d_ptr->m_flagToProperty[prop] = property;
+    }
+
+    emit flagNamesChanged(property, data.flagNames);
+
+    emit propertyChanged(property);
+    emit valueChanged(property, data.val);
+}
+
+/**
+    \reimp
+*/
+void QtFlagPropertyManager::initializeProperty(QtProperty *property)
+{
+    d_ptr->m_values[property] = QtFlagPropertyManagerPrivate::Data();
+
+    d_ptr->m_propertyToFlags[property] = QList<QtProperty *>();
+}
+
+/**
+    \reimp
+*/
+void QtFlagPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    QListIterator<QtProperty *> itProp(d_ptr->m_propertyToFlags[property]);
+    while (itProp.hasNext()) {
+        QtProperty *prop = itProp.next();
+        if (prop) {
+            delete prop;
+            d_ptr->m_flagToProperty.remove(prop);
+        }
+    }
+    d_ptr->m_propertyToFlags.remove(property);
+
+    d_ptr->m_values.remove(property);
+}
+
+// QtSizePolicyPropertyManager
+
+class QtSizePolicyPropertyManagerPrivate
+{
+    QtSizePolicyPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtSizePolicyPropertyManager)
+public:
+
+    QtSizePolicyPropertyManagerPrivate();
+
+    void slotIntChanged(QtProperty *property, int value);
+    void slotEnumChanged(QtProperty *property, int value);
+    void slotPropertyDestroyed(QtProperty *property);
+
+    typedef QMap<const QtProperty *, QSizePolicy> PropertyValueMap;
+    PropertyValueMap m_values;
+
+    QtIntPropertyManager *m_intPropertyManager;
+    QtEnumPropertyManager *m_enumPropertyManager;
+
+    QMap<const QtProperty *, QtProperty *> m_propertyToHPolicy;
+    QMap<const QtProperty *, QtProperty *> m_propertyToVPolicy;
+    QMap<const QtProperty *, QtProperty *> m_propertyToHStretch;
+    QMap<const QtProperty *, QtProperty *> m_propertyToVStretch;
+
+    QMap<const QtProperty *, QtProperty *> m_hPolicyToProperty;
+    QMap<const QtProperty *, QtProperty *> m_vPolicyToProperty;
+    QMap<const QtProperty *, QtProperty *> m_hStretchToProperty;
+    QMap<const QtProperty *, QtProperty *> m_vStretchToProperty;
+};
+
+QtSizePolicyPropertyManagerPrivate::QtSizePolicyPropertyManagerPrivate()
+{
+}
+
+void QtSizePolicyPropertyManagerPrivate::slotIntChanged(QtProperty *property, int value)
+{
+    if (QtProperty *prop = m_hStretchToProperty.value(property, 0)) {
+        QSizePolicy sp = m_values[prop];
+        sp.setHorizontalStretch(value);
+        q_ptr->setValue(prop, sp);
+    } else if (QtProperty *prop = m_vStretchToProperty.value(property, 0)) {
+        QSizePolicy sp = m_values[prop];
+        sp.setVerticalStretch(value);
+        q_ptr->setValue(prop, sp);
+    }
+}
+
+void QtSizePolicyPropertyManagerPrivate::slotEnumChanged(QtProperty *property, int value)
+{
+    if (QtProperty *prop = m_hPolicyToProperty.value(property, 0)) {
+        QSizePolicy sp = m_values[prop];
+        sp.setHorizontalPolicy(metaEnumProvider()->indexToSizePolicy(value));
+        q_ptr->setValue(prop, sp);
+    } else if (QtProperty *prop = m_vPolicyToProperty.value(property, 0)) {
+        QSizePolicy sp = m_values[prop];
+        sp.setVerticalPolicy(metaEnumProvider()->indexToSizePolicy(value));
+        q_ptr->setValue(prop, sp);
+    }
+}
+
+void QtSizePolicyPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
+{
+    if (QtProperty *pointProp = m_hStretchToProperty.value(property, 0)) {
+        m_propertyToHStretch[pointProp] = 0;
+        m_hStretchToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_vStretchToProperty.value(property, 0)) {
+        m_propertyToVStretch[pointProp] = 0;
+        m_vStretchToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_hPolicyToProperty.value(property, 0)) {
+        m_propertyToHPolicy[pointProp] = 0;
+        m_hPolicyToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_vPolicyToProperty.value(property, 0)) {
+        m_propertyToVPolicy[pointProp] = 0;
+        m_vPolicyToProperty.remove(property);
+    }
+}
+
+/**
+    \class QtSizePolicyPropertyManager
+
+    \brief The QtSizePolicyPropertyManager provides and manages QSizePolicy properties.
+
+    A size policy property has nested \e horizontalPolicy, \e
+    verticalPolicy, \e horizontalStretch and \e verticalStretch
+    subproperties. The top-level property's value can be retrieved
+    using the value() function, and set using the setValue() slot.
+
+    The subproperties are created by QtIntPropertyManager and QtEnumPropertyManager
+    objects. These managers can be retrieved using the subIntPropertyManager()
+    and subEnumPropertyManager() functions respectively. In order to provide
+    editing widgets for the subproperties in a property browser widget,
+    these managers must be associated with editor factories.
+
+    In addition, QtSizePolicyPropertyManager provides the valueChanged()
+    signal which is emitted whenever a property created by this
+    manager changes.
+
+    \sa QtAbstractPropertyManager, QtIntPropertyManager, QtEnumPropertyManager
+*/
+
+/**
+    \fn void QtSizePolicyPropertyManager::valueChanged(QtProperty *property, const QSizePolicy &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the
+    new \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtSizePolicyPropertyManager::QtSizePolicyPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtSizePolicyPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_intPropertyManager = new QtIntPropertyManager(this);
+    connect(d_ptr->m_intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotIntChanged(QtProperty *, int)));
+    d_ptr->m_enumPropertyManager = new QtEnumPropertyManager(this);
+    connect(d_ptr->m_enumPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotEnumChanged(QtProperty *, int)));
+
+    connect(d_ptr->m_intPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+    connect(d_ptr->m_enumPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtSizePolicyPropertyManager::~QtSizePolicyPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the manager that creates the nested \e horizontalStretch
+    and \e verticalStretch subproperties.
+
+    In order to provide editing widgets for the mentioned subproperties
+    in a property browser widget, this manager must be associated with
+    an editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtIntPropertyManager *QtSizePolicyPropertyManager::subIntPropertyManager() const
+{
+    return d_ptr->m_intPropertyManager;
+}
+
+/**
+    Returns the manager that creates the nested \e horizontalPolicy
+    and \e verticalPolicy subproperties.
+
+    In order to provide editing widgets for the mentioned subproperties
+    in a property browser widget, this manager must be associated with
+    an editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtEnumPropertyManager *QtSizePolicyPropertyManager::subEnumPropertyManager() const
+{
+    return d_ptr->m_enumPropertyManager;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given property is not managed by this manager, this
+    function returns the default size policy.
+
+    \sa setValue()
+*/
+QSizePolicy QtSizePolicyPropertyManager::value(const QtProperty *property) const
+{
+    return d_ptr->m_values.value(property, QSizePolicy());
+}
+
+/**
+    \reimp
+*/
+QString QtSizePolicyPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtSizePolicyPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+
+    const QSizePolicy sp = it.value();
+    const QtMetaEnumProvider *mep = metaEnumProvider();
+    const int hIndex = mep->sizePolicyToIndex(sp.horizontalPolicy());
+    const int vIndex = mep->sizePolicyToIndex(sp.verticalPolicy());
+    //! Unknown size policy on reading invalid uic3 files
+    const QString hPolicy = hIndex != -1 ? mep->policyEnumNames().at(hIndex) : tr("<Invalid>");
+    const QString vPolicy = vIndex != -1 ? mep->policyEnumNames().at(vIndex) : tr("<Invalid>");
+    const QString str = tr("[%1, %2, %3, %4]").arg(hPolicy, vPolicy).arg(sp.horizontalStretch()).arg(sp.verticalStretch());
+    return str;
+}
+
+/**
+    \fn void QtSizePolicyPropertyManager::setValue(QtProperty *property, const QSizePolicy &value)
+
+    Sets the value of the given \a property to \a value. Nested
+    properties are updated automatically.
+
+    \sa value(), valueChanged()
+*/
+void QtSizePolicyPropertyManager::setValue(QtProperty *property, const QSizePolicy &val)
+{
+    const QtSizePolicyPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    if (it.value() == val)
+        return;
+
+    it.value() = val;
+
+    d_ptr->m_enumPropertyManager->setValue(d_ptr->m_propertyToHPolicy[property],
+                metaEnumProvider()->sizePolicyToIndex(val.horizontalPolicy()));
+    d_ptr->m_enumPropertyManager->setValue(d_ptr->m_propertyToVPolicy[property],
+                metaEnumProvider()->sizePolicyToIndex(val.verticalPolicy()));
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToHStretch[property],
+                val.horizontalStretch());
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToVStretch[property],
+                val.verticalStretch());
+
+    emit propertyChanged(property);
+    emit valueChanged(property, val);
+}
+
+/**
+    \reimp
+*/
+void QtSizePolicyPropertyManager::initializeProperty(QtProperty *property)
+{
+    QSizePolicy val;
+    d_ptr->m_values[property] = val;
+
+    QtProperty *hPolicyProp = d_ptr->m_enumPropertyManager->addProperty();
+    hPolicyProp->setPropertyName(tr("Horizontal Policy"));
+    d_ptr->m_enumPropertyManager->setEnumNames(hPolicyProp, metaEnumProvider()->policyEnumNames());
+    d_ptr->m_enumPropertyManager->setValue(hPolicyProp,
+                metaEnumProvider()->sizePolicyToIndex(val.horizontalPolicy()));
+    d_ptr->m_propertyToHPolicy[property] = hPolicyProp;
+    d_ptr->m_hPolicyToProperty[hPolicyProp] = property;
+    property->addSubProperty(hPolicyProp);
+
+    QtProperty *vPolicyProp = d_ptr->m_enumPropertyManager->addProperty();
+    vPolicyProp->setPropertyName(tr("Vertical Policy"));
+    d_ptr->m_enumPropertyManager->setEnumNames(vPolicyProp, metaEnumProvider()->policyEnumNames());
+    d_ptr->m_enumPropertyManager->setValue(vPolicyProp,
+                metaEnumProvider()->sizePolicyToIndex(val.verticalPolicy()));
+    d_ptr->m_propertyToVPolicy[property] = vPolicyProp;
+    d_ptr->m_vPolicyToProperty[vPolicyProp] = property;
+    property->addSubProperty(vPolicyProp);
+
+    QtProperty *hStretchProp = d_ptr->m_intPropertyManager->addProperty();
+    hStretchProp->setPropertyName(tr("Horizontal Stretch"));
+    d_ptr->m_intPropertyManager->setValue(hStretchProp, val.horizontalStretch());
+    d_ptr->m_intPropertyManager->setRange(hStretchProp, 0, 0xff);
+    d_ptr->m_propertyToHStretch[property] = hStretchProp;
+    d_ptr->m_hStretchToProperty[hStretchProp] = property;
+    property->addSubProperty(hStretchProp);
+
+    QtProperty *vStretchProp = d_ptr->m_intPropertyManager->addProperty();
+    vStretchProp->setPropertyName(tr("Vertical Stretch"));
+    d_ptr->m_intPropertyManager->setValue(vStretchProp, val.verticalStretch());
+    d_ptr->m_intPropertyManager->setRange(vStretchProp, 0, 0xff);
+    d_ptr->m_propertyToVStretch[property] = vStretchProp;
+    d_ptr->m_vStretchToProperty[vStretchProp] = property;
+    property->addSubProperty(vStretchProp);
+
+}
+
+/**
+    \reimp
+*/
+void QtSizePolicyPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    QtProperty *hPolicyProp = d_ptr->m_propertyToHPolicy[property];
+    if (hPolicyProp) {
+        d_ptr->m_hPolicyToProperty.remove(hPolicyProp);
+        delete hPolicyProp;
+    }
+    d_ptr->m_propertyToHPolicy.remove(property);
+
+    QtProperty *vPolicyProp = d_ptr->m_propertyToVPolicy[property];
+    if (vPolicyProp) {
+        d_ptr->m_vPolicyToProperty.remove(vPolicyProp);
+        delete vPolicyProp;
+    }
+    d_ptr->m_propertyToVPolicy.remove(property);
+
+    QtProperty *hStretchProp = d_ptr->m_propertyToHStretch[property];
+    if (hStretchProp) {
+        d_ptr->m_hStretchToProperty.remove(hStretchProp);
+        delete hStretchProp;
+    }
+    d_ptr->m_propertyToHStretch.remove(property);
+
+    QtProperty *vStretchProp = d_ptr->m_propertyToVStretch[property];
+    if (vStretchProp) {
+        d_ptr->m_vStretchToProperty.remove(vStretchProp);
+        delete vStretchProp;
+    }
+    d_ptr->m_propertyToVStretch.remove(property);
+
+    d_ptr->m_values.remove(property);
+}
+
+// QtFontPropertyManager:
+// QtFontPropertyManagerPrivate has a mechanism for reacting
+// to QApplication::fontDatabaseChanged() [4.5], which is emitted
+// when someone loads an application font. The signals are compressed
+// using a timer with interval 0, which then causes the family
+// enumeration manager to re-set its strings and index values
+// for each property.
+
+Q_GLOBAL_STATIC(QFontDatabase, fontDatabase)
+
+class QtFontPropertyManagerPrivate
+{
+    QtFontPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtFontPropertyManager)
+public:
+
+    QtFontPropertyManagerPrivate();
+
+    void slotIntChanged(QtProperty *property, int value);
+    void slotEnumChanged(QtProperty *property, int value);
+    void slotBoolChanged(QtProperty *property, bool value);
+    void slotPropertyDestroyed(QtProperty *property);
+    void slotFontDatabaseChanged();
+    void slotFontDatabaseDelayedChange();
+
+    QStringList m_familyNames;
+
+    typedef QMap<const QtProperty *, QFont> PropertyValueMap;
+    PropertyValueMap m_values;
+
+    QtIntPropertyManager *m_intPropertyManager;
+    QtEnumPropertyManager *m_enumPropertyManager;
+    QtBoolPropertyManager *m_boolPropertyManager;
+
+    QMap<const QtProperty *, QtProperty *> m_propertyToFamily;
+    QMap<const QtProperty *, QtProperty *> m_propertyToPointSize;
+    QMap<const QtProperty *, QtProperty *> m_propertyToBold;
+    QMap<const QtProperty *, QtProperty *> m_propertyToItalic;
+    QMap<const QtProperty *, QtProperty *> m_propertyToUnderline;
+    QMap<const QtProperty *, QtProperty *> m_propertyToStrikeOut;
+    QMap<const QtProperty *, QtProperty *> m_propertyToKerning;
+
+    QMap<const QtProperty *, QtProperty *> m_familyToProperty;
+    QMap<const QtProperty *, QtProperty *> m_pointSizeToProperty;
+    QMap<const QtProperty *, QtProperty *> m_boldToProperty;
+    QMap<const QtProperty *, QtProperty *> m_italicToProperty;
+    QMap<const QtProperty *, QtProperty *> m_underlineToProperty;
+    QMap<const QtProperty *, QtProperty *> m_strikeOutToProperty;
+    QMap<const QtProperty *, QtProperty *> m_kerningToProperty;
+
+    bool m_settingValue;
+    QTimer *m_fontDatabaseChangeTimer;
+};
+
+QtFontPropertyManagerPrivate::QtFontPropertyManagerPrivate() :
+    m_settingValue(false),
+    m_fontDatabaseChangeTimer(0)
+{
+}
+
+void QtFontPropertyManagerPrivate::slotIntChanged(QtProperty *property, int value)
+{
+    if (m_settingValue)
+        return;
+    if (QtProperty *prop = m_pointSizeToProperty.value(property, 0)) {
+        QFont f = m_values[prop];
+        f.setPointSize(value);
+        q_ptr->setValue(prop, f);
+    }
+}
+
+void QtFontPropertyManagerPrivate::slotEnumChanged(QtProperty *property, int value)
+{
+    if (m_settingValue)
+        return;
+    if (QtProperty *prop = m_familyToProperty.value(property, 0)) {
+        QFont f = m_values[prop];
+        f.setFamily(m_familyNames.at(value));
+        q_ptr->setValue(prop, f);
+    }
+}
+
+void QtFontPropertyManagerPrivate::slotBoolChanged(QtProperty *property, bool value)
+{
+    if (m_settingValue)
+        return;
+    if (QtProperty *prop = m_boldToProperty.value(property, 0)) {
+        QFont f = m_values[prop];
+        f.setBold(value);
+        q_ptr->setValue(prop, f);
+    } else if (QtProperty *prop = m_italicToProperty.value(property, 0)) {
+        QFont f = m_values[prop];
+        f.setItalic(value);
+        q_ptr->setValue(prop, f);
+    } else if (QtProperty *prop = m_underlineToProperty.value(property, 0)) {
+        QFont f = m_values[prop];
+        f.setUnderline(value);
+        q_ptr->setValue(prop, f);
+    } else if (QtProperty *prop = m_strikeOutToProperty.value(property, 0)) {
+        QFont f = m_values[prop];
+        f.setStrikeOut(value);
+        q_ptr->setValue(prop, f);
+    } else if (QtProperty *prop = m_kerningToProperty.value(property, 0)) {
+        QFont f = m_values[prop];
+        f.setKerning(value);
+        q_ptr->setValue(prop, f);
+    }
+}
+
+void QtFontPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
+{
+    if (QtProperty *pointProp = m_pointSizeToProperty.value(property, 0)) {
+        m_propertyToPointSize[pointProp] = 0;
+        m_pointSizeToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_familyToProperty.value(property, 0)) {
+        m_propertyToFamily[pointProp] = 0;
+        m_familyToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_boldToProperty.value(property, 0)) {
+        m_propertyToBold[pointProp] = 0;
+        m_boldToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_italicToProperty.value(property, 0)) {
+        m_propertyToItalic[pointProp] = 0;
+        m_italicToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_underlineToProperty.value(property, 0)) {
+        m_propertyToUnderline[pointProp] = 0;
+        m_underlineToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_strikeOutToProperty.value(property, 0)) {
+        m_propertyToStrikeOut[pointProp] = 0;
+        m_strikeOutToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_kerningToProperty.value(property, 0)) {
+        m_propertyToKerning[pointProp] = 0;
+        m_kerningToProperty.remove(property);
+    }
+}
+
+void  QtFontPropertyManagerPrivate::slotFontDatabaseChanged()
+{
+    if (!m_fontDatabaseChangeTimer) {
+        m_fontDatabaseChangeTimer = new QTimer(q_ptr);
+        m_fontDatabaseChangeTimer->setInterval(0);
+        m_fontDatabaseChangeTimer->setSingleShot(true);
+        QObject::connect(m_fontDatabaseChangeTimer, SIGNAL(timeout()), q_ptr, SLOT(slotFontDatabaseDelayedChange()));
+    }
+    if (!m_fontDatabaseChangeTimer->isActive())
+        m_fontDatabaseChangeTimer->start();
+}
+
+void QtFontPropertyManagerPrivate::slotFontDatabaseDelayedChange()
+{
+    typedef QMap<const QtProperty *, QtProperty *> PropertyPropertyMap;
+    // rescan available font names
+    const QStringList oldFamilies = m_familyNames;
+    m_familyNames = fontDatabase()->families();
+
+    // Adapt all existing properties
+    if (!m_propertyToFamily.empty()) {
+        PropertyPropertyMap::const_iterator cend = m_propertyToFamily.constEnd();
+        for (PropertyPropertyMap::const_iterator it = m_propertyToFamily.constBegin(); it != cend; ++it) {
+            QtProperty *familyProp = it.value();
+            const int oldIdx = m_enumPropertyManager->value(familyProp);
+            int newIdx = m_familyNames.indexOf(oldFamilies.at(oldIdx));
+            if (newIdx < 0)
+                newIdx = 0;
+            m_enumPropertyManager->setEnumNames(familyProp, m_familyNames);
+            m_enumPropertyManager->setValue(familyProp, newIdx);
+        }
+    }
+}
+
+/**
+    \class QtFontPropertyManager
+
+    \brief The QtFontPropertyManager provides and manages QFont properties.
+
+    A font property has nested \e family, \e pointSize, \e bold, \e
+    italic, \e underline, \e strikeOut and \e kerning subproperties. The top-level
+    property's value can be retrieved using the value() function, and
+    set using the setValue() slot.
+
+    The subproperties are created by QtIntPropertyManager, QtEnumPropertyManager and
+    QtBoolPropertyManager objects. These managers can be retrieved using the
+    corresponding subIntPropertyManager(), subEnumPropertyManager() and
+    subBoolPropertyManager() functions. In order to provide editing widgets
+    for the subproperties in a property browser widget, these managers
+    must be associated with editor factories.
+
+    In addition, QtFontPropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes.
+
+    \sa QtAbstractPropertyManager, QtEnumPropertyManager, QtIntPropertyManager, QtBoolPropertyManager
+*/
+
+/**
+    \fn void QtFontPropertyManager::valueChanged(QtProperty *property, const QFont &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the
+    new \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtFontPropertyManager::QtFontPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtFontPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+#if QT_VERSION >= 0x040500
+    QObject::connect(qApp, SIGNAL(fontDatabaseChanged()), this, SLOT(slotFontDatabaseChanged()));
+#endif
+
+    d_ptr->m_intPropertyManager = new QtIntPropertyManager(this);
+    connect(d_ptr->m_intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotIntChanged(QtProperty *, int)));
+    d_ptr->m_enumPropertyManager = new QtEnumPropertyManager(this);
+    connect(d_ptr->m_enumPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotEnumChanged(QtProperty *, int)));
+    d_ptr->m_boolPropertyManager = new QtBoolPropertyManager(this);
+    connect(d_ptr->m_boolPropertyManager, SIGNAL(valueChanged(QtProperty *, bool)),
+                this, SLOT(slotBoolChanged(QtProperty *, bool)));
+
+    connect(d_ptr->m_intPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+    connect(d_ptr->m_enumPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+    connect(d_ptr->m_boolPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtFontPropertyManager::~QtFontPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the manager that creates the \e pointSize subproperty.
+
+    In order to provide editing widgets for the \e pointSize property
+    in a property browser widget, this manager must be associated
+    with an editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtIntPropertyManager *QtFontPropertyManager::subIntPropertyManager() const
+{
+    return d_ptr->m_intPropertyManager;
+}
+
+/**
+    Returns the manager that create the \e family subproperty.
+
+    In order to provide editing widgets for the \e family property
+    in a property browser widget, this manager must be associated
+    with an editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtEnumPropertyManager *QtFontPropertyManager::subEnumPropertyManager() const
+{
+    return d_ptr->m_enumPropertyManager;
+}
+
+/**
+    Returns the manager that creates the  \e bold, \e italic, \e underline,
+    \e strikeOut and \e kerning subproperties.
+
+    In order to provide editing widgets for the mentioned properties
+    in a property browser widget, this manager must be associated with
+    an editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtBoolPropertyManager *QtFontPropertyManager::subBoolPropertyManager() const
+{
+    return d_ptr->m_boolPropertyManager;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given property is not managed by this manager, this
+    function returns a font object that uses the application's default
+    font.
+
+    \sa setValue()
+*/
+QFont QtFontPropertyManager::value(const QtProperty *property) const
+{
+    return d_ptr->m_values.value(property, QFont());
+}
+
+/**
+    \reimp
+*/
+QString QtFontPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtFontPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+
+    return QtPropertyBrowserUtils::fontValueText(it.value());
+}
+
+/**
+    \reimp
+*/
+QIcon QtFontPropertyManager::valueIcon(const QtProperty *property) const
+{
+    const QtFontPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QIcon();
+
+    return QtPropertyBrowserUtils::fontValueIcon(it.value());
+}
+
+/**
+    \fn void QtFontPropertyManager::setValue(QtProperty *property, const QFont &value)
+
+    Sets the value of the given \a property to \a value. Nested
+    properties are updated automatically.
+
+    \sa value(), valueChanged()
+*/
+void QtFontPropertyManager::setValue(QtProperty *property, const QFont &val)
+{
+    const QtFontPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    const QFont oldVal = it.value();
+    if (oldVal == val && oldVal.resolve() == val.resolve())
+        return;
+
+    it.value() = val;
+
+    int idx = d_ptr->m_familyNames.indexOf(val.family());
+    if (idx == -1)
+        idx = 0;
+    bool settingValue = d_ptr->m_settingValue;
+    d_ptr->m_settingValue = true;
+    d_ptr->m_enumPropertyManager->setValue(d_ptr->m_propertyToFamily[property], idx);
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToPointSize[property], val.pointSize());
+    d_ptr->m_boolPropertyManager->setValue(d_ptr->m_propertyToBold[property], val.bold());
+    d_ptr->m_boolPropertyManager->setValue(d_ptr->m_propertyToItalic[property], val.italic());
+    d_ptr->m_boolPropertyManager->setValue(d_ptr->m_propertyToUnderline[property], val.underline());
+    d_ptr->m_boolPropertyManager->setValue(d_ptr->m_propertyToStrikeOut[property], val.strikeOut());
+    d_ptr->m_boolPropertyManager->setValue(d_ptr->m_propertyToKerning[property], val.kerning());
+    d_ptr->m_settingValue = settingValue;
+
+    emit propertyChanged(property);
+    emit valueChanged(property, val);
+}
+
+/**
+    \reimp
+*/
+void QtFontPropertyManager::initializeProperty(QtProperty *property)
+{
+    QFont val;
+    d_ptr->m_values[property] = val;
+
+    QtProperty *familyProp = d_ptr->m_enumPropertyManager->addProperty();
+    familyProp->setPropertyName(tr("Family"));
+    if (d_ptr->m_familyNames.empty())
+        d_ptr->m_familyNames = fontDatabase()->families();
+    d_ptr->m_enumPropertyManager->setEnumNames(familyProp, d_ptr->m_familyNames);
+    int idx = d_ptr->m_familyNames.indexOf(val.family());
+    if (idx == -1)
+        idx = 0;
+    d_ptr->m_enumPropertyManager->setValue(familyProp, idx);
+    d_ptr->m_propertyToFamily[property] = familyProp;
+    d_ptr->m_familyToProperty[familyProp] = property;
+    property->addSubProperty(familyProp);
+
+    QtProperty *pointSizeProp = d_ptr->m_intPropertyManager->addProperty();
+    pointSizeProp->setPropertyName(tr("Point Size"));
+    d_ptr->m_intPropertyManager->setValue(pointSizeProp, val.pointSize());
+    d_ptr->m_intPropertyManager->setMinimum(pointSizeProp, 1);
+    d_ptr->m_propertyToPointSize[property] = pointSizeProp;
+    d_ptr->m_pointSizeToProperty[pointSizeProp] = property;
+    property->addSubProperty(pointSizeProp);
+
+    QtProperty *boldProp = d_ptr->m_boolPropertyManager->addProperty();
+    boldProp->setPropertyName(tr("Bold"));
+    d_ptr->m_boolPropertyManager->setValue(boldProp, val.bold());
+    d_ptr->m_propertyToBold[property] = boldProp;
+    d_ptr->m_boldToProperty[boldProp] = property;
+    property->addSubProperty(boldProp);
+
+    QtProperty *italicProp = d_ptr->m_boolPropertyManager->addProperty();
+    italicProp->setPropertyName(tr("Italic"));
+    d_ptr->m_boolPropertyManager->setValue(italicProp, val.italic());
+    d_ptr->m_propertyToItalic[property] = italicProp;
+    d_ptr->m_italicToProperty[italicProp] = property;
+    property->addSubProperty(italicProp);
+
+    QtProperty *underlineProp = d_ptr->m_boolPropertyManager->addProperty();
+    underlineProp->setPropertyName(tr("Underline"));
+    d_ptr->m_boolPropertyManager->setValue(underlineProp, val.underline());
+    d_ptr->m_propertyToUnderline[property] = underlineProp;
+    d_ptr->m_underlineToProperty[underlineProp] = property;
+    property->addSubProperty(underlineProp);
+
+    QtProperty *strikeOutProp = d_ptr->m_boolPropertyManager->addProperty();
+    strikeOutProp->setPropertyName(tr("Strikeout"));
+    d_ptr->m_boolPropertyManager->setValue(strikeOutProp, val.strikeOut());
+    d_ptr->m_propertyToStrikeOut[property] = strikeOutProp;
+    d_ptr->m_strikeOutToProperty[strikeOutProp] = property;
+    property->addSubProperty(strikeOutProp);
+
+    QtProperty *kerningProp = d_ptr->m_boolPropertyManager->addProperty();
+    kerningProp->setPropertyName(tr("Kerning"));
+    d_ptr->m_boolPropertyManager->setValue(kerningProp, val.kerning());
+    d_ptr->m_propertyToKerning[property] = kerningProp;
+    d_ptr->m_kerningToProperty[kerningProp] = property;
+    property->addSubProperty(kerningProp);
+}
+
+/**
+    \reimp
+*/
+void QtFontPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    QtProperty *familyProp = d_ptr->m_propertyToFamily[property];
+    if (familyProp) {
+        d_ptr->m_familyToProperty.remove(familyProp);
+        delete familyProp;
+    }
+    d_ptr->m_propertyToFamily.remove(property);
+
+    QtProperty *pointSizeProp = d_ptr->m_propertyToPointSize[property];
+    if (pointSizeProp) {
+        d_ptr->m_pointSizeToProperty.remove(pointSizeProp);
+        delete pointSizeProp;
+    }
+    d_ptr->m_propertyToPointSize.remove(property);
+
+    QtProperty *boldProp = d_ptr->m_propertyToBold[property];
+    if (boldProp) {
+        d_ptr->m_boldToProperty.remove(boldProp);
+        delete boldProp;
+    }
+    d_ptr->m_propertyToBold.remove(property);
+
+    QtProperty *italicProp = d_ptr->m_propertyToItalic[property];
+    if (italicProp) {
+        d_ptr->m_italicToProperty.remove(italicProp);
+        delete italicProp;
+    }
+    d_ptr->m_propertyToItalic.remove(property);
+
+    QtProperty *underlineProp = d_ptr->m_propertyToUnderline[property];
+    if (underlineProp) {
+        d_ptr->m_underlineToProperty.remove(underlineProp);
+        delete underlineProp;
+    }
+    d_ptr->m_propertyToUnderline.remove(property);
+
+    QtProperty *strikeOutProp = d_ptr->m_propertyToStrikeOut[property];
+    if (strikeOutProp) {
+        d_ptr->m_strikeOutToProperty.remove(strikeOutProp);
+        delete strikeOutProp;
+    }
+    d_ptr->m_propertyToStrikeOut.remove(property);
+
+    QtProperty *kerningProp = d_ptr->m_propertyToKerning[property];
+    if (kerningProp) {
+        d_ptr->m_kerningToProperty.remove(kerningProp);
+        delete kerningProp;
+    }
+    d_ptr->m_propertyToKerning.remove(property);
+
+    d_ptr->m_values.remove(property);
+}
+
+// QtColorPropertyManager
+
+class QtColorPropertyManagerPrivate
+{
+    QtColorPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtColorPropertyManager)
+public:
+
+    void slotIntChanged(QtProperty *property, int value);
+    void slotPropertyDestroyed(QtProperty *property);
+
+    typedef QMap<const QtProperty *, QColor> PropertyValueMap;
+    PropertyValueMap m_values;
+
+    QtIntPropertyManager *m_intPropertyManager;
+
+    QMap<const QtProperty *, QtProperty *> m_propertyToR;
+    QMap<const QtProperty *, QtProperty *> m_propertyToG;
+    QMap<const QtProperty *, QtProperty *> m_propertyToB;
+    QMap<const QtProperty *, QtProperty *> m_propertyToA;
+
+    QMap<const QtProperty *, QtProperty *> m_rToProperty;
+    QMap<const QtProperty *, QtProperty *> m_gToProperty;
+    QMap<const QtProperty *, QtProperty *> m_bToProperty;
+    QMap<const QtProperty *, QtProperty *> m_aToProperty;
+};
+
+void QtColorPropertyManagerPrivate::slotIntChanged(QtProperty *property, int value)
+{
+    if (QtProperty *prop = m_rToProperty.value(property, 0)) {
+        QColor c = m_values[prop];
+        c.setRed(value);
+        q_ptr->setValue(prop, c);
+    } else if (QtProperty *prop = m_gToProperty.value(property, 0)) {
+        QColor c = m_values[prop];
+        c.setGreen(value);
+        q_ptr->setValue(prop, c);
+    } else if (QtProperty *prop = m_bToProperty.value(property, 0)) {
+        QColor c = m_values[prop];
+        c.setBlue(value);
+        q_ptr->setValue(prop, c);
+    } else if (QtProperty *prop = m_aToProperty.value(property, 0)) {
+        QColor c = m_values[prop];
+        c.setAlpha(value);
+        q_ptr->setValue(prop, c);
+    }
+}
+
+void QtColorPropertyManagerPrivate::slotPropertyDestroyed(QtProperty *property)
+{
+    if (QtProperty *pointProp = m_rToProperty.value(property, 0)) {
+        m_propertyToR[pointProp] = 0;
+        m_rToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_gToProperty.value(property, 0)) {
+        m_propertyToG[pointProp] = 0;
+        m_gToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_bToProperty.value(property, 0)) {
+        m_propertyToB[pointProp] = 0;
+        m_bToProperty.remove(property);
+    } else if (QtProperty *pointProp = m_aToProperty.value(property, 0)) {
+        m_propertyToA[pointProp] = 0;
+        m_aToProperty.remove(property);
+    }
+}
+
+/**
+    \class QtColorPropertyManager
+
+    \brief The QtColorPropertyManager provides and manages QColor properties.
+
+    A color property has nested \e red, \e green and \e blue
+    subproperties. The top-level property's value can be retrieved
+    using the value() function, and set using the setValue() slot.
+
+    The subproperties are created by a QtIntPropertyManager object. This
+    manager can be retrieved using the subIntPropertyManager() function.  In
+    order to provide editing widgets for the subproperties in a
+    property browser widget, this manager must be associated with an
+    editor factory.
+
+    In addition, QtColorPropertyManager provides the valueChanged() signal
+    which is emitted whenever a property created by this manager
+    changes.
+
+    \sa QtAbstractPropertyManager, QtAbstractPropertyBrowser, QtIntPropertyManager
+*/
+
+/**
+    \fn void QtColorPropertyManager::valueChanged(QtProperty *property, const QColor &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtColorPropertyManager::QtColorPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtColorPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_intPropertyManager = new QtIntPropertyManager(this);
+    connect(d_ptr->m_intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotIntChanged(QtProperty *, int)));
+
+    connect(d_ptr->m_intPropertyManager, SIGNAL(propertyDestroyed(QtProperty *)),
+                this, SLOT(slotPropertyDestroyed(QtProperty *)));
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtColorPropertyManager::~QtColorPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the manager that produces the nested \e red, \e green and
+    \e blue subproperties.
+
+    In order to provide editing widgets for the subproperties in a
+    property browser widget, this manager must be associated with an
+    editor factory.
+
+    \sa QtAbstractPropertyBrowser::setFactoryForManager()
+*/
+QtIntPropertyManager *QtColorPropertyManager::subIntPropertyManager() const
+{
+    return d_ptr->m_intPropertyManager;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by \e this manager, this
+    function returns an invalid color.
+
+    \sa setValue()
+*/
+QColor QtColorPropertyManager::value(const QtProperty *property) const
+{
+    return d_ptr->m_values.value(property, QColor());
+}
+
+/**
+    \reimp
+*/
+
+QString QtColorPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtColorPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+
+    return QtPropertyBrowserUtils::colorValueText(it.value());
+}
+
+/**
+    \reimp
+*/
+
+QIcon QtColorPropertyManager::valueIcon(const QtProperty *property) const
+{
+    const QtColorPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QIcon();
+    return QtPropertyBrowserUtils::brushValueIcon(QBrush(it.value()));
+}
+
+/**
+    \fn void QtColorPropertyManager::setValue(QtProperty *property, const QColor &value)
+
+    Sets the value of the given \a property to \a value.  Nested
+    properties are updated automatically.
+
+    \sa value(), valueChanged()
+*/
+void QtColorPropertyManager::setValue(QtProperty *property, const QColor &val)
+{
+    const QtColorPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    if (it.value() == val)
+        return;
+
+    it.value() = val;
+
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToR[property], val.red());
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToG[property], val.green());
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToB[property], val.blue());
+    d_ptr->m_intPropertyManager->setValue(d_ptr->m_propertyToA[property], val.alpha());
+
+    emit propertyChanged(property);
+    emit valueChanged(property, val);
+}
+
+/**
+    \reimp
+*/
+void QtColorPropertyManager::initializeProperty(QtProperty *property)
+{
+    QColor val;
+    d_ptr->m_values[property] = val;
+
+    QtProperty *rProp = d_ptr->m_intPropertyManager->addProperty();
+    rProp->setPropertyName(tr("Red"));
+    d_ptr->m_intPropertyManager->setValue(rProp, val.red());
+    d_ptr->m_intPropertyManager->setRange(rProp, 0, 0xFF);
+    d_ptr->m_propertyToR[property] = rProp;
+    d_ptr->m_rToProperty[rProp] = property;
+    property->addSubProperty(rProp);
+
+    QtProperty *gProp = d_ptr->m_intPropertyManager->addProperty();
+    gProp->setPropertyName(tr("Green"));
+    d_ptr->m_intPropertyManager->setValue(gProp, val.green());
+    d_ptr->m_intPropertyManager->setRange(gProp, 0, 0xFF);
+    d_ptr->m_propertyToG[property] = gProp;
+    d_ptr->m_gToProperty[gProp] = property;
+    property->addSubProperty(gProp);
+
+    QtProperty *bProp = d_ptr->m_intPropertyManager->addProperty();
+    bProp->setPropertyName(tr("Blue"));
+    d_ptr->m_intPropertyManager->setValue(bProp, val.blue());
+    d_ptr->m_intPropertyManager->setRange(bProp, 0, 0xFF);
+    d_ptr->m_propertyToB[property] = bProp;
+    d_ptr->m_bToProperty[bProp] = property;
+    property->addSubProperty(bProp);
+
+    QtProperty *aProp = d_ptr->m_intPropertyManager->addProperty();
+    aProp->setPropertyName(tr("Alpha"));
+    d_ptr->m_intPropertyManager->setValue(aProp, val.alpha());
+    d_ptr->m_intPropertyManager->setRange(aProp, 0, 0xFF);
+    d_ptr->m_propertyToA[property] = aProp;
+    d_ptr->m_aToProperty[aProp] = property;
+    property->addSubProperty(aProp);
+}
+
+/**
+    \reimp
+*/
+void QtColorPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    QtProperty *rProp = d_ptr->m_propertyToR[property];
+    if (rProp) {
+        d_ptr->m_rToProperty.remove(rProp);
+        delete rProp;
+    }
+    d_ptr->m_propertyToR.remove(property);
+
+    QtProperty *gProp = d_ptr->m_propertyToG[property];
+    if (gProp) {
+        d_ptr->m_gToProperty.remove(gProp);
+        delete gProp;
+    }
+    d_ptr->m_propertyToG.remove(property);
+
+    QtProperty *bProp = d_ptr->m_propertyToB[property];
+    if (bProp) {
+        d_ptr->m_bToProperty.remove(bProp);
+        delete bProp;
+    }
+    d_ptr->m_propertyToB.remove(property);
+
+    QtProperty *aProp = d_ptr->m_propertyToA[property];
+    if (aProp) {
+        d_ptr->m_aToProperty.remove(aProp);
+        delete aProp;
+    }
+    d_ptr->m_propertyToA.remove(property);
+
+    d_ptr->m_values.remove(property);
+}
+
+// QtCursorPropertyManager
+
+Q_GLOBAL_STATIC(QtCursorDatabase, cursorDatabase)
+
+class QtCursorPropertyManagerPrivate
+{
+    QtCursorPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtCursorPropertyManager)
+public:
+    typedef QMap<const QtProperty *, QCursor> PropertyValueMap;
+    PropertyValueMap m_values;
+};
+
+/**
+    \class QtCursorPropertyManager
+
+    \brief The QtCursorPropertyManager provides and manages QCursor properties.
+
+    A cursor property has a current value which can be
+    retrieved using the value() function, and set using the setValue()
+    slot. In addition, QtCursorPropertyManager provides the
+    valueChanged() signal which is emitted whenever a property created
+    by this manager changes.
+
+    \sa QtAbstractPropertyManager
+*/
+
+/**
+    \fn void QtCursorPropertyManager::valueChanged(QtProperty *property, const QCursor &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the new
+    \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtCursorPropertyManager::QtCursorPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtCursorPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtCursorPropertyManager::~QtCursorPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by this manager, this
+    function returns a default QCursor object.
+
+    \sa setValue()
+*/
+#ifndef QT_NO_CURSOR
+QCursor QtCursorPropertyManager::value(const QtProperty *property) const
+{
+    return d_ptr->m_values.value(property, QCursor());
+}
+#endif
+
+/**
+    \reimp
+*/
+QString QtCursorPropertyManager::valueText(const QtProperty *property) const
+{
+   const QtCursorPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QString();
+
+    return cursorDatabase()->cursorToShapeName(it.value());
+}
+
+/**
+    \reimp
+*/
+QIcon QtCursorPropertyManager::valueIcon(const QtProperty *property) const
+{
+    const QtCursorPropertyManagerPrivate::PropertyValueMap::const_iterator it = d_ptr->m_values.constFind(property);
+    if (it == d_ptr->m_values.constEnd())
+        return QIcon();
+
+    return cursorDatabase()->cursorToShapeIcon(it.value());
+}
+
+/**
+    \fn void QtCursorPropertyManager::setValue(QtProperty *property, const QCursor &value)
+
+    Sets the value of the given \a property to \a value.
+
+    \sa value(), valueChanged()
+*/
+void QtCursorPropertyManager::setValue(QtProperty *property, const QCursor &value)
+{
+#ifndef QT_NO_CURSOR
+    const QtCursorPropertyManagerPrivate::PropertyValueMap::iterator it = d_ptr->m_values.find(property);
+    if (it == d_ptr->m_values.end())
+        return;
+
+    if (it.value().shape() == value.shape() && value.shape() != Qt::BitmapCursor)
+        return;
+
+    it.value() = value;
+
+    emit propertyChanged(property);
+    emit valueChanged(property, value);
+#endif
+}
+
+/**
+    \reimp
+*/
+void QtCursorPropertyManager::initializeProperty(QtProperty *property)
+{
+#ifndef QT_NO_CURSOR
+    d_ptr->m_values[property] = QCursor();
+#endif
+}
+
+/**
+    \reimp
+*/
+void QtCursorPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    d_ptr->m_values.remove(property);
+}
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#include "moc_qtpropertymanager.cpp"
+#include "qtpropertymanager.moc"
diff --git a/Code/Mantid/QtPropertyBrowser/src/qtpropertymanager.h b/Code/Mantid/QtPropertyBrowser/src/qtpropertymanager.h
index 8972ed513aad80fcf12bd20e6aac85297dea7a90..709f2abf77389fb3c8a711664db5d1a4eab13a04 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qtpropertymanager.h
+++ b/Code/Mantid/QtPropertyBrowser/src/qtpropertymanager.h
@@ -1,796 +1,796 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QTPROPERTYMANAGER_H
-#define QTPROPERTYMANAGER_H
-
-#include "qtpropertybrowser.h"
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-class QDate;
-class QTime;
-class QDateTime;
-class QLocale;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtGroupPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtGroupPropertyManager(QObject *parent = 0);
-    ~QtGroupPropertyManager();
-
-protected:
-    virtual bool hasValue(const QtProperty *property) const;
-
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-};
-
-class QtIntPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtIntPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtIntPropertyManager(QObject *parent = 0);
-    ~QtIntPropertyManager();
-
-    int value(const QtProperty *property) const;
-    int minimum(const QtProperty *property) const;
-    int maximum(const QtProperty *property) const;
-    int singleStep(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, int val);
-    void setMinimum(QtProperty *property, int minVal);
-    void setMaximum(QtProperty *property, int maxVal);
-    void setRange(QtProperty *property, int minVal, int maxVal);
-    void setSingleStep(QtProperty *property, int step);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, int val);
-    void rangeChanged(QtProperty *property, int minVal, int maxVal);
-    void singleStepChanged(QtProperty *property, int step);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtIntPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtIntPropertyManager)
-    Q_DISABLE_COPY(QtIntPropertyManager)
-};
-
-class QtBoolPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtBoolPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtBoolPropertyManager(QObject *parent = 0);
-    ~QtBoolPropertyManager();
-
-    bool value(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, bool val);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, bool val);
-protected:
-    QString valueText(const QtProperty *property) const;
-    QIcon valueIcon(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtBoolPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtBoolPropertyManager)
-    Q_DISABLE_COPY(QtBoolPropertyManager)
-};
-
-class QtDoublePropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtDoublePropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtDoublePropertyManager(QObject *parent = 0);
-    ~QtDoublePropertyManager();
-
-    double value(const QtProperty *property) const;
-    double minimum(const QtProperty *property) const;
-    double maximum(const QtProperty *property) const;
-    double singleStep(const QtProperty *property) const;
-    int decimals(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, double val);
-    void setMinimum(QtProperty *property, double minVal);
-    void setMaximum(QtProperty *property, double maxVal);
-    void setRange(QtProperty *property, double minVal, double maxVal);
-    void setSingleStep(QtProperty *property, double step);
-    void setDecimals(QtProperty *property, int prec);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, double val);
-    void rangeChanged(QtProperty *property, double minVal, double maxVal);
-    void singleStepChanged(QtProperty *property, double step);
-    void decimalsChanged(QtProperty *property, int prec);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtDoublePropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtDoublePropertyManager)
-    Q_DISABLE_COPY(QtDoublePropertyManager)
-};
-
-class QtStringPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtStringPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtStringPropertyManager(QObject *parent = 0);
-    ~QtStringPropertyManager();
-
-    QString value(const QtProperty *property) const;
-    QRegExp regExp(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QString &val);
-    void setRegExp(QtProperty *property, const QRegExp &regExp);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QString &val);
-    void regExpChanged(QtProperty *property, const QRegExp &regExp);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtStringPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtStringPropertyManager)
-    Q_DISABLE_COPY(QtStringPropertyManager)
-};
-
-class QtDatePropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtDatePropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtDatePropertyManager(QObject *parent = 0);
-    ~QtDatePropertyManager();
-
-    QDate value(const QtProperty *property) const;
-    QDate minimum(const QtProperty *property) const;
-    QDate maximum(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QDate &val);
-    void setMinimum(QtProperty *property, const QDate &minVal);
-    void setMaximum(QtProperty *property, const QDate &maxVal);
-    void setRange(QtProperty *property, const QDate &minVal, const QDate &maxVal);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QDate &val);
-    void rangeChanged(QtProperty *property, const QDate &minVal, const QDate &maxVal);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtDatePropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtDatePropertyManager)
-    Q_DISABLE_COPY(QtDatePropertyManager)
-};
-
-class QtTimePropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtTimePropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtTimePropertyManager(QObject *parent = 0);
-    ~QtTimePropertyManager();
-
-    QTime value(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QTime &val);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QTime &val);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtTimePropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtTimePropertyManager)
-    Q_DISABLE_COPY(QtTimePropertyManager)
-};
-
-class QtDateTimePropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtDateTimePropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtDateTimePropertyManager(QObject *parent = 0);
-    ~QtDateTimePropertyManager();
-
-    QDateTime value(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QDateTime &val);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QDateTime &val);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtDateTimePropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtDateTimePropertyManager)
-    Q_DISABLE_COPY(QtDateTimePropertyManager)
-};
-
-class QtKeySequencePropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtKeySequencePropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtKeySequencePropertyManager(QObject *parent = 0);
-    ~QtKeySequencePropertyManager();
-
-    QKeySequence value(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QKeySequence &val);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QKeySequence &val);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtKeySequencePropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtKeySequencePropertyManager)
-    Q_DISABLE_COPY(QtKeySequencePropertyManager)
-};
-
-class QtCharPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtCharPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtCharPropertyManager(QObject *parent = 0);
-    ~QtCharPropertyManager();
-
-    QChar value(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QChar &val);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QChar &val);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtCharPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtCharPropertyManager)
-    Q_DISABLE_COPY(QtCharPropertyManager)
-};
-
-class QtEnumPropertyManager;
-class QtLocalePropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtLocalePropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtLocalePropertyManager(QObject *parent = 0);
-    ~QtLocalePropertyManager();
-
-    QtEnumPropertyManager *subEnumPropertyManager() const;
-
-    QLocale value(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QLocale &val);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QLocale &val);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtLocalePropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtLocalePropertyManager)
-    Q_DISABLE_COPY(QtLocalePropertyManager)
-    Q_PRIVATE_SLOT(d_func(), void slotEnumChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
-};
-
-class QtPointPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtPointPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtPointPropertyManager(QObject *parent = 0);
-    ~QtPointPropertyManager();
-
-    QtIntPropertyManager *subIntPropertyManager() const;
-
-    QPoint value(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QPoint &val);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QPoint &val);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtPointPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtPointPropertyManager)
-    Q_DISABLE_COPY(QtPointPropertyManager)
-    Q_PRIVATE_SLOT(d_func(), void slotIntChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
-};
-
-class QtPointFPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtPointFPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtPointFPropertyManager(QObject *parent = 0);
-    ~QtPointFPropertyManager();
-
-    QtDoublePropertyManager *subDoublePropertyManager() const;
-
-    QPointF value(const QtProperty *property) const;
-    int decimals(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QPointF &val);
-    void setDecimals(QtProperty *property, int prec);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QPointF &val);
-    void decimalsChanged(QtProperty *property, int prec);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtPointFPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtPointFPropertyManager)
-    Q_DISABLE_COPY(QtPointFPropertyManager)
-    Q_PRIVATE_SLOT(d_func(), void slotDoubleChanged(QtProperty *, double))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
-};
-
-class QtSizePropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtSizePropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtSizePropertyManager(QObject *parent = 0);
-    ~QtSizePropertyManager();
-
-    QtIntPropertyManager *subIntPropertyManager() const;
-
-    QSize value(const QtProperty *property) const;
-    QSize minimum(const QtProperty *property) const;
-    QSize maximum(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QSize &val);
-    void setMinimum(QtProperty *property, const QSize &minVal);
-    void setMaximum(QtProperty *property, const QSize &maxVal);
-    void setRange(QtProperty *property, const QSize &minVal, const QSize &maxVal);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QSize &val);
-    void rangeChanged(QtProperty *property, const QSize &minVal, const QSize &maxVal);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtSizePropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtSizePropertyManager)
-    Q_DISABLE_COPY(QtSizePropertyManager)
-    Q_PRIVATE_SLOT(d_func(), void slotIntChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
-};
-
-class QtSizeFPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtSizeFPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtSizeFPropertyManager(QObject *parent = 0);
-    ~QtSizeFPropertyManager();
-
-    QtDoublePropertyManager *subDoublePropertyManager() const;
-
-    QSizeF value(const QtProperty *property) const;
-    QSizeF minimum(const QtProperty *property) const;
-    QSizeF maximum(const QtProperty *property) const;
-    int decimals(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QSizeF &val);
-    void setMinimum(QtProperty *property, const QSizeF &minVal);
-    void setMaximum(QtProperty *property, const QSizeF &maxVal);
-    void setRange(QtProperty *property, const QSizeF &minVal, const QSizeF &maxVal);
-    void setDecimals(QtProperty *property, int prec);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QSizeF &val);
-    void rangeChanged(QtProperty *property, const QSizeF &minVal, const QSizeF &maxVal);
-    void decimalsChanged(QtProperty *property, int prec);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtSizeFPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtSizeFPropertyManager)
-    Q_DISABLE_COPY(QtSizeFPropertyManager)
-    Q_PRIVATE_SLOT(d_func(), void slotDoubleChanged(QtProperty *, double))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
-};
-
-class QtRectPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtRectPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtRectPropertyManager(QObject *parent = 0);
-    ~QtRectPropertyManager();
-
-    QtIntPropertyManager *subIntPropertyManager() const;
-
-    QRect value(const QtProperty *property) const;
-    QRect constraint(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QRect &val);
-    void setConstraint(QtProperty *property, const QRect &constraint);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QRect &val);
-    void constraintChanged(QtProperty *property, const QRect &constraint);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtRectPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtRectPropertyManager)
-    Q_DISABLE_COPY(QtRectPropertyManager)
-    Q_PRIVATE_SLOT(d_func(), void slotIntChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
-};
-
-class QtRectFPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtRectFPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtRectFPropertyManager(QObject *parent = 0);
-    ~QtRectFPropertyManager();
-
-    QtDoublePropertyManager *subDoublePropertyManager() const;
-
-    QRectF value(const QtProperty *property) const;
-    QRectF constraint(const QtProperty *property) const;
-    int decimals(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QRectF &val);
-    void setConstraint(QtProperty *property, const QRectF &constraint);
-    void setDecimals(QtProperty *property, int prec);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QRectF &val);
-    void constraintChanged(QtProperty *property, const QRectF &constraint);
-    void decimalsChanged(QtProperty *property, int prec);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtRectFPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtRectFPropertyManager)
-    Q_DISABLE_COPY(QtRectFPropertyManager)
-    Q_PRIVATE_SLOT(d_func(), void slotDoubleChanged(QtProperty *, double))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
-};
-
-class QtEnumPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtEnumPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtEnumPropertyManager(QObject *parent = 0);
-    ~QtEnumPropertyManager();
-
-    int value(const QtProperty *property) const;
-    QStringList enumNames(const QtProperty *property) const;
-    QMap<int, QIcon> enumIcons(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, int val);
-    void setEnumNames(QtProperty *property, const QStringList &names);
-    void setEnumIcons(QtProperty *property, const QMap<int, QIcon> &icons);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, int val);
-    void enumNamesChanged(QtProperty *property, const QStringList &names);
-    void enumIconsChanged(QtProperty *property, const QMap<int, QIcon> &icons);
-protected:
-    QString valueText(const QtProperty *property) const;
-    QIcon valueIcon(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtEnumPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtEnumPropertyManager)
-    Q_DISABLE_COPY(QtEnumPropertyManager)
-};
-
-class QtFlagPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtFlagPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtFlagPropertyManager(QObject *parent = 0);
-    ~QtFlagPropertyManager();
-
-    QtBoolPropertyManager *subBoolPropertyManager() const;
-
-    int value(const QtProperty *property) const;
-    QStringList flagNames(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, int val);
-    void setFlagNames(QtProperty *property, const QStringList &names);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, int val);
-    void flagNamesChanged(QtProperty *property, const QStringList &names);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtFlagPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtFlagPropertyManager)
-    Q_DISABLE_COPY(QtFlagPropertyManager)
-    Q_PRIVATE_SLOT(d_func(), void slotBoolChanged(QtProperty *, bool))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
-};
-
-class QtSizePolicyPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtSizePolicyPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtSizePolicyPropertyManager(QObject *parent = 0);
-    ~QtSizePolicyPropertyManager();
-
-    QtIntPropertyManager *subIntPropertyManager() const;
-    QtEnumPropertyManager *subEnumPropertyManager() const;
-
-    QSizePolicy value(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QSizePolicy &val);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QSizePolicy &val);
-protected:
-    QString valueText(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtSizePolicyPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtSizePolicyPropertyManager)
-    Q_DISABLE_COPY(QtSizePolicyPropertyManager)
-    Q_PRIVATE_SLOT(d_func(), void slotIntChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotEnumChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
-};
-
-class QtFontPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtFontPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtFontPropertyManager(QObject *parent = 0);
-    ~QtFontPropertyManager();
-
-    QtIntPropertyManager *subIntPropertyManager() const;
-    QtEnumPropertyManager *subEnumPropertyManager() const;
-    QtBoolPropertyManager *subBoolPropertyManager() const;
-
-    QFont value(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QFont &val);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QFont &val);
-protected:
-    QString valueText(const QtProperty *property) const;
-    QIcon valueIcon(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtFontPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtFontPropertyManager)
-    Q_DISABLE_COPY(QtFontPropertyManager)
-    Q_PRIVATE_SLOT(d_func(), void slotIntChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotEnumChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotBoolChanged(QtProperty *, bool))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
-    Q_PRIVATE_SLOT(d_func(), void slotFontDatabaseChanged())
-    Q_PRIVATE_SLOT(d_func(), void slotFontDatabaseDelayedChange())
-};
-
-class QtColorPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtColorPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtColorPropertyManager(QObject *parent = 0);
-    ~QtColorPropertyManager();
-
-    QtIntPropertyManager *subIntPropertyManager() const;
-
-    QColor value(const QtProperty *property) const;
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QColor &val);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QColor &val);
-protected:
-    QString valueText(const QtProperty *property) const;
-    QIcon valueIcon(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtColorPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtColorPropertyManager)
-    Q_DISABLE_COPY(QtColorPropertyManager)
-    Q_PRIVATE_SLOT(d_func(), void slotIntChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
-};
-
-class QtCursorPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtCursorPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtCursorPropertyManager(QObject *parent = 0);
-    ~QtCursorPropertyManager();
-
-#ifndef QT_NO_CURSOR
-    QCursor value(const QtProperty *property) const;
-#endif
-
-public Q_SLOTS:
-    void setValue(QtProperty *property, const QCursor &val);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QCursor &val);
-protected:
-    QString valueText(const QtProperty *property) const;
-    QIcon valueIcon(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-private:
-    QtCursorPropertyManagerPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtCursorPropertyManager)
-    Q_DISABLE_COPY(QtCursorPropertyManager)
-};
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#endif
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QTPROPERTYMANAGER_H
+#define QTPROPERTYMANAGER_H
+
+#include "qtpropertybrowser.h"
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+class QDate;
+class QTime;
+class QDateTime;
+class QLocale;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtGroupPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtGroupPropertyManager(QObject *parent = 0);
+    ~QtGroupPropertyManager();
+
+protected:
+    virtual bool hasValue(const QtProperty *property) const;
+
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+};
+
+class QtIntPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtIntPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtIntPropertyManager(QObject *parent = 0);
+    ~QtIntPropertyManager();
+
+    int value(const QtProperty *property) const;
+    int minimum(const QtProperty *property) const;
+    int maximum(const QtProperty *property) const;
+    int singleStep(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, int val);
+    void setMinimum(QtProperty *property, int minVal);
+    void setMaximum(QtProperty *property, int maxVal);
+    void setRange(QtProperty *property, int minVal, int maxVal);
+    void setSingleStep(QtProperty *property, int step);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, int val);
+    void rangeChanged(QtProperty *property, int minVal, int maxVal);
+    void singleStepChanged(QtProperty *property, int step);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtIntPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtIntPropertyManager)
+    Q_DISABLE_COPY(QtIntPropertyManager)
+};
+
+class QtBoolPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtBoolPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtBoolPropertyManager(QObject *parent = 0);
+    ~QtBoolPropertyManager();
+
+    bool value(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, bool val);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, bool val);
+protected:
+    QString valueText(const QtProperty *property) const;
+    QIcon valueIcon(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtBoolPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtBoolPropertyManager)
+    Q_DISABLE_COPY(QtBoolPropertyManager)
+};
+
+class QtDoublePropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtDoublePropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtDoublePropertyManager(QObject *parent = 0);
+    ~QtDoublePropertyManager();
+
+    double value(const QtProperty *property) const;
+    double minimum(const QtProperty *property) const;
+    double maximum(const QtProperty *property) const;
+    double singleStep(const QtProperty *property) const;
+    int decimals(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, double val);
+    void setMinimum(QtProperty *property, double minVal);
+    void setMaximum(QtProperty *property, double maxVal);
+    void setRange(QtProperty *property, double minVal, double maxVal);
+    void setSingleStep(QtProperty *property, double step);
+    void setDecimals(QtProperty *property, int prec);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, double val);
+    void rangeChanged(QtProperty *property, double minVal, double maxVal);
+    void singleStepChanged(QtProperty *property, double step);
+    void decimalsChanged(QtProperty *property, int prec);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtDoublePropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtDoublePropertyManager)
+    Q_DISABLE_COPY(QtDoublePropertyManager)
+};
+
+class QtStringPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtStringPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtStringPropertyManager(QObject *parent = 0);
+    ~QtStringPropertyManager();
+
+    QString value(const QtProperty *property) const;
+    QRegExp regExp(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QString &val);
+    void setRegExp(QtProperty *property, const QRegExp &regExp);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QString &val);
+    void regExpChanged(QtProperty *property, const QRegExp &regExp);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtStringPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtStringPropertyManager)
+    Q_DISABLE_COPY(QtStringPropertyManager)
+};
+
+class QtDatePropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtDatePropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtDatePropertyManager(QObject *parent = 0);
+    ~QtDatePropertyManager();
+
+    QDate value(const QtProperty *property) const;
+    QDate minimum(const QtProperty *property) const;
+    QDate maximum(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QDate &val);
+    void setMinimum(QtProperty *property, const QDate &minVal);
+    void setMaximum(QtProperty *property, const QDate &maxVal);
+    void setRange(QtProperty *property, const QDate &minVal, const QDate &maxVal);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QDate &val);
+    void rangeChanged(QtProperty *property, const QDate &minVal, const QDate &maxVal);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtDatePropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtDatePropertyManager)
+    Q_DISABLE_COPY(QtDatePropertyManager)
+};
+
+class QtTimePropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtTimePropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtTimePropertyManager(QObject *parent = 0);
+    ~QtTimePropertyManager();
+
+    QTime value(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QTime &val);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QTime &val);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtTimePropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtTimePropertyManager)
+    Q_DISABLE_COPY(QtTimePropertyManager)
+};
+
+class QtDateTimePropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtDateTimePropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtDateTimePropertyManager(QObject *parent = 0);
+    ~QtDateTimePropertyManager();
+
+    QDateTime value(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QDateTime &val);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QDateTime &val);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtDateTimePropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtDateTimePropertyManager)
+    Q_DISABLE_COPY(QtDateTimePropertyManager)
+};
+
+class QtKeySequencePropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtKeySequencePropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtKeySequencePropertyManager(QObject *parent = 0);
+    ~QtKeySequencePropertyManager();
+
+    QKeySequence value(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QKeySequence &val);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QKeySequence &val);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtKeySequencePropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtKeySequencePropertyManager)
+    Q_DISABLE_COPY(QtKeySequencePropertyManager)
+};
+
+class QtCharPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtCharPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtCharPropertyManager(QObject *parent = 0);
+    ~QtCharPropertyManager();
+
+    QChar value(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QChar &val);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QChar &val);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtCharPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtCharPropertyManager)
+    Q_DISABLE_COPY(QtCharPropertyManager)
+};
+
+class QtEnumPropertyManager;
+class QtLocalePropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtLocalePropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtLocalePropertyManager(QObject *parent = 0);
+    ~QtLocalePropertyManager();
+
+    QtEnumPropertyManager *subEnumPropertyManager() const;
+
+    QLocale value(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QLocale &val);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QLocale &val);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtLocalePropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtLocalePropertyManager)
+    Q_DISABLE_COPY(QtLocalePropertyManager)
+    Q_PRIVATE_SLOT(d_func(), void slotEnumChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
+};
+
+class QtPointPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtPointPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtPointPropertyManager(QObject *parent = 0);
+    ~QtPointPropertyManager();
+
+    QtIntPropertyManager *subIntPropertyManager() const;
+
+    QPoint value(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QPoint &val);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QPoint &val);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtPointPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtPointPropertyManager)
+    Q_DISABLE_COPY(QtPointPropertyManager)
+    Q_PRIVATE_SLOT(d_func(), void slotIntChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
+};
+
+class QtPointFPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtPointFPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtPointFPropertyManager(QObject *parent = 0);
+    ~QtPointFPropertyManager();
+
+    QtDoublePropertyManager *subDoublePropertyManager() const;
+
+    QPointF value(const QtProperty *property) const;
+    int decimals(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QPointF &val);
+    void setDecimals(QtProperty *property, int prec);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QPointF &val);
+    void decimalsChanged(QtProperty *property, int prec);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtPointFPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtPointFPropertyManager)
+    Q_DISABLE_COPY(QtPointFPropertyManager)
+    Q_PRIVATE_SLOT(d_func(), void slotDoubleChanged(QtProperty *, double))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
+};
+
+class QtSizePropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtSizePropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtSizePropertyManager(QObject *parent = 0);
+    ~QtSizePropertyManager();
+
+    QtIntPropertyManager *subIntPropertyManager() const;
+
+    QSize value(const QtProperty *property) const;
+    QSize minimum(const QtProperty *property) const;
+    QSize maximum(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QSize &val);
+    void setMinimum(QtProperty *property, const QSize &minVal);
+    void setMaximum(QtProperty *property, const QSize &maxVal);
+    void setRange(QtProperty *property, const QSize &minVal, const QSize &maxVal);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QSize &val);
+    void rangeChanged(QtProperty *property, const QSize &minVal, const QSize &maxVal);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtSizePropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtSizePropertyManager)
+    Q_DISABLE_COPY(QtSizePropertyManager)
+    Q_PRIVATE_SLOT(d_func(), void slotIntChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
+};
+
+class QtSizeFPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtSizeFPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtSizeFPropertyManager(QObject *parent = 0);
+    ~QtSizeFPropertyManager();
+
+    QtDoublePropertyManager *subDoublePropertyManager() const;
+
+    QSizeF value(const QtProperty *property) const;
+    QSizeF minimum(const QtProperty *property) const;
+    QSizeF maximum(const QtProperty *property) const;
+    int decimals(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QSizeF &val);
+    void setMinimum(QtProperty *property, const QSizeF &minVal);
+    void setMaximum(QtProperty *property, const QSizeF &maxVal);
+    void setRange(QtProperty *property, const QSizeF &minVal, const QSizeF &maxVal);
+    void setDecimals(QtProperty *property, int prec);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QSizeF &val);
+    void rangeChanged(QtProperty *property, const QSizeF &minVal, const QSizeF &maxVal);
+    void decimalsChanged(QtProperty *property, int prec);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtSizeFPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtSizeFPropertyManager)
+    Q_DISABLE_COPY(QtSizeFPropertyManager)
+    Q_PRIVATE_SLOT(d_func(), void slotDoubleChanged(QtProperty *, double))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
+};
+
+class QtRectPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtRectPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtRectPropertyManager(QObject *parent = 0);
+    ~QtRectPropertyManager();
+
+    QtIntPropertyManager *subIntPropertyManager() const;
+
+    QRect value(const QtProperty *property) const;
+    QRect constraint(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QRect &val);
+    void setConstraint(QtProperty *property, const QRect &constraint);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QRect &val);
+    void constraintChanged(QtProperty *property, const QRect &constraint);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtRectPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtRectPropertyManager)
+    Q_DISABLE_COPY(QtRectPropertyManager)
+    Q_PRIVATE_SLOT(d_func(), void slotIntChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
+};
+
+class QtRectFPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtRectFPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtRectFPropertyManager(QObject *parent = 0);
+    ~QtRectFPropertyManager();
+
+    QtDoublePropertyManager *subDoublePropertyManager() const;
+
+    QRectF value(const QtProperty *property) const;
+    QRectF constraint(const QtProperty *property) const;
+    int decimals(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QRectF &val);
+    void setConstraint(QtProperty *property, const QRectF &constraint);
+    void setDecimals(QtProperty *property, int prec);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QRectF &val);
+    void constraintChanged(QtProperty *property, const QRectF &constraint);
+    void decimalsChanged(QtProperty *property, int prec);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtRectFPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtRectFPropertyManager)
+    Q_DISABLE_COPY(QtRectFPropertyManager)
+    Q_PRIVATE_SLOT(d_func(), void slotDoubleChanged(QtProperty *, double))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
+};
+
+class QtEnumPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtEnumPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtEnumPropertyManager(QObject *parent = 0);
+    ~QtEnumPropertyManager();
+
+    int value(const QtProperty *property) const;
+    QStringList enumNames(const QtProperty *property) const;
+    QMap<int, QIcon> enumIcons(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, int val);
+    void setEnumNames(QtProperty *property, const QStringList &names);
+    void setEnumIcons(QtProperty *property, const QMap<int, QIcon> &icons);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, int val);
+    void enumNamesChanged(QtProperty *property, const QStringList &names);
+    void enumIconsChanged(QtProperty *property, const QMap<int, QIcon> &icons);
+protected:
+    QString valueText(const QtProperty *property) const;
+    QIcon valueIcon(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtEnumPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtEnumPropertyManager)
+    Q_DISABLE_COPY(QtEnumPropertyManager)
+};
+
+class QtFlagPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtFlagPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtFlagPropertyManager(QObject *parent = 0);
+    ~QtFlagPropertyManager();
+
+    QtBoolPropertyManager *subBoolPropertyManager() const;
+
+    int value(const QtProperty *property) const;
+    QStringList flagNames(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, int val);
+    void setFlagNames(QtProperty *property, const QStringList &names);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, int val);
+    void flagNamesChanged(QtProperty *property, const QStringList &names);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtFlagPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtFlagPropertyManager)
+    Q_DISABLE_COPY(QtFlagPropertyManager)
+    Q_PRIVATE_SLOT(d_func(), void slotBoolChanged(QtProperty *, bool))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
+};
+
+class QtSizePolicyPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtSizePolicyPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtSizePolicyPropertyManager(QObject *parent = 0);
+    ~QtSizePolicyPropertyManager();
+
+    QtIntPropertyManager *subIntPropertyManager() const;
+    QtEnumPropertyManager *subEnumPropertyManager() const;
+
+    QSizePolicy value(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QSizePolicy &val);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QSizePolicy &val);
+protected:
+    QString valueText(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtSizePolicyPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtSizePolicyPropertyManager)
+    Q_DISABLE_COPY(QtSizePolicyPropertyManager)
+    Q_PRIVATE_SLOT(d_func(), void slotIntChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotEnumChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
+};
+
+class QtFontPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtFontPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtFontPropertyManager(QObject *parent = 0);
+    ~QtFontPropertyManager();
+
+    QtIntPropertyManager *subIntPropertyManager() const;
+    QtEnumPropertyManager *subEnumPropertyManager() const;
+    QtBoolPropertyManager *subBoolPropertyManager() const;
+
+    QFont value(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QFont &val);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QFont &val);
+protected:
+    QString valueText(const QtProperty *property) const;
+    QIcon valueIcon(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtFontPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtFontPropertyManager)
+    Q_DISABLE_COPY(QtFontPropertyManager)
+    Q_PRIVATE_SLOT(d_func(), void slotIntChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotEnumChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotBoolChanged(QtProperty *, bool))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
+    Q_PRIVATE_SLOT(d_func(), void slotFontDatabaseChanged())
+    Q_PRIVATE_SLOT(d_func(), void slotFontDatabaseDelayedChange())
+};
+
+class QtColorPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtColorPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtColorPropertyManager(QObject *parent = 0);
+    ~QtColorPropertyManager();
+
+    QtIntPropertyManager *subIntPropertyManager() const;
+
+    QColor value(const QtProperty *property) const;
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QColor &val);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QColor &val);
+protected:
+    QString valueText(const QtProperty *property) const;
+    QIcon valueIcon(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtColorPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtColorPropertyManager)
+    Q_DISABLE_COPY(QtColorPropertyManager)
+    Q_PRIVATE_SLOT(d_func(), void slotIntChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyDestroyed(QtProperty *))
+};
+
+class QtCursorPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtCursorPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtCursorPropertyManager(QObject *parent = 0);
+    ~QtCursorPropertyManager();
+
+#ifndef QT_NO_CURSOR
+    QCursor value(const QtProperty *property) const;
+#endif
+
+public Q_SLOTS:
+    void setValue(QtProperty *property, const QCursor &val);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QCursor &val);
+protected:
+    QString valueText(const QtProperty *property) const;
+    QIcon valueIcon(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+private:
+    QtCursorPropertyManagerPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtCursorPropertyManager)
+    Q_DISABLE_COPY(QtCursorPropertyManager)
+};
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#endif
diff --git a/Code/Mantid/QtPropertyBrowser/src/qttreepropertybrowser.cpp b/Code/Mantid/QtPropertyBrowser/src/qttreepropertybrowser.cpp
index ce74bd9b59167f02baf5927928a4d0762b31a550..86a46b811b6dd63f8470378de4d450d535b42a76 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qttreepropertybrowser.cpp
+++ b/Code/Mantid/QtPropertyBrowser/src/qttreepropertybrowser.cpp
@@ -1,1098 +1,1098 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qttreepropertybrowser.h"
-#include <QtCore/QSet>
-#include <QtGui/QIcon>
-#include <QtGui/QTreeWidget>
-#include <QtGui/QItemDelegate>
-#include <QtGui/QHBoxLayout>
-#include <QtGui/QHeaderView>
-#include <QtGui/QPainter>
-#include <QtGui/QApplication>
-#include <QtGui/QFocusEvent>
-#include <QtGui/QStyle>
-#include <QtGui/QPalette>
-
-#include <iostream>
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-class QtPropertyEditorView;
-
-class QtTreePropertyBrowserPrivate
-{
-    QtTreePropertyBrowser *q_ptr;
-    Q_DECLARE_PUBLIC(QtTreePropertyBrowser)
-
-public:
-    QtTreePropertyBrowserPrivate();
-    void init(QWidget *parent);
-
-    void propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex);
-    void propertyRemoved(QtBrowserItem *index);
-    void propertyChanged(QtBrowserItem *index);
-    QWidget *createEditor(QtProperty *property, QWidget *parent) const
-        { return q_ptr->createEditor(property, parent); }
-    QtProperty *indexToProperty(const QModelIndex &index) const;
-    QTreeWidgetItem *indexToItem(const QModelIndex &index) const;
-    QtBrowserItem *indexToBrowserItem(const QModelIndex &index) const;
-    bool lastColumn(int column) const;
-    void disableItem(QTreeWidgetItem *item) const;
-    void enableItem(QTreeWidgetItem *item) const;
-    bool hasValue(QTreeWidgetItem *item) const;
-
-    void slotCollapsed(const QModelIndex &index);
-    void slotExpanded(const QModelIndex &index);
-
-    QColor calculatedBackgroundColor(QtBrowserItem *item) const;
-
-    QtPropertyEditorView *treeWidget() const { return m_treeWidget; }
-    bool markPropertiesWithoutValue() const { return m_markPropertiesWithoutValue; }
-
-    QtBrowserItem *currentItem() const;
-    void setCurrentItem(QtBrowserItem *browserItem, bool block);
-    void editItem(QtBrowserItem *browserItem);
-
-    void slotCurrentBrowserItemChanged(QtBrowserItem *item);
-    void slotCurrentTreeItemChanged(QTreeWidgetItem *newItem, QTreeWidgetItem *);
-
-    QTreeWidgetItem *editedItem() const;
-
-private:
-    void updateItem(QTreeWidgetItem *item);
-
-    QMap<QtBrowserItem *, QTreeWidgetItem *> m_indexToItem;
-    QMap<QTreeWidgetItem *, QtBrowserItem *> m_itemToIndex;
-
-    QMap<QtBrowserItem *, QColor> m_indexToBackgroundColor;
-
-    QtPropertyEditorView *m_treeWidget;
-
-    bool m_headerVisible;
-    QtTreePropertyBrowser::ResizeMode m_resizeMode;
-    class QtPropertyEditorDelegate *m_delegate;
-    bool m_markPropertiesWithoutValue;
-    bool m_browserChangedBlocked;
-    QIcon m_expandIcon;
-};
-
-// ------------ QtPropertyEditorView
-class QtPropertyEditorView : public QTreeWidget
-{
-    Q_OBJECT
-public:
-    QtPropertyEditorView(QWidget *parent = 0);
-
-    void setEditorPrivate(QtTreePropertyBrowserPrivate *editorPrivate)
-        { m_editorPrivate = editorPrivate; }
-
-    QTreeWidgetItem *indexToItem(const QModelIndex &index) const
-        { return itemFromIndex(index); }
-
-protected:
-    void keyPressEvent(QKeyEvent *event);
-    void mousePressEvent(QMouseEvent *event);
-    void drawRow(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
-
-private:
-    QtTreePropertyBrowserPrivate *m_editorPrivate;
-};
-
-QtPropertyEditorView::QtPropertyEditorView(QWidget *parent) :
-    QTreeWidget(parent),
-    m_editorPrivate(0)
-{
-    connect(header(), SIGNAL(sectionDoubleClicked(int)), this, SLOT(resizeColumnToContents(int)));
-}
-
-void QtPropertyEditorView::drawRow(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
-{
-    QStyleOptionViewItemV3 opt = option;
-    bool hasValue = true;
-    if (m_editorPrivate) {
-        QtProperty *property = m_editorPrivate->indexToProperty(index);
-        if (property)
-            hasValue = property->hasValue();
-    }
-    if (!hasValue && m_editorPrivate->markPropertiesWithoutValue()) {
-        const QColor c = option.palette.color(QPalette::Dark);
-        painter->fillRect(option.rect, c);
-        opt.palette.setColor(QPalette::AlternateBase, c);
-    } else {
-        QColor c = m_editorPrivate->calculatedBackgroundColor(m_editorPrivate->indexToBrowserItem(index));
-        if (index.parent() == QModelIndex())
-        {
-          c = option.palette.color(QPalette::Mid);
-        }
-        if (c.isValid()) {
-          
-            painter->fillRect(option.rect, c);
-            opt.palette.setColor(QPalette::AlternateBase, c.lighter(112));
-        }
-    }
-    QTreeWidget::drawRow(painter, opt, index);
-    QColor color = static_cast<QRgb>(QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor, &opt));
-    painter->save();
-    painter->setPen(QPen(color));
-    painter->drawLine(opt.rect.x(), opt.rect.bottom(), opt.rect.right(), opt.rect.bottom());
-    painter->restore();
-}
-
-void QtPropertyEditorView::keyPressEvent(QKeyEvent *event)
-{
-    switch (event->key()) {
-    case Qt::Key_Return:
-    case Qt::Key_Enter:
-    case Qt::Key_Space: // Trigger Edit
-        if (!m_editorPrivate->editedItem())
-            if (const QTreeWidgetItem *item = currentItem())
-                if (item->columnCount() >= 2 && ((item->flags() & (Qt::ItemIsEditable | Qt::ItemIsEnabled)) == (Qt::ItemIsEditable | Qt::ItemIsEnabled))) {
-                    event->accept();
-                    // If the current position is at column 0, move to 1.
-                    QModelIndex index = currentIndex();
-                    if (index.column() == 0) {
-                        index = index.sibling(index.row(), 1);
-                        setCurrentIndex(index);
-                    }
-                    edit(index);
-                    return;
-                }
-        break;
-    default:
-        break;
-    }
-    QTreeWidget::keyPressEvent(event);
-}
-
-void QtPropertyEditorView::mousePressEvent(QMouseEvent *event)
-{
-    QTreeWidget::mousePressEvent(event);
-    QTreeWidgetItem *item = itemAt(event->pos());
-
-    if (item) {
-        if ((item != m_editorPrivate->editedItem()) && (event->button() == Qt::LeftButton)
-                && (header()->logicalIndexAt(event->pos().x()) == 1)
-                && ((item->flags() & (Qt::ItemIsEditable | Qt::ItemIsEnabled)) == (Qt::ItemIsEditable | Qt::ItemIsEnabled))) {
-            editItem(item, 1);
-        } else if (!m_editorPrivate->hasValue(item) && m_editorPrivate->markPropertiesWithoutValue() && !rootIsDecorated()) {
-            if (event->pos().x() + header()->offset() < 20)
-                item->setExpanded(!item->isExpanded());
-        }
-    }
-}
-
-// ------------ QtPropertyEditorDelegate
-class QtPropertyEditorDelegate : public QItemDelegate
-{
-    Q_OBJECT
-public:
-    QtPropertyEditorDelegate(QObject *parent = 0)
-        : QItemDelegate(parent), m_editorPrivate(0), m_editedItem(0), m_editedWidget(0)
-        {}
-
-    void setEditorPrivate(QtTreePropertyBrowserPrivate *editorPrivate)
-        { m_editorPrivate = editorPrivate; }
-
-    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
-            const QModelIndex &index) const;
-
-    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
-            const QModelIndex &index) const;
-
-    void paint(QPainter *painter, const QStyleOptionViewItem &option,
-            const QModelIndex &index) const;
-
-    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
-
-    void setModelData(QWidget *, QAbstractItemModel *,
-            const QModelIndex &) const {}
-
-    void setEditorData(QWidget *, const QModelIndex &) const {}
-
-    bool eventFilter(QObject *object, QEvent *event);
-    void closeEditor(QtProperty *property);
-
-    QTreeWidgetItem *editedItem() const { return m_editedItem; }
-
-private slots:
-    void slotEditorDestroyed(QObject *object);
-
-private:
-    int indentation(const QModelIndex &index) const;
-
-    typedef QMap<QWidget *, QtProperty *> EditorToPropertyMap;
-    mutable EditorToPropertyMap m_editorToProperty;
-
-    typedef QMap<QtProperty *, QWidget *> PropertyToEditorMap;
-    mutable PropertyToEditorMap m_propertyToEditor;
-    QtTreePropertyBrowserPrivate *m_editorPrivate;
-    mutable QTreeWidgetItem *m_editedItem;
-    mutable QWidget *m_editedWidget;
-};
-
-int QtPropertyEditorDelegate::indentation(const QModelIndex &index) const
-{
-    if (!m_editorPrivate)
-        return 0;
-
-    QTreeWidgetItem *item = m_editorPrivate->indexToItem(index);
-    int indent = 0;
-    while (item->parent()) {
-        item = item->parent();
-        ++indent;
-    }
-    if (m_editorPrivate->treeWidget()->rootIsDecorated())
-        ++indent;
-    return indent * m_editorPrivate->treeWidget()->indentation();
-}
-
-void QtPropertyEditorDelegate::slotEditorDestroyed(QObject *object)
-{
-    if (QWidget *w = qobject_cast<QWidget *>(object)) {
-        const EditorToPropertyMap::iterator it = m_editorToProperty.find(w);
-        if (it != m_editorToProperty.end()) {
-            m_propertyToEditor.remove(it.value());
-            m_editorToProperty.erase(it);
-        }
-        if (m_editedWidget == w) {
-            m_editedWidget = 0;
-            m_editedItem = 0;
-        }
-    }
-}
-
-void QtPropertyEditorDelegate::closeEditor(QtProperty *property)
-{
-    if (QWidget *w = m_propertyToEditor.value(property, 0))
-        w->deleteLater();
-}
-
-QWidget *QtPropertyEditorDelegate::createEditor(QWidget *parent,
-        const QStyleOptionViewItem &, const QModelIndex &index) const
-{
-    if (index.column() == 1 && m_editorPrivate) {
-        QtProperty *property = m_editorPrivate->indexToProperty(index);
-        QTreeWidgetItem *item = m_editorPrivate->indexToItem(index);
-        if (property && item && (item->flags() & Qt::ItemIsEnabled)) {
-            QWidget *editor = m_editorPrivate->createEditor(property, parent);
-            if (editor) {
-                editor->setAutoFillBackground(true);
-                editor->installEventFilter(const_cast<QtPropertyEditorDelegate *>(this));
-                connect(editor, SIGNAL(destroyed(QObject *)), this, SLOT(slotEditorDestroyed(QObject *)));
-                m_propertyToEditor[property] = editor;
-                m_editorToProperty[editor] = property;
-                m_editedItem = item;
-                m_editedWidget = editor;
-            }
-            return editor;
-        }
-    }
-    return 0;
-}
-
-void QtPropertyEditorDelegate::updateEditorGeometry(QWidget *editor,
-        const QStyleOptionViewItem &option, const QModelIndex &index) const
-{
-    Q_UNUSED(index)
-    editor->setGeometry(option.rect.adjusted(0, 0, 0, -1));
-}
-
-void QtPropertyEditorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
-            const QModelIndex &index) const
-{
-    bool hasValue = true;
-    if (m_editorPrivate) {
-        QtProperty *property = m_editorPrivate->indexToProperty(index);
-        if (property)
-            hasValue = property->hasValue();
-    }
-    QStyleOptionViewItemV3 opt = option;
-    if ((m_editorPrivate && index.column() == 0) || !hasValue) {
-        QtProperty *property = m_editorPrivate->indexToProperty(index);
-        if (property && property->isModified()) {
-            opt.font.setBold(true);
-            opt.fontMetrics = QFontMetrics(opt.font);
-        }
-    }
-    QColor c;
-    if (!hasValue && m_editorPrivate->markPropertiesWithoutValue()) {
-        c = opt.palette.color(QPalette::Dark);
-        opt.palette.setColor(QPalette::Text, opt.palette.color(QPalette::BrightText));
-    } else {
-        c = m_editorPrivate->calculatedBackgroundColor(m_editorPrivate->indexToBrowserItem(index));
-        if (c.isValid() && (opt.features & QStyleOptionViewItemV2::Alternate))
-            c = c.lighter(112);
-    }
-    if (c.isValid())
-        painter->fillRect(option.rect, c);
-    opt.state &= ~QStyle::State_HasFocus;
-    QItemDelegate::paint(painter, opt, index);
-
-    opt.palette.setCurrentColorGroup(QPalette::Active);
-    QColor color = static_cast<QRgb>(QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor, &opt));
-    painter->save();
-    painter->setPen(QPen(color));
-    if (!m_editorPrivate || (!m_editorPrivate->lastColumn(index.column()) && hasValue)) {
-        int right = (option.direction == Qt::LeftToRight) ? option.rect.right() : option.rect.left();
-        painter->drawLine(right, option.rect.y(), right, option.rect.bottom());
-    }
-    painter->restore();
-}
-
-QSize QtPropertyEditorDelegate::sizeHint(const QStyleOptionViewItem &option,
-            const QModelIndex &index) const
-{
-    return QItemDelegate::sizeHint(option, index) + QSize(3, 4);
-}
-
-bool QtPropertyEditorDelegate::eventFilter(QObject *object, QEvent *event)
-{
-    if (event->type() == QEvent::FocusOut) {
-        QFocusEvent *fe = static_cast<QFocusEvent *>(event);
-        if (fe->reason() == Qt::ActiveWindowFocusReason)
-            return false;
-    }
-    return QItemDelegate::eventFilter(object, event);
-}
-
-//  -------- QtTreePropertyBrowserPrivate implementation
-QtTreePropertyBrowserPrivate::QtTreePropertyBrowserPrivate() :
-    m_treeWidget(0),
-    m_headerVisible(true),
-    m_resizeMode(QtTreePropertyBrowser::Stretch),
-    m_delegate(0),
-    m_markPropertiesWithoutValue(false),
-    m_browserChangedBlocked(false)
-{
-}
-
-// Draw an icon indicating opened/closing branches
-static QIcon drawIndicatorIcon(const QPalette &palette, QStyle *style)
-{
-    QPixmap pix(14, 14);
-    pix.fill(Qt::transparent);
-    QStyleOption branchOption;
-    QRect r(QPoint(0, 0), pix.size());
-    branchOption.rect = QRect(2, 2, 9, 9); // ### hardcoded in qcommonstyle.cpp
-    branchOption.palette = palette;
-    branchOption.state = QStyle::State_Children;
-
-    QPainter p;
-    // Draw closed state
-    p.begin(&pix);
-    style->drawPrimitive(QStyle::PE_IndicatorBranch, &branchOption, &p);
-    p.end();
-    QIcon rc = pix;
-    rc.addPixmap(pix, QIcon::Selected, QIcon::Off);
-    // Draw opened state
-    branchOption.state |= QStyle::State_Open;
-    pix.fill(Qt::transparent);
-    p.begin(&pix);
-    style->drawPrimitive(QStyle::PE_IndicatorBranch, &branchOption, &p);
-    p.end();
-
-    rc.addPixmap(pix, QIcon::Normal, QIcon::On);
-    rc.addPixmap(pix, QIcon::Selected, QIcon::On);
-    return rc;
-}
-
-void QtTreePropertyBrowserPrivate::init(QWidget *parent)
-{
-    QHBoxLayout *layout = new QHBoxLayout(parent);
-    layout->setMargin(0);
-    m_treeWidget = new QtPropertyEditorView(parent);
-    m_treeWidget->setEditorPrivate(this);
-    m_treeWidget->setIconSize(QSize(18, 18));
-    layout->addWidget(m_treeWidget);
-
-    m_treeWidget->setColumnCount(2);
-    QStringList labels;
-    labels.append(QApplication::translate("QtTreePropertyBrowser", "Property", 0, QApplication::UnicodeUTF8));
-    labels.append(QApplication::translate("QtTreePropertyBrowser", "Value", 0, QApplication::UnicodeUTF8));
-    m_treeWidget->setHeaderLabels(labels);
-    m_treeWidget->setAlternatingRowColors(true);
-    m_treeWidget->setEditTriggers(QAbstractItemView::EditKeyPressed);
-    m_delegate = new QtPropertyEditorDelegate(parent);
-    m_delegate->setEditorPrivate(this);
-    m_treeWidget->setItemDelegate(m_delegate);
-    m_treeWidget->header()->setMovable(false);
-    m_treeWidget->header()->setResizeMode(QHeaderView::Stretch);
-
-    m_expandIcon = drawIndicatorIcon(q_ptr->palette(), q_ptr->style());
-
-    QObject::connect(m_treeWidget, SIGNAL(collapsed(const QModelIndex &)), q_ptr, SLOT(slotCollapsed(const QModelIndex &)));
-    QObject::connect(m_treeWidget, SIGNAL(expanded(const QModelIndex &)), q_ptr, SLOT(slotExpanded(const QModelIndex &)));
-    QObject::connect(m_treeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), q_ptr, SLOT(slotCurrentTreeItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
-}
-
-QtBrowserItem *QtTreePropertyBrowserPrivate::currentItem() const
-{
-    if (QTreeWidgetItem *treeItem = m_treeWidget->currentItem())
-        return m_itemToIndex.value(treeItem);
-    return 0;
-}
-
-void QtTreePropertyBrowserPrivate::setCurrentItem(QtBrowserItem *browserItem, bool block)
-{
-    const bool blocked = block ? m_treeWidget->blockSignals(true) : false;
-    if (browserItem == 0)
-        m_treeWidget->setCurrentItem(0);
-    else
-        m_treeWidget->setCurrentItem(m_indexToItem.value(browserItem));
-    if (block)
-        m_treeWidget->blockSignals(blocked);
-}
-
-QtProperty *QtTreePropertyBrowserPrivate::indexToProperty(const QModelIndex &index) const
-{
-    QTreeWidgetItem *item = m_treeWidget->indexToItem(index);
-    QtBrowserItem *idx = m_itemToIndex.value(item);
-    if (idx)
-        return idx->property();
-    return 0;
-}
-
-QtBrowserItem *QtTreePropertyBrowserPrivate::indexToBrowserItem(const QModelIndex &index) const
-{
-    QTreeWidgetItem *item = m_treeWidget->indexToItem(index);
-    return m_itemToIndex.value(item);
-}
-
-QTreeWidgetItem *QtTreePropertyBrowserPrivate::indexToItem(const QModelIndex &index) const
-{
-    return m_treeWidget->indexToItem(index);
-}
-
-bool QtTreePropertyBrowserPrivate::lastColumn(int column) const
-{
-    return m_treeWidget->header()->visualIndex(column) == m_treeWidget->columnCount() - 1;
-}
-
-void QtTreePropertyBrowserPrivate::disableItem(QTreeWidgetItem *item) const
-{
-    Qt::ItemFlags flags = item->flags();
-    if (flags & Qt::ItemIsEnabled) {
-        flags &= ~Qt::ItemIsEnabled;
-        item->setFlags(flags);
-        m_delegate->closeEditor(m_itemToIndex[item]->property());
-        const int childCount = item->childCount();
-        for (int i = 0; i < childCount; i++) {
-            QTreeWidgetItem *child = item->child(i);
-            disableItem(child);
-        }
-    }
-}
-
-void QtTreePropertyBrowserPrivate::enableItem(QTreeWidgetItem *item) const
-{
-    Qt::ItemFlags flags = item->flags();
-    flags |= Qt::ItemIsEnabled;
-    item->setFlags(flags);
-    const int childCount = item->childCount();
-    for (int i = 0; i < childCount; i++) {
-        QTreeWidgetItem *child = item->child(i);
-        QtProperty *property = m_itemToIndex[child]->property();
-        if (property->isEnabled()) {
-            enableItem(child);
-        }
-    }
-}
-
-bool QtTreePropertyBrowserPrivate::hasValue(QTreeWidgetItem *item) const
-{
-    QtBrowserItem *browserItem = m_itemToIndex.value(item);
-    if (browserItem)
-        return browserItem->property()->hasValue();
-    return false;
-}
-
-void QtTreePropertyBrowserPrivate::propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex)
-{
-    QTreeWidgetItem *afterItem = m_indexToItem.value(afterIndex);
-    QTreeWidgetItem *parentItem = m_indexToItem.value(index->parent());
-
-    QTreeWidgetItem *newItem = 0;
-    if (parentItem) {
-        newItem = new QTreeWidgetItem(parentItem, afterItem);
-    } else {
-        newItem = new QTreeWidgetItem(m_treeWidget, afterItem);
-    }
-    m_itemToIndex[newItem] = index;
-    m_indexToItem[index] = newItem;
-
-    newItem->setFlags(newItem->flags() | Qt::ItemIsEditable);
-    m_treeWidget->setItemExpanded(newItem, true);
-
-    updateItem(newItem);
-}
-
-void QtTreePropertyBrowserPrivate::propertyRemoved(QtBrowserItem *index)
-{
-    QTreeWidgetItem *item = m_indexToItem.value(index);
-
-    if (m_treeWidget->currentItem() == item) {
-        m_treeWidget->setCurrentItem(0);
-    }
-
-    delete item;
-
-    m_indexToItem.remove(index);
-    m_itemToIndex.remove(item);
-    m_indexToBackgroundColor.remove(index);
-}
-
-void QtTreePropertyBrowserPrivate::propertyChanged(QtBrowserItem *index)
-{
-    QTreeWidgetItem *item = m_indexToItem.value(index);
-
-    updateItem(item);
-}
-
-void QtTreePropertyBrowserPrivate::updateItem(QTreeWidgetItem *item)
-{
-    QtProperty *property = m_itemToIndex[item]->property();
-    QIcon expandIcon;
-    if (property->hasValue()) {
-        QString toolTip = property->toolTip();
-        if (toolTip.isEmpty())
-            toolTip = property->valueText();
-        item->setToolTip(1, toolTip);
-        item->setIcon(1, property->valueIcon());
-        item->setText(1, property->valueText());
-    } else if (markPropertiesWithoutValue() && !m_treeWidget->rootIsDecorated()) {
-        expandIcon = m_expandIcon;
-    }
-    item->setIcon(0, expandIcon);
-    item->setFirstColumnSpanned(!property->hasValue());
-    item->setToolTip(0, property->propertyName());
-    item->setStatusTip(0, property->statusTip());
-    item->setWhatsThis(0, property->whatsThis());
-    item->setText(0, property->propertyName());
-    bool wasEnabled = item->flags() & Qt::ItemIsEnabled;
-    bool isEnabled = wasEnabled;
-    if (property->isEnabled()) {
-        QTreeWidgetItem *parent = item->parent();
-        if (!parent || (parent->flags() & Qt::ItemIsEnabled))
-            isEnabled = true;
-        else
-            isEnabled = false;
-    } else {
-        isEnabled = false;
-    }
-    if (wasEnabled != isEnabled) {
-        if (isEnabled)
-            enableItem(item);
-        else
-            disableItem(item);
-    }
-    m_treeWidget->viewport()->update();
-}
-
-QColor QtTreePropertyBrowserPrivate::calculatedBackgroundColor(QtBrowserItem *item) const
-{
-    QtBrowserItem *i = item;
-    const QMap<QtBrowserItem *, QColor>::const_iterator itEnd = m_indexToBackgroundColor.constEnd();
-    while (i) {
-        QMap<QtBrowserItem *, QColor>::const_iterator it = m_indexToBackgroundColor.constFind(i);
-        if (it != itEnd)
-            return it.value();
-        i = i->parent();
-    }
-    return QColor();
-}
-
-void QtTreePropertyBrowserPrivate::slotCollapsed(const QModelIndex &index)
-{
-    QTreeWidgetItem *item = indexToItem(index);
-    QtBrowserItem *idx = m_itemToIndex.value(item);
-    if (item)
-        emit q_ptr->collapsed(idx);
-}
-
-void QtTreePropertyBrowserPrivate::slotExpanded(const QModelIndex &index)
-{
-    QTreeWidgetItem *item = indexToItem(index);
-    QtBrowserItem *idx = m_itemToIndex.value(item);
-    if (item)
-        emit q_ptr->expanded(idx);
-}
-
-void QtTreePropertyBrowserPrivate::slotCurrentBrowserItemChanged(QtBrowserItem *item)
-{
-    if (!m_browserChangedBlocked && item != currentItem())
-        setCurrentItem(item, true);
-}
-
-void QtTreePropertyBrowserPrivate::slotCurrentTreeItemChanged(QTreeWidgetItem *newItem, QTreeWidgetItem *)
-{
-    QtBrowserItem *browserItem = newItem ? m_itemToIndex.value(newItem) : 0;
-    m_browserChangedBlocked = true;
-    q_ptr->setCurrentItem(browserItem);
-    m_browserChangedBlocked = false;
-}
-
-QTreeWidgetItem *QtTreePropertyBrowserPrivate::editedItem() const
-{
-    return m_delegate->editedItem();
-}
-
-void QtTreePropertyBrowserPrivate::editItem(QtBrowserItem *browserItem)
-{
-    if (QTreeWidgetItem *treeItem = m_indexToItem.value(browserItem, 0)) {
-        m_treeWidget->setCurrentItem (treeItem, 1);
-        m_treeWidget->editItem(treeItem, 1);
-    }
-}
-
-/**
-    \class QtTreePropertyBrowser
-
-    \brief The QtTreePropertyBrowser class provides QTreeWidget based
-    property browser.
-
-    A property browser is a widget that enables the user to edit a
-    given set of properties. Each property is represented by a label
-    specifying the property's name, and an editing widget (e.g. a line
-    edit or a combobox) holding its value. A property can have zero or
-    more subproperties.
-
-    QtTreePropertyBrowser provides a tree based view for all nested
-    properties, i.e. properties that have subproperties can be in an
-    expanded (subproperties are visible) or collapsed (subproperties
-    are hidden) state. For example:
-
-    \image qttreepropertybrowser.png
-
-    Use the QtAbstractPropertyBrowser API to add, insert and remove
-    properties from an instance of the QtTreePropertyBrowser class.
-    The properties themselves are created and managed by
-    implementations of the QtAbstractPropertyManager class.
-
-    \sa QtGroupBoxPropertyBrowser, QtAbstractPropertyBrowser
-*/
-
-/**
-    \fn void QtTreePropertyBrowser::collapsed(QtBrowserItem *item)
-
-    This signal is emitted when the \a item is collapsed.
-
-    \sa expanded(), setExpanded()
-*/
-
-/**
-    \fn void QtTreePropertyBrowser::expanded(QtBrowserItem *item)
-
-    This signal is emitted when the \a item is expanded.
-
-    \sa collapsed(), setExpanded()
-*/
-
-/**
-    Creates a property browser with the given \a parent.
-*/
-QtTreePropertyBrowser::QtTreePropertyBrowser(QWidget *parent)
-    : QtAbstractPropertyBrowser(parent)
-{
-    d_ptr = new QtTreePropertyBrowserPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->init(this);
-    connect(this, SIGNAL(currentItemChanged(QtBrowserItem*)), this, SLOT(slotCurrentBrowserItemChanged(QtBrowserItem*)));
-}
-
-/**
-    Destroys this property browser.
-
-    Note that the properties that were inserted into this browser are
-    \e not destroyed since they may still be used in other
-    browsers. The properties are owned by the manager that created
-    them.
-
-    \sa QtProperty, QtAbstractPropertyManager
-*/
-QtTreePropertyBrowser::~QtTreePropertyBrowser()
-{
-    delete d_ptr;
-}
-
-/**
-    \property QtTreePropertyBrowser::indentation
-    \brief indentation of the items in the tree view.
-*/
-int QtTreePropertyBrowser::indentation() const
-{
-    return d_ptr->m_treeWidget->indentation();
-}
-
-void QtTreePropertyBrowser::setIndentation(int i)
-{
-    d_ptr->m_treeWidget->setIndentation(i);
-}
-
-/**
-  \property QtTreePropertyBrowser::rootIsDecorated
-  \brief whether to show controls for expanding and collapsing root items.
-*/
-bool QtTreePropertyBrowser::rootIsDecorated() const
-{
-    return d_ptr->m_treeWidget->rootIsDecorated();
-}
-
-void QtTreePropertyBrowser::setRootIsDecorated(bool show)
-{
-    d_ptr->m_treeWidget->setRootIsDecorated(show);
-    QMapIterator<QTreeWidgetItem *, QtBrowserItem *> it(d_ptr->m_itemToIndex);
-    while (it.hasNext()) {
-        QtProperty *property = it.next().value()->property();
-        if (!property->hasValue())
-            d_ptr->updateItem(it.key());
-    }
-}
-
-/**
-  \property QtTreePropertyBrowser::alternatingRowColors
-  \brief whether to draw the background using alternating colors.
-  By default this property is set to true.
-*/
-bool QtTreePropertyBrowser::alternatingRowColors() const
-{
-    return d_ptr->m_treeWidget->alternatingRowColors();
-}
-
-void QtTreePropertyBrowser::setAlternatingRowColors(bool enable)
-{
-    d_ptr->m_treeWidget->setAlternatingRowColors(enable);
-    QMapIterator<QTreeWidgetItem *, QtBrowserItem *> it(d_ptr->m_itemToIndex);
-}
-
-/**
-  \property QtTreePropertyBrowser::headerVisible
-  \brief whether to show the header.
-*/
-bool QtTreePropertyBrowser::isHeaderVisible() const
-{
-    return d_ptr->m_headerVisible;
-}
-
-void QtTreePropertyBrowser::setHeaderVisible(bool visible)
-{
-    if (d_ptr->m_headerVisible == visible)
-        return;
-
-    d_ptr->m_headerVisible = visible;
-    d_ptr->m_treeWidget->header()->setVisible(visible);
-}
-
-/**
-  \enum QtTreePropertyBrowser::ResizeMode
-
-  The resize mode specifies the behavior of the header sections.
-
-  \value Interactive The user can resize the sections.
-  The sections can also be resized programmatically using setSplitterPosition().
-
-  \value Fixed The user cannot resize the section.
-  The section can only be resized programmatically using setSplitterPosition().
-
-  \value Stretch QHeaderView will automatically resize the section to fill the available space.
-  The size cannot be changed by the user or programmatically.
-
-  \value ResizeToContents QHeaderView will automatically resize the section to its optimal
-  size based on the contents of the entire column.
-  The size cannot be changed by the user or programmatically.
-
-  \sa setResizeMode()
-*/
-
-/**
-    \property QtTreePropertyBrowser::resizeMode
-    \brief the resize mode of setions in the header.
-*/
-
-QtTreePropertyBrowser::ResizeMode QtTreePropertyBrowser::resizeMode() const
-{
-    return d_ptr->m_resizeMode;
-}
-
-void QtTreePropertyBrowser::setResizeMode(QtTreePropertyBrowser::ResizeMode mode)
-{
-    if (d_ptr->m_resizeMode == mode)
-        return;
-
-    d_ptr->m_resizeMode = mode;
-    QHeaderView::ResizeMode m = QHeaderView::Stretch;
-    switch (mode) {
-        case QtTreePropertyBrowser::Interactive:      m = QHeaderView::Interactive;      break;
-        case QtTreePropertyBrowser::Fixed:            m = QHeaderView::Fixed;            break;
-        case QtTreePropertyBrowser::ResizeToContents: m = QHeaderView::ResizeToContents; break;
-        case QtTreePropertyBrowser::Stretch:
-        default:                                      m = QHeaderView::Stretch;          break;
-    }
-    d_ptr->m_treeWidget->header()->setResizeMode(m);
-}
-
-/**
-    \property QtTreePropertyBrowser::splitterPosition
-    \brief the position of the splitter between the colunms.
-*/
-
-int QtTreePropertyBrowser::splitterPosition() const
-{
-    return d_ptr->m_treeWidget->header()->sectionSize(0);
-}
-
-void QtTreePropertyBrowser::setSplitterPosition(int position)
-{
-    d_ptr->m_treeWidget->header()->resizeSection(0, position);
-}
-
-/**
-    Sets the \a item to either collapse or expanded, depending on the value of \a expanded.
-
-    \sa isExpanded(), expanded(), collapsed()
-*/
-
-void QtTreePropertyBrowser::setExpanded(QtBrowserItem *item, bool expanded)
-{
-    QTreeWidgetItem *treeItem = d_ptr->m_indexToItem.value(item);
-    if (treeItem)
-        treeItem->setExpanded(expanded);
-}
-
-/**
-    Returns true if the \a item is expanded; otherwise returns false.
-
-    \sa setExpanded()
-*/
-
-bool QtTreePropertyBrowser::isExpanded(QtBrowserItem *item) const
-{
-    QTreeWidgetItem *treeItem = d_ptr->m_indexToItem.value(item);
-    if (treeItem)
-        return treeItem->isExpanded();
-    return false;
-}
-
-/**
-    Returns true if the \a item is visible; otherwise returns false.
-
-    \sa setItemVisible()
-    \since 4.5
-*/
-
-bool QtTreePropertyBrowser::isItemVisible(QtBrowserItem *item) const
-{
-    if (const QTreeWidgetItem *treeItem = d_ptr->m_indexToItem.value(item))
-        return !treeItem->isHidden();
-    return false;
-}
-
-/**
-    Sets the \a item to be visible, depending on the value of \a visible.
-
-   \sa isItemVisible()
-   \since 4.5
-*/
-
-void QtTreePropertyBrowser::setItemVisible(QtBrowserItem *item, bool visible)
-{
-    if (QTreeWidgetItem *treeItem = d_ptr->m_indexToItem.value(item))
-        treeItem->setHidden(!visible);
-}
-
-/**
-    Sets the \a item's background color to \a color. Note that while item's background
-    is rendered every second row is being drawn with alternate color (which is a bit lighter than items \a color)
-
-    \sa backgroundColor(), calculatedBackgroundColor()
-*/
-
-void QtTreePropertyBrowser::setBackgroundColor(QtBrowserItem *item, const QColor &color)
-{
-    if (!d_ptr->m_indexToItem.contains(item))
-        return;
-    if (color.isValid())
-        d_ptr->m_indexToBackgroundColor[item] = color;
-    else
-        d_ptr->m_indexToBackgroundColor.remove(item);
-    d_ptr->m_treeWidget->viewport()->update();
-}
-
-/**
-    Returns the \a item's color. If there is no color set for item it returns invalid color.
-
-    \sa calculatedBackgroundColor(), setBackgroundColor()
-*/
-
-QColor QtTreePropertyBrowser::backgroundColor(QtBrowserItem *item) const
-{
-    return d_ptr->m_indexToBackgroundColor.value(item);
-}
-
-/**
-    Returns the \a item's color. If there is no color set for item it returns parent \a item's
-    color (if there is no color set for parent it returns grandparent's color and so on). In case
-    the color is not set for \a item and it's top level item it returns invalid color.
-
-    \sa backgroundColor(), setBackgroundColor()
-*/
-
-QColor QtTreePropertyBrowser::calculatedBackgroundColor(QtBrowserItem *item) const
-{
-    return d_ptr->calculatedBackgroundColor(item);
-}
-
-/**
-    \property QtTreePropertyBrowser::propertiesWithoutValueMarked
-    \brief whether to enable or disable marking properties without value.
-
-    When marking is enabled the item's background is rendered in dark color and item's
-    foreground is rendered with light color.
-
-    \sa propertiesWithoutValueMarked()
-*/
-void QtTreePropertyBrowser::setPropertiesWithoutValueMarked(bool mark)
-{
-    if (d_ptr->m_markPropertiesWithoutValue == mark)
-        return;
-
-    d_ptr->m_markPropertiesWithoutValue = mark;
-    QMapIterator<QTreeWidgetItem *, QtBrowserItem *> it(d_ptr->m_itemToIndex);
-    while (it.hasNext()) {
-        QtProperty *property = it.next().value()->property();
-        if (!property->hasValue())
-            d_ptr->updateItem(it.key());
-    }
-    d_ptr->m_treeWidget->viewport()->update();
-}
-
-bool QtTreePropertyBrowser::propertiesWithoutValueMarked() const
-{
-    return d_ptr->m_markPropertiesWithoutValue;
-}
-
-/**
-    \reimp
-*/
-void QtTreePropertyBrowser::itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem)
-{
-    d_ptr->propertyInserted(item, afterItem);
-}
-
-/**
-    \reimp
-*/
-void QtTreePropertyBrowser::itemRemoved(QtBrowserItem *item)
-{
-    d_ptr->propertyRemoved(item);
-}
-
-/**
-    \reimp
-*/
-void QtTreePropertyBrowser::itemChanged(QtBrowserItem *item)
-{
-    d_ptr->propertyChanged(item);
-}
-
-/**
-    Sets the current item to \a item and opens the relevant editor for it.
-*/
-void QtTreePropertyBrowser::editItem(QtBrowserItem *item)
-{
-    d_ptr->editItem(item);
-}
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#include "moc_qttreepropertybrowser.cpp"
-#include "qttreepropertybrowser.moc"
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qttreepropertybrowser.h"
+#include <QtCore/QSet>
+#include <QtGui/QIcon>
+#include <QtGui/QTreeWidget>
+#include <QtGui/QItemDelegate>
+#include <QtGui/QHBoxLayout>
+#include <QtGui/QHeaderView>
+#include <QtGui/QPainter>
+#include <QtGui/QApplication>
+#include <QtGui/QFocusEvent>
+#include <QtGui/QStyle>
+#include <QtGui/QPalette>
+
+#include <iostream>
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+class QtPropertyEditorView;
+
+class QtTreePropertyBrowserPrivate
+{
+    QtTreePropertyBrowser *q_ptr;
+    Q_DECLARE_PUBLIC(QtTreePropertyBrowser)
+
+public:
+    QtTreePropertyBrowserPrivate();
+    void init(QWidget *parent);
+
+    void propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex);
+    void propertyRemoved(QtBrowserItem *index);
+    void propertyChanged(QtBrowserItem *index);
+    QWidget *createEditor(QtProperty *property, QWidget *parent) const
+        { return q_ptr->createEditor(property, parent); }
+    QtProperty *indexToProperty(const QModelIndex &index) const;
+    QTreeWidgetItem *indexToItem(const QModelIndex &index) const;
+    QtBrowserItem *indexToBrowserItem(const QModelIndex &index) const;
+    bool lastColumn(int column) const;
+    void disableItem(QTreeWidgetItem *item) const;
+    void enableItem(QTreeWidgetItem *item) const;
+    bool hasValue(QTreeWidgetItem *item) const;
+
+    void slotCollapsed(const QModelIndex &index);
+    void slotExpanded(const QModelIndex &index);
+
+    QColor calculatedBackgroundColor(QtBrowserItem *item) const;
+
+    QtPropertyEditorView *treeWidget() const { return m_treeWidget; }
+    bool markPropertiesWithoutValue() const { return m_markPropertiesWithoutValue; }
+
+    QtBrowserItem *currentItem() const;
+    void setCurrentItem(QtBrowserItem *browserItem, bool block);
+    void editItem(QtBrowserItem *browserItem);
+
+    void slotCurrentBrowserItemChanged(QtBrowserItem *item);
+    void slotCurrentTreeItemChanged(QTreeWidgetItem *newItem, QTreeWidgetItem *);
+
+    QTreeWidgetItem *editedItem() const;
+
+private:
+    void updateItem(QTreeWidgetItem *item);
+
+    QMap<QtBrowserItem *, QTreeWidgetItem *> m_indexToItem;
+    QMap<QTreeWidgetItem *, QtBrowserItem *> m_itemToIndex;
+
+    QMap<QtBrowserItem *, QColor> m_indexToBackgroundColor;
+
+    QtPropertyEditorView *m_treeWidget;
+
+    bool m_headerVisible;
+    QtTreePropertyBrowser::ResizeMode m_resizeMode;
+    class QtPropertyEditorDelegate *m_delegate;
+    bool m_markPropertiesWithoutValue;
+    bool m_browserChangedBlocked;
+    QIcon m_expandIcon;
+};
+
+// ------------ QtPropertyEditorView
+class QtPropertyEditorView : public QTreeWidget
+{
+    Q_OBJECT
+public:
+    QtPropertyEditorView(QWidget *parent = 0);
+
+    void setEditorPrivate(QtTreePropertyBrowserPrivate *editorPrivate)
+        { m_editorPrivate = editorPrivate; }
+
+    QTreeWidgetItem *indexToItem(const QModelIndex &index) const
+        { return itemFromIndex(index); }
+
+protected:
+    void keyPressEvent(QKeyEvent *event);
+    void mousePressEvent(QMouseEvent *event);
+    void drawRow(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
+
+private:
+    QtTreePropertyBrowserPrivate *m_editorPrivate;
+};
+
+QtPropertyEditorView::QtPropertyEditorView(QWidget *parent) :
+    QTreeWidget(parent),
+    m_editorPrivate(0)
+{
+    connect(header(), SIGNAL(sectionDoubleClicked(int)), this, SLOT(resizeColumnToContents(int)));
+}
+
+void QtPropertyEditorView::drawRow(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
+{
+    QStyleOptionViewItemV3 opt = option;
+    bool hasValue = true;
+    if (m_editorPrivate) {
+        QtProperty *property = m_editorPrivate->indexToProperty(index);
+        if (property)
+            hasValue = property->hasValue();
+    }
+    if (!hasValue && m_editorPrivate->markPropertiesWithoutValue()) {
+        const QColor c = option.palette.color(QPalette::Dark);
+        painter->fillRect(option.rect, c);
+        opt.palette.setColor(QPalette::AlternateBase, c);
+    } else {
+        QColor c = m_editorPrivate->calculatedBackgroundColor(m_editorPrivate->indexToBrowserItem(index));
+        if (index.parent() == QModelIndex())
+        {
+          c = option.palette.color(QPalette::Mid);
+        }
+        if (c.isValid()) {
+          
+            painter->fillRect(option.rect, c);
+            opt.palette.setColor(QPalette::AlternateBase, c.lighter(112));
+        }
+    }
+    QTreeWidget::drawRow(painter, opt, index);
+    QColor color = static_cast<QRgb>(QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor, &opt));
+    painter->save();
+    painter->setPen(QPen(color));
+    painter->drawLine(opt.rect.x(), opt.rect.bottom(), opt.rect.right(), opt.rect.bottom());
+    painter->restore();
+}
+
+void QtPropertyEditorView::keyPressEvent(QKeyEvent *event)
+{
+    switch (event->key()) {
+    case Qt::Key_Return:
+    case Qt::Key_Enter:
+    case Qt::Key_Space: // Trigger Edit
+        if (!m_editorPrivate->editedItem())
+            if (const QTreeWidgetItem *item = currentItem())
+                if (item->columnCount() >= 2 && ((item->flags() & (Qt::ItemIsEditable | Qt::ItemIsEnabled)) == (Qt::ItemIsEditable | Qt::ItemIsEnabled))) {
+                    event->accept();
+                    // If the current position is at column 0, move to 1.
+                    QModelIndex index = currentIndex();
+                    if (index.column() == 0) {
+                        index = index.sibling(index.row(), 1);
+                        setCurrentIndex(index);
+                    }
+                    edit(index);
+                    return;
+                }
+        break;
+    default:
+        break;
+    }
+    QTreeWidget::keyPressEvent(event);
+}
+
+void QtPropertyEditorView::mousePressEvent(QMouseEvent *event)
+{
+    QTreeWidget::mousePressEvent(event);
+    QTreeWidgetItem *item = itemAt(event->pos());
+
+    if (item) {
+        if ((item != m_editorPrivate->editedItem()) && (event->button() == Qt::LeftButton)
+                && (header()->logicalIndexAt(event->pos().x()) == 1)
+                && ((item->flags() & (Qt::ItemIsEditable | Qt::ItemIsEnabled)) == (Qt::ItemIsEditable | Qt::ItemIsEnabled))) {
+            editItem(item, 1);
+        } else if (!m_editorPrivate->hasValue(item) && m_editorPrivate->markPropertiesWithoutValue() && !rootIsDecorated()) {
+            if (event->pos().x() + header()->offset() < 20)
+                item->setExpanded(!item->isExpanded());
+        }
+    }
+}
+
+// ------------ QtPropertyEditorDelegate
+class QtPropertyEditorDelegate : public QItemDelegate
+{
+    Q_OBJECT
+public:
+    QtPropertyEditorDelegate(QObject *parent = 0)
+        : QItemDelegate(parent), m_editorPrivate(0), m_editedItem(0), m_editedWidget(0)
+        {}
+
+    void setEditorPrivate(QtTreePropertyBrowserPrivate *editorPrivate)
+        { m_editorPrivate = editorPrivate; }
+
+    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
+            const QModelIndex &index) const;
+
+    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
+            const QModelIndex &index) const;
+
+    void paint(QPainter *painter, const QStyleOptionViewItem &option,
+            const QModelIndex &index) const;
+
+    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
+
+    void setModelData(QWidget *, QAbstractItemModel *,
+            const QModelIndex &) const {}
+
+    void setEditorData(QWidget *, const QModelIndex &) const {}
+
+    bool eventFilter(QObject *object, QEvent *event);
+    void closeEditor(QtProperty *property);
+
+    QTreeWidgetItem *editedItem() const { return m_editedItem; }
+
+private slots:
+    void slotEditorDestroyed(QObject *object);
+
+private:
+    int indentation(const QModelIndex &index) const;
+
+    typedef QMap<QWidget *, QtProperty *> EditorToPropertyMap;
+    mutable EditorToPropertyMap m_editorToProperty;
+
+    typedef QMap<QtProperty *, QWidget *> PropertyToEditorMap;
+    mutable PropertyToEditorMap m_propertyToEditor;
+    QtTreePropertyBrowserPrivate *m_editorPrivate;
+    mutable QTreeWidgetItem *m_editedItem;
+    mutable QWidget *m_editedWidget;
+};
+
+int QtPropertyEditorDelegate::indentation(const QModelIndex &index) const
+{
+    if (!m_editorPrivate)
+        return 0;
+
+    QTreeWidgetItem *item = m_editorPrivate->indexToItem(index);
+    int indent = 0;
+    while (item->parent()) {
+        item = item->parent();
+        ++indent;
+    }
+    if (m_editorPrivate->treeWidget()->rootIsDecorated())
+        ++indent;
+    return indent * m_editorPrivate->treeWidget()->indentation();
+}
+
+void QtPropertyEditorDelegate::slotEditorDestroyed(QObject *object)
+{
+    if (QWidget *w = qobject_cast<QWidget *>(object)) {
+        const EditorToPropertyMap::iterator it = m_editorToProperty.find(w);
+        if (it != m_editorToProperty.end()) {
+            m_propertyToEditor.remove(it.value());
+            m_editorToProperty.erase(it);
+        }
+        if (m_editedWidget == w) {
+            m_editedWidget = 0;
+            m_editedItem = 0;
+        }
+    }
+}
+
+void QtPropertyEditorDelegate::closeEditor(QtProperty *property)
+{
+    if (QWidget *w = m_propertyToEditor.value(property, 0))
+        w->deleteLater();
+}
+
+QWidget *QtPropertyEditorDelegate::createEditor(QWidget *parent,
+        const QStyleOptionViewItem &, const QModelIndex &index) const
+{
+    if (index.column() == 1 && m_editorPrivate) {
+        QtProperty *property = m_editorPrivate->indexToProperty(index);
+        QTreeWidgetItem *item = m_editorPrivate->indexToItem(index);
+        if (property && item && (item->flags() & Qt::ItemIsEnabled)) {
+            QWidget *editor = m_editorPrivate->createEditor(property, parent);
+            if (editor) {
+                editor->setAutoFillBackground(true);
+                editor->installEventFilter(const_cast<QtPropertyEditorDelegate *>(this));
+                connect(editor, SIGNAL(destroyed(QObject *)), this, SLOT(slotEditorDestroyed(QObject *)));
+                m_propertyToEditor[property] = editor;
+                m_editorToProperty[editor] = property;
+                m_editedItem = item;
+                m_editedWidget = editor;
+            }
+            return editor;
+        }
+    }
+    return 0;
+}
+
+void QtPropertyEditorDelegate::updateEditorGeometry(QWidget *editor,
+        const QStyleOptionViewItem &option, const QModelIndex &index) const
+{
+    Q_UNUSED(index)
+    editor->setGeometry(option.rect.adjusted(0, 0, 0, -1));
+}
+
+void QtPropertyEditorDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
+            const QModelIndex &index) const
+{
+    bool hasValue = true;
+    if (m_editorPrivate) {
+        QtProperty *property = m_editorPrivate->indexToProperty(index);
+        if (property)
+            hasValue = property->hasValue();
+    }
+    QStyleOptionViewItemV3 opt = option;
+    if ((m_editorPrivate && index.column() == 0) || !hasValue) {
+        QtProperty *property = m_editorPrivate->indexToProperty(index);
+        if (property && property->isModified()) {
+            opt.font.setBold(true);
+            opt.fontMetrics = QFontMetrics(opt.font);
+        }
+    }
+    QColor c;
+    if (!hasValue && m_editorPrivate->markPropertiesWithoutValue()) {
+        c = opt.palette.color(QPalette::Dark);
+        opt.palette.setColor(QPalette::Text, opt.palette.color(QPalette::BrightText));
+    } else {
+        c = m_editorPrivate->calculatedBackgroundColor(m_editorPrivate->indexToBrowserItem(index));
+        if (c.isValid() && (opt.features & QStyleOptionViewItemV2::Alternate))
+            c = c.lighter(112);
+    }
+    if (c.isValid())
+        painter->fillRect(option.rect, c);
+    opt.state &= ~QStyle::State_HasFocus;
+    QItemDelegate::paint(painter, opt, index);
+
+    opt.palette.setCurrentColorGroup(QPalette::Active);
+    QColor color = static_cast<QRgb>(QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor, &opt));
+    painter->save();
+    painter->setPen(QPen(color));
+    if (!m_editorPrivate || (!m_editorPrivate->lastColumn(index.column()) && hasValue)) {
+        int right = (option.direction == Qt::LeftToRight) ? option.rect.right() : option.rect.left();
+        painter->drawLine(right, option.rect.y(), right, option.rect.bottom());
+    }
+    painter->restore();
+}
+
+QSize QtPropertyEditorDelegate::sizeHint(const QStyleOptionViewItem &option,
+            const QModelIndex &index) const
+{
+    return QItemDelegate::sizeHint(option, index) + QSize(3, 4);
+}
+
+bool QtPropertyEditorDelegate::eventFilter(QObject *object, QEvent *event)
+{
+    if (event->type() == QEvent::FocusOut) {
+        QFocusEvent *fe = static_cast<QFocusEvent *>(event);
+        if (fe->reason() == Qt::ActiveWindowFocusReason)
+            return false;
+    }
+    return QItemDelegate::eventFilter(object, event);
+}
+
+//  -------- QtTreePropertyBrowserPrivate implementation
+QtTreePropertyBrowserPrivate::QtTreePropertyBrowserPrivate() :
+    m_treeWidget(0),
+    m_headerVisible(true),
+    m_resizeMode(QtTreePropertyBrowser::Stretch),
+    m_delegate(0),
+    m_markPropertiesWithoutValue(false),
+    m_browserChangedBlocked(false)
+{
+}
+
+// Draw an icon indicating opened/closing branches
+static QIcon drawIndicatorIcon(const QPalette &palette, QStyle *style)
+{
+    QPixmap pix(14, 14);
+    pix.fill(Qt::transparent);
+    QStyleOption branchOption;
+    QRect r(QPoint(0, 0), pix.size());
+    branchOption.rect = QRect(2, 2, 9, 9); // ### hardcoded in qcommonstyle.cpp
+    branchOption.palette = palette;
+    branchOption.state = QStyle::State_Children;
+
+    QPainter p;
+    // Draw closed state
+    p.begin(&pix);
+    style->drawPrimitive(QStyle::PE_IndicatorBranch, &branchOption, &p);
+    p.end();
+    QIcon rc = pix;
+    rc.addPixmap(pix, QIcon::Selected, QIcon::Off);
+    // Draw opened state
+    branchOption.state |= QStyle::State_Open;
+    pix.fill(Qt::transparent);
+    p.begin(&pix);
+    style->drawPrimitive(QStyle::PE_IndicatorBranch, &branchOption, &p);
+    p.end();
+
+    rc.addPixmap(pix, QIcon::Normal, QIcon::On);
+    rc.addPixmap(pix, QIcon::Selected, QIcon::On);
+    return rc;
+}
+
+void QtTreePropertyBrowserPrivate::init(QWidget *parent)
+{
+    QHBoxLayout *layout = new QHBoxLayout(parent);
+    layout->setMargin(0);
+    m_treeWidget = new QtPropertyEditorView(parent);
+    m_treeWidget->setEditorPrivate(this);
+    m_treeWidget->setIconSize(QSize(18, 18));
+    layout->addWidget(m_treeWidget);
+
+    m_treeWidget->setColumnCount(2);
+    QStringList labels;
+    labels.append(QApplication::translate("QtTreePropertyBrowser", "Property", 0, QApplication::UnicodeUTF8));
+    labels.append(QApplication::translate("QtTreePropertyBrowser", "Value", 0, QApplication::UnicodeUTF8));
+    m_treeWidget->setHeaderLabels(labels);
+    m_treeWidget->setAlternatingRowColors(true);
+    m_treeWidget->setEditTriggers(QAbstractItemView::EditKeyPressed);
+    m_delegate = new QtPropertyEditorDelegate(parent);
+    m_delegate->setEditorPrivate(this);
+    m_treeWidget->setItemDelegate(m_delegate);
+    m_treeWidget->header()->setMovable(false);
+    m_treeWidget->header()->setResizeMode(QHeaderView::Stretch);
+
+    m_expandIcon = drawIndicatorIcon(q_ptr->palette(), q_ptr->style());
+
+    QObject::connect(m_treeWidget, SIGNAL(collapsed(const QModelIndex &)), q_ptr, SLOT(slotCollapsed(const QModelIndex &)));
+    QObject::connect(m_treeWidget, SIGNAL(expanded(const QModelIndex &)), q_ptr, SLOT(slotExpanded(const QModelIndex &)));
+    QObject::connect(m_treeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), q_ptr, SLOT(slotCurrentTreeItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
+}
+
+QtBrowserItem *QtTreePropertyBrowserPrivate::currentItem() const
+{
+    if (QTreeWidgetItem *treeItem = m_treeWidget->currentItem())
+        return m_itemToIndex.value(treeItem);
+    return 0;
+}
+
+void QtTreePropertyBrowserPrivate::setCurrentItem(QtBrowserItem *browserItem, bool block)
+{
+    const bool blocked = block ? m_treeWidget->blockSignals(true) : false;
+    if (browserItem == 0)
+        m_treeWidget->setCurrentItem(0);
+    else
+        m_treeWidget->setCurrentItem(m_indexToItem.value(browserItem));
+    if (block)
+        m_treeWidget->blockSignals(blocked);
+}
+
+QtProperty *QtTreePropertyBrowserPrivate::indexToProperty(const QModelIndex &index) const
+{
+    QTreeWidgetItem *item = m_treeWidget->indexToItem(index);
+    QtBrowserItem *idx = m_itemToIndex.value(item);
+    if (idx)
+        return idx->property();
+    return 0;
+}
+
+QtBrowserItem *QtTreePropertyBrowserPrivate::indexToBrowserItem(const QModelIndex &index) const
+{
+    QTreeWidgetItem *item = m_treeWidget->indexToItem(index);
+    return m_itemToIndex.value(item);
+}
+
+QTreeWidgetItem *QtTreePropertyBrowserPrivate::indexToItem(const QModelIndex &index) const
+{
+    return m_treeWidget->indexToItem(index);
+}
+
+bool QtTreePropertyBrowserPrivate::lastColumn(int column) const
+{
+    return m_treeWidget->header()->visualIndex(column) == m_treeWidget->columnCount() - 1;
+}
+
+void QtTreePropertyBrowserPrivate::disableItem(QTreeWidgetItem *item) const
+{
+    Qt::ItemFlags flags = item->flags();
+    if (flags & Qt::ItemIsEnabled) {
+        flags &= ~Qt::ItemIsEnabled;
+        item->setFlags(flags);
+        m_delegate->closeEditor(m_itemToIndex[item]->property());
+        const int childCount = item->childCount();
+        for (int i = 0; i < childCount; i++) {
+            QTreeWidgetItem *child = item->child(i);
+            disableItem(child);
+        }
+    }
+}
+
+void QtTreePropertyBrowserPrivate::enableItem(QTreeWidgetItem *item) const
+{
+    Qt::ItemFlags flags = item->flags();
+    flags |= Qt::ItemIsEnabled;
+    item->setFlags(flags);
+    const int childCount = item->childCount();
+    for (int i = 0; i < childCount; i++) {
+        QTreeWidgetItem *child = item->child(i);
+        QtProperty *property = m_itemToIndex[child]->property();
+        if (property->isEnabled()) {
+            enableItem(child);
+        }
+    }
+}
+
+bool QtTreePropertyBrowserPrivate::hasValue(QTreeWidgetItem *item) const
+{
+    QtBrowserItem *browserItem = m_itemToIndex.value(item);
+    if (browserItem)
+        return browserItem->property()->hasValue();
+    return false;
+}
+
+void QtTreePropertyBrowserPrivate::propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex)
+{
+    QTreeWidgetItem *afterItem = m_indexToItem.value(afterIndex);
+    QTreeWidgetItem *parentItem = m_indexToItem.value(index->parent());
+
+    QTreeWidgetItem *newItem = 0;
+    if (parentItem) {
+        newItem = new QTreeWidgetItem(parentItem, afterItem);
+    } else {
+        newItem = new QTreeWidgetItem(m_treeWidget, afterItem);
+    }
+    m_itemToIndex[newItem] = index;
+    m_indexToItem[index] = newItem;
+
+    newItem->setFlags(newItem->flags() | Qt::ItemIsEditable);
+    m_treeWidget->setItemExpanded(newItem, true);
+
+    updateItem(newItem);
+}
+
+void QtTreePropertyBrowserPrivate::propertyRemoved(QtBrowserItem *index)
+{
+    QTreeWidgetItem *item = m_indexToItem.value(index);
+
+    if (m_treeWidget->currentItem() == item) {
+        m_treeWidget->setCurrentItem(0);
+    }
+
+    delete item;
+
+    m_indexToItem.remove(index);
+    m_itemToIndex.remove(item);
+    m_indexToBackgroundColor.remove(index);
+}
+
+void QtTreePropertyBrowserPrivate::propertyChanged(QtBrowserItem *index)
+{
+    QTreeWidgetItem *item = m_indexToItem.value(index);
+
+    updateItem(item);
+}
+
+void QtTreePropertyBrowserPrivate::updateItem(QTreeWidgetItem *item)
+{
+    QtProperty *property = m_itemToIndex[item]->property();
+    QIcon expandIcon;
+    if (property->hasValue()) {
+        QString toolTip = property->toolTip();
+        if (toolTip.isEmpty())
+            toolTip = property->valueText();
+        item->setToolTip(1, toolTip);
+        item->setIcon(1, property->valueIcon());
+        item->setText(1, property->valueText());
+    } else if (markPropertiesWithoutValue() && !m_treeWidget->rootIsDecorated()) {
+        expandIcon = m_expandIcon;
+    }
+    item->setIcon(0, expandIcon);
+    item->setFirstColumnSpanned(!property->hasValue());
+    item->setToolTip(0, property->propertyName());
+    item->setStatusTip(0, property->statusTip());
+    item->setWhatsThis(0, property->whatsThis());
+    item->setText(0, property->propertyName());
+    bool wasEnabled = item->flags() & Qt::ItemIsEnabled;
+    bool isEnabled = wasEnabled;
+    if (property->isEnabled()) {
+        QTreeWidgetItem *parent = item->parent();
+        if (!parent || (parent->flags() & Qt::ItemIsEnabled))
+            isEnabled = true;
+        else
+            isEnabled = false;
+    } else {
+        isEnabled = false;
+    }
+    if (wasEnabled != isEnabled) {
+        if (isEnabled)
+            enableItem(item);
+        else
+            disableItem(item);
+    }
+    m_treeWidget->viewport()->update();
+}
+
+QColor QtTreePropertyBrowserPrivate::calculatedBackgroundColor(QtBrowserItem *item) const
+{
+    QtBrowserItem *i = item;
+    const QMap<QtBrowserItem *, QColor>::const_iterator itEnd = m_indexToBackgroundColor.constEnd();
+    while (i) {
+        QMap<QtBrowserItem *, QColor>::const_iterator it = m_indexToBackgroundColor.constFind(i);
+        if (it != itEnd)
+            return it.value();
+        i = i->parent();
+    }
+    return QColor();
+}
+
+void QtTreePropertyBrowserPrivate::slotCollapsed(const QModelIndex &index)
+{
+    QTreeWidgetItem *item = indexToItem(index);
+    QtBrowserItem *idx = m_itemToIndex.value(item);
+    if (item)
+        emit q_ptr->collapsed(idx);
+}
+
+void QtTreePropertyBrowserPrivate::slotExpanded(const QModelIndex &index)
+{
+    QTreeWidgetItem *item = indexToItem(index);
+    QtBrowserItem *idx = m_itemToIndex.value(item);
+    if (item)
+        emit q_ptr->expanded(idx);
+}
+
+void QtTreePropertyBrowserPrivate::slotCurrentBrowserItemChanged(QtBrowserItem *item)
+{
+    if (!m_browserChangedBlocked && item != currentItem())
+        setCurrentItem(item, true);
+}
+
+void QtTreePropertyBrowserPrivate::slotCurrentTreeItemChanged(QTreeWidgetItem *newItem, QTreeWidgetItem *)
+{
+    QtBrowserItem *browserItem = newItem ? m_itemToIndex.value(newItem) : 0;
+    m_browserChangedBlocked = true;
+    q_ptr->setCurrentItem(browserItem);
+    m_browserChangedBlocked = false;
+}
+
+QTreeWidgetItem *QtTreePropertyBrowserPrivate::editedItem() const
+{
+    return m_delegate->editedItem();
+}
+
+void QtTreePropertyBrowserPrivate::editItem(QtBrowserItem *browserItem)
+{
+    if (QTreeWidgetItem *treeItem = m_indexToItem.value(browserItem, 0)) {
+        m_treeWidget->setCurrentItem (treeItem, 1);
+        m_treeWidget->editItem(treeItem, 1);
+    }
+}
+
+/**
+    \class QtTreePropertyBrowser
+
+    \brief The QtTreePropertyBrowser class provides QTreeWidget based
+    property browser.
+
+    A property browser is a widget that enables the user to edit a
+    given set of properties. Each property is represented by a label
+    specifying the property's name, and an editing widget (e.g. a line
+    edit or a combobox) holding its value. A property can have zero or
+    more subproperties.
+
+    QtTreePropertyBrowser provides a tree based view for all nested
+    properties, i.e. properties that have subproperties can be in an
+    expanded (subproperties are visible) or collapsed (subproperties
+    are hidden) state. For example:
+
+    \image qttreepropertybrowser.png
+
+    Use the QtAbstractPropertyBrowser API to add, insert and remove
+    properties from an instance of the QtTreePropertyBrowser class.
+    The properties themselves are created and managed by
+    implementations of the QtAbstractPropertyManager class.
+
+    \sa QtGroupBoxPropertyBrowser, QtAbstractPropertyBrowser
+*/
+
+/**
+    \fn void QtTreePropertyBrowser::collapsed(QtBrowserItem *item)
+
+    This signal is emitted when the \a item is collapsed.
+
+    \sa expanded(), setExpanded()
+*/
+
+/**
+    \fn void QtTreePropertyBrowser::expanded(QtBrowserItem *item)
+
+    This signal is emitted when the \a item is expanded.
+
+    \sa collapsed(), setExpanded()
+*/
+
+/**
+    Creates a property browser with the given \a parent.
+*/
+QtTreePropertyBrowser::QtTreePropertyBrowser(QWidget *parent)
+    : QtAbstractPropertyBrowser(parent)
+{
+    d_ptr = new QtTreePropertyBrowserPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->init(this);
+    connect(this, SIGNAL(currentItemChanged(QtBrowserItem*)), this, SLOT(slotCurrentBrowserItemChanged(QtBrowserItem*)));
+}
+
+/**
+    Destroys this property browser.
+
+    Note that the properties that were inserted into this browser are
+    \e not destroyed since they may still be used in other
+    browsers. The properties are owned by the manager that created
+    them.
+
+    \sa QtProperty, QtAbstractPropertyManager
+*/
+QtTreePropertyBrowser::~QtTreePropertyBrowser()
+{
+    delete d_ptr;
+}
+
+/**
+    \property QtTreePropertyBrowser::indentation
+    \brief indentation of the items in the tree view.
+*/
+int QtTreePropertyBrowser::indentation() const
+{
+    return d_ptr->m_treeWidget->indentation();
+}
+
+void QtTreePropertyBrowser::setIndentation(int i)
+{
+    d_ptr->m_treeWidget->setIndentation(i);
+}
+
+/**
+  \property QtTreePropertyBrowser::rootIsDecorated
+  \brief whether to show controls for expanding and collapsing root items.
+*/
+bool QtTreePropertyBrowser::rootIsDecorated() const
+{
+    return d_ptr->m_treeWidget->rootIsDecorated();
+}
+
+void QtTreePropertyBrowser::setRootIsDecorated(bool show)
+{
+    d_ptr->m_treeWidget->setRootIsDecorated(show);
+    QMapIterator<QTreeWidgetItem *, QtBrowserItem *> it(d_ptr->m_itemToIndex);
+    while (it.hasNext()) {
+        QtProperty *property = it.next().value()->property();
+        if (!property->hasValue())
+            d_ptr->updateItem(it.key());
+    }
+}
+
+/**
+  \property QtTreePropertyBrowser::alternatingRowColors
+  \brief whether to draw the background using alternating colors.
+  By default this property is set to true.
+*/
+bool QtTreePropertyBrowser::alternatingRowColors() const
+{
+    return d_ptr->m_treeWidget->alternatingRowColors();
+}
+
+void QtTreePropertyBrowser::setAlternatingRowColors(bool enable)
+{
+    d_ptr->m_treeWidget->setAlternatingRowColors(enable);
+    QMapIterator<QTreeWidgetItem *, QtBrowserItem *> it(d_ptr->m_itemToIndex);
+}
+
+/**
+  \property QtTreePropertyBrowser::headerVisible
+  \brief whether to show the header.
+*/
+bool QtTreePropertyBrowser::isHeaderVisible() const
+{
+    return d_ptr->m_headerVisible;
+}
+
+void QtTreePropertyBrowser::setHeaderVisible(bool visible)
+{
+    if (d_ptr->m_headerVisible == visible)
+        return;
+
+    d_ptr->m_headerVisible = visible;
+    d_ptr->m_treeWidget->header()->setVisible(visible);
+}
+
+/**
+  \enum QtTreePropertyBrowser::ResizeMode
+
+  The resize mode specifies the behavior of the header sections.
+
+  \value Interactive The user can resize the sections.
+  The sections can also be resized programmatically using setSplitterPosition().
+
+  \value Fixed The user cannot resize the section.
+  The section can only be resized programmatically using setSplitterPosition().
+
+  \value Stretch QHeaderView will automatically resize the section to fill the available space.
+  The size cannot be changed by the user or programmatically.
+
+  \value ResizeToContents QHeaderView will automatically resize the section to its optimal
+  size based on the contents of the entire column.
+  The size cannot be changed by the user or programmatically.
+
+  \sa setResizeMode()
+*/
+
+/**
+    \property QtTreePropertyBrowser::resizeMode
+    \brief the resize mode of setions in the header.
+*/
+
+QtTreePropertyBrowser::ResizeMode QtTreePropertyBrowser::resizeMode() const
+{
+    return d_ptr->m_resizeMode;
+}
+
+void QtTreePropertyBrowser::setResizeMode(QtTreePropertyBrowser::ResizeMode mode)
+{
+    if (d_ptr->m_resizeMode == mode)
+        return;
+
+    d_ptr->m_resizeMode = mode;
+    QHeaderView::ResizeMode m = QHeaderView::Stretch;
+    switch (mode) {
+        case QtTreePropertyBrowser::Interactive:      m = QHeaderView::Interactive;      break;
+        case QtTreePropertyBrowser::Fixed:            m = QHeaderView::Fixed;            break;
+        case QtTreePropertyBrowser::ResizeToContents: m = QHeaderView::ResizeToContents; break;
+        case QtTreePropertyBrowser::Stretch:
+        default:                                      m = QHeaderView::Stretch;          break;
+    }
+    d_ptr->m_treeWidget->header()->setResizeMode(m);
+}
+
+/**
+    \property QtTreePropertyBrowser::splitterPosition
+    \brief the position of the splitter between the colunms.
+*/
+
+int QtTreePropertyBrowser::splitterPosition() const
+{
+    return d_ptr->m_treeWidget->header()->sectionSize(0);
+}
+
+void QtTreePropertyBrowser::setSplitterPosition(int position)
+{
+    d_ptr->m_treeWidget->header()->resizeSection(0, position);
+}
+
+/**
+    Sets the \a item to either collapse or expanded, depending on the value of \a expanded.
+
+    \sa isExpanded(), expanded(), collapsed()
+*/
+
+void QtTreePropertyBrowser::setExpanded(QtBrowserItem *item, bool expanded)
+{
+    QTreeWidgetItem *treeItem = d_ptr->m_indexToItem.value(item);
+    if (treeItem)
+        treeItem->setExpanded(expanded);
+}
+
+/**
+    Returns true if the \a item is expanded; otherwise returns false.
+
+    \sa setExpanded()
+*/
+
+bool QtTreePropertyBrowser::isExpanded(QtBrowserItem *item) const
+{
+    QTreeWidgetItem *treeItem = d_ptr->m_indexToItem.value(item);
+    if (treeItem)
+        return treeItem->isExpanded();
+    return false;
+}
+
+/**
+    Returns true if the \a item is visible; otherwise returns false.
+
+    \sa setItemVisible()
+    \since 4.5
+*/
+
+bool QtTreePropertyBrowser::isItemVisible(QtBrowserItem *item) const
+{
+    if (const QTreeWidgetItem *treeItem = d_ptr->m_indexToItem.value(item))
+        return !treeItem->isHidden();
+    return false;
+}
+
+/**
+    Sets the \a item to be visible, depending on the value of \a visible.
+
+   \sa isItemVisible()
+   \since 4.5
+*/
+
+void QtTreePropertyBrowser::setItemVisible(QtBrowserItem *item, bool visible)
+{
+    if (QTreeWidgetItem *treeItem = d_ptr->m_indexToItem.value(item))
+        treeItem->setHidden(!visible);
+}
+
+/**
+    Sets the \a item's background color to \a color. Note that while item's background
+    is rendered every second row is being drawn with alternate color (which is a bit lighter than items \a color)
+
+    \sa backgroundColor(), calculatedBackgroundColor()
+*/
+
+void QtTreePropertyBrowser::setBackgroundColor(QtBrowserItem *item, const QColor &color)
+{
+    if (!d_ptr->m_indexToItem.contains(item))
+        return;
+    if (color.isValid())
+        d_ptr->m_indexToBackgroundColor[item] = color;
+    else
+        d_ptr->m_indexToBackgroundColor.remove(item);
+    d_ptr->m_treeWidget->viewport()->update();
+}
+
+/**
+    Returns the \a item's color. If there is no color set for item it returns invalid color.
+
+    \sa calculatedBackgroundColor(), setBackgroundColor()
+*/
+
+QColor QtTreePropertyBrowser::backgroundColor(QtBrowserItem *item) const
+{
+    return d_ptr->m_indexToBackgroundColor.value(item);
+}
+
+/**
+    Returns the \a item's color. If there is no color set for item it returns parent \a item's
+    color (if there is no color set for parent it returns grandparent's color and so on). In case
+    the color is not set for \a item and it's top level item it returns invalid color.
+
+    \sa backgroundColor(), setBackgroundColor()
+*/
+
+QColor QtTreePropertyBrowser::calculatedBackgroundColor(QtBrowserItem *item) const
+{
+    return d_ptr->calculatedBackgroundColor(item);
+}
+
+/**
+    \property QtTreePropertyBrowser::propertiesWithoutValueMarked
+    \brief whether to enable or disable marking properties without value.
+
+    When marking is enabled the item's background is rendered in dark color and item's
+    foreground is rendered with light color.
+
+    \sa propertiesWithoutValueMarked()
+*/
+void QtTreePropertyBrowser::setPropertiesWithoutValueMarked(bool mark)
+{
+    if (d_ptr->m_markPropertiesWithoutValue == mark)
+        return;
+
+    d_ptr->m_markPropertiesWithoutValue = mark;
+    QMapIterator<QTreeWidgetItem *, QtBrowserItem *> it(d_ptr->m_itemToIndex);
+    while (it.hasNext()) {
+        QtProperty *property = it.next().value()->property();
+        if (!property->hasValue())
+            d_ptr->updateItem(it.key());
+    }
+    d_ptr->m_treeWidget->viewport()->update();
+}
+
+bool QtTreePropertyBrowser::propertiesWithoutValueMarked() const
+{
+    return d_ptr->m_markPropertiesWithoutValue;
+}
+
+/**
+    \reimp
+*/
+void QtTreePropertyBrowser::itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem)
+{
+    d_ptr->propertyInserted(item, afterItem);
+}
+
+/**
+    \reimp
+*/
+void QtTreePropertyBrowser::itemRemoved(QtBrowserItem *item)
+{
+    d_ptr->propertyRemoved(item);
+}
+
+/**
+    \reimp
+*/
+void QtTreePropertyBrowser::itemChanged(QtBrowserItem *item)
+{
+    d_ptr->propertyChanged(item);
+}
+
+/**
+    Sets the current item to \a item and opens the relevant editor for it.
+*/
+void QtTreePropertyBrowser::editItem(QtBrowserItem *item)
+{
+    d_ptr->editItem(item);
+}
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#include "moc_qttreepropertybrowser.cpp"
+#include "qttreepropertybrowser.moc"
diff --git a/Code/Mantid/QtPropertyBrowser/src/qttreepropertybrowser.h b/Code/Mantid/QtPropertyBrowser/src/qttreepropertybrowser.h
index 47d233a6aebc35bfc2554bf50d40dee22c2b16e7..f664609d79e3ca4a25ae844b06708f6ef50da2d7 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qttreepropertybrowser.h
+++ b/Code/Mantid/QtPropertyBrowser/src/qttreepropertybrowser.h
@@ -1,184 +1,184 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QTTREEPROPERTYBROWSER_H
-#define QTTREEPROPERTYBROWSER_H
-
-#include "qtpropertybrowser.h"
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-class QTreeWidgetItem;
-class QtTreePropertyBrowserPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtTreePropertyBrowser : public QtAbstractPropertyBrowser
-{
-    Q_OBJECT
-    Q_ENUMS(ResizeMode)
-    Q_PROPERTY(int indentation READ indentation WRITE setIndentation)
-    Q_PROPERTY(bool rootIsDecorated READ rootIsDecorated WRITE setRootIsDecorated)
-    Q_PROPERTY(bool alternatingRowColors READ alternatingRowColors WRITE setAlternatingRowColors)
-    Q_PROPERTY(bool headerVisible READ isHeaderVisible WRITE setHeaderVisible)
-    Q_PROPERTY(ResizeMode resizeMode READ resizeMode WRITE setResizeMode)
-    Q_PROPERTY(int splitterPosition READ splitterPosition WRITE setSplitterPosition)
-    Q_PROPERTY(bool propertiesWithoutValueMarked READ propertiesWithoutValueMarked WRITE setPropertiesWithoutValueMarked)
-public:
-
-    enum ResizeMode
-    {
-        Interactive,
-        Stretch,
-        Fixed,
-        ResizeToContents
-    };
-
-    QtTreePropertyBrowser(QWidget *parent = 0);
-    ~QtTreePropertyBrowser();
-
-    int indentation() const;
-    void setIndentation(int i);
-
-    bool rootIsDecorated() const;
-    void setRootIsDecorated(bool show);
-
-    bool alternatingRowColors() const;
-    void setAlternatingRowColors(bool enable);
-
-    bool isHeaderVisible() const;
-    void setHeaderVisible(bool visible);
-
-    ResizeMode resizeMode() const;
-    void setResizeMode(ResizeMode mode);
-
-    int splitterPosition() const;
-    void setSplitterPosition(int position);
-
-    void setExpanded(QtBrowserItem *item, bool expanded);
-    bool isExpanded(QtBrowserItem *item) const;
-
-    bool isItemVisible(QtBrowserItem *item) const;
-    void setItemVisible(QtBrowserItem *item, bool visible);
-
-    void setBackgroundColor(QtBrowserItem *item, const QColor &color);
-    QColor backgroundColor(QtBrowserItem *item) const;
-    QColor calculatedBackgroundColor(QtBrowserItem *item) const;
-
-    void setPropertiesWithoutValueMarked(bool mark);
-    bool propertiesWithoutValueMarked() const;
-
-    void editItem(QtBrowserItem *item);
-
-Q_SIGNALS:
-
-    void collapsed(QtBrowserItem *item);
-    void expanded(QtBrowserItem *item);
-
-protected:
-    virtual void itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem);
-    virtual void itemRemoved(QtBrowserItem *item);
-    virtual void itemChanged(QtBrowserItem *item);
-
-private:
-
-    QtTreePropertyBrowserPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtTreePropertyBrowser)
-    Q_DISABLE_COPY(QtTreePropertyBrowser)
-
-    Q_PRIVATE_SLOT(d_func(), void slotCollapsed(const QModelIndex &))
-    Q_PRIVATE_SLOT(d_func(), void slotExpanded(const QModelIndex &))
-    Q_PRIVATE_SLOT(d_func(), void slotCurrentBrowserItemChanged(QtBrowserItem *))
-    Q_PRIVATE_SLOT(d_func(), void slotCurrentTreeItemChanged(QTreeWidgetItem *, QTreeWidgetItem *))
-
-};
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#endif
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QTTREEPROPERTYBROWSER_H
+#define QTTREEPROPERTYBROWSER_H
+
+#include "qtpropertybrowser.h"
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+class QTreeWidgetItem;
+class QtTreePropertyBrowserPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtTreePropertyBrowser : public QtAbstractPropertyBrowser
+{
+    Q_OBJECT
+    Q_ENUMS(ResizeMode)
+    Q_PROPERTY(int indentation READ indentation WRITE setIndentation)
+    Q_PROPERTY(bool rootIsDecorated READ rootIsDecorated WRITE setRootIsDecorated)
+    Q_PROPERTY(bool alternatingRowColors READ alternatingRowColors WRITE setAlternatingRowColors)
+    Q_PROPERTY(bool headerVisible READ isHeaderVisible WRITE setHeaderVisible)
+    Q_PROPERTY(ResizeMode resizeMode READ resizeMode WRITE setResizeMode)
+    Q_PROPERTY(int splitterPosition READ splitterPosition WRITE setSplitterPosition)
+    Q_PROPERTY(bool propertiesWithoutValueMarked READ propertiesWithoutValueMarked WRITE setPropertiesWithoutValueMarked)
+public:
+
+    enum ResizeMode
+    {
+        Interactive,
+        Stretch,
+        Fixed,
+        ResizeToContents
+    };
+
+    QtTreePropertyBrowser(QWidget *parent = 0);
+    ~QtTreePropertyBrowser();
+
+    int indentation() const;
+    void setIndentation(int i);
+
+    bool rootIsDecorated() const;
+    void setRootIsDecorated(bool show);
+
+    bool alternatingRowColors() const;
+    void setAlternatingRowColors(bool enable);
+
+    bool isHeaderVisible() const;
+    void setHeaderVisible(bool visible);
+
+    ResizeMode resizeMode() const;
+    void setResizeMode(ResizeMode mode);
+
+    int splitterPosition() const;
+    void setSplitterPosition(int position);
+
+    void setExpanded(QtBrowserItem *item, bool expanded);
+    bool isExpanded(QtBrowserItem *item) const;
+
+    bool isItemVisible(QtBrowserItem *item) const;
+    void setItemVisible(QtBrowserItem *item, bool visible);
+
+    void setBackgroundColor(QtBrowserItem *item, const QColor &color);
+    QColor backgroundColor(QtBrowserItem *item) const;
+    QColor calculatedBackgroundColor(QtBrowserItem *item) const;
+
+    void setPropertiesWithoutValueMarked(bool mark);
+    bool propertiesWithoutValueMarked() const;
+
+    void editItem(QtBrowserItem *item);
+
+Q_SIGNALS:
+
+    void collapsed(QtBrowserItem *item);
+    void expanded(QtBrowserItem *item);
+
+protected:
+    virtual void itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem);
+    virtual void itemRemoved(QtBrowserItem *item);
+    virtual void itemChanged(QtBrowserItem *item);
+
+private:
+
+    QtTreePropertyBrowserPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtTreePropertyBrowser)
+    Q_DISABLE_COPY(QtTreePropertyBrowser)
+
+    Q_PRIVATE_SLOT(d_func(), void slotCollapsed(const QModelIndex &))
+    Q_PRIVATE_SLOT(d_func(), void slotExpanded(const QModelIndex &))
+    Q_PRIVATE_SLOT(d_func(), void slotCurrentBrowserItemChanged(QtBrowserItem *))
+    Q_PRIVATE_SLOT(d_func(), void slotCurrentTreeItemChanged(QTreeWidgetItem *, QTreeWidgetItem *))
+
+};
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#endif
diff --git a/Code/Mantid/QtPropertyBrowser/src/qtvariantproperty.cpp b/Code/Mantid/QtPropertyBrowser/src/qtvariantproperty.cpp
index aa439001d46fdd2b43444fdab63165085c0d70c0..ff73d36b3f791df14152504e2945fc90ea68865d 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qtvariantproperty.cpp
+++ b/Code/Mantid/QtPropertyBrowser/src/qtvariantproperty.cpp
@@ -1,2329 +1,2329 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qtvariantproperty.h"
-#include "qtpropertymanager.h"
-#include "qteditorfactory.h"
-#include <QtCore/QVariant>
-#include <QtGui/QIcon>
-#include <QtCore/QDate>
-#include <QtCore/QLocale>
-
-#if defined(Q_CC_MSVC)
-#    pragma warning(disable: 4786) /* MS VS 6: truncating debug info after 255 characters */
-#endif
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-class QtEnumPropertyType
-{
-};
-
-
-class QtFlagPropertyType
-{
-};
-
-
-class QtGroupPropertyType
-{
-};
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-Q_DECLARE_METATYPE(QtEnumPropertyType)
-Q_DECLARE_METATYPE(QtFlagPropertyType)
-Q_DECLARE_METATYPE(QtGroupPropertyType)
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-/**
-    Returns the type id for an enum property.
-
-    Note that the property's value type can be retrieved using the
-    valueType() function (which is QVariant::Int for the enum property
-    type).
-
-    \sa propertyType(), valueType()
-*/
-int QtVariantPropertyManager::enumTypeId()
-{
-    return qMetaTypeId<QtEnumPropertyType>();
-}
-
-/**
-    Returns the type id for a flag property.
-
-    Note that the property's value type can be retrieved using the
-    valueType() function (which is QVariant::Int for the flag property
-    type).
-
-    \sa propertyType(), valueType()
-*/
-int QtVariantPropertyManager::flagTypeId()
-{
-    return qMetaTypeId<QtFlagPropertyType>();
-}
-
-/**
-    Returns the type id for a group property.
-
-    Note that the property's value type can be retrieved using the
-    valueType() function (which is QVariant::Invalid for the group
-    property type, since it doesn't provide any value).
-
-    \sa propertyType(), valueType()
-*/
-int QtVariantPropertyManager::groupTypeId()
-{
-    return qMetaTypeId<QtGroupPropertyType>();
-}
-
-/**
-    Returns the type id for a icon map attribute.
-
-    Note that the property's attribute type can be retrieved using the
-    attributeType() function.
-
-    \sa attributeType(), QtEnumPropertyManager::enumIcons()
-*/
-int QtVariantPropertyManager::iconMapTypeId()
-{
-    return qMetaTypeId<QtIconMap>();
-}
-
-typedef QMap<const QtProperty *, QtProperty *> PropertyMap;
-Q_GLOBAL_STATIC(PropertyMap, propertyToWrappedProperty)
-
-static QtProperty *wrappedProperty(QtProperty *property)
-{
-    return propertyToWrappedProperty()->value(property, 0);
-}
-
-class QtVariantPropertyPrivate
-{
-    QtVariantProperty *q_ptr;
-public:
-    QtVariantPropertyPrivate(QtVariantPropertyManager *m) : manager(m) {}
-
-    QtVariantPropertyManager *manager;
-};
-
-/**
-    \class QtVariantProperty
-
-    \brief The QtVariantProperty class is a convenience class handling
-    QVariant based properties.
-
-    QtVariantProperty provides additional API: A property's type,
-    value type, attribute values and current value can easily be
-    retrieved using the propertyType(), valueType(), attributeValue()
-    and value() functions respectively. In addition, the attribute
-    values and the current value can be set using the corresponding
-    setValue() and setAttribute() functions.
-
-    For example, instead of writing:
-
-    \code
-        QtVariantPropertyManager *variantPropertyManager;
-        QtProperty *property;
-
-        variantPropertyManager->setValue(property, 10);
-    \endcode
-
-    you can write:
-
-    \code
-        QtVariantPropertyManager *variantPropertyManager;
-        QtVariantProperty *property;
-
-        property->setValue(10);
-    \endcode
-
-    QtVariantProperty instances can only be created by the
-    QtVariantPropertyManager class.
-
-    \sa QtProperty, QtVariantPropertyManager, QtVariantEditorFactory
-*/
-
-/**
-    Creates a variant property using the given \a manager.
-
-    Do not use this constructor to create variant property instances;
-    use the QtVariantPropertyManager::addProperty() function
-    instead.  This constructor is used internally by the
-    QtVariantPropertyManager::createProperty() function.
-
-    \sa QtVariantPropertyManager
-*/
-QtVariantProperty::QtVariantProperty(QtVariantPropertyManager *manager)
-    : QtProperty(manager),  d_ptr(new QtVariantPropertyPrivate(manager))
-{
-
-}
-
-/**
-    Destroys this property.
-
-    \sa QtProperty::~QtProperty()
-*/
-QtVariantProperty::~QtVariantProperty()
-{
-    delete d_ptr;
-}
-
-/**
-    Returns the property's current value.
-
-    \sa valueType(), setValue()
-*/
-QVariant QtVariantProperty::value() const
-{
-    return d_ptr->manager->value(this);
-}
-
-/**
-    Returns this property's value for the specified \a attribute.
-
-    QtVariantPropertyManager provides a couple of related functions:
-    \l{QtVariantPropertyManager::attributes()}{attributes()} and
-    \l{QtVariantPropertyManager::attributeType()}{attributeType()}.
-
-    \sa setAttribute()
-*/
-QVariant QtVariantProperty::attributeValue(const QString &attribute) const
-{
-    return d_ptr->manager->attributeValue(this, attribute);
-}
-
-/**
-    Returns the type of this property's value.
-
-    \sa propertyType()
-*/
-int QtVariantProperty::valueType() const
-{
-    return d_ptr->manager->valueType(this);
-}
-
-/**
-    Returns this property's type.
-
-    QtVariantPropertyManager provides several related functions:
-    \l{QtVariantPropertyManager::enumTypeId()}{enumTypeId()},
-    \l{QtVariantPropertyManager::flagTypeId()}{flagTypeId()} and
-    \l{QtVariantPropertyManager::groupTypeId()}{groupTypeId()}.
-
-    \sa valueType()
-*/
-int QtVariantProperty::propertyType() const
-{
-    return d_ptr->manager->propertyType(this);
-}
-
-/**
-    Sets the value of this property to \a value.
-
-    The specified \a value must be of the type returned by
-    valueType(), or of a type that can be converted to valueType()
-    using the QVariant::canConvert() function; otherwise this function
-    does nothing.
-
-    \sa value()
-*/
-void QtVariantProperty::setValue(const QVariant &value)
-{
-    d_ptr->manager->setValue(this, value);
-}
-
-/**
-    Sets the \a attribute of property to \a value.
-
-    QtVariantPropertyManager provides the related
-    \l{QtVariantPropertyManager::setAttribute()}{setAttribute()}
-    function.
-
-    \sa attributeValue()
-*/
-void QtVariantProperty::setAttribute(const QString &attribute, const QVariant &value)
-{
-    d_ptr->manager->setAttribute(this, attribute, value);
-}
-
-class QtVariantPropertyManagerPrivate
-{
-    QtVariantPropertyManager *q_ptr;
-    Q_DECLARE_PUBLIC(QtVariantPropertyManager)
-public:
-    QtVariantPropertyManagerPrivate();
-
-    bool m_creatingProperty;
-    bool m_creatingSubProperties;
-    bool m_destroyingSubProperties;
-    int m_propertyType;
-
-    void slotValueChanged(QtProperty *property, int val);
-    void slotRangeChanged(QtProperty *property, int min, int max);
-    void slotSingleStepChanged(QtProperty *property, int step);
-    void slotValueChanged(QtProperty *property, double val);
-    void slotRangeChanged(QtProperty *property, double min, double max);
-    void slotSingleStepChanged(QtProperty *property, double step);
-    void slotDecimalsChanged(QtProperty *property, int prec);
-    void slotValueChanged(QtProperty *property, bool val);
-    void slotValueChanged(QtProperty *property, const QString &val);
-    void slotRegExpChanged(QtProperty *property, const QRegExp &regExp);
-    void slotValueChanged(QtProperty *property, const QDate &val);
-    void slotRangeChanged(QtProperty *property, const QDate &min, const QDate &max);
-    void slotValueChanged(QtProperty *property, const QTime &val);
-    void slotValueChanged(QtProperty *property, const QDateTime &val);
-    void slotValueChanged(QtProperty *property, const QKeySequence &val);
-    void slotValueChanged(QtProperty *property, const QChar &val);
-    void slotValueChanged(QtProperty *property, const QLocale &val);
-    void slotValueChanged(QtProperty *property, const QPoint &val);
-    void slotValueChanged(QtProperty *property, const QPointF &val);
-    void slotValueChanged(QtProperty *property, const QSize &val);
-    void slotRangeChanged(QtProperty *property, const QSize &min, const QSize &max);
-    void slotValueChanged(QtProperty *property, const QSizeF &val);
-    void slotRangeChanged(QtProperty *property, const QSizeF &min, const QSizeF &max);
-    void slotValueChanged(QtProperty *property, const QRect &val);
-    void slotConstraintChanged(QtProperty *property, const QRect &val);
-    void slotValueChanged(QtProperty *property, const QRectF &val);
-    void slotConstraintChanged(QtProperty *property, const QRectF &val);
-    void slotValueChanged(QtProperty *property, const QColor &val);
-    void slotEnumChanged(QtProperty *property, int val);
-    void slotEnumNamesChanged(QtProperty *property, const QStringList &enumNames);
-    void slotEnumIconsChanged(QtProperty *property, const QMap<int, QIcon> &enumIcons);
-    void slotValueChanged(QtProperty *property, const QSizePolicy &val);
-    void slotValueChanged(QtProperty *property, const QFont &val);
-    void slotValueChanged(QtProperty *property, const QCursor &val);
-    void slotFlagChanged(QtProperty *property, int val);
-    void slotFlagNamesChanged(QtProperty *property, const QStringList &flagNames);
-    void slotPropertyInserted(QtProperty *property, QtProperty *parent, QtProperty *after);
-    void slotPropertyRemoved(QtProperty *property, QtProperty *parent);
-
-    void valueChanged(QtProperty *property, const QVariant &val);
-
-    int internalPropertyToType(QtProperty *property) const;
-    QtVariantProperty *createSubProperty(QtVariantProperty *parent, QtVariantProperty *after,
-            QtProperty *internal);
-    void removeSubProperty(QtVariantProperty *property);
-
-    QMap<int, QtAbstractPropertyManager *> m_typeToPropertyManager;
-    QMap<int, QMap<QString, int> > m_typeToAttributeToAttributeType;
-
-    QMap<const QtProperty *, QPair<QtVariantProperty *, int> > m_propertyToType;
-
-    QMap<int, int> m_typeToValueType;
-
-
-    QMap<QtProperty *, QtVariantProperty *> m_internalToProperty;
-
-    const QString m_constraintAttribute;
-    const QString m_singleStepAttribute;
-    const QString m_decimalsAttribute;
-    const QString m_enumIconsAttribute;
-    const QString m_enumNamesAttribute;
-    const QString m_flagNamesAttribute;
-    const QString m_maximumAttribute;
-    const QString m_minimumAttribute;
-    const QString m_regExpAttribute;
-};
-
-QtVariantPropertyManagerPrivate::QtVariantPropertyManagerPrivate() :
-    m_constraintAttribute(QLatin1String("constraint")),
-    m_singleStepAttribute(QLatin1String("singleStep")),
-    m_decimalsAttribute(QLatin1String("decimals")),
-    m_enumIconsAttribute(QLatin1String("enumIcons")),
-    m_enumNamesAttribute(QLatin1String("enumNames")),
-    m_flagNamesAttribute(QLatin1String("flagNames")),
-    m_maximumAttribute(QLatin1String("maximum")),
-    m_minimumAttribute(QLatin1String("minimum")),
-    m_regExpAttribute(QLatin1String("regExp"))
-{
-}
-
-int QtVariantPropertyManagerPrivate::internalPropertyToType(QtProperty *property) const
-{
-    int type = 0;
-    QtAbstractPropertyManager *internPropertyManager = property->propertyManager();
-    if (qobject_cast<QtIntPropertyManager *>(internPropertyManager))
-        type = QVariant::Int;
-    else if (qobject_cast<QtEnumPropertyManager *>(internPropertyManager))
-        type = QtVariantPropertyManager::enumTypeId();
-    else if (qobject_cast<QtBoolPropertyManager *>(internPropertyManager))
-        type = QVariant::Bool;
-    else if (qobject_cast<QtDoublePropertyManager *>(internPropertyManager))
-        type = QVariant::Double;
-    return type;
-}
-
-QtVariantProperty *QtVariantPropertyManagerPrivate::createSubProperty(QtVariantProperty *parent,
-            QtVariantProperty *after, QtProperty *internal)
-{
-    int type = internalPropertyToType(internal);
-    if (!type)
-        return 0;
-
-    bool wasCreatingSubProperties = m_creatingSubProperties;
-    m_creatingSubProperties = true;
-
-    QtVariantProperty *varChild = q_ptr->addProperty(type, internal->propertyName());
-
-    m_creatingSubProperties = wasCreatingSubProperties;
-
-    varChild->setPropertyName(internal->propertyName());
-    varChild->setToolTip(internal->toolTip());
-    varChild->setStatusTip(internal->statusTip());
-    varChild->setWhatsThis(internal->whatsThis());
-
-    parent->insertSubProperty(varChild, after);
-
-    m_internalToProperty[internal] = varChild;
-    propertyToWrappedProperty()->insert(varChild, internal);
-    return varChild;
-}
-
-void QtVariantPropertyManagerPrivate::removeSubProperty(QtVariantProperty *property)
-{
-    QtProperty *internChild = wrappedProperty(property);
-    bool wasDestroyingSubProperties = m_destroyingSubProperties;
-    m_destroyingSubProperties = true;
-    delete property;
-    m_destroyingSubProperties = wasDestroyingSubProperties;
-    m_internalToProperty.remove(internChild);
-    propertyToWrappedProperty()->remove(property);
-}
-
-void QtVariantPropertyManagerPrivate::slotPropertyInserted(QtProperty *property,
-            QtProperty *parent, QtProperty *after)
-{
-    if (m_creatingProperty)
-        return;
-
-    QtVariantProperty *varParent = m_internalToProperty.value(parent, 0);
-    if (!varParent)
-        return;
-
-    QtVariantProperty *varAfter = 0;
-    if (after) {
-        varAfter = m_internalToProperty.value(after, 0);
-        if (!varAfter)
-            return;
-    }
-
-    createSubProperty(varParent, varAfter, property);
-}
-
-void QtVariantPropertyManagerPrivate::slotPropertyRemoved(QtProperty *property, QtProperty *parent)
-{
-    Q_UNUSED(parent)
-
-    QtVariantProperty *varProperty = m_internalToProperty.value(property, 0);
-    if (!varProperty)
-        return;
-
-    removeSubProperty(varProperty);
-}
-
-void QtVariantPropertyManagerPrivate::valueChanged(QtProperty *property, const QVariant &val)
-{
-    QtVariantProperty *varProp = m_internalToProperty.value(property, 0);
-    if (!varProp)
-        return;
-    emit q_ptr->valueChanged(varProp, val);
-    emit q_ptr->propertyChanged(varProp);
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, int val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotRangeChanged(QtProperty *property, int min, int max)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0)) {
-        emit q_ptr->attributeChanged(varProp, m_minimumAttribute, QVariant(min));
-        emit q_ptr->attributeChanged(varProp, m_maximumAttribute, QVariant(max));
-    }
-}
-
-void QtVariantPropertyManagerPrivate::slotSingleStepChanged(QtProperty *property, int step)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
-        emit q_ptr->attributeChanged(varProp, m_singleStepAttribute, QVariant(step));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, double val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotRangeChanged(QtProperty *property, double min, double max)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0)) {
-        emit q_ptr->attributeChanged(varProp, m_minimumAttribute, QVariant(min));
-        emit q_ptr->attributeChanged(varProp, m_maximumAttribute, QVariant(max));
-    }
-}
-
-void QtVariantPropertyManagerPrivate::slotSingleStepChanged(QtProperty *property, double step)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
-        emit q_ptr->attributeChanged(varProp, m_singleStepAttribute, QVariant(step));
-}
-
-void QtVariantPropertyManagerPrivate::slotDecimalsChanged(QtProperty *property, int prec)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
-        emit q_ptr->attributeChanged(varProp, m_decimalsAttribute, QVariant(prec));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, bool val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QString &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotRegExpChanged(QtProperty *property, const QRegExp &regExp)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
-        emit q_ptr->attributeChanged(varProp, m_regExpAttribute, QVariant(regExp));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QDate &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotRangeChanged(QtProperty *property, const QDate &min, const QDate &max)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0)) {
-        emit q_ptr->attributeChanged(varProp, m_minimumAttribute, QVariant(min));
-        emit q_ptr->attributeChanged(varProp, m_maximumAttribute, QVariant(max));
-    }
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QTime &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QDateTime &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QKeySequence &val)
-{
-    QVariant v;
-    qVariantSetValue(v, val);
-    valueChanged(property, v);
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QChar &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QLocale &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QPoint &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QPointF &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QSize &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotRangeChanged(QtProperty *property, const QSize &min, const QSize &max)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0)) {
-        emit q_ptr->attributeChanged(varProp, m_minimumAttribute, QVariant(min));
-        emit q_ptr->attributeChanged(varProp, m_maximumAttribute, QVariant(max));
-    }
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QSizeF &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotRangeChanged(QtProperty *property, const QSizeF &min, const QSizeF &max)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0)) {
-        emit q_ptr->attributeChanged(varProp, m_minimumAttribute, QVariant(min));
-        emit q_ptr->attributeChanged(varProp, m_maximumAttribute, QVariant(max));
-    }
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QRect &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotConstraintChanged(QtProperty *property, const QRect &constraint)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
-        emit q_ptr->attributeChanged(varProp, m_constraintAttribute, QVariant(constraint));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QRectF &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotConstraintChanged(QtProperty *property, const QRectF &constraint)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
-        emit q_ptr->attributeChanged(varProp, m_constraintAttribute, QVariant(constraint));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QColor &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotEnumNamesChanged(QtProperty *property, const QStringList &enumNames)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
-        emit q_ptr->attributeChanged(varProp, m_enumNamesAttribute, QVariant(enumNames));
-}
-
-void QtVariantPropertyManagerPrivate::slotEnumIconsChanged(QtProperty *property, const QMap<int, QIcon> &enumIcons)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0)) {
-        QVariant v;
-        qVariantSetValue(v, enumIcons);
-        emit q_ptr->attributeChanged(varProp, m_enumIconsAttribute, v);
-    }
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QSizePolicy &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QFont &val)
-{
-    valueChanged(property, QVariant(val));
-}
-
-void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QCursor &val)
-{
-#ifndef QT_NO_CURSOR
-    valueChanged(property, QVariant(val));
-#endif
-}
-
-void QtVariantPropertyManagerPrivate::slotFlagNamesChanged(QtProperty *property, const QStringList &flagNames)
-{
-    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
-        emit q_ptr->attributeChanged(varProp, m_flagNamesAttribute, QVariant(flagNames));
-}
-
-/**
-    \class QtVariantPropertyManager
-
-    \brief The QtVariantPropertyManager class provides and manages QVariant based properties.
-
-    QtVariantPropertyManager provides the addProperty() function which
-    creates QtVariantProperty objects. The QtVariantProperty class is
-    a convenience class handling QVariant based properties inheriting
-    QtProperty. A QtProperty object created by a
-    QtVariantPropertyManager instance can be converted into a
-    QtVariantProperty object using the variantProperty() function.
-
-    The property's value can be retrieved using the value(), and set
-    using the setValue() slot. In addition the property's type, and
-    the type of its value, can be retrieved using the propertyType()
-    and valueType() functions respectively.
-
-    A property's type is a QVariant::Type enumerator value, and
-    usually a property's type is the same as its value type. But for
-    some properties the types differ, for example for enums, flags and
-    group types in which case QtVariantPropertyManager provides the
-    enumTypeId(), flagTypeId() and groupTypeId() functions,
-    respectively, to identify their property type (the value types are
-    QVariant::Int for the enum and flag types, and QVariant::Invalid
-    for the group type).
-
-    Use the isPropertyTypeSupported() function to check if a particular
-    property type is supported. The currently supported property types
-    are:
-
-    \table
-    \header
-        \o Property Type
-        \o Property Type Id
-    \row
-        \o int
-        \o QVariant::Int
-    \row
-        \o double
-        \o QVariant::Double
-    \row
-        \o bool
-        \o QVariant::Bool
-    \row
-        \o QString
-        \o QVariant::String
-    \row
-        \o QDate
-        \o QVariant::Date
-    \row
-        \o QTime
-        \o QVariant::Time
-    \row
-        \o QDateTime
-        \o QVariant::DateTime
-    \row
-        \o QKeySequence
-        \o QVariant::KeySequence
-    \row
-        \o QChar
-        \o QVariant::Char
-    \row
-        \o QLocale
-        \o QVariant::Locale
-    \row
-        \o QPoint
-        \o QVariant::Point
-    \row
-        \o QPointF
-        \o QVariant::PointF
-    \row
-        \o QSize
-        \o QVariant::Size
-    \row
-        \o QSizeF
-        \o QVariant::SizeF
-    \row
-        \o QRect
-        \o QVariant::Rect
-    \row
-        \o QRectF
-        \o QVariant::RectF
-    \row
-        \o QColor
-        \o QVariant::Color
-    \row
-        \o QSizePolicy
-        \o QVariant::SizePolicy
-    \row
-        \o QFont
-        \o QVariant::Font
-    \row
-        \o QCursor
-        \o QVariant::Cursor
-    \row
-        \o enum
-        \o enumTypeId()
-    \row
-        \o flag
-        \o flagTypeId()
-    \row
-        \o group
-        \o groupTypeId()
-    \endtable
-
-    Each property type can provide additional attributes,
-    e.g. QVariant::Int and QVariant::Double provides minimum and
-    maximum values. The currently supported attributes are:
-
-    \table
-    \header
-        \o Property Type
-        \o Attribute Name
-        \o Attribute Type
-    \row
-        \o \c int
-        \o minimum
-        \o QVariant::Int
-    \row
-        \o
-        \o maximum
-        \o QVariant::Int
-    \row
-        \o
-        \o singleStep
-        \o QVariant::Int
-    \row
-        \o \c double
-        \o minimum
-        \o QVariant::Double
-    \row
-        \o
-        \o maximum
-        \o QVariant::Double
-    \row
-        \o
-        \o singleStep
-        \o QVariant::Double
-    \row
-        \o
-        \o decimals
-        \o QVariant::Int
-    \row
-        \o QString
-        \o regExp
-        \o QVariant::RegExp
-    \row
-        \o QDate
-        \o minimum
-        \o QVariant::Date
-    \row
-        \o
-        \o maximum
-        \o QVariant::Date
-    \row
-        \o QPointF
-        \o decimals
-        \o QVariant::Int
-    \row
-        \o QSize
-        \o minimum
-        \o QVariant::Size
-    \row
-        \o
-        \o maximum
-        \o QVariant::Size
-    \row
-        \o QSizeF
-        \o minimum
-        \o QVariant::SizeF
-    \row
-        \o
-        \o maximum
-        \o QVariant::SizeF
-    \row
-        \o
-        \o decimals
-        \o QVariant::Int
-    \row
-        \o QRect
-        \o constraint
-        \o QVariant::Rect
-    \row
-        \o QRectF
-        \o constraint
-        \o QVariant::RectF
-    \row
-        \o
-        \o decimals
-        \o QVariant::Int
-    \row
-        \o \c enum
-        \o enumNames
-        \o QVariant::StringList
-    \row
-        \o
-        \o enumIcons
-        \o iconMapTypeId()
-    \row
-        \o \c flag
-        \o flagNames
-        \o QVariant::StringList
-    \endtable
-
-    The attributes for a given property type can be retrieved using
-    the attributes() function. Each attribute has a value type which
-    can be retrieved using the attributeType() function, and a value
-    accessible through the attributeValue() function. In addition, the
-    value can be set using the setAttribute() slot.
-
-    QtVariantManager also provides the valueChanged() signal which is
-    emitted whenever a property created by this manager change, and
-    the attributeChanged() signal which is emitted whenever an
-    attribute of such a property changes.
-
-    \sa QtVariantProperty, QtVariantEditorFactory
-*/
-
-/**
-    \fn void QtVariantPropertyManager::valueChanged(QtProperty *property, const QVariant &value)
-
-    This signal is emitted whenever a property created by this manager
-    changes its value, passing a pointer to the \a property and the
-    new \a value as parameters.
-
-    \sa setValue()
-*/
-
-/**
-    \fn void QtVariantPropertyManager::attributeChanged(QtProperty *property,
-                const QString &attribute, const QVariant &value)
-
-    This signal is emitted whenever an attribute of a property created
-    by this manager changes its value, passing a pointer to the \a
-    property, the \a attribute and the new \a value as parameters.
-
-    \sa setAttribute()
-*/
-
-/**
-    Creates a manager with the given \a parent.
-*/
-QtVariantPropertyManager::QtVariantPropertyManager(QObject *parent)
-    : QtAbstractPropertyManager(parent)
-{
-    d_ptr = new QtVariantPropertyManagerPrivate;
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_creatingProperty = false;
-    d_ptr->m_creatingSubProperties = false;
-    d_ptr->m_destroyingSubProperties = false;
-    d_ptr->m_propertyType = 0;
-
-    // IntPropertyManager
-    QtIntPropertyManager *intPropertyManager = new QtIntPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Int] = intPropertyManager;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::Int][d_ptr->m_minimumAttribute] = QVariant::Int;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::Int][d_ptr->m_maximumAttribute] = QVariant::Int;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::Int][d_ptr->m_singleStepAttribute] = QVariant::Int;
-    d_ptr->m_typeToValueType[QVariant::Int] = QVariant::Int;
-    connect(intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotValueChanged(QtProperty *, int)));
-    connect(intPropertyManager, SIGNAL(rangeChanged(QtProperty *, int, int)),
-                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
-    connect(intPropertyManager, SIGNAL(singleStepChanged(QtProperty *, int)),
-                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
-    // DoublePropertyManager
-    QtDoublePropertyManager *doublePropertyManager = new QtDoublePropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Double] = doublePropertyManager;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::Double][d_ptr->m_minimumAttribute] =
-            QVariant::Double;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::Double][d_ptr->m_maximumAttribute] =
-            QVariant::Double;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::Double][d_ptr->m_singleStepAttribute] =
-            QVariant::Double;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::Double][d_ptr->m_decimalsAttribute] =
-            QVariant::Int;
-    d_ptr->m_typeToValueType[QVariant::Double] = QVariant::Double;
-    connect(doublePropertyManager, SIGNAL(valueChanged(QtProperty *, double)),
-                this, SLOT(slotValueChanged(QtProperty *, double)));
-    connect(doublePropertyManager, SIGNAL(rangeChanged(QtProperty *, double, double)),
-                this, SLOT(slotRangeChanged(QtProperty *, double, double)));
-    connect(doublePropertyManager, SIGNAL(singleStepChanged(QtProperty *, double)),
-                this, SLOT(slotSingleStepChanged(QtProperty *, double)));
-    connect(doublePropertyManager, SIGNAL(decimalsChanged(QtProperty *, int)),
-                this, SLOT(slotDecimalsChanged(QtProperty *, int)));
-    // BoolPropertyManager
-    QtBoolPropertyManager *boolPropertyManager = new QtBoolPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Bool] = boolPropertyManager;
-    d_ptr->m_typeToValueType[QVariant::Bool] = QVariant::Bool;
-    connect(boolPropertyManager, SIGNAL(valueChanged(QtProperty *, bool)),
-                this, SLOT(slotValueChanged(QtProperty *, bool)));
-    // StringPropertyManager
-    QtStringPropertyManager *stringPropertyManager = new QtStringPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::String] = stringPropertyManager;
-    d_ptr->m_typeToValueType[QVariant::String] = QVariant::String;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::String][d_ptr->m_regExpAttribute] =
-            QVariant::RegExp;
-    connect(stringPropertyManager, SIGNAL(valueChanged(QtProperty *, const QString &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QString &)));
-    connect(stringPropertyManager, SIGNAL(regExpChanged(QtProperty *, const QRegExp &)),
-                this, SLOT(slotRegExpChanged(QtProperty *, const QRegExp &)));
-    // DatePropertyManager
-    QtDatePropertyManager *datePropertyManager = new QtDatePropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Date] = datePropertyManager;
-    d_ptr->m_typeToValueType[QVariant::Date] = QVariant::Date;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::Date][d_ptr->m_minimumAttribute] =
-            QVariant::Date;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::Date][d_ptr->m_maximumAttribute] =
-            QVariant::Date;
-    connect(datePropertyManager, SIGNAL(valueChanged(QtProperty *, const QDate &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QDate &)));
-    connect(datePropertyManager, SIGNAL(rangeChanged(QtProperty *, const QDate &, const QDate &)),
-                this, SLOT(slotRangeChanged(QtProperty *, const QDate &, const QDate &)));
-    // TimePropertyManager
-    QtTimePropertyManager *timePropertyManager = new QtTimePropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Time] = timePropertyManager;
-    d_ptr->m_typeToValueType[QVariant::Time] = QVariant::Time;
-    connect(timePropertyManager, SIGNAL(valueChanged(QtProperty *, const QTime &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QTime &)));
-    // DateTimePropertyManager
-    QtDateTimePropertyManager *dateTimePropertyManager = new QtDateTimePropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::DateTime] = dateTimePropertyManager;
-    d_ptr->m_typeToValueType[QVariant::DateTime] = QVariant::DateTime;
-    connect(dateTimePropertyManager, SIGNAL(valueChanged(QtProperty *, const QDateTime &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QDateTime &)));
-    // KeySequencePropertyManager
-    QtKeySequencePropertyManager *keySequencePropertyManager = new QtKeySequencePropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::KeySequence] = keySequencePropertyManager;
-    d_ptr->m_typeToValueType[QVariant::KeySequence] = QVariant::KeySequence;
-    connect(keySequencePropertyManager, SIGNAL(valueChanged(QtProperty *, const QKeySequence &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QKeySequence &)));
-    // CharPropertyManager
-    QtCharPropertyManager *charPropertyManager = new QtCharPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Char] = charPropertyManager;
-    d_ptr->m_typeToValueType[QVariant::Char] = QVariant::Char;
-    connect(charPropertyManager, SIGNAL(valueChanged(QtProperty *, const QChar &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QChar &)));
-    // LocalePropertyManager
-    QtLocalePropertyManager *localePropertyManager = new QtLocalePropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Locale] = localePropertyManager;
-    d_ptr->m_typeToValueType[QVariant::Locale] = QVariant::Locale;
-    connect(localePropertyManager, SIGNAL(valueChanged(QtProperty *, const QLocale &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QLocale &)));
-    connect(localePropertyManager->subEnumPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotValueChanged(QtProperty *, int)));
-    connect(localePropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
-    connect(localePropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-    // PointPropertyManager
-    QtPointPropertyManager *pointPropertyManager = new QtPointPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Point] = pointPropertyManager;
-    d_ptr->m_typeToValueType[QVariant::Point] = QVariant::Point;
-    connect(pointPropertyManager, SIGNAL(valueChanged(QtProperty *, const QPoint &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QPoint &)));
-    connect(pointPropertyManager->subIntPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotValueChanged(QtProperty *, int)));
-    connect(pointPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
-    connect(pointPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-    // PointFPropertyManager
-    QtPointFPropertyManager *pointFPropertyManager = new QtPointFPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::PointF] = pointFPropertyManager;
-    d_ptr->m_typeToValueType[QVariant::PointF] = QVariant::PointF;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::PointF][d_ptr->m_decimalsAttribute] =
-            QVariant::Int;
-    connect(pointFPropertyManager, SIGNAL(valueChanged(QtProperty *, const QPointF &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QPointF &)));
-    connect(pointFPropertyManager, SIGNAL(decimalsChanged(QtProperty *, int)),
-                this, SLOT(slotDecimalsChanged(QtProperty *, int)));
-    connect(pointFPropertyManager->subDoublePropertyManager(), SIGNAL(valueChanged(QtProperty *, double)),
-                this, SLOT(slotValueChanged(QtProperty *, double)));
-    connect(pointFPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
-    connect(pointFPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-    // SizePropertyManager
-    QtSizePropertyManager *sizePropertyManager = new QtSizePropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Size] = sizePropertyManager;
-    d_ptr->m_typeToValueType[QVariant::Size] = QVariant::Size;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::Size][d_ptr->m_minimumAttribute] =
-            QVariant::Size;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::Size][d_ptr->m_maximumAttribute] =
-            QVariant::Size;
-    connect(sizePropertyManager, SIGNAL(valueChanged(QtProperty *, const QSize &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QSize &)));
-    connect(sizePropertyManager, SIGNAL(rangeChanged(QtProperty *, const QSize &, const QSize &)),
-                this, SLOT(slotRangeChanged(QtProperty *, const QSize &, const QSize &)));
-    connect(sizePropertyManager->subIntPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotValueChanged(QtProperty *, int)));
-    connect(sizePropertyManager->subIntPropertyManager(), SIGNAL(rangeChanged(QtProperty *, int, int)),
-                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
-    connect(sizePropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
-    connect(sizePropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-    // SizeFPropertyManager
-    QtSizeFPropertyManager *sizeFPropertyManager = new QtSizeFPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::SizeF] = sizeFPropertyManager;
-    d_ptr->m_typeToValueType[QVariant::SizeF] = QVariant::SizeF;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::SizeF][d_ptr->m_minimumAttribute] =
-            QVariant::SizeF;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::SizeF][d_ptr->m_maximumAttribute] =
-            QVariant::SizeF;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::SizeF][d_ptr->m_decimalsAttribute] =
-            QVariant::Int;
-    connect(sizeFPropertyManager, SIGNAL(valueChanged(QtProperty *, const QSizeF &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QSizeF &)));
-    connect(sizeFPropertyManager, SIGNAL(rangeChanged(QtProperty *, const QSizeF &, const QSizeF &)),
-                this, SLOT(slotRangeChanged(QtProperty *, const QSizeF &, const QSizeF &)));
-    connect(sizeFPropertyManager, SIGNAL(decimalsChanged(QtProperty *, int)),
-                this, SLOT(slotDecimalsChanged(QtProperty *, int)));
-    connect(sizeFPropertyManager->subDoublePropertyManager(), SIGNAL(valueChanged(QtProperty *, double)),
-                this, SLOT(slotValueChanged(QtProperty *, double)));
-    connect(sizeFPropertyManager->subDoublePropertyManager(), SIGNAL(rangeChanged(QtProperty *, double, double)),
-                this, SLOT(slotRangeChanged(QtProperty *, double, double)));
-    connect(sizeFPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
-    connect(sizeFPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-    // RectPropertyManager
-    QtRectPropertyManager *rectPropertyManager = new QtRectPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Rect] = rectPropertyManager;
-    d_ptr->m_typeToValueType[QVariant::Rect] = QVariant::Rect;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::Rect][d_ptr->m_constraintAttribute] =
-            QVariant::Rect;
-    connect(rectPropertyManager, SIGNAL(valueChanged(QtProperty *, const QRect &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QRect &)));
-    connect(rectPropertyManager, SIGNAL(constraintChanged(QtProperty *, const QRect &)),
-                this, SLOT(slotConstraintChanged(QtProperty *, const QRect &)));
-    connect(rectPropertyManager->subIntPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotValueChanged(QtProperty *, int)));
-    connect(rectPropertyManager->subIntPropertyManager(), SIGNAL(rangeChanged(QtProperty *, int, int)),
-                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
-    connect(rectPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
-    connect(rectPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-    // RectFPropertyManager
-    QtRectFPropertyManager *rectFPropertyManager = new QtRectFPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::RectF] = rectFPropertyManager;
-    d_ptr->m_typeToValueType[QVariant::RectF] = QVariant::RectF;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::RectF][d_ptr->m_constraintAttribute] =
-            QVariant::RectF;
-    d_ptr->m_typeToAttributeToAttributeType[QVariant::RectF][d_ptr->m_decimalsAttribute] =
-            QVariant::Int;
-    connect(rectFPropertyManager, SIGNAL(valueChanged(QtProperty *, const QRectF &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QRectF &)));
-    connect(rectFPropertyManager, SIGNAL(constraintChanged(QtProperty *, const QRectF &)),
-                this, SLOT(slotConstraintChanged(QtProperty *, const QRectF &)));
-    connect(rectFPropertyManager, SIGNAL(decimalsChanged(QtProperty *, int)),
-                this, SLOT(slotDecimalsChanged(QtProperty *, int)));
-    connect(rectFPropertyManager->subDoublePropertyManager(), SIGNAL(valueChanged(QtProperty *, double)),
-                this, SLOT(slotValueChanged(QtProperty *, double)));
-    connect(rectFPropertyManager->subDoublePropertyManager(), SIGNAL(rangeChanged(QtProperty *, double, double)),
-                this, SLOT(slotRangeChanged(QtProperty *, double, double)));
-    connect(rectFPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
-    connect(rectFPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-    // ColorPropertyManager
-    QtColorPropertyManager *colorPropertyManager = new QtColorPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Color] = colorPropertyManager;
-    d_ptr->m_typeToValueType[QVariant::Color] = QVariant::Color;
-    connect(colorPropertyManager, SIGNAL(valueChanged(QtProperty *, const QColor &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QColor &)));
-    connect(colorPropertyManager->subIntPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotValueChanged(QtProperty *, int)));
-    connect(colorPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
-    connect(colorPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-    // EnumPropertyManager
-    int enumId = enumTypeId();
-    QtEnumPropertyManager *enumPropertyManager = new QtEnumPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[enumId] = enumPropertyManager;
-    d_ptr->m_typeToValueType[enumId] = QVariant::Int;
-    d_ptr->m_typeToAttributeToAttributeType[enumId][d_ptr->m_enumNamesAttribute] =
-            QVariant::StringList;
-    d_ptr->m_typeToAttributeToAttributeType[enumId][d_ptr->m_enumIconsAttribute] =
-            iconMapTypeId();
-    connect(enumPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotValueChanged(QtProperty *, int)));
-    connect(enumPropertyManager, SIGNAL(enumNamesChanged(QtProperty *, const QStringList &)),
-                this, SLOT(slotEnumNamesChanged(QtProperty *, const QStringList &)));
-    connect(enumPropertyManager, SIGNAL(enumIconsChanged(QtProperty *, const QMap<int, QIcon> &)),
-                this, SLOT(slotEnumIconsChanged(QtProperty *, const QMap<int, QIcon> &)));
-    // SizePolicyPropertyManager
-    QtSizePolicyPropertyManager *sizePolicyPropertyManager = new QtSizePolicyPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::SizePolicy] = sizePolicyPropertyManager;
-    d_ptr->m_typeToValueType[QVariant::SizePolicy] = QVariant::SizePolicy;
-    connect(sizePolicyPropertyManager, SIGNAL(valueChanged(QtProperty *, const QSizePolicy &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QSizePolicy &)));
-    connect(sizePolicyPropertyManager->subIntPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotValueChanged(QtProperty *, int)));
-    connect(sizePolicyPropertyManager->subIntPropertyManager(), SIGNAL(rangeChanged(QtProperty *, int, int)),
-                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
-    connect(sizePolicyPropertyManager->subEnumPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotValueChanged(QtProperty *, int)));
-    connect(sizePolicyPropertyManager->subEnumPropertyManager(),
-                SIGNAL(enumNamesChanged(QtProperty *, const QStringList &)),
-                this, SLOT(slotEnumNamesChanged(QtProperty *, const QStringList &)));
-    connect(sizePolicyPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
-    connect(sizePolicyPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-    // FontPropertyManager
-    QtFontPropertyManager *fontPropertyManager = new QtFontPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Font] = fontPropertyManager;
-    d_ptr->m_typeToValueType[QVariant::Font] = QVariant::Font;
-    connect(fontPropertyManager, SIGNAL(valueChanged(QtProperty *, const QFont &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QFont &)));
-    connect(fontPropertyManager->subIntPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotValueChanged(QtProperty *, int)));
-    connect(fontPropertyManager->subIntPropertyManager(), SIGNAL(rangeChanged(QtProperty *, int, int)),
-                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
-    connect(fontPropertyManager->subEnumPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotValueChanged(QtProperty *, int)));
-    connect(fontPropertyManager->subEnumPropertyManager(),
-                SIGNAL(enumNamesChanged(QtProperty *, const QStringList &)),
-                this, SLOT(slotEnumNamesChanged(QtProperty *, const QStringList &)));
-    connect(fontPropertyManager->subBoolPropertyManager(), SIGNAL(valueChanged(QtProperty *, bool)),
-                this, SLOT(slotValueChanged(QtProperty *, bool)));
-    connect(fontPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
-    connect(fontPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-    // CursorPropertyManager
-    QtCursorPropertyManager *cursorPropertyManager = new QtCursorPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[QVariant::Cursor] = cursorPropertyManager;
-    d_ptr->m_typeToValueType[QVariant::Cursor] = QVariant::Cursor;
-    connect(cursorPropertyManager, SIGNAL(valueChanged(QtProperty *, const QCursor &)),
-                this, SLOT(slotValueChanged(QtProperty *, const QCursor &)));
-    // FlagPropertyManager
-    int flagId = flagTypeId();
-    QtFlagPropertyManager *flagPropertyManager = new QtFlagPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[flagId] = flagPropertyManager;
-    d_ptr->m_typeToValueType[flagId] = QVariant::Int;
-    d_ptr->m_typeToAttributeToAttributeType[flagId][d_ptr->m_flagNamesAttribute] =
-            QVariant::StringList;
-    connect(flagPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
-                this, SLOT(slotValueChanged(QtProperty *, int)));
-    connect(flagPropertyManager, SIGNAL(flagNamesChanged(QtProperty *, const QStringList &)),
-                this, SLOT(slotFlagNamesChanged(QtProperty *, const QStringList &)));
-    connect(flagPropertyManager->subBoolPropertyManager(), SIGNAL(valueChanged(QtProperty *, bool)),
-                this, SLOT(slotValueChanged(QtProperty *, bool)));
-    connect(flagPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
-    connect(flagPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
-                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
-    // FlagPropertyManager
-    int groupId = groupTypeId();
-    QtGroupPropertyManager *groupPropertyManager = new QtGroupPropertyManager(this);
-    d_ptr->m_typeToPropertyManager[groupId] = groupPropertyManager;
-    d_ptr->m_typeToValueType[groupId] = QVariant::Invalid;
-}
-
-/**
-    Destroys this manager, and all the properties it has created.
-*/
-QtVariantPropertyManager::~QtVariantPropertyManager()
-{
-    clear();
-    delete d_ptr;
-}
-
-/**
-    Returns the given \a property converted into a QtVariantProperty.
-
-    If the \a property was not created by this variant manager, the
-    function returns 0.
-
-    \sa createProperty()
-*/
-QtVariantProperty *QtVariantPropertyManager::variantProperty(const QtProperty *property) const
-{
-    const QMap<const QtProperty *, QPair<QtVariantProperty *, int> >::const_iterator it = d_ptr->m_propertyToType.constFind(property);
-    if (it == d_ptr->m_propertyToType.constEnd())
-        return 0;
-    return it.value().first;
-}
-
-/**
-    Returns true if the given \a propertyType is supported by this
-    variant manager; otherwise false.
-
-    \sa propertyType()
-*/
-bool QtVariantPropertyManager::isPropertyTypeSupported(int propertyType) const
-{
-    if (d_ptr->m_typeToValueType.contains(propertyType))
-        return true;
-    return false;
-}
-
-/**
-   Creates and returns a variant property of the given \a propertyType
-   with the given \a name.
-
-   If the specified \a propertyType is not supported by this variant
-   manager, this function returns 0.
-
-   Do not use the inherited
-   QtAbstractPropertyManager::addProperty() function to create a
-   variant property (that function will always return 0 since it will
-   not be clear what type the property should have).
-
-    \sa isPropertyTypeSupported()
-*/
-QtVariantProperty *QtVariantPropertyManager::addProperty(int propertyType, const QString &name)
-{
-    if (!isPropertyTypeSupported(propertyType))
-        return 0;
-
-    bool wasCreating = d_ptr->m_creatingProperty;
-    d_ptr->m_creatingProperty = true;
-    d_ptr->m_propertyType = propertyType;
-    QtProperty *property = QtAbstractPropertyManager::addProperty(name);
-    d_ptr->m_creatingProperty = wasCreating;
-    d_ptr->m_propertyType = 0;
-
-    if (!property)
-        return 0;
-
-    return variantProperty(property);
-}
-
-/**
-    Returns the given \a property's value.
-
-    If the given \a property is not managed by this manager, this
-    function returns an invalid variant.
-
-    \sa setValue()
-*/
-QVariant QtVariantPropertyManager::value(const QtProperty *property) const
-{
-    QtProperty *internProp = propertyToWrappedProperty()->value(property, 0);
-    if (internProp == 0)
-        return QVariant();
-
-    QtAbstractPropertyManager *manager = internProp->propertyManager();
-    if (QtIntPropertyManager *intManager = qobject_cast<QtIntPropertyManager *>(manager)) {
-        return intManager->value(internProp);
-    } else if (QtDoublePropertyManager *doubleManager = qobject_cast<QtDoublePropertyManager *>(manager)) {
-        return doubleManager->value(internProp);
-    } else if (QtBoolPropertyManager *boolManager = qobject_cast<QtBoolPropertyManager *>(manager)) {
-        return boolManager->value(internProp);
-    } else if (QtStringPropertyManager *stringManager = qobject_cast<QtStringPropertyManager *>(manager)) {
-        return stringManager->value(internProp);
-    } else if (QtDatePropertyManager *dateManager = qobject_cast<QtDatePropertyManager *>(manager)) {
-        return dateManager->value(internProp);
-    } else if (QtTimePropertyManager *timeManager = qobject_cast<QtTimePropertyManager *>(manager)) {
-        return timeManager->value(internProp);
-    } else if (QtDateTimePropertyManager *dateTimeManager = qobject_cast<QtDateTimePropertyManager *>(manager)) {
-        return dateTimeManager->value(internProp);
-    } else if (QtKeySequencePropertyManager *keySequenceManager = qobject_cast<QtKeySequencePropertyManager *>(manager)) {
-        return keySequenceManager->value(internProp);
-    } else if (QtCharPropertyManager *charManager = qobject_cast<QtCharPropertyManager *>(manager)) {
-        return charManager->value(internProp);
-    } else if (QtLocalePropertyManager *localeManager = qobject_cast<QtLocalePropertyManager *>(manager)) {
-        return localeManager->value(internProp);
-    } else if (QtPointPropertyManager *pointManager = qobject_cast<QtPointPropertyManager *>(manager)) {
-        return pointManager->value(internProp);
-    } else if (QtPointFPropertyManager *pointFManager = qobject_cast<QtPointFPropertyManager *>(manager)) {
-        return pointFManager->value(internProp);
-    } else if (QtSizePropertyManager *sizeManager = qobject_cast<QtSizePropertyManager *>(manager)) {
-        return sizeManager->value(internProp);
-    } else if (QtSizeFPropertyManager *sizeFManager = qobject_cast<QtSizeFPropertyManager *>(manager)) {
-        return sizeFManager->value(internProp);
-    } else if (QtRectPropertyManager *rectManager = qobject_cast<QtRectPropertyManager *>(manager)) {
-        return rectManager->value(internProp);
-    } else if (QtRectFPropertyManager *rectFManager = qobject_cast<QtRectFPropertyManager *>(manager)) {
-        return rectFManager->value(internProp);
-    } else if (QtColorPropertyManager *colorManager = qobject_cast<QtColorPropertyManager *>(manager)) {
-        return colorManager->value(internProp);
-    } else if (QtEnumPropertyManager *enumManager = qobject_cast<QtEnumPropertyManager *>(manager)) {
-        return enumManager->value(internProp);
-    } else if (QtSizePolicyPropertyManager *sizePolicyManager =
-               qobject_cast<QtSizePolicyPropertyManager *>(manager)) {
-        return sizePolicyManager->value(internProp);
-    } else if (QtFontPropertyManager *fontManager = qobject_cast<QtFontPropertyManager *>(manager)) {
-        return fontManager->value(internProp);
-#ifndef QT_NO_CURSOR
-    } else if (QtCursorPropertyManager *cursorManager = qobject_cast<QtCursorPropertyManager *>(manager)) {
-        return cursorManager->value(internProp);
-#endif
-    } else if (QtFlagPropertyManager *flagManager = qobject_cast<QtFlagPropertyManager *>(manager)) {
-        return flagManager->value(internProp);
-    }
-    return QVariant();
-}
-
-/**
-    Returns the given \a property's value type.
-
-    \sa propertyType()
-*/
-int QtVariantPropertyManager::valueType(const QtProperty *property) const
-{
-    int propType = propertyType(property);
-    return valueType(propType);
-}
-
-/**
-    \overload
-
-    Returns the value type associated with the given \a propertyType.
-*/
-int QtVariantPropertyManager::valueType(int propertyType) const
-{
-    if (d_ptr->m_typeToValueType.contains(propertyType))
-        return d_ptr->m_typeToValueType[propertyType];
-    return 0;
-}
-
-/**
-    Returns the given \a property's type.
-
-    \sa valueType()
-*/
-int QtVariantPropertyManager::propertyType(const QtProperty *property) const
-{
-    const QMap<const QtProperty *, QPair<QtVariantProperty *, int> >::const_iterator it = d_ptr->m_propertyToType.constFind(property);
-    if (it == d_ptr->m_propertyToType.constEnd())
-        return 0;
-    return it.value().second;
-}
-
-/**
-    Returns the given \a property's value for the specified \a
-    attribute
-
-    If the given \a property was not created by \e this manager, or if
-    the specified \a attribute does not exist, this function returns
-    an invalid variant.
-
-    \sa attributes(), attributeType(), setAttribute()
-*/
-QVariant QtVariantPropertyManager::attributeValue(const QtProperty *property, const QString &attribute) const
-{
-    int propType = propertyType(property);
-    if (!propType)
-        return QVariant();
-
-    QMap<int, QMap<QString, int> >::ConstIterator it =
-            d_ptr->m_typeToAttributeToAttributeType.find(propType);
-    if (it == d_ptr->m_typeToAttributeToAttributeType.constEnd())
-        return QVariant();
-
-    QMap<QString, int> attributes = it.value();
-    QMap<QString, int>::ConstIterator itAttr = attributes.find(attribute);
-    if (itAttr == attributes.constEnd())
-        return QVariant();
-
-    QtProperty *internProp = propertyToWrappedProperty()->value(property, 0);
-    if (internProp == 0)
-        return QVariant();
-
-    QtAbstractPropertyManager *manager = internProp->propertyManager();
-    if (QtIntPropertyManager *intManager = qobject_cast<QtIntPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_maximumAttribute)
-            return intManager->maximum(internProp);
-        if (attribute == d_ptr->m_minimumAttribute)
-            return intManager->minimum(internProp);
-        if (attribute == d_ptr->m_singleStepAttribute)
-            return intManager->singleStep(internProp);
-        return QVariant();
-    } else if (QtDoublePropertyManager *doubleManager = qobject_cast<QtDoublePropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_maximumAttribute)
-            return doubleManager->maximum(internProp);
-        if (attribute == d_ptr->m_minimumAttribute)
-            return doubleManager->minimum(internProp);
-        if (attribute == d_ptr->m_singleStepAttribute)
-            return doubleManager->singleStep(internProp);
-        if (attribute == d_ptr->m_decimalsAttribute)
-            return doubleManager->decimals(internProp);
-        return QVariant();
-    } else if (QtStringPropertyManager *stringManager = qobject_cast<QtStringPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_regExpAttribute)
-            return stringManager->regExp(internProp);
-        return QVariant();
-    } else if (QtDatePropertyManager *dateManager = qobject_cast<QtDatePropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_maximumAttribute)
-            return dateManager->maximum(internProp);
-        if (attribute == d_ptr->m_minimumAttribute)
-            return dateManager->minimum(internProp);
-        return QVariant();
-    } else if (QtPointFPropertyManager *pointFManager = qobject_cast<QtPointFPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_decimalsAttribute)
-            return pointFManager->decimals(internProp);
-        return QVariant();
-    } else if (QtSizePropertyManager *sizeManager = qobject_cast<QtSizePropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_maximumAttribute)
-            return sizeManager->maximum(internProp);
-        if (attribute == d_ptr->m_minimumAttribute)
-            return sizeManager->minimum(internProp);
-        return QVariant();
-    } else if (QtSizeFPropertyManager *sizeFManager = qobject_cast<QtSizeFPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_maximumAttribute)
-            return sizeFManager->maximum(internProp);
-        if (attribute == d_ptr->m_minimumAttribute)
-            return sizeFManager->minimum(internProp);
-        if (attribute == d_ptr->m_decimalsAttribute)
-            return sizeFManager->decimals(internProp);
-        return QVariant();
-    } else if (QtRectPropertyManager *rectManager = qobject_cast<QtRectPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_constraintAttribute)
-            return rectManager->constraint(internProp);
-        return QVariant();
-    } else if (QtRectFPropertyManager *rectFManager = qobject_cast<QtRectFPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_constraintAttribute)
-            return rectFManager->constraint(internProp);
-        if (attribute == d_ptr->m_decimalsAttribute)
-            return rectFManager->decimals(internProp);
-        return QVariant();
-    } else if (QtEnumPropertyManager *enumManager = qobject_cast<QtEnumPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_enumNamesAttribute)
-            return enumManager->enumNames(internProp);
-        if (attribute == d_ptr->m_enumIconsAttribute) {
-            QVariant v;
-            qVariantSetValue(v, enumManager->enumIcons(internProp));
-            return v;
-        }
-        return QVariant();
-    } else if (QtFlagPropertyManager *flagManager = qobject_cast<QtFlagPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_flagNamesAttribute)
-            return flagManager->flagNames(internProp);
-        return QVariant();
-    }
-    return QVariant();
-}
-
-/**
-    Returns a list of the given \a propertyType 's attributes.
-
-    \sa attributeValue(), attributeType()
-*/
-QStringList QtVariantPropertyManager::attributes(int propertyType) const
-{
-    QMap<int, QMap<QString, int> >::ConstIterator it =
-            d_ptr->m_typeToAttributeToAttributeType.find(propertyType);
-    if (it == d_ptr->m_typeToAttributeToAttributeType.constEnd())
-        return QStringList();
-    return it.value().keys();
-}
-
-/**
-    Returns the type of the specified \a attribute of the given \a
-    propertyType.
-
-    If the given \a propertyType is not supported by \e this manager,
-    or if the given \a propertyType does not possess the specified \a
-    attribute, this function returns QVariant::Invalid.
-
-    \sa attributes(), valueType()
-*/
-int QtVariantPropertyManager::attributeType(int propertyType, const QString &attribute) const
-{
-    QMap<int, QMap<QString, int> >::ConstIterator it =
-            d_ptr->m_typeToAttributeToAttributeType.find(propertyType);
-    if (it == d_ptr->m_typeToAttributeToAttributeType.constEnd())
-        return 0;
-
-    QMap<QString, int> attributes = it.value();
-    QMap<QString, int>::ConstIterator itAttr = attributes.find(attribute);
-    if (itAttr == attributes.constEnd())
-        return 0;
-    return itAttr.value();
-}
-
-/**
-    \fn void QtVariantPropertyManager::setValue(QtProperty *property, const QVariant &value)
-
-    Sets the value of the given \a property to \a value.
-
-    The specified \a value must be of a type returned by valueType(),
-    or of type that can be converted to valueType() using the
-    QVariant::canConvert() function, otherwise this function does
-    nothing.
-
-    \sa value(), QtVariantProperty::setValue(), valueChanged()
-*/
-void QtVariantPropertyManager::setValue(QtProperty *property, const QVariant &val)
-{
-    int propType = val.userType();
-    if (!propType)
-        return;
-
-    int valType = valueType(property);
-
-    if (propType != valType && !val.canConvert(static_cast<QVariant::Type>(valType)))
-        return;
-
-    QtProperty *internProp = propertyToWrappedProperty()->value(property, 0);
-    if (internProp == 0)
-        return;
-
-
-    QtAbstractPropertyManager *manager = internProp->propertyManager();
-    if (QtIntPropertyManager *intManager = qobject_cast<QtIntPropertyManager *>(manager)) {
-        intManager->setValue(internProp, qVariantValue<int>(val));
-        return;
-    } else if (QtDoublePropertyManager *doubleManager = qobject_cast<QtDoublePropertyManager *>(manager)) {
-        doubleManager->setValue(internProp, qVariantValue<double>(val));
-        return;
-    } else if (QtBoolPropertyManager *boolManager = qobject_cast<QtBoolPropertyManager *>(manager)) {
-        boolManager->setValue(internProp, qVariantValue<bool>(val));
-        return;
-    } else if (QtStringPropertyManager *stringManager = qobject_cast<QtStringPropertyManager *>(manager)) {
-        stringManager->setValue(internProp, qVariantValue<QString>(val));
-        return;
-    } else if (QtDatePropertyManager *dateManager = qobject_cast<QtDatePropertyManager *>(manager)) {
-        dateManager->setValue(internProp, qVariantValue<QDate>(val));
-        return;
-    } else if (QtTimePropertyManager *timeManager = qobject_cast<QtTimePropertyManager *>(manager)) {
-        timeManager->setValue(internProp, qVariantValue<QTime>(val));
-        return;
-    } else if (QtDateTimePropertyManager *dateTimeManager = qobject_cast<QtDateTimePropertyManager *>(manager)) {
-        dateTimeManager->setValue(internProp, qVariantValue<QDateTime>(val));
-        return;
-    } else if (QtKeySequencePropertyManager *keySequenceManager = qobject_cast<QtKeySequencePropertyManager *>(manager)) {
-        keySequenceManager->setValue(internProp, qVariantValue<QKeySequence>(val));
-        return;
-    } else if (QtCharPropertyManager *charManager = qobject_cast<QtCharPropertyManager *>(manager)) {
-        charManager->setValue(internProp, qVariantValue<QChar>(val));
-        return;
-    } else if (QtLocalePropertyManager *localeManager = qobject_cast<QtLocalePropertyManager *>(manager)) {
-        localeManager->setValue(internProp, qVariantValue<QLocale>(val));
-        return;
-    } else if (QtPointPropertyManager *pointManager = qobject_cast<QtPointPropertyManager *>(manager)) {
-        pointManager->setValue(internProp, qVariantValue<QPoint>(val));
-        return;
-    } else if (QtPointFPropertyManager *pointFManager = qobject_cast<QtPointFPropertyManager *>(manager)) {
-        pointFManager->setValue(internProp, qVariantValue<QPointF>(val));
-        return;
-    } else if (QtSizePropertyManager *sizeManager = qobject_cast<QtSizePropertyManager *>(manager)) {
-        sizeManager->setValue(internProp, qVariantValue<QSize>(val));
-        return;
-    } else if (QtSizeFPropertyManager *sizeFManager = qobject_cast<QtSizeFPropertyManager *>(manager)) {
-        sizeFManager->setValue(internProp, qVariantValue<QSizeF>(val));
-        return;
-    } else if (QtRectPropertyManager *rectManager = qobject_cast<QtRectPropertyManager *>(manager)) {
-        rectManager->setValue(internProp, qVariantValue<QRect>(val));
-        return;
-    } else if (QtRectFPropertyManager *rectFManager = qobject_cast<QtRectFPropertyManager *>(manager)) {
-        rectFManager->setValue(internProp, qVariantValue<QRectF>(val));
-        return;
-    } else if (QtColorPropertyManager *colorManager = qobject_cast<QtColorPropertyManager *>(manager)) {
-        colorManager->setValue(internProp, qVariantValue<QColor>(val));
-        return;
-    } else if (QtEnumPropertyManager *enumManager = qobject_cast<QtEnumPropertyManager *>(manager)) {
-        enumManager->setValue(internProp, qVariantValue<int>(val));
-        return;
-    } else if (QtSizePolicyPropertyManager *sizePolicyManager =
-               qobject_cast<QtSizePolicyPropertyManager *>(manager)) {
-        sizePolicyManager->setValue(internProp, qVariantValue<QSizePolicy>(val));
-        return;
-    } else if (QtFontPropertyManager *fontManager = qobject_cast<QtFontPropertyManager *>(manager)) {
-        fontManager->setValue(internProp, qVariantValue<QFont>(val));
-        return;
-#ifndef QT_NO_CURSOR
-    } else if (QtCursorPropertyManager *cursorManager = qobject_cast<QtCursorPropertyManager *>(manager)) {
-        cursorManager->setValue(internProp, qVariantValue<QCursor>(val));
-        return;
-#endif
-    } else if (QtFlagPropertyManager *flagManager = qobject_cast<QtFlagPropertyManager *>(manager)) {
-        flagManager->setValue(internProp, qVariantValue<int>(val));
-        return;
-    }
-}
-
-/**
-    Sets the value of the specified \a attribute of the given \a
-    property, to \a value.
-
-    The new \a value's type must be of the type returned by
-    attributeType(), or of a type that can be converted to
-    attributeType() using the QVariant::canConvert() function,
-    otherwise this function does nothing.
-
-    \sa attributeValue(), QtVariantProperty::setAttribute(), attributeChanged()
-*/
-void QtVariantPropertyManager::setAttribute(QtProperty *property,
-        const QString &attribute, const QVariant &value)
-{
-    QVariant oldAttr = attributeValue(property, attribute);
-    if (!oldAttr.isValid())
-        return;
-
-    int attrType = value.userType();
-    if (!attrType)
-        return;
-
-    if (attrType != attributeType(propertyType(property), attribute) &&
-                !value.canConvert((QVariant::Type)attrType))
-        return;
-
-    QtProperty *internProp = propertyToWrappedProperty()->value(property, 0);
-    if (internProp == 0)
-        return;
-
-    QtAbstractPropertyManager *manager = internProp->propertyManager();
-    if (QtIntPropertyManager *intManager = qobject_cast<QtIntPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_maximumAttribute)
-            intManager->setMaximum(internProp, qVariantValue<int>(value));
-        else if (attribute == d_ptr->m_minimumAttribute)
-            intManager->setMinimum(internProp, qVariantValue<int>(value));
-        else if (attribute == d_ptr->m_singleStepAttribute)
-            intManager->setSingleStep(internProp, qVariantValue<int>(value));
-        return;
-    } else if (QtDoublePropertyManager *doubleManager = qobject_cast<QtDoublePropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_maximumAttribute)
-            doubleManager->setMaximum(internProp, qVariantValue<double>(value));
-        if (attribute == d_ptr->m_minimumAttribute)
-            doubleManager->setMinimum(internProp, qVariantValue<double>(value));
-        if (attribute == d_ptr->m_singleStepAttribute)
-            doubleManager->setSingleStep(internProp, qVariantValue<double>(value));
-        if (attribute == d_ptr->m_decimalsAttribute)
-            doubleManager->setDecimals(internProp, qVariantValue<int>(value));
-        return;
-    } else if (QtStringPropertyManager *stringManager = qobject_cast<QtStringPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_regExpAttribute)
-            stringManager->setRegExp(internProp, qVariantValue<QRegExp>(value));
-        return;
-    } else if (QtDatePropertyManager *dateManager = qobject_cast<QtDatePropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_maximumAttribute)
-            dateManager->setMaximum(internProp, qVariantValue<QDate>(value));
-        if (attribute == d_ptr->m_minimumAttribute)
-            dateManager->setMinimum(internProp, qVariantValue<QDate>(value));
-        return;
-    } else if (QtPointFPropertyManager *pointFManager = qobject_cast<QtPointFPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_decimalsAttribute)
-            pointFManager->setDecimals(internProp, qVariantValue<int>(value));
-        return;
-    } else if (QtSizePropertyManager *sizeManager = qobject_cast<QtSizePropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_maximumAttribute)
-            sizeManager->setMaximum(internProp, qVariantValue<QSize>(value));
-        if (attribute == d_ptr->m_minimumAttribute)
-            sizeManager->setMinimum(internProp, qVariantValue<QSize>(value));
-        return;
-    } else if (QtSizeFPropertyManager *sizeFManager = qobject_cast<QtSizeFPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_maximumAttribute)
-            sizeFManager->setMaximum(internProp, qVariantValue<QSizeF>(value));
-        if (attribute == d_ptr->m_minimumAttribute)
-            sizeFManager->setMinimum(internProp, qVariantValue<QSizeF>(value));
-        if (attribute == d_ptr->m_decimalsAttribute)
-            sizeFManager->setDecimals(internProp, qVariantValue<int>(value));
-        return;
-    } else if (QtRectPropertyManager *rectManager = qobject_cast<QtRectPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_constraintAttribute)
-            rectManager->setConstraint(internProp, qVariantValue<QRect>(value));
-        return;
-    } else if (QtRectFPropertyManager *rectFManager = qobject_cast<QtRectFPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_constraintAttribute)
-            rectFManager->setConstraint(internProp, qVariantValue<QRectF>(value));
-        if (attribute == d_ptr->m_decimalsAttribute)
-            rectFManager->setDecimals(internProp, qVariantValue<int>(value));
-        return;
-    } else if (QtEnumPropertyManager *enumManager = qobject_cast<QtEnumPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_enumNamesAttribute)
-            enumManager->setEnumNames(internProp, qVariantValue<QStringList>(value));
-        if (attribute == d_ptr->m_enumIconsAttribute)
-            enumManager->setEnumIcons(internProp, qVariantValue<QtIconMap>(value));
-        return;
-    } else if (QtFlagPropertyManager *flagManager = qobject_cast<QtFlagPropertyManager *>(manager)) {
-        if (attribute == d_ptr->m_flagNamesAttribute)
-            flagManager->setFlagNames(internProp, qVariantValue<QStringList>(value));
-        return;
-    }
-}
-
-/**
-    \reimp
-*/
-bool QtVariantPropertyManager::hasValue(const QtProperty *property) const
-{
-    if (propertyType(property) == groupTypeId())
-        return false;
-    return true;
-}
-
-/**
-    \reimp
-*/
-QString QtVariantPropertyManager::valueText(const QtProperty *property) const
-{
-    const QtProperty *internProp = propertyToWrappedProperty()->value(property, 0);
-    return internProp ? internProp->valueText() : QString();
-}
-
-/**
-    \reimp
-*/
-QIcon QtVariantPropertyManager::valueIcon(const QtProperty *property) const
-{
-    const QtProperty *internProp = propertyToWrappedProperty()->value(property, 0);
-    return internProp ? internProp->valueIcon() : QIcon();
-}
-
-/**
-    \reimp
-*/
-void QtVariantPropertyManager::initializeProperty(QtProperty *property)
-{
-    QtVariantProperty *varProp = variantProperty(property);
-    if (!varProp)
-        return;
-
-    QMap<int, QtAbstractPropertyManager *>::ConstIterator it =
-            d_ptr->m_typeToPropertyManager.find(d_ptr->m_propertyType);
-    if (it != d_ptr->m_typeToPropertyManager.constEnd()) {
-        QtProperty *internProp = 0;
-        if (!d_ptr->m_creatingSubProperties) {
-            QtAbstractPropertyManager *manager = it.value();
-            internProp = manager->addProperty();
-            d_ptr->m_internalToProperty[internProp] = varProp;
-        }
-        propertyToWrappedProperty()->insert(varProp, internProp);
-        if (internProp) {
-            QList<QtProperty *> children = internProp->subProperties();
-            QListIterator<QtProperty *> itChild(children);
-            QtVariantProperty *lastProperty = 0;
-            while (itChild.hasNext()) {
-                QtVariantProperty *prop = d_ptr->createSubProperty(varProp, lastProperty, itChild.next());
-                lastProperty = prop ? prop : lastProperty;
-            }
-        }
-    }
-}
-
-/**
-    \reimp
-*/
-void QtVariantPropertyManager::uninitializeProperty(QtProperty *property)
-{
-    const QMap<const QtProperty *, QPair<QtVariantProperty *, int> >::iterator type_it = d_ptr->m_propertyToType.find(property);
-    if (type_it == d_ptr->m_propertyToType.end())
-        return;
-
-    PropertyMap::iterator it = propertyToWrappedProperty()->find(property);
-    if (it != propertyToWrappedProperty()->end()) {
-        QtProperty *internProp = it.value();
-        if (internProp) {
-            d_ptr->m_internalToProperty.remove(internProp);
-            if (!d_ptr->m_destroyingSubProperties) {
-                delete internProp;
-            }
-        }
-        propertyToWrappedProperty()->erase(it);
-    }
-    d_ptr->m_propertyToType.erase(type_it);
-}
-
-/**
-    \reimp
-*/
-QtProperty *QtVariantPropertyManager::createProperty()
-{
-    if (!d_ptr->m_creatingProperty)
-        return 0;
-
-    QtVariantProperty *property = new QtVariantProperty(this);
-    d_ptr->m_propertyToType.insert(property, qMakePair(property, d_ptr->m_propertyType));
-
-    return property;
-}
-
-/////////////////////////////
-
-class QtVariantEditorFactoryPrivate
-{
-    QtVariantEditorFactory *q_ptr;
-    Q_DECLARE_PUBLIC(QtVariantEditorFactory)
-public:
-
-    QtSpinBoxFactory           *m_spinBoxFactory;
-    QtDoubleSpinBoxFactory     *m_doubleSpinBoxFactory;
-    QtCheckBoxFactory          *m_checkBoxFactory;
-    QtLineEditFactory          *m_lineEditFactory;
-    QtDateEditFactory          *m_dateEditFactory;
-    QtTimeEditFactory          *m_timeEditFactory;
-    QtDateTimeEditFactory      *m_dateTimeEditFactory;
-    QtKeySequenceEditorFactory *m_keySequenceEditorFactory;
-    QtCharEditorFactory        *m_charEditorFactory;
-    QtEnumEditorFactory        *m_comboBoxFactory;
-    QtCursorEditorFactory      *m_cursorEditorFactory;
-    QtColorEditorFactory       *m_colorEditorFactory;
-    QtFontEditorFactory        *m_fontEditorFactory;
-
-    QMap<QtAbstractEditorFactoryBase *, int> m_factoryToType;
-    QMap<int, QtAbstractEditorFactoryBase *> m_typeToFactory;
-};
-
-/**
-    \class QtVariantEditorFactory
-
-    \brief The QtVariantEditorFactory class provides widgets for properties
-    created by QtVariantPropertyManager objects.
-
-    The variant factory provides the following widgets for the
-    specified property types:
-
-    \table
-    \header
-        \o Property Type
-        \o Widget
-    \row
-        \o \c int
-        \o QSpinBox
-    \row
-        \o \c double
-        \o QDoubleSpinBox
-    \row
-        \o \c bool
-        \o QCheckBox
-    \row
-        \o QString
-        \o QLineEdit
-    \row
-        \o QDate
-        \o QDateEdit
-    \row
-        \o QTime
-        \o QTimeEdit
-    \row
-        \o QDateTime
-        \o QDateTimeEdit
-    \row
-        \o QKeySequence
-        \o customized editor
-    \row
-        \o QChar
-        \o customized editor
-    \row
-        \o \c enum
-        \o QComboBox
-    \row
-        \o QCursor
-        \o QComboBox
-    \endtable
-
-    Note that QtVariantPropertyManager supports several additional property
-    types for which the QtVariantEditorFactory class does not provide
-    editing widgets, e.g. QPoint and QSize. To provide widgets for other
-    types using the variant approach, derive from the QtVariantEditorFactory
-    class.
-
-    \sa QtAbstractEditorFactory, QtVariantPropertyManager
-*/
-
-/**
-    Creates a factory with the given \a parent.
-*/
-QtVariantEditorFactory::QtVariantEditorFactory(QObject *parent)
-    : QtAbstractEditorFactory<QtVariantPropertyManager>(parent)
-{
-    d_ptr = new QtVariantEditorFactoryPrivate();
-    d_ptr->q_ptr = this;
-
-    d_ptr->m_spinBoxFactory = new QtSpinBoxFactory(this);
-    d_ptr->m_factoryToType[d_ptr->m_spinBoxFactory] = QVariant::Int;
-    d_ptr->m_typeToFactory[QVariant::Int] = d_ptr->m_spinBoxFactory;
-
-    d_ptr->m_doubleSpinBoxFactory = new QtDoubleSpinBoxFactory(this);
-    d_ptr->m_factoryToType[d_ptr->m_doubleSpinBoxFactory] = QVariant::Double;
-    d_ptr->m_typeToFactory[QVariant::Double] = d_ptr->m_doubleSpinBoxFactory;
-
-    d_ptr->m_checkBoxFactory = new QtCheckBoxFactory(this);
-    d_ptr->m_factoryToType[d_ptr->m_checkBoxFactory] = QVariant::Bool;
-    d_ptr->m_typeToFactory[QVariant::Bool] = d_ptr->m_checkBoxFactory;
-
-    d_ptr->m_lineEditFactory = new QtLineEditFactory(this);
-    d_ptr->m_factoryToType[d_ptr->m_lineEditFactory] = QVariant::String;
-    d_ptr->m_typeToFactory[QVariant::String] = d_ptr->m_lineEditFactory;
-
-    d_ptr->m_dateEditFactory = new QtDateEditFactory(this);
-    d_ptr->m_factoryToType[d_ptr->m_dateEditFactory] = QVariant::Date;
-    d_ptr->m_typeToFactory[QVariant::Date] = d_ptr->m_dateEditFactory;
-
-    d_ptr->m_timeEditFactory = new QtTimeEditFactory(this);
-    d_ptr->m_factoryToType[d_ptr->m_timeEditFactory] = QVariant::Time;
-    d_ptr->m_typeToFactory[QVariant::Time] = d_ptr->m_timeEditFactory;
-
-    d_ptr->m_dateTimeEditFactory = new QtDateTimeEditFactory(this);
-    d_ptr->m_factoryToType[d_ptr->m_dateTimeEditFactory] = QVariant::DateTime;
-    d_ptr->m_typeToFactory[QVariant::DateTime] = d_ptr->m_dateTimeEditFactory;
-
-    d_ptr->m_keySequenceEditorFactory = new QtKeySequenceEditorFactory(this);
-    d_ptr->m_factoryToType[d_ptr->m_keySequenceEditorFactory] = QVariant::KeySequence;
-    d_ptr->m_typeToFactory[QVariant::KeySequence] = d_ptr->m_keySequenceEditorFactory;
-
-    d_ptr->m_charEditorFactory = new QtCharEditorFactory(this);
-    d_ptr->m_factoryToType[d_ptr->m_charEditorFactory] = QVariant::Char;
-    d_ptr->m_typeToFactory[QVariant::Char] = d_ptr->m_charEditorFactory;
-
-    d_ptr->m_cursorEditorFactory = new QtCursorEditorFactory(this);
-    d_ptr->m_factoryToType[d_ptr->m_cursorEditorFactory] = QVariant::Cursor;
-    d_ptr->m_typeToFactory[QVariant::Cursor] = d_ptr->m_cursorEditorFactory;
-
-    d_ptr->m_colorEditorFactory = new QtColorEditorFactory(this);
-    d_ptr->m_factoryToType[d_ptr->m_colorEditorFactory] = QVariant::Color;
-    d_ptr->m_typeToFactory[QVariant::Color] = d_ptr->m_colorEditorFactory;
-
-    d_ptr->m_fontEditorFactory = new QtFontEditorFactory(this);
-    d_ptr->m_factoryToType[d_ptr->m_fontEditorFactory] = QVariant::Font;
-    d_ptr->m_typeToFactory[QVariant::Font] = d_ptr->m_fontEditorFactory;
-
-    d_ptr->m_comboBoxFactory = new QtEnumEditorFactory(this);
-    const int enumId = QtVariantPropertyManager::enumTypeId();
-    d_ptr->m_factoryToType[d_ptr->m_comboBoxFactory] = enumId;
-    d_ptr->m_typeToFactory[enumId] = d_ptr->m_comboBoxFactory;
-}
-
-/**
-    Destroys this factory, and all the widgets it has created.
-*/
-QtVariantEditorFactory::~QtVariantEditorFactory()
-{
-    delete d_ptr;
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtVariantEditorFactory::connectPropertyManager(QtVariantPropertyManager *manager)
-{
-    QList<QtIntPropertyManager *> intPropertyManagers = qFindChildren<QtIntPropertyManager *>(manager);
-    QListIterator<QtIntPropertyManager *> itInt(intPropertyManagers);
-    while (itInt.hasNext())
-        d_ptr->m_spinBoxFactory->addPropertyManager(itInt.next());
-
-    QList<QtDoublePropertyManager *> doublePropertyManagers = qFindChildren<QtDoublePropertyManager *>(manager);
-    QListIterator<QtDoublePropertyManager *> itDouble(doublePropertyManagers);
-    while (itDouble.hasNext())
-        d_ptr->m_doubleSpinBoxFactory->addPropertyManager(itDouble.next());
-
-    QList<QtBoolPropertyManager *> boolPropertyManagers = qFindChildren<QtBoolPropertyManager *>(manager);
-    QListIterator<QtBoolPropertyManager *> itBool(boolPropertyManagers);
-    while (itBool.hasNext())
-        d_ptr->m_checkBoxFactory->addPropertyManager(itBool.next());
-
-    QList<QtStringPropertyManager *> stringPropertyManagers = qFindChildren<QtStringPropertyManager *>(manager);
-    QListIterator<QtStringPropertyManager *> itString(stringPropertyManagers);
-    while (itString.hasNext())
-        d_ptr->m_lineEditFactory->addPropertyManager(itString.next());
-
-    QList<QtDatePropertyManager *> datePropertyManagers = qFindChildren<QtDatePropertyManager *>(manager);
-    QListIterator<QtDatePropertyManager *> itDate(datePropertyManagers);
-    while (itDate.hasNext())
-        d_ptr->m_dateEditFactory->addPropertyManager(itDate.next());
-
-    QList<QtTimePropertyManager *> timePropertyManagers = qFindChildren<QtTimePropertyManager *>(manager);
-    QListIterator<QtTimePropertyManager *> itTime(timePropertyManagers);
-    while (itTime.hasNext())
-        d_ptr->m_timeEditFactory->addPropertyManager(itTime.next());
-
-    QList<QtDateTimePropertyManager *> dateTimePropertyManagers = qFindChildren<QtDateTimePropertyManager *>(manager);
-    QListIterator<QtDateTimePropertyManager *> itDateTime(dateTimePropertyManagers);
-    while (itDateTime.hasNext())
-        d_ptr->m_dateTimeEditFactory->addPropertyManager(itDateTime.next());
-
-    QList<QtKeySequencePropertyManager *> keySequencePropertyManagers = qFindChildren<QtKeySequencePropertyManager *>(manager);
-    QListIterator<QtKeySequencePropertyManager *> itKeySequence(keySequencePropertyManagers);
-    while (itKeySequence.hasNext())
-        d_ptr->m_keySequenceEditorFactory->addPropertyManager(itKeySequence.next());
-
-    QList<QtCharPropertyManager *> charPropertyManagers = qFindChildren<QtCharPropertyManager *>(manager);
-    QListIterator<QtCharPropertyManager *> itChar(charPropertyManagers);
-    while (itChar.hasNext())
-        d_ptr->m_charEditorFactory->addPropertyManager(itChar.next());
-
-    QList<QtLocalePropertyManager *> localePropertyManagers = qFindChildren<QtLocalePropertyManager *>(manager);
-    QListIterator<QtLocalePropertyManager *> itLocale(localePropertyManagers);
-    while (itLocale.hasNext())
-        d_ptr->m_comboBoxFactory->addPropertyManager(itLocale.next()->subEnumPropertyManager());
-
-    QList<QtPointPropertyManager *> pointPropertyManagers = qFindChildren<QtPointPropertyManager *>(manager);
-    QListIterator<QtPointPropertyManager *> itPoint(pointPropertyManagers);
-    while (itPoint.hasNext())
-        d_ptr->m_spinBoxFactory->addPropertyManager(itPoint.next()->subIntPropertyManager());
-
-    QList<QtPointFPropertyManager *> pointFPropertyManagers = qFindChildren<QtPointFPropertyManager *>(manager);
-    QListIterator<QtPointFPropertyManager *> itPointF(pointFPropertyManagers);
-    while (itPointF.hasNext())
-        d_ptr->m_doubleSpinBoxFactory->addPropertyManager(itPointF.next()->subDoublePropertyManager());
-
-    QList<QtSizePropertyManager *> sizePropertyManagers = qFindChildren<QtSizePropertyManager *>(manager);
-    QListIterator<QtSizePropertyManager *> itSize(sizePropertyManagers);
-    while (itSize.hasNext())
-        d_ptr->m_spinBoxFactory->addPropertyManager(itSize.next()->subIntPropertyManager());
-
-    QList<QtSizeFPropertyManager *> sizeFPropertyManagers = qFindChildren<QtSizeFPropertyManager *>(manager);
-    QListIterator<QtSizeFPropertyManager *> itSizeF(sizeFPropertyManagers);
-    while (itSizeF.hasNext())
-        d_ptr->m_doubleSpinBoxFactory->addPropertyManager(itSizeF.next()->subDoublePropertyManager());
-
-    QList<QtRectPropertyManager *> rectPropertyManagers = qFindChildren<QtRectPropertyManager *>(manager);
-    QListIterator<QtRectPropertyManager *> itRect(rectPropertyManagers);
-    while (itRect.hasNext())
-        d_ptr->m_spinBoxFactory->addPropertyManager(itRect.next()->subIntPropertyManager());
-
-    QList<QtRectFPropertyManager *> rectFPropertyManagers = qFindChildren<QtRectFPropertyManager *>(manager);
-    QListIterator<QtRectFPropertyManager *> itRectF(rectFPropertyManagers);
-    while (itRectF.hasNext())
-        d_ptr->m_doubleSpinBoxFactory->addPropertyManager(itRectF.next()->subDoublePropertyManager());
-
-    QList<QtColorPropertyManager *> colorPropertyManagers = qFindChildren<QtColorPropertyManager *>(manager);
-    QListIterator<QtColorPropertyManager *> itColor(colorPropertyManagers);
-    while (itColor.hasNext()) {
-        QtColorPropertyManager *manager = itColor.next();
-        d_ptr->m_colorEditorFactory->addPropertyManager(manager);
-        d_ptr->m_spinBoxFactory->addPropertyManager(manager->subIntPropertyManager());
-    }
-
-    QList<QtEnumPropertyManager *> enumPropertyManagers = qFindChildren<QtEnumPropertyManager *>(manager);
-    QListIterator<QtEnumPropertyManager *> itEnum(enumPropertyManagers);
-    while (itEnum.hasNext())
-        d_ptr->m_comboBoxFactory->addPropertyManager(itEnum.next());
-
-    QList<QtSizePolicyPropertyManager *> sizePolicyPropertyManagers = qFindChildren<QtSizePolicyPropertyManager *>(manager);
-    QListIterator<QtSizePolicyPropertyManager *> itSizePolicy(sizePolicyPropertyManagers);
-    while (itSizePolicy.hasNext()) {
-        QtSizePolicyPropertyManager *manager = itSizePolicy.next();
-        d_ptr->m_spinBoxFactory->addPropertyManager(manager->subIntPropertyManager());
-        d_ptr->m_comboBoxFactory->addPropertyManager(manager->subEnumPropertyManager());
-    }
-
-    QList<QtFontPropertyManager *> fontPropertyManagers = qFindChildren<QtFontPropertyManager *>(manager);
-    QListIterator<QtFontPropertyManager *> itFont(fontPropertyManagers);
-    while (itFont.hasNext()) {
-        QtFontPropertyManager *manager = itFont.next();
-        d_ptr->m_fontEditorFactory->addPropertyManager(manager);
-        d_ptr->m_spinBoxFactory->addPropertyManager(manager->subIntPropertyManager());
-        d_ptr->m_comboBoxFactory->addPropertyManager(manager->subEnumPropertyManager());
-        d_ptr->m_checkBoxFactory->addPropertyManager(manager->subBoolPropertyManager());
-    }
-
-    QList<QtCursorPropertyManager *> cursorPropertyManagers = qFindChildren<QtCursorPropertyManager *>(manager);
-    QListIterator<QtCursorPropertyManager *> itCursor(cursorPropertyManagers);
-    while (itCursor.hasNext())
-        d_ptr->m_cursorEditorFactory->addPropertyManager(itCursor.next());
-
-    QList<QtFlagPropertyManager *> flagPropertyManagers = qFindChildren<QtFlagPropertyManager *>(manager);
-    QListIterator<QtFlagPropertyManager *> itFlag(flagPropertyManagers);
-    while (itFlag.hasNext())
-        d_ptr->m_checkBoxFactory->addPropertyManager(itFlag.next()->subBoolPropertyManager());
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-QWidget *QtVariantEditorFactory::createEditor(QtVariantPropertyManager *manager, QtProperty *property,
-        QWidget *parent)
-{
-    const int propType = manager->propertyType(property);
-    QtAbstractEditorFactoryBase *factory = d_ptr->m_typeToFactory.value(propType, 0);
-    if (!factory)
-        return 0;
-    return factory->createEditor(wrappedProperty(property), parent);
-}
-
-/**
-    \internal
-
-    Reimplemented from the QtAbstractEditorFactory class.
-*/
-void QtVariantEditorFactory::disconnectPropertyManager(QtVariantPropertyManager *manager)
-{
-    QList<QtIntPropertyManager *> intPropertyManagers = qFindChildren<QtIntPropertyManager *>(manager);
-    QListIterator<QtIntPropertyManager *> itInt(intPropertyManagers);
-    while (itInt.hasNext())
-        d_ptr->m_spinBoxFactory->removePropertyManager(itInt.next());
-
-    QList<QtDoublePropertyManager *> doublePropertyManagers = qFindChildren<QtDoublePropertyManager *>(manager);
-    QListIterator<QtDoublePropertyManager *> itDouble(doublePropertyManagers);
-    while (itDouble.hasNext())
-        d_ptr->m_doubleSpinBoxFactory->removePropertyManager(itDouble.next());
-
-    QList<QtBoolPropertyManager *> boolPropertyManagers = qFindChildren<QtBoolPropertyManager *>(manager);
-    QListIterator<QtBoolPropertyManager *> itBool(boolPropertyManagers);
-    while (itBool.hasNext())
-        d_ptr->m_checkBoxFactory->removePropertyManager(itBool.next());
-
-    QList<QtStringPropertyManager *> stringPropertyManagers = qFindChildren<QtStringPropertyManager *>(manager);
-    QListIterator<QtStringPropertyManager *> itString(stringPropertyManagers);
-    while (itString.hasNext())
-        d_ptr->m_lineEditFactory->removePropertyManager(itString.next());
-
-    QList<QtDatePropertyManager *> datePropertyManagers = qFindChildren<QtDatePropertyManager *>(manager);
-    QListIterator<QtDatePropertyManager *> itDate(datePropertyManagers);
-    while (itDate.hasNext())
-        d_ptr->m_dateEditFactory->removePropertyManager(itDate.next());
-
-    QList<QtTimePropertyManager *> timePropertyManagers = qFindChildren<QtTimePropertyManager *>(manager);
-    QListIterator<QtTimePropertyManager *> itTime(timePropertyManagers);
-    while (itTime.hasNext())
-        d_ptr->m_timeEditFactory->removePropertyManager(itTime.next());
-
-    QList<QtDateTimePropertyManager *> dateTimePropertyManagers = qFindChildren<QtDateTimePropertyManager *>(manager);
-    QListIterator<QtDateTimePropertyManager *> itDateTime(dateTimePropertyManagers);
-    while (itDateTime.hasNext())
-        d_ptr->m_dateTimeEditFactory->removePropertyManager(itDateTime.next());
-
-    QList<QtKeySequencePropertyManager *> keySequencePropertyManagers = qFindChildren<QtKeySequencePropertyManager *>(manager);
-    QListIterator<QtKeySequencePropertyManager *> itKeySequence(keySequencePropertyManagers);
-    while (itKeySequence.hasNext())
-        d_ptr->m_keySequenceEditorFactory->removePropertyManager(itKeySequence.next());
-
-    QList<QtCharPropertyManager *> charPropertyManagers = qFindChildren<QtCharPropertyManager *>(manager);
-    QListIterator<QtCharPropertyManager *> itChar(charPropertyManagers);
-    while (itChar.hasNext())
-        d_ptr->m_charEditorFactory->removePropertyManager(itChar.next());
-
-    QList<QtLocalePropertyManager *> localePropertyManagers = qFindChildren<QtLocalePropertyManager *>(manager);
-    QListIterator<QtLocalePropertyManager *> itLocale(localePropertyManagers);
-    while (itLocale.hasNext())
-        d_ptr->m_comboBoxFactory->removePropertyManager(itLocale.next()->subEnumPropertyManager());
-
-    QList<QtPointPropertyManager *> pointPropertyManagers = qFindChildren<QtPointPropertyManager *>(manager);
-    QListIterator<QtPointPropertyManager *> itPoint(pointPropertyManagers);
-    while (itPoint.hasNext())
-        d_ptr->m_spinBoxFactory->removePropertyManager(itPoint.next()->subIntPropertyManager());
-
-    QList<QtPointFPropertyManager *> pointFPropertyManagers = qFindChildren<QtPointFPropertyManager *>(manager);
-    QListIterator<QtPointFPropertyManager *> itPointF(pointFPropertyManagers);
-    while (itPointF.hasNext())
-        d_ptr->m_doubleSpinBoxFactory->removePropertyManager(itPointF.next()->subDoublePropertyManager());
-
-    QList<QtSizePropertyManager *> sizePropertyManagers = qFindChildren<QtSizePropertyManager *>(manager);
-    QListIterator<QtSizePropertyManager *> itSize(sizePropertyManagers);
-    while (itSize.hasNext())
-        d_ptr->m_spinBoxFactory->removePropertyManager(itSize.next()->subIntPropertyManager());
-
-    QList<QtSizeFPropertyManager *> sizeFPropertyManagers = qFindChildren<QtSizeFPropertyManager *>(manager);
-    QListIterator<QtSizeFPropertyManager *> itSizeF(sizeFPropertyManagers);
-    while (itSizeF.hasNext())
-        d_ptr->m_doubleSpinBoxFactory->removePropertyManager(itSizeF.next()->subDoublePropertyManager());
-
-    QList<QtRectPropertyManager *> rectPropertyManagers = qFindChildren<QtRectPropertyManager *>(manager);
-    QListIterator<QtRectPropertyManager *> itRect(rectPropertyManagers);
-    while (itRect.hasNext())
-        d_ptr->m_spinBoxFactory->removePropertyManager(itRect.next()->subIntPropertyManager());
-
-    QList<QtRectFPropertyManager *> rectFPropertyManagers = qFindChildren<QtRectFPropertyManager *>(manager);
-    QListIterator<QtRectFPropertyManager *> itRectF(rectFPropertyManagers);
-    while (itRectF.hasNext())
-        d_ptr->m_doubleSpinBoxFactory->removePropertyManager(itRectF.next()->subDoublePropertyManager());
-
-    QList<QtColorPropertyManager *> colorPropertyManagers = qFindChildren<QtColorPropertyManager *>(manager);
-    QListIterator<QtColorPropertyManager *> itColor(colorPropertyManagers);
-    while (itColor.hasNext()) {
-        QtColorPropertyManager *manager = itColor.next();
-        d_ptr->m_colorEditorFactory->removePropertyManager(manager);
-        d_ptr->m_spinBoxFactory->removePropertyManager(manager->subIntPropertyManager());
-    }
-
-    QList<QtEnumPropertyManager *> enumPropertyManagers = qFindChildren<QtEnumPropertyManager *>(manager);
-    QListIterator<QtEnumPropertyManager *> itEnum(enumPropertyManagers);
-    while (itEnum.hasNext())
-        d_ptr->m_comboBoxFactory->removePropertyManager(itEnum.next());
-
-    QList<QtSizePolicyPropertyManager *> sizePolicyPropertyManagers = qFindChildren<QtSizePolicyPropertyManager *>(manager);
-    QListIterator<QtSizePolicyPropertyManager *> itSizePolicy(sizePolicyPropertyManagers);
-    while (itSizePolicy.hasNext()) {
-        QtSizePolicyPropertyManager *manager = itSizePolicy.next();
-        d_ptr->m_spinBoxFactory->removePropertyManager(manager->subIntPropertyManager());
-        d_ptr->m_comboBoxFactory->removePropertyManager(manager->subEnumPropertyManager());
-    }
-
-    QList<QtFontPropertyManager *> fontPropertyManagers = qFindChildren<QtFontPropertyManager *>(manager);
-    QListIterator<QtFontPropertyManager *> itFont(fontPropertyManagers);
-    while (itFont.hasNext()) {
-        QtFontPropertyManager *manager = itFont.next();
-        d_ptr->m_fontEditorFactory->removePropertyManager(manager);
-        d_ptr->m_spinBoxFactory->removePropertyManager(manager->subIntPropertyManager());
-        d_ptr->m_comboBoxFactory->removePropertyManager(manager->subEnumPropertyManager());
-        d_ptr->m_checkBoxFactory->removePropertyManager(manager->subBoolPropertyManager());
-    }
-
-    QList<QtCursorPropertyManager *> cursorPropertyManagers = qFindChildren<QtCursorPropertyManager *>(manager);
-    QListIterator<QtCursorPropertyManager *> itCursor(cursorPropertyManagers);
-    while (itCursor.hasNext())
-        d_ptr->m_cursorEditorFactory->removePropertyManager(itCursor.next());
-
-    QList<QtFlagPropertyManager *> flagPropertyManagers = qFindChildren<QtFlagPropertyManager *>(manager);
-    QListIterator<QtFlagPropertyManager *> itFlag(flagPropertyManagers);
-    while (itFlag.hasNext())
-        d_ptr->m_checkBoxFactory->removePropertyManager(itFlag.next()->subBoolPropertyManager());
-}
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-#include "moc_qtvariantproperty.cpp"
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qtvariantproperty.h"
+#include "qtpropertymanager.h"
+#include "qteditorfactory.h"
+#include <QtCore/QVariant>
+#include <QtGui/QIcon>
+#include <QtCore/QDate>
+#include <QtCore/QLocale>
+
+#if defined(Q_CC_MSVC)
+#    pragma warning(disable: 4786) /* MS VS 6: truncating debug info after 255 characters */
+#endif
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+class QtEnumPropertyType
+{
+};
+
+
+class QtFlagPropertyType
+{
+};
+
+
+class QtGroupPropertyType
+{
+};
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+Q_DECLARE_METATYPE(QtEnumPropertyType)
+Q_DECLARE_METATYPE(QtFlagPropertyType)
+Q_DECLARE_METATYPE(QtGroupPropertyType)
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+/**
+    Returns the type id for an enum property.
+
+    Note that the property's value type can be retrieved using the
+    valueType() function (which is QVariant::Int for the enum property
+    type).
+
+    \sa propertyType(), valueType()
+*/
+int QtVariantPropertyManager::enumTypeId()
+{
+    return qMetaTypeId<QtEnumPropertyType>();
+}
+
+/**
+    Returns the type id for a flag property.
+
+    Note that the property's value type can be retrieved using the
+    valueType() function (which is QVariant::Int for the flag property
+    type).
+
+    \sa propertyType(), valueType()
+*/
+int QtVariantPropertyManager::flagTypeId()
+{
+    return qMetaTypeId<QtFlagPropertyType>();
+}
+
+/**
+    Returns the type id for a group property.
+
+    Note that the property's value type can be retrieved using the
+    valueType() function (which is QVariant::Invalid for the group
+    property type, since it doesn't provide any value).
+
+    \sa propertyType(), valueType()
+*/
+int QtVariantPropertyManager::groupTypeId()
+{
+    return qMetaTypeId<QtGroupPropertyType>();
+}
+
+/**
+    Returns the type id for a icon map attribute.
+
+    Note that the property's attribute type can be retrieved using the
+    attributeType() function.
+
+    \sa attributeType(), QtEnumPropertyManager::enumIcons()
+*/
+int QtVariantPropertyManager::iconMapTypeId()
+{
+    return qMetaTypeId<QtIconMap>();
+}
+
+typedef QMap<const QtProperty *, QtProperty *> PropertyMap;
+Q_GLOBAL_STATIC(PropertyMap, propertyToWrappedProperty)
+
+static QtProperty *wrappedProperty(QtProperty *property)
+{
+    return propertyToWrappedProperty()->value(property, 0);
+}
+
+class QtVariantPropertyPrivate
+{
+    QtVariantProperty *q_ptr;
+public:
+    QtVariantPropertyPrivate(QtVariantPropertyManager *m) : manager(m) {}
+
+    QtVariantPropertyManager *manager;
+};
+
+/**
+    \class QtVariantProperty
+
+    \brief The QtVariantProperty class is a convenience class handling
+    QVariant based properties.
+
+    QtVariantProperty provides additional API: A property's type,
+    value type, attribute values and current value can easily be
+    retrieved using the propertyType(), valueType(), attributeValue()
+    and value() functions respectively. In addition, the attribute
+    values and the current value can be set using the corresponding
+    setValue() and setAttribute() functions.
+
+    For example, instead of writing:
+
+    \code
+        QtVariantPropertyManager *variantPropertyManager;
+        QtProperty *property;
+
+        variantPropertyManager->setValue(property, 10);
+    \endcode
+
+    you can write:
+
+    \code
+        QtVariantPropertyManager *variantPropertyManager;
+        QtVariantProperty *property;
+
+        property->setValue(10);
+    \endcode
+
+    QtVariantProperty instances can only be created by the
+    QtVariantPropertyManager class.
+
+    \sa QtProperty, QtVariantPropertyManager, QtVariantEditorFactory
+*/
+
+/**
+    Creates a variant property using the given \a manager.
+
+    Do not use this constructor to create variant property instances;
+    use the QtVariantPropertyManager::addProperty() function
+    instead.  This constructor is used internally by the
+    QtVariantPropertyManager::createProperty() function.
+
+    \sa QtVariantPropertyManager
+*/
+QtVariantProperty::QtVariantProperty(QtVariantPropertyManager *manager)
+    : QtProperty(manager),  d_ptr(new QtVariantPropertyPrivate(manager))
+{
+
+}
+
+/**
+    Destroys this property.
+
+    \sa QtProperty::~QtProperty()
+*/
+QtVariantProperty::~QtVariantProperty()
+{
+    delete d_ptr;
+}
+
+/**
+    Returns the property's current value.
+
+    \sa valueType(), setValue()
+*/
+QVariant QtVariantProperty::value() const
+{
+    return d_ptr->manager->value(this);
+}
+
+/**
+    Returns this property's value for the specified \a attribute.
+
+    QtVariantPropertyManager provides a couple of related functions:
+    \l{QtVariantPropertyManager::attributes()}{attributes()} and
+    \l{QtVariantPropertyManager::attributeType()}{attributeType()}.
+
+    \sa setAttribute()
+*/
+QVariant QtVariantProperty::attributeValue(const QString &attribute) const
+{
+    return d_ptr->manager->attributeValue(this, attribute);
+}
+
+/**
+    Returns the type of this property's value.
+
+    \sa propertyType()
+*/
+int QtVariantProperty::valueType() const
+{
+    return d_ptr->manager->valueType(this);
+}
+
+/**
+    Returns this property's type.
+
+    QtVariantPropertyManager provides several related functions:
+    \l{QtVariantPropertyManager::enumTypeId()}{enumTypeId()},
+    \l{QtVariantPropertyManager::flagTypeId()}{flagTypeId()} and
+    \l{QtVariantPropertyManager::groupTypeId()}{groupTypeId()}.
+
+    \sa valueType()
+*/
+int QtVariantProperty::propertyType() const
+{
+    return d_ptr->manager->propertyType(this);
+}
+
+/**
+    Sets the value of this property to \a value.
+
+    The specified \a value must be of the type returned by
+    valueType(), or of a type that can be converted to valueType()
+    using the QVariant::canConvert() function; otherwise this function
+    does nothing.
+
+    \sa value()
+*/
+void QtVariantProperty::setValue(const QVariant &value)
+{
+    d_ptr->manager->setValue(this, value);
+}
+
+/**
+    Sets the \a attribute of property to \a value.
+
+    QtVariantPropertyManager provides the related
+    \l{QtVariantPropertyManager::setAttribute()}{setAttribute()}
+    function.
+
+    \sa attributeValue()
+*/
+void QtVariantProperty::setAttribute(const QString &attribute, const QVariant &value)
+{
+    d_ptr->manager->setAttribute(this, attribute, value);
+}
+
+class QtVariantPropertyManagerPrivate
+{
+    QtVariantPropertyManager *q_ptr;
+    Q_DECLARE_PUBLIC(QtVariantPropertyManager)
+public:
+    QtVariantPropertyManagerPrivate();
+
+    bool m_creatingProperty;
+    bool m_creatingSubProperties;
+    bool m_destroyingSubProperties;
+    int m_propertyType;
+
+    void slotValueChanged(QtProperty *property, int val);
+    void slotRangeChanged(QtProperty *property, int min, int max);
+    void slotSingleStepChanged(QtProperty *property, int step);
+    void slotValueChanged(QtProperty *property, double val);
+    void slotRangeChanged(QtProperty *property, double min, double max);
+    void slotSingleStepChanged(QtProperty *property, double step);
+    void slotDecimalsChanged(QtProperty *property, int prec);
+    void slotValueChanged(QtProperty *property, bool val);
+    void slotValueChanged(QtProperty *property, const QString &val);
+    void slotRegExpChanged(QtProperty *property, const QRegExp &regExp);
+    void slotValueChanged(QtProperty *property, const QDate &val);
+    void slotRangeChanged(QtProperty *property, const QDate &min, const QDate &max);
+    void slotValueChanged(QtProperty *property, const QTime &val);
+    void slotValueChanged(QtProperty *property, const QDateTime &val);
+    void slotValueChanged(QtProperty *property, const QKeySequence &val);
+    void slotValueChanged(QtProperty *property, const QChar &val);
+    void slotValueChanged(QtProperty *property, const QLocale &val);
+    void slotValueChanged(QtProperty *property, const QPoint &val);
+    void slotValueChanged(QtProperty *property, const QPointF &val);
+    void slotValueChanged(QtProperty *property, const QSize &val);
+    void slotRangeChanged(QtProperty *property, const QSize &min, const QSize &max);
+    void slotValueChanged(QtProperty *property, const QSizeF &val);
+    void slotRangeChanged(QtProperty *property, const QSizeF &min, const QSizeF &max);
+    void slotValueChanged(QtProperty *property, const QRect &val);
+    void slotConstraintChanged(QtProperty *property, const QRect &val);
+    void slotValueChanged(QtProperty *property, const QRectF &val);
+    void slotConstraintChanged(QtProperty *property, const QRectF &val);
+    void slotValueChanged(QtProperty *property, const QColor &val);
+    void slotEnumChanged(QtProperty *property, int val);
+    void slotEnumNamesChanged(QtProperty *property, const QStringList &enumNames);
+    void slotEnumIconsChanged(QtProperty *property, const QMap<int, QIcon> &enumIcons);
+    void slotValueChanged(QtProperty *property, const QSizePolicy &val);
+    void slotValueChanged(QtProperty *property, const QFont &val);
+    void slotValueChanged(QtProperty *property, const QCursor &val);
+    void slotFlagChanged(QtProperty *property, int val);
+    void slotFlagNamesChanged(QtProperty *property, const QStringList &flagNames);
+    void slotPropertyInserted(QtProperty *property, QtProperty *parent, QtProperty *after);
+    void slotPropertyRemoved(QtProperty *property, QtProperty *parent);
+
+    void valueChanged(QtProperty *property, const QVariant &val);
+
+    int internalPropertyToType(QtProperty *property) const;
+    QtVariantProperty *createSubProperty(QtVariantProperty *parent, QtVariantProperty *after,
+            QtProperty *internal);
+    void removeSubProperty(QtVariantProperty *property);
+
+    QMap<int, QtAbstractPropertyManager *> m_typeToPropertyManager;
+    QMap<int, QMap<QString, int> > m_typeToAttributeToAttributeType;
+
+    QMap<const QtProperty *, QPair<QtVariantProperty *, int> > m_propertyToType;
+
+    QMap<int, int> m_typeToValueType;
+
+
+    QMap<QtProperty *, QtVariantProperty *> m_internalToProperty;
+
+    const QString m_constraintAttribute;
+    const QString m_singleStepAttribute;
+    const QString m_decimalsAttribute;
+    const QString m_enumIconsAttribute;
+    const QString m_enumNamesAttribute;
+    const QString m_flagNamesAttribute;
+    const QString m_maximumAttribute;
+    const QString m_minimumAttribute;
+    const QString m_regExpAttribute;
+};
+
+QtVariantPropertyManagerPrivate::QtVariantPropertyManagerPrivate() :
+    m_constraintAttribute(QLatin1String("constraint")),
+    m_singleStepAttribute(QLatin1String("singleStep")),
+    m_decimalsAttribute(QLatin1String("decimals")),
+    m_enumIconsAttribute(QLatin1String("enumIcons")),
+    m_enumNamesAttribute(QLatin1String("enumNames")),
+    m_flagNamesAttribute(QLatin1String("flagNames")),
+    m_maximumAttribute(QLatin1String("maximum")),
+    m_minimumAttribute(QLatin1String("minimum")),
+    m_regExpAttribute(QLatin1String("regExp"))
+{
+}
+
+int QtVariantPropertyManagerPrivate::internalPropertyToType(QtProperty *property) const
+{
+    int type = 0;
+    QtAbstractPropertyManager *internPropertyManager = property->propertyManager();
+    if (qobject_cast<QtIntPropertyManager *>(internPropertyManager))
+        type = QVariant::Int;
+    else if (qobject_cast<QtEnumPropertyManager *>(internPropertyManager))
+        type = QtVariantPropertyManager::enumTypeId();
+    else if (qobject_cast<QtBoolPropertyManager *>(internPropertyManager))
+        type = QVariant::Bool;
+    else if (qobject_cast<QtDoublePropertyManager *>(internPropertyManager))
+        type = QVariant::Double;
+    return type;
+}
+
+QtVariantProperty *QtVariantPropertyManagerPrivate::createSubProperty(QtVariantProperty *parent,
+            QtVariantProperty *after, QtProperty *internal)
+{
+    int type = internalPropertyToType(internal);
+    if (!type)
+        return 0;
+
+    bool wasCreatingSubProperties = m_creatingSubProperties;
+    m_creatingSubProperties = true;
+
+    QtVariantProperty *varChild = q_ptr->addProperty(type, internal->propertyName());
+
+    m_creatingSubProperties = wasCreatingSubProperties;
+
+    varChild->setPropertyName(internal->propertyName());
+    varChild->setToolTip(internal->toolTip());
+    varChild->setStatusTip(internal->statusTip());
+    varChild->setWhatsThis(internal->whatsThis());
+
+    parent->insertSubProperty(varChild, after);
+
+    m_internalToProperty[internal] = varChild;
+    propertyToWrappedProperty()->insert(varChild, internal);
+    return varChild;
+}
+
+void QtVariantPropertyManagerPrivate::removeSubProperty(QtVariantProperty *property)
+{
+    QtProperty *internChild = wrappedProperty(property);
+    bool wasDestroyingSubProperties = m_destroyingSubProperties;
+    m_destroyingSubProperties = true;
+    delete property;
+    m_destroyingSubProperties = wasDestroyingSubProperties;
+    m_internalToProperty.remove(internChild);
+    propertyToWrappedProperty()->remove(property);
+}
+
+void QtVariantPropertyManagerPrivate::slotPropertyInserted(QtProperty *property,
+            QtProperty *parent, QtProperty *after)
+{
+    if (m_creatingProperty)
+        return;
+
+    QtVariantProperty *varParent = m_internalToProperty.value(parent, 0);
+    if (!varParent)
+        return;
+
+    QtVariantProperty *varAfter = 0;
+    if (after) {
+        varAfter = m_internalToProperty.value(after, 0);
+        if (!varAfter)
+            return;
+    }
+
+    createSubProperty(varParent, varAfter, property);
+}
+
+void QtVariantPropertyManagerPrivate::slotPropertyRemoved(QtProperty *property, QtProperty *parent)
+{
+    Q_UNUSED(parent)
+
+    QtVariantProperty *varProperty = m_internalToProperty.value(property, 0);
+    if (!varProperty)
+        return;
+
+    removeSubProperty(varProperty);
+}
+
+void QtVariantPropertyManagerPrivate::valueChanged(QtProperty *property, const QVariant &val)
+{
+    QtVariantProperty *varProp = m_internalToProperty.value(property, 0);
+    if (!varProp)
+        return;
+    emit q_ptr->valueChanged(varProp, val);
+    emit q_ptr->propertyChanged(varProp);
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, int val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotRangeChanged(QtProperty *property, int min, int max)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0)) {
+        emit q_ptr->attributeChanged(varProp, m_minimumAttribute, QVariant(min));
+        emit q_ptr->attributeChanged(varProp, m_maximumAttribute, QVariant(max));
+    }
+}
+
+void QtVariantPropertyManagerPrivate::slotSingleStepChanged(QtProperty *property, int step)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
+        emit q_ptr->attributeChanged(varProp, m_singleStepAttribute, QVariant(step));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, double val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotRangeChanged(QtProperty *property, double min, double max)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0)) {
+        emit q_ptr->attributeChanged(varProp, m_minimumAttribute, QVariant(min));
+        emit q_ptr->attributeChanged(varProp, m_maximumAttribute, QVariant(max));
+    }
+}
+
+void QtVariantPropertyManagerPrivate::slotSingleStepChanged(QtProperty *property, double step)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
+        emit q_ptr->attributeChanged(varProp, m_singleStepAttribute, QVariant(step));
+}
+
+void QtVariantPropertyManagerPrivate::slotDecimalsChanged(QtProperty *property, int prec)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
+        emit q_ptr->attributeChanged(varProp, m_decimalsAttribute, QVariant(prec));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, bool val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QString &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotRegExpChanged(QtProperty *property, const QRegExp &regExp)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
+        emit q_ptr->attributeChanged(varProp, m_regExpAttribute, QVariant(regExp));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QDate &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotRangeChanged(QtProperty *property, const QDate &min, const QDate &max)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0)) {
+        emit q_ptr->attributeChanged(varProp, m_minimumAttribute, QVariant(min));
+        emit q_ptr->attributeChanged(varProp, m_maximumAttribute, QVariant(max));
+    }
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QTime &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QDateTime &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QKeySequence &val)
+{
+    QVariant v;
+    qVariantSetValue(v, val);
+    valueChanged(property, v);
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QChar &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QLocale &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QPoint &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QPointF &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QSize &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotRangeChanged(QtProperty *property, const QSize &min, const QSize &max)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0)) {
+        emit q_ptr->attributeChanged(varProp, m_minimumAttribute, QVariant(min));
+        emit q_ptr->attributeChanged(varProp, m_maximumAttribute, QVariant(max));
+    }
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QSizeF &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotRangeChanged(QtProperty *property, const QSizeF &min, const QSizeF &max)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0)) {
+        emit q_ptr->attributeChanged(varProp, m_minimumAttribute, QVariant(min));
+        emit q_ptr->attributeChanged(varProp, m_maximumAttribute, QVariant(max));
+    }
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QRect &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotConstraintChanged(QtProperty *property, const QRect &constraint)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
+        emit q_ptr->attributeChanged(varProp, m_constraintAttribute, QVariant(constraint));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QRectF &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotConstraintChanged(QtProperty *property, const QRectF &constraint)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
+        emit q_ptr->attributeChanged(varProp, m_constraintAttribute, QVariant(constraint));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QColor &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotEnumNamesChanged(QtProperty *property, const QStringList &enumNames)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
+        emit q_ptr->attributeChanged(varProp, m_enumNamesAttribute, QVariant(enumNames));
+}
+
+void QtVariantPropertyManagerPrivate::slotEnumIconsChanged(QtProperty *property, const QMap<int, QIcon> &enumIcons)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0)) {
+        QVariant v;
+        qVariantSetValue(v, enumIcons);
+        emit q_ptr->attributeChanged(varProp, m_enumIconsAttribute, v);
+    }
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QSizePolicy &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QFont &val)
+{
+    valueChanged(property, QVariant(val));
+}
+
+void QtVariantPropertyManagerPrivate::slotValueChanged(QtProperty *property, const QCursor &val)
+{
+#ifndef QT_NO_CURSOR
+    valueChanged(property, QVariant(val));
+#endif
+}
+
+void QtVariantPropertyManagerPrivate::slotFlagNamesChanged(QtProperty *property, const QStringList &flagNames)
+{
+    if (QtVariantProperty *varProp = m_internalToProperty.value(property, 0))
+        emit q_ptr->attributeChanged(varProp, m_flagNamesAttribute, QVariant(flagNames));
+}
+
+/**
+    \class QtVariantPropertyManager
+
+    \brief The QtVariantPropertyManager class provides and manages QVariant based properties.
+
+    QtVariantPropertyManager provides the addProperty() function which
+    creates QtVariantProperty objects. The QtVariantProperty class is
+    a convenience class handling QVariant based properties inheriting
+    QtProperty. A QtProperty object created by a
+    QtVariantPropertyManager instance can be converted into a
+    QtVariantProperty object using the variantProperty() function.
+
+    The property's value can be retrieved using the value(), and set
+    using the setValue() slot. In addition the property's type, and
+    the type of its value, can be retrieved using the propertyType()
+    and valueType() functions respectively.
+
+    A property's type is a QVariant::Type enumerator value, and
+    usually a property's type is the same as its value type. But for
+    some properties the types differ, for example for enums, flags and
+    group types in which case QtVariantPropertyManager provides the
+    enumTypeId(), flagTypeId() and groupTypeId() functions,
+    respectively, to identify their property type (the value types are
+    QVariant::Int for the enum and flag types, and QVariant::Invalid
+    for the group type).
+
+    Use the isPropertyTypeSupported() function to check if a particular
+    property type is supported. The currently supported property types
+    are:
+
+    \table
+    \header
+        \o Property Type
+        \o Property Type Id
+    \row
+        \o int
+        \o QVariant::Int
+    \row
+        \o double
+        \o QVariant::Double
+    \row
+        \o bool
+        \o QVariant::Bool
+    \row
+        \o QString
+        \o QVariant::String
+    \row
+        \o QDate
+        \o QVariant::Date
+    \row
+        \o QTime
+        \o QVariant::Time
+    \row
+        \o QDateTime
+        \o QVariant::DateTime
+    \row
+        \o QKeySequence
+        \o QVariant::KeySequence
+    \row
+        \o QChar
+        \o QVariant::Char
+    \row
+        \o QLocale
+        \o QVariant::Locale
+    \row
+        \o QPoint
+        \o QVariant::Point
+    \row
+        \o QPointF
+        \o QVariant::PointF
+    \row
+        \o QSize
+        \o QVariant::Size
+    \row
+        \o QSizeF
+        \o QVariant::SizeF
+    \row
+        \o QRect
+        \o QVariant::Rect
+    \row
+        \o QRectF
+        \o QVariant::RectF
+    \row
+        \o QColor
+        \o QVariant::Color
+    \row
+        \o QSizePolicy
+        \o QVariant::SizePolicy
+    \row
+        \o QFont
+        \o QVariant::Font
+    \row
+        \o QCursor
+        \o QVariant::Cursor
+    \row
+        \o enum
+        \o enumTypeId()
+    \row
+        \o flag
+        \o flagTypeId()
+    \row
+        \o group
+        \o groupTypeId()
+    \endtable
+
+    Each property type can provide additional attributes,
+    e.g. QVariant::Int and QVariant::Double provides minimum and
+    maximum values. The currently supported attributes are:
+
+    \table
+    \header
+        \o Property Type
+        \o Attribute Name
+        \o Attribute Type
+    \row
+        \o \c int
+        \o minimum
+        \o QVariant::Int
+    \row
+        \o
+        \o maximum
+        \o QVariant::Int
+    \row
+        \o
+        \o singleStep
+        \o QVariant::Int
+    \row
+        \o \c double
+        \o minimum
+        \o QVariant::Double
+    \row
+        \o
+        \o maximum
+        \o QVariant::Double
+    \row
+        \o
+        \o singleStep
+        \o QVariant::Double
+    \row
+        \o
+        \o decimals
+        \o QVariant::Int
+    \row
+        \o QString
+        \o regExp
+        \o QVariant::RegExp
+    \row
+        \o QDate
+        \o minimum
+        \o QVariant::Date
+    \row
+        \o
+        \o maximum
+        \o QVariant::Date
+    \row
+        \o QPointF
+        \o decimals
+        \o QVariant::Int
+    \row
+        \o QSize
+        \o minimum
+        \o QVariant::Size
+    \row
+        \o
+        \o maximum
+        \o QVariant::Size
+    \row
+        \o QSizeF
+        \o minimum
+        \o QVariant::SizeF
+    \row
+        \o
+        \o maximum
+        \o QVariant::SizeF
+    \row
+        \o
+        \o decimals
+        \o QVariant::Int
+    \row
+        \o QRect
+        \o constraint
+        \o QVariant::Rect
+    \row
+        \o QRectF
+        \o constraint
+        \o QVariant::RectF
+    \row
+        \o
+        \o decimals
+        \o QVariant::Int
+    \row
+        \o \c enum
+        \o enumNames
+        \o QVariant::StringList
+    \row
+        \o
+        \o enumIcons
+        \o iconMapTypeId()
+    \row
+        \o \c flag
+        \o flagNames
+        \o QVariant::StringList
+    \endtable
+
+    The attributes for a given property type can be retrieved using
+    the attributes() function. Each attribute has a value type which
+    can be retrieved using the attributeType() function, and a value
+    accessible through the attributeValue() function. In addition, the
+    value can be set using the setAttribute() slot.
+
+    QtVariantManager also provides the valueChanged() signal which is
+    emitted whenever a property created by this manager change, and
+    the attributeChanged() signal which is emitted whenever an
+    attribute of such a property changes.
+
+    \sa QtVariantProperty, QtVariantEditorFactory
+*/
+
+/**
+    \fn void QtVariantPropertyManager::valueChanged(QtProperty *property, const QVariant &value)
+
+    This signal is emitted whenever a property created by this manager
+    changes its value, passing a pointer to the \a property and the
+    new \a value as parameters.
+
+    \sa setValue()
+*/
+
+/**
+    \fn void QtVariantPropertyManager::attributeChanged(QtProperty *property,
+                const QString &attribute, const QVariant &value)
+
+    This signal is emitted whenever an attribute of a property created
+    by this manager changes its value, passing a pointer to the \a
+    property, the \a attribute and the new \a value as parameters.
+
+    \sa setAttribute()
+*/
+
+/**
+    Creates a manager with the given \a parent.
+*/
+QtVariantPropertyManager::QtVariantPropertyManager(QObject *parent)
+    : QtAbstractPropertyManager(parent)
+{
+    d_ptr = new QtVariantPropertyManagerPrivate;
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_creatingProperty = false;
+    d_ptr->m_creatingSubProperties = false;
+    d_ptr->m_destroyingSubProperties = false;
+    d_ptr->m_propertyType = 0;
+
+    // IntPropertyManager
+    QtIntPropertyManager *intPropertyManager = new QtIntPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Int] = intPropertyManager;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::Int][d_ptr->m_minimumAttribute] = QVariant::Int;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::Int][d_ptr->m_maximumAttribute] = QVariant::Int;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::Int][d_ptr->m_singleStepAttribute] = QVariant::Int;
+    d_ptr->m_typeToValueType[QVariant::Int] = QVariant::Int;
+    connect(intPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotValueChanged(QtProperty *, int)));
+    connect(intPropertyManager, SIGNAL(rangeChanged(QtProperty *, int, int)),
+                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
+    connect(intPropertyManager, SIGNAL(singleStepChanged(QtProperty *, int)),
+                this, SLOT(slotSingleStepChanged(QtProperty *, int)));
+    // DoublePropertyManager
+    QtDoublePropertyManager *doublePropertyManager = new QtDoublePropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Double] = doublePropertyManager;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::Double][d_ptr->m_minimumAttribute] =
+            QVariant::Double;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::Double][d_ptr->m_maximumAttribute] =
+            QVariant::Double;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::Double][d_ptr->m_singleStepAttribute] =
+            QVariant::Double;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::Double][d_ptr->m_decimalsAttribute] =
+            QVariant::Int;
+    d_ptr->m_typeToValueType[QVariant::Double] = QVariant::Double;
+    connect(doublePropertyManager, SIGNAL(valueChanged(QtProperty *, double)),
+                this, SLOT(slotValueChanged(QtProperty *, double)));
+    connect(doublePropertyManager, SIGNAL(rangeChanged(QtProperty *, double, double)),
+                this, SLOT(slotRangeChanged(QtProperty *, double, double)));
+    connect(doublePropertyManager, SIGNAL(singleStepChanged(QtProperty *, double)),
+                this, SLOT(slotSingleStepChanged(QtProperty *, double)));
+    connect(doublePropertyManager, SIGNAL(decimalsChanged(QtProperty *, int)),
+                this, SLOT(slotDecimalsChanged(QtProperty *, int)));
+    // BoolPropertyManager
+    QtBoolPropertyManager *boolPropertyManager = new QtBoolPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Bool] = boolPropertyManager;
+    d_ptr->m_typeToValueType[QVariant::Bool] = QVariant::Bool;
+    connect(boolPropertyManager, SIGNAL(valueChanged(QtProperty *, bool)),
+                this, SLOT(slotValueChanged(QtProperty *, bool)));
+    // StringPropertyManager
+    QtStringPropertyManager *stringPropertyManager = new QtStringPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::String] = stringPropertyManager;
+    d_ptr->m_typeToValueType[QVariant::String] = QVariant::String;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::String][d_ptr->m_regExpAttribute] =
+            QVariant::RegExp;
+    connect(stringPropertyManager, SIGNAL(valueChanged(QtProperty *, const QString &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QString &)));
+    connect(stringPropertyManager, SIGNAL(regExpChanged(QtProperty *, const QRegExp &)),
+                this, SLOT(slotRegExpChanged(QtProperty *, const QRegExp &)));
+    // DatePropertyManager
+    QtDatePropertyManager *datePropertyManager = new QtDatePropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Date] = datePropertyManager;
+    d_ptr->m_typeToValueType[QVariant::Date] = QVariant::Date;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::Date][d_ptr->m_minimumAttribute] =
+            QVariant::Date;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::Date][d_ptr->m_maximumAttribute] =
+            QVariant::Date;
+    connect(datePropertyManager, SIGNAL(valueChanged(QtProperty *, const QDate &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QDate &)));
+    connect(datePropertyManager, SIGNAL(rangeChanged(QtProperty *, const QDate &, const QDate &)),
+                this, SLOT(slotRangeChanged(QtProperty *, const QDate &, const QDate &)));
+    // TimePropertyManager
+    QtTimePropertyManager *timePropertyManager = new QtTimePropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Time] = timePropertyManager;
+    d_ptr->m_typeToValueType[QVariant::Time] = QVariant::Time;
+    connect(timePropertyManager, SIGNAL(valueChanged(QtProperty *, const QTime &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QTime &)));
+    // DateTimePropertyManager
+    QtDateTimePropertyManager *dateTimePropertyManager = new QtDateTimePropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::DateTime] = dateTimePropertyManager;
+    d_ptr->m_typeToValueType[QVariant::DateTime] = QVariant::DateTime;
+    connect(dateTimePropertyManager, SIGNAL(valueChanged(QtProperty *, const QDateTime &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QDateTime &)));
+    // KeySequencePropertyManager
+    QtKeySequencePropertyManager *keySequencePropertyManager = new QtKeySequencePropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::KeySequence] = keySequencePropertyManager;
+    d_ptr->m_typeToValueType[QVariant::KeySequence] = QVariant::KeySequence;
+    connect(keySequencePropertyManager, SIGNAL(valueChanged(QtProperty *, const QKeySequence &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QKeySequence &)));
+    // CharPropertyManager
+    QtCharPropertyManager *charPropertyManager = new QtCharPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Char] = charPropertyManager;
+    d_ptr->m_typeToValueType[QVariant::Char] = QVariant::Char;
+    connect(charPropertyManager, SIGNAL(valueChanged(QtProperty *, const QChar &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QChar &)));
+    // LocalePropertyManager
+    QtLocalePropertyManager *localePropertyManager = new QtLocalePropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Locale] = localePropertyManager;
+    d_ptr->m_typeToValueType[QVariant::Locale] = QVariant::Locale;
+    connect(localePropertyManager, SIGNAL(valueChanged(QtProperty *, const QLocale &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QLocale &)));
+    connect(localePropertyManager->subEnumPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotValueChanged(QtProperty *, int)));
+    connect(localePropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
+    connect(localePropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+    // PointPropertyManager
+    QtPointPropertyManager *pointPropertyManager = new QtPointPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Point] = pointPropertyManager;
+    d_ptr->m_typeToValueType[QVariant::Point] = QVariant::Point;
+    connect(pointPropertyManager, SIGNAL(valueChanged(QtProperty *, const QPoint &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QPoint &)));
+    connect(pointPropertyManager->subIntPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotValueChanged(QtProperty *, int)));
+    connect(pointPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
+    connect(pointPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+    // PointFPropertyManager
+    QtPointFPropertyManager *pointFPropertyManager = new QtPointFPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::PointF] = pointFPropertyManager;
+    d_ptr->m_typeToValueType[QVariant::PointF] = QVariant::PointF;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::PointF][d_ptr->m_decimalsAttribute] =
+            QVariant::Int;
+    connect(pointFPropertyManager, SIGNAL(valueChanged(QtProperty *, const QPointF &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QPointF &)));
+    connect(pointFPropertyManager, SIGNAL(decimalsChanged(QtProperty *, int)),
+                this, SLOT(slotDecimalsChanged(QtProperty *, int)));
+    connect(pointFPropertyManager->subDoublePropertyManager(), SIGNAL(valueChanged(QtProperty *, double)),
+                this, SLOT(slotValueChanged(QtProperty *, double)));
+    connect(pointFPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
+    connect(pointFPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+    // SizePropertyManager
+    QtSizePropertyManager *sizePropertyManager = new QtSizePropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Size] = sizePropertyManager;
+    d_ptr->m_typeToValueType[QVariant::Size] = QVariant::Size;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::Size][d_ptr->m_minimumAttribute] =
+            QVariant::Size;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::Size][d_ptr->m_maximumAttribute] =
+            QVariant::Size;
+    connect(sizePropertyManager, SIGNAL(valueChanged(QtProperty *, const QSize &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QSize &)));
+    connect(sizePropertyManager, SIGNAL(rangeChanged(QtProperty *, const QSize &, const QSize &)),
+                this, SLOT(slotRangeChanged(QtProperty *, const QSize &, const QSize &)));
+    connect(sizePropertyManager->subIntPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotValueChanged(QtProperty *, int)));
+    connect(sizePropertyManager->subIntPropertyManager(), SIGNAL(rangeChanged(QtProperty *, int, int)),
+                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
+    connect(sizePropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
+    connect(sizePropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+    // SizeFPropertyManager
+    QtSizeFPropertyManager *sizeFPropertyManager = new QtSizeFPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::SizeF] = sizeFPropertyManager;
+    d_ptr->m_typeToValueType[QVariant::SizeF] = QVariant::SizeF;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::SizeF][d_ptr->m_minimumAttribute] =
+            QVariant::SizeF;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::SizeF][d_ptr->m_maximumAttribute] =
+            QVariant::SizeF;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::SizeF][d_ptr->m_decimalsAttribute] =
+            QVariant::Int;
+    connect(sizeFPropertyManager, SIGNAL(valueChanged(QtProperty *, const QSizeF &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QSizeF &)));
+    connect(sizeFPropertyManager, SIGNAL(rangeChanged(QtProperty *, const QSizeF &, const QSizeF &)),
+                this, SLOT(slotRangeChanged(QtProperty *, const QSizeF &, const QSizeF &)));
+    connect(sizeFPropertyManager, SIGNAL(decimalsChanged(QtProperty *, int)),
+                this, SLOT(slotDecimalsChanged(QtProperty *, int)));
+    connect(sizeFPropertyManager->subDoublePropertyManager(), SIGNAL(valueChanged(QtProperty *, double)),
+                this, SLOT(slotValueChanged(QtProperty *, double)));
+    connect(sizeFPropertyManager->subDoublePropertyManager(), SIGNAL(rangeChanged(QtProperty *, double, double)),
+                this, SLOT(slotRangeChanged(QtProperty *, double, double)));
+    connect(sizeFPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
+    connect(sizeFPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+    // RectPropertyManager
+    QtRectPropertyManager *rectPropertyManager = new QtRectPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Rect] = rectPropertyManager;
+    d_ptr->m_typeToValueType[QVariant::Rect] = QVariant::Rect;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::Rect][d_ptr->m_constraintAttribute] =
+            QVariant::Rect;
+    connect(rectPropertyManager, SIGNAL(valueChanged(QtProperty *, const QRect &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QRect &)));
+    connect(rectPropertyManager, SIGNAL(constraintChanged(QtProperty *, const QRect &)),
+                this, SLOT(slotConstraintChanged(QtProperty *, const QRect &)));
+    connect(rectPropertyManager->subIntPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotValueChanged(QtProperty *, int)));
+    connect(rectPropertyManager->subIntPropertyManager(), SIGNAL(rangeChanged(QtProperty *, int, int)),
+                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
+    connect(rectPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
+    connect(rectPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+    // RectFPropertyManager
+    QtRectFPropertyManager *rectFPropertyManager = new QtRectFPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::RectF] = rectFPropertyManager;
+    d_ptr->m_typeToValueType[QVariant::RectF] = QVariant::RectF;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::RectF][d_ptr->m_constraintAttribute] =
+            QVariant::RectF;
+    d_ptr->m_typeToAttributeToAttributeType[QVariant::RectF][d_ptr->m_decimalsAttribute] =
+            QVariant::Int;
+    connect(rectFPropertyManager, SIGNAL(valueChanged(QtProperty *, const QRectF &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QRectF &)));
+    connect(rectFPropertyManager, SIGNAL(constraintChanged(QtProperty *, const QRectF &)),
+                this, SLOT(slotConstraintChanged(QtProperty *, const QRectF &)));
+    connect(rectFPropertyManager, SIGNAL(decimalsChanged(QtProperty *, int)),
+                this, SLOT(slotDecimalsChanged(QtProperty *, int)));
+    connect(rectFPropertyManager->subDoublePropertyManager(), SIGNAL(valueChanged(QtProperty *, double)),
+                this, SLOT(slotValueChanged(QtProperty *, double)));
+    connect(rectFPropertyManager->subDoublePropertyManager(), SIGNAL(rangeChanged(QtProperty *, double, double)),
+                this, SLOT(slotRangeChanged(QtProperty *, double, double)));
+    connect(rectFPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
+    connect(rectFPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+    // ColorPropertyManager
+    QtColorPropertyManager *colorPropertyManager = new QtColorPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Color] = colorPropertyManager;
+    d_ptr->m_typeToValueType[QVariant::Color] = QVariant::Color;
+    connect(colorPropertyManager, SIGNAL(valueChanged(QtProperty *, const QColor &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QColor &)));
+    connect(colorPropertyManager->subIntPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotValueChanged(QtProperty *, int)));
+    connect(colorPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
+    connect(colorPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+    // EnumPropertyManager
+    int enumId = enumTypeId();
+    QtEnumPropertyManager *enumPropertyManager = new QtEnumPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[enumId] = enumPropertyManager;
+    d_ptr->m_typeToValueType[enumId] = QVariant::Int;
+    d_ptr->m_typeToAttributeToAttributeType[enumId][d_ptr->m_enumNamesAttribute] =
+            QVariant::StringList;
+    d_ptr->m_typeToAttributeToAttributeType[enumId][d_ptr->m_enumIconsAttribute] =
+            iconMapTypeId();
+    connect(enumPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotValueChanged(QtProperty *, int)));
+    connect(enumPropertyManager, SIGNAL(enumNamesChanged(QtProperty *, const QStringList &)),
+                this, SLOT(slotEnumNamesChanged(QtProperty *, const QStringList &)));
+    connect(enumPropertyManager, SIGNAL(enumIconsChanged(QtProperty *, const QMap<int, QIcon> &)),
+                this, SLOT(slotEnumIconsChanged(QtProperty *, const QMap<int, QIcon> &)));
+    // SizePolicyPropertyManager
+    QtSizePolicyPropertyManager *sizePolicyPropertyManager = new QtSizePolicyPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::SizePolicy] = sizePolicyPropertyManager;
+    d_ptr->m_typeToValueType[QVariant::SizePolicy] = QVariant::SizePolicy;
+    connect(sizePolicyPropertyManager, SIGNAL(valueChanged(QtProperty *, const QSizePolicy &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QSizePolicy &)));
+    connect(sizePolicyPropertyManager->subIntPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotValueChanged(QtProperty *, int)));
+    connect(sizePolicyPropertyManager->subIntPropertyManager(), SIGNAL(rangeChanged(QtProperty *, int, int)),
+                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
+    connect(sizePolicyPropertyManager->subEnumPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotValueChanged(QtProperty *, int)));
+    connect(sizePolicyPropertyManager->subEnumPropertyManager(),
+                SIGNAL(enumNamesChanged(QtProperty *, const QStringList &)),
+                this, SLOT(slotEnumNamesChanged(QtProperty *, const QStringList &)));
+    connect(sizePolicyPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
+    connect(sizePolicyPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+    // FontPropertyManager
+    QtFontPropertyManager *fontPropertyManager = new QtFontPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Font] = fontPropertyManager;
+    d_ptr->m_typeToValueType[QVariant::Font] = QVariant::Font;
+    connect(fontPropertyManager, SIGNAL(valueChanged(QtProperty *, const QFont &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QFont &)));
+    connect(fontPropertyManager->subIntPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotValueChanged(QtProperty *, int)));
+    connect(fontPropertyManager->subIntPropertyManager(), SIGNAL(rangeChanged(QtProperty *, int, int)),
+                this, SLOT(slotRangeChanged(QtProperty *, int, int)));
+    connect(fontPropertyManager->subEnumPropertyManager(), SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotValueChanged(QtProperty *, int)));
+    connect(fontPropertyManager->subEnumPropertyManager(),
+                SIGNAL(enumNamesChanged(QtProperty *, const QStringList &)),
+                this, SLOT(slotEnumNamesChanged(QtProperty *, const QStringList &)));
+    connect(fontPropertyManager->subBoolPropertyManager(), SIGNAL(valueChanged(QtProperty *, bool)),
+                this, SLOT(slotValueChanged(QtProperty *, bool)));
+    connect(fontPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
+    connect(fontPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+    // CursorPropertyManager
+    QtCursorPropertyManager *cursorPropertyManager = new QtCursorPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[QVariant::Cursor] = cursorPropertyManager;
+    d_ptr->m_typeToValueType[QVariant::Cursor] = QVariant::Cursor;
+    connect(cursorPropertyManager, SIGNAL(valueChanged(QtProperty *, const QCursor &)),
+                this, SLOT(slotValueChanged(QtProperty *, const QCursor &)));
+    // FlagPropertyManager
+    int flagId = flagTypeId();
+    QtFlagPropertyManager *flagPropertyManager = new QtFlagPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[flagId] = flagPropertyManager;
+    d_ptr->m_typeToValueType[flagId] = QVariant::Int;
+    d_ptr->m_typeToAttributeToAttributeType[flagId][d_ptr->m_flagNamesAttribute] =
+            QVariant::StringList;
+    connect(flagPropertyManager, SIGNAL(valueChanged(QtProperty *, int)),
+                this, SLOT(slotValueChanged(QtProperty *, int)));
+    connect(flagPropertyManager, SIGNAL(flagNamesChanged(QtProperty *, const QStringList &)),
+                this, SLOT(slotFlagNamesChanged(QtProperty *, const QStringList &)));
+    connect(flagPropertyManager->subBoolPropertyManager(), SIGNAL(valueChanged(QtProperty *, bool)),
+                this, SLOT(slotValueChanged(QtProperty *, bool)));
+    connect(flagPropertyManager, SIGNAL(propertyInserted(QtProperty *, QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *)));
+    connect(flagPropertyManager, SIGNAL(propertyRemoved(QtProperty *, QtProperty *)),
+                this, SLOT(slotPropertyRemoved(QtProperty *, QtProperty *)));
+    // FlagPropertyManager
+    int groupId = groupTypeId();
+    QtGroupPropertyManager *groupPropertyManager = new QtGroupPropertyManager(this);
+    d_ptr->m_typeToPropertyManager[groupId] = groupPropertyManager;
+    d_ptr->m_typeToValueType[groupId] = QVariant::Invalid;
+}
+
+/**
+    Destroys this manager, and all the properties it has created.
+*/
+QtVariantPropertyManager::~QtVariantPropertyManager()
+{
+    clear();
+    delete d_ptr;
+}
+
+/**
+    Returns the given \a property converted into a QtVariantProperty.
+
+    If the \a property was not created by this variant manager, the
+    function returns 0.
+
+    \sa createProperty()
+*/
+QtVariantProperty *QtVariantPropertyManager::variantProperty(const QtProperty *property) const
+{
+    const QMap<const QtProperty *, QPair<QtVariantProperty *, int> >::const_iterator it = d_ptr->m_propertyToType.constFind(property);
+    if (it == d_ptr->m_propertyToType.constEnd())
+        return 0;
+    return it.value().first;
+}
+
+/**
+    Returns true if the given \a propertyType is supported by this
+    variant manager; otherwise false.
+
+    \sa propertyType()
+*/
+bool QtVariantPropertyManager::isPropertyTypeSupported(int propertyType) const
+{
+    if (d_ptr->m_typeToValueType.contains(propertyType))
+        return true;
+    return false;
+}
+
+/**
+   Creates and returns a variant property of the given \a propertyType
+   with the given \a name.
+
+   If the specified \a propertyType is not supported by this variant
+   manager, this function returns 0.
+
+   Do not use the inherited
+   QtAbstractPropertyManager::addProperty() function to create a
+   variant property (that function will always return 0 since it will
+   not be clear what type the property should have).
+
+    \sa isPropertyTypeSupported()
+*/
+QtVariantProperty *QtVariantPropertyManager::addProperty(int propertyType, const QString &name)
+{
+    if (!isPropertyTypeSupported(propertyType))
+        return 0;
+
+    bool wasCreating = d_ptr->m_creatingProperty;
+    d_ptr->m_creatingProperty = true;
+    d_ptr->m_propertyType = propertyType;
+    QtProperty *property = QtAbstractPropertyManager::addProperty(name);
+    d_ptr->m_creatingProperty = wasCreating;
+    d_ptr->m_propertyType = 0;
+
+    if (!property)
+        return 0;
+
+    return variantProperty(property);
+}
+
+/**
+    Returns the given \a property's value.
+
+    If the given \a property is not managed by this manager, this
+    function returns an invalid variant.
+
+    \sa setValue()
+*/
+QVariant QtVariantPropertyManager::value(const QtProperty *property) const
+{
+    QtProperty *internProp = propertyToWrappedProperty()->value(property, 0);
+    if (internProp == 0)
+        return QVariant();
+
+    QtAbstractPropertyManager *manager = internProp->propertyManager();
+    if (QtIntPropertyManager *intManager = qobject_cast<QtIntPropertyManager *>(manager)) {
+        return intManager->value(internProp);
+    } else if (QtDoublePropertyManager *doubleManager = qobject_cast<QtDoublePropertyManager *>(manager)) {
+        return doubleManager->value(internProp);
+    } else if (QtBoolPropertyManager *boolManager = qobject_cast<QtBoolPropertyManager *>(manager)) {
+        return boolManager->value(internProp);
+    } else if (QtStringPropertyManager *stringManager = qobject_cast<QtStringPropertyManager *>(manager)) {
+        return stringManager->value(internProp);
+    } else if (QtDatePropertyManager *dateManager = qobject_cast<QtDatePropertyManager *>(manager)) {
+        return dateManager->value(internProp);
+    } else if (QtTimePropertyManager *timeManager = qobject_cast<QtTimePropertyManager *>(manager)) {
+        return timeManager->value(internProp);
+    } else if (QtDateTimePropertyManager *dateTimeManager = qobject_cast<QtDateTimePropertyManager *>(manager)) {
+        return dateTimeManager->value(internProp);
+    } else if (QtKeySequencePropertyManager *keySequenceManager = qobject_cast<QtKeySequencePropertyManager *>(manager)) {
+        return keySequenceManager->value(internProp);
+    } else if (QtCharPropertyManager *charManager = qobject_cast<QtCharPropertyManager *>(manager)) {
+        return charManager->value(internProp);
+    } else if (QtLocalePropertyManager *localeManager = qobject_cast<QtLocalePropertyManager *>(manager)) {
+        return localeManager->value(internProp);
+    } else if (QtPointPropertyManager *pointManager = qobject_cast<QtPointPropertyManager *>(manager)) {
+        return pointManager->value(internProp);
+    } else if (QtPointFPropertyManager *pointFManager = qobject_cast<QtPointFPropertyManager *>(manager)) {
+        return pointFManager->value(internProp);
+    } else if (QtSizePropertyManager *sizeManager = qobject_cast<QtSizePropertyManager *>(manager)) {
+        return sizeManager->value(internProp);
+    } else if (QtSizeFPropertyManager *sizeFManager = qobject_cast<QtSizeFPropertyManager *>(manager)) {
+        return sizeFManager->value(internProp);
+    } else if (QtRectPropertyManager *rectManager = qobject_cast<QtRectPropertyManager *>(manager)) {
+        return rectManager->value(internProp);
+    } else if (QtRectFPropertyManager *rectFManager = qobject_cast<QtRectFPropertyManager *>(manager)) {
+        return rectFManager->value(internProp);
+    } else if (QtColorPropertyManager *colorManager = qobject_cast<QtColorPropertyManager *>(manager)) {
+        return colorManager->value(internProp);
+    } else if (QtEnumPropertyManager *enumManager = qobject_cast<QtEnumPropertyManager *>(manager)) {
+        return enumManager->value(internProp);
+    } else if (QtSizePolicyPropertyManager *sizePolicyManager =
+               qobject_cast<QtSizePolicyPropertyManager *>(manager)) {
+        return sizePolicyManager->value(internProp);
+    } else if (QtFontPropertyManager *fontManager = qobject_cast<QtFontPropertyManager *>(manager)) {
+        return fontManager->value(internProp);
+#ifndef QT_NO_CURSOR
+    } else if (QtCursorPropertyManager *cursorManager = qobject_cast<QtCursorPropertyManager *>(manager)) {
+        return cursorManager->value(internProp);
+#endif
+    } else if (QtFlagPropertyManager *flagManager = qobject_cast<QtFlagPropertyManager *>(manager)) {
+        return flagManager->value(internProp);
+    }
+    return QVariant();
+}
+
+/**
+    Returns the given \a property's value type.
+
+    \sa propertyType()
+*/
+int QtVariantPropertyManager::valueType(const QtProperty *property) const
+{
+    int propType = propertyType(property);
+    return valueType(propType);
+}
+
+/**
+    \overload
+
+    Returns the value type associated with the given \a propertyType.
+*/
+int QtVariantPropertyManager::valueType(int propertyType) const
+{
+    if (d_ptr->m_typeToValueType.contains(propertyType))
+        return d_ptr->m_typeToValueType[propertyType];
+    return 0;
+}
+
+/**
+    Returns the given \a property's type.
+
+    \sa valueType()
+*/
+int QtVariantPropertyManager::propertyType(const QtProperty *property) const
+{
+    const QMap<const QtProperty *, QPair<QtVariantProperty *, int> >::const_iterator it = d_ptr->m_propertyToType.constFind(property);
+    if (it == d_ptr->m_propertyToType.constEnd())
+        return 0;
+    return it.value().second;
+}
+
+/**
+    Returns the given \a property's value for the specified \a
+    attribute
+
+    If the given \a property was not created by \e this manager, or if
+    the specified \a attribute does not exist, this function returns
+    an invalid variant.
+
+    \sa attributes(), attributeType(), setAttribute()
+*/
+QVariant QtVariantPropertyManager::attributeValue(const QtProperty *property, const QString &attribute) const
+{
+    int propType = propertyType(property);
+    if (!propType)
+        return QVariant();
+
+    QMap<int, QMap<QString, int> >::ConstIterator it =
+            d_ptr->m_typeToAttributeToAttributeType.find(propType);
+    if (it == d_ptr->m_typeToAttributeToAttributeType.constEnd())
+        return QVariant();
+
+    QMap<QString, int> attributes = it.value();
+    QMap<QString, int>::ConstIterator itAttr = attributes.find(attribute);
+    if (itAttr == attributes.constEnd())
+        return QVariant();
+
+    QtProperty *internProp = propertyToWrappedProperty()->value(property, 0);
+    if (internProp == 0)
+        return QVariant();
+
+    QtAbstractPropertyManager *manager = internProp->propertyManager();
+    if (QtIntPropertyManager *intManager = qobject_cast<QtIntPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_maximumAttribute)
+            return intManager->maximum(internProp);
+        if (attribute == d_ptr->m_minimumAttribute)
+            return intManager->minimum(internProp);
+        if (attribute == d_ptr->m_singleStepAttribute)
+            return intManager->singleStep(internProp);
+        return QVariant();
+    } else if (QtDoublePropertyManager *doubleManager = qobject_cast<QtDoublePropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_maximumAttribute)
+            return doubleManager->maximum(internProp);
+        if (attribute == d_ptr->m_minimumAttribute)
+            return doubleManager->minimum(internProp);
+        if (attribute == d_ptr->m_singleStepAttribute)
+            return doubleManager->singleStep(internProp);
+        if (attribute == d_ptr->m_decimalsAttribute)
+            return doubleManager->decimals(internProp);
+        return QVariant();
+    } else if (QtStringPropertyManager *stringManager = qobject_cast<QtStringPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_regExpAttribute)
+            return stringManager->regExp(internProp);
+        return QVariant();
+    } else if (QtDatePropertyManager *dateManager = qobject_cast<QtDatePropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_maximumAttribute)
+            return dateManager->maximum(internProp);
+        if (attribute == d_ptr->m_minimumAttribute)
+            return dateManager->minimum(internProp);
+        return QVariant();
+    } else if (QtPointFPropertyManager *pointFManager = qobject_cast<QtPointFPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_decimalsAttribute)
+            return pointFManager->decimals(internProp);
+        return QVariant();
+    } else if (QtSizePropertyManager *sizeManager = qobject_cast<QtSizePropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_maximumAttribute)
+            return sizeManager->maximum(internProp);
+        if (attribute == d_ptr->m_minimumAttribute)
+            return sizeManager->minimum(internProp);
+        return QVariant();
+    } else if (QtSizeFPropertyManager *sizeFManager = qobject_cast<QtSizeFPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_maximumAttribute)
+            return sizeFManager->maximum(internProp);
+        if (attribute == d_ptr->m_minimumAttribute)
+            return sizeFManager->minimum(internProp);
+        if (attribute == d_ptr->m_decimalsAttribute)
+            return sizeFManager->decimals(internProp);
+        return QVariant();
+    } else if (QtRectPropertyManager *rectManager = qobject_cast<QtRectPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_constraintAttribute)
+            return rectManager->constraint(internProp);
+        return QVariant();
+    } else if (QtRectFPropertyManager *rectFManager = qobject_cast<QtRectFPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_constraintAttribute)
+            return rectFManager->constraint(internProp);
+        if (attribute == d_ptr->m_decimalsAttribute)
+            return rectFManager->decimals(internProp);
+        return QVariant();
+    } else if (QtEnumPropertyManager *enumManager = qobject_cast<QtEnumPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_enumNamesAttribute)
+            return enumManager->enumNames(internProp);
+        if (attribute == d_ptr->m_enumIconsAttribute) {
+            QVariant v;
+            qVariantSetValue(v, enumManager->enumIcons(internProp));
+            return v;
+        }
+        return QVariant();
+    } else if (QtFlagPropertyManager *flagManager = qobject_cast<QtFlagPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_flagNamesAttribute)
+            return flagManager->flagNames(internProp);
+        return QVariant();
+    }
+    return QVariant();
+}
+
+/**
+    Returns a list of the given \a propertyType 's attributes.
+
+    \sa attributeValue(), attributeType()
+*/
+QStringList QtVariantPropertyManager::attributes(int propertyType) const
+{
+    QMap<int, QMap<QString, int> >::ConstIterator it =
+            d_ptr->m_typeToAttributeToAttributeType.find(propertyType);
+    if (it == d_ptr->m_typeToAttributeToAttributeType.constEnd())
+        return QStringList();
+    return it.value().keys();
+}
+
+/**
+    Returns the type of the specified \a attribute of the given \a
+    propertyType.
+
+    If the given \a propertyType is not supported by \e this manager,
+    or if the given \a propertyType does not possess the specified \a
+    attribute, this function returns QVariant::Invalid.
+
+    \sa attributes(), valueType()
+*/
+int QtVariantPropertyManager::attributeType(int propertyType, const QString &attribute) const
+{
+    QMap<int, QMap<QString, int> >::ConstIterator it =
+            d_ptr->m_typeToAttributeToAttributeType.find(propertyType);
+    if (it == d_ptr->m_typeToAttributeToAttributeType.constEnd())
+        return 0;
+
+    QMap<QString, int> attributes = it.value();
+    QMap<QString, int>::ConstIterator itAttr = attributes.find(attribute);
+    if (itAttr == attributes.constEnd())
+        return 0;
+    return itAttr.value();
+}
+
+/**
+    \fn void QtVariantPropertyManager::setValue(QtProperty *property, const QVariant &value)
+
+    Sets the value of the given \a property to \a value.
+
+    The specified \a value must be of a type returned by valueType(),
+    or of type that can be converted to valueType() using the
+    QVariant::canConvert() function, otherwise this function does
+    nothing.
+
+    \sa value(), QtVariantProperty::setValue(), valueChanged()
+*/
+void QtVariantPropertyManager::setValue(QtProperty *property, const QVariant &val)
+{
+    int propType = val.userType();
+    if (!propType)
+        return;
+
+    int valType = valueType(property);
+
+    if (propType != valType && !val.canConvert(static_cast<QVariant::Type>(valType)))
+        return;
+
+    QtProperty *internProp = propertyToWrappedProperty()->value(property, 0);
+    if (internProp == 0)
+        return;
+
+
+    QtAbstractPropertyManager *manager = internProp->propertyManager();
+    if (QtIntPropertyManager *intManager = qobject_cast<QtIntPropertyManager *>(manager)) {
+        intManager->setValue(internProp, qVariantValue<int>(val));
+        return;
+    } else if (QtDoublePropertyManager *doubleManager = qobject_cast<QtDoublePropertyManager *>(manager)) {
+        doubleManager->setValue(internProp, qVariantValue<double>(val));
+        return;
+    } else if (QtBoolPropertyManager *boolManager = qobject_cast<QtBoolPropertyManager *>(manager)) {
+        boolManager->setValue(internProp, qVariantValue<bool>(val));
+        return;
+    } else if (QtStringPropertyManager *stringManager = qobject_cast<QtStringPropertyManager *>(manager)) {
+        stringManager->setValue(internProp, qVariantValue<QString>(val));
+        return;
+    } else if (QtDatePropertyManager *dateManager = qobject_cast<QtDatePropertyManager *>(manager)) {
+        dateManager->setValue(internProp, qVariantValue<QDate>(val));
+        return;
+    } else if (QtTimePropertyManager *timeManager = qobject_cast<QtTimePropertyManager *>(manager)) {
+        timeManager->setValue(internProp, qVariantValue<QTime>(val));
+        return;
+    } else if (QtDateTimePropertyManager *dateTimeManager = qobject_cast<QtDateTimePropertyManager *>(manager)) {
+        dateTimeManager->setValue(internProp, qVariantValue<QDateTime>(val));
+        return;
+    } else if (QtKeySequencePropertyManager *keySequenceManager = qobject_cast<QtKeySequencePropertyManager *>(manager)) {
+        keySequenceManager->setValue(internProp, qVariantValue<QKeySequence>(val));
+        return;
+    } else if (QtCharPropertyManager *charManager = qobject_cast<QtCharPropertyManager *>(manager)) {
+        charManager->setValue(internProp, qVariantValue<QChar>(val));
+        return;
+    } else if (QtLocalePropertyManager *localeManager = qobject_cast<QtLocalePropertyManager *>(manager)) {
+        localeManager->setValue(internProp, qVariantValue<QLocale>(val));
+        return;
+    } else if (QtPointPropertyManager *pointManager = qobject_cast<QtPointPropertyManager *>(manager)) {
+        pointManager->setValue(internProp, qVariantValue<QPoint>(val));
+        return;
+    } else if (QtPointFPropertyManager *pointFManager = qobject_cast<QtPointFPropertyManager *>(manager)) {
+        pointFManager->setValue(internProp, qVariantValue<QPointF>(val));
+        return;
+    } else if (QtSizePropertyManager *sizeManager = qobject_cast<QtSizePropertyManager *>(manager)) {
+        sizeManager->setValue(internProp, qVariantValue<QSize>(val));
+        return;
+    } else if (QtSizeFPropertyManager *sizeFManager = qobject_cast<QtSizeFPropertyManager *>(manager)) {
+        sizeFManager->setValue(internProp, qVariantValue<QSizeF>(val));
+        return;
+    } else if (QtRectPropertyManager *rectManager = qobject_cast<QtRectPropertyManager *>(manager)) {
+        rectManager->setValue(internProp, qVariantValue<QRect>(val));
+        return;
+    } else if (QtRectFPropertyManager *rectFManager = qobject_cast<QtRectFPropertyManager *>(manager)) {
+        rectFManager->setValue(internProp, qVariantValue<QRectF>(val));
+        return;
+    } else if (QtColorPropertyManager *colorManager = qobject_cast<QtColorPropertyManager *>(manager)) {
+        colorManager->setValue(internProp, qVariantValue<QColor>(val));
+        return;
+    } else if (QtEnumPropertyManager *enumManager = qobject_cast<QtEnumPropertyManager *>(manager)) {
+        enumManager->setValue(internProp, qVariantValue<int>(val));
+        return;
+    } else if (QtSizePolicyPropertyManager *sizePolicyManager =
+               qobject_cast<QtSizePolicyPropertyManager *>(manager)) {
+        sizePolicyManager->setValue(internProp, qVariantValue<QSizePolicy>(val));
+        return;
+    } else if (QtFontPropertyManager *fontManager = qobject_cast<QtFontPropertyManager *>(manager)) {
+        fontManager->setValue(internProp, qVariantValue<QFont>(val));
+        return;
+#ifndef QT_NO_CURSOR
+    } else if (QtCursorPropertyManager *cursorManager = qobject_cast<QtCursorPropertyManager *>(manager)) {
+        cursorManager->setValue(internProp, qVariantValue<QCursor>(val));
+        return;
+#endif
+    } else if (QtFlagPropertyManager *flagManager = qobject_cast<QtFlagPropertyManager *>(manager)) {
+        flagManager->setValue(internProp, qVariantValue<int>(val));
+        return;
+    }
+}
+
+/**
+    Sets the value of the specified \a attribute of the given \a
+    property, to \a value.
+
+    The new \a value's type must be of the type returned by
+    attributeType(), or of a type that can be converted to
+    attributeType() using the QVariant::canConvert() function,
+    otherwise this function does nothing.
+
+    \sa attributeValue(), QtVariantProperty::setAttribute(), attributeChanged()
+*/
+void QtVariantPropertyManager::setAttribute(QtProperty *property,
+        const QString &attribute, const QVariant &value)
+{
+    QVariant oldAttr = attributeValue(property, attribute);
+    if (!oldAttr.isValid())
+        return;
+
+    int attrType = value.userType();
+    if (!attrType)
+        return;
+
+    if (attrType != attributeType(propertyType(property), attribute) &&
+                !value.canConvert((QVariant::Type)attrType))
+        return;
+
+    QtProperty *internProp = propertyToWrappedProperty()->value(property, 0);
+    if (internProp == 0)
+        return;
+
+    QtAbstractPropertyManager *manager = internProp->propertyManager();
+    if (QtIntPropertyManager *intManager = qobject_cast<QtIntPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_maximumAttribute)
+            intManager->setMaximum(internProp, qVariantValue<int>(value));
+        else if (attribute == d_ptr->m_minimumAttribute)
+            intManager->setMinimum(internProp, qVariantValue<int>(value));
+        else if (attribute == d_ptr->m_singleStepAttribute)
+            intManager->setSingleStep(internProp, qVariantValue<int>(value));
+        return;
+    } else if (QtDoublePropertyManager *doubleManager = qobject_cast<QtDoublePropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_maximumAttribute)
+            doubleManager->setMaximum(internProp, qVariantValue<double>(value));
+        if (attribute == d_ptr->m_minimumAttribute)
+            doubleManager->setMinimum(internProp, qVariantValue<double>(value));
+        if (attribute == d_ptr->m_singleStepAttribute)
+            doubleManager->setSingleStep(internProp, qVariantValue<double>(value));
+        if (attribute == d_ptr->m_decimalsAttribute)
+            doubleManager->setDecimals(internProp, qVariantValue<int>(value));
+        return;
+    } else if (QtStringPropertyManager *stringManager = qobject_cast<QtStringPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_regExpAttribute)
+            stringManager->setRegExp(internProp, qVariantValue<QRegExp>(value));
+        return;
+    } else if (QtDatePropertyManager *dateManager = qobject_cast<QtDatePropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_maximumAttribute)
+            dateManager->setMaximum(internProp, qVariantValue<QDate>(value));
+        if (attribute == d_ptr->m_minimumAttribute)
+            dateManager->setMinimum(internProp, qVariantValue<QDate>(value));
+        return;
+    } else if (QtPointFPropertyManager *pointFManager = qobject_cast<QtPointFPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_decimalsAttribute)
+            pointFManager->setDecimals(internProp, qVariantValue<int>(value));
+        return;
+    } else if (QtSizePropertyManager *sizeManager = qobject_cast<QtSizePropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_maximumAttribute)
+            sizeManager->setMaximum(internProp, qVariantValue<QSize>(value));
+        if (attribute == d_ptr->m_minimumAttribute)
+            sizeManager->setMinimum(internProp, qVariantValue<QSize>(value));
+        return;
+    } else if (QtSizeFPropertyManager *sizeFManager = qobject_cast<QtSizeFPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_maximumAttribute)
+            sizeFManager->setMaximum(internProp, qVariantValue<QSizeF>(value));
+        if (attribute == d_ptr->m_minimumAttribute)
+            sizeFManager->setMinimum(internProp, qVariantValue<QSizeF>(value));
+        if (attribute == d_ptr->m_decimalsAttribute)
+            sizeFManager->setDecimals(internProp, qVariantValue<int>(value));
+        return;
+    } else if (QtRectPropertyManager *rectManager = qobject_cast<QtRectPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_constraintAttribute)
+            rectManager->setConstraint(internProp, qVariantValue<QRect>(value));
+        return;
+    } else if (QtRectFPropertyManager *rectFManager = qobject_cast<QtRectFPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_constraintAttribute)
+            rectFManager->setConstraint(internProp, qVariantValue<QRectF>(value));
+        if (attribute == d_ptr->m_decimalsAttribute)
+            rectFManager->setDecimals(internProp, qVariantValue<int>(value));
+        return;
+    } else if (QtEnumPropertyManager *enumManager = qobject_cast<QtEnumPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_enumNamesAttribute)
+            enumManager->setEnumNames(internProp, qVariantValue<QStringList>(value));
+        if (attribute == d_ptr->m_enumIconsAttribute)
+            enumManager->setEnumIcons(internProp, qVariantValue<QtIconMap>(value));
+        return;
+    } else if (QtFlagPropertyManager *flagManager = qobject_cast<QtFlagPropertyManager *>(manager)) {
+        if (attribute == d_ptr->m_flagNamesAttribute)
+            flagManager->setFlagNames(internProp, qVariantValue<QStringList>(value));
+        return;
+    }
+}
+
+/**
+    \reimp
+*/
+bool QtVariantPropertyManager::hasValue(const QtProperty *property) const
+{
+    if (propertyType(property) == groupTypeId())
+        return false;
+    return true;
+}
+
+/**
+    \reimp
+*/
+QString QtVariantPropertyManager::valueText(const QtProperty *property) const
+{
+    const QtProperty *internProp = propertyToWrappedProperty()->value(property, 0);
+    return internProp ? internProp->valueText() : QString();
+}
+
+/**
+    \reimp
+*/
+QIcon QtVariantPropertyManager::valueIcon(const QtProperty *property) const
+{
+    const QtProperty *internProp = propertyToWrappedProperty()->value(property, 0);
+    return internProp ? internProp->valueIcon() : QIcon();
+}
+
+/**
+    \reimp
+*/
+void QtVariantPropertyManager::initializeProperty(QtProperty *property)
+{
+    QtVariantProperty *varProp = variantProperty(property);
+    if (!varProp)
+        return;
+
+    QMap<int, QtAbstractPropertyManager *>::ConstIterator it =
+            d_ptr->m_typeToPropertyManager.find(d_ptr->m_propertyType);
+    if (it != d_ptr->m_typeToPropertyManager.constEnd()) {
+        QtProperty *internProp = 0;
+        if (!d_ptr->m_creatingSubProperties) {
+            QtAbstractPropertyManager *manager = it.value();
+            internProp = manager->addProperty();
+            d_ptr->m_internalToProperty[internProp] = varProp;
+        }
+        propertyToWrappedProperty()->insert(varProp, internProp);
+        if (internProp) {
+            QList<QtProperty *> children = internProp->subProperties();
+            QListIterator<QtProperty *> itChild(children);
+            QtVariantProperty *lastProperty = 0;
+            while (itChild.hasNext()) {
+                QtVariantProperty *prop = d_ptr->createSubProperty(varProp, lastProperty, itChild.next());
+                lastProperty = prop ? prop : lastProperty;
+            }
+        }
+    }
+}
+
+/**
+    \reimp
+*/
+void QtVariantPropertyManager::uninitializeProperty(QtProperty *property)
+{
+    const QMap<const QtProperty *, QPair<QtVariantProperty *, int> >::iterator type_it = d_ptr->m_propertyToType.find(property);
+    if (type_it == d_ptr->m_propertyToType.end())
+        return;
+
+    PropertyMap::iterator it = propertyToWrappedProperty()->find(property);
+    if (it != propertyToWrappedProperty()->end()) {
+        QtProperty *internProp = it.value();
+        if (internProp) {
+            d_ptr->m_internalToProperty.remove(internProp);
+            if (!d_ptr->m_destroyingSubProperties) {
+                delete internProp;
+            }
+        }
+        propertyToWrappedProperty()->erase(it);
+    }
+    d_ptr->m_propertyToType.erase(type_it);
+}
+
+/**
+    \reimp
+*/
+QtProperty *QtVariantPropertyManager::createProperty()
+{
+    if (!d_ptr->m_creatingProperty)
+        return 0;
+
+    QtVariantProperty *property = new QtVariantProperty(this);
+    d_ptr->m_propertyToType.insert(property, qMakePair(property, d_ptr->m_propertyType));
+
+    return property;
+}
+
+/////////////////////////////
+
+class QtVariantEditorFactoryPrivate
+{
+    QtVariantEditorFactory *q_ptr;
+    Q_DECLARE_PUBLIC(QtVariantEditorFactory)
+public:
+
+    QtSpinBoxFactory           *m_spinBoxFactory;
+    QtDoubleSpinBoxFactory     *m_doubleSpinBoxFactory;
+    QtCheckBoxFactory          *m_checkBoxFactory;
+    QtLineEditFactory          *m_lineEditFactory;
+    QtDateEditFactory          *m_dateEditFactory;
+    QtTimeEditFactory          *m_timeEditFactory;
+    QtDateTimeEditFactory      *m_dateTimeEditFactory;
+    QtKeySequenceEditorFactory *m_keySequenceEditorFactory;
+    QtCharEditorFactory        *m_charEditorFactory;
+    QtEnumEditorFactory        *m_comboBoxFactory;
+    QtCursorEditorFactory      *m_cursorEditorFactory;
+    QtColorEditorFactory       *m_colorEditorFactory;
+    QtFontEditorFactory        *m_fontEditorFactory;
+
+    QMap<QtAbstractEditorFactoryBase *, int> m_factoryToType;
+    QMap<int, QtAbstractEditorFactoryBase *> m_typeToFactory;
+};
+
+/**
+    \class QtVariantEditorFactory
+
+    \brief The QtVariantEditorFactory class provides widgets for properties
+    created by QtVariantPropertyManager objects.
+
+    The variant factory provides the following widgets for the
+    specified property types:
+
+    \table
+    \header
+        \o Property Type
+        \o Widget
+    \row
+        \o \c int
+        \o QSpinBox
+    \row
+        \o \c double
+        \o QDoubleSpinBox
+    \row
+        \o \c bool
+        \o QCheckBox
+    \row
+        \o QString
+        \o QLineEdit
+    \row
+        \o QDate
+        \o QDateEdit
+    \row
+        \o QTime
+        \o QTimeEdit
+    \row
+        \o QDateTime
+        \o QDateTimeEdit
+    \row
+        \o QKeySequence
+        \o customized editor
+    \row
+        \o QChar
+        \o customized editor
+    \row
+        \o \c enum
+        \o QComboBox
+    \row
+        \o QCursor
+        \o QComboBox
+    \endtable
+
+    Note that QtVariantPropertyManager supports several additional property
+    types for which the QtVariantEditorFactory class does not provide
+    editing widgets, e.g. QPoint and QSize. To provide widgets for other
+    types using the variant approach, derive from the QtVariantEditorFactory
+    class.
+
+    \sa QtAbstractEditorFactory, QtVariantPropertyManager
+*/
+
+/**
+    Creates a factory with the given \a parent.
+*/
+QtVariantEditorFactory::QtVariantEditorFactory(QObject *parent)
+    : QtAbstractEditorFactory<QtVariantPropertyManager>(parent)
+{
+    d_ptr = new QtVariantEditorFactoryPrivate();
+    d_ptr->q_ptr = this;
+
+    d_ptr->m_spinBoxFactory = new QtSpinBoxFactory(this);
+    d_ptr->m_factoryToType[d_ptr->m_spinBoxFactory] = QVariant::Int;
+    d_ptr->m_typeToFactory[QVariant::Int] = d_ptr->m_spinBoxFactory;
+
+    d_ptr->m_doubleSpinBoxFactory = new QtDoubleSpinBoxFactory(this);
+    d_ptr->m_factoryToType[d_ptr->m_doubleSpinBoxFactory] = QVariant::Double;
+    d_ptr->m_typeToFactory[QVariant::Double] = d_ptr->m_doubleSpinBoxFactory;
+
+    d_ptr->m_checkBoxFactory = new QtCheckBoxFactory(this);
+    d_ptr->m_factoryToType[d_ptr->m_checkBoxFactory] = QVariant::Bool;
+    d_ptr->m_typeToFactory[QVariant::Bool] = d_ptr->m_checkBoxFactory;
+
+    d_ptr->m_lineEditFactory = new QtLineEditFactory(this);
+    d_ptr->m_factoryToType[d_ptr->m_lineEditFactory] = QVariant::String;
+    d_ptr->m_typeToFactory[QVariant::String] = d_ptr->m_lineEditFactory;
+
+    d_ptr->m_dateEditFactory = new QtDateEditFactory(this);
+    d_ptr->m_factoryToType[d_ptr->m_dateEditFactory] = QVariant::Date;
+    d_ptr->m_typeToFactory[QVariant::Date] = d_ptr->m_dateEditFactory;
+
+    d_ptr->m_timeEditFactory = new QtTimeEditFactory(this);
+    d_ptr->m_factoryToType[d_ptr->m_timeEditFactory] = QVariant::Time;
+    d_ptr->m_typeToFactory[QVariant::Time] = d_ptr->m_timeEditFactory;
+
+    d_ptr->m_dateTimeEditFactory = new QtDateTimeEditFactory(this);
+    d_ptr->m_factoryToType[d_ptr->m_dateTimeEditFactory] = QVariant::DateTime;
+    d_ptr->m_typeToFactory[QVariant::DateTime] = d_ptr->m_dateTimeEditFactory;
+
+    d_ptr->m_keySequenceEditorFactory = new QtKeySequenceEditorFactory(this);
+    d_ptr->m_factoryToType[d_ptr->m_keySequenceEditorFactory] = QVariant::KeySequence;
+    d_ptr->m_typeToFactory[QVariant::KeySequence] = d_ptr->m_keySequenceEditorFactory;
+
+    d_ptr->m_charEditorFactory = new QtCharEditorFactory(this);
+    d_ptr->m_factoryToType[d_ptr->m_charEditorFactory] = QVariant::Char;
+    d_ptr->m_typeToFactory[QVariant::Char] = d_ptr->m_charEditorFactory;
+
+    d_ptr->m_cursorEditorFactory = new QtCursorEditorFactory(this);
+    d_ptr->m_factoryToType[d_ptr->m_cursorEditorFactory] = QVariant::Cursor;
+    d_ptr->m_typeToFactory[QVariant::Cursor] = d_ptr->m_cursorEditorFactory;
+
+    d_ptr->m_colorEditorFactory = new QtColorEditorFactory(this);
+    d_ptr->m_factoryToType[d_ptr->m_colorEditorFactory] = QVariant::Color;
+    d_ptr->m_typeToFactory[QVariant::Color] = d_ptr->m_colorEditorFactory;
+
+    d_ptr->m_fontEditorFactory = new QtFontEditorFactory(this);
+    d_ptr->m_factoryToType[d_ptr->m_fontEditorFactory] = QVariant::Font;
+    d_ptr->m_typeToFactory[QVariant::Font] = d_ptr->m_fontEditorFactory;
+
+    d_ptr->m_comboBoxFactory = new QtEnumEditorFactory(this);
+    const int enumId = QtVariantPropertyManager::enumTypeId();
+    d_ptr->m_factoryToType[d_ptr->m_comboBoxFactory] = enumId;
+    d_ptr->m_typeToFactory[enumId] = d_ptr->m_comboBoxFactory;
+}
+
+/**
+    Destroys this factory, and all the widgets it has created.
+*/
+QtVariantEditorFactory::~QtVariantEditorFactory()
+{
+    delete d_ptr;
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtVariantEditorFactory::connectPropertyManager(QtVariantPropertyManager *manager)
+{
+    QList<QtIntPropertyManager *> intPropertyManagers = qFindChildren<QtIntPropertyManager *>(manager);
+    QListIterator<QtIntPropertyManager *> itInt(intPropertyManagers);
+    while (itInt.hasNext())
+        d_ptr->m_spinBoxFactory->addPropertyManager(itInt.next());
+
+    QList<QtDoublePropertyManager *> doublePropertyManagers = qFindChildren<QtDoublePropertyManager *>(manager);
+    QListIterator<QtDoublePropertyManager *> itDouble(doublePropertyManagers);
+    while (itDouble.hasNext())
+        d_ptr->m_doubleSpinBoxFactory->addPropertyManager(itDouble.next());
+
+    QList<QtBoolPropertyManager *> boolPropertyManagers = qFindChildren<QtBoolPropertyManager *>(manager);
+    QListIterator<QtBoolPropertyManager *> itBool(boolPropertyManagers);
+    while (itBool.hasNext())
+        d_ptr->m_checkBoxFactory->addPropertyManager(itBool.next());
+
+    QList<QtStringPropertyManager *> stringPropertyManagers = qFindChildren<QtStringPropertyManager *>(manager);
+    QListIterator<QtStringPropertyManager *> itString(stringPropertyManagers);
+    while (itString.hasNext())
+        d_ptr->m_lineEditFactory->addPropertyManager(itString.next());
+
+    QList<QtDatePropertyManager *> datePropertyManagers = qFindChildren<QtDatePropertyManager *>(manager);
+    QListIterator<QtDatePropertyManager *> itDate(datePropertyManagers);
+    while (itDate.hasNext())
+        d_ptr->m_dateEditFactory->addPropertyManager(itDate.next());
+
+    QList<QtTimePropertyManager *> timePropertyManagers = qFindChildren<QtTimePropertyManager *>(manager);
+    QListIterator<QtTimePropertyManager *> itTime(timePropertyManagers);
+    while (itTime.hasNext())
+        d_ptr->m_timeEditFactory->addPropertyManager(itTime.next());
+
+    QList<QtDateTimePropertyManager *> dateTimePropertyManagers = qFindChildren<QtDateTimePropertyManager *>(manager);
+    QListIterator<QtDateTimePropertyManager *> itDateTime(dateTimePropertyManagers);
+    while (itDateTime.hasNext())
+        d_ptr->m_dateTimeEditFactory->addPropertyManager(itDateTime.next());
+
+    QList<QtKeySequencePropertyManager *> keySequencePropertyManagers = qFindChildren<QtKeySequencePropertyManager *>(manager);
+    QListIterator<QtKeySequencePropertyManager *> itKeySequence(keySequencePropertyManagers);
+    while (itKeySequence.hasNext())
+        d_ptr->m_keySequenceEditorFactory->addPropertyManager(itKeySequence.next());
+
+    QList<QtCharPropertyManager *> charPropertyManagers = qFindChildren<QtCharPropertyManager *>(manager);
+    QListIterator<QtCharPropertyManager *> itChar(charPropertyManagers);
+    while (itChar.hasNext())
+        d_ptr->m_charEditorFactory->addPropertyManager(itChar.next());
+
+    QList<QtLocalePropertyManager *> localePropertyManagers = qFindChildren<QtLocalePropertyManager *>(manager);
+    QListIterator<QtLocalePropertyManager *> itLocale(localePropertyManagers);
+    while (itLocale.hasNext())
+        d_ptr->m_comboBoxFactory->addPropertyManager(itLocale.next()->subEnumPropertyManager());
+
+    QList<QtPointPropertyManager *> pointPropertyManagers = qFindChildren<QtPointPropertyManager *>(manager);
+    QListIterator<QtPointPropertyManager *> itPoint(pointPropertyManagers);
+    while (itPoint.hasNext())
+        d_ptr->m_spinBoxFactory->addPropertyManager(itPoint.next()->subIntPropertyManager());
+
+    QList<QtPointFPropertyManager *> pointFPropertyManagers = qFindChildren<QtPointFPropertyManager *>(manager);
+    QListIterator<QtPointFPropertyManager *> itPointF(pointFPropertyManagers);
+    while (itPointF.hasNext())
+        d_ptr->m_doubleSpinBoxFactory->addPropertyManager(itPointF.next()->subDoublePropertyManager());
+
+    QList<QtSizePropertyManager *> sizePropertyManagers = qFindChildren<QtSizePropertyManager *>(manager);
+    QListIterator<QtSizePropertyManager *> itSize(sizePropertyManagers);
+    while (itSize.hasNext())
+        d_ptr->m_spinBoxFactory->addPropertyManager(itSize.next()->subIntPropertyManager());
+
+    QList<QtSizeFPropertyManager *> sizeFPropertyManagers = qFindChildren<QtSizeFPropertyManager *>(manager);
+    QListIterator<QtSizeFPropertyManager *> itSizeF(sizeFPropertyManagers);
+    while (itSizeF.hasNext())
+        d_ptr->m_doubleSpinBoxFactory->addPropertyManager(itSizeF.next()->subDoublePropertyManager());
+
+    QList<QtRectPropertyManager *> rectPropertyManagers = qFindChildren<QtRectPropertyManager *>(manager);
+    QListIterator<QtRectPropertyManager *> itRect(rectPropertyManagers);
+    while (itRect.hasNext())
+        d_ptr->m_spinBoxFactory->addPropertyManager(itRect.next()->subIntPropertyManager());
+
+    QList<QtRectFPropertyManager *> rectFPropertyManagers = qFindChildren<QtRectFPropertyManager *>(manager);
+    QListIterator<QtRectFPropertyManager *> itRectF(rectFPropertyManagers);
+    while (itRectF.hasNext())
+        d_ptr->m_doubleSpinBoxFactory->addPropertyManager(itRectF.next()->subDoublePropertyManager());
+
+    QList<QtColorPropertyManager *> colorPropertyManagers = qFindChildren<QtColorPropertyManager *>(manager);
+    QListIterator<QtColorPropertyManager *> itColor(colorPropertyManagers);
+    while (itColor.hasNext()) {
+        QtColorPropertyManager *manager = itColor.next();
+        d_ptr->m_colorEditorFactory->addPropertyManager(manager);
+        d_ptr->m_spinBoxFactory->addPropertyManager(manager->subIntPropertyManager());
+    }
+
+    QList<QtEnumPropertyManager *> enumPropertyManagers = qFindChildren<QtEnumPropertyManager *>(manager);
+    QListIterator<QtEnumPropertyManager *> itEnum(enumPropertyManagers);
+    while (itEnum.hasNext())
+        d_ptr->m_comboBoxFactory->addPropertyManager(itEnum.next());
+
+    QList<QtSizePolicyPropertyManager *> sizePolicyPropertyManagers = qFindChildren<QtSizePolicyPropertyManager *>(manager);
+    QListIterator<QtSizePolicyPropertyManager *> itSizePolicy(sizePolicyPropertyManagers);
+    while (itSizePolicy.hasNext()) {
+        QtSizePolicyPropertyManager *manager = itSizePolicy.next();
+        d_ptr->m_spinBoxFactory->addPropertyManager(manager->subIntPropertyManager());
+        d_ptr->m_comboBoxFactory->addPropertyManager(manager->subEnumPropertyManager());
+    }
+
+    QList<QtFontPropertyManager *> fontPropertyManagers = qFindChildren<QtFontPropertyManager *>(manager);
+    QListIterator<QtFontPropertyManager *> itFont(fontPropertyManagers);
+    while (itFont.hasNext()) {
+        QtFontPropertyManager *manager = itFont.next();
+        d_ptr->m_fontEditorFactory->addPropertyManager(manager);
+        d_ptr->m_spinBoxFactory->addPropertyManager(manager->subIntPropertyManager());
+        d_ptr->m_comboBoxFactory->addPropertyManager(manager->subEnumPropertyManager());
+        d_ptr->m_checkBoxFactory->addPropertyManager(manager->subBoolPropertyManager());
+    }
+
+    QList<QtCursorPropertyManager *> cursorPropertyManagers = qFindChildren<QtCursorPropertyManager *>(manager);
+    QListIterator<QtCursorPropertyManager *> itCursor(cursorPropertyManagers);
+    while (itCursor.hasNext())
+        d_ptr->m_cursorEditorFactory->addPropertyManager(itCursor.next());
+
+    QList<QtFlagPropertyManager *> flagPropertyManagers = qFindChildren<QtFlagPropertyManager *>(manager);
+    QListIterator<QtFlagPropertyManager *> itFlag(flagPropertyManagers);
+    while (itFlag.hasNext())
+        d_ptr->m_checkBoxFactory->addPropertyManager(itFlag.next()->subBoolPropertyManager());
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+QWidget *QtVariantEditorFactory::createEditor(QtVariantPropertyManager *manager, QtProperty *property,
+        QWidget *parent)
+{
+    const int propType = manager->propertyType(property);
+    QtAbstractEditorFactoryBase *factory = d_ptr->m_typeToFactory.value(propType, 0);
+    if (!factory)
+        return 0;
+    return factory->createEditor(wrappedProperty(property), parent);
+}
+
+/**
+    \internal
+
+    Reimplemented from the QtAbstractEditorFactory class.
+*/
+void QtVariantEditorFactory::disconnectPropertyManager(QtVariantPropertyManager *manager)
+{
+    QList<QtIntPropertyManager *> intPropertyManagers = qFindChildren<QtIntPropertyManager *>(manager);
+    QListIterator<QtIntPropertyManager *> itInt(intPropertyManagers);
+    while (itInt.hasNext())
+        d_ptr->m_spinBoxFactory->removePropertyManager(itInt.next());
+
+    QList<QtDoublePropertyManager *> doublePropertyManagers = qFindChildren<QtDoublePropertyManager *>(manager);
+    QListIterator<QtDoublePropertyManager *> itDouble(doublePropertyManagers);
+    while (itDouble.hasNext())
+        d_ptr->m_doubleSpinBoxFactory->removePropertyManager(itDouble.next());
+
+    QList<QtBoolPropertyManager *> boolPropertyManagers = qFindChildren<QtBoolPropertyManager *>(manager);
+    QListIterator<QtBoolPropertyManager *> itBool(boolPropertyManagers);
+    while (itBool.hasNext())
+        d_ptr->m_checkBoxFactory->removePropertyManager(itBool.next());
+
+    QList<QtStringPropertyManager *> stringPropertyManagers = qFindChildren<QtStringPropertyManager *>(manager);
+    QListIterator<QtStringPropertyManager *> itString(stringPropertyManagers);
+    while (itString.hasNext())
+        d_ptr->m_lineEditFactory->removePropertyManager(itString.next());
+
+    QList<QtDatePropertyManager *> datePropertyManagers = qFindChildren<QtDatePropertyManager *>(manager);
+    QListIterator<QtDatePropertyManager *> itDate(datePropertyManagers);
+    while (itDate.hasNext())
+        d_ptr->m_dateEditFactory->removePropertyManager(itDate.next());
+
+    QList<QtTimePropertyManager *> timePropertyManagers = qFindChildren<QtTimePropertyManager *>(manager);
+    QListIterator<QtTimePropertyManager *> itTime(timePropertyManagers);
+    while (itTime.hasNext())
+        d_ptr->m_timeEditFactory->removePropertyManager(itTime.next());
+
+    QList<QtDateTimePropertyManager *> dateTimePropertyManagers = qFindChildren<QtDateTimePropertyManager *>(manager);
+    QListIterator<QtDateTimePropertyManager *> itDateTime(dateTimePropertyManagers);
+    while (itDateTime.hasNext())
+        d_ptr->m_dateTimeEditFactory->removePropertyManager(itDateTime.next());
+
+    QList<QtKeySequencePropertyManager *> keySequencePropertyManagers = qFindChildren<QtKeySequencePropertyManager *>(manager);
+    QListIterator<QtKeySequencePropertyManager *> itKeySequence(keySequencePropertyManagers);
+    while (itKeySequence.hasNext())
+        d_ptr->m_keySequenceEditorFactory->removePropertyManager(itKeySequence.next());
+
+    QList<QtCharPropertyManager *> charPropertyManagers = qFindChildren<QtCharPropertyManager *>(manager);
+    QListIterator<QtCharPropertyManager *> itChar(charPropertyManagers);
+    while (itChar.hasNext())
+        d_ptr->m_charEditorFactory->removePropertyManager(itChar.next());
+
+    QList<QtLocalePropertyManager *> localePropertyManagers = qFindChildren<QtLocalePropertyManager *>(manager);
+    QListIterator<QtLocalePropertyManager *> itLocale(localePropertyManagers);
+    while (itLocale.hasNext())
+        d_ptr->m_comboBoxFactory->removePropertyManager(itLocale.next()->subEnumPropertyManager());
+
+    QList<QtPointPropertyManager *> pointPropertyManagers = qFindChildren<QtPointPropertyManager *>(manager);
+    QListIterator<QtPointPropertyManager *> itPoint(pointPropertyManagers);
+    while (itPoint.hasNext())
+        d_ptr->m_spinBoxFactory->removePropertyManager(itPoint.next()->subIntPropertyManager());
+
+    QList<QtPointFPropertyManager *> pointFPropertyManagers = qFindChildren<QtPointFPropertyManager *>(manager);
+    QListIterator<QtPointFPropertyManager *> itPointF(pointFPropertyManagers);
+    while (itPointF.hasNext())
+        d_ptr->m_doubleSpinBoxFactory->removePropertyManager(itPointF.next()->subDoublePropertyManager());
+
+    QList<QtSizePropertyManager *> sizePropertyManagers = qFindChildren<QtSizePropertyManager *>(manager);
+    QListIterator<QtSizePropertyManager *> itSize(sizePropertyManagers);
+    while (itSize.hasNext())
+        d_ptr->m_spinBoxFactory->removePropertyManager(itSize.next()->subIntPropertyManager());
+
+    QList<QtSizeFPropertyManager *> sizeFPropertyManagers = qFindChildren<QtSizeFPropertyManager *>(manager);
+    QListIterator<QtSizeFPropertyManager *> itSizeF(sizeFPropertyManagers);
+    while (itSizeF.hasNext())
+        d_ptr->m_doubleSpinBoxFactory->removePropertyManager(itSizeF.next()->subDoublePropertyManager());
+
+    QList<QtRectPropertyManager *> rectPropertyManagers = qFindChildren<QtRectPropertyManager *>(manager);
+    QListIterator<QtRectPropertyManager *> itRect(rectPropertyManagers);
+    while (itRect.hasNext())
+        d_ptr->m_spinBoxFactory->removePropertyManager(itRect.next()->subIntPropertyManager());
+
+    QList<QtRectFPropertyManager *> rectFPropertyManagers = qFindChildren<QtRectFPropertyManager *>(manager);
+    QListIterator<QtRectFPropertyManager *> itRectF(rectFPropertyManagers);
+    while (itRectF.hasNext())
+        d_ptr->m_doubleSpinBoxFactory->removePropertyManager(itRectF.next()->subDoublePropertyManager());
+
+    QList<QtColorPropertyManager *> colorPropertyManagers = qFindChildren<QtColorPropertyManager *>(manager);
+    QListIterator<QtColorPropertyManager *> itColor(colorPropertyManagers);
+    while (itColor.hasNext()) {
+        QtColorPropertyManager *manager = itColor.next();
+        d_ptr->m_colorEditorFactory->removePropertyManager(manager);
+        d_ptr->m_spinBoxFactory->removePropertyManager(manager->subIntPropertyManager());
+    }
+
+    QList<QtEnumPropertyManager *> enumPropertyManagers = qFindChildren<QtEnumPropertyManager *>(manager);
+    QListIterator<QtEnumPropertyManager *> itEnum(enumPropertyManagers);
+    while (itEnum.hasNext())
+        d_ptr->m_comboBoxFactory->removePropertyManager(itEnum.next());
+
+    QList<QtSizePolicyPropertyManager *> sizePolicyPropertyManagers = qFindChildren<QtSizePolicyPropertyManager *>(manager);
+    QListIterator<QtSizePolicyPropertyManager *> itSizePolicy(sizePolicyPropertyManagers);
+    while (itSizePolicy.hasNext()) {
+        QtSizePolicyPropertyManager *manager = itSizePolicy.next();
+        d_ptr->m_spinBoxFactory->removePropertyManager(manager->subIntPropertyManager());
+        d_ptr->m_comboBoxFactory->removePropertyManager(manager->subEnumPropertyManager());
+    }
+
+    QList<QtFontPropertyManager *> fontPropertyManagers = qFindChildren<QtFontPropertyManager *>(manager);
+    QListIterator<QtFontPropertyManager *> itFont(fontPropertyManagers);
+    while (itFont.hasNext()) {
+        QtFontPropertyManager *manager = itFont.next();
+        d_ptr->m_fontEditorFactory->removePropertyManager(manager);
+        d_ptr->m_spinBoxFactory->removePropertyManager(manager->subIntPropertyManager());
+        d_ptr->m_comboBoxFactory->removePropertyManager(manager->subEnumPropertyManager());
+        d_ptr->m_checkBoxFactory->removePropertyManager(manager->subBoolPropertyManager());
+    }
+
+    QList<QtCursorPropertyManager *> cursorPropertyManagers = qFindChildren<QtCursorPropertyManager *>(manager);
+    QListIterator<QtCursorPropertyManager *> itCursor(cursorPropertyManagers);
+    while (itCursor.hasNext())
+        d_ptr->m_cursorEditorFactory->removePropertyManager(itCursor.next());
+
+    QList<QtFlagPropertyManager *> flagPropertyManagers = qFindChildren<QtFlagPropertyManager *>(manager);
+    QListIterator<QtFlagPropertyManager *> itFlag(flagPropertyManagers);
+    while (itFlag.hasNext())
+        d_ptr->m_checkBoxFactory->removePropertyManager(itFlag.next()->subBoolPropertyManager());
+}
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+#include "moc_qtvariantproperty.cpp"
diff --git a/Code/Mantid/QtPropertyBrowser/src/qtvariantproperty.h b/Code/Mantid/QtPropertyBrowser/src/qtvariantproperty.h
index b842219ce4da91cbfa384f97df2daefd3403ce96..9f20d3dd41cfe29b9d3b0fc710b392472b45d86a 100644
--- a/Code/Mantid/QtPropertyBrowser/src/qtvariantproperty.h
+++ b/Code/Mantid/QtPropertyBrowser/src/qtvariantproperty.h
@@ -1,232 +1,232 @@
-/****************************************************************************
-**
-** 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  
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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 
-** 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.
-** 
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
-** Contact: Qt Software Information (qt-info@nokia.com)
-**
-** This file is part of the tools applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** No Commercial Usage
-** This file contains pre-release code and may not be distributed.
-** You may use this file in accordance with the terms and conditions
-** contained in the either Technology Preview License Agreement or the
-** Beta Release License Agreement.
-**
-** 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
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** 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
-** 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.
-**
-** If you are unsure which license is appropriate for your use, please
-** contact the sales department at qt-sales@nokia.com.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QTVARIANTPROPERTY_H
-#define QTVARIANTPROPERTY_H
-
-#include "qtpropertybrowser.h"
-#include <QtCore/QVariant>
-#include <QtGui/QIcon>
-
-#if QT_VERSION >= 0x040400
-QT_BEGIN_NAMESPACE
-#endif
-
-typedef QMap<int, QIcon> QtIconMap;
-
-class QtVariantPropertyManager;
-class QtVariantPropertyPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtVariantProperty : public QtProperty
-{
-public:
-    ~QtVariantProperty();
-    QVariant value() const;
-    QVariant attributeValue(const QString &attribute) const;
-    int valueType() const;
-    int propertyType() const;
-
-    void setValue(const QVariant &value);
-    void setAttribute(const QString &attribute, const QVariant &value);
-protected:
-    QtVariantProperty(QtVariantPropertyManager *manager);
-private:
-    friend class QtVariantPropertyManager;
-    QtVariantPropertyPrivate *d_ptr;
-};
-
-class QtVariantPropertyManagerPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtVariantPropertyManager : public QtAbstractPropertyManager
-{
-    Q_OBJECT
-public:
-    QtVariantPropertyManager(QObject *parent = 0);
-    ~QtVariantPropertyManager();
-
-    virtual QtVariantProperty *addProperty(int propertyType, const QString &name = QString());
-
-    int propertyType(const QtProperty *property) const;
-    int valueType(const QtProperty *property) const;
-    QtVariantProperty *variantProperty(const QtProperty *property) const;
-
-    virtual bool isPropertyTypeSupported(int propertyType) const;
-    virtual int valueType(int propertyType) const;
-    virtual QStringList attributes(int propertyType) const;
-    virtual int attributeType(int propertyType, const QString &attribute) const;
-
-    virtual QVariant value(const QtProperty *property) const;
-    virtual QVariant attributeValue(const QtProperty *property, const QString &attribute) const;
-
-    static int enumTypeId();
-    static int flagTypeId();
-    static int groupTypeId();
-    static int iconMapTypeId();
-public Q_SLOTS:
-    virtual void setValue(QtProperty *property, const QVariant &val);
-    virtual void setAttribute(QtProperty *property,
-                const QString &attribute, const QVariant &value);
-Q_SIGNALS:
-    void valueChanged(QtProperty *property, const QVariant &val);
-    void attributeChanged(QtProperty *property,
-                const QString &attribute, const QVariant &val);
-protected:
-    virtual bool hasValue(const QtProperty *property) const;
-    QString valueText(const QtProperty *property) const;
-    QIcon valueIcon(const QtProperty *property) const;
-    virtual void initializeProperty(QtProperty *property);
-    virtual void uninitializeProperty(QtProperty *property);
-    virtual QtProperty *createProperty();
-private:
-    QtVariantPropertyManagerPrivate *d_ptr;
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, int, int))
-    Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, double))
-    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, double, double))
-    Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, double))
-    Q_PRIVATE_SLOT(d_func(), void slotDecimalsChanged(QtProperty *, int))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, bool))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QString &))
-    Q_PRIVATE_SLOT(d_func(), void slotRegExpChanged(QtProperty *, const QRegExp &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QDate &))
-    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, const QDate &, const QDate &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QTime &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QDateTime &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QKeySequence &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QChar &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QLocale &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QPoint &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QPointF &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QSize &))
-    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, const QSize &, const QSize &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QSizeF &))
-    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, const QSizeF &, const QSizeF &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QRect &))
-    Q_PRIVATE_SLOT(d_func(), void slotConstraintChanged(QtProperty *, const QRect &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QRectF &))
-    Q_PRIVATE_SLOT(d_func(), void slotConstraintChanged(QtProperty *, const QRectF &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QColor &))
-    Q_PRIVATE_SLOT(d_func(), void slotEnumNamesChanged(QtProperty *, const QStringList &))
-    Q_PRIVATE_SLOT(d_func(), void slotEnumIconsChanged(QtProperty *, const QMap<int, QIcon> &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QSizePolicy &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QFont &))
-    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QCursor &))
-    Q_PRIVATE_SLOT(d_func(), void slotFlagNamesChanged(QtProperty *, const QStringList &))
-
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *))
-    Q_PRIVATE_SLOT(d_func(), void slotPropertyRemoved(QtProperty *, QtProperty *))
-    Q_DECLARE_PRIVATE(QtVariantPropertyManager)
-    Q_DISABLE_COPY(QtVariantPropertyManager)
-};
-
-class QtVariantEditorFactoryPrivate;
-
-class QT_QTPROPERTYBROWSER_EXPORT QtVariantEditorFactory : public QtAbstractEditorFactory<QtVariantPropertyManager>
-{
-    Q_OBJECT
-public:
-    QtVariantEditorFactory(QObject *parent = 0);
-    ~QtVariantEditorFactory();
-protected:
-    void connectPropertyManager(QtVariantPropertyManager *manager);
-    QWidget *createEditor(QtVariantPropertyManager *manager, QtProperty *property,
-                QWidget *parent);
-    void disconnectPropertyManager(QtVariantPropertyManager *manager);
-private:
-    QtVariantEditorFactoryPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(QtVariantEditorFactory)
-    Q_DISABLE_COPY(QtVariantEditorFactory)
-};
-
-#if QT_VERSION >= 0x040400
-QT_END_NAMESPACE
-#endif
-
-Q_DECLARE_METATYPE(QIcon)
-Q_DECLARE_METATYPE(QtIconMap)
-#endif
+/****************************************************************************
+**
+** 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  
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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 
+** 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.
+** 
+****************************************************************************/
+
+/****************************************************************************
+**
+** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: Qt Software Information (qt-info@nokia.com)
+**
+** This file is part of the tools applications of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the either Technology Preview License Agreement or the
+** Beta Release License Agreement.
+**
+** 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
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** 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
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at qt-sales@nokia.com.
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QTVARIANTPROPERTY_H
+#define QTVARIANTPROPERTY_H
+
+#include "qtpropertybrowser.h"
+#include <QtCore/QVariant>
+#include <QtGui/QIcon>
+
+#if QT_VERSION >= 0x040400
+QT_BEGIN_NAMESPACE
+#endif
+
+typedef QMap<int, QIcon> QtIconMap;
+
+class QtVariantPropertyManager;
+class QtVariantPropertyPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtVariantProperty : public QtProperty
+{
+public:
+    ~QtVariantProperty();
+    QVariant value() const;
+    QVariant attributeValue(const QString &attribute) const;
+    int valueType() const;
+    int propertyType() const;
+
+    void setValue(const QVariant &value);
+    void setAttribute(const QString &attribute, const QVariant &value);
+protected:
+    QtVariantProperty(QtVariantPropertyManager *manager);
+private:
+    friend class QtVariantPropertyManager;
+    QtVariantPropertyPrivate *d_ptr;
+};
+
+class QtVariantPropertyManagerPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtVariantPropertyManager : public QtAbstractPropertyManager
+{
+    Q_OBJECT
+public:
+    QtVariantPropertyManager(QObject *parent = 0);
+    ~QtVariantPropertyManager();
+
+    virtual QtVariantProperty *addProperty(int propertyType, const QString &name = QString());
+
+    int propertyType(const QtProperty *property) const;
+    int valueType(const QtProperty *property) const;
+    QtVariantProperty *variantProperty(const QtProperty *property) const;
+
+    virtual bool isPropertyTypeSupported(int propertyType) const;
+    virtual int valueType(int propertyType) const;
+    virtual QStringList attributes(int propertyType) const;
+    virtual int attributeType(int propertyType, const QString &attribute) const;
+
+    virtual QVariant value(const QtProperty *property) const;
+    virtual QVariant attributeValue(const QtProperty *property, const QString &attribute) const;
+
+    static int enumTypeId();
+    static int flagTypeId();
+    static int groupTypeId();
+    static int iconMapTypeId();
+public Q_SLOTS:
+    virtual void setValue(QtProperty *property, const QVariant &val);
+    virtual void setAttribute(QtProperty *property,
+                const QString &attribute, const QVariant &value);
+Q_SIGNALS:
+    void valueChanged(QtProperty *property, const QVariant &val);
+    void attributeChanged(QtProperty *property,
+                const QString &attribute, const QVariant &val);
+protected:
+    virtual bool hasValue(const QtProperty *property) const;
+    QString valueText(const QtProperty *property) const;
+    QIcon valueIcon(const QtProperty *property) const;
+    virtual void initializeProperty(QtProperty *property);
+    virtual void uninitializeProperty(QtProperty *property);
+    virtual QtProperty *createProperty();
+private:
+    QtVariantPropertyManagerPrivate *d_ptr;
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, int, int))
+    Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, double))
+    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, double, double))
+    Q_PRIVATE_SLOT(d_func(), void slotSingleStepChanged(QtProperty *, double))
+    Q_PRIVATE_SLOT(d_func(), void slotDecimalsChanged(QtProperty *, int))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, bool))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QString &))
+    Q_PRIVATE_SLOT(d_func(), void slotRegExpChanged(QtProperty *, const QRegExp &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QDate &))
+    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, const QDate &, const QDate &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QTime &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QDateTime &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QKeySequence &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QChar &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QLocale &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QPoint &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QPointF &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QSize &))
+    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, const QSize &, const QSize &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QSizeF &))
+    Q_PRIVATE_SLOT(d_func(), void slotRangeChanged(QtProperty *, const QSizeF &, const QSizeF &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QRect &))
+    Q_PRIVATE_SLOT(d_func(), void slotConstraintChanged(QtProperty *, const QRect &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QRectF &))
+    Q_PRIVATE_SLOT(d_func(), void slotConstraintChanged(QtProperty *, const QRectF &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QColor &))
+    Q_PRIVATE_SLOT(d_func(), void slotEnumNamesChanged(QtProperty *, const QStringList &))
+    Q_PRIVATE_SLOT(d_func(), void slotEnumIconsChanged(QtProperty *, const QMap<int, QIcon> &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QSizePolicy &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QFont &))
+    Q_PRIVATE_SLOT(d_func(), void slotValueChanged(QtProperty *, const QCursor &))
+    Q_PRIVATE_SLOT(d_func(), void slotFlagNamesChanged(QtProperty *, const QStringList &))
+
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyInserted(QtProperty *, QtProperty *, QtProperty *))
+    Q_PRIVATE_SLOT(d_func(), void slotPropertyRemoved(QtProperty *, QtProperty *))
+    Q_DECLARE_PRIVATE(QtVariantPropertyManager)
+    Q_DISABLE_COPY(QtVariantPropertyManager)
+};
+
+class QtVariantEditorFactoryPrivate;
+
+class QT_QTPROPERTYBROWSER_EXPORT QtVariantEditorFactory : public QtAbstractEditorFactory<QtVariantPropertyManager>
+{
+    Q_OBJECT
+public:
+    QtVariantEditorFactory(QObject *parent = 0);
+    ~QtVariantEditorFactory();
+protected:
+    void connectPropertyManager(QtVariantPropertyManager *manager);
+    QWidget *createEditor(QtVariantPropertyManager *manager, QtProperty *property,
+                QWidget *parent);
+    void disconnectPropertyManager(QtVariantPropertyManager *manager);
+private:
+    QtVariantEditorFactoryPrivate *d_ptr;
+    Q_DECLARE_PRIVATE(QtVariantEditorFactory)
+    Q_DISABLE_COPY(QtVariantEditorFactory)
+};
+
+#if QT_VERSION >= 0x040400
+QT_END_NAMESPACE
+#endif
+
+Q_DECLARE_METATYPE(QIcon)
+Q_DECLARE_METATYPE(QtIconMap)
+#endif
diff --git a/Code/Mantid/Scripts/Inelastic/IndirectCommon.py b/Code/Mantid/Scripts/Inelastic/IndirectCommon.py
index 719d98b642d171d66d602cfa6bfa4ee4249d0f25..d8eaf2af230f5aa3c4be69ef8f0f3d4a0f8e139d 100644
--- a/Code/Mantid/Scripts/Inelastic/IndirectCommon.py
+++ b/Code/Mantid/Scripts/Inelastic/IndirectCommon.py
@@ -1,80 +1,80 @@
-from mantidsimple import *
-import os.path
-import math
-
-def loadNexus(filename):
-    '''Loads a Nexus file into a workspace with the name based on the
-    filename. Convenience function for not having to play around with paths
-    in every function.'''
-    name = os.path.splitext( os.path.split(filename)[1] )[0]
-    LoadNexus(filename, name)
-    return name
-    
-def getWSprefix(workspace):
-    '''Returns a string of the form '<ins><run>_<analyser><refl>_' on which
-    all of our other naming conventions are built.'''
-    if workspace == '':
-        return ''
-    ws = mtd[workspace]
-    ins = ws.getInstrument().getName()
-    ins = ConfigService().facility().instrument(ins).shortName().lower()
-    run = ws.getRun().getLogData('run_number').value
-    try:
-        analyser = ws.getInstrument().getStringParameter('analyser')[0]
-        reflection = ws.getInstrument().getStringParameter('reflection')[0]
-    except IndexError:
-        analyser = ''
-        reflection = ''
-    prefix = ins + run + '_' + analyser + reflection + '_'
-    return prefix
-
-def getEfixed(workspace, detIndex=0):
-    det = mtd[workspace].getDetector(detIndex)
-    try:
-        efixed = det.getNumberParameter('Efixed')[0]
-    except AttributeError:
-        ids = det.getDetectorIDs()
-        det = mtd[workspace].getInstrument().getDetector(ids[0])
-        efixed = det.getNumberParameter('Efixed')[0]
-    return efixed
-
-def getRunTitle(workspace):
-    ws = mtd[workspace]
-    title = ws.getRun()['run_title'].value.strip()
-    runNo = ws.getRun()['run_number'].value
-    inst = ws.getInstrument().getName()
-    isn = ConfigService().facility().instrument(inst).shortName().upper()
-    valid = "-_.() %s%s" % (string.ascii_letters, string.digits)
-    title = ''.join(ch for ch in title if ch in valid)
-    title = isn + runNo + '-' + title
-    return title
-
-def createQaxis(inputWS):
-    result = []
-    ws = mtd[inputWS]
-    nHist = ws.getNumberHistograms()
-    if ws.getAxis(1).isSpectra():
-        inst = ws.getInstrument()
-        samplePos = inst.getSample().getPos()
-        beamPos = samplePos - inst.getSource().getPos()
-        for i in range(0,nHist):
-            efixed = getEfixed(inputWS, i)
-            detector = ws.getDetector(i)
-            theta = detector.getTwoTheta(samplePos, beamPos) / 2
-            lamda = math.sqrt(81.787/efixed)
-            q = 4 * math.pi * math.sin(theta) / lamda
-            result.append(q)
-    else:
-        axis = ws.getAxis(1)
-        msg = 'Creating Axis based on Detector Q value: '
-        if not axis.isNumeric():
-            msg += 'Input workspace must have either spectra or numeric axis.'
-            print msg
-            sys.exit(msg)
-        if ( axis.getUnit().name() != 'MomentumTransfer' ):
-            msg += 'Input must have axis values of Q'
-            print msg
-            sys.exit(msg)
-        for i in range(0, nHist):
-            result.append(float(axis.label(i)))
+from mantidsimple import *
+import os.path
+import math
+
+def loadNexus(filename):
+    '''Loads a Nexus file into a workspace with the name based on the
+    filename. Convenience function for not having to play around with paths
+    in every function.'''
+    name = os.path.splitext( os.path.split(filename)[1] )[0]
+    LoadNexus(filename, name)
+    return name
+    
+def getWSprefix(workspace):
+    '''Returns a string of the form '<ins><run>_<analyser><refl>_' on which
+    all of our other naming conventions are built.'''
+    if workspace == '':
+        return ''
+    ws = mtd[workspace]
+    ins = ws.getInstrument().getName()
+    ins = ConfigService().facility().instrument(ins).shortName().lower()
+    run = ws.getRun().getLogData('run_number').value
+    try:
+        analyser = ws.getInstrument().getStringParameter('analyser')[0]
+        reflection = ws.getInstrument().getStringParameter('reflection')[0]
+    except IndexError:
+        analyser = ''
+        reflection = ''
+    prefix = ins + run + '_' + analyser + reflection + '_'
+    return prefix
+
+def getEfixed(workspace, detIndex=0):
+    det = mtd[workspace].getDetector(detIndex)
+    try:
+        efixed = det.getNumberParameter('Efixed')[0]
+    except AttributeError:
+        ids = det.getDetectorIDs()
+        det = mtd[workspace].getInstrument().getDetector(ids[0])
+        efixed = det.getNumberParameter('Efixed')[0]
+    return efixed
+
+def getRunTitle(workspace):
+    ws = mtd[workspace]
+    title = ws.getRun()['run_title'].value.strip()
+    runNo = ws.getRun()['run_number'].value
+    inst = ws.getInstrument().getName()
+    isn = ConfigService().facility().instrument(inst).shortName().upper()
+    valid = "-_.() %s%s" % (string.ascii_letters, string.digits)
+    title = ''.join(ch for ch in title if ch in valid)
+    title = isn + runNo + '-' + title
+    return title
+
+def createQaxis(inputWS):
+    result = []
+    ws = mtd[inputWS]
+    nHist = ws.getNumberHistograms()
+    if ws.getAxis(1).isSpectra():
+        inst = ws.getInstrument()
+        samplePos = inst.getSample().getPos()
+        beamPos = samplePos - inst.getSource().getPos()
+        for i in range(0,nHist):
+            efixed = getEfixed(inputWS, i)
+            detector = ws.getDetector(i)
+            theta = detector.getTwoTheta(samplePos, beamPos) / 2
+            lamda = math.sqrt(81.787/efixed)
+            q = 4 * math.pi * math.sin(theta) / lamda
+            result.append(q)
+    else:
+        axis = ws.getAxis(1)
+        msg = 'Creating Axis based on Detector Q value: '
+        if not axis.isNumeric():
+            msg += 'Input workspace must have either spectra or numeric axis.'
+            print msg
+            sys.exit(msg)
+        if ( axis.getUnit().name() != 'MomentumTransfer' ):
+            msg += 'Input must have axis values of Q'
+            print msg
+            sys.exit(msg)
+        for i in range(0, nHist):
+            result.append(float(axis.label(i)))
     return result
\ No newline at end of file
diff --git a/Code/Mantid/Scripts/Inelastic/IndirectDataAnalysis.py b/Code/Mantid/Scripts/Inelastic/IndirectDataAnalysis.py
index 48d8e33d36bb6580a7ce4bb52b3796214b5826c6..3f9af450ee20788d23f75a2a2f4c4493d2919d26 100644
--- a/Code/Mantid/Scripts/Inelastic/IndirectDataAnalysis.py
+++ b/Code/Mantid/Scripts/Inelastic/IndirectDataAnalysis.py
@@ -1,459 +1,459 @@
-from mantidsimple import *
-from mantidplot import *
-import IndirectEnergyConversion as IEC
-from IndirectCommon import *
-
-import math
-import re
-import os.path
-
-def abscyl(inWS_n, outWS_n, efixed, sample, can):
-    ConvertUnits(inWS_n, 'wavelength', 'Wavelength', 'Indirect', efixed)
-    CylinderAbsorption('wavelength', outWS_n, sample[0], sample[1], sample[2],
-        can[0],can[1], EMode='Indirect', EFixed=efixed, NumberOfSlices=can[2],
-        NumberOfAnnuli=can[3])
-    mantid.deleteWorkspace('wavelength')
-
-def absflat(inWS_n, outWS_n, efixed, sample, can):
-    ConvertUnits(inWS_n, 'wlength', 'Wavelength', 'Indirect', efixed)
-    FlatPlateAbsorption('wlength', outWS_n, sample[0], sample[1], sample[2],
-        can[0], can[1], can[2], EMode='Indirect', EFixed=efixed,
-        ElementSize=can[3])
-    mantid.deleteWorkspace('wlength')
-
-def absorption(input, mode, sample, can, Save=False, Verbose=False,
-        Plot=False):
-    root = loadNexus(input)
-    efixed = getEfixed(root)
-    outWS_n = root[:-3] + 'abs'
-    if mode == 'Flat Plate':
-        absflat(root, outWS_n, efixed, sample, can)
-    if mode == 'Cylinder':
-        abscyl(root, outWS_n, efixed, sample, can)
-    if Save:
-        SaveNexus(outWS_n, outWS_n+'.nxs')
-    mantid.deleteWorkspace(root)
-    if Plot:
-        graph = plotSpectrum(outWS_n,0)
-
-def concatWSs(workspaces, unit, name):
-    dataX = []
-    dataY = []
-    dataE = []
-    for ws in workspaces:
-        readX = mtd[ws].readX(0)
-        readY = mtd[ws].readY(0)
-        readE = mtd[ws].readE(0)
-        for i in range(0, len(readX)):
-            dataX.append(readX[i])
-        for i in range(0, len(readY)):
-            dataY.append(readY[i])
-            dataE.append(readE[i])
-    CreateWorkspace(name, dataX, dataY, dataE, NSpec=len(workspaces),
-        UnitX=unit)
-
-def confitParsToWS(Table, Data, BackG='FixF', specMin=0, specMax=-1):
-    if ( specMax == -1 ):
-        specMax = mtd[Data].getNumberHistograms() - 1
-    dataX = createQaxis(Data)
-    xAxisVals = []
-    dataY = []
-    dataE = []
-    names = ''
-    ws = mtd[Table]
-    cName =  ws.getColumnNames()
-    nSpec = ( ws.getColumnCount() - 1 ) / 2
-    for spec in range(0,nSpec):
-        yAxis = cName[(spec*2)+1]
-        if re.search('HWHM$', yAxis) or re.search('Height$', yAxis):
-            xAxisVals += dataX        
-            if (len(names) > 0):
-                names += ","
-            names += yAxis
-            eAxis = cName[(spec*2)+2]
-            for row in range(0, ws.getRowCount()):
-                dataY.append(ws.getDouble(yAxis,row))
-                dataE.append(ws.getDouble(eAxis,row))
-        else:
-            nSpec -= 1
-    suffix = str(nSpec / 2) + 'L' + BackG
-    outNm = Table + suffix
-    CreateWorkspace(outNm, xAxisVals, dataY, dataE, nSpec,
-        UnitX='MomentumTransfer', VerticalAxisUnit='Text',
-        VerticalAxisValues=names)
-    return outNm
-
-def confitPlotSeq(inputWS, plot):
-    nhist = mtd[inputWS].getNumberHistograms()
-    if ( plot == 'All' ):
-        plotSpectrum(inputWS, range(0, nhist))
-        return    
-    plotSpecs = []
-    if ( plot == 'Intensity' ):
-        res = 'Height$'
-    elif ( plot == 'HWHM' ):
-        res = 'HWHM$'
-    for i in range(0,nhist):
-        title = mtd[inputWS].getAxis(1).label(i)
-        if re.search(res, title):
-            plotSpecs.append(i)
-    plotSpectrum(inputWS, plotSpecs)
-
-def confitSeq(inputWS, func, startX, endX, save, plot, bg, specMin, specMax):
-    input = inputWS+',i' + str(specMin)
-    if (specMax == -1):
-        specMax = mtd[inputWS].getNumberHistograms() - 1
-    for i in range(specMin + 1, specMax + 1):
-        input += ';'+inputWS+',i'+str(i)
-    outNm = getWSprefix(inputWS) + 'conv_'
-    PlotPeakByLogValue(input, outNm, func, StartX=startX, EndX=endX)
-    wsname = confitParsToWS(outNm, inputWS, bg, specMin, specMax)
-    if save:
-            SaveNexusProcessed(wsname, wsname+'.nxs')
-    if plot != 'None':
-        confitPlotSeq(wsname, plot)
-
-def demon(rawfiles, first, last, instrument, Smooth=False, SumFiles=False,
-        grouping='Individual', cal='', CleanUp=True, Verbose=False, 
-        Plot='None', Save=True, Real=False, Vanadium='', Monitor=True):
-    '''DEMON routine for diffraction reduction on indirect instruments (IRIS /
-    OSIRIS).'''
-    # Get instrument workspace for gathering parameters and such
-    wsInst = mtd['__empty_' + instrument]
-    if wsInst is None:
-        IEC.loadInst(instrument)
-        wsInst = mtd['__empty_' + instrument]
-    # short name of instrument for saving etc
-    isn = ConfigService().facility().instrument(instrument).shortName().lower()
-    # parameters to do with monitor
-    if Monitor:
-        fmon, fdet = IEC.getFirstMonFirstDet('__empty_'+instrument)
-        ws_mon_l = IEC.loadData(rawfiles, Sum=SumFiles, Suffix='_mon',
-            SpecMin=fmon+1, SpecMax=fmon+1)
-    ws_det_l = IEC.loadData(rawfiles, Sum=SumFiles, SpecMin=first, 
-        SpecMax=last)
-    workspaces = []
-    for i in range(0, len(ws_det_l)):
-        det_ws = ws_det_l[i]
-        # Get Run No
-        runNo = mtd[det_ws].getRun().getLogData("run_number").value
-        savefile = isn + runNo + '_diff'
-        if Monitor:
-            mon_ws = ws_mon_l[i]
-            # Get Monitor WS
-            IEC.timeRegime(monitor=mon_ws, detectors=det_ws, Smooth=Smooth)
-            IEC.monitorEfficiency(mon_ws)
-            IEC.normToMon(Factor=1e6, monitor=mon_ws, detectors=det_ws)
-            # Remove monitor workspace
-            DeleteWorkspace(mon_ws)
-        if ( cal != '' ): # AlignDetectors and Group by .cal file
-            if Monitor:
-                ConvertUnits(det_ws, det_ws, 'TOF')
-            if ( mtd[det_ws].isDistribution() ):
-                ConvertFromDistribution(det_ws)
-            AlignDetectors(det_ws, det_ws, cal)
-            CloneWorkspace(det_ws, 'demon_CorByMon-and-Aligned')
-            DiffractionFocussing(det_ws, savefile, cal)
-            DeleteWorkspace(det_ws)
-            if ( Vanadium != '' ):
-                print "NotImplemented: divide by vanadium."
-        else: ## Do it the old fashioned way
-            # Convert to dSpacing - need to AlignBins so we can group later
-            ConvertUnits(det_ws, det_ws, 'dSpacing', AlignBins=True)
-            IEC.groupData(grouping, savefile, detectors=det_ws)
-        if Save:
-            SaveNexusProcessed(savefile, savefile+'.nxs')
-        workspaces.append(savefile)
-    if ( Plot != 'None' ):
-        for demon in workspaces:
-            if ( Plot == 'Contour' ):
-                importMatrixWorkspace(demon).plotGraph2D()
-            else:
-                nspec = mtd[demon].getNumberHistograms()
-                plotSpectrum(demon, range(0, nspec))
-    return workspaces
-
-def elwin(inputFiles, eRange, Save=False, Verbose=False, Plot=False):
-    eq1 = [] # output workspaces with units in Q
-    eq2 = [] # output workspaces with units in Q^2
-    for file in inputFiles:
-        root = loadNexus(file)
-        savefile = getWSprefix(root)
-        if ( len(eRange) == 4 ):
-            ElasticWindow(root, savefile+'eq1', savefile+'eq2',eRange[0],
-                eRange[1], eRange[2], eRange[3])
-        elif ( len(eRange) == 2 ):
-            ElasticWindow(root, savefile+'eq1', savefile+'eq2', 
-            eRange[0], eRange[1])
-        if Save:
-            SaveNexusProcessed(savefile+'eq1', savefile+'eq1.nxs')
-            SaveNexusProcessed(savefile+'eq2', savefile+'eq2.nxs')
-        eq1.append(savefile+'eq1')
-        eq2.append(savefile+'eq2')
-        DeleteWorkspace(root)
-    if Plot:
-        nBins = mtd[eq1[0]].getNumberBins()
-        lastXeq1 = mtd[eq1[0]].readX(0)[nBins-1]
-        graph1 = plotSpectrum(eq1, 0)
-        layer = graph1.activeLayer()
-        layer.setScale(Layer.Bottom, 0.0, lastXeq1)
-        nBins = mtd[eq2[0]].getNumberBins()
-        lastXeq2 = mtd[eq2[0]].readX(0)[nBins-1]
-        graph2 = plotSpectrum(eq2, 0)
-        layer = graph2.activeLayer()
-        layer.setScale(Layer.Bottom, 0.0, lastXeq2)
-    return eq1, eq2
-
-def fury(sam_files, res_file, rebinParam, RES=True, Save=False, Verbose=False,
-        Plot=False):
-    outWSlist = []
-    # Process RES Data Only Once
-    LoadNexus(res_file, 'res_data') # RES
-    Rebin('res_data', 'res_data', rebinParam)
-    ExtractFFTSpectrum('res_data', 'res_fft', 2)
-    Integration('res_data', 'res_int')
-    Divide('res_fft', 'res_int', 'res')
-    for sam_file in sam_files:
-        (direct, filename) = os.path.split(sam_file)
-        (root, ext) = os.path.splitext(filename)
-        if (ext == '.nxs'):
-            LoadNexus(sam_file, 'sam_data') # SAMPLE
-            Rebin('sam_data', 'sam_data', rebinParam)
-        else: #input is workspace
-            Rebin(sam_file, 'sam_data', rebinParam)
-        ExtractFFTSpectrum('sam_data', 'sam_fft', 2)
-        Integration('sam_data', 'sam_int')
-        Divide('sam_fft', 'sam_int', 'sam')
-        # Create save file name
-        savefile = getWSprefix('sam_data') + 'iqt'
-        outWSlist.append(savefile)
-        Divide('sam', 'res', savefile)
-        #Cleanup Sample Files
-        DeleteWorkspace('sam_data')
-        DeleteWorkspace('sam_int')
-        DeleteWorkspace('sam_fft')
-        DeleteWorkspace('sam')
-        # Crop nonsense values off workspace
-        bin = int(math.ceil(mtd[savefile].getNumberBins()/ 2.0))
-        binV = mtd[savefile].dataX(0)[bin]
-        CropWorkspace(savefile, savefile, XMax=binV)
-        if Save:
-            SaveNexusProcessed(savefile, savefile+'.nxs')
-    # Clean Up RES files
-    DeleteWorkspace('res_data')
-    DeleteWorkspace('res_int')
-    DeleteWorkspace('res_fft')
-    DeleteWorkspace('res')
-    if Plot:
-        specrange = range(0,mtd[outWSlist[0]].getNumberHistograms())
-        plotFury(outWSlist, specrange)
-    return outWSlist
-
-def furyfitParsToWS(Table, Data):
-    dataX = createQaxis(Data)
-    dataY = []
-    dataE = []
-    names = ""
-    xAxisVals = []
-    ws = mtd[Table]
-    cCount = ws.getColumnCount()
-    rCount = ws.getRowCount()
-    cName =  ws.getColumnNames()
-    nSpec = ( cCount - 1 ) / 2
-    xAxis = cName[0]
-    stretched = 0
-    for spec in range(0,nSpec):
-        yAxis = cName[(spec*2)+1]
-        if ( re.search('Intensity$', yAxis) or re.search('Tau$', yAxis) or
-            re.search('Beta$', yAxis) ):
-            xAxisVals += dataX
-            if (len(names) > 0):
-                names += ","
-            names += yAxis
-            eAxis = cName[(spec*2)+2]
-            for row in range(0, rCount):
-                dataY.append(ws.getDouble(yAxis,row))
-                dataE.append(ws.getDouble(eAxis,row))
-            if ( re.search('Beta$', yAxis) ): # need to know how many of curves
-                stretched += 1                # are stretched exponentials
-        else:
-            nSpec -= 1
-    suffix = ''
-    nE = ( nSpec / 2 ) - stretched
-    if ( nE > 0 ):
-        suffix += str(nE) + 'E'
-    if ( stretched > 0 ):
-        suffix += str(stretched) + 'S'
-    wsname = Table + suffix
-    CreateWorkspace(wsname, xAxisVals, dataY, dataE, nSpec,
-        UnitX='MomentumTransfer', VerticalAxisUnit='Text',
-        VerticalAxisValues=names)
-    return wsname
-
-def furyfitPlotSeq(inputWS, plot):
-    nHist = mtd[inputWS].getNumberHistograms()
-    if ( plot == 'All' ):
-        plotSpectrum(inputWS, range(0, nHist))
-        return
-    plotSpecs = []
-    if ( plot == 'Intensity' ):
-        res = 'Intensity$'
-    if ( plot == 'Tau' ):
-        res = 'Tau$'
-    elif ( plot == 'Beta' ):
-        res = 'Beta$'    
-    for i in range(0, nHist):
-        title = mtd[inputWS].getAxis(1).label(i)
-        if ( re.search(res, title) ):
-            plotSpecs.append(i)
-    plotSpectrum(inputWS, plotSpecs)
-
-def furyfitSeq(inputWS, func, startx, endx, save, plot):
-    input = inputWS+',i0'
-    nHist = mtd[inputWS].getNumberHistograms()
-    for i in range(1,nHist):
-        input += ';'+inputWS+',i'+str(i)
-    outNm = getWSprefix(inputWS) + 'fury_'
-    PlotPeakByLogValue(input, outNm, func, StartX=startx, EndX=endx)
-    wsname = furyfitParsToWS(outNm, inputWS)
-    if save:
-        SaveNexusProcessed(wsname, wsname+'.nxs')
-    if ( plot != 'None' ):
-        furyfitPlotSeq(wsname, plot)
-
-def msdfit(inputs, startX, endX, Save=False, Verbose=False, Plot=False):
-    output = []
-    for file in inputs:
-        (direct, filename) = os.path.split(file)
-        (root, ext) = os.path.splitext(filename)
-        LoadNexusProcessed(file, root)
-        outWS_n = root[:-3] + 'msd'
-        fit_alg = Linear(root, outWS_n, WorkspaceIndex=0, StartX=startX, 
-            EndX=endX)
-        output.append(outWS_n)
-        A0 = fit_alg.getPropertyValue("FitIntercept")
-        A1 = fit_alg.getPropertyValue("FitSlope")
-        title = 'Intercept: '+A0+' ; Slope: '+A1
-        if Plot:
-            graph=plotSpectrum([root,outWS_n],0, 1)
-            graph.activeLayer().setTitle(title)
-        if Save:
-            SaveNexusProcessed(outWS_n, outWS_n+'.nxs', Title=title)
-    return output
-
-def plotFury(inWS_n, spec):
-    inWS = mtd[inWS_n[0]]
-    nbins = inWS.getNumberBins()
-    graph = plotSpectrum(inWS_n, spec)
-    layer = graph.activeLayer()
-    layer.setScale(Layer.Left, 0, 1.0)
-
-def plotInput(inputfiles,spectra=[]):
-    OneSpectra = False
-    if len(spectra) != 2:
-        spectra = [spectra[0], spectra[0]]
-        OneSpectra = True
-    workspaces = []
-    for file in inputfiles:
-        root = loadNexus(file)
-        if not OneSpectra:
-            GroupDetectors(root, root,
-                DetectorList=range(spectra[0],spectra[1]+1) )
-        workspaces.append(root)
-    if len(workspaces) > 0:
-        graph = plotSpectrum(workspaces,0)
-        layer = graph.activeLayer().setTitle(", ".join(workspaces))
-        
-###############################################################################
-## abscor (previously in SpencerAnalysis) #####################################
-###############################################################################
-
-def CubicFit(inputWS, spec):
-    '''Uses the Mantid Fit Algorithm to fit a cubic function to the inputWS
-    parameter. Returns a list containing the fitted parameter values.'''
-    function = 'name=UserFunction, Formula=A0+A1*x+A2*x*x, A0=1, A1=0, A2=0'
-    fit = Fit(inputWS, spec, Function=function)
-    return fit.getPropertyValue('Parameters')
-
-def applyCorrections(inputWS, cannisterWS, corrections, efixed):
-    '''Through the PolynomialCorrection algorithm, makes corrections to the
-    input workspace based on the supplied correction values.'''
-    # Corrections are applied in Lambda (Wavelength)
-    ConvertUnits(inputWS, inputWS, 'Wavelength', 'Indirect',
-        EFixed=efixed)
-    if cannisterWS != '':
-        ConvertUnits(cannisterWS, cannisterWS, 'Wavelength', 'Indirect',
-            EFixed=efixed)
-    nHist = mtd[inputWS].getNumberHistograms()
-    # Check that number of histograms in each corrections workspace matches
-    # that of the input (sample) workspace
-    for ws in corrections:
-        if ( mtd[ws].getNumberHistograms() != nHist ):
-            raise ValueError('Mismatch: num of spectra in '+ws+' and inputWS')
-    # Workspaces that hold intermediate results
-    CorrectedWorkspace = getWSprefix(inputWS) + 'csam'
-    CorrectedSampleWorkspace = '__csamws'
-    CorrectedCanWorkspace = getWSprefix(cannisterWS) + 'ccan'
-    for i in range(0, nHist): # Loop through each spectra in the inputWS
-        ExtractSingleSpectrum(inputWS, CorrectedSampleWorkspace, i)
-        if ( len(corrections) == 1 ):
-            Ass = CubicFit(corrections[0], i)
-            PolynomialCorrection(CorrectedSampleWorkspace, 
-                CorrectedSampleWorkspace, Ass, 'Divide')
-            if ( i == 0 ):
-                CloneWorkspace(CorrectedSampleWorkspace, CorrectedWorkspace)
-            else:
-                ConjoinWorkspaces(CorrectedWorkspace, CorrectedSampleWorkspace)
-        else:
-            ExtractSingleSpectrum(cannisterWS, CorrectedCanWorkspace, i)
-            Acc = CubicFit(corrections[3], i)
-            PolynomialCorrection(CorrectedCanWorkspace, CorrectedCanWorkspace,
-                Acc, 'Divide')
-            Acsc = CubicFit(corrections[2], i)
-            PolynomialCorrection(CorrectedCanWorkspace, CorrectedCanWorkspace,
-                Acsc, 'Multiply')
-            Minus(CorrectedSampleWorkspace, CorrectedCanWorkspace,
-                CorrectedSampleWorkspace)
-            Assc = CubicFit(corrections[1], i)
-            PolynomialCorrection(CorrectedSampleWorkspace, 
-                CorrectedSampleWorkspace, Assc, 'Divide')
-            if ( i == 0 ):
-                CloneWorkspace(CorrectedSampleWorkspace, CorrectedWorkspace)
-            else:
-                ConjoinWorkspaces(CorrectedWorkspace, CorrectedSampleWorkspace)
-    ConvertUnits(CorrectedWorkspace, CorrectedWorkspace, 'DeltaE', 'Indirect',
-        EFixed=efixed)
-    if cannisterWS != '':
-        ConvertUnits(CorrectedCanWorkspace, CorrectedCanWorkspace, 'DeltaE',
-            'Indirect', EFixed=efixed)
-                
-def abscorFeeder(sample, container, geom, useCor):
-    '''Load up the necessary files and then passes them into the main
-    applyCorrections routine.'''
-    if useCor:
-        ## Files named: (ins)(runNo)_(geom)_(suffix)
-        ins = mtd[sample].getInstrument().getName()
-        ins = ConfigService().facility().instrument(ins).shortName().lower()
-        run = mtd[sample].getRun().getLogData('run_number').value
-        name = ins + run + '_' + geom + '_'
-        corrections = [loadNexus(name+'ass.nxs')]
-        if container != '': # if container is given we have 3 more corrections
-            corrections.append(loadNexus(name+'assc.nxs'))
-            corrections.append(loadNexus(name+'acsc.nxs'))
-            corrections.append(loadNexus(name+'acc.nxs'))
-    else:
-        if ( container == '' ):
-            sys.exit("What do you want me to do?")
-        else:
-            result = getWSprefix(sample) + 'bgd'
-            Minus(sample, container, result)
-            return
-    # Get efixed
-    efixed = getEfixed(sample)
-    # Fire off main routine
-    try:
-        applyCorrections(sample, container, corrections, efixed)
-    except ValueError:
-        print """Number of histograms in corrections workspaces do not match
-            the sample workspace."""
-        raise
+from mantidsimple import *
+from mantidplot import *
+import IndirectEnergyConversion as IEC
+from IndirectCommon import *
+
+import math
+import re
+import os.path
+
+def abscyl(inWS_n, outWS_n, efixed, sample, can):
+    ConvertUnits(inWS_n, 'wavelength', 'Wavelength', 'Indirect', efixed)
+    CylinderAbsorption('wavelength', outWS_n, sample[0], sample[1], sample[2],
+        can[0],can[1], EMode='Indirect', EFixed=efixed, NumberOfSlices=can[2],
+        NumberOfAnnuli=can[3])
+    mantid.deleteWorkspace('wavelength')
+
+def absflat(inWS_n, outWS_n, efixed, sample, can):
+    ConvertUnits(inWS_n, 'wlength', 'Wavelength', 'Indirect', efixed)
+    FlatPlateAbsorption('wlength', outWS_n, sample[0], sample[1], sample[2],
+        can[0], can[1], can[2], EMode='Indirect', EFixed=efixed,
+        ElementSize=can[3])
+    mantid.deleteWorkspace('wlength')
+
+def absorption(input, mode, sample, can, Save=False, Verbose=False,
+        Plot=False):
+    root = loadNexus(input)
+    efixed = getEfixed(root)
+    outWS_n = root[:-3] + 'abs'
+    if mode == 'Flat Plate':
+        absflat(root, outWS_n, efixed, sample, can)
+    if mode == 'Cylinder':
+        abscyl(root, outWS_n, efixed, sample, can)
+    if Save:
+        SaveNexus(outWS_n, outWS_n+'.nxs')
+    mantid.deleteWorkspace(root)
+    if Plot:
+        graph = plotSpectrum(outWS_n,0)
+
+def concatWSs(workspaces, unit, name):
+    dataX = []
+    dataY = []
+    dataE = []
+    for ws in workspaces:
+        readX = mtd[ws].readX(0)
+        readY = mtd[ws].readY(0)
+        readE = mtd[ws].readE(0)
+        for i in range(0, len(readX)):
+            dataX.append(readX[i])
+        for i in range(0, len(readY)):
+            dataY.append(readY[i])
+            dataE.append(readE[i])
+    CreateWorkspace(name, dataX, dataY, dataE, NSpec=len(workspaces),
+        UnitX=unit)
+
+def confitParsToWS(Table, Data, BackG='FixF', specMin=0, specMax=-1):
+    if ( specMax == -1 ):
+        specMax = mtd[Data].getNumberHistograms() - 1
+    dataX = createQaxis(Data)
+    xAxisVals = []
+    dataY = []
+    dataE = []
+    names = ''
+    ws = mtd[Table]
+    cName =  ws.getColumnNames()
+    nSpec = ( ws.getColumnCount() - 1 ) / 2
+    for spec in range(0,nSpec):
+        yAxis = cName[(spec*2)+1]
+        if re.search('HWHM$', yAxis) or re.search('Height$', yAxis):
+            xAxisVals += dataX        
+            if (len(names) > 0):
+                names += ","
+            names += yAxis
+            eAxis = cName[(spec*2)+2]
+            for row in range(0, ws.getRowCount()):
+                dataY.append(ws.getDouble(yAxis,row))
+                dataE.append(ws.getDouble(eAxis,row))
+        else:
+            nSpec -= 1
+    suffix = str(nSpec / 2) + 'L' + BackG
+    outNm = Table + suffix
+    CreateWorkspace(outNm, xAxisVals, dataY, dataE, nSpec,
+        UnitX='MomentumTransfer', VerticalAxisUnit='Text',
+        VerticalAxisValues=names)
+    return outNm
+
+def confitPlotSeq(inputWS, plot):
+    nhist = mtd[inputWS].getNumberHistograms()
+    if ( plot == 'All' ):
+        plotSpectrum(inputWS, range(0, nhist))
+        return    
+    plotSpecs = []
+    if ( plot == 'Intensity' ):
+        res = 'Height$'
+    elif ( plot == 'HWHM' ):
+        res = 'HWHM$'
+    for i in range(0,nhist):
+        title = mtd[inputWS].getAxis(1).label(i)
+        if re.search(res, title):
+            plotSpecs.append(i)
+    plotSpectrum(inputWS, plotSpecs)
+
+def confitSeq(inputWS, func, startX, endX, save, plot, bg, specMin, specMax):
+    input = inputWS+',i' + str(specMin)
+    if (specMax == -1):
+        specMax = mtd[inputWS].getNumberHistograms() - 1
+    for i in range(specMin + 1, specMax + 1):
+        input += ';'+inputWS+',i'+str(i)
+    outNm = getWSprefix(inputWS) + 'conv_'
+    PlotPeakByLogValue(input, outNm, func, StartX=startX, EndX=endX)
+    wsname = confitParsToWS(outNm, inputWS, bg, specMin, specMax)
+    if save:
+            SaveNexusProcessed(wsname, wsname+'.nxs')
+    if plot != 'None':
+        confitPlotSeq(wsname, plot)
+
+def demon(rawfiles, first, last, instrument, Smooth=False, SumFiles=False,
+        grouping='Individual', cal='', CleanUp=True, Verbose=False, 
+        Plot='None', Save=True, Real=False, Vanadium='', Monitor=True):
+    '''DEMON routine for diffraction reduction on indirect instruments (IRIS /
+    OSIRIS).'''
+    # Get instrument workspace for gathering parameters and such
+    wsInst = mtd['__empty_' + instrument]
+    if wsInst is None:
+        IEC.loadInst(instrument)
+        wsInst = mtd['__empty_' + instrument]
+    # short name of instrument for saving etc
+    isn = ConfigService().facility().instrument(instrument).shortName().lower()
+    # parameters to do with monitor
+    if Monitor:
+        fmon, fdet = IEC.getFirstMonFirstDet('__empty_'+instrument)
+        ws_mon_l = IEC.loadData(rawfiles, Sum=SumFiles, Suffix='_mon',
+            SpecMin=fmon+1, SpecMax=fmon+1)
+    ws_det_l = IEC.loadData(rawfiles, Sum=SumFiles, SpecMin=first, 
+        SpecMax=last)
+    workspaces = []
+    for i in range(0, len(ws_det_l)):
+        det_ws = ws_det_l[i]
+        # Get Run No
+        runNo = mtd[det_ws].getRun().getLogData("run_number").value
+        savefile = isn + runNo + '_diff'
+        if Monitor:
+            mon_ws = ws_mon_l[i]
+            # Get Monitor WS
+            IEC.timeRegime(monitor=mon_ws, detectors=det_ws, Smooth=Smooth)
+            IEC.monitorEfficiency(mon_ws)
+            IEC.normToMon(Factor=1e6, monitor=mon_ws, detectors=det_ws)
+            # Remove monitor workspace
+            DeleteWorkspace(mon_ws)
+        if ( cal != '' ): # AlignDetectors and Group by .cal file
+            if Monitor:
+                ConvertUnits(det_ws, det_ws, 'TOF')
+            if ( mtd[det_ws].isDistribution() ):
+                ConvertFromDistribution(det_ws)
+            AlignDetectors(det_ws, det_ws, cal)
+            CloneWorkspace(det_ws, 'demon_CorByMon-and-Aligned')
+            DiffractionFocussing(det_ws, savefile, cal)
+            DeleteWorkspace(det_ws)
+            if ( Vanadium != '' ):
+                print "NotImplemented: divide by vanadium."
+        else: ## Do it the old fashioned way
+            # Convert to dSpacing - need to AlignBins so we can group later
+            ConvertUnits(det_ws, det_ws, 'dSpacing', AlignBins=True)
+            IEC.groupData(grouping, savefile, detectors=det_ws)
+        if Save:
+            SaveNexusProcessed(savefile, savefile+'.nxs')
+        workspaces.append(savefile)
+    if ( Plot != 'None' ):
+        for demon in workspaces:
+            if ( Plot == 'Contour' ):
+                importMatrixWorkspace(demon).plotGraph2D()
+            else:
+                nspec = mtd[demon].getNumberHistograms()
+                plotSpectrum(demon, range(0, nspec))
+    return workspaces
+
+def elwin(inputFiles, eRange, Save=False, Verbose=False, Plot=False):
+    eq1 = [] # output workspaces with units in Q
+    eq2 = [] # output workspaces with units in Q^2
+    for file in inputFiles:
+        root = loadNexus(file)
+        savefile = getWSprefix(root)
+        if ( len(eRange) == 4 ):
+            ElasticWindow(root, savefile+'eq1', savefile+'eq2',eRange[0],
+                eRange[1], eRange[2], eRange[3])
+        elif ( len(eRange) == 2 ):
+            ElasticWindow(root, savefile+'eq1', savefile+'eq2', 
+            eRange[0], eRange[1])
+        if Save:
+            SaveNexusProcessed(savefile+'eq1', savefile+'eq1.nxs')
+            SaveNexusProcessed(savefile+'eq2', savefile+'eq2.nxs')
+        eq1.append(savefile+'eq1')
+        eq2.append(savefile+'eq2')
+        DeleteWorkspace(root)
+    if Plot:
+        nBins = mtd[eq1[0]].getNumberBins()
+        lastXeq1 = mtd[eq1[0]].readX(0)[nBins-1]
+        graph1 = plotSpectrum(eq1, 0)
+        layer = graph1.activeLayer()
+        layer.setScale(Layer.Bottom, 0.0, lastXeq1)
+        nBins = mtd[eq2[0]].getNumberBins()
+        lastXeq2 = mtd[eq2[0]].readX(0)[nBins-1]
+        graph2 = plotSpectrum(eq2, 0)
+        layer = graph2.activeLayer()
+        layer.setScale(Layer.Bottom, 0.0, lastXeq2)
+    return eq1, eq2
+
+def fury(sam_files, res_file, rebinParam, RES=True, Save=False, Verbose=False,
+        Plot=False):
+    outWSlist = []
+    # Process RES Data Only Once
+    LoadNexus(res_file, 'res_data') # RES
+    Rebin('res_data', 'res_data', rebinParam)
+    ExtractFFTSpectrum('res_data', 'res_fft', 2)
+    Integration('res_data', 'res_int')
+    Divide('res_fft', 'res_int', 'res')
+    for sam_file in sam_files:
+        (direct, filename) = os.path.split(sam_file)
+        (root, ext) = os.path.splitext(filename)
+        if (ext == '.nxs'):
+            LoadNexus(sam_file, 'sam_data') # SAMPLE
+            Rebin('sam_data', 'sam_data', rebinParam)
+        else: #input is workspace
+            Rebin(sam_file, 'sam_data', rebinParam)
+        ExtractFFTSpectrum('sam_data', 'sam_fft', 2)
+        Integration('sam_data', 'sam_int')
+        Divide('sam_fft', 'sam_int', 'sam')
+        # Create save file name
+        savefile = getWSprefix('sam_data') + 'iqt'
+        outWSlist.append(savefile)
+        Divide('sam', 'res', savefile)
+        #Cleanup Sample Files
+        DeleteWorkspace('sam_data')
+        DeleteWorkspace('sam_int')
+        DeleteWorkspace('sam_fft')
+        DeleteWorkspace('sam')
+        # Crop nonsense values off workspace
+        bin = int(math.ceil(mtd[savefile].getNumberBins()/ 2.0))
+        binV = mtd[savefile].dataX(0)[bin]
+        CropWorkspace(savefile, savefile, XMax=binV)
+        if Save:
+            SaveNexusProcessed(savefile, savefile+'.nxs')
+    # Clean Up RES files
+    DeleteWorkspace('res_data')
+    DeleteWorkspace('res_int')
+    DeleteWorkspace('res_fft')
+    DeleteWorkspace('res')
+    if Plot:
+        specrange = range(0,mtd[outWSlist[0]].getNumberHistograms())
+        plotFury(outWSlist, specrange)
+    return outWSlist
+
+def furyfitParsToWS(Table, Data):
+    dataX = createQaxis(Data)
+    dataY = []
+    dataE = []
+    names = ""
+    xAxisVals = []
+    ws = mtd[Table]
+    cCount = ws.getColumnCount()
+    rCount = ws.getRowCount()
+    cName =  ws.getColumnNames()
+    nSpec = ( cCount - 1 ) / 2
+    xAxis = cName[0]
+    stretched = 0
+    for spec in range(0,nSpec):
+        yAxis = cName[(spec*2)+1]
+        if ( re.search('Intensity$', yAxis) or re.search('Tau$', yAxis) or
+            re.search('Beta$', yAxis) ):
+            xAxisVals += dataX
+            if (len(names) > 0):
+                names += ","
+            names += yAxis
+            eAxis = cName[(spec*2)+2]
+            for row in range(0, rCount):
+                dataY.append(ws.getDouble(yAxis,row))
+                dataE.append(ws.getDouble(eAxis,row))
+            if ( re.search('Beta$', yAxis) ): # need to know how many of curves
+                stretched += 1                # are stretched exponentials
+        else:
+            nSpec -= 1
+    suffix = ''
+    nE = ( nSpec / 2 ) - stretched
+    if ( nE > 0 ):
+        suffix += str(nE) + 'E'
+    if ( stretched > 0 ):
+        suffix += str(stretched) + 'S'
+    wsname = Table + suffix
+    CreateWorkspace(wsname, xAxisVals, dataY, dataE, nSpec,
+        UnitX='MomentumTransfer', VerticalAxisUnit='Text',
+        VerticalAxisValues=names)
+    return wsname
+
+def furyfitPlotSeq(inputWS, plot):
+    nHist = mtd[inputWS].getNumberHistograms()
+    if ( plot == 'All' ):
+        plotSpectrum(inputWS, range(0, nHist))
+        return
+    plotSpecs = []
+    if ( plot == 'Intensity' ):
+        res = 'Intensity$'
+    if ( plot == 'Tau' ):
+        res = 'Tau$'
+    elif ( plot == 'Beta' ):
+        res = 'Beta$'    
+    for i in range(0, nHist):
+        title = mtd[inputWS].getAxis(1).label(i)
+        if ( re.search(res, title) ):
+            plotSpecs.append(i)
+    plotSpectrum(inputWS, plotSpecs)
+
+def furyfitSeq(inputWS, func, startx, endx, save, plot):
+    input = inputWS+',i0'
+    nHist = mtd[inputWS].getNumberHistograms()
+    for i in range(1,nHist):
+        input += ';'+inputWS+',i'+str(i)
+    outNm = getWSprefix(inputWS) + 'fury_'
+    PlotPeakByLogValue(input, outNm, func, StartX=startx, EndX=endx)
+    wsname = furyfitParsToWS(outNm, inputWS)
+    if save:
+        SaveNexusProcessed(wsname, wsname+'.nxs')
+    if ( plot != 'None' ):
+        furyfitPlotSeq(wsname, plot)
+
+def msdfit(inputs, startX, endX, Save=False, Verbose=False, Plot=False):
+    output = []
+    for file in inputs:
+        (direct, filename) = os.path.split(file)
+        (root, ext) = os.path.splitext(filename)
+        LoadNexusProcessed(file, root)
+        outWS_n = root[:-3] + 'msd'
+        fit_alg = Linear(root, outWS_n, WorkspaceIndex=0, StartX=startX, 
+            EndX=endX)
+        output.append(outWS_n)
+        A0 = fit_alg.getPropertyValue("FitIntercept")
+        A1 = fit_alg.getPropertyValue("FitSlope")
+        title = 'Intercept: '+A0+' ; Slope: '+A1
+        if Plot:
+            graph=plotSpectrum([root,outWS_n],0, 1)
+            graph.activeLayer().setTitle(title)
+        if Save:
+            SaveNexusProcessed(outWS_n, outWS_n+'.nxs', Title=title)
+    return output
+
+def plotFury(inWS_n, spec):
+    inWS = mtd[inWS_n[0]]
+    nbins = inWS.getNumberBins()
+    graph = plotSpectrum(inWS_n, spec)
+    layer = graph.activeLayer()
+    layer.setScale(Layer.Left, 0, 1.0)
+
+def plotInput(inputfiles,spectra=[]):
+    OneSpectra = False
+    if len(spectra) != 2:
+        spectra = [spectra[0], spectra[0]]
+        OneSpectra = True
+    workspaces = []
+    for file in inputfiles:
+        root = loadNexus(file)
+        if not OneSpectra:
+            GroupDetectors(root, root,
+                DetectorList=range(spectra[0],spectra[1]+1) )
+        workspaces.append(root)
+    if len(workspaces) > 0:
+        graph = plotSpectrum(workspaces,0)
+        layer = graph.activeLayer().setTitle(", ".join(workspaces))
+        
+###############################################################################
+## abscor (previously in SpencerAnalysis) #####################################
+###############################################################################
+
+def CubicFit(inputWS, spec):
+    '''Uses the Mantid Fit Algorithm to fit a cubic function to the inputWS
+    parameter. Returns a list containing the fitted parameter values.'''
+    function = 'name=UserFunction, Formula=A0+A1*x+A2*x*x, A0=1, A1=0, A2=0'
+    fit = Fit(inputWS, spec, Function=function)
+    return fit.getPropertyValue('Parameters')
+
+def applyCorrections(inputWS, cannisterWS, corrections, efixed):
+    '''Through the PolynomialCorrection algorithm, makes corrections to the
+    input workspace based on the supplied correction values.'''
+    # Corrections are applied in Lambda (Wavelength)
+    ConvertUnits(inputWS, inputWS, 'Wavelength', 'Indirect',
+        EFixed=efixed)
+    if cannisterWS != '':
+        ConvertUnits(cannisterWS, cannisterWS, 'Wavelength', 'Indirect',
+            EFixed=efixed)
+    nHist = mtd[inputWS].getNumberHistograms()
+    # Check that number of histograms in each corrections workspace matches
+    # that of the input (sample) workspace
+    for ws in corrections:
+        if ( mtd[ws].getNumberHistograms() != nHist ):
+            raise ValueError('Mismatch: num of spectra in '+ws+' and inputWS')
+    # Workspaces that hold intermediate results
+    CorrectedWorkspace = getWSprefix(inputWS) + 'csam'
+    CorrectedSampleWorkspace = '__csamws'
+    CorrectedCanWorkspace = getWSprefix(cannisterWS) + 'ccan'
+    for i in range(0, nHist): # Loop through each spectra in the inputWS
+        ExtractSingleSpectrum(inputWS, CorrectedSampleWorkspace, i)
+        if ( len(corrections) == 1 ):
+            Ass = CubicFit(corrections[0], i)
+            PolynomialCorrection(CorrectedSampleWorkspace, 
+                CorrectedSampleWorkspace, Ass, 'Divide')
+            if ( i == 0 ):
+                CloneWorkspace(CorrectedSampleWorkspace, CorrectedWorkspace)
+            else:
+                ConjoinWorkspaces(CorrectedWorkspace, CorrectedSampleWorkspace)
+        else:
+            ExtractSingleSpectrum(cannisterWS, CorrectedCanWorkspace, i)
+            Acc = CubicFit(corrections[3], i)
+            PolynomialCorrection(CorrectedCanWorkspace, CorrectedCanWorkspace,
+                Acc, 'Divide')
+            Acsc = CubicFit(corrections[2], i)
+            PolynomialCorrection(CorrectedCanWorkspace, CorrectedCanWorkspace,
+                Acsc, 'Multiply')
+            Minus(CorrectedSampleWorkspace, CorrectedCanWorkspace,
+                CorrectedSampleWorkspace)
+            Assc = CubicFit(corrections[1], i)
+            PolynomialCorrection(CorrectedSampleWorkspace, 
+                CorrectedSampleWorkspace, Assc, 'Divide')
+            if ( i == 0 ):
+                CloneWorkspace(CorrectedSampleWorkspace, CorrectedWorkspace)
+            else:
+                ConjoinWorkspaces(CorrectedWorkspace, CorrectedSampleWorkspace)
+    ConvertUnits(CorrectedWorkspace, CorrectedWorkspace, 'DeltaE', 'Indirect',
+        EFixed=efixed)
+    if cannisterWS != '':
+        ConvertUnits(CorrectedCanWorkspace, CorrectedCanWorkspace, 'DeltaE',
+            'Indirect', EFixed=efixed)
+                
+def abscorFeeder(sample, container, geom, useCor):
+    '''Load up the necessary files and then passes them into the main
+    applyCorrections routine.'''
+    if useCor:
+        ## Files named: (ins)(runNo)_(geom)_(suffix)
+        ins = mtd[sample].getInstrument().getName()
+        ins = ConfigService().facility().instrument(ins).shortName().lower()
+        run = mtd[sample].getRun().getLogData('run_number').value
+        name = ins + run + '_' + geom + '_'
+        corrections = [loadNexus(name+'ass.nxs')]
+        if container != '': # if container is given we have 3 more corrections
+            corrections.append(loadNexus(name+'assc.nxs'))
+            corrections.append(loadNexus(name+'acsc.nxs'))
+            corrections.append(loadNexus(name+'acc.nxs'))
+    else:
+        if ( container == '' ):
+            sys.exit("What do you want me to do?")
+        else:
+            result = getWSprefix(sample) + 'bgd'
+            Minus(sample, container, result)
+            return
+    # Get efixed
+    efixed = getEfixed(sample)
+    # Fire off main routine
+    try:
+        applyCorrections(sample, container, corrections, efixed)
+    except ValueError:
+        print """Number of histograms in corrections workspaces do not match
+            the sample workspace."""
+        raise
diff --git a/Code/Mantid/Scripts/Inelastic/IndirectEnergyConversion.py b/Code/Mantid/Scripts/Inelastic/IndirectEnergyConversion.py
index 588ccc735d2652459d1b07fc3df867849048ab1a..47e2f36ab6f7cc411bed9df357dc3d4ec4c83ed4 100644
--- a/Code/Mantid/Scripts/Inelastic/IndirectEnergyConversion.py
+++ b/Code/Mantid/Scripts/Inelastic/IndirectEnergyConversion.py
@@ -1,569 +1,569 @@
-from mantidsimple import *
-
-try: # mantidplot can only be imported within mantidplot
-    from mantidplot import * # we want to be able to run from mantid script
-except ImportError:
-    print "Could not import MantidPlot module. Plotting is disabled."
-    pass
-
-import re
-
-from IndirectCommon import *
-
-def convert_to_energy(rawfiles, grouping, first, last,
-        instrument, analyser, reflection,
-        SumFiles=False, bgremove=[0, 0], tempK=-1, calib='', rebinParam='',
-        saveFormats=[], CleanUp = True, Verbose = False):        
-    # Get hold of base empty instrument workspace
-    wsInst = mtd['__empty_' + instrument]
-    if wsInst is None:
-        loadInst(instrument)
-        wsInst = mtd['__empty_' + instrument]
-    fmon, fdet = getFirstMonFirstDet('__empty_'+instrument)
-    isTosca = adjustTOF('__empty_'+instrument)
-    # Get short name of instrument from the config service
-    isn = ConfigService().facility().instrument(instrument).shortName().lower()
-    if ( calib != '' ): # Only load Calibration file once
-        LoadNexusProcessed(calib, '__calibration')    
-    # Holds output parameters
-    output_workspace_names = []
-    runNos = []
-    mon_wsl = loadData(rawfiles, Sum=SumFiles, SpecMin=fmon+1, SpecMax=fmon+1,
-        Suffix='_mon')
-    if isTosca: # Check if we need to use ChopData etc
-        ws = mtd[mon_wsl[0]]
-        if ( ws.readX(0)[ws.getNumberBins()] > 40000 ):
-            DeleteWorkspace(mon_wsl[0])
-            workspaces = toscaChop(rawfiles)
-            if ( saveFormats != [] ): # Save data in selected formats
-                saveItems(workspaces, saveFormats)
-            return workspaces
-    ws_names = loadData(rawfiles, Sum=SumFiles, SpecMin=first, SpecMax=last)
-    if ( len(mon_wsl) != len(ws_names) ):
-        print "Indirect CTE: Error loading data files."
-        sys.exit("Indirect CTE: Error loading data files.")
-    for i in range(0, len(ws_names)):
-        ws = ws_names[i]
-        ws_mon = mon_wsl[i]
-        invalid = []
-        if ( analyser != "" and reflection != "" ):
-            applyParameterFile(ws, analyser, reflection)
-        if isTosca:
-            invalid = getBadDetectorList(ws)
-            factor = 1e9
-        else:
-            factor = 1e6
-        runNo = mtd[ws].getRun().getLogData("run_number").value
-        runNos.append(runNo)
-        name = isn + runNo + '_' + analyser + reflection + '_red'
-        timeRegime(monitor=ws_mon, detectors=ws)
-        monitorEfficiency(ws_mon)
-        ## start dealing with detector data here
-        if ( bgremove != [0, 0] ):
-            backgroundRemoval(bgremove[0], bgremove[1], detectors=ws)
-        if ( calib != '' ):
-            calibrated = useCalib(detectors=ws)
-        normToMon(Factor=factor, monitor=ws_mon, detectors=ws)
-        # Remove monitor workspace
-        DeleteWorkspace(ws_mon)
-        conToEnergy(detectors=ws)
-        if not CleanUp:
-            CloneWorkspace(ws, name+'_intermediate')
-        if ( rebinParam != ''): # Rebin data
-            rebinData(rebinParam, detectors=ws)
-        if ( tempK != -1 ): # "Detailed Balance" correction
-            ExponentialCorrection(ws, ws, 1.0, ( 11.606 / ( 2 * tempK ) ) )
-        # Final stage, grouping of detectors - apply name
-        if isTosca: # TOSCA's grouping is pre-determined and fixed
-            name = getRunTitle(ws)
-            groupTosca(name, invalid, detectors=ws)
-        else:
-            groupData(grouping, name, detectors=ws)
-        output_workspace_names.append(name)
-    if ( saveFormats != [] ): # Save data in selected formats
-        saveItems(output_workspace_names, saveFormats)
-    if ( calib != '' ): # Remove calibration workspace
-        DeleteWorkspace('__calibration')
-    return output_workspace_names
-
-def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1,
-        Suffix=''):
-    workspaces = []
-    for file in rawfiles:
-        ( dir, filename ) = os.path.split(file)
-        ( name, ext ) = os.path.splitext(filename)
-        try:
-            if ( SpecMin == -1 ) and ( SpecMax == -1 ):
-                LoadRaw(file, name+Suffix, LoadLogFiles=False)
-            else:
-                LoadRaw(file, name+Suffix, SpectrumMin=SpecMin, 
-                    SpectrumMax=SpecMax, LoadLogFiles=False)
-            workspaces.append(name+Suffix)
-        except ValueError, message:
-            print message
-            sys.exit(message)
-    if Sum and ( len(workspaces) > 1 ):
-        MergeRuns(','.join(workspaces), outWS+Suffix)
-        factor = 1.0 / len(workspaces)
-        Scale(outWS+Suffix, outWS+Suffix, factor)
-        for ws in workspaces:
-            DeleteWorkspace(ws)
-        return [outWS+Suffix]
-    else:
-        return workspaces
-
-def toscaChop(files):
-    '''Reduction routine for TOSCA instrument when input workspace must be 
-    "split" into parts and folded together after it has been corrected to the 
-    monitor.'''
-    wslist = []
-    workspace_list = loadData(files)
-    for raw in workspace_list:
-        invalid = getBadDetectorList(raw)
-        chopdata = ChopData(raw,raw+'_data')
-        wsgroup = mtd[raw+'_data'].getNames()
-        for ws in wsgroup:
-            ExtractSingleSpectrum(ws, ws+'mon', 140)
-            ConvertUnits(ws+'mon', ws+'mon', 'Wavelength', 'Indirect')
-            monitorEfficiency(ws+'mon')
-            CropWorkspace(ws, ws, StartWorkspaceIndex=0, EndWorkspaceIndex=139)
-            normToMon(Factor=1e9, monitor=ws+'mon', detectors=ws)
-            DeleteWorkspace(ws+'mon')
-        workspaces = ','.join(wsgroup)
-        ws = raw+'_c'
-        MergeRuns(workspaces, ws)
-        scaling = createScalingWorkspace(wsgroup, ws)
-        Divide(ws, scaling, ws)
-        DeleteWorkspace(scaling)
-        for grpws in wsgroup:
-            DeleteWorkspace(grpws)
-        conToEnergy(detectors=ws)
-        Rebin(ws, ws, '-2.5,0.015,3,-0.005,1000')
-        wstitle = getRunTitle(ws) # Have Run title as Workspace Name
-        ws = groupTosca(wstitle, invalid, detectors=ws)
-        wslist.append(ws)
-        DeleteWorkspace(raw)
-    return wslist
-
-def createScalingWorkspace(wsgroup, merged, wsname='__scaling'):
-    '''Based on the widths of the workspaces in the group once they've been
-    converted into Wavelength and normalised by the monitor, this function
-    uses the CreateWorksapce algorithm to decide how to scale the merged
-    workspace.'''
-    largest = 0
-    nlargest = 0
-    nlrgws = ''
-    for ws in wsgroup:
-        nbin = mtd[ws].getNumberBins()
-        if ( nbin > largest ):
-            nlargest = largest
-            largest = nbin
-        elif ( nbin > nlargest ):
-            nlargest = nbin
-            nlrgws = ws
-    nlargestX = mtd[nlrgws].dataX(0)[nlargest]	
-    largestValInNLrg = nlargestX
-    binIndex = mtd[merged].binIndexOf(largestValInNLrg)	
-    dataX = list(mtd[merged].readX(0))
-    dataY = []
-    dataE = []
-    totalBins = mtd[merged].getNumberBins()
-    nWS = len(wsgroup)
-    for i in range(0, binIndex):
-        dataE.append(0.0)
-        dataY.append(nWS)    
-    for i in range(binIndex, totalBins):
-        dataE.append(0.0)
-        dataY.append(1.0)	
-    CreateWorkspace(wsname, dataX, dataY, dataE, UnitX='Wavelength')
-    return wsname
-
-def getFirstMonFirstDet(inWS):
-    workspace = mtd[inWS]
-    FirstDet = FirstMon = -1
-    nhist = workspace.getNumberHistograms()
-    for counter in range(0, nhist):
-        try:
-            detector = workspace.getDetector(counter)
-        except RuntimeError: # This causes problems when encountering some
-            pass             # incomplete instrument definition files (TOSCA)
-        if detector.isMonitor():
-            if (FirstMon == -1):
-                FirstMon = counter
-        else:
-            if (FirstDet == -1):
-                FirstDet = counter
-        if ( FirstMon != -1 and FirstDet != -1 ):
-            break
-    return FirstMon, FirstDet
-
-def timeRegime(Smooth=True, monitor='', detectors=''):
-    SpecMon = mtd[monitor].readX(0)[0]
-    SpecDet = mtd[detectors].readX(0)[0]
-    if ( SpecMon == SpecDet ) and not adjustTOF(monitor):
-        LRef = getReferenceLength(detectors, 0)
-        alg = Unwrap(monitor, monitor, LRef = LRef)
-        join = float(alg.getPropertyValue('JoinWavelength'))
-        RemoveBins(monitor, monitor, join-0.001, join+0.001, 
-                Interpolation='Linear')
-        if Smooth:
-            FFTSmooth(monitor, monitor, 0)
-    else:
-        ConvertUnits(monitor, monitor, 'Wavelength', 'Indirect')
-    return monitor
-
-def monitorEfficiency(inWS):
-    inst = mtd[inWS].getInstrument()
-    try:
-        area = inst.getNumberParameter('mon-area')[0]
-        thickness = inst.getNumberParameter('mon-thickness')[0]
-        OneMinusExponentialCor(inWS, inWS, (8.3 * thickness), area)
-    except IndexError:
-        print "Unable to take Monitor Area and Thickness from Paremeter File."
-    return inWS
-
-def getReferenceLength(inWS, fdi):
-    workspace = mtd[inWS]
-    instrument = workspace.getInstrument()
-    sample = instrument.getSample()
-    source = instrument.getSource()
-    detector = workspace.getDetector(fdi)
-    sample_to_source = sample.getPos() - source.getPos()
-    r = detector.getDistance(sample)
-    x = sample_to_source.getZ()
-    LRef = x + r
-    return LRef
-
-def useCalib(detectors=''):
-    tmp = mtd[detectors]
-    shist = tmp.getNumberHistograms()
-    tmp = mtd['__calibration']
-    chist = tmp.getNumberHistograms()
-    if chist != shist:
-        msg = 'Number of spectra in calibration file does not match number \
-                that exist in the data file.'
-        print msg
-        sys.exit(msg)
-    else:
-        Divide(detectors,'__calibration',detectors)
-    return detectors
-
-def normToMon(Factor=1e6, monitor='', detectors=''):
-    ConvertUnits(detectors, detectors, 'Wavelength', 'Indirect')
-    RebinToWorkspace(detectors,monitor,detectors)
-    Divide(detectors,monitor,detectors)
-    Scale(detectors, detectors, Factor)
-    return detectors
-
-def conToEnergy(detectors=''):
-    ConvertUnits(detectors, detectors, 'DeltaE', 'Indirect')
-    CorrectKiKf(detectors, detectors, 'Indirect')
-    return detectors
-
-def rebinData(rebinParam, detectors=''):
-    Rebin(detectors, detectors, rebinParam)
-    return detectors
-
-def groupData(grouping, name, detectors=''):
-    if (grouping == 'Individual'):
-        if ( detectors != name ):
-            RenameWorkspace(detectors, name)
-        return name
-    elif ( grouping == 'All' ):
-        nhist = mtd[detectors].getNumberHistograms()
-        GroupDetectors(detectors, name, WorkspaceIndexList=range(0,nhist),
-            Behaviour='Average')
-    else:
-        GroupDetectors(detectors, name, MapFile=grouping, Behaviour='Average')
-    if ( detectors != name ):
-        DeleteWorkspace(detectors)
-    return name
-
-def groupTosca(wsname, invalid, detectors=''):
-    grp = range(0,70)
-    for i in invalid:
-        try:
-            grp.remove(i)
-        except ValueError:
-            pass
-    GroupDetectors(detectors, wsname, WorkspaceIndexList=grp, 
-        Behaviour='Average')
-    grp = range(70,140)
-    for i in invalid:
-        try:
-            grp.remove(i)
-        except ValueError:
-            pass
-    GroupDetectors(detectors, '__front', WorkspaceIndexList=grp, 
-        Behaviour='Average')
-    DeleteWorkspace(detectors)
-    ConjoinWorkspaces(wsname, '__front')
-    return wsname
-
-def getBadDetectorList(workspace):
-    IdentifyNoisyDetectors(workspace, '__temp_tsc_noise')
-    ws = mtd['__temp_tsc_noise']
-    nhist = ws.getNumberHistograms()
-    invalid = []
-    for i in range(0, nhist):
-        if ( ws.readY(i)[0] == 0.0 ):
-            invalid.append(i)
-    DeleteWorkspace('__temp_tsc_noise')
-    return invalid
-
-def backgroundRemoval(tofStart, tofEnd, detectors=''):
-    ConvertToDistribution(detectors)
-    FlatBackground(detectors, detectors, tofStart, tofEnd, Mode='Mean')
-    ConvertFromDistribution(detectors)
-    return detectors
-
-def cte_rebin(grouping, tempK, rebinParam, analyser, reflection,
-        saveFormats, CleanUp=False, Verbose=False):
-    # Generate list
-    ws_list = []
-    for workspace in list(mantid.getWorkspaceNames()):
-        if workspace.endswith('_'+analyser+reflection+r'_red_intermediate'):
-            ws_list.append(workspace)
-    if ( len(ws_list) == 0 ):
-        message = "No intermediate workspaces were found. Run with "
-        message += "'Keep Intermediate Workspaces' checked."
-        print message
-        sys.exit(message)
-    output = []
-    for ws in ws_list:
-        runNo = mtd[ws].getRun().getLogData("run_number").value
-        inst = mtd[ws].getInstrument().getName()
-        inst = ConfigService().facility().instrument(inst).shortName().lower()
-        name = inst + runNo + '_' + analyser + reflection + '_red'
-        if not CleanUp:
-            CloneWorkspace(ws, name)
-            ws = name
-        if ( rebinParam != ''):
-            rebin = rebinData(rebinParam, detectors=ws)
-        if ( tempK != -1 ): # Detailed Balance correction
-            ExponentialCorrection(ws, ws, 1.0, ( 11.606 / ( 2 * tempK ) ) )
-        groupData(grouping, name, detectors=ws)
-        output.append(name)
-    if ( saveFormats != [] ):
-        saveItems(output, saveFormats)
-    return output
-
-def createMappingFile(groupFile, ngroup, nspec, first):
-    if ( ngroup == 1 ): return 'All'
-    if ( nspec == 1 ): return 'Individual'
-    filename = mtd.getConfigProperty('defaultsave.directory')
-    filename += groupFile
-    handle = open(filename, 'w')
-    handle.write(str(ngroup) +  "\n" )
-    for n in range(0, ngroup):
-        n1 = n * nspec + first
-        handle.write(str(n+1) +  '\n' )
-        handle.write(str(nspec) +  '\n')
-        for i in range(1, nspec+1):
-            n3 = n1 + i - 1
-            handle.write(str(n3).center(4) + ' ')
-        handle.write('\n')
-    handle.close()
-    return filename
-
-def createCalibFile(rawfiles, suffix, peakMin, peakMax, backMin, backMax, 
-        specMin, specMax, PlotOpt=False):
-    savepath = mantid.getConfigProperty('defaultsave.directory')
-    runs = []
-    for file in rawfiles:
-        (direct, filename) = os.path.split(file)
-        (root, ext) = os.path.splitext(filename)
-        try:
-            LoadRaw(file, root, SpectrumMin=specMin, SpectrumMax=specMax,
-                LoadLogFiles=False)
-            runs.append(root)
-        except:
-            sys.exit('Indirect-Could not load raw file: ' + file)
-    cwsn = '__calibration'
-    if ( len(runs) > 1 ):
-        MergeRuns(",".join(runs), cwsn)
-        factor = 1.0 / len(runs)
-        Scale(cwsn, cwsn, factor)
-    else:
-        cwsn = runs[0]
-    tmp = mtd[cwsn]
-    nhist = tmp.getNumberHistograms()
-    FlatBackground(cwsn, cwsn, StartX=backMin, EndX=backMax, Mode='Mean')
-    Integration(cwsn, cwsn, peakMin, peakMax)
-    cal_ws = mtd[cwsn]
-    sum = 0
-    for i in range(0, nhist):
-        sum += cal_ws.readY(i)[0]
-    value = sum / nhist
-    CreateSingleValuedWorkspace('__cal_avg', value)
-    runNo = mtd[cwsn].getRun().getLogData("run_number").value
-    outWS_n = runs[0][:3] + runNo + suffix
-    Divide(cwsn, '__cal_avg', outWS_n)
-    DeleteWorkspace('__cal_avg')
-    savefile = os.path.join(savepath, outWS_n+'.nxs')
-    SaveNexusProcessed(outWS_n, savefile, 'Calibration')
-    if PlotOpt:
-        graph = plotTimeBin(outWS_n, 0)
-    ## Tidyup
-    DeleteWorkspace(cwsn)
-    return savefile
-
-def resolution(files, iconOpt, rebinParam, bground, 
-        instrument, analyser, reflection,
-        plotOpt=False, Res=True):
-    workspace_list = convert_to_energy(files, 'All', 
-        iconOpt['first'], iconOpt['last'], SumFiles=True, 
-        instrument=instrument, analyser=analyser, reflection=reflection)
-    iconWS = workspace_list[0]
-    if Res:
-        run = mtd[iconWS].getRun().getLogData("run_number").value
-        name = iconWS[:3].lower() + run + '_' + analyser + reflection + '_res'
-        FlatBackground(iconWS, '__background', bground[0], bground[1], 
-            Mode='Mean', OutputMode='Return Background')
-        Rebin(iconWS, iconWS, rebinParam)
-        FFTSmooth(iconWS,iconWS,0)
-        RebinToWorkspace('__background', iconWS, '__background')
-        Minus(iconWS, '__background', name)
-        DeleteWorkspace(iconWS)
-        DeleteWorkspace('__background')
-        SaveNexusProcessed(name, name+'.nxs')
-        if plotOpt:
-            graph = plotSpectrum(name, 0)
-        return name
-    else:
-        if plotOpt:
-            graph = plotSpectrum(iconWS, 0)
-        return iconWS
-
-def saveItems(workspaces, fileFormats, Verbose=False):
-    for workspace in workspaces:
-        for j in fileFormats:
-            if j == 'spe':
-                SaveSPE(workspace, workspace+'.spe')
-            elif j == 'nxs':
-                SaveNexusProcessed(workspace, workspace+'.nxs')
-            elif j == 'nxspe':
-                SaveNXSPE(workspace, workspace+'.nxspe')
-            else:
-                print 'Save: unknown file type.'
-                system.exit('Save: unknown file type.')
-
-def slice(inputfiles, calib, xrange, spec,  suffix, Save=False, Verbose=False,
-        Plot=False):
-    outWSlist = []
-    if  not ( ( len(xrange) == 2 ) or ( len(xrange) == 4 ) ):
-        mantid.sendLogMessage('>> TOF Range must contain either 2 or 4 \
-                numbers.')
-        sys.exit(1)
-    for file in inputfiles:
-        (direct, filename) = os.path.split(file)
-        (root, ext) = os.path.splitext(filename)
-        if spec == [0, 0]:
-            LoadRaw(file, root, LoadLogFiles=False)
-        else:
-            LoadRaw(file, root, SpectrumMin=spec[0], SpectrumMax=spec[1],
-                LoadLogFiles=False)
-        nhist = mtd[root].getNumberHistograms()
-        if calib != '':
-            useCalib(calib, inWS_n=root, outWS_n=root)
-        run = mtd[root].getRun().getLogData("run_number").value
-        sfile = root[:3].lower() + run + '_' + suffix + '_slt'
-        if (len(xrange) == 2):
-            Integration(root, sfile, xrange[0], xrange[1], 0, nhist-1)
-        else:
-            FlatBackground(root, sfile, StartX=xrange[2], EndX=xrange[3], 
-                    Mode='Mean')
-            Integration(sfile, sfile, xrange[0], xrange[1], 0, nhist-1)
-        if Save:
-            SaveNexusProcessed(sfile, sfile+'.nxs')
-        outWSlist.append(sfile)
-        DeleteWorkspace(root)
-    if Plot:
-        graph = plotBin(outWSlist, 0)
-
-def getInstrumentDetails(instrument):
-    workspace = mtd['__empty_' + instrument]
-    if ( workspace == None ):
-        idf_dir = mantid.getConfigProperty('instrumentDefinition.directory')
-        idf = idf_dir + instrument + '_Definition.xml'
-        LoadEmptyInstrument(idf, '__empty_'+instrument)
-        workspace = mtd['__empty_'+instrument]
-    instrument = workspace.getInstrument()
-    ana_list_split = instrument.getStringParameter('analysers')[0].split(',')
-    reflections = []
-    result = ''
-    for i in range(0,len(ana_list_split)):
-        list = []
-        name = 'refl-' + ana_list_split[i]
-        list.append( ana_list_split[i] )
-        try:
-            item = instrument.getStringParameter(name)[0]
-        except IndexError:
-            item = ''
-        refl = item.split(',')
-        list.append( refl )
-        reflections.append(list)
-    for i in range(0, len(reflections)):
-        message = reflections[i][0] + '-'
-        for j in range(0,len(reflections[i][1])):
-            message += str(reflections[i][1][j])
-            if j < ( len(reflections[i][1]) -1 ):
-                message += ','
-        result += message
-        if ( i < ( len(reflections) - 1) ):
-            result += '\n'
-    return result
-
-def getReflectionDetails(inst, analyser, refl):
-    idf_dir = mantid.getConfigProperty('instrumentDefinition.directory')
-    ws = '__empty_' + inst
-    if (mtd[ws] == None):
-        idf = idf_dir + inst + '_Definition.xml'
-        LoadEmptyInstrument(idf, ws)
-    ipf = idf_dir + inst + '_' + analyser + '_' + refl + '_Parameters.xml'
-    LoadParameterFile(ws, ipf)
-    inst = mtd[ws].getInstrument()
-    result = ''
-    try:
-        result += str( inst.getStringParameter('analysis-type')[0] ) + '\n'
-        result += str( int(inst.getNumberParameter('spectra-min')[0]) ) + '\n'
-        result += str( int(inst.getNumberParameter('spectra-max')[0]) ) + '\n'
-        result += str( inst.getNumberParameter('efixed-val')[0] ) + '\n'
-        result += str( int(inst.getNumberParameter('peak-start')[0]) ) + '\n'
-        result += str( int(inst.getNumberParameter('peak-end')[0]) ) + '\n'
-        result += str( int(inst.getNumberParameter('back-start')[0]) ) + '\n'
-        result += str( int(inst.getNumberParameter('back-end')[0]) ) + '\n'
-        result += inst.getStringParameter('rebin-default')[0]
-    except IndexError:
-        pass
-    return result
-
-def loadInst(instrument):    
-    ws = '__empty_' + instrument
-    if (mtd[ws] == None):
-        idf_dir = mantid.getConfigProperty('instrumentDefinition.directory')
-        idf = idf_dir + instrument + '_Definition.xml'
-        LoadEmptyInstrument(idf, ws)
-
-def adjustTOF(ws='', inst=''):
-    if ( ws != '' ):
-        ins = mtd[ws].getInstrument()
-    elif ( inst != ''):
-        idf_dir = mantid.getConfigProperty('instrumentDefinition.directory')
-        idf = idf_dir + inst + '_Definition.xml'
-        LoadEmptyInstrument(idf, 'ins')
-        ins = mtd['ins'].getInstrument()
-    try:
-        val = ins.getNumberParameter('adjustTOF')[0]
-    except IndexError:
-        val = 0
-    if ( val == 1 ):
-        return True
-    else:
-        return False
-
-def applyParameterFile(workspace, analyser, refl):
-    inst = mtd[workspace].getInstrument().getName()
-    idf_dir = mantid.getConfigProperty('instrumentDefinition.directory')
-    ipf = idf_dir + inst + '_' + analyser + '_' + refl + '_Parameters.xml'
-    LoadParameterFile(workspace, ipf)
+from mantidsimple import *
+
+try: # mantidplot can only be imported within mantidplot
+    from mantidplot import * # we want to be able to run from mantid script
+except ImportError:
+    print "Could not import MantidPlot module. Plotting is disabled."
+    pass
+
+import re
+
+from IndirectCommon import *
+
+def convert_to_energy(rawfiles, grouping, first, last,
+        instrument, analyser, reflection,
+        SumFiles=False, bgremove=[0, 0], tempK=-1, calib='', rebinParam='',
+        saveFormats=[], CleanUp = True, Verbose = False):        
+    # Get hold of base empty instrument workspace
+    wsInst = mtd['__empty_' + instrument]
+    if wsInst is None:
+        loadInst(instrument)
+        wsInst = mtd['__empty_' + instrument]
+    fmon, fdet = getFirstMonFirstDet('__empty_'+instrument)
+    isTosca = adjustTOF('__empty_'+instrument)
+    # Get short name of instrument from the config service
+    isn = ConfigService().facility().instrument(instrument).shortName().lower()
+    if ( calib != '' ): # Only load Calibration file once
+        LoadNexusProcessed(calib, '__calibration')    
+    # Holds output parameters
+    output_workspace_names = []
+    runNos = []
+    mon_wsl = loadData(rawfiles, Sum=SumFiles, SpecMin=fmon+1, SpecMax=fmon+1,
+        Suffix='_mon')
+    if isTosca: # Check if we need to use ChopData etc
+        ws = mtd[mon_wsl[0]]
+        if ( ws.readX(0)[ws.getNumberBins()] > 40000 ):
+            DeleteWorkspace(mon_wsl[0])
+            workspaces = toscaChop(rawfiles)
+            if ( saveFormats != [] ): # Save data in selected formats
+                saveItems(workspaces, saveFormats)
+            return workspaces
+    ws_names = loadData(rawfiles, Sum=SumFiles, SpecMin=first, SpecMax=last)
+    if ( len(mon_wsl) != len(ws_names) ):
+        print "Indirect CTE: Error loading data files."
+        sys.exit("Indirect CTE: Error loading data files.")
+    for i in range(0, len(ws_names)):
+        ws = ws_names[i]
+        ws_mon = mon_wsl[i]
+        invalid = []
+        if ( analyser != "" and reflection != "" ):
+            applyParameterFile(ws, analyser, reflection)
+        if isTosca:
+            invalid = getBadDetectorList(ws)
+            factor = 1e9
+        else:
+            factor = 1e6
+        runNo = mtd[ws].getRun().getLogData("run_number").value
+        runNos.append(runNo)
+        name = isn + runNo + '_' + analyser + reflection + '_red'
+        timeRegime(monitor=ws_mon, detectors=ws)
+        monitorEfficiency(ws_mon)
+        ## start dealing with detector data here
+        if ( bgremove != [0, 0] ):
+            backgroundRemoval(bgremove[0], bgremove[1], detectors=ws)
+        if ( calib != '' ):
+            calibrated = useCalib(detectors=ws)
+        normToMon(Factor=factor, monitor=ws_mon, detectors=ws)
+        # Remove monitor workspace
+        DeleteWorkspace(ws_mon)
+        conToEnergy(detectors=ws)
+        if not CleanUp:
+            CloneWorkspace(ws, name+'_intermediate')
+        if ( rebinParam != ''): # Rebin data
+            rebinData(rebinParam, detectors=ws)
+        if ( tempK != -1 ): # "Detailed Balance" correction
+            ExponentialCorrection(ws, ws, 1.0, ( 11.606 / ( 2 * tempK ) ) )
+        # Final stage, grouping of detectors - apply name
+        if isTosca: # TOSCA's grouping is pre-determined and fixed
+            name = getRunTitle(ws)
+            groupTosca(name, invalid, detectors=ws)
+        else:
+            groupData(grouping, name, detectors=ws)
+        output_workspace_names.append(name)
+    if ( saveFormats != [] ): # Save data in selected formats
+        saveItems(output_workspace_names, saveFormats)
+    if ( calib != '' ): # Remove calibration workspace
+        DeleteWorkspace('__calibration')
+    return output_workspace_names
+
+def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1,
+        Suffix=''):
+    workspaces = []
+    for file in rawfiles:
+        ( dir, filename ) = os.path.split(file)
+        ( name, ext ) = os.path.splitext(filename)
+        try:
+            if ( SpecMin == -1 ) and ( SpecMax == -1 ):
+                LoadRaw(file, name+Suffix, LoadLogFiles=False)
+            else:
+                LoadRaw(file, name+Suffix, SpectrumMin=SpecMin, 
+                    SpectrumMax=SpecMax, LoadLogFiles=False)
+            workspaces.append(name+Suffix)
+        except ValueError, message:
+            print message
+            sys.exit(message)
+    if Sum and ( len(workspaces) > 1 ):
+        MergeRuns(','.join(workspaces), outWS+Suffix)
+        factor = 1.0 / len(workspaces)
+        Scale(outWS+Suffix, outWS+Suffix, factor)
+        for ws in workspaces:
+            DeleteWorkspace(ws)
+        return [outWS+Suffix]
+    else:
+        return workspaces
+
+def toscaChop(files):
+    '''Reduction routine for TOSCA instrument when input workspace must be 
+    "split" into parts and folded together after it has been corrected to the 
+    monitor.'''
+    wslist = []
+    workspace_list = loadData(files)
+    for raw in workspace_list:
+        invalid = getBadDetectorList(raw)
+        chopdata = ChopData(raw,raw+'_data')
+        wsgroup = mtd[raw+'_data'].getNames()
+        for ws in wsgroup:
+            ExtractSingleSpectrum(ws, ws+'mon', 140)
+            ConvertUnits(ws+'mon', ws+'mon', 'Wavelength', 'Indirect')
+            monitorEfficiency(ws+'mon')
+            CropWorkspace(ws, ws, StartWorkspaceIndex=0, EndWorkspaceIndex=139)
+            normToMon(Factor=1e9, monitor=ws+'mon', detectors=ws)
+            DeleteWorkspace(ws+'mon')
+        workspaces = ','.join(wsgroup)
+        ws = raw+'_c'
+        MergeRuns(workspaces, ws)
+        scaling = createScalingWorkspace(wsgroup, ws)
+        Divide(ws, scaling, ws)
+        DeleteWorkspace(scaling)
+        for grpws in wsgroup:
+            DeleteWorkspace(grpws)
+        conToEnergy(detectors=ws)
+        Rebin(ws, ws, '-2.5,0.015,3,-0.005,1000')
+        wstitle = getRunTitle(ws) # Have Run title as Workspace Name
+        ws = groupTosca(wstitle, invalid, detectors=ws)
+        wslist.append(ws)
+        DeleteWorkspace(raw)
+    return wslist
+
+def createScalingWorkspace(wsgroup, merged, wsname='__scaling'):
+    '''Based on the widths of the workspaces in the group once they've been
+    converted into Wavelength and normalised by the monitor, this function
+    uses the CreateWorksapce algorithm to decide how to scale the merged
+    workspace.'''
+    largest = 0
+    nlargest = 0
+    nlrgws = ''
+    for ws in wsgroup:
+        nbin = mtd[ws].getNumberBins()
+        if ( nbin > largest ):
+            nlargest = largest
+            largest = nbin
+        elif ( nbin > nlargest ):
+            nlargest = nbin
+            nlrgws = ws
+    nlargestX = mtd[nlrgws].dataX(0)[nlargest]	
+    largestValInNLrg = nlargestX
+    binIndex = mtd[merged].binIndexOf(largestValInNLrg)	
+    dataX = list(mtd[merged].readX(0))
+    dataY = []
+    dataE = []
+    totalBins = mtd[merged].getNumberBins()
+    nWS = len(wsgroup)
+    for i in range(0, binIndex):
+        dataE.append(0.0)
+        dataY.append(nWS)    
+    for i in range(binIndex, totalBins):
+        dataE.append(0.0)
+        dataY.append(1.0)	
+    CreateWorkspace(wsname, dataX, dataY, dataE, UnitX='Wavelength')
+    return wsname
+
+def getFirstMonFirstDet(inWS):
+    workspace = mtd[inWS]
+    FirstDet = FirstMon = -1
+    nhist = workspace.getNumberHistograms()
+    for counter in range(0, nhist):
+        try:
+            detector = workspace.getDetector(counter)
+        except RuntimeError: # This causes problems when encountering some
+            pass             # incomplete instrument definition files (TOSCA)
+        if detector.isMonitor():
+            if (FirstMon == -1):
+                FirstMon = counter
+        else:
+            if (FirstDet == -1):
+                FirstDet = counter
+        if ( FirstMon != -1 and FirstDet != -1 ):
+            break
+    return FirstMon, FirstDet
+
+def timeRegime(Smooth=True, monitor='', detectors=''):
+    SpecMon = mtd[monitor].readX(0)[0]
+    SpecDet = mtd[detectors].readX(0)[0]
+    if ( SpecMon == SpecDet ) and not adjustTOF(monitor):
+        LRef = getReferenceLength(detectors, 0)
+        alg = Unwrap(monitor, monitor, LRef = LRef)
+        join = float(alg.getPropertyValue('JoinWavelength'))
+        RemoveBins(monitor, monitor, join-0.001, join+0.001, 
+                Interpolation='Linear')
+        if Smooth:
+            FFTSmooth(monitor, monitor, 0)
+    else:
+        ConvertUnits(monitor, monitor, 'Wavelength', 'Indirect')
+    return monitor
+
+def monitorEfficiency(inWS):
+    inst = mtd[inWS].getInstrument()
+    try:
+        area = inst.getNumberParameter('mon-area')[0]
+        thickness = inst.getNumberParameter('mon-thickness')[0]
+        OneMinusExponentialCor(inWS, inWS, (8.3 * thickness), area)
+    except IndexError:
+        print "Unable to take Monitor Area and Thickness from Paremeter File."
+    return inWS
+
+def getReferenceLength(inWS, fdi):
+    workspace = mtd[inWS]
+    instrument = workspace.getInstrument()
+    sample = instrument.getSample()
+    source = instrument.getSource()
+    detector = workspace.getDetector(fdi)
+    sample_to_source = sample.getPos() - source.getPos()
+    r = detector.getDistance(sample)
+    x = sample_to_source.getZ()
+    LRef = x + r
+    return LRef
+
+def useCalib(detectors=''):
+    tmp = mtd[detectors]
+    shist = tmp.getNumberHistograms()
+    tmp = mtd['__calibration']
+    chist = tmp.getNumberHistograms()
+    if chist != shist:
+        msg = 'Number of spectra in calibration file does not match number \
+                that exist in the data file.'
+        print msg
+        sys.exit(msg)
+    else:
+        Divide(detectors,'__calibration',detectors)
+    return detectors
+
+def normToMon(Factor=1e6, monitor='', detectors=''):
+    ConvertUnits(detectors, detectors, 'Wavelength', 'Indirect')
+    RebinToWorkspace(detectors,monitor,detectors)
+    Divide(detectors,monitor,detectors)
+    Scale(detectors, detectors, Factor)
+    return detectors
+
+def conToEnergy(detectors=''):
+    ConvertUnits(detectors, detectors, 'DeltaE', 'Indirect')
+    CorrectKiKf(detectors, detectors, 'Indirect')
+    return detectors
+
+def rebinData(rebinParam, detectors=''):
+    Rebin(detectors, detectors, rebinParam)
+    return detectors
+
+def groupData(grouping, name, detectors=''):
+    if (grouping == 'Individual'):
+        if ( detectors != name ):
+            RenameWorkspace(detectors, name)
+        return name
+    elif ( grouping == 'All' ):
+        nhist = mtd[detectors].getNumberHistograms()
+        GroupDetectors(detectors, name, WorkspaceIndexList=range(0,nhist),
+            Behaviour='Average')
+    else:
+        GroupDetectors(detectors, name, MapFile=grouping, Behaviour='Average')
+    if ( detectors != name ):
+        DeleteWorkspace(detectors)
+    return name
+
+def groupTosca(wsname, invalid, detectors=''):
+    grp = range(0,70)
+    for i in invalid:
+        try:
+            grp.remove(i)
+        except ValueError:
+            pass
+    GroupDetectors(detectors, wsname, WorkspaceIndexList=grp, 
+        Behaviour='Average')
+    grp = range(70,140)
+    for i in invalid:
+        try:
+            grp.remove(i)
+        except ValueError:
+            pass
+    GroupDetectors(detectors, '__front', WorkspaceIndexList=grp, 
+        Behaviour='Average')
+    DeleteWorkspace(detectors)
+    ConjoinWorkspaces(wsname, '__front')
+    return wsname
+
+def getBadDetectorList(workspace):
+    IdentifyNoisyDetectors(workspace, '__temp_tsc_noise')
+    ws = mtd['__temp_tsc_noise']
+    nhist = ws.getNumberHistograms()
+    invalid = []
+    for i in range(0, nhist):
+        if ( ws.readY(i)[0] == 0.0 ):
+            invalid.append(i)
+    DeleteWorkspace('__temp_tsc_noise')
+    return invalid
+
+def backgroundRemoval(tofStart, tofEnd, detectors=''):
+    ConvertToDistribution(detectors)
+    FlatBackground(detectors, detectors, tofStart, tofEnd, Mode='Mean')
+    ConvertFromDistribution(detectors)
+    return detectors
+
+def cte_rebin(grouping, tempK, rebinParam, analyser, reflection,
+        saveFormats, CleanUp=False, Verbose=False):
+    # Generate list
+    ws_list = []
+    for workspace in list(mantid.getWorkspaceNames()):
+        if workspace.endswith('_'+analyser+reflection+r'_red_intermediate'):
+            ws_list.append(workspace)
+    if ( len(ws_list) == 0 ):
+        message = "No intermediate workspaces were found. Run with "
+        message += "'Keep Intermediate Workspaces' checked."
+        print message
+        sys.exit(message)
+    output = []
+    for ws in ws_list:
+        runNo = mtd[ws].getRun().getLogData("run_number").value
+        inst = mtd[ws].getInstrument().getName()
+        inst = ConfigService().facility().instrument(inst).shortName().lower()
+        name = inst + runNo + '_' + analyser + reflection + '_red'
+        if not CleanUp:
+            CloneWorkspace(ws, name)
+            ws = name
+        if ( rebinParam != ''):
+            rebin = rebinData(rebinParam, detectors=ws)
+        if ( tempK != -1 ): # Detailed Balance correction
+            ExponentialCorrection(ws, ws, 1.0, ( 11.606 / ( 2 * tempK ) ) )
+        groupData(grouping, name, detectors=ws)
+        output.append(name)
+    if ( saveFormats != [] ):
+        saveItems(output, saveFormats)
+    return output
+
+def createMappingFile(groupFile, ngroup, nspec, first):
+    if ( ngroup == 1 ): return 'All'
+    if ( nspec == 1 ): return 'Individual'
+    filename = mtd.getConfigProperty('defaultsave.directory')
+    filename += groupFile
+    handle = open(filename, 'w')
+    handle.write(str(ngroup) +  "\n" )
+    for n in range(0, ngroup):
+        n1 = n * nspec + first
+        handle.write(str(n+1) +  '\n' )
+        handle.write(str(nspec) +  '\n')
+        for i in range(1, nspec+1):
+            n3 = n1 + i - 1
+            handle.write(str(n3).center(4) + ' ')
+        handle.write('\n')
+    handle.close()
+    return filename
+
+def createCalibFile(rawfiles, suffix, peakMin, peakMax, backMin, backMax, 
+        specMin, specMax, PlotOpt=False):
+    savepath = mantid.getConfigProperty('defaultsave.directory')
+    runs = []
+    for file in rawfiles:
+        (direct, filename) = os.path.split(file)
+        (root, ext) = os.path.splitext(filename)
+        try:
+            LoadRaw(file, root, SpectrumMin=specMin, SpectrumMax=specMax,
+                LoadLogFiles=False)
+            runs.append(root)
+        except:
+            sys.exit('Indirect-Could not load raw file: ' + file)
+    cwsn = '__calibration'
+    if ( len(runs) > 1 ):
+        MergeRuns(",".join(runs), cwsn)
+        factor = 1.0 / len(runs)
+        Scale(cwsn, cwsn, factor)
+    else:
+        cwsn = runs[0]
+    tmp = mtd[cwsn]
+    nhist = tmp.getNumberHistograms()
+    FlatBackground(cwsn, cwsn, StartX=backMin, EndX=backMax, Mode='Mean')
+    Integration(cwsn, cwsn, peakMin, peakMax)
+    cal_ws = mtd[cwsn]
+    sum = 0
+    for i in range(0, nhist):
+        sum += cal_ws.readY(i)[0]
+    value = sum / nhist
+    CreateSingleValuedWorkspace('__cal_avg', value)
+    runNo = mtd[cwsn].getRun().getLogData("run_number").value
+    outWS_n = runs[0][:3] + runNo + suffix
+    Divide(cwsn, '__cal_avg', outWS_n)
+    DeleteWorkspace('__cal_avg')
+    savefile = os.path.join(savepath, outWS_n+'.nxs')
+    SaveNexusProcessed(outWS_n, savefile, 'Calibration')
+    if PlotOpt:
+        graph = plotTimeBin(outWS_n, 0)
+    ## Tidyup
+    DeleteWorkspace(cwsn)
+    return savefile
+
+def resolution(files, iconOpt, rebinParam, bground, 
+        instrument, analyser, reflection,
+        plotOpt=False, Res=True):
+    workspace_list = convert_to_energy(files, 'All', 
+        iconOpt['first'], iconOpt['last'], SumFiles=True, 
+        instrument=instrument, analyser=analyser, reflection=reflection)
+    iconWS = workspace_list[0]
+    if Res:
+        run = mtd[iconWS].getRun().getLogData("run_number").value
+        name = iconWS[:3].lower() + run + '_' + analyser + reflection + '_res'
+        FlatBackground(iconWS, '__background', bground[0], bground[1], 
+            Mode='Mean', OutputMode='Return Background')
+        Rebin(iconWS, iconWS, rebinParam)
+        FFTSmooth(iconWS,iconWS,0)
+        RebinToWorkspace('__background', iconWS, '__background')
+        Minus(iconWS, '__background', name)
+        DeleteWorkspace(iconWS)
+        DeleteWorkspace('__background')
+        SaveNexusProcessed(name, name+'.nxs')
+        if plotOpt:
+            graph = plotSpectrum(name, 0)
+        return name
+    else:
+        if plotOpt:
+            graph = plotSpectrum(iconWS, 0)
+        return iconWS
+
+def saveItems(workspaces, fileFormats, Verbose=False):
+    for workspace in workspaces:
+        for j in fileFormats:
+            if j == 'spe':
+                SaveSPE(workspace, workspace+'.spe')
+            elif j == 'nxs':
+                SaveNexusProcessed(workspace, workspace+'.nxs')
+            elif j == 'nxspe':
+                SaveNXSPE(workspace, workspace+'.nxspe')
+            else:
+                print 'Save: unknown file type.'
+                system.exit('Save: unknown file type.')
+
+def slice(inputfiles, calib, xrange, spec,  suffix, Save=False, Verbose=False,
+        Plot=False):
+    outWSlist = []
+    if  not ( ( len(xrange) == 2 ) or ( len(xrange) == 4 ) ):
+        mantid.sendLogMessage('>> TOF Range must contain either 2 or 4 \
+                numbers.')
+        sys.exit(1)
+    for file in inputfiles:
+        (direct, filename) = os.path.split(file)
+        (root, ext) = os.path.splitext(filename)
+        if spec == [0, 0]:
+            LoadRaw(file, root, LoadLogFiles=False)
+        else:
+            LoadRaw(file, root, SpectrumMin=spec[0], SpectrumMax=spec[1],
+                LoadLogFiles=False)
+        nhist = mtd[root].getNumberHistograms()
+        if calib != '':
+            useCalib(calib, inWS_n=root, outWS_n=root)
+        run = mtd[root].getRun().getLogData("run_number").value
+        sfile = root[:3].lower() + run + '_' + suffix + '_slt'
+        if (len(xrange) == 2):
+            Integration(root, sfile, xrange[0], xrange[1], 0, nhist-1)
+        else:
+            FlatBackground(root, sfile, StartX=xrange[2], EndX=xrange[3], 
+                    Mode='Mean')
+            Integration(sfile, sfile, xrange[0], xrange[1], 0, nhist-1)
+        if Save:
+            SaveNexusProcessed(sfile, sfile+'.nxs')
+        outWSlist.append(sfile)
+        DeleteWorkspace(root)
+    if Plot:
+        graph = plotBin(outWSlist, 0)
+
+def getInstrumentDetails(instrument):
+    workspace = mtd['__empty_' + instrument]
+    if ( workspace == None ):
+        idf_dir = mantid.getConfigProperty('instrumentDefinition.directory')
+        idf = idf_dir + instrument + '_Definition.xml'
+        LoadEmptyInstrument(idf, '__empty_'+instrument)
+        workspace = mtd['__empty_'+instrument]
+    instrument = workspace.getInstrument()
+    ana_list_split = instrument.getStringParameter('analysers')[0].split(',')
+    reflections = []
+    result = ''
+    for i in range(0,len(ana_list_split)):
+        list = []
+        name = 'refl-' + ana_list_split[i]
+        list.append( ana_list_split[i] )
+        try:
+            item = instrument.getStringParameter(name)[0]
+        except IndexError:
+            item = ''
+        refl = item.split(',')
+        list.append( refl )
+        reflections.append(list)
+    for i in range(0, len(reflections)):
+        message = reflections[i][0] + '-'
+        for j in range(0,len(reflections[i][1])):
+            message += str(reflections[i][1][j])
+            if j < ( len(reflections[i][1]) -1 ):
+                message += ','
+        result += message
+        if ( i < ( len(reflections) - 1) ):
+            result += '\n'
+    return result
+
+def getReflectionDetails(inst, analyser, refl):
+    idf_dir = mantid.getConfigProperty('instrumentDefinition.directory')
+    ws = '__empty_' + inst
+    if (mtd[ws] == None):
+        idf = idf_dir + inst + '_Definition.xml'
+        LoadEmptyInstrument(idf, ws)
+    ipf = idf_dir + inst + '_' + analyser + '_' + refl + '_Parameters.xml'
+    LoadParameterFile(ws, ipf)
+    inst = mtd[ws].getInstrument()
+    result = ''
+    try:
+        result += str( inst.getStringParameter('analysis-type')[0] ) + '\n'
+        result += str( int(inst.getNumberParameter('spectra-min')[0]) ) + '\n'
+        result += str( int(inst.getNumberParameter('spectra-max')[0]) ) + '\n'
+        result += str( inst.getNumberParameter('efixed-val')[0] ) + '\n'
+        result += str( int(inst.getNumberParameter('peak-start')[0]) ) + '\n'
+        result += str( int(inst.getNumberParameter('peak-end')[0]) ) + '\n'
+        result += str( int(inst.getNumberParameter('back-start')[0]) ) + '\n'
+        result += str( int(inst.getNumberParameter('back-end')[0]) ) + '\n'
+        result += inst.getStringParameter('rebin-default')[0]
+    except IndexError:
+        pass
+    return result
+
+def loadInst(instrument):    
+    ws = '__empty_' + instrument
+    if (mtd[ws] == None):
+        idf_dir = mantid.getConfigProperty('instrumentDefinition.directory')
+        idf = idf_dir + instrument + '_Definition.xml'
+        LoadEmptyInstrument(idf, ws)
+
+def adjustTOF(ws='', inst=''):
+    if ( ws != '' ):
+        ins = mtd[ws].getInstrument()
+    elif ( inst != ''):
+        idf_dir = mantid.getConfigProperty('instrumentDefinition.directory')
+        idf = idf_dir + inst + '_Definition.xml'
+        LoadEmptyInstrument(idf, 'ins')
+        ins = mtd['ins'].getInstrument()
+    try:
+        val = ins.getNumberParameter('adjustTOF')[0]
+    except IndexError:
+        val = 0
+    if ( val == 1 ):
+        return True
+    else:
+        return False
+
+def applyParameterFile(workspace, analyser, refl):
+    inst = mtd[workspace].getInstrument().getName()
+    idf_dir = mantid.getConfigProperty('instrumentDefinition.directory')
+    ipf = idf_dir + inst + '_' + analyser + '_' + refl + '_Parameters.xml'
+    LoadParameterFile(workspace, ipf)
diff --git a/Code/Mantid/Scripts/Inelastic/SpencerAbsCor.py b/Code/Mantid/Scripts/Inelastic/SpencerAbsCor.py
index 7607e4c3c0976bfb0196afac3990e662708d410e..9ae1bbb6e1830a3bb1e8cdad932f175c587e9d83 100644
--- a/Code/Mantid/Scripts/Inelastic/SpencerAbsCor.py
+++ b/Code/Mantid/Scripts/Inelastic/SpencerAbsCor.py
@@ -1,152 +1,152 @@
-# Spencer's F2PY Absorption Corrections Wrapper
-# and the application of these corrections
-###############################################################################
-## Handle selection of .pyd files for absorption corrections                 ##
-import platform                                                              ##
-opeteratingenvironment = platform.system()+platform.architecture()[0]        ##
-if ( opeteratingenvironment == 'Windows32bit' ):                             ##
-    import fltabs_win32 as fltabs                                            ##
-    import cylabs_win32 as cylabs                                            ##
-else:                                                                        ##
-    sys.exit('F2PY absorption corrections only available on Win32')          ##
-###############################################################################
-###############################################################################
-
-## Other imports
-from mantidsimple import *
-from mantidplot import *
-from IndirectCommon import getEfixed, createQaxis
-import math
-
-def GetWSangles(inWS):
-    tmp = mtd[inWS]
-    nhist = tmp.getNumberHistograms() # get no. of histograms/groups
-    sourcePos = tmp.getInstrument().getSource().getPos()
-    samplePos = tmp.getInstrument().getSample().getPos()
-    beamPos = samplePos - sourcePos
-    group_angles = [] # will be list of angles
-    for index in range(0, nhist):
-        detector = tmp.getDetector(index) # get index
-        twoTheta = detector.getTwoTheta(samplePos, beamPos)*180.0/math.pi # calc angle
-        group_angles.append(twoTheta) # add angle
-    return group_angles
-
-def WaveRange(inWS,delw, efixed):
-    oWS = '__spencer_WaveRange'
-    ExtractSingleSpectrum(inWS,oWS,0)
-    ConvertUnits(oWS,oWS,'Wavelength','Indirect', efixed)
-    tempWS = mtd[oWS]
-    Xin = tempWS.readX(0)
-    npt = len(Xin)-1			
-    xmin = tempWS.readX(0)[0]
-    xmax = tempWS.readX(0)[npt]
-    if delw == 0.0:
-        ebin = 0.5
-    else:
-        ebin = delw
-    nw1 = int(xmin/ebin)
-    nw2 = int(xmax/ebin)+1
-    w1 = nw1*ebin
-    w2 = nw2*ebin
-    wave = []
-    if delw == 0.0:
-        nw = 10
-        ebin = (w2-w1)/(nw-1)
-    else:
-        nw = nw2-nw1+1
-    for l in range(0,nw):
-        wave.append(w1+l*ebin)
-    DeleteWorkspace(oWS)
-    return wave
-
-def AbsRun(workdir, prefix, sam, geom, beam, ncan, size, density, sigs, siga,
-        avar, efixed, verbose=False, inputWS='Sam'):
-    det = GetWSangles(inputWS)
-    ndet = len(det)
-    wavelas = math.sqrt(81.787/efixed) # elastic wavelength
-    waves = WaveRange(inputWS, 0.0, efixed) # get wavelengths
-    nw = len(waves)
-    DataX = []
-    DataE = []
-    for n in range(0,nw):
-        DataX.append(waves[n])
-        DataE.append(0)
-    name = prefix + sam + '_' + geom
-    assWS = name + '_ass'
-    asscWS = name + '_assc'
-    acscWS = name + '_acsc'
-    accWS = name + '_acc'
-    wrk = workdir + prefix + sam
-    wrk.ljust(120,' ')
-    plot_list = []
-    dataY_a1ws = []
-    dataY_a2ws = []
-    dataY_a3ws = []
-    dataY_a4ws = []
-    for n in range(0,ndet):
-        if geom == 'flt':
-            angles = [avar, det[n]]
-            kill, A1, A2, A3, A4 = fltabs.fltabs(ncan, size, density, sigs,
-                siga, angles, waves, n, wrk, 0)
-        if geom == 'cyl':
-            astep = avar
-            angle = det[n]
-            kill, A1, A2, A3, A4 = cylabs.cylabs(astep, beam, ncan, size,
-                density, sigs, siga, angle, wavelas, waves, n, wrk, 0)
-        if kill == 0:
-            print 'Detector '+str(n)+' at angle : '+str(det[n])+' * successful'
-            dataY_a1ws += list(A1)
-            if ncan > 1:
-                dataY_a2ws += list(A2)
-                dataY_a3ws += list(A3)
-                dataY_a4ws += list(A4)              
-            plot_list.append(n)
-    ## Create the workspaces
-    nspec = len(plot_list)
-    DataX = DataX * nspec
-    DataE = DataE * nspec
-    qAxis = createQaxis(inputWS)
-    CreateWorkspace(assWS, DataX, dataY_a1ws, DataE,nspec,'Wavelength',
-            VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=qAxis)
-    if ( ncan > 1 ):
-        CreateWorkspace(asscWS, DataX, dataY_a2ws, DataE,nspec,'Wavelength',
-            VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=qAxis)
-        CreateWorkspace(acscWS, DataX, dataY_a3ws, DataE,nspec,'Wavelength',
-            VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=qAxis)
-        CreateWorkspace(accWS, DataX, dataY_a4ws, DataE,nspec,'Wavelength',
-            VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=qAxis)
-    ## Tidy up & Save output
-    SaveNexusProcessed(assWS, assWS+'.nxs')
-    if ncan > 1:
-        SaveNexusProcessed(asscWS, asscWS+'.nxs')
-        SaveNexusProcessed(acscWS, acscWS+'.nxs')
-        SaveNexusProcessed(accWS, accWS+'.nxs')
-    if ncan > 1:
-        return [assWS, asscWS, acscWS, accWS]
-    else:
-        return [assWS]
-
-def AbsRunFeeder(inputws, geom, beam, ncan, size, density, sigs, siga, avar,
-        plotOpt='None'):
-    '''Handles the feeding of input and plotting of output for the F2PY
-    absorption correction routine.'''
-    ws = mtd[inputws]
-    ## workdir is default save directory
-    workdir = mantid.getConfigProperty('defaultsave.directory')
-    ## prefix is instrument short name
-    prefix = ws.getInstrument().getName()
-    prefix = ConfigService().facility().instrument(prefix).shortName().lower()
-    ## sam = run number
-    sam = ws.getRun().getLogData("run_number").value
-    ## efixed can be taken from the instrument parameter file
-    efixed = getEfixed(inputws)
-    ## Run the routine
-    workspaces = AbsRun(workdir, prefix, sam, geom, beam, ncan, size, density,
-        sigs, siga, avar, efixed, inputWS=inputws)
-    if ( plotOpt == 'None' ):
-        return
-    if ( plotOpt == 'Wavelength' or plotOpt == 'Both' ):
-        graph = plotSpectrum(workspaces, 0)
-    if ( plotOpt == 'Angle' or plotOpt == 'Both' ):
-        graph = plotTimeBin(workspaces, 0)
-        graph.activeLayer().setAxisTitle(Layer.Bottom, 'Angle')
+# Spencer's F2PY Absorption Corrections Wrapper
+# and the application of these corrections
+###############################################################################
+## Handle selection of .pyd files for absorption corrections                 ##
+import platform                                                              ##
+opeteratingenvironment = platform.system()+platform.architecture()[0]        ##
+if ( opeteratingenvironment == 'Windows32bit' ):                             ##
+    import fltabs_win32 as fltabs                                            ##
+    import cylabs_win32 as cylabs                                            ##
+else:                                                                        ##
+    sys.exit('F2PY absorption corrections only available on Win32')          ##
+###############################################################################
+###############################################################################
+
+## Other imports
+from mantidsimple import *
+from mantidplot import *
+from IndirectCommon import getEfixed, createQaxis
+import math
+
+def GetWSangles(inWS):
+    tmp = mtd[inWS]
+    nhist = tmp.getNumberHistograms() # get no. of histograms/groups
+    sourcePos = tmp.getInstrument().getSource().getPos()
+    samplePos = tmp.getInstrument().getSample().getPos()
+    beamPos = samplePos - sourcePos
+    group_angles = [] # will be list of angles
+    for index in range(0, nhist):
+        detector = tmp.getDetector(index) # get index
+        twoTheta = detector.getTwoTheta(samplePos, beamPos)*180.0/math.pi # calc angle
+        group_angles.append(twoTheta) # add angle
+    return group_angles
+
+def WaveRange(inWS,delw, efixed):
+    oWS = '__spencer_WaveRange'
+    ExtractSingleSpectrum(inWS,oWS,0)
+    ConvertUnits(oWS,oWS,'Wavelength','Indirect', efixed)
+    tempWS = mtd[oWS]
+    Xin = tempWS.readX(0)
+    npt = len(Xin)-1			
+    xmin = tempWS.readX(0)[0]
+    xmax = tempWS.readX(0)[npt]
+    if delw == 0.0:
+        ebin = 0.5
+    else:
+        ebin = delw
+    nw1 = int(xmin/ebin)
+    nw2 = int(xmax/ebin)+1
+    w1 = nw1*ebin
+    w2 = nw2*ebin
+    wave = []
+    if delw == 0.0:
+        nw = 10
+        ebin = (w2-w1)/(nw-1)
+    else:
+        nw = nw2-nw1+1
+    for l in range(0,nw):
+        wave.append(w1+l*ebin)
+    DeleteWorkspace(oWS)
+    return wave
+
+def AbsRun(workdir, prefix, sam, geom, beam, ncan, size, density, sigs, siga,
+        avar, efixed, verbose=False, inputWS='Sam'):
+    det = GetWSangles(inputWS)
+    ndet = len(det)
+    wavelas = math.sqrt(81.787/efixed) # elastic wavelength
+    waves = WaveRange(inputWS, 0.0, efixed) # get wavelengths
+    nw = len(waves)
+    DataX = []
+    DataE = []
+    for n in range(0,nw):
+        DataX.append(waves[n])
+        DataE.append(0)
+    name = prefix + sam + '_' + geom
+    assWS = name + '_ass'
+    asscWS = name + '_assc'
+    acscWS = name + '_acsc'
+    accWS = name + '_acc'
+    wrk = workdir + prefix + sam
+    wrk.ljust(120,' ')
+    plot_list = []
+    dataY_a1ws = []
+    dataY_a2ws = []
+    dataY_a3ws = []
+    dataY_a4ws = []
+    for n in range(0,ndet):
+        if geom == 'flt':
+            angles = [avar, det[n]]
+            kill, A1, A2, A3, A4 = fltabs.fltabs(ncan, size, density, sigs,
+                siga, angles, waves, n, wrk, 0)
+        if geom == 'cyl':
+            astep = avar
+            angle = det[n]
+            kill, A1, A2, A3, A4 = cylabs.cylabs(astep, beam, ncan, size,
+                density, sigs, siga, angle, wavelas, waves, n, wrk, 0)
+        if kill == 0:
+            print 'Detector '+str(n)+' at angle : '+str(det[n])+' * successful'
+            dataY_a1ws += list(A1)
+            if ncan > 1:
+                dataY_a2ws += list(A2)
+                dataY_a3ws += list(A3)
+                dataY_a4ws += list(A4)              
+            plot_list.append(n)
+    ## Create the workspaces
+    nspec = len(plot_list)
+    DataX = DataX * nspec
+    DataE = DataE * nspec
+    qAxis = createQaxis(inputWS)
+    CreateWorkspace(assWS, DataX, dataY_a1ws, DataE,nspec,'Wavelength',
+            VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=qAxis)
+    if ( ncan > 1 ):
+        CreateWorkspace(asscWS, DataX, dataY_a2ws, DataE,nspec,'Wavelength',
+            VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=qAxis)
+        CreateWorkspace(acscWS, DataX, dataY_a3ws, DataE,nspec,'Wavelength',
+            VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=qAxis)
+        CreateWorkspace(accWS, DataX, dataY_a4ws, DataE,nspec,'Wavelength',
+            VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=qAxis)
+    ## Tidy up & Save output
+    SaveNexusProcessed(assWS, assWS+'.nxs')
+    if ncan > 1:
+        SaveNexusProcessed(asscWS, asscWS+'.nxs')
+        SaveNexusProcessed(acscWS, acscWS+'.nxs')
+        SaveNexusProcessed(accWS, accWS+'.nxs')
+    if ncan > 1:
+        return [assWS, asscWS, acscWS, accWS]
+    else:
+        return [assWS]
+
+def AbsRunFeeder(inputws, geom, beam, ncan, size, density, sigs, siga, avar,
+        plotOpt='None'):
+    '''Handles the feeding of input and plotting of output for the F2PY
+    absorption correction routine.'''
+    ws = mtd[inputws]
+    ## workdir is default save directory
+    workdir = mantid.getConfigProperty('defaultsave.directory')
+    ## prefix is instrument short name
+    prefix = ws.getInstrument().getName()
+    prefix = ConfigService().facility().instrument(prefix).shortName().lower()
+    ## sam = run number
+    sam = ws.getRun().getLogData("run_number").value
+    ## efixed can be taken from the instrument parameter file
+    efixed = getEfixed(inputws)
+    ## Run the routine
+    workspaces = AbsRun(workdir, prefix, sam, geom, beam, ncan, size, density,
+        sigs, siga, avar, efixed, inputWS=inputws)
+    if ( plotOpt == 'None' ):
+        return
+    if ( plotOpt == 'Wavelength' or plotOpt == 'Both' ):
+        graph = plotSpectrum(workspaces, 0)
+    if ( plotOpt == 'Angle' or plotOpt == 'Both' ):
+        graph = plotTimeBin(workspaces, 0)
+        graph.activeLayer().setAxisTitle(Layer.Bottom, 'Angle')
diff --git a/Code/Mantid/Scripts/SANS/utest_SANSReduction.py b/Code/Mantid/Scripts/SANS/utest_SANSReduction.py
index 940967471b0de265180e8fef0378c88c32dafde8..91dd4159b186275479925bc1300dea7d5180ab3f 100644
--- a/Code/Mantid/Scripts/SANS/utest_SANSReduction.py
+++ b/Code/Mantid/Scripts/SANS/utest_SANSReduction.py
@@ -1,88 +1,88 @@
-"""
-    Unit tests for SANS reduction
-"""
-from MantidFramework import *
-mtd.initialise()
-import sys
-import unittest
-import SANSReduction
-from mantidsimple import *
-
-class TestReduction(unittest.TestCase):
-    """
-        Simple test to check that the API all works out.
-        No actual value checking.
-    """
-    
-    def setUp(self):
-        SANSReduction.DataPath("../../../../../Test/Data/SANS2D")
-        SANSReduction.UserPath("../../../../../Test/Data/SANS2D")
-        SANSReduction.SANS2D()    
-        SANSReduction.Set1D()
-        SANSReduction.MaskFile('MASKSANS2D.091A')
-        self.ws_name,_ = SANSReduction.AssignSample('992.raw')
-                
-    def test_move_detector(self):
-        # Refactor test: Removing the following line and replacing it by a call to a call to an instrument class method. 
-        #v1, v2 = SANSReduction.SetupComponentPositions(SANSReduction.INSTRUMENT.cur_detector().name() , self.ws_name, 3.69, 2.59)    
-        v1, v2 = SANSReduction.INSTRUMENT.set_component_positions(self.ws_name, 3.69, 2.59)    
-        self.assertEquals(v1[0],0)
-        self.assertEquals(v1[1],0)
-        self.assertEquals(v2[0],-3.69)
-        self.assertEquals(v2[1],-2.59)
-        
-    def test_reduction(self):
-        SANSReduction.Detector("rear-detector")
-        ws = SANSReduction.WavRangeReduction()
-        self.assertEquals(SANSReduction._SAMPLE_SETUP._maskrmin, [0,0])
-        self.assertEquals(SANSReduction._SAMPLE_SETUP._maskrmax, [-0.084199999999999997, 0.19650000000000001])
-
-        x = mtd[ws].dataX(0)[:len(mtd[ws].dataX(0))]
-        y = mtd[ws].dataY(0)
-        e = mtd[ws].dataE(0)
-        data = zip(x,y,e)
-
-        self.assertEquals(len(data), 178)
-
-        self.assertAlmostEqual(data[10][0], 0.0243799, 0.00001)
-        self.assertAlmostEqual(data[10][1], 83.6761, 0.00001)
-        self.assertAlmostEqual(data[10][2], 0.462703, 0.00001)
-
-        self.assertAlmostEqual(data[100][0], 0.144893, 0.00001)
-        self.assertAlmostEqual(data[100][1], 3.68945, 0.00001)
-        self.assertAlmostEqual(data[100][2], 0.023424, 0.00001)
-
-        self.assertAlmostEqual(data[50][0], 0.0538318, 0.00001)
-        self.assertAlmostEqual(data[50][1], 22.862, 0.00001)
-        self.assertAlmostEqual(data[50][2], 0.112137, 0.00001)
-
-
-    def test_reduction_front(self):
-        SANSReduction.Detector("front-detector")
-        ws = SANSReduction.WavRangeReduction()
-        self.assertEquals(SANSReduction._SAMPLE_SETUP._maskrmin, [0,0])
-        self.assertEquals(SANSReduction._SAMPLE_SETUP._maskrmax, [0,0])
-
-        x = mtd[ws].dataX(0)[:len(mtd[ws].dataX(0))]
-        y = mtd[ws].dataY(0)
-        e = mtd[ws].dataE(0)
-        data = zip(x,y,e)
-
-        self.assertEquals(len(data), 122)
-
-        self.assertAlmostEqual(data[10][0], 0.109811, 0.00001)
-        self.assertAlmostEqual(data[10][1], 6.56454, 0.00001)
-        self.assertAlmostEqual(data[10][2], 0.291573, 0.00001)
-
-        self.assertAlmostEqual(data[100][0], 0.65262, 0.00001)
-        self.assertAlmostEqual(data[100][1], 0.703535, 0.00001)
-        self.assertAlmostEqual(data[100][2], 0.00570243, 0.00001)
-
-        self.assertAlmostEqual(data[50][0], 0.242466, 0.00001)
-        self.assertAlmostEqual(data[50][1], 1.53335, 0.00001)
-        self.assertAlmostEqual(data[50][2], 0.0194757, 0.00001)
-
-if __name__ == '__main__':
-    unittest.main()
-    
+"""
+    Unit tests for SANS reduction
+"""
+from MantidFramework import *
+mtd.initialise()
+import sys
+import unittest
+import SANSReduction
+from mantidsimple import *
+
+class TestReduction(unittest.TestCase):
+    """
+        Simple test to check that the API all works out.
+        No actual value checking.
+    """
+    
+    def setUp(self):
+        SANSReduction.DataPath("../../../../../Test/Data/SANS2D")
+        SANSReduction.UserPath("../../../../../Test/Data/SANS2D")
+        SANSReduction.SANS2D()    
+        SANSReduction.Set1D()
+        SANSReduction.MaskFile('MASKSANS2D.091A')
+        self.ws_name,_ = SANSReduction.AssignSample('992.raw')
+                
+    def test_move_detector(self):
+        # Refactor test: Removing the following line and replacing it by a call to a call to an instrument class method. 
+        #v1, v2 = SANSReduction.SetupComponentPositions(SANSReduction.INSTRUMENT.cur_detector().name() , self.ws_name, 3.69, 2.59)    
+        v1, v2 = SANSReduction.INSTRUMENT.set_component_positions(self.ws_name, 3.69, 2.59)    
+        self.assertEquals(v1[0],0)
+        self.assertEquals(v1[1],0)
+        self.assertEquals(v2[0],-3.69)
+        self.assertEquals(v2[1],-2.59)
+        
+    def test_reduction(self):
+        SANSReduction.Detector("rear-detector")
+        ws = SANSReduction.WavRangeReduction()
+        self.assertEquals(SANSReduction._SAMPLE_SETUP._maskrmin, [0,0])
+        self.assertEquals(SANSReduction._SAMPLE_SETUP._maskrmax, [-0.084199999999999997, 0.19650000000000001])
+
+        x = mtd[ws].dataX(0)[:len(mtd[ws].dataX(0))]
+        y = mtd[ws].dataY(0)
+        e = mtd[ws].dataE(0)
+        data = zip(x,y,e)
+
+        self.assertEquals(len(data), 178)
+
+        self.assertAlmostEqual(data[10][0], 0.0243799, 0.00001)
+        self.assertAlmostEqual(data[10][1], 83.6761, 0.00001)
+        self.assertAlmostEqual(data[10][2], 0.462703, 0.00001)
+
+        self.assertAlmostEqual(data[100][0], 0.144893, 0.00001)
+        self.assertAlmostEqual(data[100][1], 3.68945, 0.00001)
+        self.assertAlmostEqual(data[100][2], 0.023424, 0.00001)
+
+        self.assertAlmostEqual(data[50][0], 0.0538318, 0.00001)
+        self.assertAlmostEqual(data[50][1], 22.862, 0.00001)
+        self.assertAlmostEqual(data[50][2], 0.112137, 0.00001)
+
+
+    def test_reduction_front(self):
+        SANSReduction.Detector("front-detector")
+        ws = SANSReduction.WavRangeReduction()
+        self.assertEquals(SANSReduction._SAMPLE_SETUP._maskrmin, [0,0])
+        self.assertEquals(SANSReduction._SAMPLE_SETUP._maskrmax, [0,0])
+
+        x = mtd[ws].dataX(0)[:len(mtd[ws].dataX(0))]
+        y = mtd[ws].dataY(0)
+        e = mtd[ws].dataE(0)
+        data = zip(x,y,e)
+
+        self.assertEquals(len(data), 122)
+
+        self.assertAlmostEqual(data[10][0], 0.109811, 0.00001)
+        self.assertAlmostEqual(data[10][1], 6.56454, 0.00001)
+        self.assertAlmostEqual(data[10][2], 0.291573, 0.00001)
+
+        self.assertAlmostEqual(data[100][0], 0.65262, 0.00001)
+        self.assertAlmostEqual(data[100][1], 0.703535, 0.00001)
+        self.assertAlmostEqual(data[100][2], 0.00570243, 0.00001)
+
+        self.assertAlmostEqual(data[50][0], 0.242466, 0.00001)
+        self.assertAlmostEqual(data[50][1], 1.53335, 0.00001)
+        self.assertAlmostEqual(data[50][2], 0.0194757, 0.00001)
+
+if __name__ == '__main__':
+    unittest.main()
+    
     
\ No newline at end of file
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/RebinningCutterOperator/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/RebinningCutterOperator/CMakeLists.txt
index 92e4074e22585d725c648c267a4b67e283bdb671..8380ad8b93f2c3b5bef299a7b63da100f58dc916 100755
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/RebinningCutterOperator/CMakeLists.txt
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/RebinningCutterOperator/CMakeLists.txt
@@ -1,16 +1,16 @@
-cmake_minimum_required(VERSION 2.6)
-PROJECT(MantidParaViewRebinningCutter)
-
-FIND_PACKAGE(ParaView REQUIRED)
-INCLUDE(${PARAVIEW_USE_FILE})
-
-set_mantid_subprojects(Vates/VatesAPI)
-
-ADD_PARAVIEW_PLUGIN(MantidParaViewRebinningCutterSMPlugin "1.0"
-	SERVER_MANAGER_XML RebinningCutter.xml
-	SERVER_MANAGER_SOURCES vtkRebinningCutter.cxx
-        GUI_RESOURCES RebinningCutter.qrc
-		GUI_RESOURCE_FILES RebinningCutterGUI.xml
-)
-
-TARGET_LINK_LIBRARIES(MantidParaViewRebinningCutterSMPlugin ${MANTID_SUBPROJECT_LIBS} ${HDF5_LIBRARY})
+cmake_minimum_required(VERSION 2.6)
+PROJECT(MantidParaViewRebinningCutter)
+
+FIND_PACKAGE(ParaView REQUIRED)
+INCLUDE(${PARAVIEW_USE_FILE})
+
+set_mantid_subprojects(Vates/VatesAPI)
+
+ADD_PARAVIEW_PLUGIN(MantidParaViewRebinningCutterSMPlugin "1.0"
+	SERVER_MANAGER_XML RebinningCutter.xml
+	SERVER_MANAGER_SOURCES vtkRebinningCutter.cxx
+        GUI_RESOURCES RebinningCutter.qrc
+		GUI_RESOURCE_FILES RebinningCutterGUI.xml
+)
+
+TARGET_LINK_LIBRARIES(MantidParaViewRebinningCutterSMPlugin ${MANTID_SUBPROJECT_LIBS} ${HDF5_LIBRARY})
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/RebinningCutterOperator/vtkRebinningCutter.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/RebinningCutterOperator/vtkRebinningCutter.h
index 102d4e7133232d38420bbba85f50c0231a8e7f59..f0ef075c90d6052cd0996eca61552d040a661fe7 100755
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/RebinningCutterOperator/vtkRebinningCutter.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/RebinningCutterOperator/vtkRebinningCutter.h
@@ -1,148 +1,148 @@
-#ifndef _vtkRebinningCutter_h
-#define _vtkRebinningCutter_h
-#include "vtkUnstructuredGridAlgorithm.h"
-#include "MantidVatesAPI/RebinningCutterPresenter.h"
-#include "MantidVatesAPI/vtkDataSetFactory.h"
-#include "RebinningActionManager.h"
-
-/**
- *
- * Paraview Filter implementing rebinning/cutting operations.
-
-    @author Owen Arnold, RAL ISIS
-    @date 18/03/2011
-
-    Copyright &copy; 2007-10 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>.
-    Code Documentation is available at: <http://doxygen.mantidproject.org>
-*/
-
-class vtkImplicitFunction;
-class VTK_EXPORT vtkRebinningCutter : public vtkUnstructuredGridAlgorithm
-{
-public:
-  static vtkRebinningCutter *New();
-  vtkTypeRevisionMacro(vtkRebinningCutter,vtkUnstructuredGridAlgorithm);
-  void PrintSelf(ostream& os, vtkIndent indent);
-
-  /// Paraview Related Commands. See *.xml proxy/property file --------------------------------
-  void SetClipFunction( vtkImplicitFunction * func);
-  void SetMaxThreshold(double maxThreshold);
-  void SetMinThreshold(double minThreshold);
-  void SetAppliedXDimensionXML(std::string xml);
-  void SetAppliedYDimensionXML(std::string xml);
-  void SetAppliedZDimensionXML(std::string xml);
-  void SetAppliedTDimensionXML(std::string xml);
-  const char* GetInputGeometryXML();
-  /// Paraview Related Commands. See *.xml proxy/property file --------------------------------
-
-  /// Called by presenter to force progress information updating.
-  void UpdateAlgorithmProgress(double progress);
-
-protected:
-
-  ///Constructor
-  vtkRebinningCutter();
-
-  ///Destructor
-  ~vtkRebinningCutter();
-
-  ///Request information prior to execution.
-  int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
-
-  ///Execution.
-  int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
-
-  ///Update extents.
-  int RequestUpdateExtent(vtkInformation*,
-                                    vtkInformationVector**, vtkInformationVector* );
-
-  ///Handle time variation.
-  unsigned long GetMTime();
-
-  ///Overrriden fill inports so that vtkDataSets may be specified.
-  int FillInputPortInformation(int port, vtkInformation* info);
-
-private:
-
-  vtkRebinningCutter(const vtkRebinningCutter&);
-
-  void operator = (const vtkRebinningCutter&);
-
-  /// Executor peforms the logic associated with running rebinning operations.
-  Mantid::VATES::RebinningCutterPresenter m_presenter;
-  /// Get the x dimension form the input dataset.
-  Mantid::VATES::Dimension_sptr getDimensionX(vtkDataSet* in_ds) const;
-
-  /// Get the y dimension form the input dataset.
-  Mantid::VATES::Dimension_sptr getDimensionY(vtkDataSet* in_ds) const;
-
-  /// Get the z dimension form the input dataset.
-  Mantid::VATES::Dimension_sptr getDimensionZ(vtkDataSet* in_ds) const;
-
-  /// Get the t dimension form the input dataset.
-  Mantid::VATES::Dimension_sptr getDimensiont(vtkDataSet* in_ds) const;
-
-  boost::shared_ptr<Mantid::API::ImplicitFunction> constructBox(
-          Mantid::VATES::Dimension_sptr spDimX,
-          Mantid::VATES::Dimension_sptr spDimY,
-          Mantid::VATES::Dimension_sptr spDimZ) const;
-
-  /// Selects the dataset factory to use.
-  Mantid::VATES::vtkDataSetFactory_sptr createDataSetFactory(Mantid::MDDataObjects::MDWorkspace_sptr spRebinnedWs) const;
-
-  /// DataSet handles remappings, so allows regeneration of a visual dataset in rapid time.
-  Mantid::VATES::vtkDataSetFactory_sptr createQuickChangeDataSetFactory(Mantid::MDDataObjects::MDWorkspace_sptr spRebinnedWs) const;
-
-  /// Dataset does not handle remappings and is therefore may be generated quickly.
-  Mantid::VATES::vtkDataSetFactory_sptr createQuickRenderDataSetFactory(Mantid::MDDataObjects::MDWorkspace_sptr spRebinnedWs) const;
-
-  /// Decides on the necessary iteration action that is to be performed.
-  void determineAnyCommonExecutionActions(const int timestep);
-
-  /// creates a hash of arguments considered as flags for redrawing the visualisation dataset.
-  std::string createRedrawHash() const;
-
-  /// Clip function provided by ClipFunction ProxyProperty
-  vtkImplicitFunction* m_clipFunction;
-  /// Cached vtkDataSet. Enables fast visualisation where possible.
-  vtkDataSet* m_cachedVTKDataSet;
-  /// Arguments that cause redrawing are hashed and cached for rapid comparison regarding any changes.
-  std::string m_cachedRedrawArguments;
-  /// Flag indicating whether set up has occured or not
-  bool m_isSetup;
-  /// Flag containing the timestep.
-  int m_timestep;
-  /// Threshold maximum for signal values to be rendered as cells.
-  double m_thresholdMax;
-  /// Threshold minimum for signal values to be rendered as cells.
-  double m_thresholdMin;
-  /// the dimension information applied to the xDimension Mapping.
-  Mantid::VATES::Dimension_sptr m_appliedXDimension;
-  /// the dimension information applied to the yDimension Mapping.
-  Mantid::VATES::Dimension_sptr m_appliedYDimension;
-  /// the dimension information applied to the zDimension Mapping.
-  Mantid::VATES::Dimension_sptr m_appliedZDimension;
-  /// the dimension information applied to the tDimension Mapping.
-  Mantid::VATES::Dimension_sptr m_appliedTDimension;
-  /// Manages the precedence of rebinning related actions.
-  Mantid::VATES::RebinningActionManger m_actionRequester;
-
-};
-#endif
+#ifndef _vtkRebinningCutter_h
+#define _vtkRebinningCutter_h
+#include "vtkUnstructuredGridAlgorithm.h"
+#include "MantidVatesAPI/RebinningCutterPresenter.h"
+#include "MantidVatesAPI/vtkDataSetFactory.h"
+#include "RebinningActionManager.h"
+
+/**
+ *
+ * Paraview Filter implementing rebinning/cutting operations.
+
+    @author Owen Arnold, RAL ISIS
+    @date 18/03/2011
+
+    Copyright &copy; 2007-10 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://svn.mantidproject.org/mantid/trunk/Code/Mantid>.
+    Code Documentation is available at: <http://doxygen.mantidproject.org>
+*/
+
+class vtkImplicitFunction;
+class VTK_EXPORT vtkRebinningCutter : public vtkUnstructuredGridAlgorithm
+{
+public:
+  static vtkRebinningCutter *New();
+  vtkTypeRevisionMacro(vtkRebinningCutter,vtkUnstructuredGridAlgorithm);
+  void PrintSelf(ostream& os, vtkIndent indent);
+
+  /// Paraview Related Commands. See *.xml proxy/property file --------------------------------
+  void SetClipFunction( vtkImplicitFunction * func);
+  void SetMaxThreshold(double maxThreshold);
+  void SetMinThreshold(double minThreshold);
+  void SetAppliedXDimensionXML(std::string xml);
+  void SetAppliedYDimensionXML(std::string xml);
+  void SetAppliedZDimensionXML(std::string xml);
+  void SetAppliedTDimensionXML(std::string xml);
+  const char* GetInputGeometryXML();
+  /// Paraview Related Commands. See *.xml proxy/property file --------------------------------
+
+  /// Called by presenter to force progress information updating.
+  void UpdateAlgorithmProgress(double progress);
+
+protected:
+
+  ///Constructor
+  vtkRebinningCutter();
+
+  ///Destructor
+  ~vtkRebinningCutter();
+
+  ///Request information prior to execution.
+  int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
+
+  ///Execution.
+  int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
+
+  ///Update extents.
+  int RequestUpdateExtent(vtkInformation*,
+                                    vtkInformationVector**, vtkInformationVector* );
+
+  ///Handle time variation.
+  unsigned long GetMTime();
+
+  ///Overrriden fill inports so that vtkDataSets may be specified.
+  int FillInputPortInformation(int port, vtkInformation* info);
+
+private:
+
+  vtkRebinningCutter(const vtkRebinningCutter&);
+
+  void operator = (const vtkRebinningCutter&);
+
+  /// Executor peforms the logic associated with running rebinning operations.
+  Mantid::VATES::RebinningCutterPresenter m_presenter;
+  /// Get the x dimension form the input dataset.
+  Mantid::VATES::Dimension_sptr getDimensionX(vtkDataSet* in_ds) const;
+
+  /// Get the y dimension form the input dataset.
+  Mantid::VATES::Dimension_sptr getDimensionY(vtkDataSet* in_ds) const;
+
+  /// Get the z dimension form the input dataset.
+  Mantid::VATES::Dimension_sptr getDimensionZ(vtkDataSet* in_ds) const;
+
+  /// Get the t dimension form the input dataset.
+  Mantid::VATES::Dimension_sptr getDimensiont(vtkDataSet* in_ds) const;
+
+  boost::shared_ptr<Mantid::API::ImplicitFunction> constructBox(
+          Mantid::VATES::Dimension_sptr spDimX,
+          Mantid::VATES::Dimension_sptr spDimY,
+          Mantid::VATES::Dimension_sptr spDimZ) const;
+
+  /// Selects the dataset factory to use.
+  Mantid::VATES::vtkDataSetFactory_sptr createDataSetFactory(Mantid::MDDataObjects::MDWorkspace_sptr spRebinnedWs) const;
+
+  /// DataSet handles remappings, so allows regeneration of a visual dataset in rapid time.
+  Mantid::VATES::vtkDataSetFactory_sptr createQuickChangeDataSetFactory(Mantid::MDDataObjects::MDWorkspace_sptr spRebinnedWs) const;
+
+  /// Dataset does not handle remappings and is therefore may be generated quickly.
+  Mantid::VATES::vtkDataSetFactory_sptr createQuickRenderDataSetFactory(Mantid::MDDataObjects::MDWorkspace_sptr spRebinnedWs) const;
+
+  /// Decides on the necessary iteration action that is to be performed.
+  void determineAnyCommonExecutionActions(const int timestep);
+
+  /// creates a hash of arguments considered as flags for redrawing the visualisation dataset.
+  std::string createRedrawHash() const;
+
+  /// Clip function provided by ClipFunction ProxyProperty
+  vtkImplicitFunction* m_clipFunction;
+  /// Cached vtkDataSet. Enables fast visualisation where possible.
+  vtkDataSet* m_cachedVTKDataSet;
+  /// Arguments that cause redrawing are hashed and cached for rapid comparison regarding any changes.
+  std::string m_cachedRedrawArguments;
+  /// Flag indicating whether set up has occured or not
+  bool m_isSetup;
+  /// Flag containing the timestep.
+  int m_timestep;
+  /// Threshold maximum for signal values to be rendered as cells.
+  double m_thresholdMax;
+  /// Threshold minimum for signal values to be rendered as cells.
+  double m_thresholdMin;
+  /// the dimension information applied to the xDimension Mapping.
+  Mantid::VATES::Dimension_sptr m_appliedXDimension;
+  /// the dimension information applied to the yDimension Mapping.
+  Mantid::VATES::Dimension_sptr m_appliedYDimension;
+  /// the dimension information applied to the zDimension Mapping.
+  Mantid::VATES::Dimension_sptr m_appliedZDimension;
+  /// the dimension information applied to the tDimension Mapping.
+  Mantid::VATES::Dimension_sptr m_appliedTDimension;
+  /// Manages the precedence of rebinning related actions.
+  Mantid::VATES::RebinningActionManger m_actionRequester;
+
+};
+#endif
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/vtkSQWReader.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/vtkSQWReader.h
index c6636fc73a3e864a9243bcdf7341f961d760b8c8..94e39e36d57d23ab8bd249891da3c11be93a6dcc 100755
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/vtkSQWReader.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewReaders/SQWReader/vtkSQWReader.h
@@ -1,28 +1,28 @@
-#ifndef _vtkSQWReader_h
-#define _vtkSQWReader_h
-
-#include "MantidVatesAPI/MultiDimensionalDbPresenter.h"
-#include "vtkStructuredGridAlgorithm.h"
-class VTK_EXPORT vtkSQWReader : public vtkStructuredGridAlgorithm
-{
-public:
-  static vtkSQWReader *New();
-  vtkTypeRevisionMacro(vtkSQWReader,vtkStructuredGridAlgorithm);
-  void PrintSelf(ostream& os, vtkIndent indent);
-  vtkSetStringMacro(FileName);
-  vtkGetStringMacro(FileName);
-  int CanReadFile(const char* fname);
-
-protected:
-  vtkSQWReader();
-  ~vtkSQWReader();
-  int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
-  int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
-
-private:
-  vtkSQWReader(const vtkSQWReader&);
-  void operator = (const vtkSQWReader&);
-  Mantid::VATES::MultiDimensionalDbPresenter m_presenter;
-  char *FileName;
-};
-#endif
+#ifndef _vtkSQWReader_h
+#define _vtkSQWReader_h
+
+#include "MantidVatesAPI/MultiDimensionalDbPresenter.h"
+#include "vtkStructuredGridAlgorithm.h"
+class VTK_EXPORT vtkSQWReader : public vtkStructuredGridAlgorithm
+{
+public:
+  static vtkSQWReader *New();
+  vtkTypeRevisionMacro(vtkSQWReader,vtkStructuredGridAlgorithm);
+  void PrintSelf(ostream& os, vtkIndent indent);
+  vtkSetStringMacro(FileName);
+  vtkGetStringMacro(FileName);
+  int CanReadFile(const char* fname);
+
+protected:
+  vtkSQWReader();
+  ~vtkSQWReader();
+  int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
+  int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
+
+private:
+  vtkSQWReader(const vtkSQWReader&);
+  void operator = (const vtkSQWReader&);
+  Mantid::VATES::MultiDimensionalDbPresenter m_presenter;
+  char *FileName;
+};
+#endif
diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/WidgetDllOption.h b/Code/Mantid/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/WidgetDllOption.h
index 63cf0e90e9deb08d1fcb818b2fff8c0fc694f563..82c72c8c1db3d6e748971cf604ddd5381901d4da 100644
--- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/WidgetDllOption.h
+++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewWidgets/QtWidgets/WidgetDllOption.h
@@ -1,12 +1,12 @@
-#ifndef MANTIDPARAVIEWQT_MANTIDPARAVIEWWIDGETS_DLLOPTION_H_
-#define MANTIDPARAVIEWQT_MANTIDPARAVIEWWIDGETS_DLLOPTION_H_
-
-#include <MantidKernel/System.h>
-
-#ifdef IN_MANTIDPARAVIEWQT_MANTIDPARAVIEWWIDGETS
-#define EXPORT_OPT_MANTIDPARVIEW DLLExport 
-#else
-#define EXPORT_OPT_MANTIDPARVIEW DLLImport
-#endif /* IN_MANTIDQT_MANTIDWIDGETS */
-
-#endif //MANTIDQT_MANTIDWIDGETS_DLLOPTION_H_
+#ifndef MANTIDPARAVIEWQT_MANTIDPARAVIEWWIDGETS_DLLOPTION_H_
+#define MANTIDPARAVIEWQT_MANTIDPARAVIEWWIDGETS_DLLOPTION_H_
+
+#include <MantidKernel/System.h>
+
+#ifdef IN_MANTIDPARAVIEWQT_MANTIDPARAVIEWWIDGETS
+#define EXPORT_OPT_MANTIDPARVIEW DLLExport 
+#else
+#define EXPORT_OPT_MANTIDPARVIEW DLLImport
+#endif /* IN_MANTIDQT_MANTIDWIDGETS */
+
+#endif //MANTIDQT_MANTIDWIDGETS_DLLOPTION_H_
diff --git a/Code/Mantid/Vates/VatesAPI/test/RebinningCutterTest.h b/Code/Mantid/Vates/VatesAPI/test/RebinningCutterTest.h
index ebb5b35d4a2318c41241b809ee60cdfda6ee0be6..e518aefcb8a8b32c2bfdbf5110da77e3b4b70459 100644
--- a/Code/Mantid/Vates/VatesAPI/test/RebinningCutterTest.h
+++ b/Code/Mantid/Vates/VatesAPI/test/RebinningCutterTest.h
@@ -1,454 +1,454 @@
-#ifndef REBINNING_CUTTER_TEST_H_
-#define REBINNING_CUTTER_TEST_H_
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-#include <cxxtest/TestSuite.h>
-#include <boost/shared_ptr.hpp>
-#include <cmath>
-#include <typeinfo>
-
-#include "MantidGeometry/MDGeometry/MDDimensionRes.h"
-#include "MantidMDAlgorithms/CompositeImplicitFunction.h"
-#include "MantidMDAlgorithms/BoxImplicitFunction.h"
-#include "MantidAPI/Point3D.h"
-#include <vtkFieldData.h>
-#include <vtkCharArray.h>
-#include <vtkDataSet.h>
-#include "MantidVatesAPI/RebinningCutterPresenter.h"
-#include "MantidVatesAPI/RebinningCutterXMLDefinitions.h"
-#include "MantidVatesAPI/vtkStructuredGridFactory.h"
-#include "MantidVatesAPI/TimeStepToTimeStep.h"
-#include <boost/algorithm/string.hpp>
-#include <boost/scoped_ptr.hpp>
-#include <boost/regex.hpp>
-
-using namespace Mantid::VATES;
-
-class RebinningCutterTest: public CxxTest::TestSuite
-{
-
-private:
-
-  class MockProgressAction : public ProgressAction
-  {
-    virtual void eventRaised(double progress)
-    {
-      //Do nothing.
-    }
-  };
-
-  class PsudoFilter
-  {
-  private:
-
-    std::vector<double> m_origin;
-
-  public:
-    PsudoFilter(std::vector<double> origin) :
-      m_origin(origin)
-    {
-    }
-
-    vtkDataSet* Execute(vtkDataSet* in_ds)
-    {
-      using namespace Mantid::VATES;
-      using namespace Mantid::Geometry;
-      using namespace Mantid::MDAlgorithms;
-      using Mantid::VATES::DimensionVec;
-      using Mantid::VATES::Dimension_sptr;
-      using Mantid::MDDataObjects::MDImage;
-      using Mantid::MDDataObjects::MDWorkspace_sptr;
-
-      RebinningCutterPresenter presenter;
-
-      DimensionVec vec;
-      MDDimensionRes* pDimQx = new MDDimensionRes("qx", q1); //In reality these commands come from UI inputs.
-      pDimQx->setRange(-1.5, 5, 5);
-      Dimension_sptr dimX = Dimension_sptr(pDimQx);
-
-      MDDimensionRes* pDimQy = new MDDimensionRes("qy", q2); //In reality these commands come from UI inputs.
-      pDimQy->setRange(-6.6, 6.6, 5);
-      Dimension_sptr dimY = Dimension_sptr(pDimQy);
-
-      MDDimensionRes* pDimQz = new MDDimensionRes("qz", q3); //In reality these commands come from UI inputs.
-      pDimQz->setRange(-6.6, 6.6, 5);
-      Dimension_sptr dimZ = Dimension_sptr(pDimQz);
-
-      MDDimension* pDimEn = new MDDimension("en");
-      pDimEn->setRange(0, 150, 5);
-      Dimension_sptr dimT = Dimension_sptr(pDimEn);
-
-      vec.push_back(dimX);
-      vec.push_back(dimY);
-      vec.push_back(dimZ);
-      vec.push_back(dimT);
-
-      OriginParameter originParam = OriginParameter(m_origin.at(0), m_origin.at(1), m_origin.at(2));
-      WidthParameter widthParam = WidthParameter(1);
-      HeightParameter heightParam = HeightParameter(2);
-      DepthParameter depthParam = DepthParameter(3);
-
-      //Create the composite holder.
-      Mantid::MDAlgorithms::CompositeImplicitFunction* compFunction = new Mantid::MDAlgorithms::CompositeImplicitFunction;
-
-        presenter.constructReductionKnowledge(vec, dimX, dimY, dimZ, dimT, compFunction, in_ds);
-        MockProgressAction action;
-        MDWorkspace_sptr spRebinnedWs = presenter.applyRebinningAction(RecalculateAll, action);
-      TimeStepToTimeStep proxy;
-      vtkDataSetFactory_sptr spDataSetFactory = vtkDataSetFactory_sptr(new vtkStructuredGridFactory<MDImage, TimeStepToTimeStep>(spRebinnedWs->get_spMDImage(), "", 1, proxy));
-      vtkDataSet *ug = presenter.createVisualDataSet(spDataSetFactory);
-
-      in_ds->Delete();
-      return ug;
-    }
-  };
-
-//helper method;
-std::string getXMLInstructions()
-{
-  return std::string("<Function><Type>BoxImplicitFunction</Type><ParameterList><Parameter><Type>WidthParameter</Type><Value>1.0000</Value></Parameter><Parameter><Type>DepthParameter</Type><Value>3.0000</Value></Parameter><Parameter><Type>HeightParameter</Type><Value>2.0000</Value></Parameter><Parameter><Type>OriginParameter</Type><Value>2.0000, 3.0000, 4.0000</Value></Parameter></ParameterList></Function>");
-}
-
-//helper method
-std::string getComplexXMLInstructions()
-{
-    return std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>") +
-"<MDInstruction>" +
-  "<MDWorkspaceName>Input</MDWorkspaceName>" +
-  "<MDWorkspaceLocation>fe_demo_30.sqw</MDWorkspaceLocation>" +
-  "<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>" +
-      "<ReciprocalDimensionMapping>q1</ReciprocalDimensionMapping>" +
-    "</Dimension>" +
-    "<Dimension ID=\"qy\">" +
-      "<Name>Qy</Name>" +
-      "<UpperBounds>6.6</UpperBounds>" +
-      "<LowerBounds>-6.6</LowerBounds>" +
-      "<NumberOfBins>5</NumberOfBins>" +
-      "<ReciprocalDimensionMapping>q2</ReciprocalDimensionMapping>" +
-    "</Dimension>" +
-    "<Dimension ID=\"qz\">" +
-      "<Name>Qz</Name>" +
-      "<UpperBounds>6.6</UpperBounds>" +
-      "<LowerBounds>-6.6</LowerBounds>" +
-      "<NumberOfBins>5</NumberOfBins>" +
-      "<ReciprocalDimensionMapping>q3</ReciprocalDimensionMapping>" +
-    "</Dimension>" +
-    "<XDimension>" +
-      "<RefDimensionId>qx</RefDimensionId>" +
-    "</XDimension>" +
-    "<YDimension>" +
-      "<RefDimensionId>qy</RefDimensionId>" +
-    "</YDimension>" +
-    "<ZDimension>" +
-      "<RefDimensionId>qz</RefDimensionId>" +
-    "</ZDimension>" +
-    "<TDimension>" +
-      "<RefDimensionId>en</RefDimensionId>" +
-    "</TDimension>" +
-  "</DimensionSet>" +
-  "<Function>" +
-    "<Type>CompositeImplicitFunction</Type>" +
-    "<ParameterList/>" +
-    "<Function>" +
-      "<Type>BoxImplicitFunction</Type>" +
-      "<ParameterList>" +
-        "<Parameter>" +
-          "<Type>HeightParameter</Type>" +
-          "<Value>6</Value>" +
-       "</Parameter>" +
-        "<Parameter>" +
-          "<Type>WidthParameter</Type>" +
-          "<Value>1.5</Value>" +
-       "</Parameter>" +
-       "<Parameter>" +
-          "<Type>DepthParameter</Type>" +
-          "<Value>6</Value>" +
-       "</Parameter>" +
-        "<Parameter>" +
-          "<Type>OriginParameter</Type>" +
-          "<Value>0, 0, 0</Value>" +
-        "</Parameter>" +
-      "</ParameterList>" +
-    "</Function>" +
-    "<Function>" +
-          "<Type>CompositeImplicitFunction</Type>" +
-          "<ParameterList/>" +
-            "<Function>" +
-              "<Type>BoxImplicitFunction</Type>" +
-              "<ParameterList>" +
-                "<Parameter>" +
-                  "<Type>WidthParameter</Type>" +
-                  "<Value>4</Value>" +
-                "</Parameter>" +
-                "<Parameter>" +
-                  "<Type>HeightParameter</Type>" +
-                  "<Value>1.5</Value>" +
-               "</Parameter>" +
-               "<Parameter>" +
-                  "<Type>DepthParameter</Type>" +
-                  "<Value>6</Value>" +
-               "</Parameter>" +
-               "<Parameter>" +
-                  "<Type>OriginParameter</Type>" +
-                  "<Value>0, 0, 0</Value>" +
-               "</Parameter>" +
-              "</ParameterList>" +
-            "</Function>" +
-      "</Function>" +
-  "</Function>" +
-"</MDInstruction>";
-  }
-
-//helper method
-std::string convertCharArrayToString(vtkCharArray* carry)
-{
-  std::string sResult;
-  for (int i = 0; i < carry->GetSize(); i++)
-  {
-    char c = carry->GetValue(i);
-    if(int(c) > 1)
-    {
-      sResult.push_back(c);
-    }
-  }
-  boost::trim(sResult);
-  return sResult;
-}
-
-//helper method
-vtkFieldData* createFieldDataWithCharArray(std::string testData, std::string id)
-{
-  vtkFieldData* fieldData = vtkFieldData::New();
-  vtkCharArray* charArray = vtkCharArray::New();
-  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);
-  charArray->Delete();
-  return fieldData;
-}
-
-//Helper method to construct a dataset identical to what would be expected as the input to a RebinningCutterFilter without the any geometric/topological data.
-vtkDataSet* constructInputDataSet()
-{
-
-  vtkDataSet* dataset = vtkUnstructuredGrid::New();
-  std::string id = XMLDefinitions::metaDataId();
-  vtkFieldData* fieldData =createFieldDataWithCharArray(getComplexXMLInstructions(), id);
-  dataset->SetFieldData(fieldData);
-  fieldData->Delete();
-  return dataset;
-}
-
-public:
-
-//Simple schenario testing end-to-end working of this presenter.
-void testExecution()
-{
-  //Create an input dataset with the field data.
-    vtkDataSet* in_ds = constructInputDataSet();
-
-    PsudoFilter filter(std::vector<double>(3,0));
-
-    vtkDataSet* out_ds = filter.Execute(in_ds);
-
-    //NB 125 = 5 * 5 * 5 see pseudo filter execution method's number of bins above.
-    TSM_ASSERT_EQUALS("An empty visualisation data set has been generated.", out_ds->GetNumberOfPoints() , 216);
-
-    out_ds->Delete();
-
-}
-
-//A more complex version of the above testExecution. Uses filter chaining as would occur in real pipeline.
-void testExecutionInChainedSchenario()
-{
-  //Create an input dataset with the field data.
-  vtkDataSet* in_ds = constructInputDataSet();
-
-  PsudoFilter a(std::vector<double>(3,0));
-  PsudoFilter b(std::vector<double>(3,0));
-  PsudoFilter c(std::vector<double>(3,0));
-
-  vtkDataSet* out_ds = c.Execute(b.Execute(a.Execute(in_ds)));
-  out_ds->Delete();
-}
-
-void testgetMetaDataID()
-{
-
-  TSM_ASSERT_EQUALS("The expected id for the slicing metadata was not found", "VATES_Metadata", XMLDefinitions::metaDataId());
-}
-
-void testFindExistingRebinningDefinitions()
-{
-  using namespace Mantid::API;
-  using namespace Mantid::MDAlgorithms;
-  std::string id = XMLDefinitions::metaDataId();
-  vtkDataSet* dataset = constructInputDataSet();
-
-  ImplicitFunction* func = findExistingRebinningDefinitions(dataset, id.c_str());
-
-  TSM_ASSERT("There was a previous definition of a function that should have been recognised and generated."
-      , CompositeImplicitFunction::functionName() == func->getName());
-
-  dataset->Delete();
-  delete func;
-}
-
-
-void testNoExistingRebinningDefinitions()
-{
-  using namespace Mantid::API;
-
-  vtkDataSet* dataset = vtkUnstructuredGrid::New();
-  TSM_ASSERT_THROWS("There were no previous definitions carried through. Should have thrown.", findExistingRebinningDefinitions(dataset, XMLDefinitions::metaDataId().c_str()), std::runtime_error);
-  dataset->Delete();
-}
-
-//
-//void testCreateVisualDataSetThrows()
-//{
-//    using namespace Mantid::API;
-//    using namespace Mantid::MDAlgorithms;
-//
-//    Mantid::VATES::RebinningCutterPresenter presenter;
-//
-//    TSM_ASSERT_THROWS("Should have thrown if constructReductionKnowledge not called first.", presenter.createVisualDataSet("", false,1), std::runtime_error);
-//}
-
-void testFindWorkspaceName()
-{
-  std::string id = XMLDefinitions::metaDataId();
-  vtkDataSet* dataset = constructInputDataSet();
-
-  std::string name = findExistingWorkspaceName(dataset, id.c_str());
-
-  TSM_ASSERT_EQUALS("The workspace name is different from the xml value.", "Input", name );
-  dataset->Delete();
-}
-
-void testFindWorkspaceLocation()
-{
-  std::string id = XMLDefinitions::metaDataId();
-  vtkDataSet* dataset = constructInputDataSet();
-
-  std::string location = findExistingWorkspaceLocation(dataset, id.c_str());
-  static const boost::regex match(".*(fe_demo_30.sqw)$");
-
-  TSM_ASSERT("The workspace location is differrent from the xml value.", regex_match(location, match));
-  dataset->Delete();
-}
-
-void testFindWorkspaceNameThrows()
-{
-  vtkDataSet* dataset = vtkUnstructuredGrid::New();
-  std::string id =  XMLDefinitions::metaDataId();
-  dataset->SetFieldData(createFieldDataWithCharArray("<IncorrectXML></IncorrectXML>", id.c_str()));
-
-  TSM_ASSERT_THROWS("The xml does not contain a name element, so should throw.", findExistingWorkspaceName(dataset, id.c_str()), std::runtime_error);
-  dataset->Delete();
-}
-
-void testFindWorkspaceLocationThrows()
-{
-  vtkDataSet* dataset = vtkUnstructuredGrid::New();
-  std::string id =  XMLDefinitions::metaDataId();
-  dataset->SetFieldData(createFieldDataWithCharArray("<IncorrectXML></IncorrectXML>", id.c_str()));
-
-  TSM_ASSERT_THROWS("The xml does not contain a location element, so should throw.", findExistingWorkspaceLocation(dataset, id.c_str()), std::runtime_error);
-  dataset->Delete();
-}
-
-void testGetXDimension()
-{
-  Mantid::VATES::RebinningCutterPresenter presenter;
-  vtkDataSet* dataSet = constructInputDataSet(); //Creates a vtkDataSet with fielddata containing geomtry xml.
-  Mantid::VATES::Dimension_sptr xDimension = presenter.getXDimensionFromDS(dataSet);
-  TSM_ASSERT_EQUALS("Wrong number of x dimension bins", 5, xDimension->getNBins());
-  TSM_ASSERT_EQUALS("Wrong minimum x obtained", 5, xDimension->getMaximum());
-  TSM_ASSERT_EQUALS("Wrong maximum x obtained", -1.5, xDimension->getMinimum());
-  dataSet->Delete();
-}
-
-void testGetYDimension()
-{
-  Mantid::VATES::RebinningCutterPresenter presenter;
-    vtkDataSet* dataSet = constructInputDataSet(); //Creates a vtkDataSet with fielddata containing geomtry xml.
-    Mantid::VATES::Dimension_sptr yDimension = presenter.getYDimensionFromDS(dataSet);
-    TSM_ASSERT_EQUALS("Wrong number of y dimension bins", 5, yDimension->getNBins());
-    TSM_ASSERT_EQUALS("Wrong minimum y obtained", 6.6, yDimension->getMaximum());
-    TSM_ASSERT_EQUALS("Wrong maximum y obtained", -6.6, yDimension->getMinimum());
-    dataSet->Delete();
-}
-
-void testGetZDimension()
-{
-  Mantid::VATES::RebinningCutterPresenter presenter;
-  vtkDataSet* dataSet = constructInputDataSet(); //Creates a vtkDataSet with fielddata containing geomtry xml.
-  Mantid::VATES::Dimension_sptr zDimension = presenter.getZDimensionFromDS(dataSet);
-  TSM_ASSERT_EQUALS("Wrong number of z dimension bins", 5, zDimension->getNBins());
-  TSM_ASSERT_EQUALS("Wrong minimum z obtained", -6.6, zDimension->getMinimum());
-  TSM_ASSERT_EQUALS("Wrong maximum z obtained", 6.6, zDimension->getMaximum());
-  dataSet->Delete();
-}
-
-void testGettDimension()
-{
-  Mantid::VATES::RebinningCutterPresenter presenter;
-  vtkDataSet* dataSet = constructInputDataSet(); //Creates a vtkDataSet with fielddata containing geomtry xml.
-  Mantid::VATES::Dimension_sptr tDimension = presenter.getTDimensionFromDS(dataSet);
-  TSM_ASSERT_EQUALS("Wrong number of z dimension bins", 5, tDimension->getNBins());
-  TSM_ASSERT_EQUALS("Wrong minimum t obtained", 0, tDimension->getMinimum());
-  TSM_ASSERT_EQUALS("Wrong maximum t obtained", 150, tDimension->getMaximum());
-  dataSet->Delete();
-}
-
-void testGetWorkspaceGeometryThrows()
-{
-  Mantid::VATES::RebinningCutterPresenter presenter;
-  TSM_ASSERT_THROWS("Not properly initalized. Getting workspace geometry should throw.", presenter.getWorkspaceGeometry(), std::runtime_error);
-}
-
-void testCanProcessInput()
-{
-  std::string id = XMLDefinitions::metaDataId();
-  vtkDataSet* dataset = constructInputDataSet(); //Correct fielddata provided.
-
-  TSM_ASSERT("The dataset should be processable given that the correct metadata is present.", canProcessInput(dataset));
-  dataset->Delete();
-}
-
-void testCannotProcessInput()
-{
-  std::string id = XMLDefinitions::metaDataId();
-  vtkDataSet* dataset = vtkUnstructuredGrid::New(); //No fielddata provided.
-
-  TSM_ASSERT("The dataset should not be processable given that no metadata is present.", !canProcessInput(dataset));
-  dataset->Delete();
-}
-
-
-};
-
-
-#endif 
+#ifndef REBINNING_CUTTER_TEST_H_
+#define REBINNING_CUTTER_TEST_H_
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <cxxtest/TestSuite.h>
+#include <boost/shared_ptr.hpp>
+#include <cmath>
+#include <typeinfo>
+
+#include "MantidGeometry/MDGeometry/MDDimensionRes.h"
+#include "MantidMDAlgorithms/CompositeImplicitFunction.h"
+#include "MantidMDAlgorithms/BoxImplicitFunction.h"
+#include "MantidAPI/Point3D.h"
+#include <vtkFieldData.h>
+#include <vtkCharArray.h>
+#include <vtkDataSet.h>
+#include "MantidVatesAPI/RebinningCutterPresenter.h"
+#include "MantidVatesAPI/RebinningCutterXMLDefinitions.h"
+#include "MantidVatesAPI/vtkStructuredGridFactory.h"
+#include "MantidVatesAPI/TimeStepToTimeStep.h"
+#include <boost/algorithm/string.hpp>
+#include <boost/scoped_ptr.hpp>
+#include <boost/regex.hpp>
+
+using namespace Mantid::VATES;
+
+class RebinningCutterTest: public CxxTest::TestSuite
+{
+
+private:
+
+  class MockProgressAction : public ProgressAction
+  {
+    virtual void eventRaised(double progress)
+    {
+      //Do nothing.
+    }
+  };
+
+  class PsudoFilter
+  {
+  private:
+
+    std::vector<double> m_origin;
+
+  public:
+    PsudoFilter(std::vector<double> origin) :
+      m_origin(origin)
+    {
+    }
+
+    vtkDataSet* Execute(vtkDataSet* in_ds)
+    {
+      using namespace Mantid::VATES;
+      using namespace Mantid::Geometry;
+      using namespace Mantid::MDAlgorithms;
+      using Mantid::VATES::DimensionVec;
+      using Mantid::VATES::Dimension_sptr;
+      using Mantid::MDDataObjects::MDImage;
+      using Mantid::MDDataObjects::MDWorkspace_sptr;
+
+      RebinningCutterPresenter presenter;
+
+      DimensionVec vec;
+      MDDimensionRes* pDimQx = new MDDimensionRes("qx", q1); //In reality these commands come from UI inputs.
+      pDimQx->setRange(-1.5, 5, 5);
+      Dimension_sptr dimX = Dimension_sptr(pDimQx);
+
+      MDDimensionRes* pDimQy = new MDDimensionRes("qy", q2); //In reality these commands come from UI inputs.
+      pDimQy->setRange(-6.6, 6.6, 5);
+      Dimension_sptr dimY = Dimension_sptr(pDimQy);
+
+      MDDimensionRes* pDimQz = new MDDimensionRes("qz", q3); //In reality these commands come from UI inputs.
+      pDimQz->setRange(-6.6, 6.6, 5);
+      Dimension_sptr dimZ = Dimension_sptr(pDimQz);
+
+      MDDimension* pDimEn = new MDDimension("en");
+      pDimEn->setRange(0, 150, 5);
+      Dimension_sptr dimT = Dimension_sptr(pDimEn);
+
+      vec.push_back(dimX);
+      vec.push_back(dimY);
+      vec.push_back(dimZ);
+      vec.push_back(dimT);
+
+      OriginParameter originParam = OriginParameter(m_origin.at(0), m_origin.at(1), m_origin.at(2));
+      WidthParameter widthParam = WidthParameter(1);
+      HeightParameter heightParam = HeightParameter(2);
+      DepthParameter depthParam = DepthParameter(3);
+
+      //Create the composite holder.
+      Mantid::MDAlgorithms::CompositeImplicitFunction* compFunction = new Mantid::MDAlgorithms::CompositeImplicitFunction;
+
+        presenter.constructReductionKnowledge(vec, dimX, dimY, dimZ, dimT, compFunction, in_ds);
+        MockProgressAction action;
+        MDWorkspace_sptr spRebinnedWs = presenter.applyRebinningAction(RecalculateAll, action);
+      TimeStepToTimeStep proxy;
+      vtkDataSetFactory_sptr spDataSetFactory = vtkDataSetFactory_sptr(new vtkStructuredGridFactory<MDImage, TimeStepToTimeStep>(spRebinnedWs->get_spMDImage(), "", 1, proxy));
+      vtkDataSet *ug = presenter.createVisualDataSet(spDataSetFactory);
+
+      in_ds->Delete();
+      return ug;
+    }
+  };
+
+//helper method;
+std::string getXMLInstructions()
+{
+  return std::string("<Function><Type>BoxImplicitFunction</Type><ParameterList><Parameter><Type>WidthParameter</Type><Value>1.0000</Value></Parameter><Parameter><Type>DepthParameter</Type><Value>3.0000</Value></Parameter><Parameter><Type>HeightParameter</Type><Value>2.0000</Value></Parameter><Parameter><Type>OriginParameter</Type><Value>2.0000, 3.0000, 4.0000</Value></Parameter></ParameterList></Function>");
+}
+
+//helper method
+std::string getComplexXMLInstructions()
+{
+    return std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>") +
+"<MDInstruction>" +
+  "<MDWorkspaceName>Input</MDWorkspaceName>" +
+  "<MDWorkspaceLocation>fe_demo_30.sqw</MDWorkspaceLocation>" +
+  "<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>" +
+      "<ReciprocalDimensionMapping>q1</ReciprocalDimensionMapping>" +
+    "</Dimension>" +
+    "<Dimension ID=\"qy\">" +
+      "<Name>Qy</Name>" +
+      "<UpperBounds>6.6</UpperBounds>" +
+      "<LowerBounds>-6.6</LowerBounds>" +
+      "<NumberOfBins>5</NumberOfBins>" +
+      "<ReciprocalDimensionMapping>q2</ReciprocalDimensionMapping>" +
+    "</Dimension>" +
+    "<Dimension ID=\"qz\">" +
+      "<Name>Qz</Name>" +
+      "<UpperBounds>6.6</UpperBounds>" +
+      "<LowerBounds>-6.6</LowerBounds>" +
+      "<NumberOfBins>5</NumberOfBins>" +
+      "<ReciprocalDimensionMapping>q3</ReciprocalDimensionMapping>" +
+    "</Dimension>" +
+    "<XDimension>" +
+      "<RefDimensionId>qx</RefDimensionId>" +
+    "</XDimension>" +
+    "<YDimension>" +
+      "<RefDimensionId>qy</RefDimensionId>" +
+    "</YDimension>" +
+    "<ZDimension>" +
+      "<RefDimensionId>qz</RefDimensionId>" +
+    "</ZDimension>" +
+    "<TDimension>" +
+      "<RefDimensionId>en</RefDimensionId>" +
+    "</TDimension>" +
+  "</DimensionSet>" +
+  "<Function>" +
+    "<Type>CompositeImplicitFunction</Type>" +
+    "<ParameterList/>" +
+    "<Function>" +
+      "<Type>BoxImplicitFunction</Type>" +
+      "<ParameterList>" +
+        "<Parameter>" +
+          "<Type>HeightParameter</Type>" +
+          "<Value>6</Value>" +
+       "</Parameter>" +
+        "<Parameter>" +
+          "<Type>WidthParameter</Type>" +
+          "<Value>1.5</Value>" +
+       "</Parameter>" +
+       "<Parameter>" +
+          "<Type>DepthParameter</Type>" +
+          "<Value>6</Value>" +
+       "</Parameter>" +
+        "<Parameter>" +
+          "<Type>OriginParameter</Type>" +
+          "<Value>0, 0, 0</Value>" +
+        "</Parameter>" +
+      "</ParameterList>" +
+    "</Function>" +
+    "<Function>" +
+          "<Type>CompositeImplicitFunction</Type>" +
+          "<ParameterList/>" +
+            "<Function>" +
+              "<Type>BoxImplicitFunction</Type>" +
+              "<ParameterList>" +
+                "<Parameter>" +
+                  "<Type>WidthParameter</Type>" +
+                  "<Value>4</Value>" +
+                "</Parameter>" +
+                "<Parameter>" +
+                  "<Type>HeightParameter</Type>" +
+                  "<Value>1.5</Value>" +
+               "</Parameter>" +
+               "<Parameter>" +
+                  "<Type>DepthParameter</Type>" +
+                  "<Value>6</Value>" +
+               "</Parameter>" +
+               "<Parameter>" +
+                  "<Type>OriginParameter</Type>" +
+                  "<Value>0, 0, 0</Value>" +
+               "</Parameter>" +
+              "</ParameterList>" +
+            "</Function>" +
+      "</Function>" +
+  "</Function>" +
+"</MDInstruction>";
+  }
+
+//helper method
+std::string convertCharArrayToString(vtkCharArray* carry)
+{
+  std::string sResult;
+  for (int i = 0; i < carry->GetSize(); i++)
+  {
+    char c = carry->GetValue(i);
+    if(int(c) > 1)
+    {
+      sResult.push_back(c);
+    }
+  }
+  boost::trim(sResult);
+  return sResult;
+}
+
+//helper method
+vtkFieldData* createFieldDataWithCharArray(std::string testData, std::string id)
+{
+  vtkFieldData* fieldData = vtkFieldData::New();
+  vtkCharArray* charArray = vtkCharArray::New();
+  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);
+  charArray->Delete();
+  return fieldData;
+}
+
+//Helper method to construct a dataset identical to what would be expected as the input to a RebinningCutterFilter without the any geometric/topological data.
+vtkDataSet* constructInputDataSet()
+{
+
+  vtkDataSet* dataset = vtkUnstructuredGrid::New();
+  std::string id = XMLDefinitions::metaDataId();
+  vtkFieldData* fieldData =createFieldDataWithCharArray(getComplexXMLInstructions(), id);
+  dataset->SetFieldData(fieldData);
+  fieldData->Delete();
+  return dataset;
+}
+
+public:
+
+//Simple schenario testing end-to-end working of this presenter.
+void testExecution()
+{
+  //Create an input dataset with the field data.
+    vtkDataSet* in_ds = constructInputDataSet();
+
+    PsudoFilter filter(std::vector<double>(3,0));
+
+    vtkDataSet* out_ds = filter.Execute(in_ds);
+
+    //NB 125 = 5 * 5 * 5 see pseudo filter execution method's number of bins above.
+    TSM_ASSERT_EQUALS("An empty visualisation data set has been generated.", out_ds->GetNumberOfPoints() , 216);
+
+    out_ds->Delete();
+
+}
+
+//A more complex version of the above testExecution. Uses filter chaining as would occur in real pipeline.
+void testExecutionInChainedSchenario()
+{
+  //Create an input dataset with the field data.
+  vtkDataSet* in_ds = constructInputDataSet();
+
+  PsudoFilter a(std::vector<double>(3,0));
+  PsudoFilter b(std::vector<double>(3,0));
+  PsudoFilter c(std::vector<double>(3,0));
+
+  vtkDataSet* out_ds = c.Execute(b.Execute(a.Execute(in_ds)));
+  out_ds->Delete();
+}
+
+void testgetMetaDataID()
+{
+
+  TSM_ASSERT_EQUALS("The expected id for the slicing metadata was not found", "VATES_Metadata", XMLDefinitions::metaDataId());
+}
+
+void testFindExistingRebinningDefinitions()
+{
+  using namespace Mantid::API;
+  using namespace Mantid::MDAlgorithms;
+  std::string id = XMLDefinitions::metaDataId();
+  vtkDataSet* dataset = constructInputDataSet();
+
+  ImplicitFunction* func = findExistingRebinningDefinitions(dataset, id.c_str());
+
+  TSM_ASSERT("There was a previous definition of a function that should have been recognised and generated."
+      , CompositeImplicitFunction::functionName() == func->getName());
+
+  dataset->Delete();
+  delete func;
+}
+
+
+void testNoExistingRebinningDefinitions()
+{
+  using namespace Mantid::API;
+
+  vtkDataSet* dataset = vtkUnstructuredGrid::New();
+  TSM_ASSERT_THROWS("There were no previous definitions carried through. Should have thrown.", findExistingRebinningDefinitions(dataset, XMLDefinitions::metaDataId().c_str()), std::runtime_error);
+  dataset->Delete();
+}
+
+//
+//void testCreateVisualDataSetThrows()
+//{
+//    using namespace Mantid::API;
+//    using namespace Mantid::MDAlgorithms;
+//
+//    Mantid::VATES::RebinningCutterPresenter presenter;
+//
+//    TSM_ASSERT_THROWS("Should have thrown if constructReductionKnowledge not called first.", presenter.createVisualDataSet("", false,1), std::runtime_error);
+//}
+
+void testFindWorkspaceName()
+{
+  std::string id = XMLDefinitions::metaDataId();
+  vtkDataSet* dataset = constructInputDataSet();
+
+  std::string name = findExistingWorkspaceName(dataset, id.c_str());
+
+  TSM_ASSERT_EQUALS("The workspace name is different from the xml value.", "Input", name );
+  dataset->Delete();
+}
+
+void testFindWorkspaceLocation()
+{
+  std::string id = XMLDefinitions::metaDataId();
+  vtkDataSet* dataset = constructInputDataSet();
+
+  std::string location = findExistingWorkspaceLocation(dataset, id.c_str());
+  static const boost::regex match(".*(fe_demo_30.sqw)$");
+
+  TSM_ASSERT("The workspace location is differrent from the xml value.", regex_match(location, match));
+  dataset->Delete();
+}
+
+void testFindWorkspaceNameThrows()
+{
+  vtkDataSet* dataset = vtkUnstructuredGrid::New();
+  std::string id =  XMLDefinitions::metaDataId();
+  dataset->SetFieldData(createFieldDataWithCharArray("<IncorrectXML></IncorrectXML>", id.c_str()));
+
+  TSM_ASSERT_THROWS("The xml does not contain a name element, so should throw.", findExistingWorkspaceName(dataset, id.c_str()), std::runtime_error);
+  dataset->Delete();
+}
+
+void testFindWorkspaceLocationThrows()
+{
+  vtkDataSet* dataset = vtkUnstructuredGrid::New();
+  std::string id =  XMLDefinitions::metaDataId();
+  dataset->SetFieldData(createFieldDataWithCharArray("<IncorrectXML></IncorrectXML>", id.c_str()));
+
+  TSM_ASSERT_THROWS("The xml does not contain a location element, so should throw.", findExistingWorkspaceLocation(dataset, id.c_str()), std::runtime_error);
+  dataset->Delete();
+}
+
+void testGetXDimension()
+{
+  Mantid::VATES::RebinningCutterPresenter presenter;
+  vtkDataSet* dataSet = constructInputDataSet(); //Creates a vtkDataSet with fielddata containing geomtry xml.
+  Mantid::VATES::Dimension_sptr xDimension = presenter.getXDimensionFromDS(dataSet);
+  TSM_ASSERT_EQUALS("Wrong number of x dimension bins", 5, xDimension->getNBins());
+  TSM_ASSERT_EQUALS("Wrong minimum x obtained", 5, xDimension->getMaximum());
+  TSM_ASSERT_EQUALS("Wrong maximum x obtained", -1.5, xDimension->getMinimum());
+  dataSet->Delete();
+}
+
+void testGetYDimension()
+{
+  Mantid::VATES::RebinningCutterPresenter presenter;
+    vtkDataSet* dataSet = constructInputDataSet(); //Creates a vtkDataSet with fielddata containing geomtry xml.
+    Mantid::VATES::Dimension_sptr yDimension = presenter.getYDimensionFromDS(dataSet);
+    TSM_ASSERT_EQUALS("Wrong number of y dimension bins", 5, yDimension->getNBins());
+    TSM_ASSERT_EQUALS("Wrong minimum y obtained", 6.6, yDimension->getMaximum());
+    TSM_ASSERT_EQUALS("Wrong maximum y obtained", -6.6, yDimension->getMinimum());
+    dataSet->Delete();
+}
+
+void testGetZDimension()
+{
+  Mantid::VATES::RebinningCutterPresenter presenter;
+  vtkDataSet* dataSet = constructInputDataSet(); //Creates a vtkDataSet with fielddata containing geomtry xml.
+  Mantid::VATES::Dimension_sptr zDimension = presenter.getZDimensionFromDS(dataSet);
+  TSM_ASSERT_EQUALS("Wrong number of z dimension bins", 5, zDimension->getNBins());
+  TSM_ASSERT_EQUALS("Wrong minimum z obtained", -6.6, zDimension->getMinimum());
+  TSM_ASSERT_EQUALS("Wrong maximum z obtained", 6.6, zDimension->getMaximum());
+  dataSet->Delete();
+}
+
+void testGettDimension()
+{
+  Mantid::VATES::RebinningCutterPresenter presenter;
+  vtkDataSet* dataSet = constructInputDataSet(); //Creates a vtkDataSet with fielddata containing geomtry xml.
+  Mantid::VATES::Dimension_sptr tDimension = presenter.getTDimensionFromDS(dataSet);
+  TSM_ASSERT_EQUALS("Wrong number of z dimension bins", 5, tDimension->getNBins());
+  TSM_ASSERT_EQUALS("Wrong minimum t obtained", 0, tDimension->getMinimum());
+  TSM_ASSERT_EQUALS("Wrong maximum t obtained", 150, tDimension->getMaximum());
+  dataSet->Delete();
+}
+
+void testGetWorkspaceGeometryThrows()
+{
+  Mantid::VATES::RebinningCutterPresenter presenter;
+  TSM_ASSERT_THROWS("Not properly initalized. Getting workspace geometry should throw.", presenter.getWorkspaceGeometry(), std::runtime_error);
+}
+
+void testCanProcessInput()
+{
+  std::string id = XMLDefinitions::metaDataId();
+  vtkDataSet* dataset = constructInputDataSet(); //Correct fielddata provided.
+
+  TSM_ASSERT("The dataset should be processable given that the correct metadata is present.", canProcessInput(dataset));
+  dataset->Delete();
+}
+
+void testCannotProcessInput()
+{
+  std::string id = XMLDefinitions::metaDataId();
+  vtkDataSet* dataset = vtkUnstructuredGrid::New(); //No fielddata provided.
+
+  TSM_ASSERT("The dataset should not be processable given that no metadata is present.", !canProcessInput(dataset));
+  dataset->Delete();
+}
+
+
+};
+
+
+#endif