From 1a18d3ea4271b2a640924fd4fce75d38600096b7 Mon Sep 17 00:00:00 2001
From: Steve Williams <stephen.williams@stfc.ac.uk>
Date: Wed, 12 Jan 2011 19:40:51 +0000
Subject: [PATCH] The SANS GUI now has a "Manage Directories" button and it
 handles multi-period files better too. refs #2145 and #2146

---
 .../MantidPlot/src/ApplicationWindow.cpp      |   1 -
 .../inc/MantidQtAPI/ManageUserDirectories.h   |   2 +
 .../API/src/ManageUserDirectories.cpp         |  10 +
 .../MantidQtCustomInterfaces/SANSAddFiles.h   |  21 +-
 .../MantidQtCustomInterfaces/SANSRunWindow.ui | 169 ++++++++-------
 .../CustomInterfaces/src/ConvertToEnergy.cpp  |   1 -
 .../src/IndirectDataAnalysis.cpp              |   1 -
 .../src/IndirectDiffractionReduction.cpp      |   1 -
 .../CustomInterfaces/src/SANSAddFiles.cpp     | 101 ++++++---
 .../CustomInterfaces/src/SANSRunWindow.cpp    |  10 +-
 .../Scripts/SANS/ISISCommandInterface.py      |  26 ++-
 Code/Mantid/Scripts/SANS/SANSadd2.py          | 200 +++++++++++-------
 Code/Mantid/Scripts/SANS/isis_reducer.py      |  24 +--
 .../Scripts/SANS/isis_reduction_steps.py      |  98 ++++++---
 14 files changed, 405 insertions(+), 260 deletions(-)

diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp
index a44167c426c..8fb0cd450cc 100644
--- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp
+++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp
@@ -16176,7 +16176,6 @@ void ApplicationWindow::showCustomActionDialog()
 void ApplicationWindow::showUserDirectoryDialog()
 {
   MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
-  ad->setAttribute(Qt::WA_DeleteOnClose);
   ad->show();
   ad->setFocus();
 }
diff --git a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/ManageUserDirectories.h b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/ManageUserDirectories.h
index 8b83f41870d..eb93570cae1 100644
--- a/Code/Mantid/MantidQt/API/inc/MantidQtAPI/ManageUserDirectories.h
+++ b/Code/Mantid/MantidQt/API/inc/MantidQtAPI/ManageUserDirectories.h
@@ -17,6 +17,8 @@ public:
 	ManageUserDirectories(QWidget *parent = 0);
 	~ManageUserDirectories();
 
+  static void openUserDirsDialog(QWidget * parent);
+
 private:
   virtual void initLayout();
   void loadProperties();
diff --git a/Code/Mantid/MantidQt/API/src/ManageUserDirectories.cpp b/Code/Mantid/MantidQt/API/src/ManageUserDirectories.cpp
index 8274f4aa210..eccce8ce134 100644
--- a/Code/Mantid/MantidQt/API/src/ManageUserDirectories.cpp
+++ b/Code/Mantid/MantidQt/API/src/ManageUserDirectories.cpp
@@ -6,6 +6,7 @@ using namespace MantidQt::API;
 
 ManageUserDirectories::ManageUserDirectories(QWidget *parent) : QDialog(parent)
 {
+  setAttribute(Qt::WA_DeleteOnClose);
 	m_uiForm.setupUi(this);
   initLayout();
 }
@@ -177,3 +178,12 @@ void ManageUserDirectories::selectSaveDir()
   }
 
 }
+/** 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/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSAddFiles.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSAddFiles.h
index f9f571e5dea..1e8f216da6f 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSAddFiles.h
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSAddFiles.h
@@ -3,10 +3,10 @@
 
 #include "ui_SANSRunWindow.h"
 #include "MantidQtAPI/UserSubWindow.h"
+#include "MantidKernel/ConfigService.h"
+#include "Poco/NObserver.h"
 #include <QString>
 
-#include <set>
-
 namespace MantidQt
 {
 namespace CustomInterfaces
@@ -32,21 +32,30 @@ private:
   std::set<std::string> m_exts;
   //this is set to the extensions supported by LoadRaw
   std::set<std::string> m_rawExts;
-  //A reference to a logger
+  ///the directory to which files will be saved
+  QString m_outDir;
+  ///A reference to a logger
   static Mantid::Kernel::Logger & g_log;
+  ///The text that goes into the beginning of the output directory message
+  static const QString OUT_MSG;
+
+  Poco::NObserver<SANSAddFiles, Mantid::Kernel::ConfigValChangeNotification> m_newOutDir;
 
   void initLayout();
+  void setToolTips();
+  QListWidgetItem* insertListFront(const QString &text);
+  ///The directory where files are saved is defined by the config data service
+  void changeOutputDir(Mantid::Kernel::ConfigValChangeNotification_ptr pDirInfo);
+  void setOutDir(std::string dir);
   void readSettings();
   void saveSettings();
-  QListWidgetItem* insertListFront(const QString &text);
 
 private slots:
   ///insert another row into the files to sum table (tbRunsToAdd), in response to a click on the pbNewRow button
   void add2Runs2Add();
   ///run the Python that sums the files together in response to a pbSum button click
   void runPythonAddFiles();
-  ///this slot opens the output file path browser
-  void summedPathBrowse();
+  void outPathSel();
   ///this slot opens a browser to select a new file to add
   void new2AddBrowse();
   ///sets data associated with the cell
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.ui
index e4250af0e57..96e07a2a3eb 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.ui
+++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SANSRunWindow.ui
@@ -1884,7 +1884,7 @@ p, li { white-space: pre-wrap; }
            </widget>
           </item>
           <item row="3" column="1" colspan="2" >
-           <widget class="MantidQt::MantidWidgets::MWRunFiles" name="floodFile" >
+           <widget class="MantidQt::MantidWidgets::MWRunFiles" native="1" name="floodFile" >
             <property name="findRunFiles" stdset="0" >
              <bool>false</bool>
             </property>
@@ -3536,7 +3536,7 @@ p, li { white-space: pre-wrap; }
        <string>Add Runs</string>
       </attribute>
       <layout class="QGridLayout" name="gridLayout_18" >
-       <item row="0" column="3" >
+       <item row="0" column="2" >
         <spacer name="verticalSpacer_9" >
          <property name="orientation" >
           <enum>Qt::Vertical</enum>
@@ -3565,50 +3565,15 @@ p, li { white-space: pre-wrap; }
          </property>
         </spacer>
        </item>
-       <item row="2" column="3" >
-        <spacer name="verticalSpacer_10" >
-         <property name="orientation" >
-          <enum>Qt::Vertical</enum>
-         </property>
-         <property name="sizeHint" stdset="0" >
-          <size>
-           <width>20</width>
-           <height>40</height>
-          </size>
-         </property>
-        </spacer>
-       </item>
-       <item row="3" column="6" >
-        <spacer name="horizontalSpacer_18" >
-         <property name="orientation" >
-          <enum>Qt::Horizontal</enum>
-         </property>
-         <property name="sizeType" >
-          <enum>QSizePolicy::Maximum</enum>
-         </property>
-         <property name="sizeHint" stdset="0" >
-          <size>
-           <width>40</width>
-           <height>20</height>
-          </size>
-         </property>
-        </spacer>
-       </item>
-       <item row="6" column="4" >
-        <spacer name="verticalSpacer_7" >
-         <property name="orientation" >
-          <enum>Qt::Vertical</enum>
-         </property>
-         <property name="sizeHint" stdset="0" >
-          <size>
-           <width>20</width>
-           <height>40</height>
-          </size>
+       <item row="1" column="2" >
+        <widget class="QLabel" name="summedPath_lb" >
+         <property name="text" >
+          <string/>
          </property>
-        </spacer>
+        </widget>
        </item>
-       <item row="8" column="4" >
-        <spacer name="verticalSpacer_8" >
+       <item row="3" column="2" >
+        <spacer name="verticalSpacer_10" >
          <property name="orientation" >
           <enum>Qt::Vertical</enum>
          </property>
@@ -3620,34 +3585,7 @@ p, li { white-space: pre-wrap; }
          </property>
         </spacer>
        </item>
-       <item row="1" column="1" colspan="2" >
-        <widget class="QLabel" name="label_40" >
-         <property name="toolTip" >
-          <string>The directory to created the summed run file in</string>
-         </property>
-         <property name="text" >
-          <string>Output File Path</string>
-         </property>
-        </widget>
-       </item>
-       <item row="1" column="3" >
-        <widget class="QLineEdit" name="summedPath_edit" >
-         <property name="toolTip" >
-          <string>The directory to created the summed run file in</string>
-         </property>
-        </widget>
-       </item>
-       <item row="1" column="4" >
-        <widget class="QPushButton" name="summedPath_Btn" >
-         <property name="toolTip" >
-          <string>The directory to created the summed run file in</string>
-         </property>
-         <property name="text" >
-          <string>Browse</string>
-         </property>
-        </widget>
-       </item>
-       <item row="3" column="0" colspan="2" >
+       <item row="4" column="0" colspan="2" >
         <widget class="QLabel" name="label_42" >
          <property name="sizePolicy" >
           <sizepolicy vsizetype="Preferred" hsizetype="Fixed" >
@@ -3669,14 +3607,14 @@ p, li { white-space: pre-wrap; }
          </property>
         </widget>
        </item>
-       <item row="3" column="2" colspan="2" >
+       <item row="4" column="2" >
         <widget class="QLineEdit" name="new2Add_edit" >
          <property name="toolTip" >
           <string>Type , separated lists of run numbers or ranges of numbers with a : </string>
          </property>
         </widget>
        </item>
-       <item row="3" column="4" >
+       <item row="4" column="3" >
         <widget class="QPushButton" name="add_Btn" >
          <property name="toolTip" >
           <string>Adds entries to the big table, use before clicking "Sum".</string>
@@ -3686,7 +3624,7 @@ p, li { white-space: pre-wrap; }
          </property>
         </widget>
        </item>
-       <item row="3" column="5" >
+       <item row="4" column="4" >
         <widget class="QPushButton" name="browse_to_add_Btn" >
          <property name="toolTip" >
           <string>Find a file on your system</string>
@@ -3696,17 +3634,33 @@ p, li { white-space: pre-wrap; }
          </property>
         </widget>
        </item>
-       <item row="7" column="4" >
-        <widget class="QPushButton" name="sum_Btn" >
+       <item row="4" column="5" >
+        <spacer name="horizontalSpacer_18" >
+         <property name="orientation" >
+          <enum>Qt::Horizontal</enum>
+         </property>
+         <property name="sizeType" >
+          <enum>QSizePolicy::Maximum</enum>
+         </property>
+         <property name="sizeHint" stdset="0" >
+          <size>
+           <width>40</width>
+           <height>20</height>
+          </size>
+         </property>
+        </spacer>
+       </item>
+       <item row="5" column="0" >
+        <widget class="QLabel" name="label_46" >
          <property name="toolTip" >
-          <string>Load the files in the table above and save them to one file</string>
+          <string>Files to be summed, click at the top of this box or use the "Add" button</string>
          </property>
          <property name="text" >
-          <string>Sum</string>
+          <string>Run files to sum</string>
          </property>
         </widget>
        </item>
-       <item rowspan="3" row="4" column="2" colspan="2" >
+       <item rowspan="3" row="5" column="1" colspan="2" >
         <widget class="QListWidget" name="toAdd_List" >
          <property name="toolTip" >
           <string>Files to be summed, click at the top of this box or use the "Add" button</string>
@@ -3728,7 +3682,7 @@ p, li { white-space: pre-wrap; }
          </property>
         </widget>
        </item>
-       <item row="4" column="4" >
+       <item row="5" column="3" >
         <widget class="QPushButton" name="clear_Btn" >
          <property name="toolTip" >
           <string>Clear the table</string>
@@ -3738,7 +3692,7 @@ p, li { white-space: pre-wrap; }
          </property>
         </widget>
        </item>
-       <item row="5" column="4" >
+       <item row="6" column="3" >
         <widget class="QPushButton" name="remove_Btn" >
          <property name="toolTip" >
           <string>Select rows by clicking on the table and remove then with this button</string>
@@ -3748,13 +3702,56 @@ p, li { white-space: pre-wrap; }
          </property>
         </widget>
        </item>
-       <item row="4" column="0" colspan="2" >
-        <widget class="QLabel" name="label_46" >
+       <item row="7" column="3" >
+        <spacer name="verticalSpacer_7" >
+         <property name="orientation" >
+          <enum>Qt::Vertical</enum>
+         </property>
+         <property name="sizeHint" stdset="0" >
+          <size>
+           <width>20</width>
+           <height>40</height>
+          </size>
+         </property>
+        </spacer>
+       </item>
+       <item row="8" column="3" >
+        <widget class="QPushButton" name="sum_Btn" >
          <property name="toolTip" >
-          <string>Files to be summed, click at the top of this box or use the "Add" button</string>
+          <string>Load the files in the table above and save them to one file</string>
          </property>
          <property name="text" >
-          <string>Run files to sum</string>
+          <string>Sum</string>
+         </property>
+        </widget>
+       </item>
+       <item row="9" column="3" >
+        <spacer name="verticalSpacer_8" >
+         <property name="orientation" >
+          <enum>Qt::Vertical</enum>
+         </property>
+         <property name="sizeHint" stdset="0" >
+          <size>
+           <width>20</width>
+           <height>40</height>
+          </size>
+         </property>
+        </spacer>
+       </item>
+       <item row="1" column="4" >
+        <widget class="QPushButton" name="summedPath_Btn" >
+         <property name="toolTip" >
+          <string>The directory to created the summed run file in</string>
+         </property>
+         <property name="text" >
+          <string>Manage Directories</string>
+         </property>
+        </widget>
+       </item>
+       <item row="2" column="2" >
+        <widget class="QCheckBox" name="loadSeparateEntries" >
+         <property name="text" >
+          <string>Minimise memory usage</string>
          </property>
         </widget>
        </item>
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/ConvertToEnergy.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/ConvertToEnergy.cpp
index 4a578e4b868..61fd20ace51 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/ConvertToEnergy.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/ConvertToEnergy.cpp
@@ -376,7 +376,6 @@ void ConvertToEnergy::userSelectInstrument(const QString& prefix)
 void ConvertToEnergy::openDirectoryDialog()
 {
   MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
-  ad->setAttribute(Qt::WA_DeleteOnClose);
   ad->show();
   ad->setFocus();
 }
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDataAnalysis.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDataAnalysis.cpp
index 16686700030..61d87b5345f 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDataAnalysis.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDataAnalysis.cpp
@@ -2030,7 +2030,6 @@ void IndirectDataAnalysis::absorptionShape(int index)
 void IndirectDataAnalysis::openDirectoryDialog()
 {
   MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
-  ad->setAttribute(Qt::WA_DeleteOnClose);
   ad->show();
   ad->setFocus();
 }
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDiffractionReduction.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDiffractionReduction.cpp
index 08370fc6e10..157d8772f51 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDiffractionReduction.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/IndirectDiffractionReduction.cpp
@@ -120,7 +120,6 @@ void IndirectDiffractionReduction::reflectionSelected(int)
 void IndirectDiffractionReduction::openDirectoryDialog()
 {
   MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
-  ad->setAttribute(Qt::WA_DeleteOnClose);
   ad->show();
   ad->setFocus();
 }
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SANSAddFiles.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SANSAddFiles.cpp
index 9e96a403257..e11f5630e95 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/SANSAddFiles.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SANSAddFiles.cpp
@@ -1,5 +1,6 @@
 #include "MantidQtCustomInterfaces/SANSAddFiles.h"
 #include "MantidQtCustomInterfaces/SANSRunWindow.h"
+#include "MantidQtAPI/ManageUserDirectories.h"
 #include "MantidKernel/ConfigService.h"
 #include "MantidAPI/FileProperty.h"
 #include "MantidKernel/ArrayProperty.h"
@@ -24,9 +25,11 @@ using namespace Mantid::API;
 
 // Initialize the logger
 Logger& SANSAddFiles::g_log = Logger::get("SANSAddFiles");
+const QString SANSAddFiles::OUT_MSG("Output Directory = ");
 
 SANSAddFiles::SANSAddFiles(QWidget *parent, Ui::SANSRunWindow *ParWidgets) :
-  m_SANSForm(ParWidgets), parForm(parent), m_pythonRunning(false)
+  m_SANSForm(ParWidgets), parForm(parent), m_pythonRunning(false),
+  m_newOutDir(*this, &SANSAddFiles::changeOutputDir)
 {
   initLayout();
   
@@ -38,11 +41,21 @@ SANSAddFiles::SANSAddFiles(QWidget *parent, Ui::SANSRunWindow *ParWidgets) :
   alg = AlgorithmManager::Instance().create("LoadRaw");
   prop = alg->getProperty("Filename");
   m_rawExts = prop->allowedValues();
+
+  ConfigService::Instance().addObserver(m_newOutDir);
 }
 
 SANSAddFiles::~SANSAddFiles()
 {
-  saveSettings();
+  try
+  {
+    ConfigService::Instance().removeObserver(m_newOutDir);
+    saveSettings();
+  }
+  catch(...)
+  {
+    //we've cleaned up the best we can, move on
+  }
 }
 
 //Connect signals and setup widgets
@@ -63,12 +76,16 @@ void SANSAddFiles::initLayout()
   //buttons on the Add Runs tab
   connect(m_SANSForm->add_Btn, SIGNAL(clicked()), this, SLOT(add2Runs2Add()));
   connect(m_SANSForm->sum_Btn, SIGNAL(clicked()), this, SLOT(runPythonAddFiles()));
-  connect(m_SANSForm->summedPath_Btn, SIGNAL(clicked()), this, SLOT(summedPathBrowse()));
+  connect(m_SANSForm->summedPath_Btn, SIGNAL(clicked()), this, SLOT(outPathSel()));
   connect(m_SANSForm->browse_to_add_Btn, SIGNAL(clicked()), this, SLOT(new2AddBrowse()));
   connect(m_SANSForm->clear_Btn, SIGNAL(clicked()), this, SLOT(clearClicked()));
   connect(m_SANSForm->remove_Btn, SIGNAL(clicked()), this, SLOT(removeSelected()));
 
   readSettings();
+
+  setToolTips();
+
+  setOutDir(ConfigService::Instance().getString("defaultsave.directory"));
 }
 /**
  * Restore previous input
@@ -76,20 +93,10 @@ void SANSAddFiles::initLayout()
 void SANSAddFiles::readSettings()
 {
   QSettings value_store;
-  value_store.beginGroup("CustomInterfaces/SANSRunWindow");
-  std::string defOut =
-    ConfigService::Instance().getString("defaultsave.directory");
+  value_store.beginGroup("CustomInterfaces/AddRuns");
   
-  QString qDefOut = QString::fromStdString(defOut);
-  //this string may be passed to python, so convert any '\' to '/' to make it compatible on all systems
-  Poco::Path defOutComp = Poco::Path(defOut);
-  if ( defOutComp.separator() == '\\' )
-  {
-    qDefOut.replace('\\', '/');
-  }
-  
-  m_SANSForm->summedPath_edit->setText(
-    value_store.value("AddRuns/OutPath", qDefOut).toString());
+  m_SANSForm->loadSeparateEntries->setChecked(
+    value_store.value("Minimise_memory", false).toBool());
 
   value_store.endGroup();
 }
@@ -99,8 +106,23 @@ void SANSAddFiles::readSettings()
 void SANSAddFiles::saveSettings()
 {
   QSettings value_store;
-  value_store.beginGroup("CustomInterfaces/SANSRunWindow");
-  value_store.setValue("AddRuns/OutPath", m_SANSForm->summedPath_edit->text());
+  value_store.beginGroup("CustomInterfaces/AddRuns");
+  value_store.setValue(
+    "Minimise_memory", m_SANSForm->loadSeparateEntries->isChecked());
+}
+/** sets tool tip strings for the components on the form
+*/
+void SANSAddFiles::setToolTips()
+{
+  m_SANSForm->summedPath_lb->setToolTip("The output files from summing the workspaces\nwill be saved to this directory");
+  m_SANSForm->summedPath_Btn->setToolTip("Set the directories used both for loading and\nsaving run data");
+  m_SANSForm->loadSeparateEntries->setToolTip("Where possible load a minimum amount into\nmemory at any time");
+
+  m_SANSForm->add_Btn->setToolTip("Click here to do the sum");
+  m_SANSForm->clear_Btn->setToolTip("Clear the run files to sum box");
+  m_SANSForm->browse_to_add_Btn->setToolTip("Select a run to add to the sum");
+  m_SANSForm->new2Add_edit->setToolTip("Select a run to add to the sum");
+  m_SANSForm->add_Btn->setToolTip("Select a run to add to the sum");
 }
 /** Creates a QListWidgetItem with the given text and inserts it
 *  into the list box
@@ -114,6 +136,26 @@ QListWidgetItem* SANSAddFiles::insertListFront(const QString &text)
   m_SANSForm->toAdd_List->insertItem(0, newItem);
   return newItem;
 }
+/** Sets directory to which files will be saved and the label
+*  that users see
+*  @param dir full path of the output directory
+*/
+void SANSAddFiles::setOutDir(std::string dir)
+{
+  m_outDir = QString::fromStdString(dir);
+  m_SANSForm->summedPath_lb->setText(OUT_MSG+m_outDir);
+}
+/** Update the output directory edit box if the Mantid system output
+*  directory has changed
+*  @param pDirInfo a pointer to an object with the output directory name in it
+*/
+void SANSAddFiles::changeOutputDir(Mantid::Kernel::ConfigValChangeNotification_ptr pDirInfo)
+{
+  if ( pDirInfo->key() == "defaultsave.directory" )
+  {
+    setOutDir(pDirInfo->curValue());
+  }
+}
 /**Moves the entry in the line edit new2Add_edit to the
 *  listbox toAdd_List, expanding any run number lists
 */
@@ -171,8 +213,7 @@ void SANSAddFiles::runPythonAddFiles()
   add2Runs2Add();
 
   QString code_torun = "import SANSadd2\n";
-  code_torun += "print SANSadd2.add_runs('";
-  code_torun += m_SANSForm->summedPath_edit->text()+"', (";
+  code_torun += "print SANSadd2.add_runs((";
   //there are multiple file list inputs that can be filled in loop through them
   for(int i = 0; i < m_SANSForm->toAdd_List->count(); ++i )
   {
@@ -203,6 +244,9 @@ void SANSAddFiles::runPythonAddFiles()
   //remove the comma that would remain at the end of the list
   code_torun.truncate(code_torun.length()-1);
   code_torun += ")";
+  
+  QString lowMem = m_SANSForm->loadSeparateEntries->isChecked()?"True":"False";
+  code_torun += ", lowMem="+lowMem;
 
   code_torun += ")\n";
 
@@ -227,21 +271,12 @@ void SANSAddFiles::runPythonAddFiles()
     QMessageBox::information(this, "Files summed", status);
   }
 }
-/** This slot opens a file browser allowing a user select a path, which
-* is copied into the summedPath_edit
+/** This slot opens a manage user directories dialog to allowing the default
+*  output directory to be changed
 */
-void SANSAddFiles::summedPathBrowse()
+void SANSAddFiles::outPathSel()
 {
-  QString dir = m_SANSForm->summedPath_edit->text();
-  
-  QString oPath = QFileDialog::getExistingDirectory(parForm, "Output path", dir);
-  if( ! oPath.trimmed().isEmpty() )
-  {
-    m_SANSForm->summedPath_edit->setText(oPath);
-    QSettings prevVals;
-    prevVals.beginGroup("CustomInterfaces/SANSRunWindow/AddRuns");
-    prevVals.setValue("OutPath", oPath);
-  }
+  MantidQt::API::ManageUserDirectories::openUserDirsDialog(this);
 }
 /** This slot opens a file browser allowing a user select files, which is
 * copied into the new2Add_edit ready to be copied to the listbox (toAdd_List)
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp
index 49fb5a18272..3b58757e259 100644
--- a/Code/Mantid/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp
+++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp
@@ -162,7 +162,7 @@ void SANSRunWindow::initLayout()
   {//sets up the AddFiles tab which must be deleted in the destructor
     m_addFilesTab = new SANSAddFiles(this, &m_uiForm);
   }
-  //List for Workspace delete signals
+  //Listen for Workspace delete signals
   AnalysisDataService::Instance().notificationCenter.addObserver(m_delete_observer);
 
   readSettings();
@@ -2852,6 +2852,7 @@ bool SANSRunWindow::runAssign(int key, QString & logs)
   if( is_trans )
   {
     QString direct_run = m_run_no_boxes.value(key + 3)->text();
+    QString direct_per = QString::number(getPeriod(key + 3));
     if( QFileInfo(direct_run).completeSuffix().isEmpty() )
     {
       if( direct_run.endsWith(".") ) 
@@ -2870,7 +2871,8 @@ bool SANSRunWindow::runAssign(int key, QString & logs)
       assign_fn = "i.TransmissionSample";
     }
     assign_fn += "('"+run_number+"','"+direct_run+"', reload = True";
-    assign_fn += ", period = " + QString::number(getPeriod(key))+")";
+    assign_fn += ", period_t = " + QString::number(getPeriod(key));
+    assign_fn += ", period_d = " + direct_per+")";
     //assign the workspace name to a Python variable and read back some details
     QString pythonC="t1, t2 = " + assign_fn + ";print '"+PYTHON_SEP+"',t1,'"+PYTHON_SEP+"',t2";
     QString ws_names = runReduceScriptFunction(pythonC);
@@ -3147,7 +3149,7 @@ void SANSRunWindow::setNumberPeriods(const int key, const int num)
 
   if (num > 0)
   {
-    label->setText("/ " + QString::number(num));
+    label->setText("/" + QString::number(num));
     if (userentry->text().isEmpty())
     {//default period to analysis is the first one
       userentry->setText("1");
@@ -3156,7 +3158,7 @@ void SANSRunWindow::setNumberPeriods(const int key, const int num)
   else
   {
     userentry->clear();
-    label->setText("/ ??");
+    label->setText("/??");
   }
 }
 /** Blank the periods information in a box
diff --git a/Code/Mantid/Scripts/SANS/ISISCommandInterface.py b/Code/Mantid/Scripts/SANS/ISISCommandInterface.py
index b599b232ffb..9e5300a027f 100644
--- a/Code/Mantid/Scripts/SANS/ISISCommandInterface.py
+++ b/Code/Mantid/Scripts/SANS/ISISCommandInterface.py
@@ -137,15 +137,31 @@ def AssignCan(can_run, reload = True, period = -1):
     return ISIS_global().background_subtracter.assign_can(
                                                     ISIS_global())
 
-def TransmissionSample(sample, direct, reload = True, period = -1):
+def TransmissionSample(sample, direct, reload = True, period_t = -1, period_d = -1):
+    """
+        Specify the transmission and direct runs for the sample
+        @param sample: the transmission run
+        @param direct: direct run
+        @param reload: if to replace the workspace if it is already there
+        @param period_t: the entry number of the transmission run (default single entry file)  
+        @param period_d: the entry number of the direct run (default single entry file)
+    """  
     _printMessage('TransmissionSample("' + sample + '","' + direct + '")')
-    ISIS_global().set_trans_sample(sample, direct, reload = True, period = -1)
+    ISIS_global().set_trans_sample(sample, direct, True, period_t, period_d)
     return ISIS_global().samp_trans_load.execute(
                                         ISIS_global(), None)
 
-def TransmissionCan(can, direct, reload = True, period = -1):
+def TransmissionCan(can, direct, reload = True, period_t = -1, period_d = -1):
+    """
+        Specify the transmission and direct runs for the can
+        @param can: the transmission run
+        @param direct: direct run
+        @param reload: if to replace the workspace if it is already there
+        @param period_t: the entry number of the transmission run (default single entry file)  
+        @param period_d: the entry number of the direct run (default single entry file)
+    """
     _printMessage('TransmissionCan("' + can + '","' + direct + '")')
-    ISIS_global().set_trans_can(can, direct, reload = True, period = -1)
+    ISIS_global().set_trans_can(can, direct, True, period_t, period_d)
     return ISIS_global().can_trans_load.execute(
                                             ISIS_global(), None)
     
@@ -251,7 +267,7 @@ def displayUserFile():
     print '-- Mask file defaults --'
     print ISIS_global().to_wavlen
     print ISIS_global().Q_string()
-    print correction_files()
+#    print correction_files()
     print '    direct beam file rear:',
     print ISIS_global().instrument.detector_file('rear')
     print '    direct beam file front:',
diff --git a/Code/Mantid/Scripts/SANS/SANSadd2.py b/Code/Mantid/Scripts/SANS/SANSadd2.py
index 3d6a4d1c835..c2b71e3ca74 100644
--- a/Code/Mantid/Scripts/SANS/SANSadd2.py
+++ b/Code/Mantid/Scripts/SANS/SANSadd2.py
@@ -1,6 +1,132 @@
 from mantidsimple import *
 from shutil import copyfile
 
+_NO_INDIVIDUAL_PERIODS = -1
+
+def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add'), lowMem=False):
+  #check if there is at least one file in the list
+  if len(runs) < 1 : return
+
+  if not defType.startswith('.') : defType = '.'+defType
+
+  #these input arguments need to be arrays of strings, enforce this
+  if type(runs) == str : runs = (runs, )
+  if type(rawTypes) == str : rawTypes = (rawTypes, )
+
+  if lowMem:
+    lowMem = _can_load_periods(runs, defType, rawTypes)
+  if lowMem:
+    period = 1
+  else:
+    period = _NO_INDIVIDUAL_PERIODS
+
+  userEntry = runs[0] 
+  
+  while(True):
+    #we need to catch all exceptions to ensure that a dialog box is raised with the error
+    try :
+      lastPath, lastFile, logFile, num_periods = _loadWS(
+        userEntry, defType, inst, 'AddFilesSumTempory', rawTypes, period)
+
+      for i in range(len(runs)-1):
+        userEntry = runs[i+1]
+        lastPath, lastFile, logFile, dummy = _loadWS(
+          userEntry, defType, inst,'AddFilesNewTempory', rawTypes, period)
+        Plus('AddFilesSumTempory', 'AddFilesNewTempory', 'AddFilesSumTempory')
+        mantid.deleteWorkspace("AddFilesNewTempory")
+        
+    except ValueError, reason:
+      error = 'Error opening file ' + userEntry+': ' + reason.message
+      print error
+      mantid.sendLogMessage(error)
+      if mantid.workspaceExists('AddFilesSumTempory')  : mantid.deleteWorkspace('AddFilesSumTempory')
+      return ""
+    except Exception, reason:
+      error = 'Error finding files: ' + reason.message
+      print error
+      mantid.sendLogMessage(error)
+      if mantid.workspaceExists('AddFilesSumTempory') : mantid.deleteWorkspace('AddFilesSumTempory')
+      if mantid.workspaceExists('AddFilesNewTempory') : mantid.deleteWorkspace("AddFilesNewTempory")
+      return ""
+
+    lastFile = lastFile.rpartition('.')[0]
+    # now save the added file
+    outFile = lastFile+'-add.'+'nxs'
+    mantid.sendLogMessage('writing file:   '+outFile)
+    if period == 1 or period == _NO_INDIVIDUAL_PERIODS:
+      #replace the file the first time around
+      sav = SaveNexusProcessed("AddFilesSumTempory", outFile, Append=False)
+    else:
+      #then append
+      sav = SaveNexusProcessed("AddFilesSumTempory", outFile, Append=True)
+     
+    mantid.deleteWorkspace("AddFilesSumTempory")
+  
+    if period == num_periods:
+      break
+
+    if period == _NO_INDIVIDUAL_PERIODS:
+      break
+    else:
+      period += 1
+
+  #this adds the path to the filename
+  outFile = sav.getPropertyValue('Filename')
+  pathout = os.path.split(outFile)[0]
+  if logFile:
+    _copyLog(lastPath, logFile, pathout)
+
+  return 'The following file has been created:\n'+outFile
+
+def _can_load_periods(runs, defType, rawTypes):
+  """
+    Searches through the supplied list of run file names and
+    returns False if some appear to be raw files else True
+  """ 
+  for i in runs:
+    dummy, ext = os.path.splitext(i)
+    if ext == '': ext = defType
+    if _isType(ext, rawTypes):
+      return False
+  #no raw files were found, assume we can specify the period number for each
+  return True
+
+def _loadWS(entry, ext, inst, wsName, rawTypes, period=_NO_INDIVIDUAL_PERIODS) :
+  try :
+    runNum = int(entry)                          #the user entered something that translates to a run number, convert it to a file 
+    filename=inst+_padZero(runNum, inst)+ext
+  except ValueError :                            #we don't have a run number, assume it's a valid filename
+    filename = entry
+    dummy, ext = os.path.splitext(filename)
+
+  mantid.sendLogMessage('reading file:   '+filename)
+
+  if period != _NO_INDIVIDUAL_PERIODS:
+      #load just a single period
+      props = Load(Filename=filename,OutputWorkspace=wsName, EntryNumber=period)
+  else:
+      props = Load(Filename=filename,OutputWorkspace=wsName)
+
+  path = props.getPropertyValue('FileName')
+  path, fName = os.path.split(path)
+  if path.find('/') == -1:
+    #looks like we're on a windows system, convert the directory separators
+    path = path.replace('\\', '/')
+
+  logFile = None
+  #file types of .raw need their log files to be copied too
+  if _isType(ext, rawTypes):
+    logFile = fName.rpartition('.')[0]+'.log'
+    
+  try:
+    samp = mtd[wsName].getSampleDetails()
+    numPeriods = samp.getLogData('nperiods').value
+  except:
+    #assume the run file didn't support multi-period data and so there is only one period
+    numPeriods = 1
+  
+  return path, fName, logFile, numPeriods
+
 def _padZero(runNum, inst='SANS2D'):
   if inst.upper() == 'SANS2D' : numDigits = 8
   elif inst.upper() == 'LOQ' : numDigits = 5
@@ -25,82 +151,12 @@ def _isType(ext, allTypes):
         return True
   return False
 
-def _loadWS(entry, ext, inst, wsName, rawTypes) :
-  try :
-    runNum = int(entry)                          #the user entered something that translates to a run number, convert it to a file 
-    filename=inst+_padZero(runNum, inst)+ext
-  except ValueError :                            #we don't have a run number, assume it's a valid filename
-    filename = entry
-    dummy, ext = os.path.splitext(filename)
-
-  mantid.sendLogMessage('reading file:   '+filename)
-
-  props = Load(Filename=filename,OutputWorkspace=wsName)
-
-  path = props.getPropertyValue('FileName')
-  path, fName = os.path.split(path)
-
-  logFile = None
-  #file types of .raw need their log files to be copied too
-  if _isType(ext, rawTypes):
-    logFile = fName.rpartition('.')[0]+'.log'
-  
-  return path, fName, logFile
-
 def _copyLog(lastPath, logFile, pathout):
   try :
     logFile = lastPath+'/'+logFile
-    copyfile(logFile, pathout+os.path.basename(logFile))
-  except Exception, reason:
-    error = 'Error copying log file ' + logFile + ' to directory' + pathout
-    print error
-    mantid.sendLogMessage(error)
-
-def add_runs(pathout, runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add')):
-  pathout += '/'+inst+'/'
-  if not defType.startswith('.') : defType = '.'+defType
-
-  #these input arguments need to be arrays of strings, inforce this
-  if type(runs) == str : runs = (runs, )
-  if type(rawTypes) == str : rawTypes = (rawTypes, )
-
-  indices=range(len(runs)-1)
-
-  if len(runs) < 1 : return                    #check if there is at least one file in the list
-
-  userEntry = runs[0]
-  #we need to catch all exceptions to ensure that a dialog box is raised with the error
-  try :
-    lastPath, lastFile, logFile = _loadWS(userEntry, defType, inst, 'AddFilesSumTempory', rawTypes)
-
-    for i in indices:
-      userEntry = runs[i+1]
-      lastPath, lastFile, logFile = _loadWS(userEntry, defType, inst,'AddFilesNewTempory', rawTypes)
-      Plus('AddFilesSumTempory', 'AddFilesNewTempory', 'AddFilesSumTempory')
-      mantid.deleteWorkspace("AddFilesNewTempory")
-
-  except ValueError, reason:
-    error = 'Error opening file ' + userEntry+': ' + reason.message
-    print error
-    mantid.sendLogMessage(error)
-    if mantid.workspaceExists('AddFilesSumTempory')  : mantid.deleteWorkspace('AddFilesSumTempory')
-    return ""
+    copyfile(logFile, pathout+'/'+os.path.basename(logFile))
   except Exception, reason:
-    error = 'Error finding files: ' + reason.message
+    error = 'Error copying log file ' + logFile + ' to directory ' + pathout+'\n'
     print error
     mantid.sendLogMessage(error)
-    if mantid.workspaceExists('AddFilesSumTempory') : mantid.deleteWorkspace('AddFilesSumTempory')
-    if mantid.workspaceExists('AddFilesNewTempory') : mantid.deleteWorkspace("AddFilesNewTempory")
-    return ""
-
-  lastFile = lastFile.rpartition('.')[0]
-  # now save the added file
-  outFile = pathout+lastFile+"-add."+'nxs'
-  mantid.sendLogMessage('writing file:   '+outFile)
-  SaveNexusProcessed("AddFilesSumTempory", outFile)
-  mantid.deleteWorkspace("AddFilesSumTempory")
-  
-  if not logFile is None:
-    _copyLog(lastPath, logFile, pathout)
 
-  return 'The following file has been created:\n'+outFile
\ No newline at end of file
diff --git a/Code/Mantid/Scripts/SANS/isis_reducer.py b/Code/Mantid/Scripts/SANS/isis_reducer.py
index c98f955c497..9d9e1b9a923 100644
--- a/Code/Mantid/Scripts/SANS/isis_reducer.py
+++ b/Code/Mantid/Scripts/SANS/isis_reducer.py
@@ -78,9 +78,6 @@ class ISISReducer(SANSReducer):
         self._reduction_steps.append(self.background_subtracter)
         self._reduction_steps.append(self._zero_errors)
         self._reduction_steps.append(self._rem_zeros)
-        
-        #if set to an integer only that period will be extracted from the run file and processed 
-        self._period_num = None
 
     def _init_steps(self):
         """
@@ -110,9 +107,6 @@ class ISISReducer(SANSReducer):
         self._geo_corr =       sans_reduction_steps.SampleGeomCor(self.geometry)
         self._zero_errors =    isis_reduction_steps.ReplaceErrors()
         self._rem_zeros =      sans_reduction_steps.StripEndZeros()
-        
-        #if set to an integer only that period will be extracted from the run file and processed 
-        self._period_num = None
 
     def pre_process(self): 
         """
@@ -141,8 +135,6 @@ class ISISReducer(SANSReducer):
         if not issubclass(self.data_loader.__class__, isis_reduction_steps.LoadSample):
             raise RuntimeError, "ISISReducer.load_set_options: method called with wrong loader class"
         self.data_loader.set_options(reload, period)
-        if period > 0:
-            self._period_num = period
 
     def set_run_number(self, data_file, workspace=None):
         """
@@ -181,17 +173,19 @@ class ISISReducer(SANSReducer):
         self.transmission_calculator.set_trans_fit(lambda_min, lambda_max, fit_method, override=True)
         self.transmission_calculator.enabled = True
         
-    def set_trans_sample(self, sample, direct, reload=True, period=-1):
+    def set_trans_sample(self, sample, direct, reload=True, period_t = -1, period_d = -1):
         if not issubclass(self.samp_trans_load.__class__, sans_reduction_steps.BaseTransmission):
-            self.samp_trans_load = isis_reduction_steps.LoadTransmissions()
-        self.samp_trans_load.set_run(sample, direct, reload, period)
+            self.samp_trans_load = isis_reduction_steps.LoadTransmissions(reload)
+        self.samp_trans_load.set_trans(sample, period_t)
+        self.samp_trans_load.set_direc(direct, period_d)
         self.transmission_calculator.set_loader(self.samp_trans_load)
 
-    def set_trans_can(self, can, direct, reload = True, period = -1):
+    def set_trans_can(self, can, direct, reload = True, period_t = -1, period_d = -1):
         if not issubclass(self.can_trans_load.__class__, sans_reduction_steps.BaseTransmission):
-            self.can_trans_load = isis_reduction_steps.LoadTransmissions(is_can=True)
-        self.can_trans_load.set_run(can, direct, reload, period)
-        
+            self.can_trans_load = isis_reduction_steps.LoadTransmissions(is_can=True, reload=reload)
+        self.can_trans_load.set_trans(can, period_t)
+        self.can_trans_load.set_direc(direct, period_d)
+
     def set_monitor_spectrum(self, specNum, interp=False, override=True):
         if override:
             self._monitor_set=True
diff --git a/Code/Mantid/Scripts/SANS/isis_reduction_steps.py b/Code/Mantid/Scripts/SANS/isis_reduction_steps.py
index 9db21cae447..b29d45f415b 100644
--- a/Code/Mantid/Scripts/SANS/isis_reduction_steps.py
+++ b/Code/Mantid/Scripts/SANS/isis_reduction_steps.py
@@ -41,13 +41,14 @@ class LoadRun(ReductionStep):
         Load a data file, move its detector to the right position according
         to the beam center and normalize the data.
     """
-    def __init__(self, data_file=None, spec_min=None, spec_max=None, period=1):
+    UNSET_PERIOD = -1
+    def __init__(self, data_file=None, spec_min=None, spec_max=None, entry=UNSET_PERIOD):
         #TODO: data_file = None only makes sense when AppendDataFile is used... (AssignSample?)
         super(LoadRun, self).__init__()
         self._data_file = data_file
         self._spec_min = spec_min
         self._spec_max = spec_max
-        self._period = period
+        self.period = entry
         
     def execute(self, reducer, workspace):
         # If we don't have a data file, look up the workspace handle
@@ -59,24 +60,40 @@ class LoadRun(ReductionStep):
                 raise RuntimeError, "ISISReductionSteps.LoadRun doesn't recognize workspace handle %s" % workspace
         
         if os.path.splitext(self._data_file)[1].lower().startswith('.r'):
+            #raw files have some different options
             alg = LoadRaw(self._data_file, workspace, SpectrumMin=self._spec_min, SpectrumMax=self._spec_max)
             LoadSampleDetailsFromRaw(workspace, self._data_file)
         else:
-            alg = Load(self._data_file, workspace, SpectrumMin=self._spec_min, SpectrumMax=self._spec_max)
-    
+            #this is the generic situation
+            if not self.period == self.UNSET_PERIOD:
+                alg = Load(self._data_file, workspace,
+                  SpectrumMin=self._spec_min, SpectrumMax=self._spec_max, EntryNumber=self.period)
+            else:
+                #no specific period was requested
+                alg = Load(self._data_file, workspace,
+                  SpectrumMin=self._spec_min, SpectrumMax=self._spec_max)
+       
+        #deal with selection and reporting of periods in multi-period files, this is complicated because different file formats have different ways of report numbers of periods
+        numPeriods = -1
         pWorksp = mantid[workspace]
-    
         if pWorksp.isGroup() :
             #get the number of periods in a group using the fact that each period has a different name
             numPeriods = len(pWorksp.getNames())
-            workspace = self._leaveSinglePeriod(pWorksp, self._period)
+            #if the user didn't specify a period use the first period
+            if self.period == self.UNSET_PERIOD: self.period == 1
+            workspace = self._leaveSinglePeriod(pWorksp, self.period)
         else :
-            #if the work space isn't a group there is only one period
-            numPeriods = 1
+            if self.period == self.UNSET_PERIOD:
+                #they didn't specify a period but there is only one period, the original file must contain no more than one period 
+                numPeriods = 1
+        #the logs have the definitive information on the number of periods, if it is in the logs
+        try:
+            samp = pWorksp.getSampleDetails()
+            numPeriods = samp.getLogData('nperiods').value
+        except:
+            #it's OK for there not to be any logs
+            pass
             
-        if (self._period > numPeriods) or (self._period < 1):
-            raise ValueError('_loadRawData: Period number ' + str(self._period) + ' doesn\'t exist in workspace ' + pWorksp.getName())
-        
         # Return the file path actually used to load the data
         fullpath = alg.getPropertyValue("Filename")
 
@@ -89,13 +106,13 @@ class LoadRun(ReductionStep):
 
         wkspname, run_no, logname, data_file = extract_workspace_name(
             run_string, is_trans, prefix=reducer.instrument.name(), 
-            run_number_width=reducer.instrument.run_number_width)
+            run_number_width=reducer.instrument.run_number_width, period=period)
 
         if run_no == '':
             return SANSUtility.WorkspaceDetails('', -1),True,'','', -1
 
         if reload == False and mantid.workspaceExists(wkspname):
-            return SANSUtility.WorkspaceDetails(wkspname, shortrun_no),False,'','', -1
+            return SANSUtility.WorkspaceDetails(wkspname, run_no),False,'','', -1
 
         filename = os.path.join(reducer._data_path, data_file)
         # Workaround so that the FileProperty does the correct searching of data paths if this file doesn't exist
@@ -113,14 +130,14 @@ class LoadRun(ReductionStep):
                     specmin = None
                     specmax = 8
 
-                loader = LoadRun(filename, spec_min=specmin, spec_max=specmax, period=period)
+                loader = LoadRun(filename, spec_min=specmin, spec_max=specmax, entry=period)
                 [filepath, wkspname, nPeriods] = loader.execute(reducer, wkspname)
             except RuntimeError, err:
                 mantid.sendLogMessage("::SANS::Warning: "+str(err))
                 return SANSUtility.WorkspaceDetails('', -1),True,'','', -1
         else:
             try:
-                loader = LoadRun(filename, spec_min=None, spec_max=None, period=period)
+                loader = LoadRun(filename, spec_min=None, spec_max=None, entry=period)
                 [filepath, wkspname, nPeriods] = loader.execute(reducer, wkspname)
             except RuntimeError, details:
                 mantid.sendLogMessage("::SANS::Warning: "+str(details))
@@ -131,6 +148,9 @@ class LoadRun(ReductionStep):
         return inWS,True, reducer.instrument.name() + logname, filepath, nPeriods
 
     def _leaveSinglePeriod(self, groupW, period):
+        if (self.period > len(pWorksp.getNames())) or (self.period < 1):
+            raise ValueError('_loadRawData: Period number ' + str(self.period) + ' doesn\'t exist in workspace ' + pWorksp.getName())
+
         #get the name of the individual workspace in the group
         oldName = groupW.getName()+'_'+str(period)
         #move this workspace out of the group (this doesn't delete it)
@@ -162,31 +182,39 @@ class LoadTransmissions(sans_reduction_steps.BaseTransmission, LoadRun):
         sample or can 
     """
 
-    def __init__(self, is_can=False):
+    def __init__(self, is_can=False, reload=True):
         """
+            Two settings can be set at initialization, if this is for
+            can and if the workspaces should be reloaded if they already
+            exist
+            @param is_can: if this is to correct the can (default false i.e. it's for the sample)
+            @param reload: setting this to false will mean the workspaces aren't reloaded if they already exist (default True i.e. reload)
         """
         super(LoadTransmissions, self).__init__()
         self.trans_name = None
         self.direct_name = None
-        self._reload = True
-        self._period = -1
+        self._reload = reload
+        self._period_t = -1
+        self._period_d = -1
         self.can = is_can
 
-    def set_run(self, sample, direct, reload=True, period=-1):            
-        self._trans_name = sample
+    def set_trans(self, trans, period=-1):            
+        self._trans_name = trans
+        self._period_t = period
+
+    def set_direc(self, direct, period=-1):            
         self._direct_name = direct
-        self._reload = reload
-        self._period = period
+        self._period_d = period
 
     def execute(self, reducer, workspace):
         if self._trans_name not in [None, '']:
             trans_ws, dummy1, dummy2, dummy3, self.TRANS_SAMPLE_N_PERIODS = \
-                self._assignHelper(reducer, self._trans_name, True, self._reload, self._period)
+                self._assignHelper(reducer, self._trans_name, True, self._reload, self._period_t)
             self.trans_name = trans_ws.getName()
         
         if self._direct_name not in [None, '']:
             direct_sample_ws, dummy1, dummy2, dummy3, self.DIRECT_SAMPLE_N_PERIODS = \
-                self._assignHelper(reducer, self._direct_name, True, self._reload, self._period)
+                self._assignHelper(reducer, self._direct_name, True, self._reload, self._period_d)
             self.direct_name = direct_sample_ws.getName()
 
         return self.trans_name, self.direct_name
@@ -226,7 +254,7 @@ class CanSubtraction(LoadRun):
             return '', '()'
     
         self.SCATTER_CAN ,reset, logname,filepath, self._CAN_N_PERIODS = \
-            self._assignHelper(reducer, self._can_run, False, reload, period)
+            self._assignHelper(reducer, self._can_run, False, reload, self._can_run_period)
         if self.SCATTER_CAN.getName() == '':
             mantid.sendLogMessage('::SANS::Warning: Unable to load sans can run, cannot continue.')
             return '','()'
@@ -678,8 +706,8 @@ class LoadSample(LoadRun):
     #TODO: we don't need a dictionary here
     PERIOD_NOS = { "SCATTER_SAMPLE":1, "SCATTER_CAN":1 }
 
-    def __init__(self, sample=None, reload=True, period=-1):
-        super(LoadRun, self).__init__()
+    def __init__(self, sample=None, reload=True, entry=-1):
+        super(LoadSample, self).__init__(entry)
         self.SCATTER_SAMPLE = None
         self._SAMPLE_SETUP = None
         self._SAMPLE_RUN = None
@@ -687,7 +715,6 @@ class LoadSample(LoadRun):
         # the run number followed by dot and the extension
         self.sample_run = sample
         self._reload = reload
-        self._period = period
         
         self.maskpt_rmin = None
         
@@ -696,7 +723,7 @@ class LoadSample(LoadRun):
     
     def set_options(self, reload=True, period=-1):
         self._reload = reload
-        self._period = period
+        self.period = period
         
     def execute(self, reducer, workspace):
         # If we don't have a data file, look up the workspace handle
@@ -712,7 +739,7 @@ class LoadSample(LoadRun):
             self.SCATTER_SAMPLE = None
             raise RuntimeError('Sample needs to be assigned as run_number.file_type')
 
-        self.SCATTER_SAMPLE, reset, logname, filepath, self._SAMPLE_N_PERIODS = self._assignHelper(reducer, self.sample_run, False, self._reload, self._period)
+        self.SCATTER_SAMPLE, reset, logname, filepath, self._SAMPLE_N_PERIODS = self._assignHelper(reducer, self.sample_run, False, self._reload, self.period)
         if self.SCATTER_SAMPLE.getName() == '':
             raise RuntimeError('Unable to load SANS sample run, cannot continue.')
         if reset == True:
@@ -741,7 +768,7 @@ class LoadSample(LoadRun):
         except AttributeError:
             if not reducer.instrument.name() == 'LOQ': raise
         
-        self.PERIOD_NOS["SCATTER_SAMPLE"] = self._period
+        self.PERIOD_NOS["SCATTER_SAMPLE"] = self.period
 
         reducer.wksp_name = self.uncropped
         
@@ -1483,8 +1510,6 @@ class GetOutputName(ReductionStep):
         run = reducer._data_files.values()[0]
         name = run.split('_')[0]
         
-        if (not reducer._period_num is None) and (reducer._period_num > 0):
-            name += 'p'+str(reducer._period_num)
         name += reducer.instrument.cur_detector().name('short')
         name += '_' + reducer.to_Q.output_type
         name += '_' + reducer.to_wavelen.get_range()
@@ -1499,7 +1524,7 @@ class ReplaceErrors(ReductionStep):
         ReplaceSpecialValues(InputWorkspace = workspace,OutputWorkspace = workspace, NaNValue="0", InfinityValue="0")
 
 
-def extract_workspace_name(run_string, is_trans=False, prefix='', run_number_width=8):
+def extract_workspace_name(run_string, is_trans=False, prefix='', run_number_width=8, period=-1):
     """
         Takes a run number and file type and generates the filename, workspace name and log name
         @param run_string a run number followed by a dot and then the file type, i.e. file extension
@@ -1513,7 +1538,10 @@ def extract_workspace_name(run_string, is_trans=False, prefix='', run_number_wid
         ext = pieces[1]
     
     fullrun_no, logname, shortrun_no = _padRunNumber(run_no, run_number_width)
-
+    shortrun_no = str(shortrun_no)
+    
+    if period > -1:
+        shortrun_no += 'p'+str(period)
     if is_trans:
         wkspname =  shortrun_no + '_trans_' + ext.lower()
     else:
-- 
GitLab