Index: SaveAll.ui
===================================================================
--- SaveAll.ui	(revision 1255)
+++ SaveAll.ui	(revision 1256)
@@ -1,172 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>SaveAllDlg</class>
- <widget class="QDialog" name="SaveAllDlg">
-  <property name="geometry">
-   <rect>
-    <x>0</x>
-    <y>0</y>
-    <width>861</width>
-    <height>388</height>
-   </rect>
-  </property>
-  <property name="windowTitle">
-   <string>Dialog</string>
-  </property>
-  <layout class="QGridLayout" name="gridLayout_2">
-   <item row="0" column="0" colspan="2">
-    <widget class="QGroupBox" name="saveViewFile">
-     <property name="title">
-      <string>View File</string>
-     </property>
-     <property name="checkable">
-      <bool>true</bool>
-     </property>
-     <layout class="QHBoxLayout" name="horizontalLayout_2">
-      <item>
-       <widget class="QLineEdit" name="viewFileName"/>
-      </item>
-      <item>
-       <widget class="QPushButton" name="selectViewFile">
-        <property name="maximumSize">
-         <size>
-          <width>32</width>
-          <height>32</height>
-         </size>
-        </property>
-        <property name="text">
-         <string>...</string>
-        </property>
-       </widget>
-      </item>
-     </layout>
-    </widget>
-   </item>
-   <item row="1" column="0">
-    <widget class="QGroupBox" name="saveStacks">
-     <property name="title">
-      <string>Stacks</string>
-     </property>
-     <property name="checkable">
-      <bool>true</bool>
-     </property>
-     <layout class="QGridLayout" name="gridLayout">
-      <item row="0" column="0" colspan="3">
-       <widget class="QTreeView" name="stackList">
-        <property name="alternatingRowColors">
-         <bool>true</bool>
-        </property>
-        <property name="rootIsDecorated">
-         <bool>false</bool>
-        </property>
-       </widget>
-      </item>
-      <item row="1" column="0">
-       <spacer name="horizontalSpacer">
-        <property name="orientation">
-         <enum>Qt::Horizontal</enum>
-        </property>
-        <property name="sizeHint" stdset="0">
-         <size>
-          <width>195</width>
-          <height>20</height>
-         </size>
-        </property>
-       </spacer>
-      </item>
-      <item row="1" column="1">
-       <widget class="QLabel" name="label">
-        <property name="text">
-         <string>Compression level</string>
-        </property>
-       </widget>
-      </item>
-      <item row="1" column="2">
-       <widget class="QSpinBox" name="compressionLevel">
-        <property name="minimum">
-         <number>-1</number>
-        </property>
-        <property name="maximum">
-         <number>9</number>
-        </property>
-       </widget>
-      </item>
-     </layout>
-    </widget>
-   </item>
-   <item row="1" column="1">
-    <widget class="QGroupBox" name="saveMeshes">
-     <property name="title">
-      <string>Meshes</string>
-     </property>
-     <property name="checkable">
-      <bool>true</bool>
-     </property>
-     <layout class="QVBoxLayout" name="verticalLayout">
-      <item>
-       <widget class="QTreeView" name="meshList">
-        <property name="alternatingRowColors">
-         <bool>true</bool>
-        </property>
-        <property name="rootIsDecorated">
-         <bool>false</bool>
-        </property>
-       </widget>
-      </item>
-     </layout>
-    </widget>
-   </item>
-   <item row="2" column="0" colspan="2">
-    <widget class="QDialogButtonBox" name="buttonBox">
-     <property name="orientation">
-      <enum>Qt::Horizontal</enum>
-     </property>
-     <property name="standardButtons">
-      <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
-     </property>
-    </widget>
-   </item>
-  </layout>
-  <zorder>saveViewFile</zorder>
-  <zorder>saveStacks</zorder>
-  <zorder>saveMeshes</zorder>
-  <zorder>buttonBox</zorder>
-  <zorder>selectViewFile</zorder>
-  <zorder>meshList</zorder>
- </widget>
- <resources/>
- <connections>
-  <connection>
-   <sender>buttonBox</sender>
-   <signal>accepted()</signal>
-   <receiver>SaveAllDlg</receiver>
-   <slot>accept()</slot>
-   <hints>
-    <hint type="sourcelabel">
-     <x>248</x>
-     <y>254</y>
-    </hint>
-    <hint type="destinationlabel">
-     <x>157</x>
-     <y>274</y>
-    </hint>
-   </hints>
-  </connection>
-  <connection>
-   <sender>buttonBox</sender>
-   <signal>rejected()</signal>
-   <receiver>SaveAllDlg</receiver>
-   <slot>reject()</slot>
-   <hints>
-    <hint type="sourcelabel">
-     <x>316</x>
-     <y>260</y>
-    </hint>
-    <hint type="destinationlabel">
-     <x>286</x>
-     <y>274</y>
-    </hint>
-   </hints>
-  </connection>
- </connections>
-</ui>
Index: SystemProcessSave.cpp
===================================================================
--- SystemProcessSave.cpp	(revision 1255)
+++ SystemProcessSave.cpp	(revision 1256)
@@ -18,7 +18,6 @@
 
 #include <ui_SaveMesh.h>
 #include <ui_ExportMesh.h>
-#include <ui_SaveAll.h>
 #include <ui_ExportStack.h>
 
 using namespace cimg_library;
@@ -31,132 +30,145 @@
 #  define FileDialogOptions 0
 #endif
 
-namespace mgx {
-namespace process {
+namespace mgx { namespace process {
 
-typedef CImg<ushort> CImgUS;
-
-struct StackHdr {
-  uint hdrsz;
-  uint xsz, ysz, zsz;
-  float xum, yum, zum;
-  uint datasz;
-
-  StackHdr()
-    : hdrsz(1024)
+  typedef CImg<ushort> CImgUS;
+  
+  struct StackHdr 
   {
+    uint hdrsz;
+    uint xsz, ysz, zsz;
+    float xum, yum, zum;
+    uint datasz;
+  
+    StackHdr() : hdrsz(1024) {}
+  };
+  
+  bool StackSave::operator()(const QStringList& parms)
+  {
+    int stackId = parms[2].toInt();
+    int compressionLevel = parms[3].toInt();
+    if(!checkState().stack(STACK_ANY, stackId))
+      return false;
+    Stack* stack = this->stack(stackId);
+    Store* store = (stringToWorkStore(parms[1]) ? stack->work() : stack->main());
+    bool res = (*this)(stack, store, parms[0], compressionLevel);
+    return res;
   }
-};
-
-bool StackSave::operator()(const QStringList& parms)
-{
-  int stackId = parms[2].toInt();
-  int compressionLevel = parms[3].toInt();
-  if(!checkState().stack(STACK_ANY, stackId))
-    return false;
-  Stack* stack = this->stack(stackId);
-  Store* store = (stringToWorkStore(parms[1]) ? stack->work() : stack->main());
-  bool res = (*this)(stack, store, parms[0], compressionLevel);
-  return res;
-}
-
-bool StackSave::operator()(Stack* stack, Store* store, const QString& filename, int compressionLevel)
-{
-  if(filename.isEmpty()) {
-    setErrorMessage("Error, trying to save a stack with an empty filename.");
-    return false;
-  }
-
-  actingFile(filename);
-
-  QFile file(filename);
-  if(!file.open(QIODevice::WriteOnly))
-    throw QString("Cannot open output file - %1").arg(filename);
-
-  store->setFile(util::stripCurrentDir(filename));
-
-  HVecUS& data = store->data();
-
-  Progress progress(QString("Saving %1 Stack %2").arg(store == stack->main() ? "main" : "work").arg(stack->userId()),
-                    0);
-  qint64 qty;
-
-  // Process the various types
-  if(filename.endsWith(".mgxs", Qt::CaseInsensitive)) {
-    if(compressionLevel > 9)
-      compressionLevel = 9;
-    if(compressionLevel < -1)
-      compressionLevel = -1;
-    Point3u size = stack->size();
-    Point3f step = stack->step();
-    Point3f origin = stack->origin();
-    quint32 xsz = size.x();
-    quint32 ysz = size.y();
-    quint32 zsz = size.z();
-    quint8 cl = (quint8)compressionLevel;
-    float xum = step.x();
-    float yum = step.y();
-    float zum = step.z();
-    float sxum = origin.x();
-    float syum = origin.y();
-    float szum = origin.z();
-    bool isLabel = store->labels();
-    quint64 datasz = quint64(data.size()) * 2ul;
-
-    static const char version[] = "MGXS 1.3 ";
-    qty = file.write(version, sizeof(version) - 1);
-    if(qty != sizeof(version) - 1)
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(version)
-                                                                                               - 1);
-    qty = file.write((const char*)&isLabel, sizeof(bool));
-    if(qty != sizeof(bool))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(bool));
-    qty = file.write((const char*)&sxum, sizeof(float));
-    if(qty != sizeof(float))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
-    qty = file.write((const char*)&syum, sizeof(float));
-    if(qty != sizeof(float))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
-    qty = file.write((const char*)&szum, sizeof(float));
-    if(qty != sizeof(float))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
-    qty = file.write((const char*)&xsz, sizeof(quint32));
-    if(qty != sizeof(quint32))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(quint32));
-    qty = file.write((const char*)&ysz, sizeof(quint32));
-    if(qty != sizeof(quint32))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(quint32));
-    qty = file.write((const char*)&zsz, sizeof(quint32));
-    if(qty != sizeof(quint32))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(quint32));
-    qty = file.write((const char*)&xum, sizeof(float));
-    if(qty != sizeof(float))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
-    qty = file.write((const char*)&yum, sizeof(float));
-    if(qty != sizeof(float))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
-    qty = file.write((const char*)&zum, sizeof(float));
-    if(qty != sizeof(float))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
-    qty = file.write((const char*)&datasz, sizeof(quint64));
-    if(qty != sizeof(quint64))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(quint64));
-    qty = file.write((const char*)&cl, sizeof(quint8));
-    if(qty != sizeof(quint8))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(quint8));
-
-    if(compressionLevel > 0) {
-      // QByteArray stkdata = qCompress((const uchar *)data.data(), data.size() * 2ul, 1);
-      // file.write(stkdata);
-      // Make slices of 64MB
-      quint64 nb_slices = datasz >> 26;
-      quint64 slice_size = 1ul << 26;
-      progress.setMaximum(nb_slices);
-      for(quint64 i = 0; i < nb_slices; ++i) {
-        QByteArray stkdata
-          = qCompress((const uchar*)data.data() + i * slice_size, slice_size, compressionLevel);
+  
+  bool StackSave::operator()(Stack* stack, Store* store, const QString& filename, int compressionLevel)
+  {
+    if(filename.isEmpty()) {
+      setErrorMessage("Error, trying to save a stack with an empty filename.");
+      return false;
+    }
+  
+    actingFile(filename);
+  
+    QFile file(filename);
+    if(!file.open(QIODevice::WriteOnly))
+      throw QString("Cannot open output file - %1").arg(filename);
+  
+    store->setFile(util::stripCurrentDir(filename));
+  
+    HVecUS& data = store->data();
+  
+    Progress progress(QString("Saving %1 Stack %2").arg(store == stack->main() ? "main" : "work").arg(stack->userId()),
+                      0);
+    qint64 qty;
+  
+    // Process the various types
+    if(filename.endsWith(".mgxs", Qt::CaseInsensitive)) {
+      if(compressionLevel > 9)
+        compressionLevel = 9;
+      if(compressionLevel < -1)
+        compressionLevel = -1;
+      Point3u size = stack->size();
+      Point3f step = stack->step();
+      Point3f origin = stack->origin();
+      quint32 xsz = size.x();
+      quint32 ysz = size.y();
+      quint32 zsz = size.z();
+      quint8 cl = (quint8)compressionLevel;
+      float xum = step.x();
+      float yum = step.y();
+      float zum = step.z();
+      float sxum = origin.x();
+      float syum = origin.y();
+      float szum = origin.z();
+      bool isLabel = store->labels();
+      quint64 datasz = quint64(data.size()) * 2ul;
+  
+      static const char version[] = "MGXS 1.3 ";
+      qty = file.write(version, sizeof(version) - 1);
+      if(qty != sizeof(version) - 1)
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(version)
+                                                                                                 - 1);
+      qty = file.write((const char*)&isLabel, sizeof(bool));
+      if(qty != sizeof(bool))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(bool));
+      qty = file.write((const char*)&sxum, sizeof(float));
+      if(qty != sizeof(float))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
+      qty = file.write((const char*)&syum, sizeof(float));
+      if(qty != sizeof(float))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
+      qty = file.write((const char*)&szum, sizeof(float));
+      if(qty != sizeof(float))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
+      qty = file.write((const char*)&xsz, sizeof(quint32));
+      if(qty != sizeof(quint32))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(quint32));
+      qty = file.write((const char*)&ysz, sizeof(quint32));
+      if(qty != sizeof(quint32))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(quint32));
+      qty = file.write((const char*)&zsz, sizeof(quint32));
+      if(qty != sizeof(quint32))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(quint32));
+      qty = file.write((const char*)&xum, sizeof(float));
+      if(qty != sizeof(float))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
+      qty = file.write((const char*)&yum, sizeof(float));
+      if(qty != sizeof(float))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
+      qty = file.write((const char*)&zum, sizeof(float));
+      if(qty != sizeof(float))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
+      qty = file.write((const char*)&datasz, sizeof(quint64));
+      if(qty != sizeof(quint64))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(quint64));
+      qty = file.write((const char*)&cl, sizeof(quint8));
+      if(qty != sizeof(quint8))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(quint8));
+  
+      if(compressionLevel > 0) {
+        // QByteArray stkdata = qCompress((const uchar *)data.data(), data.size() * 2ul, 1);
+        // file.write(stkdata);
+        // Make slices of 64MB
+        quint64 nb_slices = datasz >> 26;
+        quint64 slice_size = 1ul << 26;
+        progress.setMaximum(nb_slices);
+        for(quint64 i = 0; i < nb_slices; ++i) {
+          QByteArray stkdata
+            = qCompress((const uchar*)data.data() + i * slice_size, slice_size, compressionLevel);
+          quint32 sz = stkdata.size();
+          qty = file.write((const char*)&sz, sizeof(quint32));
+          if(qty != sizeof(quint32)) {
+            throw QString("Could not write enough data to file (written = %1, expected = %2)").arg(qty).arg(
+                    sizeof(quint32));
+          }
+          qty = file.write(stkdata);
+          if(qty != stkdata.size()) {
+            throw QString("Could not write enough data to file (written = %1, expected = %2)").arg(qty).arg(
+                    stkdata.size());
+          }
+          if(!progress.advance(i))
+            userCancel();
+        }
+        quint64 left_size = datasz - (nb_slices << 26);
+        QByteArray stkdata = qCompress((const uchar*)data.data() + (nb_slices << 26), left_size, compressionLevel);
         quint32 sz = stkdata.size();
-        qty = file.write((const char*)&sz, sizeof(quint32));
+        qint64 qty = file.write((const char*)&sz, sizeof(quint32));
         if(qty != sizeof(quint32)) {
           throw QString("Could not write enough data to file (written = %1, expected = %2)").arg(qty).arg(
                   sizeof(quint32));
@@ -163,1971 +175,1694 @@
         }
         qty = file.write(stkdata);
         if(qty != stkdata.size()) {
-          throw QString("Could not write enough data to file (written = %1, expected = %2)").arg(qty).arg(
+          throw QString("Could not write enough data from MGXS file (written = %1, expected = %2)").arg(qty).arg(
                   stkdata.size());
         }
-        if(!progress.advance(i))
+        if(!progress.advance(nb_slices))
           userCancel();
-      }
-      quint64 left_size = datasz - (nb_slices << 26);
-      QByteArray stkdata = qCompress((const uchar*)data.data() + (nb_slices << 26), left_size, compressionLevel);
-      quint32 sz = stkdata.size();
-      qint64 qty = file.write((const char*)&sz, sizeof(quint32));
-      if(qty != sizeof(quint32)) {
-        throw QString("Could not write enough data to file (written = %1, expected = %2)").arg(qty).arg(
-                sizeof(quint32));
-      }
-      qty = file.write(stkdata);
-      if(qty != stkdata.size()) {
-        throw QString("Could not write enough data from MGXS file (written = %1, expected = %2)").arg(qty).arg(
-                stkdata.size());
-      }
-      if(!progress.advance(nb_slices))
-        userCancel();
-    } else {
-      // Ok, if greater than 64MB, write in bits
-      quint64 nb_slices = datasz >> 26;
-      quint64 slice_size = 1ul << 26;
-      for(quint64 i = 0; i < nb_slices; ++i) {
-        qty = file.write((char*)data.data() + i * slice_size, slice_size);
-        if(quint64(qty) != slice_size) {
-          throw QString("Could not write enough data to file (written = %1, expected = %2)").arg(qty).arg(
-                  slice_size);
+      } else {
+        // Ok, if greater than 64MB, write in bits
+        quint64 nb_slices = datasz >> 26;
+        quint64 slice_size = 1ul << 26;
+        for(quint64 i = 0; i < nb_slices; ++i) {
+          qty = file.write((char*)data.data() + i * slice_size, slice_size);
+          if(quint64(qty) != slice_size) {
+            throw QString("Could not write enough data to file (written = %1, expected = %2)").arg(qty).arg(
+                    slice_size);
+          }
         }
+        quint64 left_size = datasz - (nb_slices << 26);
+        qty = file.write((char*)data.data() + (nb_slices << 26), left_size);
+        if(quint64(qty) != left_size) {
+          throw QString("Could not write enough data from MGXS file (written = %1, expected = %2)").arg(qty).arg(
+                  left_size);
+        }
       }
-      quint64 left_size = datasz - (nb_slices << 26);
-      qty = file.write((char*)data.data() + (nb_slices << 26), left_size);
-      if(quint64(qty) != left_size) {
-        throw QString("Could not write enough data from MGXS file (written = %1, expected = %2)").arg(qty).arg(
-                left_size);
-      }
+      progress.advance(0);
+  
+      file.close();
+    } else if(filename.endsWith(".inr", Qt::CaseInsensitive)) {
+      file.close();
+      Point3u size = stack->size();
+      Point3f step = stack->step();
+      CImgUS image(&data[0], size.x(), size.y(), size.z(), 1, true);
+      image.save_inr(filename.toStdString().data(), step.data());
+    } else if(filename.endsWith(".tif", Qt::CaseInsensitive) or filename.endsWith(".tiff", Qt::CaseInsensitive)) {
+      file.close();
+      Point3u size = stack->size();
+      Point3f step = stack->step();
+      Image3D image(data, size, step, store->labels());
+      saveTIFFImage(filename, image);
+    } else
+      throw QString("Invalid file type %1").arg(filename);
+  
+    store->setFile(util::stripCurrentDir(filename));
+  
+    SETSTATUS("Saved Stack " << store->file() << ", Size: " << stack->size() << " voxel size:" << stack->step());
+    return true;
+  }
+  
+  bool StackSave::initialize(QStringList& parms, QWidget* parent)
+  {
+    int stackId = parms[2].toInt();
+    bool is_work_store = stringToWorkStore(parms[1]);
+    if(!checkState().store((is_work_store ? STORE_WORK : STORE_MAIN), stackId))
+      return false;
+    QString mgxsFilter("MorphoGraphX Stack files (*.mgxs)"), inrFilter("Inria Stack files (*.inr)");
+    QString tiffFilter("TIFF Stack files (*.tif *.tiff)"), filter;
+    Stack* s = stack(stackId);
+    Store* store = (stringToWorkStore(parms[1]) ? s->work() : s->main());
+    QString filename = store->file();
+    if(filename.isEmpty())
+      filename = parms[0];
+    // If we loaded a file before, strip of the ending
+    if(filename.right(4) == ".txt") {
+      filename = filename.left(filename.length() - 4);
+      filename += ".mgxs";
     }
-    progress.advance(0);
-
-    file.close();
-  } else if(filename.endsWith(".inr", Qt::CaseInsensitive)) {
-    file.close();
-    Point3u size = stack->size();
-    Point3f step = stack->step();
-    CImgUS image(&data[0], size.x(), size.y(), size.z(), 1, true);
-    image.save_inr(filename.toStdString().data(), step.data());
-  } else if(filename.endsWith(".tif", Qt::CaseInsensitive) or filename.endsWith(".tiff", Qt::CaseInsensitive)) {
-    file.close();
-    Point3u size = stack->size();
-    Point3f step = stack->step();
-    Image3D image(data, size, step, store->labels());
-    saveTIFFImage(filename, image);
-  } else
-    throw QString("Invalid file type %1").arg(filename);
-
-  store->setFile(util::stripCurrentDir(filename));
-
-  SETSTATUS("Saved Stack " << store->file() << ", Size: " << stack->size() << " voxel size:" << stack->step());
-  return true;
-}
-
-bool StackSave::initialize(QStringList& parms, QWidget* parent)
-{
-  int stackId = parms[2].toInt();
-  bool is_work_store = stringToWorkStore(parms[1]);
-  if(!checkState().store((is_work_store ? STORE_WORK : STORE_MAIN), stackId))
-    return false;
-  QString mgxsFilter("MorphoGraphX Stack files (*.mgxs)"), inrFilter("Inria Stack files (*.inr)");
-  QString tiffFilter("TIFF Stack files (*.tif *.tiff)"), filter;
-  Stack* s = stack(stackId);
-  Store* store = (stringToWorkStore(parms[1]) ? s->work() : s->main());
-  QString filename = store->file();
-  if(filename.isEmpty())
-    filename = parms[0];
-  // If we loaded a file before, strip of the ending
-  if(filename.right(4) == ".txt") {
-    filename = filename.left(filename.length() - 4);
-    filename += ".mgxs";
+  
+    if(filename.endsWith(".inr", Qt::CaseInsensitive))
+      filter = inrFilter;
+    else if(filename.endsWith(".tif", Qt::CaseInsensitive) or filename.endsWith(".tiff", Qt::CaseInsensitive))
+      filter = tiffFilter;
+    else
+      filter = mgxsFilter;
+  
+    // Get the file name
+    filename = QFileDialog::getSaveFileName(parent, QString("Select stack file"), filename,
+                                            QString(mgxsFilter + ";;" + inrFilter + ";;" + tiffFilter), &filter,
+                                            FileDialogOptions);
+    if(filename.isEmpty())
+      return false;
+  
+    // Check ending
+    if(filter == inrFilter and !filename.endsWith(".inr", Qt::CaseInsensitive))
+      filename += ".inr";
+    else if(filter == tiffFilter
+            and !(filename.endsWith(".tif", Qt::CaseInsensitive) or filename.endsWith(".tiff", Qt::CaseInsensitive)))
+      filename += ".tif";
+    else if(filter == mgxsFilter and !filename.endsWith(".mgxs", Qt::CaseInsensitive))
+      filename += ".mgxs";
+  
+    parms[0] = filename;
+    return true;
   }
-
-  if(filename.endsWith(".inr", Qt::CaseInsensitive))
-    filter = inrFilter;
-  else if(filename.endsWith(".tif", Qt::CaseInsensitive) or filename.endsWith(".tiff", Qt::CaseInsensitive))
-    filter = tiffFilter;
-  else
-    filter = mgxsFilter;
-
-  // Get the file name
-  filename = QFileDialog::getSaveFileName(parent, QString("Select stack file"), filename,
-                                          QString(mgxsFilter + ";;" + inrFilter + ";;" + tiffFilter), &filter,
-                                          FileDialogOptions);
-  if(filename.isEmpty())
+  
+  bool StackExport::initialize(QStringList& parms, QWidget* parent)
+  {
+    int stackId = parms[4].toInt();
+    bool is_work_store = stringToWorkStore(parms[1]);
+    if(!checkState().store((is_work_store ? STORE_WORK : STORE_MAIN), stackId))
+      return false;
+    Stack* s = stack(stackId);
+    Store* store = (stringToWorkStore(parms[1]) ? s->work() : s->main());
+    QString filename = store->file();
+  
+    QDialog dlg(parent);
+    Ui_ExportStackDialog ui;
+    ui.setupUi(&dlg);
+    this->dlg = &dlg;
+    this->ui = &ui;
+  
+    connect(ui.SelectImageFile, SIGNAL(clicked()), this, SLOT(selectImageFile()));
+    connect(ui.ImageType, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(setImageType(const QString &)));
+  
+    QStringList suppTypes = supportedImageWriteFormats();
+    QStringList types;
+    foreach(QString f, suppTypes) {
+      types << f;
+    }
+  
+    ui.ImageType->addItems(types);
+    ui.generateVoxelSpacing->setChecked(stringToBool(parms[3]));
+  
+    if(dlg.exec() == QDialog::Accepted) {
+      parms[2] = suppTypes[ui.ImageType->currentIndex()];
+      parms[0] = ui.ImageFile->text();
+      parms[3] = (ui.generateVoxelSpacing->isChecked() ? "Yes" : "No");
+      parms[5] = QString::number(ui.nbDigits->value());
+      return true;
+    }
     return false;
-
-  // Check ending
-  if(filter == inrFilter and !filename.endsWith(".inr", Qt::CaseInsensitive))
-    filename += ".inr";
-  else if(filter == tiffFilter
-          and !(filename.endsWith(".tif", Qt::CaseInsensitive) or filename.endsWith(".tiff", Qt::CaseInsensitive)))
-    filename += ".tif";
-  else if(filter == mgxsFilter and !filename.endsWith(".mgxs", Qt::CaseInsensitive))
-    filename += ".mgxs";
-
-  parms[0] = filename;
-  return true;
-}
-
-// REGISTER_STACK_PROCESS(StackSave);
-
-bool StackExport::initialize(QStringList& parms, QWidget* parent)
-{
-  int stackId = parms[4].toInt();
-  bool is_work_store = stringToWorkStore(parms[1]);
-  if(!checkState().store((is_work_store ? STORE_WORK : STORE_MAIN), stackId))
-    return false;
-  Stack* s = stack(stackId);
-  Store* store = (stringToWorkStore(parms[1]) ? s->work() : s->main());
-  QString filename = store->file();
-
-  QDialog dlg(parent);
-  Ui_ExportStackDialog ui;
-  ui.setupUi(&dlg);
-  this->dlg = &dlg;
-  this->ui = &ui;
-
-  connect(ui.SelectImageFile, SIGNAL(clicked()), this, SLOT(selectImageFile()));
-  connect(ui.ImageType, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(setImageType(const QString &)));
-
-  QStringList suppTypes = supportedImageWriteFormats();
-  QStringList types;
-  foreach(QString f, suppTypes) {
-    types << f;
   }
-
-  ui.ImageType->addItems(types);
-  ui.generateVoxelSpacing->setChecked(stringToBool(parms[3]));
-
-  if(dlg.exec() == QDialog::Accepted) {
-    parms[2] = suppTypes[ui.ImageType->currentIndex()];
-    parms[0] = ui.ImageFile->text();
-    parms[3] = (ui.generateVoxelSpacing->isChecked() ? "Yes" : "No");
-    parms[5] = QString::number(ui.nbDigits->value());
-    return true;
-  }
-  return false;
-}
-
-void StackExport::selectImageFile()
-{
-  QStringList filter;
-  foreach(QString f, supportedImageWriteFormats()) {
-    if(f != "CImg Auto")
-      filter << QString("%1 images (*.%2 *.%1)").arg(f.toUpper()).arg(f.toLower());
-    else
-      filter << "CImg Auto (*.*)";
-  }
-  QString filename = ui->ImageFile->text();
-  QString selected;
-  filename = QFileDialog::getSaveFileName(dlg, "Filename to export to", filename, filter.join(";;"), &selected);
-  if(!filename.isEmpty()) {
-    int idx = filter.indexOf(selected);
-    ui->ImageType->setCurrentIndex(idx);
-    if(!selected.startsWith("CImg Auto")) {
-      QString type = selected.left(selected.indexOf(" ")).toLower();
-      if(!filename.endsWith("." + type, Qt::CaseInsensitive)) {
-        filename += "." + type;
+  
+  void StackExport::selectImageFile()
+  {
+    QStringList filter;
+    foreach(QString f, supportedImageWriteFormats()) {
+      if(f != "CImg Auto")
+        filter << QString("%1 images (*.%2 *.%1)").arg(f.toUpper()).arg(f.toLower());
+      else
+        filter << "CImg Auto (*.*)";
+    }
+    QString filename = ui->ImageFile->text();
+    QString selected;
+    filename = QFileDialog::getSaveFileName(dlg, "Filename to export to", filename, filter.join(";;"), &selected);
+    if(!filename.isEmpty()) {
+      int idx = filter.indexOf(selected);
+      ui->ImageType->setCurrentIndex(idx);
+      if(!selected.startsWith("CImg Auto")) {
+        QString type = selected.left(selected.indexOf(" ")).toLower();
+        if(!filename.endsWith("." + type, Qt::CaseInsensitive)) {
+          filename += "." + type;
+        }
       }
+      ui->ImageFile->setText(filename);
     }
-    ui->ImageFile->setText(filename);
   }
-}
-
-void StackExport::setImageType(const QString& type)
-{
-  if(!type.startsWith("CImg Auto")) {
-    QString t = type.toLower();
-    QString fn = ui->ImageFile->text();
-    int idx = fn.lastIndexOf(".");
-    if(idx != -1)
-      fn = fn.left(idx + 1) + t;
-    else
-      fn += "." + t;
-    ui->ImageFile->setText(fn);
+  
+  void StackExport::setImageType(const QString& type)
+  {
+    if(!type.startsWith("CImg Auto")) {
+      QString t = type.toLower();
+      QString fn = ui->ImageFile->text();
+      int idx = fn.lastIndexOf(".");
+      if(idx != -1)
+        fn = fn.left(idx + 1) + t;
+      else
+        fn += "." + t;
+      ui->ImageFile->setText(fn);
+    }
   }
-}
-
-bool StackExport::operator()(const QStringList& parms)
-{
-  int stackId = parms[4].toInt();
-  bool is_work_store = stringToWorkStore(parms[1]);
-  if(!checkState().store((is_work_store ? STORE_WORK : STORE_MAIN), stackId))
-    return false;
-  Stack* s = stack(stackId);
-  Store* store = (stringToWorkStore(parms[1]) ? s->work() : s->main());
-  QString filename = parms[0];
-  QString type = parms[2];
-  uint nb_digits = parms[5].toUInt();
-  if(filename.isEmpty()) {
-    setErrorMessage("Error, filename provided is empty");
-    return false;
+  
+  bool StackExport::operator()(const QStringList& parms)
+  {
+    int stackId = parms[4].toInt();
+    bool is_work_store = stringToWorkStore(parms[1]);
+    if(!checkState().store((is_work_store ? STORE_WORK : STORE_MAIN), stackId))
+      return false;
+    Stack* s = stack(stackId);
+    Store* store = (stringToWorkStore(parms[1]) ? s->work() : s->main());
+    QString filename = parms[0];
+    QString type = parms[2];
+    uint nb_digits = parms[5].toUInt();
+    if(filename.isEmpty()) {
+      setErrorMessage("Error, filename provided is empty");
+      return false;
+    }
+    if(type.isEmpty()) {
+      setErrorMessage("Error, type provided is empty");
+      return false;
+    }
+    if(nb_digits > 500) {
+      setErrorMessage("Error, the number of digits asked for is greater than 500. It seems unreasonnably high.");
+      return false;
+    }
+    return (*this)(s, store, filename, type, nb_digits, stringToBool(parms[3]));
   }
-  if(type.isEmpty()) {
-    setErrorMessage("Error, type provided is empty");
-    return false;
+  
+  bool StackExport::operator()(Stack* stack, Store* store, const QString& filename, const QString& type,
+                               unsigned int nb_digits, bool generate_voxel_spacing)
+  {
+    actingFile(filename);
+    Point3u size = stack->size();
+    Point3f step = stack->step();
+    Image3D image(store->data(), size, step);
+    saveImage(filename, image, type, nb_digits);
+    if(generate_voxel_spacing) {
+      QFileInfo fi(filename);
+      QDir d = fi.dir();
+      QFile file(d.filePath("voxelspacing.txt"));
+      if(!file.open(QIODevice::WriteOnly)) {
+        setErrorMessage(QString("Error, cannot open file '%1' for writing.").arg(file.fileName()));
+        return false;
+      }
+      QTextStream ss(&file);
+      ss << "x " << stack->step().x() << endl << "y " << stack->step().y() << endl << "z " << stack->step().z()
+         << endl;
+      file.close();
+    }
+    return true;
   }
-  if(nb_digits > 500) {
-    setErrorMessage("Error, the number of digits asked for is greater than 500. It seems unreasonnably high.");
-    return false;
+  
+  QString MeshExport::properFile(QString filename, const QString& type) const
+  {
+    QFileInfo fi(filename);
+    QString suf = fi.suffix();
+    if(!suf.isEmpty())
+      filename = filename.left(filename.size() - suf.size() - 1);
+    if(type == "Text" or type == "Cells")
+      filename += ".txt";
+    else if(type == "MeshEdit")
+      filename += ".mesh";
+    else if(type == "STL")
+      filename += ".stl";
+    else if(type.startsWith("VTK Mesh"))
+      filename += ".vtu";
+    else if(type == "OBJ")
+      filename += ".obj";
+    else if(type.startsWith("PLY"))
+      filename += ".ply";
+    return filename;
   }
-  return (*this)(s, store, filename, type, nb_digits, stringToBool(parms[3]));
-}
-
-bool StackExport::operator()(Stack* stack, Store* store, const QString& filename, const QString& type,
-                             unsigned int nb_digits, bool generate_voxel_spacing)
-{
-  actingFile(filename);
-  Point3u size = stack->size();
-  Point3f step = stack->step();
-  Image3D image(store->data(), size, step);
-  saveImage(filename, image, type, nb_digits);
-  if(generate_voxel_spacing) {
-    QFileInfo fi(filename);
-    QDir d = fi.dir();
-    QFile file(d.filePath("voxelspacing.txt"));
-    if(!file.open(QIODevice::WriteOnly)) {
-      setErrorMessage(QString("Error, cannot open file '%1' for writing.").arg(file.fileName()));
+  
+  bool MeshExport::initialize(QStringList& parms, QWidget* parent)
+  {
+    int stackId = parms[3].toInt();
+    if(!checkState().mesh(MESH_ANY, stackId))
       return false;
+  
+    QDialog dlg(parent);
+    Ui_ExportMeshDialog ui;
+    ui.setupUi(&dlg);
+  
+    this->ui = &ui;
+    this->dlg = &dlg;
+  
+    connect(ui.SelectMeshFile, SIGNAL(clicked()), this, SLOT(selectMeshFile()));
+    connect(ui.MeshType, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(selectMeshType(const QString &)));
+  
+    Mesh* m = mesh(stackId);
+    QString filename = m->file();
+    if(filename.isEmpty())
+      filename = parms[0];
+  
+    setMeshFile(filename);
+    ui.Transform->setChecked(stringToBool(parms[2]));
+  
+    bool res = false;
+    if(dlg.exec() == QDialog::Accepted) {
+      parms[1] = ui.MeshType->currentText();
+      parms[0] = ui.MeshFile->text(), parms[1];
+      parms[2] = boolToString(ui.Transform->isChecked());
+      res = true;
     }
-    QTextStream ss(&file);
-    ss << "x " << stack->step().x() << endl << "y " << stack->step().y() << endl << "z " << stack->step().z()
-       << endl;
-    file.close();
+    this->ui = 0;
+    this->dlg = 0;
+    return res;
   }
-  return true;
-}
-
-QString MeshExport::properFile(QString filename, const QString& type) const
-{
-  QFileInfo fi(filename);
-  QString suf = fi.suffix();
-  if(!suf.isEmpty())
-    filename = filename.left(filename.size() - suf.size() - 1);
-  if(type == "Text" or type == "Cells")
-    filename += ".txt";
-  else if(type == "MeshEdit")
-    filename += ".mesh";
-  else if(type == "STL")
-    filename += ".stl";
-  else if(type.startsWith("VTK Mesh"))
-    filename += ".vtu";
-  else if(type == "OBJ")
-    filename += ".obj";
-  else if(type.startsWith("PLY"))
-    filename += ".ply";
-  return filename;
-}
-
-// REGISTER_STACK_PROCESS(StackExport);
-
-bool MeshExport::initialize(QStringList& parms, QWidget* parent)
-{
-  int stackId = parms[3].toInt();
-  if(!checkState().mesh(MESH_ANY, stackId))
-    return false;
-
-  QDialog dlg(parent);
-  Ui_ExportMeshDialog ui;
-  ui.setupUi(&dlg);
-
-  this->ui = &ui;
-  this->dlg = &dlg;
-
-  connect(ui.SelectMeshFile, SIGNAL(clicked()), this, SLOT(selectMeshFile()));
-  connect(ui.MeshType, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(selectMeshType(const QString &)));
-
-  Mesh* m = mesh(stackId);
-  QString filename = m->file();
-  if(filename.isEmpty())
-    filename = parms[0];
-
-  setMeshFile(filename);
-  ui.Transform->setChecked(stringToBool(parms[2]));
-
-  bool res = false;
-  if(dlg.exec() == QDialog::Accepted) {
-    parms[1] = ui.MeshType->currentText();
-    parms[0] = ui.MeshFile->text(), parms[1];
-    parms[2] = boolToString(ui.Transform->isChecked());
-    res = true;
+  
+  void MeshExport::selectMeshType(const QString& type)
+  {
+    QString filename = ui->MeshFile->text();
+    if(filename.isEmpty())
+      return;
+    ui->MeshFile->setText(properFile(filename, type));
   }
-  this->ui = 0;
-  this->dlg = 0;
-  return res;
-}
-
-void MeshExport::selectMeshType(const QString& type)
-{
-  QString filename = ui->MeshFile->text();
-  if(filename.isEmpty())
-    return;
-  ui->MeshFile->setText(properFile(filename, type));
-}
-
-void MeshExport::selectMeshFile()
-{
-  QString filename = ui->MeshFile->text();
-  QStringList filters;
-  filters << "Stanford Polygon file (*.ply)"
-          << "VTK Mesh File (*.vtu)"
-          << "Text or cell files (*.txt)"
-          << "MeshEdit files (*.mesh)"
-          << "STL CAD files (*.stl)"
-          << "Wavefront Object files (*.obj)"
-          << "All Mesh Files (*.ply *.vtu *.txt *.mesh *.stl *.obj)";
-  QString filter;
+  
+  void MeshExport::selectMeshFile()
   {
+    QString filename = ui->MeshFile->text();
+    QStringList filters;
+    filters << "Stanford Polygon file (*.ply)"
+            << "VTK Mesh File (*.vtu)"
+            << "Text or cell files (*.txt)"
+            << "MeshEdit files (*.mesh)"
+            << "STL CAD files (*.stl)"
+            << "Wavefront Object files (*.obj)"
+            << "All Mesh Files (*.ply *.vtu *.txt *.mesh *.stl *.obj)";
+    QString filter;
+    {
+      QFileInfo fi(filename);
+      QString suf = fi.suffix();
+      if(suf == "ply")
+        filter = filters[0];
+      else if(suf == "vtu")
+        filter = filters[1];
+      else if(suf == "txt")
+        filter = filters[2];
+      else if(suf == "mesh")
+        filter = filters[3];
+      else if(suf == "stl")
+        filter = filters[4];
+      else if(suf == "obj")
+        filter = filters[5];
+      else
+        filter = filters[6];
+    }
+    filename = QFileDialog::getSaveFileName(dlg, QString("Select mesh file"), filename, filters.join(";;"), &filter,
+                                            FileDialogOptions);
+    if(!filename.isEmpty())
+      setMeshFile(filename);
+  }
+  
+  void MeshExport::setMeshFile(const QString& filename)
+  {
     QFileInfo fi(filename);
     QString suf = fi.suffix();
+    // This is nasty, if you add/change anything here you'll have to change the exportmesh.ui file
     if(suf == "ply")
-      filter = filters[0];
+      ui->MeshType->setCurrentIndex(0);
     else if(suf == "vtu")
-      filter = filters[1];
+      ui->MeshType->setCurrentIndex(2);
     else if(suf == "txt")
-      filter = filters[2];
+      ui->MeshType->setCurrentIndex(4);
     else if(suf == "mesh")
-      filter = filters[3];
+      ui->MeshType->setCurrentIndex(6);
     else if(suf == "stl")
-      filter = filters[4];
+      ui->MeshType->setCurrentIndex(7);
     else if(suf == "obj")
-      filter = filters[5];
-    else
-      filter = filters[6];
+      ui->MeshType->setCurrentIndex(8);
+    else {
+      ui->MeshType->setCurrentIndex(0);
+      ui->MeshFile->setText(properFile(filename, "PLY Binary"));
+      return;
+    }
+    ui->MeshFile->setText(filename);
   }
-  filename = QFileDialog::getSaveFileName(dlg, QString("Select mesh file"), filename, filters.join(";;"), &filter,
-                                          FileDialogOptions);
-  if(!filename.isEmpty())
-    setMeshFile(filename);
-}
-
-void MeshExport::setMeshFile(const QString& filename)
-{
-  QFileInfo fi(filename);
-  QString suf = fi.suffix();
-  // This is nasty, if you add/change anything here you'll have to change the exportmesh.ui file
-  if(suf == "ply")
-    ui->MeshType->setCurrentIndex(0);
-  else if(suf == "vtu")
-    ui->MeshType->setCurrentIndex(2);
-  else if(suf == "txt")
-    ui->MeshType->setCurrentIndex(4);
-  else if(suf == "mesh")
-    ui->MeshType->setCurrentIndex(6);
-  else if(suf == "stl")
-    ui->MeshType->setCurrentIndex(7);
-  else if(suf == "obj")
-    ui->MeshType->setCurrentIndex(8);
-  else {
-    ui->MeshType->setCurrentIndex(0);
-    ui->MeshFile->setText(properFile(filename, "PLY Binary"));
-    return;
+  
+  bool MeshExport::operator()(const QStringList& parms)
+  {
+    int meshId = parms[3].toInt();
+    if(!checkState().mesh(STACK_ANY, meshId))
+      return false;
+    Mesh* mesh = this->mesh(meshId);
+    QString type = parms[1];
+    if(parms[1] != "PLY Binary" and parms[1] != "PLY Ascii" and parms[1] != "VTK Mesh Binary"
+       and parms[1] != "VTK Mesh Ascii" and parms[1] != "Text" and parms[1] != "Cells" and parms[1] != "MeshEdit"
+       and parms[1] != "STL" and parms[1] != "OBJ") {
+      setErrorMessage("Error, type must be one of 'PLY Binary', 'PLY Ascii',"
+                      " 'VTK Mesh Binary', 'VTK Mesh Ascii', 'Text', 'Cells', 'MeshEdit', 'STL', 'OBJ'.");
+      return false;
+    }
+    bool transform = stringToBool(parms[2]);
+    bool res = (*this)(mesh, parms[0], type, transform);
+    return res;
   }
-  ui->MeshFile->setText(filename);
-}
-
-bool MeshExport::operator()(const QStringList& parms)
-{
-  int meshId = parms[3].toInt();
-  if(!checkState().mesh(STACK_ANY, meshId))
-    return false;
-  Mesh* mesh = this->mesh(meshId);
-  QString type = parms[1];
-  if(parms[1] != "PLY Binary" and parms[1] != "PLY Ascii" and parms[1] != "VTK Mesh Binary"
-     and parms[1] != "VTK Mesh Ascii" and parms[1] != "Text" and parms[1] != "Cells" and parms[1] != "MeshEdit"
-     and parms[1] != "STL" and parms[1] != "OBJ") {
-    setErrorMessage("Error, type must be one of 'PLY Binary', 'PLY Ascii',"
-                    " 'VTK Mesh Binary', 'VTK Mesh Ascii', 'Text', 'Cells', 'MeshEdit', 'STL', 'OBJ'.");
-    return false;
+  
+  bool MeshExport::operator()(Mesh* mesh, const QString& filename, const QString& type, bool transform)
+  {
+    if(filename.isEmpty()) {
+      setErrorMessage("Filename is empty, cannot save mesh");
+      return false;
+    }
+    actingFile(filename);
+    Progress progress(QString("Saving Mesh %1 in File '%2'").arg(mesh->userId()).arg(filename), 0, false);
+    QFileInfo fi(filename);
+    QString suf = fi.suffix();
+    bool success = false;
+    if(type == "PLY Binary")
+      success = savePLY(mesh, filename, transform, true);
+    else if(type == "PLY Ascii")
+      success = savePLY(mesh, filename, transform, false);
+    if(type == "VTK Mesh Binary")
+      success = saveVTU(mesh, filename, transform, true);
+    else if(type == "VTK Mesh Ascii")
+      success = saveVTU(mesh, filename, transform, false);
+    else if(type == "Text")
+      success = saveText(mesh, filename, transform);
+    else if(type == "Cells")
+      success = saveCells(mesh, filename, transform);
+    else if(type == "MeshEdit")
+      success = saveMeshEdit(mesh, filename, transform);
+    else if(type == "STL")
+      success = saveMeshSTL(mesh, filename, transform);
+    else if(type == "OBJ")
+      success = saveOBJ(mesh, filename, transform);
+    if(success) {
+      mesh->setTransformed(transform);
+      mesh->updateAll();
+    }
+    return success;
   }
-  bool transform = stringToBool(parms[2]);
-  bool res = (*this)(mesh, parms[0], type, transform);
-  return res;
-}
-
-bool MeshExport::operator()(Mesh* mesh, const QString& filename, const QString& type, bool transform)
-{
-  if(filename.isEmpty()) {
-    setErrorMessage("Filename is empty, cannot save mesh");
-    return false;
+  
+  Point3f MeshExport::savedPos(Point3f pos, bool transform, const Stack* stack)
+  {
+    if(transform)
+      pos = Point3f(stack->getFrame().inverseCoordinatesOf(Vec(pos)));
+    return pos;
   }
-  actingFile(filename);
-  Progress progress(QString("Saving Mesh %1 in File '%2'").arg(mesh->userId()).arg(filename), 0, false);
-  QFileInfo fi(filename);
-  QString suf = fi.suffix();
-  bool success = false;
-  if(type == "PLY Binary")
-    success = savePLY(mesh, filename, transform, true);
-  else if(type == "PLY Ascii")
-    success = savePLY(mesh, filename, transform, false);
-  if(type == "VTK Mesh Binary")
-    success = saveVTU(mesh, filename, transform, true);
-  else if(type == "VTK Mesh Ascii")
-    success = saveVTU(mesh, filename, transform, false);
-  else if(type == "Text")
-    success = saveText(mesh, filename, transform);
-  else if(type == "Cells")
-    success = saveCells(mesh, filename, transform);
-  else if(type == "MeshEdit")
-    success = saveMeshEdit(mesh, filename, transform);
-  else if(type == "STL")
-    success = saveMeshSTL(mesh, filename, transform);
-  else if(type == "OBJ")
-    success = saveOBJ(mesh, filename, transform);
-  if(success) {
-    mesh->setTransformed(transform);
-    mesh->updateAll();
+  
+  static QString vtkBinaryEncoding(const char* data, int size)
+  {
+    QByteArray ba = (QByteArray::fromRawData((const char*)&size, 4) + QByteArray::fromRawData(data, size)).toBase64();
+    return QString::fromAscii(ba);
   }
-  return success;
-}
-
-Point3f MeshExport::savedPos(Point3f pos, bool transform, const Stack* stack)
-{
-  if(transform)
-    pos = Point3f(stack->getFrame().inverseCoordinatesOf(Vec(pos)));
-  return pos;
-}
-
-static QString vtkBinaryEncoding(const char* data, int size)
-{
-  QByteArray ba = (QByteArray::fromRawData((const char*)&size, 4) + QByteArray::fromRawData(data, size)).toBase64();
-  return QString::fromAscii(ba);
-}
-
-template <typename T> static QDomText vtkBinaryEncoding(const std::vector<T>& data, QDomDocument& doc)
-{
-  QDomText text = doc.createTextNode(vtkBinaryEncoding((const char*)&data[0], data.size() * sizeof(T)));
-  return text;
-}
-
-QString vtkAsciiEncoding(const int& i) {
-  return QString::number(i);
-}
-
-QString vtkAsciiEncoding(const float& f) {
-  return QString::number(f, 'g', 10);
-}
-
-QString vtkAsciiEncoding(const Point3f& p)
-{
-  return QString("%1 %2 %3").arg(p.x(), 0, 'g', 10).arg(p.y(), 0, 'g', 10).arg(p.z(), 0, 'g', 10);
-}
-
-QString vtkAsciiEncoding(const Point2i& p) {
-  return QString("%1 %2").arg(p.x()).arg(p.y());
-}
-
-QString vtkAsciiEncoding(const Point3i& p) {
-  return QString("%1 %2 %3").arg(p.x()).arg(p.y()).arg(p.z());
-}
-
-template <typename T> static QDomText vtkAsciiEncoding(const std::vector<T>& values, QDomDocument& doc)
-{
-  QStringList strings;
-#if QT_VERSION >= 0x040700
-  strings.reserve(values.size());
-#endif
-  forall(const T& v, values)
-    strings << vtkAsciiEncoding(v);
-  return doc.createTextNode(strings.join("\n"));
-}
-
-template <typename T> static QDomText vtkEncoding(const std::vector<T>& values, QDomDocument& doc, bool binary)
-{
-  if(binary)
-    return vtkBinaryEncoding(values, doc);
-  else
-    return vtkAsciiEncoding(values, doc);
-}
-
-bool MeshExport::saveOBJ(Mesh* mesh, const QString& filename, bool transform)
-{
-  QFile file(filename);
-  if(!file.open(QIODevice::WriteOnly)) {
-    setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
-    return false;
+  
+  template <typename T> static QDomText vtkBinaryEncoding(const std::vector<T>& data, QDomDocument& doc)
+  {
+    QDomText text = doc.createTextNode(vtkBinaryEncoding((const char*)&data[0], data.size() * sizeof(T)));
+    return text;
   }
-
-  QTextStream ts(&file);
-
-  const vvgraph& S = mesh->graph();
-
-  std::unordered_map<vertex, int> inv_vs;
-
-  ts << "# Triangular mesh created by MorphoGraphX" << endl;
-  ts << QString::fromWCharArray(L"# Length unit: \xb5m") << endl << endl;
-
-  ts << "# Vertices" << endl;
-
-  // write vertices
-  int i = 0;
-  forall(const vertex& v, S) {
-    inv_vs[v] = i + 1;
-    ts << "v " << savedPos(v->pos, transform, mesh->stack()) << endl;
-    ts << "vn " << normalized(savedPos(v->nrml, transform, mesh->stack())) << endl;
-    ++i;
+  
+  QString vtkAsciiEncoding(const int& i) {
+    return QString::number(i);
   }
-
-  ts << endl << "# Triangles" << endl;
-
-  // write triangles
-  forall(const vertex& v, S) {
-    forall(const vertex& n, S.neighbors(v)) {
-      const vertex& m = S.nextTo(v, n);
-      if(mesh->uniqueTri(v, n, m)) {
-        ts << "f " << inv_vs[v] << " " << inv_vs[n] << " " << inv_vs[m] << endl;
+  
+  QString vtkAsciiEncoding(const float& f) {
+    return QString::number(f, 'g', 10);
+  }
+  
+  QString vtkAsciiEncoding(const Point3f& p)
+  {
+    return QString("%1 %2 %3").arg(p.x(), 0, 'g', 10).arg(p.y(), 0, 'g', 10).arg(p.z(), 0, 'g', 10);
+  }
+  
+  QString vtkAsciiEncoding(const Point2i& p) {
+    return QString("%1 %2").arg(p.x()).arg(p.y());
+  }
+  
+  QString vtkAsciiEncoding(const Point3i& p) {
+    return QString("%1 %2 %3").arg(p.x()).arg(p.y()).arg(p.z());
+  }
+  
+  template <typename T> static QDomText vtkAsciiEncoding(const std::vector<T>& values, QDomDocument& doc)
+  {
+    QStringList strings;
+  #if QT_VERSION >= 0x040700
+    strings.reserve(values.size());
+  #endif
+    forall(const T& v, values)
+      strings << vtkAsciiEncoding(v);
+    return doc.createTextNode(strings.join("\n"));
+  }
+  
+  template <typename T> static QDomText vtkEncoding(const std::vector<T>& values, QDomDocument& doc, bool binary)
+  {
+    if(binary)
+      return vtkBinaryEncoding(values, doc);
+    else
+      return vtkAsciiEncoding(values, doc);
+  }
+  
+  bool MeshExport::saveOBJ(Mesh* mesh, const QString& filename, bool transform)
+  {
+    QFile file(filename);
+    if(!file.open(QIODevice::WriteOnly)) {
+      setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
+      return false;
+    }
+  
+    QTextStream ts(&file);
+  
+    const vvgraph& S = mesh->graph();
+  
+    std::unordered_map<vertex, int> inv_vs;
+  
+    ts << "# Triangular mesh created by MorphoGraphX" << endl;
+    ts << QString::fromWCharArray(L"# Length unit: \xb5m") << endl << endl;
+  
+    ts << "# Vertices" << endl;
+  
+    // write vertices
+    int i = 0;
+    forall(const vertex& v, S) {
+      inv_vs[v] = i + 1;
+      ts << "v " << savedPos(v->pos, transform, mesh->stack()) << endl;
+      ts << "vn " << normalized(savedPos(v->nrml, transform, mesh->stack())) << endl;
+      ++i;
+    }
+  
+    ts << endl << "# Triangles" << endl;
+  
+    // write triangles
+    forall(const vertex& v, S) {
+      forall(const vertex& n, S.neighbors(v)) {
+        const vertex& m = S.nextTo(v, n);
+        if(mesh->uniqueTri(v, n, m)) {
+          ts << "f " << inv_vs[v] << " " << inv_vs[n] << " " << inv_vs[m] << endl;
+        }
       }
     }
+  
+    file.close();
+    return true;
   }
-
-  file.close();
-  return true;
-}
-
-bool MeshExport::saveVTU(Mesh* mesh, const QString& filename, bool transform, bool binary)
-{
-  QFile file(filename);
-  if(!file.open(QIODevice::WriteOnly)) {
-    setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
-    return false;
-  }
-
-  QDomDocument doc("VTKFile");
-  QDomElement root = doc.createElement("VTKFile");
-  root.setAttribute("type", "UnstructuredGrid");
-  root.setAttribute("byte_order", "LittleEndian");
-  root.setAttribute("version", "0.1");
-  doc.appendChild(root);
-  // Add the grid
-  QDomElement grid = doc.createElement("UnstructuredGrid");
-  root.appendChild(grid);
-  // Add the pieces
-  QDomElement piece = doc.createElement("Piece");
-  grid.appendChild(piece);
-  const vvgraph& S = mesh->graph();
-  piece.setAttribute("NumberOfPoints", (uint)S.size());
-  QString format;
-  if(binary)
-    format = "binary";
-  else
-    format = "ascii";
-  // Points
-  QDomElement points = doc.createElement("Points");
-  piece.appendChild(points);
-  QDomElement points_pos = doc.createElement("DataArray");
-  points_pos.setAttribute("NumberOfComponents", "3");
-  points_pos.setAttribute("type", "Float32");
-  points_pos.setAttribute("format", format);
-  std::vector<Point3f> points_pos_data(S.size());
-  points.appendChild(points_pos);
-  // Points attributes
-  QDomElement points_data = doc.createElement("PointData");
-  piece.appendChild(points_data);
-  QString signal_name;
-  if(mesh->signalUnit().isEmpty())
-    signal_name = "Signal";
-  else
-    signal_name = QString("Signal (%1)").arg(mesh->signalUnit());
-  points_data.setAttribute("Scalars", signal_name);
-  points_data.setAttribute("Normals", "Normals");
-  QDomElement points_signal = doc.createElement("DataArray");
-  points_signal.setAttribute("Name", signal_name);
-  points_signal.setAttribute("type", "Float32");
-  points_signal.setAttribute("NumberOfComponents", "1");
-  points_signal.setAttribute("format", format);
-  std::vector<float> points_signal_data(S.size());
-  QDomElement points_normal = doc.createElement("DataArray");
-  points_normal.setAttribute("Name", "Normals");
-  points_normal.setAttribute("type", "Float32");
-  points_normal.setAttribute("NumberOfComponents", "3");
-  points_normal.setAttribute("format", format);
-  std::vector<Point3f> points_normal_data(S.size());
-  QDomElement points_label = doc.createElement("DataArray");
-  points_label.setAttribute("Name", "Label");
-  points_label.setAttribute("type", "Int32");
-  points_label.setAttribute("NumberOfComponents", "1");
-  points_label.setAttribute("format", format);
-  std::vector<int> points_label_data(S.size());
-  points_data.appendChild(points_signal);
-  points_data.appendChild(points_normal);
-  points_data.appendChild(points_label);
-  // Initialize vertex number and counts cells
-  int saveId = 0;
-  size_t count_cells = 0;
-  forall(const vertex& v, S) {
-    v->saveId = saveId++;
-    forall(const vertex& n, S.neighbors(v)) {
-      const vertex& m = S.nextTo(v, n);
-      if(mesh->uniqueTri(v, n, m))
-        ++count_cells;
+  
+  bool MeshExport::saveVTU(Mesh* mesh, const QString& filename, bool transform, bool binary)
+  {
+    QFile file(filename);
+    if(!file.open(QIODevice::WriteOnly)) {
+      setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
+      return false;
     }
-  }
-  // Cells
-  piece.setAttribute("NumberOfCells", (uint)count_cells);
-  QDomElement cells = doc.createElement("Cells");
-  piece.appendChild(cells);
-  QDomElement cells_connectivity = doc.createElement("DataArray");
-  cells_connectivity.setAttribute("type", "Int32");
-  cells_connectivity.setAttribute("Name", "connectivity");
-  cells_connectivity.setAttribute("format", format);
-  std::vector<Point3i> cells_connectivity_data(count_cells);
-  QDomElement cells_offsets = doc.createElement("DataArray");
-  cells_offsets.setAttribute("type", "Int32");
-  cells_offsets.setAttribute("Name", "offsets");
-  cells_offsets.setAttribute("format", format);
-  std::vector<int> cells_offsets_data(count_cells);
-  QDomElement cells_types = doc.createElement("DataArray");
-  cells_types.setAttribute("type", "UInt8");
-  cells_types.setAttribute("Name", "types");
-  cells_types.setAttribute("format", format);
-  std::vector<quint8> cells_types_data(count_cells, quint8(5));
-  cells.appendChild(cells_connectivity);
-  cells.appendChild(cells_offsets);
-  cells.appendChild(cells_types);
-  // Cells attributes
-  QDomElement cells_data = doc.createElement("CellData");
-  piece.appendChild(cells_data);
-  QDomElement cells_label = doc.createElement("DataArray");
-  cells_label.setAttribute("Name", "Label");
-  cells_label.setAttribute("type", "Int32");
-  cells_label.setAttribute("NumberOfComponents", "1");
-  cells_label.setAttribute("format", format);
-  cells_data.appendChild(cells_label);
-  std::vector<int> cells_label_data(count_cells);
-  QDomElement cells_heat = doc.createElement("DataArray");
-  const IntFloatMap& mesh_cell_heat = mesh->labelHeat();
-  const IntIntFloatMap& mesh_wall_heat = mesh->wallHeat();
-  bool has_cell_heat = !mesh_cell_heat.empty();
-  bool has_wall_heat = !mesh_wall_heat.empty();
-  QString heat_name = "Heat";
-  if(has_cell_heat)
-    heat_name = "Cell " + heat_name;
-  else if(has_wall_heat)
-    heat_name = "Wall " + heat_name;
-  if(!mesh->heatMapUnit().isEmpty())
-    heat_name += QString(" (%1)").arg(mesh->heatMapUnit());
-
-  float minHeat = mesh->heatMapBounds()[0];
-  float maxHeat = mesh->heatMapBounds()[1];
-
-  cells_heat.setAttribute("Name", heat_name);
-  cells_heat.setAttribute("type", "Float32");
-  cells_heat.setAttribute("NumberOfComponents", "1");
-  cells_heat.setAttribute("format", format);
-  cells_heat.setAttribute("RangeMin", minHeat);
-  cells_heat.setAttribute("RangeMax", maxHeat);
-  std::vector<float> cells_heat_data;
-  if(has_cell_heat or has_wall_heat) {
-    cells_heat_data.resize(count_cells);
-    cells_data.appendChild(cells_heat);
-    cells_data.setAttribute("Scalars", heat_name);
-  } else
-    cells_data.setAttribute("Scalars", "Label");
-
-  std::unordered_set<int> labels;
-
-  // Fills in everything
-  int cell_id = 0;
-  forall(const vertex& v, S) {
-    int id = v->saveId;
-    Point3f pos = savedPos(v->pos, transform, mesh->stack());
-    Point3f nrml = normalized(savedPos(v->nrml, transform, mesh->stack()));
-    points_pos_data[id] = pos;
-    points_label_data[id] = v->label;
-    points_signal_data[id] = v->signal;
-    points_normal_data[id] = nrml;
-    forall(const vertex& n, S.neighbors(v)) {
-      const vertex& m = S.nextTo(v, n);
-      if(mesh->uniqueTri(v, n, m)) {
-        cells_connectivity_data[cell_id] = Point3i(id, n->saveId, m->saveId);
-        cells_offsets_data[cell_id] = 3 * (cell_id + 1);
-        int label = mesh->getLabel(v, n, m);
-        labels.insert(label);
-        cells_label_data[cell_id] = label;
-        if(has_cell_heat) {
-          IntFloatMap::const_iterator found = mesh_cell_heat.find(label);
-          if(found != mesh_cell_heat.end())
-            cells_heat_data[cell_id] = found->second;
-          else
-            cells_heat_data[cell_id] = std::numeric_limits<float>::quiet_NaN();
-        } else if(has_wall_heat) {
-          IntIntPair wall;
-          if(mesh->isBordTriangle(label, v, n, m, wall)) {
-            IntIntFloatMap::const_iterator found = mesh_wall_heat.find(wall);
-            if(found != mesh_wall_heat.end())
+  
+    QDomDocument doc("VTKFile");
+    QDomElement root = doc.createElement("VTKFile");
+    root.setAttribute("type", "UnstructuredGrid");
+    root.setAttribute("byte_order", "LittleEndian");
+    root.setAttribute("version", "0.1");
+    doc.appendChild(root);
+    // Add the grid
+    QDomElement grid = doc.createElement("UnstructuredGrid");
+    root.appendChild(grid);
+    // Add the pieces
+    QDomElement piece = doc.createElement("Piece");
+    grid.appendChild(piece);
+    const vvgraph& S = mesh->graph();
+    piece.setAttribute("NumberOfPoints", (uint)S.size());
+    QString format;
+    if(binary)
+      format = "binary";
+    else
+      format = "ascii";
+    // Points
+    QDomElement points = doc.createElement("Points");
+    piece.appendChild(points);
+    QDomElement points_pos = doc.createElement("DataArray");
+    points_pos.setAttribute("NumberOfComponents", "3");
+    points_pos.setAttribute("type", "Float32");
+    points_pos.setAttribute("format", format);
+    std::vector<Point3f> points_pos_data(S.size());
+    points.appendChild(points_pos);
+    // Points attributes
+    QDomElement points_data = doc.createElement("PointData");
+    piece.appendChild(points_data);
+    QString signal_name;
+    if(mesh->signalUnit().isEmpty())
+      signal_name = "Signal";
+    else
+      signal_name = QString("Signal (%1)").arg(mesh->signalUnit());
+    points_data.setAttribute("Scalars", signal_name);
+    points_data.setAttribute("Normals", "Normals");
+    QDomElement points_signal = doc.createElement("DataArray");
+    points_signal.setAttribute("Name", signal_name);
+    points_signal.setAttribute("type", "Float32");
+    points_signal.setAttribute("NumberOfComponents", "1");
+    points_signal.setAttribute("format", format);
+    std::vector<float> points_signal_data(S.size());
+    QDomElement points_normal = doc.createElement("DataArray");
+    points_normal.setAttribute("Name", "Normals");
+    points_normal.setAttribute("type", "Float32");
+    points_normal.setAttribute("NumberOfComponents", "3");
+    points_normal.setAttribute("format", format);
+    std::vector<Point3f> points_normal_data(S.size());
+    QDomElement points_label = doc.createElement("DataArray");
+    points_label.setAttribute("Name", "Label");
+    points_label.setAttribute("type", "Int32");
+    points_label.setAttribute("NumberOfComponents", "1");
+    points_label.setAttribute("format", format);
+    std::vector<int> points_label_data(S.size());
+    points_data.appendChild(points_signal);
+    points_data.appendChild(points_normal);
+    points_data.appendChild(points_label);
+    // Initialize vertex number and counts cells
+    int saveId = 0;
+    size_t count_cells = 0;
+    forall(const vertex& v, S) {
+      v->saveId = saveId++;
+      forall(const vertex& n, S.neighbors(v)) {
+        const vertex& m = S.nextTo(v, n);
+        if(mesh->uniqueTri(v, n, m))
+          ++count_cells;
+      }
+    }
+    // Cells
+    piece.setAttribute("NumberOfCells", (uint)count_cells);
+    QDomElement cells = doc.createElement("Cells");
+    piece.appendChild(cells);
+    QDomElement cells_connectivity = doc.createElement("DataArray");
+    cells_connectivity.setAttribute("type", "Int32");
+    cells_connectivity.setAttribute("Name", "connectivity");
+    cells_connectivity.setAttribute("format", format);
+    std::vector<Point3i> cells_connectivity_data(count_cells);
+    QDomElement cells_offsets = doc.createElement("DataArray");
+    cells_offsets.setAttribute("type", "Int32");
+    cells_offsets.setAttribute("Name", "offsets");
+    cells_offsets.setAttribute("format", format);
+    std::vector<int> cells_offsets_data(count_cells);
+    QDomElement cells_types = doc.createElement("DataArray");
+    cells_types.setAttribute("type", "UInt8");
+    cells_types.setAttribute("Name", "types");
+    cells_types.setAttribute("format", format);
+    std::vector<quint8> cells_types_data(count_cells, quint8(5));
+    cells.appendChild(cells_connectivity);
+    cells.appendChild(cells_offsets);
+    cells.appendChild(cells_types);
+    // Cells attributes
+    QDomElement cells_data = doc.createElement("CellData");
+    piece.appendChild(cells_data);
+    QDomElement cells_label = doc.createElement("DataArray");
+    cells_label.setAttribute("Name", "Label");
+    cells_label.setAttribute("type", "Int32");
+    cells_label.setAttribute("NumberOfComponents", "1");
+    cells_label.setAttribute("format", format);
+    cells_data.appendChild(cells_label);
+    std::vector<int> cells_label_data(count_cells);
+    QDomElement cells_heat = doc.createElement("DataArray");
+    const IntFloatMap& mesh_cell_heat = mesh->labelHeat();
+    const IntIntFloatMap& mesh_wall_heat = mesh->wallHeat();
+    bool has_cell_heat = !mesh_cell_heat.empty();
+    bool has_wall_heat = !mesh_wall_heat.empty();
+    QString heat_name = "Heat";
+    if(has_cell_heat)
+      heat_name = "Cell " + heat_name;
+    else if(has_wall_heat)
+      heat_name = "Wall " + heat_name;
+    if(!mesh->heatMapUnit().isEmpty())
+      heat_name += QString(" (%1)").arg(mesh->heatMapUnit());
+  
+    float minHeat = mesh->heatMapBounds()[0];
+    float maxHeat = mesh->heatMapBounds()[1];
+  
+    cells_heat.setAttribute("Name", heat_name);
+    cells_heat.setAttribute("type", "Float32");
+    cells_heat.setAttribute("NumberOfComponents", "1");
+    cells_heat.setAttribute("format", format);
+    cells_heat.setAttribute("RangeMin", minHeat);
+    cells_heat.setAttribute("RangeMax", maxHeat);
+    std::vector<float> cells_heat_data;
+    if(has_cell_heat or has_wall_heat) {
+      cells_heat_data.resize(count_cells);
+      cells_data.appendChild(cells_heat);
+      cells_data.setAttribute("Scalars", heat_name);
+    } else
+      cells_data.setAttribute("Scalars", "Label");
+  
+    std::unordered_set<int> labels;
+  
+    // Fills in everything
+    int cell_id = 0;
+    forall(const vertex& v, S) {
+      int id = v->saveId;
+      Point3f pos = savedPos(v->pos, transform, mesh->stack());
+      Point3f nrml = normalized(savedPos(v->nrml, transform, mesh->stack()));
+      points_pos_data[id] = pos;
+      points_label_data[id] = v->label;
+      points_signal_data[id] = v->signal;
+      points_normal_data[id] = nrml;
+      forall(const vertex& n, S.neighbors(v)) {
+        const vertex& m = S.nextTo(v, n);
+        if(mesh->uniqueTri(v, n, m)) {
+          cells_connectivity_data[cell_id] = Point3i(id, n->saveId, m->saveId);
+          cells_offsets_data[cell_id] = 3 * (cell_id + 1);
+          int label = mesh->getLabel(v, n, m);
+          labels.insert(label);
+          cells_label_data[cell_id] = label;
+          if(has_cell_heat) {
+            IntFloatMap::const_iterator found = mesh_cell_heat.find(label);
+            if(found != mesh_cell_heat.end())
               cells_heat_data[cell_id] = found->second;
             else
               cells_heat_data[cell_id] = std::numeric_limits<float>::quiet_NaN();
-          } else
-            cells_heat_data[cell_id] = std::numeric_limits<float>::quiet_NaN();
+          } else if(has_wall_heat) {
+            IntIntPair wall;
+            if(mesh->isBordTriangle(label, v, n, m, wall)) {
+              IntIntFloatMap::const_iterator found = mesh_wall_heat.find(wall);
+              if(found != mesh_wall_heat.end())
+                cells_heat_data[cell_id] = found->second;
+              else
+                cells_heat_data[cell_id] = std::numeric_limits<float>::quiet_NaN();
+            } else
+              cells_heat_data[cell_id] = std::numeric_limits<float>::quiet_NaN();
+          }
+          cell_id++;
         }
-        cell_id++;
       }
     }
+  
+    // Global fields
+    QDomElement global_fields = doc.createElement("FieldData");
+    grid.appendChild(global_fields);
+  
+    QDomElement scale = doc.createElement("DataArray");
+    scale.setAttribute("Name", "Scale");
+    scale.setAttribute("type", "Float32");
+    scale.setAttribute("NumberOfTuples", 1);
+    scale.setAttribute("format", "ascii");
+    scale.appendChild(doc.createTextNode("1e-6"));
+    global_fields.appendChild(scale);
+  
+    QDomElement labels_field = doc.createElement("DataArray");
+    labels_field.setAttribute("Name", "Labels");
+    labels_field.setAttribute("type", "Int32");
+    labels_field.setAttribute("NumberOfTuples", (int)labels.size());
+    labels_field.setAttribute("format", format);
+    std::vector<int> labels_fields_data(labels.begin(), labels.end());
+    std::sort(labels_fields_data.begin(), labels_fields_data.end());
+    labels_field.appendChild(vtkEncoding(labels_fields_data, doc, binary));
+    global_fields.appendChild(labels_field);
+  
+    if(has_cell_heat) {
+      QDomElement cell_heat = doc.createElement("DataArray");
+      QString cell_heat_name = "Cell Heat";
+      if(!mesh->heatMapUnit().isEmpty())
+        cell_heat_name += QString(" (%1)").arg(mesh->heatMapUnit());
+      cell_heat.setAttribute("Name", cell_heat_name);
+      cell_heat.setAttribute("type", "Float32");
+      cell_heat.setAttribute("NumberOfTuples", (int)labels.size());
+      cell_heat.setAttribute("format", format);
+      cell_heat.setAttribute("RangeMin", minHeat);
+      cell_heat.setAttribute("RangeMax", maxHeat);
+      std::vector<float> cell_heat_data(labels.size());
+      for(size_t i = 0; i < labels.size(); ++i) {
+        int label = labels_fields_data[i];
+        IntFloatMap::const_iterator found = mesh_cell_heat.find(label);
+        if(found == mesh_cell_heat.end())
+          cell_heat_data[i] = std::numeric_limits<float>::quiet_NaN();
+        else
+          cell_heat_data[i] = found->second;
+      }
+      cell_heat.appendChild(vtkEncoding(cell_heat_data, doc, binary));
+      global_fields.appendChild(cell_heat);
+    } else if(has_wall_heat) {
+      QDomElement walls_fields = doc.createElement("DataArray");
+      walls_fields.setAttribute("Name", "Walls");
+      walls_fields.setAttribute("type", "Int32");
+      walls_fields.setAttribute("NumberOfTuples", (int)mesh_wall_heat.size());
+      walls_fields.setAttribute("format", format);
+      std::vector<Point2i> walls_fields_data(mesh_wall_heat.size());
+  
+      QDomElement wall_heat = doc.createElement("DataArray");
+      QString wall_heat_name = "Wall Heat";
+      if(!mesh->heatMapUnit().isEmpty())
+        wall_heat_name += QString(" (%1)").arg(mesh->heatMapUnit());
+      wall_heat.setAttribute("Name", wall_heat_name);
+      wall_heat.setAttribute("type", "Float32");
+      wall_heat.setAttribute("NumberOfTuples", (int)mesh_wall_heat.size());
+      wall_heat.setAttribute("format", format);
+      wall_heat.setAttribute("RangeMin", minHeat);
+      wall_heat.setAttribute("RangeMax", maxHeat);
+      std::vector<float> wall_heat_data(labels.size());
+      int i = 0;
+      forall(const IntIntFloatPair& vs, mesh_wall_heat) {
+        const IntIntPair& w = vs.first;
+        float value = vs.second;
+        walls_fields_data[i] = Point2i(w.first, w.second);
+        wall_heat_data[i] = value;
+        ++i;
+      }
+      walls_fields.appendChild(vtkEncoding(walls_fields_data, doc, binary));
+      wall_heat.appendChild(vtkEncoding(wall_heat_data, doc, binary));
+      global_fields.appendChild(walls_fields);
+      global_fields.appendChild(wall_heat);
+    }
+  
+    points_pos.appendChild(vtkEncoding(points_pos_data, doc, binary));
+    points_label.appendChild(vtkEncoding(points_label_data, doc, binary));
+    points_signal.appendChild(vtkEncoding(points_signal_data, doc, binary));
+    points_normal.appendChild(vtkEncoding(points_normal_data, doc, binary));
+  
+    cells_connectivity.appendChild(vtkEncoding(cells_connectivity_data, doc, binary));
+    cells_offsets.appendChild(vtkEncoding(cells_offsets_data, doc, binary));
+    cells_types.appendChild(vtkEncoding(cells_types_data, doc, binary));
+  
+    if(has_cell_heat or has_wall_heat)
+      cells_heat.appendChild(vtkEncoding(cells_heat_data, doc, binary));
+  
+    cells_label.appendChild(vtkEncoding(cells_label_data, doc, binary));
+  
+    QString xmlString = doc.toString();
+    QByteArray xmlArray = xmlString.toUtf8();
+    qint64 qty = file.write(xmlArray);
+    if(qty != xmlArray.size())
+      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(xmlArray.size());
+  
+    file.close();
+  
+    return true;
   }
-
-  // Global fields
-  QDomElement global_fields = doc.createElement("FieldData");
-  grid.appendChild(global_fields);
-
-  QDomElement scale = doc.createElement("DataArray");
-  scale.setAttribute("Name", "Scale");
-  scale.setAttribute("type", "Float32");
-  scale.setAttribute("NumberOfTuples", 1);
-  scale.setAttribute("format", "ascii");
-  scale.appendChild(doc.createTextNode("1e-6"));
-  global_fields.appendChild(scale);
-
-  QDomElement labels_field = doc.createElement("DataArray");
-  labels_field.setAttribute("Name", "Labels");
-  labels_field.setAttribute("type", "Int32");
-  labels_field.setAttribute("NumberOfTuples", (int)labels.size());
-  labels_field.setAttribute("format", format);
-  std::vector<int> labels_fields_data(labels.begin(), labels.end());
-  std::sort(labels_fields_data.begin(), labels_fields_data.end());
-  labels_field.appendChild(vtkEncoding(labels_fields_data, doc, binary));
-  global_fields.appendChild(labels_field);
-
-  if(has_cell_heat) {
-    QDomElement cell_heat = doc.createElement("DataArray");
-    QString cell_heat_name = "Cell Heat";
-    if(!mesh->heatMapUnit().isEmpty())
-      cell_heat_name += QString(" (%1)").arg(mesh->heatMapUnit());
-    cell_heat.setAttribute("Name", cell_heat_name);
-    cell_heat.setAttribute("type", "Float32");
-    cell_heat.setAttribute("NumberOfTuples", (int)labels.size());
-    cell_heat.setAttribute("format", format);
-    cell_heat.setAttribute("RangeMin", minHeat);
-    cell_heat.setAttribute("RangeMax", maxHeat);
-    std::vector<float> cell_heat_data(labels.size());
-    for(size_t i = 0; i < labels.size(); ++i) {
-      int label = labels_fields_data[i];
-      IntFloatMap::const_iterator found = mesh_cell_heat.find(label);
-      if(found == mesh_cell_heat.end())
-        cell_heat_data[i] = std::numeric_limits<float>::quiet_NaN();
-      else
-        cell_heat_data[i] = found->second;
+  
+  bool MeshExport::saveText(Mesh* mesh, const QString& filename, bool transform)
+  {
+    const Stack* stack = mesh->stack();
+    QFile file(filename);
+    if(!file.open(QIODevice::WriteOnly)) {
+      setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
+      return false;
     }
-    cell_heat.appendChild(vtkEncoding(cell_heat_data, doc, binary));
-    global_fields.appendChild(cell_heat);
-  } else if(has_wall_heat) {
-    QDomElement walls_fields = doc.createElement("DataArray");
-    walls_fields.setAttribute("Name", "Walls");
-    walls_fields.setAttribute("type", "Int32");
-    walls_fields.setAttribute("NumberOfTuples", (int)mesh_wall_heat.size());
-    walls_fields.setAttribute("format", format);
-    std::vector<Point2i> walls_fields_data(mesh_wall_heat.size());
-
-    QDomElement wall_heat = doc.createElement("DataArray");
-    QString wall_heat_name = "Wall Heat";
-    if(!mesh->heatMapUnit().isEmpty())
-      wall_heat_name += QString(" (%1)").arg(mesh->heatMapUnit());
-    wall_heat.setAttribute("Name", wall_heat_name);
-    wall_heat.setAttribute("type", "Float32");
-    wall_heat.setAttribute("NumberOfTuples", (int)mesh_wall_heat.size());
-    wall_heat.setAttribute("format", format);
-    wall_heat.setAttribute("RangeMin", minHeat);
-    wall_heat.setAttribute("RangeMax", maxHeat);
-    std::vector<float> wall_heat_data(labels.size());
+  
+    const vvgraph& S = mesh->graph();
+  
+    QTextStream out(&file);
+    int saveId = 0;
     int i = 0;
-    forall(const IntIntFloatPair& vs, mesh_wall_heat) {
-      const IntIntPair& w = vs.first;
-      float value = vs.second;
-      walls_fields_data[i] = Point2i(w.first, w.second);
-      wall_heat_data[i] = value;
+  
+    out << S.size() << endl;
+  
+    Progress progress(QString("Saving Text Mesh %1 in File '%2'").arg(mesh->userId()).arg(filename), S.size() * 2);
+    int interval = S.size() / 100;
+    if(interval < 1)
+      interval = 1;
+    forall(const vertex& v, S) {
+      v->saveId = saveId++;
+      Point3f pos = savedPos(v->pos, transform, stack);
+      out << v->saveId << " " << pos << " " << v->label << endl;
+      if((i % interval == 0)and !progress.advance(i))
+        userCancel();
       ++i;
     }
-    walls_fields.appendChild(vtkEncoding(walls_fields_data, doc, binary));
-    wall_heat.appendChild(vtkEncoding(wall_heat_data, doc, binary));
-    global_fields.appendChild(walls_fields);
-    global_fields.appendChild(wall_heat);
-  }
-
-  points_pos.appendChild(vtkEncoding(points_pos_data, doc, binary));
-  points_label.appendChild(vtkEncoding(points_label_data, doc, binary));
-  points_signal.appendChild(vtkEncoding(points_signal_data, doc, binary));
-  points_normal.appendChild(vtkEncoding(points_normal_data, doc, binary));
-
-  cells_connectivity.appendChild(vtkEncoding(cells_connectivity_data, doc, binary));
-  cells_offsets.appendChild(vtkEncoding(cells_offsets_data, doc, binary));
-  cells_types.appendChild(vtkEncoding(cells_types_data, doc, binary));
-
-  if(has_cell_heat or has_wall_heat)
-    cells_heat.appendChild(vtkEncoding(cells_heat_data, doc, binary));
-
-  cells_label.appendChild(vtkEncoding(cells_label_data, doc, binary));
-
-  QString xmlString = doc.toString();
-  QByteArray xmlArray = xmlString.toUtf8();
-  qint64 qty = file.write(xmlArray);
-  if(qty != xmlArray.size())
-    throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(xmlArray.size());
-
-  file.close();
-
-  return true;
-}
-
-bool MeshExport::saveText(Mesh* mesh, const QString& filename, bool transform)
-{
-  const Stack* stack = mesh->stack();
-  QFile file(filename);
-  if(!file.open(QIODevice::WriteOnly)) {
-    setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
-    return false;
-  }
-
-  const vvgraph& S = mesh->graph();
-
-  QTextStream out(&file);
-  int saveId = 0;
-  int i = 0;
-
-  out << S.size() << endl;
-
-  Progress progress(QString("Saving Text Mesh %1 in File '%2'").arg(mesh->userId()).arg(filename), S.size() * 2);
-  int interval = S.size() / 100;
-  if(interval < 1)
-    interval = 1;
-  forall(const vertex& v, S) {
-    v->saveId = saveId++;
-    Point3f pos = savedPos(v->pos, transform, stack);
-    out << v->saveId << " " << pos << " " << v->label << endl;
-    if((i % interval == 0)and !progress.advance(i))
-      userCancel();
-    ++i;
-  }
-  forall(const vertex& v, S) {
-    out << v->saveId << " " << S.valence(v);
-    forall(const vertex& n, S.neighbors(v))
-      out << " " << n->saveId;
-    out << endl;
-    if((i % interval == 0)and !progress.advance(i))
-      userCancel();
-    ++i;
-  }
-  if(!progress.advance(S.size() * 2))
-    userCancel();
-  file.close();
-  SETSTATUS("Saved mesh, file:" << mesh->file() << ", vertices:" << S.size());
-  return true;
-}
-
-bool MeshExport::saveCells(Mesh* mesh, const QString& filename, bool transform)
-{
-  const Stack* stack = mesh->stack();
-  QFile file(filename);
-  if(!file.open(QIODevice::WriteOnly)) {
-    setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
-    return false;
-  }
-
-  const vvgraph& S = mesh->graph();
-
-  QTextStream out(&file);
-  int saveId = 0;
-  Progress progress(QString("Saving Cells %1 in File '%2'").arg(mesh->userId()).arg(filename), S.size() * 2);
-  out << S.size() << endl;
-  int interval = S.size() / 100;
-  if(interval < 1)
-    interval = 1;
-  int i = 0;
-  forall(const vertex& v, S) {
-    v->saveId = saveId++;
-    Point3f pos = savedPos(v->pos, transform, stack);
-    out << v->saveId << " " << pos << " " << v->label << " " << v->type << endl;
-    if((i % interval == 0)and !progress.advance(i))
-      userCancel();
-    ++i;
-  }
-  forall(const vertex& v, S) {
-    out << v->saveId << " " << S.valence(v);
-    forall(const vertex& n, S.neighbors(v))
-      out << " " << n->saveId;
-    out << endl;
-    if((i % interval == 0)and !progress.advance(i))
-      userCancel();
-    ++i;
-  }
-  if(!progress.advance(S.size() * 2))
-    userCancel();
-  SETSTATUS("Saved cellular mesh, file:" << mesh->file() << ", vertices:" << S.size());
-  return true;
-}
-
-bool MeshExport::saveMeshEdit(Mesh* mesh, const QString& filename, bool transform)
-{
-  const Stack* stack = mesh->stack();
-  QFile file(filename);
-  if(!file.open(QIODevice::WriteOnly)) {
-    setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
-    return false;
-  }
-
-  const vvgraph& S = mesh->graph();
-
-  QTextStream out(&file);
-  int saveId = 1;
-  out << "MeshVersionFormatted 1" << endl;
-  out << "Dimension 3" << endl;
-  out << "Vertices" << endl;
-  out << S.size() << endl;
-  Progress progress(QString("Saving Mesh Edit %1 in File '%2'").arg(mesh->userId()).arg(filename), S.size());
-  int i = 0;
-  int interval = S.size() / 100;
-  if(interval < 1)
-    interval = 1;
-  forall(const vertex& v, S) {
-    v->saveId = saveId++;
-    Point3f pos = savedPos(v->pos, transform, stack);
-    out << pos << " " << v->label << endl;
-  }
-  // Count the triangles
-  int count = 0;
-  forall(const vertex& v, S)
-    forall(const vertex& n, S.neighbors(v)) {
-      vertex m = S.nextTo(v, n);
-      if(!mesh->uniqueTri(v, n, m))
-        continue;
-      count++;
+    forall(const vertex& v, S) {
+      out << v->saveId << " " << S.valence(v);
+      forall(const vertex& n, S.neighbors(v))
+        out << " " << n->saveId;
+      out << endl;
+      if((i % interval == 0)and !progress.advance(i))
+        userCancel();
+      ++i;
     }
-  out << "Triangles" << endl;
-  out << count << endl;
-  forall(const vertex& v, S) {
-    forall(const vertex& n, S.neighbors(v)) {
-      vertex m = S.nextTo(v, n);
-      if(!mesh->uniqueTri(v, n, m))
-        continue;
-      out << v->saveId << " " << n->saveId << " " << m->saveId << " ";
-      out << mesh->getLabel(v, n, m) << endl;
-    }
-    if((i % interval == 0)and !progress.advance(i))
+    if(!progress.advance(S.size() * 2))
       userCancel();
+    file.close();
+    SETSTATUS("Saved mesh, file:" << mesh->file() << ", vertices:" << S.size());
+    return true;
   }
-  if(!progress.advance(S.size()))
-    userCancel();
-  out << "End" << endl;
-  SETSTATUS("Saving triangle mesh, file:" << mesh->file() << ", vertices:" << S.size());
-  return true;
-}
-
-bool MeshExport::saveMeshSTL(Mesh* mesh, const QString& filename, bool transform)
-{
-  const Stack* stack = mesh->stack();
-  QFile file(filename);
-  if(!file.open(QIODevice::WriteOnly)) {
-    setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
-    return false;
-  }
-
-  const vvgraph& S = mesh->graph();
-
-  QTextStream out(&file);
-  Progress progress(QString("Saving STL Mesh %1 in File '%2'").arg(mesh->userId()).arg(filename), S.size());
-  int i = 0;
-  int interval = S.size() / 100;
-  if(interval < 1)
-    interval = 1;
-
-  out << "solid mgx" << endl;
-  const std::vector<vertex>& av = mesh->activeVertices();
-  forall(const vertex& v, av) {
-    forall(const vertex& n, S.neighbors(v)) {
-      vertex m = S.nextTo(v, n);
-      if(!mesh->uniqueTri(v, n, m))
-        continue;
-      Point3f vpos = savedPos(v->pos, transform, stack);
-      Point3f npos = savedPos(n->pos, transform, stack);
-      Point3f mpos = savedPos(m->pos, transform, stack);
-      Point3f nrml = ((npos - vpos) ^ (mpos - vpos)).normalize();
-      out << "facet normal " << nrml.x() << " " << nrml.y() << " " << nrml.z() << endl;
-      out << "  outer loop" << endl;
-      out << "    vertex " << vpos.x() << " " << vpos.y() << " " << vpos.z() << endl;
-      out << "    vertex " << npos.x() << " " << npos.y() << " " << npos.z() << endl;
-      out << "    vertex " << mpos.x() << " " << mpos.y() << " " << mpos.z() << endl;
-      out << "  endloop" << endl;
-      out << "endfacet" << endl;
+  
+  bool MeshExport::saveCells(Mesh* mesh, const QString& filename, bool transform)
+  {
+    const Stack* stack = mesh->stack();
+    QFile file(filename);
+    if(!file.open(QIODevice::WriteOnly)) {
+      setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
+      return false;
     }
-    if((i % interval == 0)and !progress.advance(i))
-      userCancel();
-  }
-  out << "endsolid mgx" << endl;
-  if(!progress.advance(S.size()))
-    userCancel();
-  SETSTATUS("Saving STL mesh, file:" << mesh->file() << ", vertices:" << S.size());
-  return true;
-}
-
-bool MeshExport::savePLY(Mesh* mesh, const QString& filename, bool transform, bool binary)
-{
-  const Stack* stack = mesh->stack();
-  QFile file(filename);
-  if(!file.open(QIODevice::WriteOnly)) {
-    setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
-    return false;
-  }
-
-  const vvgraph& S = mesh->graph();
-  QTextStream outText(&file);
-  QDataStream outBinary(&file);
-  outBinary.setByteOrder(QDataStream::LittleEndian);
-  outBinary.setFloatingPointPrecision(QDataStream::SinglePrecision);
-
-  if(mesh->cells()) {
-    Progress progress(QString("Saving Cell Mesh in File '%1'").arg(filename), 0);
-    // First count the junctions
-    int cells = 0;
-    int junctions = 0;
-    // Cell mesh
-    forall(const vertex& v, S) {
-      if(v->type == 'c')
-        ++cells;
-      else if(v->type == 'j')
-        // We are not writing cell centers
-        v->saveId = junctions++;
-      else {
-        setErrorMessage(QString("MeshExport::Error:Bad vertex type:%1").arg(v->type));
-        return false;
-      }
-    }
-
-    // Write header
-    outText << "ply" << endl;
-    if(binary)
-      outText << "format binary_little_endian 1.0" << endl;
-    else
-      outText << "format ascii 1.0" << endl;
-    outText << "comment Exported from MorphoGraphX " << VERSION << " " REVISION << endl;
-    outText << "comment Cellular mesh" << endl;
-    outText << "element vertex " << junctions << endl;
-    outText << "property float x" << endl;
-    outText << "property float y" << endl;
-    outText << "property float z" << endl;
-    outText << "element face " << cells << endl;
-    outText << "property list int int vertex_index" << endl;
-    outText << "property int label" << endl;
-    outText << "end_header" << endl;
-
-    // For progress bar
-    int interval = junctions;
+  
+    const vvgraph& S = mesh->graph();
+  
+    QTextStream out(&file);
+    int saveId = 0;
+    Progress progress(QString("Saving Cells %1 in File '%2'").arg(mesh->userId()).arg(filename), S.size() * 2);
+    out << S.size() << endl;
+    int interval = S.size() / 100;
     if(interval < 1)
       interval = 1;
     int i = 0;
-
-    // First write vertices
     forall(const vertex& v, S) {
-      if(v->type == 'c')
-        continue;
-
+      v->saveId = saveId++;
       Point3f pos = savedPos(v->pos, transform, stack);
-      if(binary)
-        outBinary << pos.x() << pos.y() << pos.z();
-      else
-        outText << pos << endl;
-      if((i++ % interval == 0)and !progress.advance(0))
+      out << v->saveId << " " << pos << " " << v->label << " " << v->type << endl;
+      if((i % interval == 0)and !progress.advance(i))
         userCancel();
+      ++i;
     }
-
-    // Now write cells (faces)
     forall(const vertex& v, S) {
-      if(v->type == 'j')
-        continue;
-      if(binary)
-        outBinary << qint32(S.valence(v));
-      else
-        outText << S.valence(v);
-
-      // Write cell polygon
+      out << v->saveId << " " << S.valence(v);
       forall(const vertex& n, S.neighbors(v))
-        if(binary)
-          outBinary << qint32(n->saveId);
-        else
-          outText << " " << n->saveId;
-      if(binary)
-        outBinary << qint32(v->label);
-      else
-        outText << " " << v->label << endl;
-
-      if((i++ % interval == 0)and !progress.advance(0))
+        out << " " << n->saveId;
+      out << endl;
+      if((i % interval == 0)and !progress.advance(i))
         userCancel();
+      ++i;
     }
-    if(!progress.advance(0))
+    if(!progress.advance(S.size() * 2))
       userCancel();
-
-    SETSTATUS("Saved cellular mesh to file:" << mesh->file() << ", cells:" << cells << ", vertices:" << junctions);
-
-  } else {
-    // Save triangle mesh
-    Progress progress(
-      QString("Saving Triangle Mesh with %1 vertices in File '%2'").arg(mesh->userId()).arg(filename), 0);
-
-    // First count the junctions
-    int vertices = 0;
-    int triangles = 0;
-    forall(const vertex& v, S) {
-      v->saveId = vertices++;
-      forall(const vertex& n, S.neighbors(v)) {
-        const vertex& m = S.nextTo(v, n);
-        if(!mesh->uniqueTri(v, n, m))
-          continue;
-        triangles++;
-      }
+    SETSTATUS("Saved cellular mesh, file:" << mesh->file() << ", vertices:" << S.size());
+    return true;
+  }
+  
+  bool MeshExport::saveMeshEdit(Mesh* mesh, const QString& filename, bool transform)
+  {
+    const Stack* stack = mesh->stack();
+    QFile file(filename);
+    if(!file.open(QIODevice::WriteOnly)) {
+      setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
+      return false;
     }
-
-    // Write header
-    outText << "ply" << endl;
-    if(binary)
-      outText << "format binary_little_endian 1.0" << endl;
-    else
-      outText << "format ascii 1.0" << endl;
-    outText << "comment Exported from MorphoGraphX " << VERSION << " " REVISION << endl;
-    outText << "comment Triangle mesh" << endl;
-    outText << "element vertex " << vertices << endl;
-    outText << "property float x" << endl;
-    outText << "property float y" << endl;
-    outText << "property float z" << endl;
-    outText << "property int label" << endl;
-    outText << "element face " << triangles << endl;
-    outText << "property list uchar int vertex_index" << endl;
-    outText << "property int label" << endl;
-    outText << "end_header" << endl;
-
-    // For progress bar
-    int interval = vertices / 100;
+  
+    const vvgraph& S = mesh->graph();
+  
+    QTextStream out(&file);
+    int saveId = 1;
+    out << "MeshVersionFormatted 1" << endl;
+    out << "Dimension 3" << endl;
+    out << "Vertices" << endl;
+    out << S.size() << endl;
+    Progress progress(QString("Saving Mesh Edit %1 in File '%2'").arg(mesh->userId()).arg(filename), S.size());
+    int i = 0;
+    int interval = S.size() / 100;
     if(interval < 1)
       interval = 1;
-    int i = 0;
-
-    // First write vertices
     forall(const vertex& v, S) {
+      v->saveId = saveId++;
       Point3f pos = savedPos(v->pos, transform, stack);
-      if(binary)
-        outBinary << pos.x() << pos.y() << pos.z() << qint32(v->label);
-      else
-        outText << pos << " " << v->label << endl;
-      if((i++ % interval == 0)and !progress.advance(0))
-        userCancel();
+      out << pos << " " << v->label << endl;
     }
-    // Now write cells or triangles (faces)
+    // Count the triangles
+    int count = 0;
+    forall(const vertex& v, S)
+      forall(const vertex& n, S.neighbors(v)) {
+        vertex m = S.nextTo(v, n);
+        if(!mesh->uniqueTri(v, n, m))
+          continue;
+        count++;
+      }
+    out << "Triangles" << endl;
+    out << count << endl;
     forall(const vertex& v, S) {
-      // Write fan of triangles
       forall(const vertex& n, S.neighbors(v)) {
-        const vertex& m = S.nextTo(v, n);
+        vertex m = S.nextTo(v, n);
         if(!mesh->uniqueTri(v, n, m))
           continue;
-        if(binary)
-          outBinary << quint8(3) << qint32(v->saveId) << qint32(n->saveId) << qint32(m->saveId)
-                    << qint32(mesh->getLabel(v, n, m));
-        else
-          outText << "3 " << v->saveId << " " << n->saveId << " " << m->saveId << " "
-                  << mesh->getLabel(v, n, m) << endl;
+        out << v->saveId << " " << n->saveId << " " << m->saveId << " ";
+        out << mesh->getLabel(v, n, m) << endl;
       }
-      if((i++ % interval == 0)and !progress.advance(0))
+      if((i % interval == 0)and !progress.advance(i))
         userCancel();
     }
-    if(!progress.advance(0))
+    if(!progress.advance(S.size()))
       userCancel();
-
-    SETSTATUS("Saved triangle mesh to file:" << mesh->file() << ", triangles:" << triangles
-                                             << ", vertices:" << vertices);
+    out << "End" << endl;
+    SETSTATUS("Saving triangle mesh, file:" << mesh->file() << ", vertices:" << S.size());
+    return true;
   }
-  return true;
-}
-
-// REGISTER_MESH_PROCESS(MeshExport);
-
-bool MeshSave::initialize(QStringList& parms, QWidget* parent)
-{
-  int meshId = parms[2].toInt();
-  if(!checkState().mesh(MESH_ANY, meshId))
-    return false;
-
-  QDialog dlg(parent);
-  Ui_SaveMeshDialog ui;
-  ui.setupUi(&dlg);
-
-  this->ui = &ui;
-  this->dlg = &dlg;
-
-  connect(ui.SelectMeshFile, SIGNAL(clicked()), this, SLOT(selectMeshFile()));
-
-  Mesh* m = mesh(meshId);
-  QString filename = m->file();
-  if(filename.isEmpty())
-    filename = parms[0];
-
-  setMeshFile(filename);
-  ui.Transform->setChecked(stringToBool(parms[1]));
-
-  bool res = false;
-  if(dlg.exec() == QDialog::Accepted) {
-    parms[0] = properFile(ui.MeshFile->text());
-    parms[1] = (ui.Transform->isChecked() ? "yes" : "no");
-    res = true;
-  }
-  this->ui = 0;
-  this->dlg = 0;
-  return res;
-}
-
-QString MeshSave::properFile(QString filename) const
-{
-  QFileInfo fi(filename);
-  QString suf = fi.suffix();
-  if(!suf.isEmpty())
-    filename = filename.left(filename.size() - suf.size() - 1);
-  return filename + ".mgxm";
-}
-
-void MeshSave::selectMeshFile()
-{
-  QString filename = ui->MeshFile->text();
-  filename = QFileDialog::getSaveFileName(dlg, QString("Save mesh as ..."), filename, "Mesh files (*.mgxm)", 0,
-                                          FileDialogOptions);
-  if(!filename.isEmpty())
-    setMeshFile(filename);
-}
-
-void MeshSave::setMeshFile(const QString& filename)
-{
-  if(!filename.endsWith(".mgxm", Qt::CaseInsensitive))
-    ui->MeshFile->setText(filename + ".mgxm");
-  else
-    ui->MeshFile->setText(filename);
-}
-
-bool MeshSave::operator()(const QStringList& parms)
-{
-  int meshId = parms[2].toInt();
-  if(!checkState().mesh(STACK_ANY, meshId))
-    return false;
-  Mesh* mesh = this->mesh(meshId);
-  bool transform = stringToBool(parms[1]);
-  bool res = (*this)(mesh, parms[0], transform);
-  return res;
-}
-
-Point3f MeshSave::savedPos(Point3f pos, bool transform, const Stack* stack)
-{
-  if(transform)
-    pos = Point3f(stack->getFrame().inverseCoordinatesOf(Vec(pos)));
-  return pos;
-}
-
-bool MeshSave::operator()(Mesh* mesh, const QString& filename, bool transform)
-{
-  const Stack* stack = mesh->stack();
-  actingFile(filename);
-  QFile file(filename);
-  if(!file.open(QIODevice::WriteOnly)) {
-    setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
-    return false;
-  }
-
-  const vvgraph& S = mesh->graph();
-
-  qint64 qty;
-
-  file.write("MGXM 1.3 ", 9);
-  bool scale = true;
-  bool is_cells = mesh->cells();
-  qty = file.write((char*)&is_cells, sizeof(bool));
-  if(qty != sizeof(bool))
-    throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(bool));
-  qty = file.write((char*)&scale, sizeof(bool));
-  if(qty != sizeof(bool))
-    throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(bool));
-  qty = file.write((char*)&transform, sizeof(bool));
-  if(qty != sizeof(bool))
-    throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(bool));
-
-  Point2f signalBounds = mesh->signalBounds();
-  qty = file.write((char*)&signalBounds[0], sizeof(float));
-  if(qty != sizeof(float))
-    throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
-  qty = file.write((char*)&signalBounds[1], sizeof(float));
-  if(qty != sizeof(float))
-    throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
-
-  QByteArray ba = mesh->signalUnit().toUtf8();
-  uint stringSize = ba.size();
-  qty = file.write((char*)&stringSize, sizeof(uint));
-  if(qty != sizeof(uint))
-    throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(uint));
-  qty = file.write(ba.data(), stringSize);
-  if(qty != stringSize)
-    throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(stringSize);
-
-  static const uint size_vertex = sizeof(int) + sizeof(float) + sizeof(char) + sizeof(bool);
-  uint header[] = { 0, (uint)S.size(), size_vertex, 0 };
-  qty = file.write((char*)header, 16);
-  if(qty != 16)
-    throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(16);
-
-  uint saveId = 0;
-  Progress progress(QString("Saving Mesh %1 in File '%2'").arg(mesh->userId()).arg(filename), S.size() * 2);
-  int interval = S.size() / 100;
-  if(interval < 1)
-    interval = 1;
-  int i = 0;
-  forall(const vertex& v, S) {
-    v->saveId = saveId++;
-    qty = file.write((char*)&v->saveId, sizeof(uint));
-    if(qty != sizeof(uint))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(uint));
-    Point3f pos = savedPos(v->pos, transform, stack);
-    qty = file.write((char*)&pos, sizeof(Point3f));
-    if(qty != sizeof(Point3f))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(Point3f));
-    qty = file.write((char*)&v->label, sizeof(int));
-    if(qty != sizeof(int))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(int));
-    qty = file.write((char*)&v->signal, sizeof(float));
-    if(qty != sizeof(float))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
-    qty = file.write((char*)&v->type, sizeof(char));
-    if(qty != sizeof(char))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(char));
-    qty = file.write((char*)&v->selected, sizeof(bool));
-    if(qty != sizeof(bool))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(bool));
-
-    if((i % interval == 0)and !progress.advance(i))
-      userCancel();
-    ++i;
-  }
-  forall(const vertex& v, S) {
-    qty = file.write((char*)&v->saveId, sizeof(uint));
-    if(qty != sizeof(uint))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(uint));
-    uint val = S.valence(v);
-    qty = file.write((char*)&val, sizeof(uint));
-    if(qty != sizeof(uint))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(uint));
-    forall(const vertex& n, S.neighbors(v))
-      qty = file.write((char*)&n->saveId, sizeof(uint));
-    if(qty != sizeof(uint))
-      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(uint));
-    if((i % interval == 0)and !progress.advance(i))
-      userCancel();
-    ++i;
-  }
-  if(!progress.advance(S.size() * 2))
-    userCancel();
-  file.close();
-  mesh->setFile(util::stripCurrentDir(filename));
-  SETSTATUS("Saved mesh, file:" << mesh->file() << ", vertices:" << S.size());
-  return true;
-}
-
-// REGISTER_MESH_PROCESS(MeshSave);
-
-bool SaveViewFile::operator()(const QStringList& parms) {
-  return (*this)(parms[0]);
-}
-
-bool SaveViewFile::operator()(const QString& filename)
-{
-  if(filename.isEmpty()) {
-    setErrorMessage("Filename is empty. Cannot save view file.");
-    return false;
-  }
-  actingFile(filename, true);
-  bool res = systemCommand(SAVE_VIEW, QStringList() << filename);
-  SETSTATUS("saving view to file " << filename);
-  if(!res) {
-    setErrorMessage("Error while saving view file.");
-    return false;
-  }
-  return true;
-}
-
-bool SaveViewFile::initialize(QStringList& parms, QWidget* parent)
-{
-  QString filename = parms[0];
-
-  // Get the file name
-  filename = QFileDialog::getSaveFileName(parent, QString("Select view file"), filename,
-                                          "MorphoGraphX View files (*.mgxv);;All files (*.*)", 0, FileDialogOptions);
-
-  if(filename.isEmpty())
-    return false;
-  if(!filename.endsWith(".mgxv", Qt::CaseInsensitive))
-    filename += ".mgxv";
-
-  parms[0] = filename;
-  return true;
-}
-
-// REGISTER_GLOBAL_PROCESS(SaveViewFile);
-
-class MeshListModel : public QAbstractTableModel {
-public:
-  MeshListModel(Process* p, QObject* parent = 0)
-    : QAbstractTableModel(parent)
-    , proc(p)
+  
+  bool MeshExport::saveMeshSTL(Mesh* mesh, const QString& filename, bool transform)
   {
-    for(int i = 0; i < proc->meshCount(); ++i) {
-      names << QString("Mesh%1").arg(i + 1);
-      Mesh* m = proc->mesh(i);
-      QString shortFile = util::stripCurrentDir(m->file());
-      selected << not (shortFile.isEmpty());
-      files << shortFile;
-      transforms << false;
+    const Stack* stack = mesh->stack();
+    QFile file(filename);
+    if(!file.open(QIODevice::WriteOnly)) {
+      setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
+      return false;
     }
-  }
-
-  int rowCount(const QModelIndex& parent = QModelIndex()) const
-  {
-    if(parent.isValid())
-      return 0;
-    return names.size();
-  }
-
-  int columnCount(const QModelIndex& /*parent*/ = QModelIndex()) const {
-    return 4;
-  }
-
-  QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const
-  {
-    if(role != Qt::DisplayRole)
-      return QVariant();
-    if(orientation == Qt::Vertical)
-      return QVariant();
-    switch(section) {
-    case 0:
-      return "Mesh";
-    case 1:
-      return "Filename";
-    case 2:
-      return "Transformed";
-    default:
-      return QVariant();
+  
+    const vvgraph& S = mesh->graph();
+  
+    QTextStream out(&file);
+    Progress progress(QString("Saving STL Mesh %1 in File '%2'").arg(mesh->userId()).arg(filename), S.size());
+    int i = 0;
+    int interval = S.size() / 100;
+    if(interval < 1)
+      interval = 1;
+  
+    out << "solid mgx" << endl;
+    const std::vector<vertex>& av = mesh->activeVertices();
+    forall(const vertex& v, av) {
+      forall(const vertex& n, S.neighbors(v)) {
+        vertex m = S.nextTo(v, n);
+        if(!mesh->uniqueTri(v, n, m))
+          continue;
+        Point3f vpos = savedPos(v->pos, transform, stack);
+        Point3f npos = savedPos(n->pos, transform, stack);
+        Point3f mpos = savedPos(m->pos, transform, stack);
+        Point3f nrml = ((npos - vpos) ^ (mpos - vpos)).normalize();
+        out << "facet normal " << nrml.x() << " " << nrml.y() << " " << nrml.z() << endl;
+        out << "  outer loop" << endl;
+        out << "    vertex " << vpos.x() << " " << vpos.y() << " " << vpos.z() << endl;
+        out << "    vertex " << npos.x() << " " << npos.y() << " " << npos.z() << endl;
+        out << "    vertex " << mpos.x() << " " << mpos.y() << " " << mpos.z() << endl;
+        out << "  endloop" << endl;
+        out << "endfacet" << endl;
+      }
+      if((i % interval == 0)and !progress.advance(i))
+        userCancel();
     }
+    out << "endsolid mgx" << endl;
+    if(!progress.advance(S.size()))
+      userCancel();
+    SETSTATUS("Saving STL mesh, file:" << mesh->file() << ", vertices:" << S.size());
+    return true;
   }
-
-  Qt::ItemFlags flags(const QModelIndex& index) const
+  
+  bool MeshExport::savePLY(Mesh* mesh, const QString& filename, bool transform, bool binary)
   {
-    if(!index.isValid())
-      return Qt::ItemIsEnabled;
-    int i = index.row();
-    if(i < 0 or i >= names.size())
-      return Qt::ItemIsEnabled;
-    switch(index.column()) {
-    case 0:
-      return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable;
-    case 1:
-      if(selected[i])
-        return Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable;
-      else
-        return 0;
-    case 2:
-      if(selected[i])
-        return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable;
-      else
-        return 0;
-    default:
-      return Qt::ItemIsEnabled;
-    }
-  }
-
-  QString properFile(const QString& filename)
-  {
-    if(!filename.endsWith(".mgxm", Qt::CaseInsensitive))
-      return filename + ".mgxm";
-    return filename;
-  }
-
-  bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole)
-  {
-    if(!index.isValid() or index.column() > 3)
+    const Stack* stack = mesh->stack();
+    QFile file(filename);
+    if(!file.open(QIODevice::WriteOnly)) {
+      setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
       return false;
-
-    int i = index.row();
-
-    if(i < 0 or i >= names.size())
-      return false;
-
-    switch(index.column()) {
-    case 0:
-      if(role != Qt::CheckStateRole)
-        return false;
-      selected[i] = value.toBool();
-      emit dataChanged(this->index(i, 0), this->index(i, 4));
-      break;
-    case 1:
-      if(role != Qt::EditRole)
-        return false;
-      files[i] = properFile(value.toString());
-      emit dataChanged(index, index);
-      break;
-    case 2:
-      if(role != Qt::CheckStateRole)
-        return false;
-      transforms[i] = value.toBool();
-      emit dataChanged(index, index);
-      break;
-    default:
-      return false;
     }
-    return true;
-  }
-
-  QVariant data(const QModelIndex& index, int role) const
-  {
-    if(!index.isValid() or index.row() >= names.size() or index.column() > 3)
-      return QVariant();
-    int i = index.row();
-    switch(role) {
-    case Qt::CheckStateRole:
-      switch(index.column()) {
-      case 0:
-        return selected[i] ? Qt::Checked : Qt::Unchecked;
-      case 2:
-        return transforms[i] ? Qt::Checked : Qt::Unchecked;
-      case 1:
-      default:
-        return QVariant();
+  
+    const vvgraph& S = mesh->graph();
+    QTextStream outText(&file);
+    QDataStream outBinary(&file);
+    outBinary.setByteOrder(QDataStream::LittleEndian);
+    outBinary.setFloatingPointPrecision(QDataStream::SinglePrecision);
+  
+    if(mesh->cells()) {
+      Progress progress(QString("Saving Cell Mesh in File '%1'").arg(filename), 0);
+      // First count the junctions
+      int cells = 0;
+      int junctions = 0;
+      // Cell mesh
+      forall(const vertex& v, S) {
+        if(v->type == 'c')
+          ++cells;
+        else if(v->type == 'j')
+          // We are not writing cell centers
+          v->saveId = junctions++;
+        else {
+          setErrorMessage(QString("MeshExport::Error:Bad vertex type:%1").arg(v->type));
+          return false;
+        }
       }
-    case Qt::EditRole:
-      if(index.column() == 1)
-        return files[i];
+  
+      // Write header
+      outText << "ply" << endl;
+      if(binary)
+        outText << "format binary_little_endian 1.0" << endl;
       else
-        return QVariant();
-    case Qt::DisplayRole:
-      if(index.column() == 0)
-        return names[i];
-      else if(index.column() == 1)
-        return files[i];
+        outText << "format ascii 1.0" << endl;
+      outText << "comment Exported from MorphoGraphX " << VERSION << " " REVISION << endl;
+      outText << "comment Cellular mesh" << endl;
+      outText << "element vertex " << junctions << endl;
+      outText << "property float x" << endl;
+      outText << "property float y" << endl;
+      outText << "property float z" << endl;
+      outText << "element face " << cells << endl;
+      outText << "property list int int vertex_index" << endl;
+      outText << "property int label" << endl;
+      outText << "end_header" << endl;
+  
+      // For progress bar
+      int interval = junctions;
+      if(interval < 1)
+        interval = 1;
+      int i = 0;
+  
+      // First write vertices
+      forall(const vertex& v, S) {
+        if(v->type == 'c')
+          continue;
+  
+        Point3f pos = savedPos(v->pos, transform, stack);
+        if(binary)
+          outBinary << pos.x() << pos.y() << pos.z();
+        else
+          outText << pos << endl;
+        if((i++ % interval == 0)and !progress.advance(0))
+          userCancel();
+      }
+  
+      // Now write cells (faces)
+      forall(const vertex& v, S) {
+        if(v->type == 'j')
+          continue;
+        if(binary)
+          outBinary << qint32(S.valence(v));
+        else
+          outText << S.valence(v);
+  
+        // Write cell polygon
+        forall(const vertex& n, S.neighbors(v))
+          if(binary)
+            outBinary << qint32(n->saveId);
+          else
+            outText << " " << n->saveId;
+        if(binary)
+          outBinary << qint32(v->label);
+        else
+          outText << " " << v->label << endl;
+  
+        if((i++ % interval == 0)and !progress.advance(0))
+          userCancel();
+      }
+      if(!progress.advance(0))
+        userCancel();
+  
+      SETSTATUS("Saved cellular mesh to file:" << mesh->file() << ", cells:" << cells << ", vertices:" << junctions);
+  
+    } else {
+      // Save triangle mesh
+      Progress progress(
+        QString("Saving Triangle Mesh with %1 vertices in File '%2'").arg(mesh->userId()).arg(filename), 0);
+  
+      // First count the junctions
+      int vertices = 0;
+      int triangles = 0;
+      forall(const vertex& v, S) {
+        v->saveId = vertices++;
+        forall(const vertex& n, S.neighbors(v)) {
+          const vertex& m = S.nextTo(v, n);
+          if(!mesh->uniqueTri(v, n, m))
+            continue;
+          triangles++;
+        }
+      }
+  
+      // Write header
+      outText << "ply" << endl;
+      if(binary)
+        outText << "format binary_little_endian 1.0" << endl;
       else
-        return QVariant();
-    default:
-      return QVariant();
+        outText << "format ascii 1.0" << endl;
+      outText << "comment Exported from MorphoGraphX " << VERSION << " " REVISION << endl;
+      outText << "comment Triangle mesh" << endl;
+      outText << "element vertex " << vertices << endl;
+      outText << "property float x" << endl;
+      outText << "property float y" << endl;
+      outText << "property float z" << endl;
+      outText << "property int label" << endl;
+      outText << "element face " << triangles << endl;
+      outText << "property list uchar int vertex_index" << endl;
+      outText << "property int label" << endl;
+      outText << "end_header" << endl;
+  
+      // For progress bar
+      int interval = vertices / 100;
+      if(interval < 1)
+        interval = 1;
+      int i = 0;
+  
+      // First write vertices
+      forall(const vertex& v, S) {
+        Point3f pos = savedPos(v->pos, transform, stack);
+        if(binary)
+          outBinary << pos.x() << pos.y() << pos.z() << qint32(v->label);
+        else
+          outText << pos << " " << v->label << endl;
+        if((i++ % interval == 0)and !progress.advance(0))
+          userCancel();
+      }
+      // Now write cells or triangles (faces)
+      forall(const vertex& v, S) {
+        // Write fan of triangles
+        forall(const vertex& n, S.neighbors(v)) {
+          const vertex& m = S.nextTo(v, n);
+          if(!mesh->uniqueTri(v, n, m))
+            continue;
+          if(binary)
+            outBinary << quint8(3) << qint32(v->saveId) << qint32(n->saveId) << qint32(m->saveId)
+                      << qint32(mesh->getLabel(v, n, m));
+          else
+            outText << "3 " << v->saveId << " " << n->saveId << " " << m->saveId << " "
+                    << mesh->getLabel(v, n, m) << endl;
+        }
+        if((i++ % interval == 0)and !progress.advance(0))
+          userCancel();
+      }
+      if(!progress.advance(0))
+        userCancel();
+  
+      SETSTATUS("Saved triangle mesh to file:" << mesh->file() << ", triangles:" << triangles
+                                               << ", vertices:" << vertices);
     }
+    return true;
   }
-
-  void changeMesh(const QString& name, const QString& file, bool trans)
+  
+  bool MeshSave::initialize(QStringList& parms, QWidget* parent)
   {
-    int idx = names.indexOf(name);
-    if(idx >= 0) {
-      files[idx] = file;
-      selected[idx] = true;
-      transforms[idx] = trans;
-      emit dataChanged(index(idx, 0), index(idx, 4));
+    int meshId = parms[2].toInt();
+    if(!checkState().mesh(MESH_ANY, meshId))
+      return false;
+  
+    QDialog dlg(parent);
+    Ui_SaveMeshDialog ui;
+    ui.setupUi(&dlg);
+  
+    this->ui = &ui;
+    this->dlg = &dlg;
+  
+    connect(ui.SelectMeshFile, SIGNAL(clicked()), this, SLOT(selectMeshFile()));
+  
+    Mesh* m = mesh(meshId);
+    QString filename = m->file();
+    if(filename.isEmpty())
+      filename = parms[0];
+  
+    setMeshFile(filename);
+    ui.Transform->setChecked(stringToBool(parms[1]));
+  
+    bool res = false;
+    if(dlg.exec() == QDialog::Accepted) {
+      parms[0] = properFile(ui.MeshFile->text());
+      parms[1] = (ui.Transform->isChecked() ? "yes" : "no");
+      res = true;
     }
+    this->ui = 0;
+    this->dlg = 0;
+    return res;
   }
-
-  QStringList typeList;
-  QStringList names;
-  QStringList files;
-  QList<bool> selected, transforms;
-
-protected:
-  Process* proc;
-};
-
-class StackListModel : public QAbstractTableModel {
-public:
-  StackListModel(Process* p, QObject* parent = 0)
-    : QAbstractTableModel(parent)
-    , proc(p)
+  
+  QString MeshSave::properFile(QString filename) const
   {
-    for(int i = 0; i < proc->stackCount(); ++i) {
-      Stack* s = proc->stack(i);
-      if(!s)
-        continue;
-      Store* main = s->main();
-      if(main) {
-        names << QString("MainStack%1").arg(i + 1);
-        QString shortFile = util::stripCurrentDir(main->file());
-        files << properFile(shortFile);
-        selected << not shortFile.isEmpty();
-      }
-      Store* work = s->work();
-      if(work) {
-        names << QString("WorkStack%1").arg(i + 1);
-        QString shortFile = util::stripCurrentDir(work->file());
-        files << properFile(shortFile);
-        selected << not shortFile.isEmpty();
-      }
-    }
-  }
-
-  QString properFile(const QString& filename)
-  {
-    QString result = filename;
     QFileInfo fi(filename);
     QString suf = fi.suffix();
-    if(suf == "txt")
-      result = filename.left(result.size() - 3) + "mgxs";
-    else if(suf != "inr" and suf != "mgxs")
-      result = filename + ".mgxs";
-    return result;
+    if(!suf.isEmpty())
+      filename = filename.left(filename.size() - suf.size() - 1);
+    return filename + ".mgxm";
   }
-
-  int rowCount(const QModelIndex& parent = QModelIndex()) const
+  
+  void MeshSave::selectMeshFile()
   {
-    if(parent.isValid())
-      return 0;
-    return names.size();
+    QString filename = ui->MeshFile->text();
+    filename = QFileDialog::getSaveFileName(dlg, QString("Save mesh as ..."), filename, "Mesh files (*.mgxm)", 0,
+                                            FileDialogOptions);
+    if(!filename.isEmpty())
+      setMeshFile(filename);
   }
-
-  int columnCount(const QModelIndex& /*parent*/ = QModelIndex()) const {
-    return 2;
+  
+  void MeshSave::setMeshFile(const QString& filename)
+  {
+    if(!filename.endsWith(".mgxm", Qt::CaseInsensitive))
+      ui->MeshFile->setText(filename + ".mgxm");
+    else
+      ui->MeshFile->setText(filename);
   }
-
-  QVariant data(const QModelIndex& index, int role) const
+  
+  bool MeshSave::operator()(const QStringList& parms)
   {
-    if(!index.isValid() or index.row() >= names.size() or index.column() > 2)
-      return QVariant();
-    int i = index.row();
-    if(role == Qt::CheckStateRole and index.column() == 0)
-      return selected[i] ? Qt::Checked : Qt::Unchecked;
-    if(role == Qt::EditRole and index.column() == 1)
-      return files[i];
-    if(role == Qt::DisplayRole) {
-      if(index.column() == 0)
-        return names[i];
-      if(index.column() == 1)
-        return files[i];
-    }
-    return QVariant();
+    int meshId = parms[2].toInt();
+    if(!checkState().mesh(STACK_ANY, meshId))
+      return false;
+    Mesh* mesh = this->mesh(meshId);
+    bool transform = stringToBool(parms[1]);
+    bool res = (*this)(mesh, parms[0], transform);
+    return res;
   }
-
-  QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const
+  
+  Point3f MeshSave::savedPos(Point3f pos, bool transform, const Stack* stack)
   {
-    if(role != Qt::DisplayRole)
-      return QVariant();
-    if(orientation == Qt::Vertical)
-      return QVariant();
-    switch(section) {
-    case 0:
-      return "Stack";
-    case 1:
-      return "Filename";
-    default:
-      return QVariant();
-    }
+    if(transform)
+      pos = Point3f(stack->getFrame().inverseCoordinatesOf(Vec(pos)));
+    return pos;
   }
-
-  Qt::ItemFlags flags(const QModelIndex& index) const
+  
+  bool MeshSave::operator()(Mesh* mesh, const QString& filename, bool transform)
   {
-    if(!index.isValid())
-      return Qt::ItemIsEnabled;
-    int i = index.row();
-    if(i < 0 or i >= names.size())
-      return Qt::ItemIsEnabled;
-    switch(index.column()) {
-    case 0:
-      return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable;
-    case 1:
-      if(selected[i])
-        return Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable;
-      else
-        return 0;
-    default:
-      return Qt::ItemIsEnabled;
+    const Stack* stack = mesh->stack();
+    actingFile(filename);
+    QFile file(filename);
+    if(!file.open(QIODevice::WriteOnly)) {
+      setErrorMessage(QString("MeshExport::Error:Cannot open output file: %1").arg(filename));
+      return false;
     }
+  
+    const vvgraph& S = mesh->graph();
+  
+    qint64 qty;
+  
+    file.write("MGXM 1.3 ", 9);
+    bool scale = true;
+    bool is_cells = mesh->cells();
+    qty = file.write((char*)&is_cells, sizeof(bool));
+    if(qty != sizeof(bool))
+      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(bool));
+    qty = file.write((char*)&scale, sizeof(bool));
+    if(qty != sizeof(bool))
+      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(bool));
+    qty = file.write((char*)&transform, sizeof(bool));
+    if(qty != sizeof(bool))
+      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(bool));
+  
+    Point2f signalBounds = mesh->signalBounds();
+    qty = file.write((char*)&signalBounds[0], sizeof(float));
+    if(qty != sizeof(float))
+      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
+    qty = file.write((char*)&signalBounds[1], sizeof(float));
+    if(qty != sizeof(float))
+      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
+  
+    QByteArray ba = mesh->signalUnit().toUtf8();
+    uint stringSize = ba.size();
+    qty = file.write((char*)&stringSize, sizeof(uint));
+    if(qty != sizeof(uint))
+      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(uint));
+    qty = file.write(ba.data(), stringSize);
+    if(qty != stringSize)
+      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(stringSize);
+  
+    static const uint size_vertex = sizeof(int) + sizeof(float) + sizeof(char) + sizeof(bool);
+    uint header[] = { 0, (uint)S.size(), size_vertex, 0 };
+    qty = file.write((char*)header, 16);
+    if(qty != 16)
+      throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(16);
+  
+    uint saveId = 0;
+    Progress progress(QString("Saving Mesh %1 in File '%2'").arg(mesh->userId()).arg(filename), S.size() * 2);
+    int interval = S.size() / 100;
+    if(interval < 1)
+      interval = 1;
+    int i = 0;
+    forall(const vertex& v, S) {
+      v->saveId = saveId++;
+      qty = file.write((char*)&v->saveId, sizeof(uint));
+      if(qty != sizeof(uint))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(uint));
+      Point3f pos = savedPos(v->pos, transform, stack);
+      qty = file.write((char*)&pos, sizeof(Point3f));
+      if(qty != sizeof(Point3f))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(Point3f));
+      qty = file.write((char*)&v->label, sizeof(int));
+      if(qty != sizeof(int))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(int));
+      qty = file.write((char*)&v->signal, sizeof(float));
+      if(qty != sizeof(float))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(float));
+      qty = file.write((char*)&v->type, sizeof(char));
+      if(qty != sizeof(char))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(char));
+      qty = file.write((char*)&v->selected, sizeof(bool));
+      if(qty != sizeof(bool))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(bool));
+  
+      if((i % interval == 0)and !progress.advance(i))
+        userCancel();
+      ++i;
+    }
+    forall(const vertex& v, S) {
+      qty = file.write((char*)&v->saveId, sizeof(uint));
+      if(qty != sizeof(uint))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(uint));
+      uint val = S.valence(v);
+      qty = file.write((char*)&val, sizeof(uint));
+      if(qty != sizeof(uint))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(uint));
+      forall(const vertex& n, S.neighbors(v))
+        qty = file.write((char*)&n->saveId, sizeof(uint));
+      if(qty != sizeof(uint))
+        throw QString("Could not write data to file (written = %1, expected = %2)").arg(qty).arg(sizeof(uint));
+      if((i % interval == 0)and !progress.advance(i))
+        userCancel();
+      ++i;
+    }
+    if(!progress.advance(S.size() * 2))
+      userCancel();
+    file.close();
+    mesh->setFile(util::stripCurrentDir(filename));
+    SETSTATUS("Saved mesh, file:" << mesh->file() << ", vertices:" << S.size());
+    return true;
   }
-
-  bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole)
+  
+  bool SaveViewFile::operator()(const QStringList& parms) {
+    return (*this)(parms[0]);
+  }
+  
+  bool SaveViewFile::operator()(const QString& filename)
   {
-    if(!index.isValid() or index.column() > 1)
+    if(filename.isEmpty()) {
+      setErrorMessage("Filename is empty. Cannot save view file.");
       return false;
-
-    int i = index.row();
-
-    if(i < 0 or i >= names.size())
+    }
+    actingFile(filename, true);
+    bool res = systemCommand(SAVE_VIEW, QStringList() << filename);
+    SETSTATUS("saving view to file " << filename);
+    if(!res) {
+      setErrorMessage("Error while saving view file.");
       return false;
-
-    if(index.column() == 0 and role == Qt::CheckStateRole) {
-      selected[i] = value.toBool();
-      emit dataChanged(this->index(i, 0), this->index(i, 1));
-    } else if(index.column() == 1 and role == Qt::EditRole) {
-      files[i] = properFile(value.toString());
-      emit dataChanged(index, index);
-    } else
-      return false;
-
+    }
     return true;
   }
-
-  void changeStack(const QString& name, const QString& file)
+  
+  bool SaveViewFile::initialize(QStringList& parms, QWidget* parent)
   {
-    int idx = names.indexOf(name);
-    if(idx >= 0) {
-      files[idx] = file;
-      selected[idx] = true;
-      emit dataChanged(index(idx, 0), index(idx, 1));
-    }
-  }
-
-  QStringList names;
-  QStringList files;
-  QList<bool> selected;
-
-protected:
-  Process* proc;
-};
-
-QRegExp SaveAll::type_expr("^(?:(?:(Work|Main)Stack|(?:(Transformed)?Mesh))(\\d+)|View)$");
-
-void SaveAll::selectViewFile()
-{
-  QString filename = ui->viewFileName->text();
-  filename = QFileDialog::getSaveFileName(dlg, QString("Select view file"), filename,
-                                          "MorphoGraphX View files (*.mgxv);;All files (*.*)", 0, FileDialogOptions);
-  if(!filename.isEmpty()) {
-    if(!filename.endsWith(".mgxv"))
+    QString filename = parms[0];
+  
+    // Get the file name
+    filename = QFileDialog::getSaveFileName(parent, QString("Select view file"), filename,
+                                            "MorphoGraphX View files (*.mgxv);;All files (*.*)", 0, FileDialogOptions);
+  
+    if(filename.isEmpty())
+      return false;
+    if(!filename.endsWith(".mgxv", Qt::CaseInsensitive))
       filename += ".mgxv";
-    ui->viewFileName->setText(filename);
+  
+    parms[0] = filename;
+    return true;
   }
-}
-
-void SaveAll::validateViewFile()
-{
-  QString filename = ui->viewFileName->text();
-  if(!filename.isEmpty() and !filename.endsWith(".mgxv")) {
-    filename += ".mgxv";
-    ui->viewFileName->setText(filename);
-  }
-}
-
-bool SaveAll::initialize(QStringList& parms, QWidget* parent)
-{
-  QDialog dlg(parent);
-  Ui_SaveAllDlg ui;
-  ui.setupUi(&dlg);
-  this->dlg = &dlg;
-  this->ui = &ui;
-
-  connect(ui.selectViewFile, SIGNAL(clicked()), this, SLOT(selectViewFile()));
-  connect(ui.viewFileName, SIGNAL(editingFinished()), this, SLOT(validateViewFile()));
-
-  // First, set the system
-  ui.viewFileName->setText(file());
-  ui.saveViewFile->setChecked(not file().isEmpty());
-  ui.compressionLevel->setValue(parms[2].toInt());
-
-  StackListModel smodel(this);
-  MeshListModel mmodel(this);
-  ui.stackList->setModel(&smodel);
-  ui.meshList->setModel(&mmodel);
-
-  ui.stackList->resizeColumnToContents(0);
-  ui.stackList->resizeColumnToContents(1);
-
-  ui.meshList->resizeColumnToContents(0);
-  ui.meshList->resizeColumnToContents(1);
-  ui.meshList->resizeColumnToContents(2);
-  ui.meshList->resizeColumnToContents(3);
-
-  if(dlg.exec() == QDialog::Accepted) {
-    validateViewFile();
-    parms[0] = "Defined";
-    QStringList definition;
-    if(ui.saveViewFile->isChecked()) {
-      QString fn = ui.viewFileName->text();
-      definition << QString("View=%1").arg(fn);
+  
+  class MeshListModel : public QAbstractTableModel {
+  public:
+    MeshListModel(Process* p, QObject* parent = 0)
+      : QAbstractTableModel(parent)
+      , proc(p)
+    {
+      for(int i = 0; i < proc->meshCount(); ++i) {
+        names << QString("Mesh%1").arg(i + 1);
+        Mesh* m = proc->mesh(i);
+        QString shortFile = util::stripCurrentDir(m->file());
+        selected << not (shortFile.isEmpty());
+        files << shortFile;
+        transforms << false;
+      }
     }
-    if(ui.saveStacks->isChecked()) {
-      for(int i = 0; i < smodel.names.size(); ++i) {
-        if(smodel.selected[i] and not smodel.files[i].isEmpty())
-          definition << QString("%1=%2").arg(smodel.names[i]).arg(smodel.files[i]);
+  
+    int rowCount(const QModelIndex& parent = QModelIndex()) const
+    {
+      if(parent.isValid())
+        return 0;
+      return names.size();
+    }
+  
+    int columnCount(const QModelIndex& /*parent*/ = QModelIndex()) const {
+      return 4;
+    }
+  
+    QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const
+    {
+      if(role != Qt::DisplayRole)
+        return QVariant();
+      if(orientation == Qt::Vertical)
+        return QVariant();
+      switch(section) {
+      case 0:
+        return "Mesh";
+      case 1:
+        return "Filename";
+      case 2:
+        return "Transformed";
+      default:
+        return QVariant();
       }
     }
-    if(ui.saveMeshes->isChecked()) {
-      for(int i = 0; i < mmodel.names.size(); ++i) {
-        if(mmodel.selected[i] and not mmodel.files[i].isEmpty()) {
-          QString type;
-          QString name = (QString("%1Mesh%2").arg(mmodel.transforms[i] ? "Transformed" : "").arg(i + 1));
-          definition << QString("%1=%2").arg(name).arg(mmodel.files[i]);
-        }
+  
+    Qt::ItemFlags flags(const QModelIndex& index) const
+    {
+      if(!index.isValid())
+        return Qt::ItemIsEnabled;
+      int i = index.row();
+      if(i < 0 or i >= names.size())
+        return Qt::ItemIsEnabled;
+      switch(index.column()) {
+      case 0:
+        return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable;
+      case 1:
+        if(selected[i])
+          return Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable;
+        else
+          return 0;
+      case 2:
+        if(selected[i])
+          return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable;
+        else
+          return 0;
+      default:
+        return Qt::ItemIsEnabled;
       }
     }
-    parms[1] = definition.join(",");
-    parms[2] = QString::number(ui.compressionLevel->value());
-    return true;
-  }
-
-  return false;
-}
-
-bool SaveAll::operator()(const QStringList& parms)
-{
-  QList<SaveStruct> tosave;
-  if(parms[0].toLower() == "all") {
-    SaveStruct s;
-    s.type = ALL;
-    s.filename = parms[1];
-    tosave << s;
-  } else if(parms[0].toLower() == "defined") {
-    QStringList fields = parms[1].split(",");
-    Information::out << "tosave = '" << fields.join(" - ") << "'" << endl;
-    for(int i = 0; i < fields.size(); ++i) {
-      const QString& f = fields[i];
-      int sep = f.indexOf('=');
-      if(sep == -1)
-        return setErrorMessage(QString("Invalid save definition: missing '=' sign in field %1").arg(i + 1));
-      QString type = f.left(sep);
-      QString value = f.mid(sep + 1);
-      SaveStruct s;
-      s.filename = value;
-      if(type_expr.indexIn(type) != 0) {
-        setErrorMessage(QString("The string '%1' in field %2 is not a valid type").arg(type).arg(i + 1));
+  
+    QString properFile(const QString& filename)
+    {
+      if(!filename.endsWith(".mgxm", Qt::CaseInsensitive))
+        return filename + ".mgxm";
+      return filename;
+    }
+  
+    bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole)
+    {
+      if(!index.isValid() or index.column() > 3)
         return false;
+  
+      int i = index.row();
+  
+      if(i < 0 or i >= names.size())
+        return false;
+  
+      switch(index.column()) {
+      case 0:
+        if(role != Qt::CheckStateRole)
+          return false;
+        selected[i] = value.toBool();
+        emit dataChanged(this->index(i, 0), this->index(i, 4));
+        break;
+      case 1:
+        if(role != Qt::EditRole)
+          return false;
+        files[i] = properFile(value.toString());
+        emit dataChanged(index, index);
+        break;
+      case 2:
+        if(role != Qt::CheckStateRole)
+          return false;
+        transforms[i] = value.toBool();
+        emit dataChanged(index, index);
+        break;
+      default:
+        return false;
       }
-      if(!type_expr.cap(1).isEmpty())       // Stack
-      {
-        if(type_expr.cap(1) == "Work")
-          s.type = WORK_STACK;
+      return true;
+    }
+  
+    QVariant data(const QModelIndex& index, int role) const
+    {
+      if(!index.isValid() or index.row() >= names.size() or index.column() > 3)
+        return QVariant();
+      int i = index.row();
+      switch(role) {
+      case Qt::CheckStateRole:
+        switch(index.column()) {
+        case 0:
+          return selected[i] ? Qt::Checked : Qt::Unchecked;
+        case 2:
+          return transforms[i] ? Qt::Checked : Qt::Unchecked;
+        case 1:
+        default:
+          return QVariant();
+        }
+      case Qt::EditRole:
+        if(index.column() == 1)
+          return files[i];
         else
-          s.type = MAIN_STACK;
-        s.id = type_expr.cap(3).toInt() - 1;
-      } else if(!type_expr.cap(3).isEmpty())       // Mesh
-      {
-        s.type = MESH;
-        s.transform = !type_expr.cap(2).isEmpty();
-        s.id = type_expr.cap(3).toInt() - 1;
-      } else
-        s.type = VIEW;
-      tosave << s;
+          return QVariant();
+      case Qt::DisplayRole:
+        if(index.column() == 0)
+          return names[i];
+        else if(index.column() == 1)
+          return files[i];
+        else
+          return QVariant();
+      default:
+        return QVariant();
+      }
     }
-  } else
-    return setErrorMessage(QString("Error, unknown type '%1'").arg(parms[0]));
-  bool ok;
-  int cl = parms[2].toInt(&ok);
-  if(not ok)
-    return setErrorMessage("Error, parameter 'Compression Level' must be an integer number");
-  return (*this)(tosave, cl);
-}
-
-bool SaveAll::operator()(const QList<SaveStruct>& _tosave, int compressionLevel)
-{
-  // Check if the VIEW is saved. If so set this as the current project file
-  forall(const SaveStruct& s, _tosave) {
-    if(s.type == VIEW) {
-      actingFile(s.filename, true);
-      break;
+  
+    void changeMesh(const QString& name, const QString& file, bool trans)
+    {
+      int idx = names.indexOf(name);
+      if(idx >= 0) {
+        files[idx] = file;
+        selected[idx] = true;
+        transforms[idx] = trans;
+        emit dataChanged(index(idx, 0), index(idx, 4));
+      }
     }
-  }
-  QList<SaveStruct> tosave = _tosave;
-  if(tosave.size() == 1 and tosave[0].type == ALL) {
-    tosave[0].type = VIEW;
-    if(tosave[0].filename.isEmpty())
-      tosave[0].filename = file();
-    for(int i = 0; i < stackCount(); ++i) {
-      SaveStruct sm, sw;
-      Stack* st = stack(i);
-      sm.type = MAIN_STACK;
-      sw.type = WORK_STACK;
-      Store* main = st->main();
-      Store* work = st->work();
-      sm.id = sw.id = i;
-      if(main and !main->file().isEmpty()) {
-        sm.filename = main->file();
-        tosave << sm;
+  
+    QStringList typeList;
+    QStringList names;
+    QStringList files;
+    QList<bool> selected, transforms;
+  
+  protected:
+    Process* proc;
+  };
+  
+  class StackListModel : public QAbstractTableModel {
+  public:
+    StackListModel(Process* p, QObject* parent = 0)
+      : QAbstractTableModel(parent)
+      , proc(p)
+    {
+      for(int i = 0; i < proc->stackCount(); ++i) {
+        Stack* s = proc->stack(i);
+        if(!s)
+          continue;
+        Store* main = s->main();
+        if(main) {
+          names << QString("MainStack%1").arg(i + 1);
+          QString shortFile = util::stripCurrentDir(main->file());
+          files << properFile(shortFile);
+          selected << not shortFile.isEmpty();
+        }
+        Store* work = s->work();
+        if(work) {
+          names << QString("WorkStack%1").arg(i + 1);
+          QString shortFile = util::stripCurrentDir(work->file());
+          files << properFile(shortFile);
+          selected << not shortFile.isEmpty();
+        }
       }
-      if(work and !work->file().isEmpty()) {
-        sw.filename = work->file();
-        tosave << sw;
+    }
+  
+    QString properFile(const QString& filename)
+    {
+      QString result = filename;
+      QFileInfo fi(filename);
+      QString suf = fi.suffix();
+      if(suf == "txt")
+        result = filename.left(result.size() - 3) + "mgxs";
+      else if(suf != "inr" and suf != "mgxs")
+        result = filename + ".mgxs";
+      return result;
+    }
+  
+    int rowCount(const QModelIndex& parent = QModelIndex()) const
+    {
+      if(parent.isValid())
+        return 0;
+      return names.size();
+    }
+  
+    int columnCount(const QModelIndex& /*parent*/ = QModelIndex()) const {
+      return 2;
+    }
+  
+    QVariant data(const QModelIndex& index, int role) const
+    {
+      if(!index.isValid() or index.row() >= names.size() or index.column() > 2)
+        return QVariant();
+      int i = index.row();
+      if(role == Qt::CheckStateRole and index.column() == 0)
+        return selected[i] ? Qt::Checked : Qt::Unchecked;
+      if(role == Qt::EditRole and index.column() == 1)
+        return files[i];
+      if(role == Qt::DisplayRole) {
+        if(index.column() == 0)
+          return names[i];
+        if(index.column() == 1)
+          return files[i];
       }
+      return QVariant();
     }
-    for(int i = 0; i < meshCount(); ++i) {
-      SaveStruct s;
-      s.type = MESH;
-      s.id = i;
-      s.transform = false;
-      tosave << s;
+  
+    QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const
+    {
+      if(role != Qt::DisplayRole)
+        return QVariant();
+      if(orientation == Qt::Vertical)
+        return QVariant();
+      switch(section) {
+      case 0:
+        return "Stack";
+      case 1:
+        return "Filename";
+      default:
+        return QVariant();
+      }
     }
-  }
-  SaveViewFile saveViewFile(*this);
-  MeshSave saveMesh(*this);
-  StackSave saveStack(*this);
-  Progress progress("Saving all files ...", tosave.size());
-  QString viewFilename;
-  for(int i = 0; i < tosave.size(); ++i) {
-    if(!progress.advance(i))
-      userCancel();
-    const SaveStruct& s = tosave[i];
-    switch(s.type) {
-    case VIEW:
-      viewFilename = s.filename;
-      break;
-    case MAIN_STACK: {
-      Stack* st = stack(s.id);
-      if(!st) {
-        setErrorMessage(QString("No stack numbered %1").arg(s.id));
-        return false;
+  
+    Qt::ItemFlags flags(const QModelIndex& index) const
+    {
+      if(!index.isValid())
+        return Qt::ItemIsEnabled;
+      int i = index.row();
+      if(i < 0 or i >= names.size())
+        return Qt::ItemIsEnabled;
+      switch(index.column()) {
+      case 0:
+        return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable;
+      case 1:
+        if(selected[i])
+          return Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable;
+        else
+          return 0;
+      default:
+        return Qt::ItemIsEnabled;
       }
-      if(!saveStack(st, st->main(), s.filename, compressionLevel))
+    }
+  
+    bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole)
+    {
+      if(!index.isValid() or index.column() > 1)
         return false;
-    } break;
-    case WORK_STACK: {
-      Stack* st = stack(s.id);
-      if(!st) {
-        setErrorMessage(QString("No stack numbered %1").arg(s.id));
+  
+      int i = index.row();
+  
+      if(i < 0 or i >= names.size())
         return false;
-      }
-      if(!saveStack(st, st->work(), s.filename, compressionLevel))
+  
+      if(index.column() == 0 and role == Qt::CheckStateRole) {
+        selected[i] = value.toBool();
+        emit dataChanged(this->index(i, 0), this->index(i, 1));
+      } else if(index.column() == 1 and role == Qt::EditRole) {
+        files[i] = properFile(value.toString());
+        emit dataChanged(index, index);
+      } else
         return false;
-    } break;
-    case MESH: {
-      Mesh* m = mesh(s.id);
-      if(!m) {
-        setErrorMessage(QString("No mesh numbered %1").arg(s.id));
-        return false;
+  
+      return true;
+    }
+  
+    void changeStack(const QString& name, const QString& file)
+    {
+      int idx = names.indexOf(name);
+      if(idx >= 0) {
+        files[idx] = file;
+        selected[idx] = true;
+        emit dataChanged(index(idx, 0), index(idx, 1));
       }
-      if(!saveMesh(m, s.filename, s.transform))
-        return false;
-    } break;
-    case ALL: {
-      setErrorMessage("The type 'All' can only be used in isolation, with no other file specification");
-      return false;
     }
-    }
+  
+    QStringList names;
+    QStringList files;
+    QList<bool> selected;
+  
+  protected:
+    Process* proc;
+  };
+  
+  bool TakeSnapshot::operator()(QString filename, float overSampling, int width, int height, int quality,
+                                bool expand_frustum)
+  {
+    return takeSnapshot(filename, overSampling, width, height, quality, expand_frustum);
   }
-  // It needs to be always the last thing done
-  if(!viewFilename.isEmpty()) {
-    if(!saveViewFile(viewFilename))
-      return false;
-  }
-  SETSTATUS("All saved");
-  return true;
-}
 
-bool ResetAll::operator()()
-{
-  for(int i = 0; i < stackCount(); ++i) {
-    Stack* stk = stack(i);
-    if(stk) {
-      stk->reset();
-      stk->main()->changed();
-      stk->work()->changed();
-    }
-  }
-
-  for(int i = 0; i < meshCount(); ++i) {
-    Mesh* m = mesh(i);
-    if(m) {
-      m->reset();
-      m->updateAll();
-    }
-  }
-
-  resetProject();
-
-  return true;
-}
-
-// REGISTER_GLOBAL_PROCESS(SaveAll);
-bool TakeSnapshot::operator()(QString filename, float overSampling, int width, int height, int quality,
-                              bool expand_frustum)
-{
-  return takeSnapshot(filename, overSampling, width, height, quality, expand_frustum);
-}
-} // namespace process
-} // namespace mgx
+}}
Index: Progress.cpp
===================================================================
--- Progress.cpp	(revision 1255)
+++ Progress.cpp	(revision 1256)
@@ -8,6 +8,7 @@
 #include <stdio.h>
 #include <QTimer>
 #include <omp.h>
+#include <iostream>
 
 #define SHOW_TIMER 2000
 
@@ -16,12 +17,7 @@
 
 struct StartProgressEvent : public QEvent {
   StartProgressEvent(const QString& msg, int steps, bool allow_cancel)
-    : QEvent(QEvent::User)
-    , msg(msg)
-    , steps(steps)
-    , allow_cancel(allow_cancel)
-  {
-  }
+    : QEvent(QEvent::User) , msg(msg) , steps(steps) , allow_cancel(allow_cancel) {}
 
   QString msg;
   int steps;
@@ -30,10 +26,7 @@
 
 struct AdvanceProgressEvent : public QEvent {
   AdvanceProgressEvent(int i)
-    : QEvent(QEvent::User)
-    , step(i)
-  {
-  }
+    : QEvent(QEvent::User) , step(i) {}
 
   int step;
 };
@@ -40,10 +33,7 @@
 
 struct SetMaximumProgressEvent : public QEvent {
   SetMaximumProgressEvent(int n)
-    : QEvent(QEvent::User)
-    , steps(n)
-  {
-  }
+    : QEvent(QEvent::User) , steps(n) {}
 
   int steps;
 };
@@ -50,10 +40,7 @@
 
 struct SetMsgProgressEvent : public QEvent {
   SetMsgProgressEvent(QString _msg)
-    : QEvent(QEvent::User)
-    , msg(_msg)
-  {
-  }
+    : QEvent(QEvent::User) , msg(_msg) {}
 
   QString msg;
 };
@@ -60,9 +47,7 @@
 
 struct StopProgressEvent : public QEvent {
   StopProgressEvent()
-    : QEvent(QEvent::User)
-  {
-  }
+    : QEvent(QEvent::User) {}
 };
 
 GlobalProgress* GlobalProgress::_instance = 0;
@@ -77,11 +62,7 @@
 // Progress dialog class
 
 GlobalProgress::GlobalProgress()
-  : parent(0)
-  , prg(0)
-  , ismodal(true)
-  , _canceled(false)
-  , access(QMutex::Recursive)
+  : parent(0) , prg(0) , ismodal(true) , _canceled(false) , access(QMutex::Recursive)
   , showTimer(new QTimer(this))
 {
   showTimer->setInterval(SHOW_TIMER);
@@ -91,9 +72,8 @@
 
 GlobalProgress::~GlobalProgress()
 {
-  if(prg) {
+  if(prg)
     delete prg;
-  }
   prg = 0;
 }
 
Index: ColorBar.hpp
===================================================================
--- ColorBar.hpp	(revision 1255)
+++ ColorBar.hpp	(revision 1256)
@@ -15,63 +15,63 @@
 #include <valarray>
 
 namespace mgx {
-class MGX_EXPORT Colorbar {
-public:
-  typedef std::valarray<double> array;
-  enum Position { TOP, BOTTOM, LEFT, RIGHT, TOP_LEFT, TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT };
-
-  enum Orientation { HORIZONTAL, VERTICAL };
-
-  Colorbar(Position pos = RIGHT);
-
-  void draw(QGLViewer* viewer, GLuint colormapTexId, QPaintDevice* device = 0) const;
-
-  Position position;
-  Orientation orientation;
-  QFont font;
-
-  double scale_length;
-  double width;
-  double distance_to_border;
-  double text_to_bar;
-  double tick_size;
-  double exp_size;
-  double epsilon;
-  double line_width;
-
-  double vmin, vmax;
-
-  double globalScaling;
-
-  QString label;
-
-  void readParms(util::Parms& parms, QString section);
-  void writeParms(QTextStream& pout, QString section);
-
-  void scaleDrawing(double scale);
-  void restoreScale();
-
-protected:
-  void startScreenCoordinatesSystem(QPaintDevice* device) const;
-  void stopScreenCoordinatesSystem() const;
-
-  mutable double prev_width, prev_height;
-  void _getValues(double start, double end, double delta, array& result) const;
-  array _selectValues_direct(double length, bool is_vertical, const QFontMetricsF& metric, double min_dist) const;
-  std::pair<double, double> _significant_digits(double start, double end) const;
-  bool _canRenderTicks(const array& ticks, double length, double min_dist, bool is_vertical,
-                       const QFontMetricsF& font_metric) const;
-  QStringList _tick2str(const array& ticks, QString* extra = 0) const;
-  array selectValues(double length, bool is_vertical, const QFontMetricsF* metric = 0) const;
-};
-
-std::ostream& operator<<(std::ostream& s, const Colorbar::Position& pos);
-std::istream& operator>>(std::istream& s, Colorbar::Position& pos);
-
-QTextStream& operator<<(QTextStream& s, const Colorbar::Position& pos);
-QTextStream& operator>>(QTextStream& s, Colorbar::Position& pos);
-
-QDataStream& operator<<(QDataStream& s, const Colorbar::Position& pos);
-QDataStream& operator>>(QDataStream& s, Colorbar::Position& pos);
+  class MGX_EXPORT Colorbar {
+  public:
+    typedef std::valarray<double> array;
+    enum Position { TOP, BOTTOM, LEFT, RIGHT, TOP_LEFT, TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT };
+  
+    enum Orientation { HORIZONTAL, VERTICAL };
+  
+    Colorbar(Position pos = RIGHT);
+  
+    void draw(QGLViewer* viewer, GLuint colormapTexId, QPaintDevice* device = 0) const;
+  
+    Position position;
+    Orientation orientation;
+    QFont font;
+  
+    double scale_length;
+    double width;
+    double distance_to_border;
+    double text_to_bar;
+    double tick_size;
+    double exp_size;
+    double epsilon;
+    double line_width;
+  
+    double vmin, vmax;
+  
+    double globalScaling;
+  
+    QString label;
+  
+    void readParms(util::Parms& parms, QString section);
+    void writeParms(QTextStream& pout, QString section);
+  
+    void scaleDrawing(double scale);
+    void restoreScale();
+  
+  protected:
+    void startScreenCoordinatesSystem(QPaintDevice* device) const;
+    void stopScreenCoordinatesSystem() const;
+  
+    mutable double prev_width, prev_height;
+    void getValues(double start, double end, double delta, array& result) const;
+    array selectValuesDirect(double length, bool is_vertical, const QFontMetricsF& metric, double min_dist) const;
+    std::pair<double, double> significantDigits(double start, double end) const;
+    bool canRenderTicks(const array& ticks, double length, double min_dist, bool is_vertical,
+                         const QFontMetricsF& font_metric) const;
+    QStringList _tick2str(const array& ticks, QString* extra = 0) const;
+    array selectValues(double length, bool is_vertical, const QFontMetricsF* metric = 0) const;
+  };
+  
+  std::ostream& operator<<(std::ostream& s, const Colorbar::Position& pos);
+  std::istream& operator>>(std::istream& s, Colorbar::Position& pos);
+  
+  QTextStream& operator<<(QTextStream& s, const Colorbar::Position& pos);
+  QTextStream& operator>>(QTextStream& s, Colorbar::Position& pos);
+  
+  QDataStream& operator<<(QDataStream& s, const Colorbar::Position& pos);
+  QDataStream& operator>>(QDataStream& s, Colorbar::Position& pos);
 } // namespace mgx
 #endif // COLORBAR_H
Index: VVGraph.hpp
===================================================================
--- VVGraph.hpp	(revision 1255)
+++ VVGraph.hpp	(revision 1256)
@@ -29,2509 +29,2323 @@
 using namespace tr1;
 }
 
-namespace mgx {
-namespace graph {
-
-/**
- * Contains all the classes related to the graphs.
- *
- * For now, the only graph available is the VVGraph.
- */
-
-/**
- * \class _EmptyEdgeContent vvgraph.h <graph/vvgraph.h>
- *
- * Empty class used as default for edge content
- */
-struct _EmptyEdgeContent {
-  _EmptyEdgeContent& operator=(const _EmptyEdgeContent& /*other*/) {
-    return *this;
-  }
-};
-
-/**
- * \class VVGraph vvgraph.h <graph/vvgraph.h>
- * Class representing a VV graph.
- *
- * A VV graph is an oriented rotational graph. That is, the edges of a given
- * vertex have a circular order. That is, if an edge has three edges e1, e2,
- * e3, there is no first edge, but we can say e1 < e2 < e3 < e1. In that
- * case, '<' denote the succession.
- *
- * \c VertexContent is the type used to hold the vertex data.
- *
- * \c EdgeContent is the type used to hold the edge data. If no type is
- * specified for \c EdgeContent, then an empty structure is used.
- *
- * \section Perfs Performance notes
- * The graph includes two caching mecanisms to improve performances when
- * iterating over the graph and retrieve edge information:
- *   -# while iterating over the graph, the vertex cache the current iterator.
- *   So that accessing the neighborhood of the vertex is constant time (i.e.
- *   it's dereferencing the cached iterator).
- *   -# while iterating over the neighborhood of a vertex, the target vertex
- *   (i.e. the one returned by the iteration) cache the iterator on the
- *   neighborhood. So that any operation using that specific edge (i.e.
- *   getting edge data, splicing, replacing or erasing) is alos constant
- *   time.
- *
- * To make this caching mecanism correct, the cached data are never copied.
- * This means, to make use of the caching mecanism, you have to iterate using
- * constant references (references will end up with compilation errors if
- * used on the graph):
- * \code
- * forall(const vertex &v, S)
- * {
- *   // Here the vertex v has the vertex cache
- *   forall(const vertex &n, S.neighbors(S)) // Makes use of the cache
- *   {
- *     S.edge(v,n)->pos = Point3d(1,2,3); // Uses the edge cache
- *     S.edge(n,v)->pos = Point3d(3,2,1); // Do not use any cache
- *   }
- *   v->pos = Point3d(0,0,0); // Valid
- * }
- * \endcode
- *
- * \warning Do not iterate using constant references if you ever remove the
- * vertex you iterate on ! (i.e. remove from the graph if you iterate on the
- * graph or remove from the neighborhood if you iterate on the neighborhood)
- *
- * Even though this code manipulate constant references, modifying the data
- * pointed by the vertex is allowed. The vertexes are coded to allow that.
- * That means if you are using vertexes in a dictionary or a set, using their
- * content to compare them, you must not modify them ! The compiler won't
- * guard you against it.
- */
-template <typename VertexContent, typename EdgeContent = _EmptyEdgeContent,
-          typename Alloc = std::allocator<VertexContent> >
-class VVGraph {
-public:
-  typedef typename Alloc::template rebind<EdgeContent>::other EdgeAlloc;
-  static EdgeAlloc edge_alloc;
-
-  ///\name Smart pointer types
-  //@{
+namespace mgx { namespace graph {
+  
   /**
-   * Smart pointer on a vertex
-   */
-  typedef typename Alloc::template rebind<VertexContent>::other VertexAlloc;
-  typedef Vertex<VertexContent, VertexAlloc> vertex_t;
-  /**
-   * Weak pointer on an edge
-   */
-  typedef Edge<EdgeContent> edge_t;
-  /**
-   * Weak pointer on a constant edge
-   */
-  typedef Edge<const EdgeContent> const_edge_t;
-  /**
-   * Weak pointer on an arc.
+   * Contains all the classes related to the graphs.
    *
-   * When an object of this type is destroyed, the content of the primary
-   * edge (i.e. the edge source -> target) is copied into the other.
+   * For now, the only graph available is the VVGraph.
    */
-  typedef Arc<EdgeContent> arc_t;
-  //@}
-
+  
   /**
-   * Type of the value of the graph as standard container.
-   */
-  typedef vertex_t value_type;
-
-  /**
-   * Default constructor
+   * \class _EmptyEdgeContent vvgraph.h <graph/vvgraph.h>
    *
-   * Creates an empty VV graph
+   * Empty class used as default for edge content
    */
-  VVGraph()
-    : modified_vertices(false)
-  {
-  }
-
+  struct _EmptyEdgeContent {
+    _EmptyEdgeContent& operator=(const _EmptyEdgeContent& /*other*/) {
+      return *this;
+    }
+  };
+  
   /**
-   * Copy constructor.
+   * \class VVGraph vvgraph.h <graph/vvgraph.h>
+   * Class representing a VV graph.
    *
-   * Maintains the caches in a valid state
-   */
-  VVGraph(const VVGraph& copy);
-
-  /**
-   * Construct from an existing list of vertices
+   * A VV graph is a graph rotation system, that is, a graph where the neighbors
+   * of vertices are stored in a circular order. 
    *
-   * \param check_unique If false, there must be not be duplicated vertex in the sequence
-   */
-  template <typename Iterator> VVGraph(Iterator begin, Iterator end, bool check_unique = true)
-  {
-    insert(begin, end, check_unique);
-  }
-
-  /**
-   * Construct from an existing list of vertices
+   * \c VertexContent is the type used to hold the vertex data.
    *
-   * \param check_unique If false, there must be not be duplicated vertex in the sequence
+   * \c EdgeContent is the type used to hold the edge data. If no type is
+   * specified for \c EdgeContent, then an empty structure is used.
+   *
    */
-  template <typename Container> VVGraph(const Container& c, bool check_unique = true)
-  {
-    insert(util::ForAll::make_range(c), check_unique);
-  }
-
-protected:
-  struct single_neighborhood_t;
-
-  /**
-   * Structure maintaining the data for a single neighbor
-   */
-  struct neighbor_t : public EdgeContent {
+  template <typename VertexContent, typename EdgeContent = _EmptyEdgeContent,
+            typename Alloc = std::allocator<VertexContent> >
+  class VVGraph {
+  public:
+    typedef typename Alloc::template rebind<EdgeContent>::other EdgeAlloc;
+    static EdgeAlloc edge_alloc;
+  
+    ///\name Smart pointer types
+    //@{
     /**
-     * Type of the list of outgoing neighbors
+     * Smart pointer on a vertex
      */
-    typedef std::list<neighbor_t> edge_list_t;
-
+    typedef typename Alloc::template rebind<VertexContent>::other VertexAlloc;
+    typedef Vertex<VertexContent, VertexAlloc> vertex_t;
     /**
-     * Constructor
+     * Weak pointer on an edge
      */
-    neighbor_t(const vertex_t& tgt, const EdgeContent& e)
-      : EdgeContent(e)
-      , target(tgt)
-    {
-    }
-
-    neighbor_t(const neighbor_t& copy)
-      : EdgeContent(copy)
-      , target(copy.target)
-    {
-    }
-
-    void clear_edge() {
-      static_cast<EdgeContent&>(*this) = EdgeContent();
-    }
-
-    ~neighbor_t() {
-    }
-
-    neighbor_t& operator=(const neighbor_t& copy)
-    {
-      target = copy.target;
-      static_cast<EdgeContent&>(*this) = static_cast<const EdgeContent&>(copy);
-      return *this;
-    }
-
+    typedef Edge<EdgeContent> edge_t;
     /**
-     * Target of the edge
+     * Weak pointer on a constant edge
+     */
+    typedef Edge<const EdgeContent> const_edge_t;
+    //@}
+  
+    /**
+     * Type of the value of the graph as standard container.
+     */
+    typedef vertex_t value_type;
+  
+    /**
+     * Default constructor
      *
-     * i.e. neighbor itself
+     * Creates an empty VV graph
      */
-    vertex_t target;
-
+    VVGraph() : modified_vertices(false) {}
+  
     /**
-     * Equality of two neighbors/edge
+     * Copy constructor.
      *
-     * A single neighbor is equal to another if the vertex and the content are
-     * the same
+     * Maintains the caches in a valid state
      */
-    bool operator==(const neighbor_t& other) const
+    VVGraph(const VVGraph& copy);
+  
+    /**
+     * Construct from an existing list of vertices
+     *
+     * \param check_unique If false, there must be not be duplicated vertex in the sequence
+     */
+    template <typename Iterator> VVGraph(Iterator begin, Iterator end, bool check_unique = true)
     {
-      return (target == other.target)
-             && (static_cast<const EdgeContent&>(*this) == static_cast<const EdgeContent&>(other));
+      insert(begin, end, check_unique);
     }
-  };
-
-  /**
-   * Type of the list of outgoing neighbors
-   */
-  typedef typename neighbor_t::edge_list_t edge_list_t;
-
-  /**
-   * Type of the list of sources of the in-edges
-   */
-  typedef std::vector<vertex_t> in_edges_t;
-
-  /**
-   * Type of the neighborhood of a vertex
-   */
-  struct single_neighborhood_t {
-
-    single_neighborhood_t()
-      : flagged(0)
+  
+    /**
+     * Construct from an existing list of vertices
+     *
+     * \param check_unique If false, there must be not be duplicated vertex in the sequence
+     */
+    template <typename Container> VVGraph(const Container& c, bool check_unique = true)
     {
+      insert(util::ForAll::make_range(c), check_unique);
     }
-
-    single_neighborhood_t(const single_neighborhood_t& copy)
-      : edges(copy.edges)
-      , in_edges(copy.in_edges)
-      , flagged(copy.flagged)
-    {
-      if(flagged) {
-        for(typename edge_list_t::iterator it = edges.begin(); it != edges.end(); ++it) {
-          if(it->target == *flagged) {
-            flagged = &it->target;
-            break;
-          }
-        }
+  
+  protected:
+    struct single_neighborhood_t;
+  
+    /**
+     * Structure maintaining the data for a single neighbor
+     */
+    struct neighbor_t : public EdgeContent {
+      /**
+       * Type of the list of outgoing neighbors
+       */
+      typedef std::list<neighbor_t> edge_list_t;
+  
+      /**
+       * Constructor
+       */
+      neighbor_t(const vertex_t& tgt, const EdgeContent& e) : EdgeContent(e), target(tgt) {}
+  
+      neighbor_t(const neighbor_t& copy) : EdgeContent(copy) , target(copy.target) {}
+  
+      void clear_edge() {
+        static_cast<EdgeContent&>(*this) = EdgeContent();
       }
-    }
-
+  
+      ~neighbor_t() {}
+  
+      neighbor_t& operator=(const neighbor_t& copy)
+      {
+        target = copy.target;
+        static_cast<EdgeContent&>(*this) = static_cast<const EdgeContent&>(copy);
+        return *this;
+      }
+  
+      /**
+       * Target of the edge
+       *
+       * i.e. neighbor itself
+       */
+      vertex_t target;
+  
+      /**
+       * Equality of two neighbors/edge
+       *
+       * A single neighbor is equal to another if the vertex and the content are
+       * the same
+       */
+      bool operator==(const neighbor_t& other) const
+      {
+        return (target == other.target)
+               && (static_cast<const EdgeContent&>(*this) == static_cast<const EdgeContent&>(other));
+      }
+    };
+  
     /**
-     * List of the outgoing edges
+     * Type of the list of outgoing neighbors
      */
-    edge_list_t edges;
-
+    typedef typename neighbor_t::edge_list_t edge_list_t;
+  
     /**
-     * Set of the sources of the incoming edges
+     * Type of the list of sources of the in-edges
      */
-    in_edges_t in_edges;
-
+    typedef std::vector<vertex_t> in_edges_t;
+  
     /**
-     * Iterator toward the flagged neighbor
+     * Type of the neighborhood of a vertex
      */
-    const vertex_t* flagged;
-
-    single_neighborhood_t& operator=(const single_neighborhood_t& other)
-    {
-      edges = other.edges;
-      in_edges = other.in_edges;
-      if(other.flagged) {
-        for(typename edge_list_t::iterator it = edges.begin(); it != edges.end(); ++it) {
-          if(it->target == *flagged) {
-            flagged = &it->target;
-            break;
+    struct single_neighborhood_t {
+  
+      single_neighborhood_t() : flagged(0) {}
+  
+      single_neighborhood_t(const single_neighborhood_t& copy)
+        : edges(copy.edges), in_edges(copy.in_edges), flagged(copy.flagged)
+      {
+        if(flagged) {
+          for(typename edge_list_t::iterator it = edges.begin(); it != edges.end(); ++it) {
+            if(it->target == *flagged) {
+              flagged = &it->target;
+              break;
+            }
           }
         }
-      } else
-        flagged = 0;
-      return *this;
-    }
-
+      }
+  
+      /**
+       * List of the outgoing edges
+       */
+      edge_list_t edges;
+  
+      /**
+       * Set of the sources of the incoming edges
+       */
+      in_edges_t in_edges;
+  
+      /**
+       * Iterator toward the flagged neighbor
+       */
+      const vertex_t* flagged;
+  
+      single_neighborhood_t& operator=(const single_neighborhood_t& other)
+      {
+        edges = other.edges;
+        in_edges = other.in_edges;
+        if(other.flagged) {
+          for(typename edge_list_t::iterator it = edges.begin(); it != edges.end(); ++it) {
+            if(it->target == *flagged) {
+              flagged = &it->target;
+              break;
+            }
+          }
+        } else
+          flagged = 0;
+        return *this;
+      }
+  
+      /**
+       * Equality of two neighborhood
+       *
+       * Only the outgoing edges are compared!
+       */
+      bool operator==(const single_neighborhood_t& other) const {
+        return edges == other.edges;
+      }
+    };
+  
+  public:
+    struct NeighborhoodPair {
+  protected:
+      NeighborhoodPair(const vertex_t& v) : vertex(v) {}
+  
+      NeighborhoodPair(const NeighborhoodPair& copy)
+        : vertex(copy.vertex), single_neighborhood(copy.single_neighborhood) {}
+  
+  public:
+      NeighborhoodPair* copy() const
+      {
+        NeighborhoodPair* np = np_alloc.allocate(1);
+        ::new (np) NeighborhoodPair(*this);
+        return np;
+      }
+  
+      static NeighborhoodPair* New(const vertex_t& v)
+      {
+        NeighborhoodPair* np = np_alloc.allocate(1);
+        ::new (np) NeighborhoodPair(v);
+        return np;
+      }
+  
+      static void Delete(NeighborhoodPair* np)
+      {
+        if(np) {
+          np->~NeighborhoodPair();
+          np_alloc.deallocate(np, 1);
+        }
+      }
+  
+      vertex_t vertex;
+      single_neighborhood_t single_neighborhood;
+    };
+  
+    typedef typename Alloc::template rebind<NeighborhoodPair>::other NPAlloc;
+    static NPAlloc np_alloc;
+  
+    // typedef std::map<vertex_t, single_neighborhood_t> neighborhood_t;
     /**
-     * Equality of two neighborhood
+     * Type of the list of vertexes, together with the neighborhood
+     */
+    typedef std::vector<NeighborhoodPair*> neighborhood_t;
+  
+    /**
+     * Type of the fast-search map
+     */
+    typedef std::unordered_map<vertex_t, NeighborhoodPair*> lookup_t;
+  
+    /**
+     * Shortcut for the value_type of the neighborhood
+     */
+    typedef typename neighborhood_t::value_type neighborhood_value_type;
+  
+    /**
+     * Type of a size
+     */
+    typedef typename neighborhood_t::size_type size_type;
+  
+  ///\name Iterators
+  //@{
+  /**
+   * Iterator on the vertexes
+   */
+  #ifdef _MSC_VER
+    typedef const vertex_t typename std::iterator_traits<typename neighborhood_t::iterator>::value_type::*
+      msvc_bug_workaround_t;
+  
+    typedef util::SelectMemberPointerIterator<typename neighborhood_t::iterator, const vertex_t,
+                                              reinterpret_cast<msvc_bug_workaround_t>(&neighborhood_value_type::first)>
+      iterator;
+    /**
+     * Constant iterator on the vertexes
+     */
+    typedef util::SelectMemberPointerIterator<typename neighborhood_t::const_iterator, const vertex_t,
+                                              reinterpret_cast<msvc_bug_workaround_t>(&neighborhood_value_type::vertex)>
+      const_iterator;
+  #else
+    typedef util::SelectMemberPointerIterator<typename neighborhood_t::iterator, const vertex_t,
+                                              &NeighborhoodPair::vertex> iterator;
+    /**
+     * Constant iterator on the vertexes
+     */
+    typedef util::SelectMemberPointerIterator<typename neighborhood_t::const_iterator, const vertex_t,
+                                              &NeighborhoodPair::vertex> const_iterator;
+  #endif
+  
+    /**
+     * Iterator on the neighbors of a vertex
+     */
+    typedef util::SelectMemberIterator<typename edge_list_t::iterator, vertex_t, &neighbor_t::target> neighbor_iterator;
+    /**
+     * Range of the neighbors of a vertex. The \c first element of the pair is an
+     * iterator on the beginning of the range, the \c second element is the
+     * past-the-end iterator.
+     */
+    typedef std::pair<neighbor_iterator, neighbor_iterator> neighbor_iterator_pair;
+  
+    /**
+     * Iterator used to iterate over the neighbors, but specifying the
+     * starting point
+     */
+    typedef util::CircIterator<neighbor_iterator> circ_neighbor_iterator;
+  
+    /**
+     * Range of circular iterators
+     */
+    typedef std::pair<circ_neighbor_iterator, circ_neighbor_iterator> circ_neighbor_iterator_pair;
+  
+    /**
+     * Iterator on the incoming neighbors of a vertex.
      *
-     * Only the outgoing edges are compared!
+     * An incoming neighbor is a source vertex of an edge whose target is the
+     * current vertex.
      */
-    bool operator==(const single_neighborhood_t& other) const {
-      return edges == other.edges;
-    }
-  };
-
-public:
-  struct NeighborhoodPair {
-protected:
-    NeighborhoodPair(const vertex_t& v)
-      : vertex(v)
+    typedef typename in_edges_t::iterator ineighbor_iterator;
+    typedef typename in_edges_t::const_iterator const_ineighbor_iterator;
+  
+    /**
+     * Range of the incoming neighbors of a vertex. The \c first element of the
+     * pair is an iterator on the beginning of the range, the \c second element
+     * is the past-the-end iterator.
+     *
+     * \see ineighbor_iterator
+     */
+    typedef std::pair<ineighbor_iterator, ineighbor_iterator> ineighbor_iterator_pair;
+    typedef std::pair<const_ineighbor_iterator, const_ineighbor_iterator> const_ineighbor_iterator_pair;
+  
+    /**
+     * Constant iterator on the neighbors of a vertex
+     */
+    typedef util::SelectMemberIterator<typename edge_list_t::const_iterator, const vertex_t, &neighbor_t::target>
+      const_neighbor_iterator;
+    /**
+     * Constant range of the neighbors of a vertex. The \c first element of the
+     * pair is a constant iterator on the beginning of the range, the \c second
+     * element is the past-the-end constant iterator.
+     */
+    typedef std::pair<const_neighbor_iterator, const_neighbor_iterator> const_neighbor_iterator_pair;
+  
+    /**
+     * Iterator used to iterate over the neighbors, but spcifying the
+     * starting point
+     */
+    typedef util::CircIterator<const_neighbor_iterator> const_circ_neighbor_iterator;
+  
+    /**
+     * Range of circular iterators
+     */
+    typedef std::pair<const_circ_neighbor_iterator, const_circ_neighbor_iterator> const_circ_neighbor_iterator_pair;
+  
+    //@}
+  
+    ///\name Vertex set edition methods
+    //@{
+  
+    /**
+     * Remove a vertex from the graph.
+     *
+     * \param v vertex to erase
+     *
+     * \returns 1 if the vertex was erased, 0 else.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // Add vertices to S
+     * vertex v = S.any();
+     * S.erase(v); // Remove a vertex of S
+     * \endcode
+     */
+    size_type erase(const vertex_t& v);
+  
+    /**
+     * Insert a new vertex in the graph.
+     *
+     * \returns An iterator on the inserted vertex.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * vertex v; // Create a vertex
+     * S.insert(v); // Insert it in the graph
+     * \endcode
+     */
+    iterator insert(const vertex_t& v);
+  
+    //@}
+  
+    ///\name Vertex set lookup methods
+    //@{
+  
+    /**
+     * Return a vertex from the graph.
+     *
+     * \returns A vertex of the graph, or a null vertex if the graph is empty.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // Add vertices in S
+     * const vertex& v = S.any(); // Get a vertex in S
+     * \endcode
+     */
+    const vertex_t& any() const;
+  
+    /**
+     * Return the element of index \c idx.
+     *
+     * \note This is a convenience function whose complexity if O(idx)
+     *
+     * \returns The element \c idx position after the first one (using
+     * iterators)
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // Fill in S
+     * size_t i = 0, selected = 0;
+     * forall(const vertex& v, S)
+     * {
+     *   if(condition(v))
+     *   {
+     *     selected = i;
+     *     break;
+     *   }
+     *   ++i;
+     * }
+     * // ...
+     * const vertex& v = S[selected]; // Work with the vertex previously selected
+     * \endcode
+     * This construct is useful is case you need to refer to your vertices by
+     * 32bits numbers. It is true if you use selection with OpenGL for
+     * example.
+     */
+    const vertex_t& operator[](size_type idx) const;
+  
+    /**
+     * Test if \c v is in the graph.
+     *
+     * \returns \c true is \c v is in the graph.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * vertex v;
+     * S.insert(v);
+     * assert(S.contains(v));
+     * \endcode
+     */
+    bool contains(const vertex_t& v) const;
+  
+    /**
+     * Get a reference on the vertex in the graph
+     *
+     * If the vertex do not exist in the graph, the function returns a null
+     * vertex.
+     *
+     * \note This function is useful if you obtained the vertex not from this
+     * graph but will use it intensively.
+     *
+     * Example:
+     * \code
+     * vvgraph S1, S2;
+     * // Initialize S1 and S2 with the same vertices but different neighborhood
+     * forall(const vertex& v1, S1)
+     * {
+     *   const vertex& v2 = S2.reference(v1);
+     *   // Use v2 in S2 and v1 in v1 for speed optimizatioN
+     * }
+     * \endcode
+     */
+    const vertex_t& reference(vertex_t v) const
     {
+      const NeighborhoodPair* found = this->findVertex(v);
+      if(found)
+        return found->vertex;
+      return vertex_t::null;     // vertex_t(0);
     }
-
-    NeighborhoodPair(const NeighborhoodPair& copy)
-      : vertex(copy.vertex)
-      , single_neighborhood(copy.single_neighborhood)
-    {
+  
+    /**
+     * Return the number of vertexes on the graph
+     */
+    size_type size() const {
+      return neighborhood.size();
     }
-
-public:
-    NeighborhoodPair* copy() const
-    {
-      NeighborhoodPair* np = np_alloc.allocate(1);
-      ::new (np) NeighborhoodPair(*this);
-      return np;
+  
+    /**
+     * Test if there is any vertex in the graph
+     */
+    bool empty() const {
+      return neighborhood.empty();
     }
-
-    static NeighborhoodPair* New(const vertex_t& v)
+  
+    //@}
+  
+    ///\name Neighborhood lookup methods
+    //@{
+  
+    /**
+     * Return a vertex in the neighborhood of \c v.
+     *
+     * \returns A vertex in the neighborhood of \c v, or a null vertex if \c v is
+     * not in the graph or \c v has no neighborhood.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * forall(const vertex& v, S)
+     * {
+     *   const vertex& n = S.anyIn(v);
+     *   if(n)
+     *   {
+     *     edge e = S.edge(v,n); // e exist !
+     *   }
+     * }
+     * \endcode
+     */
+    const vertex_t& anyIn(const vertex_t& v) const;
+  
+    /**
+     * Returns the number of neighbors of \c v.
+     *
+     * If \c v is not in the graph, the behavior is undefined.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   size_t nb_neighbors = S.valence(v); // Number of neighbors of v in S
+     *   // ...
+     * }
+     * \endcode
+     */
+    size_type valence(const vertex_t& v) const;
+  
+    /**
+     * Test if a vertex has a neighbor.
+     *
+     * Returns false if it does. If a vertex is not in the graph, it is
+     * considered as having no neighbor. In the same way, the null vertex has
+     * no neighbors.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(cnst vertex& v, S)
+     * {
+     *   if(!S.empty(v))
+     *   {
+     *      const vertex& n = S.anyIn(v);
+     *      // Working with n a neighbor of v
+     *   }
+     * }
+     * \endcode
+     */
+    bool empty(const vertex_t& v) const;
+  
+    /**
+     * Returns any incoming neighbor of \c v.
+     *
+     * \returns A vertex in the incoming neighborhood of \c v, or a null
+     * vertex if \c v is not in the graph or \c v has no incoming neighbor.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& n, S)
+     * {
+     *   const vertex& v = S.iAnyIn(v);
+     *   if(v)
+     *   {
+     *     edge e = S.edge(v, n);
+     *     // Work with e the edge from v to n
+     *   }
+     * }
+     * \endcode
+     */
+    const vertex_t& iAnyIn(const vertex_t& v) const;
+  
+    /**
+     * Returns the number of incoming neighbors of \c v
+     *
+     * The incoming neighbors are the set of vertexes with on edge ending on
+     * \c v.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& n, S)
+     * {
+     *    size_t nb_ineighbors = S.iValence(n);
+     *    // nb_ineighbors is the number of vertices source of an edge toward n
+     * }
+     * \endcode
+     */
+    size_type iValence(const vertex_t& v) const;
+  
+    /**
+     * Test if a vertex has an incoming neighbor.
+     *
+     * Returns false if it does. If a vertex is not in the graph, it is
+     * considered as having no incoming neighbor. In the same way, the null
+     * vertex has no incoming neighbors.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& n, S)
+     * {
+     *   if(!S.iEmpty(n))
+     *   {
+     *     const vertex& v = S.iAnyIn(n);
+     *     edge e = S.edge(v,n); // It exists !
+     *   }
+     * }
+     * \endcode
+     */
+    bool iEmpty(const vertex_t& v) const;
+  
+    /**
+     * Returns the nth vertex after \c neighbor in the neighborhood of \c v.
+     *
+     * \returns The vertex found or a null vertex if there is any problem.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   forall(const vertex& n, S.neighbors(v))
+     *   {
+     *     const vertex& m, S.nextTo(v);
+     *     // m is the vertex after n in v
+     *   }
+     * }
+     * \endcode
+     */
+    const vertex_t& nextTo(const vertex_t& v, const vertex_t& neighbor, unsigned int n = 1) const;
+  
+    /**
+     * Returns the nth vertex before ref in the neighborhood of v.
+     *
+     * If ref is not in the neighborhood of v, return a null vertex.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   forall(const vertex& n, S.neighbors(v))
+     *   {
+     *     const vertex& m, S.prevTo(v);
+     *     // m is the vertex before n in v
+     *   }
+     * }
+     * \endcode
+     */
+    const vertex_t& prevTo(const vertex_t& v, const vertex_t& ref, unsigned int n = 1) const;
+  
+    /**
+     * Returns the edge from \c src to \c tgt.
+     *
+     * If the edge does not exists, returns a null edge.
+     *
+     * Example:
+     * \code
+     * struct VertexContent {};
+     * struct EdgeContent { int a; }
+     * typedef graph::VVGraph<VertexContent,EdgeContent> vvgraph;
+     * typedef vvgraph::vertex_t vertex;
+     * typedef vvgraph::edge_t edge;
+     * // ...
+     *
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   forall(const vertex& n, S.neighbors(v))
+     *   {
+     *     edge e = S.edge(v,n);
+     *     e->a = 10;
+     *   }
+     * }
+     * \endcode
+     */
+    edge_t edge(const vertex_t& src, const vertex_t& tgt);
+  
+    /**
+     * Returns the edge from \c src to \c tgt.
+     *
+     * If the edge does not exists, returns a null edge.
+     *
+     * Example:
+     * \code
+     * struct VertexContent {};
+     * struct EdgeContent { int a; }
+     * typedef graph::VVGraph<VertexContent,EdgeContent> vvgraph;
+     * typedef vvgraph::vertex_t vertex;
+     * typedef vvgraph::edge_t edge;
+     * typedef vvgraph::const_edge_t const_edge;
+     * // ...
+     *
+     * void fct(const vvgraph& S)
+     * {
+     *   forall(const vertex& v, S)
+     *   {
+     *     forall(const vertex& n, S.neighbors(v))
+     *     {
+     *       const_edge e = S.edge(v,n);
+     *       cout << e->a << endl; // Here e->a cannot be modified
+     *     }
+     *   }
+     * }
+     * \endcode
+     */
+    const_edge_t edge(const vertex_t& src, const vertex_t& tgt) const;
+  
+    /**
+     * Flag a neighbor for quick retrieval
+     *
+     * \return true if the vertex has been correctly flagged
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // Initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   forall(const vertex& n, S.neighbors(v))
+     *   {
+     *     if(condition(v,n))
+     *     {
+     *       S.flag(v,n);
+     *       break;
+     *     }
+     *   }
+     * }
+     * // ...
+     * forall(const vertex& v, S)
+     * {
+     *   const vertex& n = S.flagged(v);
+     *   if(n) // If a neighbor has been flagged
+     *   {
+     *     // Work with the flagged neighbor
+     *   }
+     * }
+     * \endcode
+     */
+    bool flag(const vertex_t& src, const vertex_t& neighbor);
+  
+    /**
+     * Return the flagged neighbor or a null vertex is no neighbor have been flagged.
+     *
+     * \see VVGraph::flag(const vertex_t&, const vertex_t&)
+     */
+    const vertex_t& flagged(const vertex_t& src) const;
+  
+    /**
+     * Return the constant range of neighbors of \c v
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   forall(const vertex& n, S.neighbors(v))
+     *   {
+     *     // n is a neighbor of v
+     *   }
+     * }
+     * \endcode
+     */
+    const_neighbor_iterator_pair neighbors(const vertex_t& v) const;
+    /**
+     * Return the range of neighbors of \c v
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   forall(const vertex& n, S.neighbors(v))
+     *   {
+     *     // n is a neighbor of v
+     *   }
+     * }
+     * \endcode
+     */
+    neighbor_iterator_pair neighbors(const vertex_t& v);
+  
+    /**
+     * Return the range of neighbors of \c v, starting at \c n
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& m, S.neighbors(v,n))
+     * {
+     *   // m is a neighbor of v
+     *   // on the first loop, m == n
+     * }
+     * \endcode
+     */
+    circ_neighbor_iterator_pair neighbors(const vertex_t& v, const vertex_t& n);
+  
+    /**
+     * Return the range of neighbors of \c v, starting at \c n
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& m, S.neighbors(v,n))
+     * {
+     *   // m is a neighbor of v
+     *   // on the first loop, m == n
+     * }
+     * \endcode
+     */
+    const_circ_neighbor_iterator_pair neighbors(const vertex_t& v, const vertex_t& n) const;
+  
+    /**
+     * Return the range of incoming neighbors of \c v.
+     *
+     * Iterating over iNeighbors will go through all the vertexes having an edge
+     * toward \c v.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& n, S)
+     * {
+     *   forall(const vertex& v, S.iNeighbors(v))
+     *   {
+     *     // n is a neighbor of v
+     *   }
+     * }
+     * \endcode
+     */
+    ineighbor_iterator_pair iNeighbors(const vertex_t& v);
+  
+    /**
+     * Return the range of incoming neighbors of \c v.
+     *
+     * Iterating over iNeighbors will go through all the vertexes having an edge
+     * toward \c v.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // initialize S
+     * forall(const vertex& n, S)
+     * {
+     *   forall(const vertex& v, S.iNeighbors(v))
+     *   {
+     *     // n is a neighbor of v
+     *   }
+     * }
+     * \endcode
+     */
+    const_ineighbor_iterator_pair iNeighbors(const vertex_t& v) const;
+  
+    /**
+     * Return the source vertex of the edge
+     *
+     * Example:
+     * \code
+     * void fct(edge e, const vvgraph& S)
+     * {
+     *   const vertex& src = S.source(e);
+     *   const vertex& tgt = S.target(e);
+     *   // Work with the vertices
+     * }
+     * \endcode
+     */
+    const vertex_t& source(const edge_t& edge) const
     {
-      NeighborhoodPair* np = np_alloc.allocate(1);
-      ::new (np) NeighborhoodPair(v);
-      return np;
+      const NeighborhoodPair* found = this->findVertex(vertex_t(edge.source()));
+      if(found)
+        return found->vertex;
+      return vertex_t::null;     // vertex_t(0);
     }
-
-    static void Delete(NeighborhoodPair* np)
+  
+    /**
+     * Return the target vertex of the edge
+     *
+     * Example:
+     * \code
+     * void fct(edge e, const vvgraph& S)
+     * {
+     *   const vertex& src = S.source(e);
+     *   const vertex& tgt = S.target(e);
+     *   // Work with the vertices
+     * }
+     * \endcode
+     */
+    const vertex_t& target(const edge_t& edge) const
     {
-      if(np) {
-        np->~NeighborhoodPair();
-        np_alloc.deallocate(np, 1);
-      }
+      const NeighborhoodPair* found = this->findVertex(vertex_t(edge.target()));
+      if(found)
+        return found->vertex;
+      return vertex_t::null;     // vertex_t(0);
     }
-
-    vertex_t vertex;
-    single_neighborhood_t single_neighborhood;
-  };
-
-  typedef typename Alloc::template rebind<NeighborhoodPair>::other NPAlloc;
-  static NPAlloc np_alloc;
-
-  // typedef std::map<vertex_t, single_neighborhood_t> neighborhood_t;
-  /**
-   * Type of the list of vertexes, together with the neighborhood
-   */
-  typedef std::vector<NeighborhoodPair*> neighborhood_t;
-
-  /**
-   * Type of the fast-search map
-   */
-  typedef std::unordered_map<vertex_t, NeighborhoodPair*> lookup_t;
-
-  /**
-   * Shortcut for the value_type of the neighborhood
-   */
-  typedef typename neighborhood_t::value_type neighborhood_value_type;
-
-  /**
-   * Type of a size
-   */
-  typedef typename neighborhood_t::size_type size_type;
-
-///\name Iterators
-//@{
-/**
- * Iterator on the vertexes
- */
-#ifdef _MSC_VER
-  typedef const vertex_t typename std::iterator_traits<typename neighborhood_t::iterator>::value_type::*
-    msvc_bug_workaround_t;
-
-  typedef util::SelectMemberPointerIterator<typename neighborhood_t::iterator, const vertex_t,
-                                            reinterpret_cast<msvc_bug_workaround_t>(&neighborhood_value_type::first)>
-    iterator;
-  /**
-   * Constant iterator on the vertexes
-   */
-  typedef util::SelectMemberPointerIterator<typename neighborhood_t::const_iterator, const vertex_t,
-                                            reinterpret_cast<msvc_bug_workaround_t>(&neighborhood_value_type::vertex)>
-    const_iterator;
-#else
-  typedef util::SelectMemberPointerIterator<typename neighborhood_t::iterator, const vertex_t,
-                                            &NeighborhoodPair::vertex> iterator;
-  /**
-   * Constant iterator on the vertexes
-   */
-  typedef util::SelectMemberPointerIterator<typename neighborhood_t::const_iterator, const vertex_t,
-                                            &NeighborhoodPair::vertex> const_iterator;
-#endif
-
-  /**
-   * Iterator on the neighbors of a vertex
-   */
-  typedef util::SelectMemberIterator<typename edge_list_t::iterator, vertex_t, &neighbor_t::target> neighbor_iterator;
-  /**
-   * Range of the neighbors of a vertex. The \c first element of the pair is an
-   * iterator on the beginning of the range, the \c second element is the
-   * past-the-end iterator.
-   */
-  typedef std::pair<neighbor_iterator, neighbor_iterator> neighbor_iterator_pair;
-
-  /**
-   * Iterator used to iterate over the neighbors, but specifying the
-   * starting point
-   */
-  typedef util::CircIterator<neighbor_iterator> circ_neighbor_iterator;
-
-  /**
-   * Range of circular iterators
-   */
-  typedef std::pair<circ_neighbor_iterator, circ_neighbor_iterator> circ_neighbor_iterator_pair;
-
-  /**
-   * Iterator on the incoming neighbors of a vertex.
-   *
-   * An incoming neighbor is a source vertex of an edge whose target is the
-   * current vertex.
-   */
-  typedef typename in_edges_t::iterator ineighbor_iterator;
-  typedef typename in_edges_t::const_iterator const_ineighbor_iterator;
-
-  /**
-   * Range of the incoming neighbors of a vertex. The \c first element of the
-   * pair is an iterator on the beginning of the range, the \c second element
-   * is the past-the-end iterator.
-   *
-   * \see ineighbor_iterator
-   */
-  typedef std::pair<ineighbor_iterator, ineighbor_iterator> ineighbor_iterator_pair;
-  typedef std::pair<const_ineighbor_iterator, const_ineighbor_iterator> const_ineighbor_iterator_pair;
-
-  /**
-   * Constant iterator on the neighbors of a vertex
-   */
-  typedef util::SelectMemberIterator<typename edge_list_t::const_iterator, const vertex_t, &neighbor_t::target>
-    const_neighbor_iterator;
-  /**
-   * Constant range of the neighbors of a vertex. The \c first element of the
-   * pair is a constant iterator on the beginning of the range, the \c second
-   * element is the past-the-end constant iterator.
-   */
-  typedef std::pair<const_neighbor_iterator, const_neighbor_iterator> const_neighbor_iterator_pair;
-
-  /**
-   * Iterator used to iterate over the neighbors, but spcifying the
-   * starting point
-   */
-  typedef util::CircIterator<const_neighbor_iterator> const_circ_neighbor_iterator;
-
-  /**
-   * Range of circular iterators
-   */
-  typedef std::pair<const_circ_neighbor_iterator, const_circ_neighbor_iterator> const_circ_neighbor_iterator_pair;
-
-  //@}
-
-  ///\name Vertex set edition methods
-  //@{
-
-  /**
-   * Remove a vertex from the graph.
-   *
-   * \param v vertex to erase
-   *
-   * \returns 1 if the vertex was erased, 0 else.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Add vertices to S
-   * vertex v = S.any();
-   * S.erase(v); // Remove a vertex of S
-   * \endcode
-   */
-  size_type erase(const vertex_t& v);
-
-  /**
-   * Insert a new vertex in the graph.
-   *
-   * \returns An iterator on the inserted vertex.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * vertex v; // Create a vertex
-   * S.insert(v); // Insert it in the graph
-   * \endcode
-   */
-  iterator insert(const vertex_t& v);
-
-  //@}
-
-  ///\name Vertex set lookup methods
-  //@{
-
-  /**
-   * Return a vertex from the graph.
-   *
-   * \returns A vertex of the graph, or a null vertex if the graph is empty.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Add vertices in S
-   * const vertex& v = S.any(); // Get a vertex in S
-   * \endcode
-   */
-  const vertex_t& any() const;
-
-  /**
-   * Return the element of index \c idx.
-   *
-   * \note This is a convenience function whose complexity if O(idx)
-   *
-   * \returns The element \c idx position after the first one (using
-   * iterators)
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Fill in S
-   * size_t i = 0, selected = 0;
-   * forall(const vertex& v, S)
-   * {
-   *   if(condition(v))
-   *   {
-   *     selected = i;
-   *     break;
-   *   }
-   *   ++i;
-   * }
-   * // ...
-   * const vertex& v = S[selected]; // Work with the vertex previously selected
-   * \endcode
-   * This construct is useful is case you need to refer to your vertices by
-   * 32bits numbers. It is true if you use selection with OpenGL for
-   * example.
-   */
-  const vertex_t& operator[](size_type idx) const;
-
-  /**
-   * Test if \c v is in the graph.
-   *
-   * \returns \c true is \c v is in the graph.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * vertex v;
-   * S.insert(v);
-   * assert(S.contains(v));
-   * \endcode
-   */
-  bool contains(const vertex_t& v) const;
-
-  /**
-   * Get a reference on the vertex in the graph
-   *
-   * If the vertex do not exist in the graph, the function returns a null
-   * vertex.
-   *
-   * \note This function is useful if you obtained the vertex not from this
-   * graph but will use it intensively.
-   *
-   * Example:
-   * \code
-   * vvgraph S1, S2;
-   * // Initialize S1 and S2 with the same vertices but different neighborhood
-   * forall(const vertex& v1, S1)
-   * {
-   *   const vertex& v2 = S2.reference(v1);
-   *   // Use v2 in S2 and v1 in v1 for speed optimizatioN
-   * }
-   * \endcode
-   */
-  const vertex_t& reference(vertex_t v) const
-  {
-    const NeighborhoodPair* found = this->findVertex(v);
-    if(found)
-      return found->vertex;
-    return vertex_t::null;     // vertex_t(0);
-  }
-
-  /**
-   * Return the number of vertexes on the graph
-   */
-  size_type size() const {
-    return neighborhood.size();
-  }
-
-  /**
-   * Test if there is any vertex in the graph
-   */
-  bool empty() const {
-    return neighborhood.empty();
-  }
-
-  //@}
-
-  ///\name Neighborhood lookup methods
-  //@{
-
-  /**
-   * Return a vertex in the neighborhood of \c v.
-   *
-   * \returns A vertex in the neighborhood of \c v, or a null vertex if \c v is
-   * not in the graph or \c v has no neighborhood.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * forall(const vertex& v, S)
-   * {
-   *   const vertex& n = S.anyIn(v);
-   *   if(n)
-   *   {
-   *     edge e = S.edge(v,n); // e exist !
-   *   }
-   * }
-   * \endcode
-   */
-  const vertex_t& anyIn(const vertex_t& v) const;
-
-  /**
-   * Returns the number of neighbors of \c v.
-   *
-   * If \c v is not in the graph, the behavior is undefined.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   size_t nb_neighbors = S.valence(v); // Number of neighbors of v in S
-   *   // ...
-   * }
-   * \endcode
-   */
-  size_type valence(const vertex_t& v) const;
-
-  /**
-   * Test if a vertex has a neighbor.
-   *
-   * Returns false if it does. If a vertex is not in the graph, it is
-   * considered as having no neighbor. In the same way, the null vertex has
-   * no neighbors.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(cnst vertex& v, S)
-   * {
-   *   if(!S.empty(v))
-   *   {
-   *      const vertex& n = S.anyIn(v);
-   *      // Working with n a neighbor of v
-   *   }
-   * }
-   * \endcode
-   */
-  bool empty(const vertex_t& v) const;
-
-  /**
-   * Returns any incoming neighbor of \c v.
-   *
-   * \returns A vertex in the incoming neighborhood of \c v, or a null
-   * vertex if \c v is not in the graph or \c v has no incoming neighbor.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& n, S)
-   * {
-   *   const vertex& v = S.iAnyIn(v);
-   *   if(v)
-   *   {
-   *     edge e = S.edge(v, n);
-   *     // Work with e the edge from v to n
-   *   }
-   * }
-   * \endcode
-   */
-  const vertex_t& iAnyIn(const vertex_t& v) const;
-
-  /**
-   * Returns the number of incoming neighbors of \c v
-   *
-   * The incoming neighbors are the set of vertexes with on edge ending on
-   * \c v.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& n, S)
-   * {
-   *    size_t nb_ineighbors = S.iValence(n);
-   *    // nb_ineighbors is the number of vertices source of an edge toward n
-   * }
-   * \endcode
-   */
-  size_type iValence(const vertex_t& v) const;
-
-  /**
-   * Test if a vertex has an incoming neighbor.
-   *
-   * Returns false if it does. If a vertex is not in the graph, it is
-   * considered as having no incoming neighbor. In the same way, the null
-   * vertex has no incoming neighbors.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& n, S)
-   * {
-   *   if(!S.iEmpty(n))
-   *   {
-   *     const vertex& v = S.iAnyIn(n);
-   *     edge e = S.edge(v,n); // It exists !
-   *   }
-   * }
-   * \endcode
-   */
-  bool iEmpty(const vertex_t& v) const;
-
-  /**
-   * Returns the nth vertex after \c neighbor in the neighborhood of \c v.
-   *
-   * \returns The vertex found or a null vertex if there is any problem.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   forall(const vertex& n, S.neighbors(v))
-   *   {
-   *     const vertex& m, S.nextTo(v);
-   *     // m is the vertex after n in v
-   *   }
-   * }
-   * \endcode
-   */
-  const vertex_t& nextTo(const vertex_t& v, const vertex_t& neighbor, unsigned int n = 1) const;
-
-  /**
-   * Returns the nth vertex before ref in the neighborhood of v.
-   *
-   * If ref is not in the neighborhood of v, return a null vertex.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   forall(const vertex& n, S.neighbors(v))
-   *   {
-   *     const vertex& m, S.prevTo(v);
-   *     // m is the vertex before n in v
-   *   }
-   * }
-   * \endcode
-   */
-  const vertex_t& prevTo(const vertex_t& v, const vertex_t& ref, unsigned int n = 1) const;
-
-  /**
-   * Returns the edge from \c src to \c tgt.
-   *
-   * If the edge does not exists, returns a null edge.
-   *
-   * Example:
-   * \code
-   * struct VertexContent {};
-   * struct EdgeContent { int a; }
-   * typedef graph::VVGraph<VertexContent,EdgeContent> vvgraph;
-   * typedef vvgraph::vertex_t vertex;
-   * typedef vvgraph::edge_t edge;
-   * // ...
-   *
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   forall(const vertex& n, S.neighbors(v))
-   *   {
-   *     edge e = S.edge(v,n);
-   *     e->a = 10;
-   *   }
-   * }
-   * \endcode
-   */
-  edge_t edge(const vertex_t& src, const vertex_t& tgt);
-
-  /**
-   * Returns the arc (i.e. undirected edge) between \c src and \c tgt.
-   *
-   * When the arc is destroyed, the values of both half-edge are
-   * synchronized.
-   *
-   * Example:
-   * \code
-   * struct VertexContent();
-   * struct EdgeContent {int a; }
-   * typedef graph::VVGraph<VertexContent,EdgeContent> vvgraph;
-   * typedef vvgraph::vertex_t vertex;
-   * typedef vvgraph::arc_t arc;
-   * typedef vvgraph::edge_t edge;
-   * // ...
-   *
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   forall(const vertex& n, S.neighbors(v))
-   *     if(v<n)
-   *       S.arc(v,n)->a = 5
-   *  }
-   * \endcode
-   * At the end, all edges have a value of 5 for \c a, even though we
-   * applied the function to only half the edges.
-   */
-  arc_t arc(const vertex_t& src, const vertex_t& tgt);
-
-  /**
-   * Returns the edge from \c src to \c tgt.
-   *
-   * If the edge does not exists, returns a null edge.
-   *
-   * Example:
-   * \code
-   * struct VertexContent {};
-   * struct EdgeContent { int a; }
-   * typedef graph::VVGraph<VertexContent,EdgeContent> vvgraph;
-   * typedef vvgraph::vertex_t vertex;
-   * typedef vvgraph::edge_t edge;
-   * typedef vvgraph::const_edge_t const_edge;
-   * // ...
-   *
-   * void fct(const vvgraph& S)
-   * {
-   *   forall(const vertex& v, S)
-   *   {
-   *     forall(const vertex& n, S.neighbors(v))
-   *     {
-   *       const_edge e = S.edge(v,n);
-   *       cout << e->a << endl; // Here e->a cannot be modified
-   *     }
-   *   }
-   * }
-   * \endcode
-   */
-  const_edge_t edge(const vertex_t& src, const vertex_t& tgt) const;
-
-  /**
-   * Flag a neighbor for quick retrieval
-   *
-   * \return true if the vertex has been correctly flagged
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   forall(const vertex& n, S.neighbors(v))
-   *   {
-   *     if(condition(v,n))
-   *     {
-   *       S.flag(v,n);
-   *       break;
-   *     }
-   *   }
-   * }
-   * // ...
-   * forall(const vertex& v, S)
-   * {
-   *   const vertex& n = S.flagged(v);
-   *   if(n) // If a neighbor has been flagged
-   *   {
-   *     // Work with the flagged neighbor
-   *   }
-   * }
-   * \endcode
-   */
-  bool flag(const vertex_t& src, const vertex_t& neighbor);
-
-  /**
-   * Return the flagged neighbor or a null vertex is no neighbor have been flagged.
-   *
-   * \see VVGraph::flag(const vertex_t&, const vertex_t&)
-   */
-  const vertex_t& flagged(const vertex_t& src) const;
-
-  /**
-   * Return the constant range of neighbors of \c v
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   forall(const vertex& n, S.neighbors(v))
-   *   {
-   *     // n is a neighbor of v
-   *   }
-   * }
-   * \endcode
-   */
-  const_neighbor_iterator_pair neighbors(const vertex_t& v) const;
-  /**
-   * Return the range of neighbors of \c v
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   forall(const vertex& n, S.neighbors(v))
-   *   {
-   *     // n is a neighbor of v
-   *   }
-   * }
-   * \endcode
-   */
-  neighbor_iterator_pair neighbors(const vertex_t& v);
-
-  /**
-   * Return the range of neighbors of \c v, starting at \c n
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& m, S.neighbors(v,n))
-   * {
-   *   // m is a neighbor of v
-   *   // on the first loop, m == n
-   * }
-   * \endcode
-   */
-  circ_neighbor_iterator_pair neighbors(const vertex_t& v, const vertex_t& n);
-
-  /**
-   * Return the range of neighbors of \c v, starting at \c n
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& m, S.neighbors(v,n))
-   * {
-   *   // m is a neighbor of v
-   *   // on the first loop, m == n
-   * }
-   * \endcode
-   */
-  const_circ_neighbor_iterator_pair neighbors(const vertex_t& v, const vertex_t& n) const;
-
-  /**
-   * Return the range of incoming neighbors of \c v.
-   *
-   * Iterating over iNeighbors will go through all the vertexes having an edge
-   * toward \c v.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& n, S)
-   * {
-   *   forall(const vertex& v, S.iNeighbors(v))
-   *   {
-   *     // n is a neighbor of v
-   *   }
-   * }
-   * \endcode
-   */
-  ineighbor_iterator_pair iNeighbors(const vertex_t& v);
-
-  /**
-   * Return the range of incoming neighbors of \c v.
-   *
-   * Iterating over iNeighbors will go through all the vertexes having an edge
-   * toward \c v.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // initialize S
-   * forall(const vertex& n, S)
-   * {
-   *   forall(const vertex& v, S.iNeighbors(v))
-   *   {
-   *     // n is a neighbor of v
-   *   }
-   * }
-   * \endcode
-   */
-  const_ineighbor_iterator_pair iNeighbors(const vertex_t& v) const;
-
-  /**
-   * Return the source vertex of the edge
-   *
-   * Example:
-   * \code
-   * void fct(edge e, const vvgraph& S)
-   * {
-   *   const vertex& src = S.source(e);
-   *   const vertex& tgt = S.target(e);
-   *   // Work with the vertices
-   * }
-   * \endcode
-   */
-  const vertex_t& source(const edge_t& edge) const
-  {
-    const NeighborhoodPair* found = this->findVertex(vertex_t(edge.source()));
-    if(found)
-      return found->vertex;
-    return vertex_t::null;     // vertex_t(0);
-  }
-
-  const vertex_t& source(const arc_t& arc) const
-  {
-    const NeighborhoodPair* found = this->findVertex(vertex_t(arc.source()));
-    if(found)
-      return found->vertex;
-    return vertex_t::null;     // vertex_t(0);
-  }
-
-  /**
-   * Return the target vertex of the edge
-   *
-   * Example:
-   * \code
-   * void fct(edge e, const vvgraph& S)
-   * {
-   *   const vertex& src = S.source(e);
-   *   const vertex& tgt = S.target(e);
-   *   // Work with the vertices
-   * }
-   * \endcode
-   */
-  const vertex_t& target(const edge_t& edge) const
-  {
-    const NeighborhoodPair* found = this->findVertex(vertex_t(edge.target()));
-    if(found)
-      return found->vertex;
-    return vertex_t::null;     // vertex_t(0);
-  }
-
-  const vertex_t& target(const arc_t& arc) const
-  {
-    const NeighborhoodPair* found = this->findVertex(vertex_t(arc.target()));
-    if(found)
-      return found->vertex;
-    return vertex_t::null;     // vertex_t(0);
-  }
-
-  //@}
-
-  ///\name Neighborhood edition methods
-  //@{
-  /**
-   * Erase the edge from \c src to \c tgt.
-   *
-   * \returns True if successful.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   forall(const vertex& n, S.neighbors(v))
-   *   {
-   *     if(condition)
-   *     {
-   *       S.eraseEdge(v,n);
-   *       break; // The iteration must not continue after the neighborhood has been altered
-   *     }
-   *   }
-   * }
-   * \endcode
-   */
-  size_type eraseEdge(const vertex_t& src, const vertex_t& tgt);
-
-  /**
-   * Replace a vertex by another in a neighborhood.
-   *
-   * \param[in] v Vertex whose neighborhood is changed.
-   * \param[in] neighbor Vertex to replace
-   * \param[in] new_neighbor Vertex replacing \c neighbor
-   *
-   * If \c new_neighbor is already in the neighborhood of \c v, then the
-   * operation fails and nothing is changed.
-   *
-   * \returns The edge between \c v and \c new_neighbor or a null edge if
-   * anything goes wrong.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   forall(const vertex& n, S.neighbors(v))
-   *   {
-   *     if(condition)
-   *     {
-   *       vertex n1;
-   *       S.replace(v,n,n1); // Now n1 is where n was in v
-   *       break; // The iteration must not continue after the neighborhood has been altered
-   *     }
-   *   }
-   * }
-   * \endcode
-   */
-  edge_t replace(const vertex_t& v, const vertex_t& neighbor, const vertex_t& new_neighbor);
-
-  /**
-   * Insert neighbor in the neighborhood of v after reference.
-   *
-   * If \c new_neighbor is already in the neighborhood of \c v, the insertion
-   * fails.
-   *
-   * \returns The just created edge if everything succeed, or a null edge.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   forall(const vertex& n, S.neighbors(v))
-   *   {
-   *     if(condition)
-   *     {
-   *       vertex n1;
-   *       S.spliceAfter(v,n,n1); // Now n1 is after n in v
-   *       break; // The iteration must not continue after the neighborhood has been altered
-   *     }
-   *   }
-   * }
-   * \endcode
-   */
-  edge_t spliceAfter(const vertex_t& v, const vertex_t& neighbor, const vertex_t& new_neighbor);
-
-  /**
-   * Insert neighbor in the neighborhood of v before reference.
-   *
-   * If \c new_neighbor is already in the neighborhood of \c v, the insertion
-   * fails.
-   *
-   * \returns The just created edge if everything succeed, or a null edge.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   forall(const vertex& n, S.neighbors(v))
-   *   {
-   *     if(condition)
-   *     {
-   *       vertex n1;
-   *       S.spliceBefore(v,n,n1); // Now n1 is before n in v
-   *       break; // The iteration must not continue after the neighborhood has been altered
-   *     }
-   *   }
-   * }
-   * \endcode
-   */
-  edge_t spliceBefore(const vertex_t& v, const vertex_t& neighbor, const vertex_t& new_neighbor);
-
-  /**
-   * Insert a new edge in the graph, without ordering.
-   *
-   * If \c new_neighbor is already in the neighborhood of \c v, the insertion
-   * fails.
-   *
-   * \returns The just created edge if everything succeed, or a null edge.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * vertex v1, v2;
-   * S.insert(v1);
-   * S.insert(v2);
-   * S.insertEdge(v1, v2); // Insert the edge between v1 and v2
-   * S.insertEdge(v2, v1); // Insert the edge between v2 and v1
-   * \endcode
-   */
-  edge_t insertEdge(const vertex_t& src, const vertex_t& tgt);
-
-  /**
-   * Clear the neighborhood of a vertex.
-   *
-   * All edges, to and from \c v will be erased.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   if(condition)
-   *   {
-   *     S.eraseAllEdges(v);
-   *     assert(S.empty(v)); // No outgoing edges
-   *     assert(S.iEmpty(v)); // No incoming edges
-   *   }
-   * }
-   * \endcode
-   */
-  bool eraseAllEdges(const vertex_t& v);
-
-  /**
-   * Clear the outgoing edges of a vertex
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Initialize S
-   * forall(const vertex& v, S)
-   * {
-   *   if(condition)
-   *   {
-   *     S.clear(v);
-   *     assert(S.empty(v));
-   *   }
-   * }
-   * \endcode
-   */
-  bool clear(const vertex_t& v);
-
-  //@}
-
-  ///\name Whole structure methods
-  //@{
-  /**
-   * Copy the graph into another graph
-   */
-  VVGraph& operator=(const VVGraph& other);
-
-  /**
-   * Reverse the order of all the neighbors
-   */
-  VVGraph& reverse();
-
-  /**
-   * Swap the content of both graphs
-   */
-  void swap(VVGraph& other);
-
-  /**
-   * Test equality for the graphs.
-   *
-   * Two graphs are equal if they shared the sames vertices and their
-   * neighborhood are equivalent.
-   *
-   * \note Current implementation do not consider invariance of
-   * neighborhood by rotation.
-   */
-  bool operator==(const VVGraph& other) const;
-
-  /**
-   * Clear the graph.
-   */
-  void clear();
-
-  /**
-   * Clear all the edges in the graph
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Initialize S
-   * vvgraph::size_type s1 = S.size(); // Save the number of vertices
-   * S.eraseAllEdges();
-   * assert(s1 == S.size()); // The number of vertices didn't change
-   * forall(const vertex& v, S)
-   * {
-   *   assert(S.empty(v)); // No neighbor
-   * }
-   * \endcode
-   */
-  void eraseAllEdges();
-
-  /**
-   * Extract the subgraph containing the \p vertexes
-   *
-   * The subgraph is the set of vertexes and the edges whose source and target
-   * are in the extracted vertexes.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Initialize S
-   * std::vector<vertex> to_keep;
-   * // Fill in to_keep with a subset of the vertices of S
-   * vvgraph S1 = S.subgraph(to_keep);
-   * \endcode
-   */
-  template <typename VertexContainer> VVGraph subgraph(const VertexContainer& vertexes) const;
-  //@}
-
-  ///\name STL compatibility methods
-  //@{
-
-  /**
-   * Erase element at position \p pos
-   */
-  void erase(iterator pos);
-
-  /**
-   * Erase the edge pointed to by the iterator.
-   */
-  size_type eraseEdge(const vertex_t& v, neighbor_iterator pos);
-
-  /**
-   * Erase the edge pointed to by the iterator.
-   */
-  size_type eraseEdge(const vertex_t& v, circ_neighbor_iterator pos);
-
-  /**
-   * Insert a new vertex in the graph
-   *
-   * The iterator is ignored ...
-   */
-  iterator insert(iterator pos, const vertex_t& v);
-  /**
-   * Insert all the vertexes from first to last-1 in the graph.
-   */
-  template <typename Iterator> void insert(Iterator first, Iterator last, bool check_unique = true);
-
-  /**
-   * Insert all the vertexes from range.first to range.last-1 in the graph.
-   */
-  template <typename Iterator> void insert(const std::pair<Iterator, Iterator>& range, bool check_unique = true);
-
-  /**
-   * Returns an iterator on the beginning of the set of vertexes of the graph.
-   */
-  iterator begin() {
-    return neighborhood.begin();
-  }
-  /**
-   * Returns an iterator on the end of the set of vertexes of the graph.
-   */
-  iterator end() {
-    return neighborhood.end();
-  }
-
-  /**
-   * Returns an iterator on the beginning of the set of vertexes of the graph.
-   */
-  const_iterator begin() const {
-    return neighborhood.begin();
-  }
-  /**
-   * Returns an iterator on the end of the set of vertexes of the graph.
-   */
-  const_iterator end() const {
-    return neighborhood.end();
-  }
-
-  /**
-   * Store the vertices in a STL container. By default, the cache will be
-   * setup for quick vertex access.
-   *
-   * Example:
-   * \code
-   * vvgraph S;
-   * // Initialize S
-   * std::vector<vertex> vertices;
-   * S.store_vertices(vertices);
-   * forall(const vertex& v, vertices)
-   * {
-   *   // The cache information is used to speed up lookup
-   *   if(condition)
-   *   {
-   *     S.erase(v); // Valid, but do not use v in S after that
-   *   }
-   * }
-   * \endcode
-   */
-  void store_vertices(std::vector<vertex_t>& vertices) const
-  {
-    vertices.resize(this->size(), vertex_t::null);
-    size_t k = 0;
-    for(typename neighborhood_t::const_iterator it = neighborhood.begin(); it != neighborhood.end(); ++it) {
-      const vertex_t& v = it->vertex;
-      vertices[k] = v;
-      ++k;
-    }
-  }
-
-  /**
-   * Find the vertex \c v in the graph.
-   *
-   * \returns An iterator on \c v if found, or end()
-   */
-  // iterator find(const vertex_t& v) { return this->findVertex(v); }
-  /**
-   * Find the vertex \c v in the graph.
-   *
-   * \returns An iterator on \c v if found, or end()
-   */
-  // const_iterator find(const vertex_t& v) const { return this->findVertex(v); }
-
-  /**
-   * Count the number of vertexes \p v in the graph (can be 0 or 1 only)
-   */
-  size_type count(const vertex_t& v) const;
-
-  /**
-   * Find the vertex \c n in the neighborhood of \c v.
-   *
-   * \returns
-   *  - An iterator on \c n in the neighborhood of \c v, if found
-   *  - An iterator on the end of the neighborhood if \c n is not found in \c
-   *  v
-   *  - Otherwise, the result is undefined
-   */
-  neighbor_iterator findIn(const vertex_t& v, const vertex_t& n);
-  /**
-   * Find the vertex \c n in the neighborhood of \c v.
-   *
-   * \returns
-   *  - An iterator on \c n in the neighborhood of \c v, if found
-   *  - An iterator on the end of the neighborhood if \c n is not found in \c
-   *  v
-   *  - Otherwise, the result is undefined
-   */
-  const_neighbor_iterator findIn(const vertex_t& v, const vertex_t& n) const;
-
-  /**
-   * Clear the neighborhood of a vertex.
-   *
-   * All edges, to and from \c *it will be erased.
-   */
-  void eraseAllEdges(iterator it);
-
-  /**
-   * Clear the outgoing edges of a vertex.
-   */
-  void clear(iterator it);
-
-  /**
-   * Reserve space for more vertices
-   */
-  void reserve(size_type s) {
-    neighborhood.reserve(s);
-  }
-
-  //@}
-
-protected:
-  void eraseAllEdges(NeighborhoodPair* it);
-  /**
-   * Type of the result of the search for a vertex in a neighborhood
-   *
-   * This data structure is made such that all edit or lookup operations can
-   * be done from that data structure.
-   */
-  template <class Neighborhood, class Iterator> struct search_result_t {
+  
+    //@}
+  
+    ///\name Neighborhood edition methods
+    //@{
     /**
-     * Default constructor
+     * Erase the edge from \c src to \c tgt.
      *
-     * By default, the search is unsuccessful
+     * \returns True if successful.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // Initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   forall(const vertex& n, S.neighbors(v))
+     *   {
+     *     if(condition)
+     *     {
+     *       S.eraseEdge(v,n);
+     *       break; // The iteration must not continue after the neighborhood has been altered
+     *     }
+     *   }
+     * }
+     * \endcode
      */
-    search_result_t()
-      : found(false)
-      , neighborhood(0)
-    {
+    size_type eraseEdge(const vertex_t& src, const vertex_t& tgt);
+  
+    /**
+     * Replace a vertex by another in a neighborhood.
+     *
+     * \param[in] v Vertex whose neighborhood is changed.
+     * \param[in] neighbor Vertex to replace
+     * \param[in] new_neighbor Vertex replacing \c neighbor
+     *
+     * If \c new_neighbor is already in the neighborhood of \c v, then the
+     * operation fails and nothing is changed.
+     *
+     * \returns The edge between \c v and \c new_neighbor or a null edge if
+     * anything goes wrong.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // Initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   forall(const vertex& n, S.neighbors(v))
+     *   {
+     *     if(condition)
+     *     {
+     *       vertex n1;
+     *       S.replace(v,n,n1); // Now n1 is where n was in v
+     *       break; // The iteration must not continue after the neighborhood has been altered
+     *     }
+     *   }
+     * }
+     * \endcode
+     */
+    edge_t replace(const vertex_t& v, const vertex_t& neighbor, const vertex_t& new_neighbor);
+  
+    /**
+     * Insert neighbor in the neighborhood of v after reference.
+     *
+     * If \c new_neighbor is already in the neighborhood of \c v, the insertion
+     * fails.
+     *
+     * \returns The just created edge if everything succeed, or a null edge.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // Initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   forall(const vertex& n, S.neighbors(v))
+     *   {
+     *     if(condition)
+     *     {
+     *       vertex n1;
+     *       S.spliceAfter(v,n,n1); // Now n1 is after n in v
+     *       break; // The iteration must not continue after the neighborhood has been altered
+     *     }
+     *   }
+     * }
+     * \endcode
+     */
+    edge_t spliceAfter(const vertex_t& v, const vertex_t& neighbor, const vertex_t& new_neighbor);
+  
+    /**
+     * Insert neighbor in the neighborhood of v before reference.
+     *
+     * If \c new_neighbor is already in the neighborhood of \c v, the insertion
+     * fails.
+     *
+     * \returns The just created edge if everything succeed, or a null edge.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // Initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   forall(const vertex& n, S.neighbors(v))
+     *   {
+     *     if(condition)
+     *     {
+     *       vertex n1;
+     *       S.spliceBefore(v,n,n1); // Now n1 is before n in v
+     *       break; // The iteration must not continue after the neighborhood has been altered
+     *     }
+     *   }
+     * }
+     * \endcode
+     */
+    edge_t spliceBefore(const vertex_t& v, const vertex_t& neighbor, const vertex_t& new_neighbor);
+  
+    /**
+     * Insert a new edge in the graph, without ordering.
+     *
+     * If \c new_neighbor is already in the neighborhood of \c v, the insertion
+     * fails.
+     *
+     * \returns The just created edge if everything succeed, or a null edge.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * vertex v1, v2;
+     * S.insert(v1);
+     * S.insert(v2);
+     * S.insertEdge(v1, v2); // Insert the edge between v1 and v2
+     * S.insertEdge(v2, v1); // Insert the edge between v2 and v1
+     * \endcode
+     */
+    edge_t insertEdge(const vertex_t& src, const vertex_t& tgt);
+  
+    /**
+     * Clear the neighborhood of a vertex.
+     *
+     * All edges, to and from \c v will be erased.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // Initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   if(condition)
+     *   {
+     *     S.eraseAllEdges(v);
+     *     assert(S.empty(v)); // No outgoing edges
+     *     assert(S.iEmpty(v)); // No incoming edges
+     *   }
+     * }
+     * \endcode
+     */
+    bool eraseAllEdges(const vertex_t& v);
+  
+    /**
+     * Clear the outgoing edges of a vertex
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // Initialize S
+     * forall(const vertex& v, S)
+     * {
+     *   if(condition)
+     *   {
+     *     S.clear(v);
+     *     assert(S.empty(v));
+     *   }
+     * }
+     * \endcode
+     */
+    bool clear(const vertex_t& v);
+  
+    //@}
+  
+    ///\name Whole structure methods
+    //@{
+    /**
+     * Copy the graph into another graph
+     */
+    VVGraph& operator=(const VVGraph& other);
+  
+    /**
+     * Reverse the order of all the neighbors
+     */
+    VVGraph& reverse();
+  
+    /**
+     * Swap the content of both graphs
+     */
+    void swap(VVGraph& other);
+  
+    /**
+     * Test equality for the graphs.
+     *
+     * Two graphs are equal if they shared the sames vertices and their
+     * neighborhood are equivalent.
+     *
+     * \note Current implementation do not consider invariance of
+     * neighborhood by rotation.
+     */
+    bool operator==(const VVGraph& other) const;
+  
+    /**
+     * Clear the graph.
+     */
+    void clear();
+  
+    /**
+     * Clear all the edges in the graph
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // Initialize S
+     * vvgraph::size_type s1 = S.size(); // Save the number of vertices
+     * S.eraseAllEdges();
+     * assert(s1 == S.size()); // The number of vertices didn't change
+     * forall(const vertex& v, S)
+     * {
+     *   assert(S.empty(v)); // No neighbor
+     * }
+     * \endcode
+     */
+    void eraseAllEdges();
+  
+    /**
+     * Extract the subgraph containing the \p vertexes
+     *
+     * The subgraph is the set of vertexes and the edges whose source and target
+     * are in the extracted vertexes.
+     *
+     * Example:
+     * \code
+     * vvgraph S;
+     * // Initialize S
+     * std::vector<vertex> to_keep;
+     * // Fill in to_keep with a subset of the vertices of S
+     * vvgraph S1 = S.subgraph(to_keep);
+     * \endcode
+     */
+    template <typename VertexContainer> VVGraph subgraph(const VertexContainer& vertexes) const;
+    //@}
+  
+    ///\name STL compatibility methods
+    //@{
+  
+    /**
+     * Erase element at position \p pos
+     */
+    void erase(iterator pos);
+  
+    /**
+     * Erase the edge pointed to by the iterator.
+     */
+    size_type eraseEdge(const vertex_t& v, neighbor_iterator pos);
+  
+    /**
+     * Erase the edge pointed to by the iterator.
+     */
+    size_type eraseEdge(const vertex_t& v, circ_neighbor_iterator pos);
+  
+    /**
+     * Insert a new vertex in the graph
+     *
+     * The iterator is ignored ...
+     */
+    iterator insert(iterator pos, const vertex_t& v);
+    /**
+     * Insert all the vertexes from first to last-1 in the graph.
+     */
+    template <typename Iterator> void insert(Iterator first, Iterator last, bool check_unique = true);
+  
+    /**
+     * Insert all the vertexes from range.first to range.last-1 in the graph.
+     */
+    template <typename Iterator> void insert(const std::pair<Iterator, Iterator>& range, bool check_unique = true);
+  
+    /**
+     * Returns an iterator on the beginning of the set of vertexes of the graph.
+     */
+    iterator begin() {
+      return neighborhood.begin();
     }
-
     /**
-     * Successful constructor
+     * Returns an iterator on the end of the set of vertexes of the graph.
      */
-    search_result_t(Iterator i, Neighborhood* n, bool ok = true)
-      : found(ok)
-      , it(i)
-      , neighborhood(n)
-    {
+    iterator end() {
+      return neighborhood.end();
     }
-
+  
     /**
-     * Copy constructor
+     * Returns an iterator on the beginning of the set of vertexes of the graph.
      */
-    search_result_t(const search_result_t& copy)
-      : found(copy.found)
-      , it(copy.it)
-      , neighborhood(copy.neighborhood)
-    {
+    const_iterator begin() const {
+      return neighborhood.begin();
     }
-
     /**
-     * Convert the object to true if the search is successful
+     * Returns an iterator on the end of the set of vertexes of the graph.
      */
-    operator bool() {
-      return found;
+    const_iterator end() const {
+      return neighborhood.end();
     }
-
+  
     /**
-     * True if the search was completely successful
+     * Count the number of vertexes \p v in the graph (can be 0 or 1 only)
      */
-    bool found;
+    size_type count(const vertex_t& v) const;
+  
     /**
-     * Iterator pointing in the edge list
+     * Find the vertex \c n in the neighborhood of \c v.
+     *
+     * \returns
+     *  - An iterator on \c n in the neighborhood of \c v, if found
+     *  - An iterator on the end of the neighborhood if \c n is not found in \c
+     *  v
+     *  - Otherwise, the result is undefined
      */
-    Iterator it;
+    neighbor_iterator findIn(const vertex_t& v, const vertex_t& n);
     /**
-     * Neighborhood containing the element
+     * Find the vertex \c n in the neighborhood of \c v.
+     *
+     * \returns
+     *  - An iterator on \c n in the neighborhood of \c v, if found
+     *  - An iterator on the end of the neighborhood if \c n is not found in \c
+     *  v
+     *  - Otherwise, the result is undefined
      */
-    Neighborhood* neighborhood;
+    const_neighbor_iterator findIn(const vertex_t& v, const vertex_t& n) const;
+  
+    /**
+     * Clear the neighborhood of a vertex.
+     *
+     * All edges, to and from \c *it will be erased.
+     */
+    void eraseAllEdges(iterator it);
+  
+    /**
+     * Clear the outgoing edges of a vertex.
+     */
+    void clear(iterator it);
+  
+    /**
+     * Reserve space for more vertices
+     */
+    void reserve(size_type s) {
+      neighborhood.reserve(s);
+    }
+  
+    //@}
+  
+  protected:
+    void eraseAllEdges(NeighborhoodPair* it);
+    /**
+     * Type of the result of the search for a vertex in a neighborhood
+     *
+     * This data structure is made such that all edit or lookup operations can
+     * be done from that data structure.
+     */
+    template <class Neighborhood, class Iterator> struct search_result_t {
+      /**
+       * Default constructor
+       *
+       * By default, the search is unsuccessful
+       */
+      search_result_t() : found(false), neighborhood(0) {}
+  
+      /**
+       * Successful constructor
+       */
+      search_result_t(Iterator i, Neighborhood* n, bool ok = true)
+        : found(ok) , it(i), neighborhood(n) {}
+  
+      /**
+       * Copy constructor
+       */
+      search_result_t(const search_result_t& copy)
+        : found(copy.found), it(copy.it), neighborhood(copy.neighborhood) {}
+  
+      /**
+       * Convert the object to true if the search is successful
+       */
+      operator bool() {
+        return found;
+      }
+  
+      /**
+       * True if the search was completely successful
+       */
+      bool found;
+      /**
+       * Iterator pointing in the edge list
+       */
+      Iterator it;
+      /**
+       * Neighborhood containing the element
+       */
+      Neighborhood* neighborhood;
+    };
+  
+    /**
+     * Iterator on the outgoing edges
+     */
+    typedef typename edge_list_t::iterator int_neighbor_iterator;
+    /**
+     * Constant iterator on the outgoing edges
+     */
+    typedef typename edge_list_t::const_iterator int_const_neighbor_iterator;
+  
+    /**
+     * Result of a search in the neighborhood
+     */
+    typedef search_result_t<single_neighborhood_t, int_neighbor_iterator> neighbor_found_t;
+    /**
+     * Constant result of a search in the neighborhood
+     */
+    typedef search_result_t<const single_neighborhood_t, int_const_neighbor_iterator> const_neighbor_found_t;
+  
+    /**
+     * Find a vertex in the graph and returns the iterator on it.
+     *
+     * Goal is to introduce a new optimization. When iterating over the
+     * vertices of the graph, they will cache their own iterator. So accessing
+     * their neighborhood would be constant time.
+     */
+    NeighborhoodPair* findVertex(const vertex_t& v);
+  
+    /**
+     * Constant version of findVertex(const vertex_t&)
+     */
+    const NeighborhoodPair* findVertex(const vertex_t& v) const;
+  
+    /**
+     * Find the iterator for a given neighborhood pair
+     */
+    typename neighborhood_t::iterator findIterator(const NeighborhoodPair* np);
+    typename neighborhood_t::const_iterator findIterator(const NeighborhoodPair* np) const;
+  
+    /**
+     * Find a vertex neighbor in the neighborhood of v.
+     *
+     * If 'v' is in the graph and 'neighbor' is in its neighborhood, the
+     * result is convertible to true, 'neighborhood' points toward the
+     * neighborhood structure and 'it' points toward the neighbor.
+     *
+     * If 'v' is in the graph, but 'neighbor' is not in the neighborhood, the
+     * result is convertible to false, 'neighborhood' points toward the
+     * neighborhood structure and 'it' is neighborhood->edges.end().
+     *
+     * If v is not in the graph, the result is convertible to false and the
+     * address of the stored neighborhood is 0.
+     */
+    neighbor_found_t findInVertex(const vertex_t& v, const vertex_t& neighbor);
+  
+    /**
+     * Constant version of findInVertex(const vertex_t&, const vertex_t&)
+     */
+    const_neighbor_found_t findInVertex(const vertex_t& v, const vertex_t& neighbor) const;
+  
+    /**
+     * Insert v in the in_edges of new_neighbor and return true if the insertion
+     * was actually done, or false if v was already there.
+     */
+    std::pair<ineighbor_iterator, bool> insertInEdge(const vertex_t& v, const vertex_t& new_neighbor);
+  
+    /**
+     * Undo the insertion of an in edge as a roll-back mechanism if the whole
+     * edge insertion fails.
+     */
+    void undoInEdge(const vertex_t& new_neighbor, ineighbor_iterator& it);
+  
+    /**
+     * Main data structure containing everything
+     */
+    neighborhood_t neighborhood;
+  
+    /**
+     * Hash map to optimise look-up
+     */
+    lookup_t lookup;
+  
+    /**
+     * If true, the vertex list has been modified
+     */
+    bool modified_vertices;
   };
-
-  /**
-   * Iterator on the outgoing edges
-   */
-  typedef typename edge_list_t::iterator int_neighbor_iterator;
-  /**
-   * Constant iterator on the outgoing edges
-   */
-  typedef typename edge_list_t::const_iterator int_const_neighbor_iterator;
-
-  /**
-   * Result of a search in the neighborhood
-   */
-  typedef search_result_t<single_neighborhood_t, int_neighbor_iterator> neighbor_found_t;
-  /**
-   * Constant result of a search in the neighborhood
-   */
-  typedef search_result_t<const single_neighborhood_t, int_const_neighbor_iterator> const_neighbor_found_t;
-
-  /**
-   * Find a vertex in the graph and returns the iterator on it.
-   *
-   * Goal is to introduce a new optimization. When iterating over the
-   * vertices of the graph, they will cache their own iterator. So accessing
-   * their neighborhood would be constant time.
-   */
-  NeighborhoodPair* findVertex(const vertex_t& v);
-
-  /**
-   * Constant version of findVertex(const vertex_t&)
-   */
-  const NeighborhoodPair* findVertex(const vertex_t& v) const;
-
-  /**
-   * Find the iterator for a given neighborhood pair
-   */
-  typename neighborhood_t::iterator findIterator(const NeighborhoodPair* np);
-  typename neighborhood_t::const_iterator findIterator(const NeighborhoodPair* np) const;
-
-  /**
-   * Find a vertex neighbor in the neighborhood of v.
-   *
-   * If 'v' is in the graph and 'neighbor' is in its neighborhood, the
-   * result is convertible to true, 'neighborhood' points toward the
-   * neighborhood structure and 'it' points toward the neighbor.
-   *
-   * If 'v' is in the graph, but 'neighbor' is not in the neighborhood, the
-   * result is convertible to false, 'neighborhood' points toward the
-   * neighborhood structure and 'it' is neighborhood->edges.end().
-   *
-   * If v is not in the graph, the result is convertible to false and the
-   * address of the stored neighborhood is 0.
-   */
-  neighbor_found_t findInVertex(const vertex_t& v, const vertex_t& neighbor);
-
-  /**
-   * Constant version of findInVertex(const vertex_t&, const vertex_t&)
-   */
-  const_neighbor_found_t findInVertex(const vertex_t& v, const vertex_t& neighbor) const;
-
-  /**
-   * Insert v in the in_edges of new_neighbor and return true if the insertion
-   * was actually done, or false if v was already there.
-   */
-  std::pair<ineighbor_iterator, bool> insertInEdge(const vertex_t& v, const vertex_t& new_neighbor);
-
-  /**
-   * Undo the insertion of an in edge as a roll-back mechanism if the whole
-   * edge insertion fails.
-   */
-  void undoInEdge(const vertex_t& new_neighbor, ineighbor_iterator& it);
-
-  /**
-   * Main data structure containing everything
-   */
-  neighborhood_t neighborhood;
-
-  /**
-   * Hash map to optimise look-up
-   */
-  lookup_t lookup;
-
-  /**
-   * If true, the vertex list has been modified
-   */
-  bool modified_vertices;
-};
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::EdgeAlloc VVGraph<VertexContent, EdgeContent, Alloc>::edge_alloc;
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::NPAlloc VVGraph<VertexContent, EdgeContent, Alloc>::np_alloc;
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-void VVGraph<VertexContent, EdgeContent, Alloc>::clear()
-{
-  typename neighborhood_t::iterator it;
-  for(it = neighborhood.begin(); it != neighborhood.end(); ++it) {
-    NeighborhoodPair::Delete(*it);
-    *it = 0;
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::EdgeAlloc VVGraph<VertexContent, EdgeContent, Alloc>::edge_alloc;
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::NPAlloc VVGraph<VertexContent, EdgeContent, Alloc>::np_alloc;
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  void VVGraph<VertexContent, EdgeContent, Alloc>::clear()
+  {
+    typename neighborhood_t::iterator it;
+    for(it = neighborhood.begin(); it != neighborhood.end(); ++it) {
+      NeighborhoodPair::Delete(*it);
+      *it = 0;
+    }
+    neighborhood.clear();
+    lookup.clear();
   }
-  neighborhood.clear();
-  lookup.clear();
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-void VVGraph<VertexContent, EdgeContent, Alloc>::erase(iterator it)
-{
-  eraseAllEdges(it);
-  lookup.erase(*it);
-  NeighborhoodPair::Delete(*it.base());
-  *it.base() = neighborhood.back();
-  neighborhood.pop_back();
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
-VVGraph<VertexContent, EdgeContent, Alloc>::erase(const vertex_t& v)
-{
-  if(eraseAllEdges(v)) {
-    NeighborhoodPair* np = lookup[v];
-    lookup.erase(v);
-    typename neighborhood_t::iterator it = this->findIterator(np);
-    NeighborhoodPair::Delete(np);
-    *it = neighborhood.back();
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  void VVGraph<VertexContent, EdgeContent, Alloc>::erase(iterator it)
+  {
+    eraseAllEdges(it);
+    lookup.erase(*it);
+    NeighborhoodPair::Delete(*it.base());
+    *it.base() = neighborhood.back();
     neighborhood.pop_back();
-    return 1;
   }
-  return 0;
-}
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-void VVGraph<VertexContent, EdgeContent, Alloc>::eraseAllEdges()
-{
-  for(typename neighborhood_t::iterator it = neighborhood.begin(); it != neighborhood.end(); ++it) {
-    it->single_neighborhood.edges.clear();
-    it->single_neighborhood.in_edges.clear();
-    it->single_neighborhood.flagged = 0;
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
+  VVGraph<VertexContent, EdgeContent, Alloc>::erase(const vertex_t& v)
+  {
+    if(eraseAllEdges(v)) {
+      NeighborhoodPair* np = lookup[v];
+      lookup.erase(v);
+      typename neighborhood_t::iterator it = this->findIterator(np);
+      NeighborhoodPair::Delete(np);
+      *it = neighborhood.back();
+      neighborhood.pop_back();
+      return 1;
+    }
+    return 0;
   }
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-bool VVGraph<VertexContent, EdgeContent, Alloc>::eraseAllEdges(const vertex_t& v)
-{
-  NeighborhoodPair* it_found = this->findVertex(v);
-  if(it_found) {
-    eraseAllEdges(it_found);
-    return true;
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  void VVGraph<VertexContent, EdgeContent, Alloc>::eraseAllEdges()
+  {
+    for(typename neighborhood_t::iterator it = neighborhood.begin(); it != neighborhood.end(); ++it) {
+      it->single_neighborhood.edges.clear();
+      it->single_neighborhood.in_edges.clear();
+      it->single_neighborhood.flagged = 0;
+    }
   }
-  return false;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-void VVGraph<VertexContent, EdgeContent, Alloc>::eraseAllEdges(NeighborhoodPair* np)
-{
-  const vertex_t& v = np->vertex;
-  for(typename edge_list_t::iterator it_el = np->single_neighborhood.edges.begin();
-      it_el != np->single_neighborhood.edges.end(); ++it_el) {
-    in_edges_t& ie = lookup[it_el->target]->single_neighborhood.in_edges;
-    typename in_edges_t::iterator it_found = std::find(ie.begin(), ie.end(), v);
-    ie.erase(it_found);
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  bool VVGraph<VertexContent, EdgeContent, Alloc>::eraseAllEdges(const vertex_t& v)
+  {
+    NeighborhoodPair* it_found = this->findVertex(v);
+    if(it_found) {
+      eraseAllEdges(it_found);
+      return true;
+    }
+    return false;
   }
-  np->single_neighborhood.edges.clear();
-  np->single_neighborhood.flagged = 0;
-  // Remove the incoming edges
-  in_edges_t& in_edges = np->single_neighborhood.in_edges;
-  for(typename in_edges_t::iterator it = in_edges.begin(); it != in_edges.end(); ++it) {
-    neighbor_found_t found = findInVertex(*it, v);
-    found.neighborhood->edges.erase(found.it);
-    if(found.neighborhood->flagged && *found.neighborhood->flagged == v)
-      found.neighborhood->flagged = 0;
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  void VVGraph<VertexContent, EdgeContent, Alloc>::eraseAllEdges(NeighborhoodPair* np)
+  {
+    const vertex_t& v = np->vertex;
+    for(typename edge_list_t::iterator it_el = np->single_neighborhood.edges.begin();
+        it_el != np->single_neighborhood.edges.end(); ++it_el) {
+      in_edges_t& ie = lookup[it_el->target]->single_neighborhood.in_edges;
+      typename in_edges_t::iterator it_found = std::find(ie.begin(), ie.end(), v);
+      ie.erase(it_found);
+    }
+    np->single_neighborhood.edges.clear();
+    np->single_neighborhood.flagged = 0;
+    // Remove the incoming edges
+    in_edges_t& in_edges = np->single_neighborhood.in_edges;
+    for(typename in_edges_t::iterator it = in_edges.begin(); it != in_edges.end(); ++it) {
+      neighbor_found_t found = findInVertex(*it, v);
+      found.neighborhood->edges.erase(found.it);
+      if(found.neighborhood->flagged && *found.neighborhood->flagged == v)
+        found.neighborhood->flagged = 0;
+    }
+    in_edges.clear();
   }
-  in_edges.clear();
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-void VVGraph<VertexContent, EdgeContent, Alloc>::eraseAllEdges(iterator it_found)
-{
-  eraseAllEdges(*it_found.base());
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-bool VVGraph<VertexContent, EdgeContent, Alloc>::clear(const vertex_t& v)
-{
-  typename neighborhood_t::iterator it_found = this->findVertex(v);
-  if(it_found != neighborhood.end()) {
-    clear(it_found);
-    return true;
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  void VVGraph<VertexContent, EdgeContent, Alloc>::eraseAllEdges(iterator it_found)
+  {
+    eraseAllEdges(*it_found.base());
   }
-  return false;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-void VVGraph<VertexContent, EdgeContent, Alloc>::clear(iterator it)
-{
-  const vertex_t& v = *it;
-  for(typename edge_list_t::iterator it_el = it.base()->single_neighborhood.edges.begin();
-      it_el != it.base()->single_neighborhood.edges.end(); ++it_el) {
-    typename neighborhood_t::iterator it_found = this->findVertex(it_el->target);
-    in_edges_t& ie = it_found->single_neighborhood.in_edges;
-    typename in_edges_t::iterator it_found2 = std::find(ie.begin(), ie.end(), v);
-    ie.erase(it_found2);
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  bool VVGraph<VertexContent, EdgeContent, Alloc>::clear(const vertex_t& v)
+  {
+    typename neighborhood_t::iterator it_found = this->findVertex(v);
+    if(it_found != neighborhood.end()) {
+      clear(it_found);
+      return true;
+    }
+    return false;
   }
-  it.base()->single_neighborhood.edges.clear();
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
-VVGraph<VertexContent, EdgeContent, Alloc>::count(const vertex_t& v) const
-{
-  return lookup.count(v);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::iterator
-VVGraph<VertexContent, EdgeContent, Alloc>::insert(const vertex_t& v)
-{
-  typename lookup_t::iterator it_found = lookup.find(v);
-  if(it_found == lookup.end()) {
-    NeighborhoodPair* np = NeighborhoodPair::New(v);
-    neighborhood.push_back(np);
-    lookup[v] = np;
-    iterator it = neighborhood.end();
-    --it;
-    return it;
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  void VVGraph<VertexContent, EdgeContent, Alloc>::clear(iterator it)
+  {
+    const vertex_t& v = *it;
+    for(typename edge_list_t::iterator it_el = it.base()->single_neighborhood.edges.begin();
+        it_el != it.base()->single_neighborhood.edges.end(); ++it_el) {
+      typename neighborhood_t::iterator it_found = this->findVertex(it_el->target);
+      in_edges_t& ie = it_found->single_neighborhood.in_edges;
+      typename in_edges_t::iterator it_found2 = std::find(ie.begin(), ie.end(), v);
+      ie.erase(it_found2);
+    }
+    it.base()->single_neighborhood.edges.clear();
   }
-  return findIterator(it_found->second);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::iterator
-VVGraph<VertexContent, EdgeContent, Alloc>::insert(iterator, const vertex_t& v)
-{
-  return this->insert(v);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-template <typename Iterator>
-void VVGraph<VertexContent, EdgeContent, Alloc>::insert(const std::pair<Iterator, Iterator>& range, bool check_unique)
-{
-  insert(range.first, range.second, check_unique);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-template <typename Iterator>
-void VVGraph<VertexContent, EdgeContent, Alloc>::insert(Iterator first, Iterator last, bool check_unique)
-{
-  if(check_unique) {
-    for(Iterator it = first; it != last; ++it) {
-      insert(*it);
-    }
-  } else {
-    for(Iterator it = first; it != last; ++it) {
-      NeighborhoodPair* np = NeighborhoodPair::New(*it);
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
+  VVGraph<VertexContent, EdgeContent, Alloc>::count(const vertex_t& v) const
+  {
+    return lookup.count(v);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::iterator
+  VVGraph<VertexContent, EdgeContent, Alloc>::insert(const vertex_t& v)
+  {
+    typename lookup_t::iterator it_found = lookup.find(v);
+    if(it_found == lookup.end()) {
+      NeighborhoodPair* np = NeighborhoodPair::New(v);
       neighborhood.push_back(np);
-      lookup[*it] = np;
+      lookup[v] = np;
+      iterator it = neighborhood.end();
+      --it;
+      return it;
     }
+    return findIterator(it_found->second);
   }
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t&
-VVGraph<VertexContent, EdgeContent, Alloc>::any() const
-{
-  if(neighborhood.empty())
-    return vertex_t::null;
-  return *begin();
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t& VVGraph<VertexContent, EdgeContent, Alloc>::
-operator[](size_type idx) const
-{
-  typename neighborhood_t::const_iterator it = neighborhood.begin();
-  std::advance(it, idx);
-  return (*it)->vertex;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t&
-VVGraph<VertexContent, EdgeContent, Alloc>::anyIn(const vertex_t &v) const
-{
-  if(v.isNull())
-    return vertex_t::null;     // vertex_t(0);
-  const NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found || it_found->single_neighborhood.edges.empty())
-    return vertex_t::null;     // vertex_t(0);
-  const edge_list_t& lst = it_found->single_neighborhood.edges;
-  return lst.front().target;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
-VVGraph<VertexContent, EdgeContent, Alloc>::valence(const vertex_t& v) const
-{
-  if(v.isNull())
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::iterator
+  VVGraph<VertexContent, EdgeContent, Alloc>::insert(iterator, const vertex_t& v)
+  {
+    return this->insert(v);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  template <typename Iterator>
+  void VVGraph<VertexContent, EdgeContent, Alloc>::insert(const std::pair<Iterator, Iterator>& range, bool check_unique)
+  {
+    insert(range.first, range.second, check_unique);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  template <typename Iterator>
+  void VVGraph<VertexContent, EdgeContent, Alloc>::insert(Iterator first, Iterator last, bool check_unique)
+  {
+    if(check_unique) {
+      for(Iterator it = first; it != last; ++it) {
+        insert(*it);
+      }
+    } else {
+      for(Iterator it = first; it != last; ++it) {
+        NeighborhoodPair* np = NeighborhoodPair::New(*it);
+        neighborhood.push_back(np);
+        lookup[*it] = np;
+      }
+    }
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t&
+  VVGraph<VertexContent, EdgeContent, Alloc>::any() const
+  {
+    if(neighborhood.empty())
+      return vertex_t::null;
+    return *begin();
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t& VVGraph<VertexContent, EdgeContent, Alloc>::
+  operator[](size_type idx) const
+  {
+    typename neighborhood_t::const_iterator it = neighborhood.begin();
+    std::advance(it, idx);
+    return (*it)->vertex;
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t&
+  VVGraph<VertexContent, EdgeContent, Alloc>::anyIn(const vertex_t &v) const
+  {
+    if(v.isNull())
+      return vertex_t::null;     // vertex_t(0);
+    const NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found || it_found->single_neighborhood.edges.empty())
+      return vertex_t::null;     // vertex_t(0);
+    const edge_list_t& lst = it_found->single_neighborhood.edges;
+    return lst.front().target;
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
+  VVGraph<VertexContent, EdgeContent, Alloc>::valence(const vertex_t& v) const
+  {
+    if(v.isNull())
+      return 0;
+    const NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found)
+      return 0;
+    return it_found->single_neighborhood.edges.size();
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  bool VVGraph<VertexContent, EdgeContent, Alloc>::empty(const vertex_t& v) const
+  {
+    if(v.isNull())
+      return true;
+    const NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found)
+      return true;
+    return it_found->single_neighborhood.edges.empty();
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t&
+  VVGraph<VertexContent, EdgeContent, Alloc>::iAnyIn(const vertex_t &v) const
+  {
+    if(v.isNull())
+      return vertex_t::null;     // vertex_t(0);
+    const NeighborhoodPair& it_found = this->findVertex(v);
+    if(not it_found || it_found->single_neighborhood.in_edges.empty())
+      return vertex_t::null;     // vertex_t(0);
+    const in_edges_t& lst = it_found->single_neighborhood.in_edges;
+    return *lst.begin();
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
+  VVGraph<VertexContent, EdgeContent, Alloc>::iValence(const vertex_t& v) const
+  {
+    if(v.isNull())
+      return 0;
+    const NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found)
+      return 0;
+    return it_found->single_neighborhood.in_edges.size();
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  bool VVGraph<VertexContent, EdgeContent, Alloc>::iEmpty(const vertex_t& v) const
+  {
+    if(v.isNull())
+      return true;
+    const NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found)
+      return true;
+    return it_found->single_neighborhood.in_edges.empty();
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::neighborhood_t::iterator
+  VVGraph<VertexContent, EdgeContent, Alloc>::findIterator(const NeighborhoodPair* np)
+  {
+    return std::find(neighborhood.begin(), neighborhood.end(), np);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::neighborhood_t::const_iterator
+  VVGraph<VertexContent, EdgeContent, Alloc>::findIterator(const NeighborhoodPair* np) const
+  {
+    return std::find(neighborhood.begin(), neighborhood.end(), np);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::NeighborhoodPair*
+  VVGraph<VertexContent, EdgeContent, Alloc>::findVertex(const vertex_t &v)
+  {
+    typename lookup_t::const_iterator it_found = lookup.find(v);
+    if(it_found != lookup.end())
+      return it_found->second;
     return 0;
-  const NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found)
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  const typename VVGraph<VertexContent, EdgeContent, Alloc>::NeighborhoodPair*
+  VVGraph<VertexContent, EdgeContent, Alloc>::findVertex(const vertex_t &v) const
+  {
+    typename lookup_t::const_iterator it_found = lookup.find(v);
+    if(it_found != lookup.end())
+      return it_found->second;
     return 0;
-  return it_found->single_neighborhood.edges.size();
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-bool VVGraph<VertexContent, EdgeContent, Alloc>::empty(const vertex_t& v) const
-{
-  if(v.isNull())
-    return true;
-  const NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found)
-    return true;
-  return it_found->single_neighborhood.edges.empty();
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t&
-VVGraph<VertexContent, EdgeContent, Alloc>::iAnyIn(const vertex_t &v) const
-{
-  if(v.isNull())
-    return vertex_t::null;     // vertex_t(0);
-  const NeighborhoodPair& it_found = this->findVertex(v);
-  if(not it_found || it_found->single_neighborhood.in_edges.empty())
-    return vertex_t::null;     // vertex_t(0);
-  const in_edges_t& lst = it_found->single_neighborhood.in_edges;
-  return *lst.begin();
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
-VVGraph<VertexContent, EdgeContent, Alloc>::iValence(const vertex_t& v) const
-{
-  if(v.isNull())
-    return 0;
-  const NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found)
-    return 0;
-  return it_found->single_neighborhood.in_edges.size();
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-bool VVGraph<VertexContent, EdgeContent, Alloc>::iEmpty(const vertex_t& v) const
-{
-  if(v.isNull())
-    return true;
-  const NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found)
-    return true;
-  return it_found->single_neighborhood.in_edges.empty();
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::neighborhood_t::iterator
-VVGraph<VertexContent, EdgeContent, Alloc>::findIterator(const NeighborhoodPair* np)
-{
-  return std::find(neighborhood.begin(), neighborhood.end(), np);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::neighborhood_t::const_iterator
-VVGraph<VertexContent, EdgeContent, Alloc>::findIterator(const NeighborhoodPair* np) const
-{
-  return std::find(neighborhood.begin(), neighborhood.end(), np);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::NeighborhoodPair*
-VVGraph<VertexContent, EdgeContent, Alloc>::findVertex(const vertex_t &v)
-{
-  typename lookup_t::const_iterator it_found = lookup.find(v);
-  if(it_found != lookup.end())
-    return it_found->second;
-  return 0;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-const typename VVGraph<VertexContent, EdgeContent, Alloc>::NeighborhoodPair*
-VVGraph<VertexContent, EdgeContent, Alloc>::findVertex(const vertex_t &v) const
-{
-  typename lookup_t::const_iterator it_found = lookup.find(v);
-  if(it_found != lookup.end())
-    return it_found->second;
-  return 0;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::neighbor_found_t
-VVGraph<VertexContent, EdgeContent, Alloc>::findInVertex(const vertex_t& v, const vertex_t& n)
-{
-  if(v.isNull() || n.isNull() || v == n)
-    return neighbor_found_t();
-  NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found)
-    return neighbor_found_t();
-  edge_list_t& lst = it_found->single_neighborhood.edges;
-  single_neighborhood_t* neighborhood = &it_found->single_neighborhood;
-  for(typename edge_list_t::iterator it = lst.begin(); it != lst.end(); ++it) {
-    if(it->target == n) {
-      return neighbor_found_t(it, neighborhood);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::neighbor_found_t
+  VVGraph<VertexContent, EdgeContent, Alloc>::findInVertex(const vertex_t& v, const vertex_t& n)
+  {
+    if(v.isNull() || n.isNull() || v == n)
+      return neighbor_found_t();
+    NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found)
+      return neighbor_found_t();
+    edge_list_t& lst = it_found->single_neighborhood.edges;
+    single_neighborhood_t* neighborhood = &it_found->single_neighborhood;
+    for(typename edge_list_t::iterator it = lst.begin(); it != lst.end(); ++it) {
+      if(it->target == n) {
+        return neighbor_found_t(it, neighborhood);
+      }
     }
+    return neighbor_found_t(lst.end(), neighborhood, false);
   }
-  return neighbor_found_t(lst.end(), neighborhood, false);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::const_neighbor_found_t
-VVGraph<VertexContent, EdgeContent, Alloc>::findInVertex(const vertex_t& v, const vertex_t& n) const
-{
-  if(v.isNull() || n.isNull() || v == n)
-    return const_neighbor_found_t();
-  const NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found)
-    return const_neighbor_found_t();
-  const edge_list_t& lst = it_found->single_neighborhood.edges;
-  const single_neighborhood_t* neighborhood = &it_found->single_neighborhood;
-  for(typename edge_list_t::const_iterator it = lst.begin(); it != lst.end(); ++it) {
-    if(it->target == n) {
-      return const_neighbor_found_t(it, neighborhood);
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::const_neighbor_found_t
+  VVGraph<VertexContent, EdgeContent, Alloc>::findInVertex(const vertex_t& v, const vertex_t& n) const
+  {
+    if(v.isNull() || n.isNull() || v == n)
+      return const_neighbor_found_t();
+    const NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found)
+      return const_neighbor_found_t();
+    const edge_list_t& lst = it_found->single_neighborhood.edges;
+    const single_neighborhood_t* neighborhood = &it_found->single_neighborhood;
+    for(typename edge_list_t::const_iterator it = lst.begin(); it != lst.end(); ++it) {
+      if(it->target == n) {
+        return const_neighbor_found_t(it, neighborhood);
+      }
     }
+    return const_neighbor_found_t(lst.end(), neighborhood, false);
   }
-  return const_neighbor_found_t(lst.end(), neighborhood, false);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::neighbor_iterator
-VVGraph<VertexContent, EdgeContent, Alloc>::findIn(const vertex_t& v, const vertex_t& n)
-{
-  neighbor_found_t found = this->findInVertex(v, n);
-  if(found.neighborhood)
-    return neighbor_iterator(found.it);
-  return neighbor_iterator();
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::const_neighbor_iterator
-VVGraph<VertexContent, EdgeContent, Alloc>::findIn(const vertex_t& v, const vertex_t& n) const
-{
-  const_neighbor_found_t found = this->findInVertex(v, n);
-  if(found.neighborhood)
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::neighbor_iterator
+  VVGraph<VertexContent, EdgeContent, Alloc>::findIn(const vertex_t& v, const vertex_t& n)
+  {
+    neighbor_found_t found = this->findInVertex(v, n);
+    if(found.neighborhood)
+      return neighbor_iterator(found.it);
+    return neighbor_iterator();
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::const_neighbor_iterator
+  VVGraph<VertexContent, EdgeContent, Alloc>::findIn(const vertex_t& v, const vertex_t& n) const
+  {
+    const_neighbor_found_t found = this->findInVertex(v, n);
+    if(found.neighborhood)
+      return const_neighbor_iterator(found.it);
     return const_neighbor_iterator(found.it);
-  return const_neighbor_iterator(found.it);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
-VVGraph<VertexContent, EdgeContent, Alloc>::eraseEdge(const vertex_t& v, neighbor_iterator pos)
-{
-  NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found)
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
+  VVGraph<VertexContent, EdgeContent, Alloc>::eraseEdge(const vertex_t& v, neighbor_iterator pos)
+  {
+    NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found)
+      return 0;
+    const vertex_t& n = *pos;
+    NeighborhoodPair* it_found2 = this->findVertex(n);
+    if(not it_found2)
+      return 0;
+    in_edges_t& ie = it_found2->single_neighborhood.in_edges;
+    typename in_edges_t::iterator it_found_ie = std::find(ie.begin(), ie.end(), v);
+    if(it_found_ie != ie.end()) {
+      ie.erase(it_found_ie);
+      typename edge_list_t::iterator it = pos.base();
+      it_found->single_neighborhood.edges.erase(it);
+      return 1;
+    }
     return 0;
-  const vertex_t& n = *pos;
-  NeighborhoodPair* it_found2 = this->findVertex(n);
-  if(not it_found2)
-    return 0;
-  in_edges_t& ie = it_found2->single_neighborhood.in_edges;
-  typename in_edges_t::iterator it_found_ie = std::find(ie.begin(), ie.end(), v);
-  if(it_found_ie != ie.end()) {
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
+  VVGraph<VertexContent, EdgeContent, Alloc>::eraseEdge(const vertex_t& v, circ_neighbor_iterator pos)
+  {
+    return eraseEdge(v, pos.base());
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
+  VVGraph<VertexContent, EdgeContent, Alloc>::eraseEdge(const vertex_t& v, const vertex_t& n)
+  {
+    neighbor_found_t found = this->findInVertex(v, n);
+    if(!found)
+      return 0;
+    if(found.neighborhood->flagged && *found.neighborhood->flagged == n)
+      found.neighborhood->flagged = 0;
+    found.neighborhood->edges.erase(found.it);
+    in_edges_t& ie = lookup[n]->single_neighborhood.in_edges;
+    typename in_edges_t::iterator it_found_ie = std::find(ie.begin(), ie.end(), v);
     ie.erase(it_found_ie);
-    typename edge_list_t::iterator it = pos.base();
-    it_found->single_neighborhood.edges.erase(it);
     return 1;
   }
-  return 0;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
-VVGraph<VertexContent, EdgeContent, Alloc>::eraseEdge(const vertex_t& v, circ_neighbor_iterator pos)
-{
-  return eraseEdge(v, pos.base());
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::size_type
-VVGraph<VertexContent, EdgeContent, Alloc>::eraseEdge(const vertex_t& v, const vertex_t& n)
-{
-  neighbor_found_t found = this->findInVertex(v, n);
-  if(!found)
-    return 0;
-  if(found.neighborhood->flagged && *found.neighborhood->flagged == n)
-    found.neighborhood->flagged = 0;
-  found.neighborhood->edges.erase(found.it);
-  in_edges_t& ie = lookup[n]->single_neighborhood.in_edges;
-  typename in_edges_t::iterator it_found_ie = std::find(ie.begin(), ie.end(), v);
-  ie.erase(it_found_ie);
-  return 1;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-bool VVGraph<VertexContent, EdgeContent, Alloc>::contains(const vertex_t& v) const
-{
-  return this->findVertex(v);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-std::pair<typename VVGraph<VertexContent, EdgeContent, Alloc>::ineighbor_iterator, bool>
-VVGraph<VertexContent, EdgeContent, Alloc>::insertInEdge(const vertex_t& v, const vertex_t& new_neighbor)
-{
-  typename lookup_t::iterator found = lookup.find(new_neighbor);
-  if(found == lookup.end())
-    return std::make_pair(ineighbor_iterator(), false);
-  in_edges_t& ie = found->second->single_neighborhood.in_edges;
-  typename in_edges_t::iterator it_found = std::find(ie.begin(), ie.end(), v);
-  if(it_found != ie.end())
-    return std::make_pair(it_found, false);
-  ie.push_back(v);
-  ineighbor_iterator it = ie.end();
-  --it;
-  return std::make_pair(it, true);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-void VVGraph<VertexContent, EdgeContent, Alloc>::undoInEdge(const vertex_t& new_neighbor, ineighbor_iterator& it)
-{
-  typename lookup_t::iterator found = lookup.find(new_neighbor);
-  // typename neighborhood_t::iterator found = neighborhood.find(new_neighbor);
-  // if(found == neighborhood.end())
-  // return;
-  if(found == lookup.end())
-    return;
-  found->single_neighborhood.single_neighborhood.in_edges.erase(it);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::edge_t
-VVGraph<VertexContent, EdgeContent, Alloc>::replace(const vertex_t& v, const vertex_t& neighbor,
-                                                    const vertex_t& new_neighbor)
-{
-  if(new_neighbor.isNull() or (v == new_neighbor) or (neighbor == new_neighbor))
-    return edge_t();
-  neighbor_found_t found = this->findInVertex(v, neighbor);
-  if(!found)
-    return edge_t();
-  NeighborhoodPair* n_found = this->findVertex(neighbor);
-  ineighbor_iterator it_in;
-  bool inserted;
-  util::tie(it_in, inserted) = insertInEdge(v, new_neighbor);
-  if(!inserted)
-    return edge_t();
-  in_edges_t& ie = n_found->single_neighborhood.in_edges;
-  typename in_edges_t::iterator it_found_ie = std::find(ie.begin(), ie.end(), v);
-  ie.erase(it_found_ie);
-  found.it->target = new_neighbor;
-  found.it->clear_edge();
-  if(n_found->single_neighborhood.flagged and *n_found->single_neighborhood.flagged == neighbor)
-    n_found->single_neighborhood.flagged = 0;
-  return edge_t(v.id(), new_neighbor.id(), &*found.it);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t&
-VVGraph<VertexContent, EdgeContent, Alloc>::nextTo(const vertex_t &v, const vertex_t &ref, unsigned int n) const
-{
-  const_neighbor_found_t found = this->findInVertex(v, ref);
-  if(!found)
-    return vertex_t::null;     // vertex_t(0);
-  typename edge_list_t::const_iterator it = found.it;
-  const edge_list_t& lst = found.neighborhood->edges;
-  for(unsigned int i = 0; i < n; ++i) {
-    ++it;
-    if(it == lst.end())
-      it = lst.begin();
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  bool VVGraph<VertexContent, EdgeContent, Alloc>::contains(const vertex_t& v) const
+  {
+    return this->findVertex(v);
   }
-  return it->target;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t&
-VVGraph<VertexContent, EdgeContent, Alloc>::prevTo(const vertex_t &v, const vertex_t &ref, unsigned int n) const
-{
-  const_neighbor_found_t found = this->findInVertex(v, ref);
-  if(!found)
-    return vertex_t::null;     // vertex_t(0);
-  typename edge_list_t::const_iterator it = found.it;
-  const edge_list_t& lst = found.neighborhood->edges;
-  for(unsigned int i = 0; i < n; ++i) {
-    if(it == lst.begin())
-      it = lst.end();
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  std::pair<typename VVGraph<VertexContent, EdgeContent, Alloc>::ineighbor_iterator, bool>
+  VVGraph<VertexContent, EdgeContent, Alloc>::insertInEdge(const vertex_t& v, const vertex_t& new_neighbor)
+  {
+    typename lookup_t::iterator found = lookup.find(new_neighbor);
+    if(found == lookup.end())
+      return std::make_pair(ineighbor_iterator(), false);
+    in_edges_t& ie = found->second->single_neighborhood.in_edges;
+    typename in_edges_t::iterator it_found = std::find(ie.begin(), ie.end(), v);
+    if(it_found != ie.end())
+      return std::make_pair(it_found, false);
+    ie.push_back(v);
+    ineighbor_iterator it = ie.end();
     --it;
+    return std::make_pair(it, true);
   }
-  return it->target;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::edge_t
-VVGraph<VertexContent, EdgeContent, Alloc>::edge(const vertex_t& src, const vertex_t& tgt)
-{
-  neighbor_found_t found = this->findInVertex(src, tgt);
-  if(!found)
-    return edge_t();
-  return edge_t(src.id(), tgt.id(), &*found.it);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::arc_t
-VVGraph<VertexContent, EdgeContent, Alloc>::arc(const vertex_t& src, const vertex_t& tgt)
-{
-  neighbor_found_t found = this->findInVertex(src, tgt);
-  if(!found)
-    return arc_t();
-  neighbor_found_t other = this->findInVertex(tgt, src);
-  if(!other)
-    return arc_t();
-  return arc_t(src.id(), tgt.id(), &*found.it, &*other.it);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::const_edge_t
-VVGraph<VertexContent, EdgeContent, Alloc>::edge(const vertex_t& src, const vertex_t& tgt) const
-{
-  const_neighbor_found_t found = this->findInVertex(src, tgt);
-  if(!found)
-    return const_edge_t();
-  return const_edge_t(src.id(), tgt.id(), &*found.it);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-bool VVGraph<VertexContent, EdgeContent, Alloc>::flag(const vertex_t& src, const vertex_t& neighbor)
-{
-  neighbor_found_t found = this->findInVertex(src, neighbor);
-  if(!found)
-    return false;
-  found.neighborhood->flagged = &(found.it->target);
-  return true;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t&
-VVGraph<VertexContent, EdgeContent, Alloc>::flagged(const vertex_t &src) const
-{
-  const NeighborhoodPair* found = this->findVertex(src);
-  if(not found or found->single_neighborhood.flagged == 0)
-    return vertex_t::null;
-  return *found->single_neighborhood.flagged;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::edge_t
-VVGraph<VertexContent, EdgeContent, Alloc>::spliceAfter(const vertex_t& v, const vertex_t& neighbor,
-                                                        const vertex_t& new_neighbor)
-{
-  if(new_neighbor.isNull() || v == new_neighbor)
-    return edge_t();
-  neighbor_found_t found = this->findInVertex(v, neighbor);
-  if(!found)
-    return edge_t();
-  ineighbor_iterator it_in;
-  bool inserted;
-  util::tie(it_in, inserted) = insertInEdge(v, new_neighbor);
-  if(!inserted)
-    return edge_t();
-  ++found.it;
-  typename edge_list_t::iterator new_edge_it
-    = found.neighborhood->edges.insert(found.it, neighbor_t(new_neighbor, EdgeContent()));
-  return edge_t(v.id(), new_neighbor.id(), &*new_edge_it);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::edge_t
-VVGraph<VertexContent, EdgeContent, Alloc>::spliceBefore(const vertex_t& v, const vertex_t& neighbor,
-                                                         const vertex_t& new_neighbor)
-{
-  if(new_neighbor.isNull() || v == new_neighbor)
-    return edge_t();
-  neighbor_found_t found = this->findInVertex(v, neighbor);
-  if(!found)
-    return edge_t();
-  ineighbor_iterator it_in;
-  bool inserted;
-  util::tie(it_in, inserted) = insertInEdge(v, new_neighbor);
-  if(!inserted)
-    return edge_t();
-  typename edge_list_t::iterator new_edge_it
-    = found.neighborhood->edges.insert(found.it, neighbor_t(new_neighbor, EdgeContent()));
-  return edge_t(v.id(), new_neighbor.id(), &*new_edge_it);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::edge_t
-VVGraph<VertexContent, EdgeContent, Alloc>::insertEdge(const vertex_t& v, const vertex_t& new_neighbor)
-{
-  if(v.isNull() || new_neighbor.isNull() || v == new_neighbor)
-    return edge_t();
-  NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found)
-    return edge_t();
-  ineighbor_iterator it_in;
-  bool inserted;
-  util::tie(it_in, inserted) = insertInEdge(v, new_neighbor);
-  if(!inserted)
-    return edge_t();
-  edge_list_t& lst = it_found->single_neighborhood.edges;
-  lst.push_front(neighbor_t(new_neighbor, EdgeContent()));
-  typename edge_list_t::iterator it = lst.begin();
-  return edge_t(v.id(), new_neighbor.id(), &*it);
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::const_neighbor_iterator_pair
-VVGraph<VertexContent, EdgeContent, Alloc>::neighbors(const vertex_t& v) const
-{
-  const_neighbor_iterator_pair result;
-  if(v.isNull())
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  void VVGraph<VertexContent, EdgeContent, Alloc>::undoInEdge(const vertex_t& new_neighbor, ineighbor_iterator& it)
+  {
+    typename lookup_t::iterator found = lookup.find(new_neighbor);
+    // typename neighborhood_t::iterator found = neighborhood.find(new_neighbor);
+    // if(found == neighborhood.end())
+    // return;
+    if(found == lookup.end())
+      return;
+    found->single_neighborhood.single_neighborhood.in_edges.erase(it);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::edge_t
+  VVGraph<VertexContent, EdgeContent, Alloc>::replace(const vertex_t& v, const vertex_t& neighbor,
+                                                      const vertex_t& new_neighbor)
+  {
+    if(new_neighbor.isNull() or (v == new_neighbor) or (neighbor == new_neighbor))
+      return edge_t();
+    neighbor_found_t found = this->findInVertex(v, neighbor);
+    if(!found)
+      return edge_t();
+    NeighborhoodPair* n_found = this->findVertex(neighbor);
+    ineighbor_iterator it_in;
+    bool inserted;
+    util::tie(it_in, inserted) = insertInEdge(v, new_neighbor);
+    if(!inserted)
+      return edge_t();
+    in_edges_t& ie = n_found->single_neighborhood.in_edges;
+    typename in_edges_t::iterator it_found_ie = std::find(ie.begin(), ie.end(), v);
+    ie.erase(it_found_ie);
+    found.it->target = new_neighbor;
+    found.it->clear_edge();
+    if(n_found->single_neighborhood.flagged and *n_found->single_neighborhood.flagged == neighbor)
+      n_found->single_neighborhood.flagged = 0;
+    return edge_t(v.id(), new_neighbor.id(), &*found.it);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t&
+  VVGraph<VertexContent, EdgeContent, Alloc>::nextTo(const vertex_t &v, const vertex_t &ref, unsigned int n) const
+  {
+    const_neighbor_found_t found = this->findInVertex(v, ref);
+    if(!found)
+      return vertex_t::null;     // vertex_t(0);
+    typename edge_list_t::const_iterator it = found.it;
+    const edge_list_t& lst = found.neighborhood->edges;
+    for(unsigned int i = 0; i < n; ++i) {
+      ++it;
+      if(it == lst.end())
+        it = lst.begin();
+    }
+    return it->target;
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t&
+  VVGraph<VertexContent, EdgeContent, Alloc>::prevTo(const vertex_t &v, const vertex_t &ref, unsigned int n) const
+  {
+    const_neighbor_found_t found = this->findInVertex(v, ref);
+    if(!found)
+      return vertex_t::null;     // vertex_t(0);
+    typename edge_list_t::const_iterator it = found.it;
+    const edge_list_t& lst = found.neighborhood->edges;
+    for(unsigned int i = 0; i < n; ++i) {
+      if(it == lst.begin())
+        it = lst.end();
+      --it;
+    }
+    return it->target;
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::edge_t
+  VVGraph<VertexContent, EdgeContent, Alloc>::edge(const vertex_t& src, const vertex_t& tgt)
+  {
+    neighbor_found_t found = this->findInVertex(src, tgt);
+    if(!found)
+      return edge_t();
+    return edge_t(src.id(), tgt.id(), &*found.it);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::const_edge_t
+  VVGraph<VertexContent, EdgeContent, Alloc>::edge(const vertex_t& src, const vertex_t& tgt) const
+  {
+    const_neighbor_found_t found = this->findInVertex(src, tgt);
+    if(!found)
+      return const_edge_t();
+    return const_edge_t(src.id(), tgt.id(), &*found.it);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  bool VVGraph<VertexContent, EdgeContent, Alloc>::flag(const vertex_t& src, const vertex_t& neighbor)
+  {
+    neighbor_found_t found = this->findInVertex(src, neighbor);
+    if(!found)
+      return false;
+    found.neighborhood->flagged = &(found.it->target);
+    return true;
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  const typename VVGraph<VertexContent, EdgeContent, Alloc>::vertex_t&
+  VVGraph<VertexContent, EdgeContent, Alloc>::flagged(const vertex_t &src) const
+  {
+    const NeighborhoodPair* found = this->findVertex(src);
+    if(not found or found->single_neighborhood.flagged == 0)
+      return vertex_t::null;
+    return *found->single_neighborhood.flagged;
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::edge_t
+  VVGraph<VertexContent, EdgeContent, Alloc>::spliceAfter(const vertex_t& v, const vertex_t& neighbor,
+                                                          const vertex_t& new_neighbor)
+  {
+    if(new_neighbor.isNull() || v == new_neighbor)
+      return edge_t();
+    neighbor_found_t found = this->findInVertex(v, neighbor);
+    if(!found)
+      return edge_t();
+    ineighbor_iterator it_in;
+    bool inserted;
+    util::tie(it_in, inserted) = insertInEdge(v, new_neighbor);
+    if(!inserted)
+      return edge_t();
+    ++found.it;
+    typename edge_list_t::iterator new_edge_it
+      = found.neighborhood->edges.insert(found.it, neighbor_t(new_neighbor, EdgeContent()));
+    return edge_t(v.id(), new_neighbor.id(), &*new_edge_it);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::edge_t
+  VVGraph<VertexContent, EdgeContent, Alloc>::spliceBefore(const vertex_t& v, const vertex_t& neighbor,
+                                                           const vertex_t& new_neighbor)
+  {
+    if(new_neighbor.isNull() || v == new_neighbor)
+      return edge_t();
+    neighbor_found_t found = this->findInVertex(v, neighbor);
+    if(!found)
+      return edge_t();
+    ineighbor_iterator it_in;
+    bool inserted;
+    util::tie(it_in, inserted) = insertInEdge(v, new_neighbor);
+    if(!inserted)
+      return edge_t();
+    typename edge_list_t::iterator new_edge_it
+      = found.neighborhood->edges.insert(found.it, neighbor_t(new_neighbor, EdgeContent()));
+    return edge_t(v.id(), new_neighbor.id(), &*new_edge_it);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::edge_t
+  VVGraph<VertexContent, EdgeContent, Alloc>::insertEdge(const vertex_t& v, const vertex_t& new_neighbor)
+  {
+    if(v.isNull() || new_neighbor.isNull() || v == new_neighbor)
+      return edge_t();
+    NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found)
+      return edge_t();
+    ineighbor_iterator it_in;
+    bool inserted;
+    util::tie(it_in, inserted) = insertInEdge(v, new_neighbor);
+    if(!inserted)
+      return edge_t();
+    edge_list_t& lst = it_found->single_neighborhood.edges;
+    lst.push_front(neighbor_t(new_neighbor, EdgeContent()));
+    typename edge_list_t::iterator it = lst.begin();
+    return edge_t(v.id(), new_neighbor.id(), &*it);
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::const_neighbor_iterator_pair
+  VVGraph<VertexContent, EdgeContent, Alloc>::neighbors(const vertex_t& v) const
+  {
+    const_neighbor_iterator_pair result;
+    if(v.isNull())
+      return result;
+    const NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found)
+      return result;
+    const edge_list_t& lst = it_found->single_neighborhood.edges;
+    result.first = const_neighbor_iterator(lst.begin());
+    result.second = const_neighbor_iterator(lst.end());
     return result;
-  const NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found)
+  }
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::neighbor_iterator_pair
+  VVGraph<VertexContent, EdgeContent, Alloc>::neighbors(const vertex_t& v)
+  {
+    neighbor_iterator_pair result;
+    if(v.isNull())
+      return result;
+    NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found)
+      return result;
+    edge_list_t& lst = it_found->single_neighborhood.edges;
+    result.first = neighbor_iterator(lst.begin());
+    result.second = neighbor_iterator(lst.end());
     return result;
-  const edge_list_t& lst = it_found->single_neighborhood.edges;
-  result.first = const_neighbor_iterator(lst.begin());
-  result.second = const_neighbor_iterator(lst.end());
-  return result;
-}
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::neighbor_iterator_pair
-VVGraph<VertexContent, EdgeContent, Alloc>::neighbors(const vertex_t& v)
-{
-  neighbor_iterator_pair result;
-  if(v.isNull())
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::const_circ_neighbor_iterator_pair
+  VVGraph<VertexContent, EdgeContent, Alloc>::neighbors(const vertex_t& v, const vertex_t& n) const
+  {
+    const_circ_neighbor_iterator_pair result;
+    if(v.isNull())
+      return result;
+    const_neighbor_found_t found = this->findInVertex(v, n);
+    if(!found)
+      return result;
+    const edge_list_t& lst = found.neighborhood->edges;
+    result.first = const_circ_neighbor_iterator(lst.begin(), lst.end(), found.it);
+    result.second = const_circ_neighbor_iterator(lst.begin(), lst.end());
     return result;
-  NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found)
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::circ_neighbor_iterator_pair
+  VVGraph<VertexContent, EdgeContent, Alloc>::neighbors(const vertex_t& v, const vertex_t& n)
+  {
+    circ_neighbor_iterator_pair result;
+    if(v.isNull())
+      return result;
+    neighbor_found_t found = this->findInVertex(v, n);
+    if(!found)
+      return result;
+    edge_list_t& lst = found.neighborhood->edges;
+    result.first = circ_neighbor_iterator(lst.begin(), lst.end(), found.it);
+    result.second = circ_neighbor_iterator(lst.begin(), lst.end());
     return result;
-  edge_list_t& lst = it_found->single_neighborhood.edges;
-  result.first = neighbor_iterator(lst.begin());
-  result.second = neighbor_iterator(lst.end());
-  return result;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::const_circ_neighbor_iterator_pair
-VVGraph<VertexContent, EdgeContent, Alloc>::neighbors(const vertex_t& v, const vertex_t& n) const
-{
-  const_circ_neighbor_iterator_pair result;
-  if(v.isNull())
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::const_ineighbor_iterator_pair
+  VVGraph<VertexContent, EdgeContent, Alloc>::iNeighbors(const vertex_t& v) const
+  {
+    const_ineighbor_iterator_pair result;
+    if(v.isNull())
+      return result;
+    const NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found)
+      return result;
+    const in_edges_t& lst = it_found->single_neighborhood.in_edges;
+    result.first = const_ineighbor_iterator(lst.begin());
+    result.second = const_ineighbor_iterator(lst.end());
     return result;
-  const_neighbor_found_t found = this->findInVertex(v, n);
-  if(!found)
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  typename VVGraph<VertexContent, EdgeContent, Alloc>::ineighbor_iterator_pair
+  VVGraph<VertexContent, EdgeContent, Alloc>::iNeighbors(const vertex_t& v)
+  {
+    ineighbor_iterator_pair result;
+    if(v.isNull())
+      return result;
+    NeighborhoodPair* it_found = this->findVertex(v);
+    if(not it_found)
+      return result;
+    in_edges_t& lst = it_found->single_neighborhood.in_edges;
+    result.first = ineighbor_iterator(lst.begin());
+    result.second = ineighbor_iterator(lst.end());
     return result;
-  const edge_list_t& lst = found.neighborhood->edges;
-  result.first = const_circ_neighbor_iterator(lst.begin(), lst.end(), found.it);
-  result.second = const_circ_neighbor_iterator(lst.begin(), lst.end());
-  return result;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::circ_neighbor_iterator_pair
-VVGraph<VertexContent, EdgeContent, Alloc>::neighbors(const vertex_t& v, const vertex_t& n)
-{
-  circ_neighbor_iterator_pair result;
-  if(v.isNull())
-    return result;
-  neighbor_found_t found = this->findInVertex(v, n);
-  if(!found)
-    return result;
-  edge_list_t& lst = found.neighborhood->edges;
-  result.first = circ_neighbor_iterator(lst.begin(), lst.end(), found.it);
-  result.second = circ_neighbor_iterator(lst.begin(), lst.end());
-  return result;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::const_ineighbor_iterator_pair
-VVGraph<VertexContent, EdgeContent, Alloc>::iNeighbors(const vertex_t& v) const
-{
-  const_ineighbor_iterator_pair result;
-  if(v.isNull())
-    return result;
-  const NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found)
-    return result;
-  const in_edges_t& lst = it_found->single_neighborhood.in_edges;
-  result.first = const_ineighbor_iterator(lst.begin());
-  result.second = const_ineighbor_iterator(lst.end());
-  return result;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-typename VVGraph<VertexContent, EdgeContent, Alloc>::ineighbor_iterator_pair
-VVGraph<VertexContent, EdgeContent, Alloc>::iNeighbors(const vertex_t& v)
-{
-  ineighbor_iterator_pair result;
-  if(v.isNull())
-    return result;
-  NeighborhoodPair* it_found = this->findVertex(v);
-  if(not it_found)
-    return result;
-  in_edges_t& lst = it_found->single_neighborhood.in_edges;
-  result.first = ineighbor_iterator(lst.begin());
-  result.second = ineighbor_iterator(lst.end());
-  return result;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-template <typename VertexContainer>
-VVGraph<VertexContent, EdgeContent, Alloc>
-VVGraph<VertexContent, EdgeContent, Alloc>::subgraph(const VertexContainer& verts) const
-{
-  typename VertexContainer::const_iterator it;
-  VVGraph result;
-  // First, insert the vertexes in the result graph
-  for(it = verts.begin(); it != verts.end(); ++it) {
-    result.insert(*it);
   }
-  const NeighborhoodPair* it_orign;
-  typename neighborhood_t::iterator it_n;
-  typename edge_list_t::const_reverse_iterator it_sn;
-  // Then, creates the in and out edges
-  for(it_n = result.neighborhood.begin(); it_n != result.neighborhood.end(); ++it_n) {
-    const vertex_t& v = (*it_n)->vertex;
-    // For each vertex, find out which edges to add
-    it_orign = this->findVertex(v);
-    const edge_list_t& orig_lst = it_orign->single_neighborhood.edges;
-    edge_list_t& lst = (*it_n)->single_neighborhood.edges;
-    // Going backward because it is easier to retrieve the iterator ...
-    for(it_sn = orig_lst.rbegin(); it_sn != orig_lst.rend(); ++it_sn) {
-      // For each existing edge from the vertex, keep only the ones whose
-      // target are on the subgraph
-      if(result.contains(it_sn->target)) {
-        // Insert the incoming edge
-        ineighbor_iterator it_in = result.insertInEdge(v, it_sn->target).first;
-        // Insert the outgoing edge
-        lst.push_front(neighbor_t(it_sn->target, *it_sn));
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  template <typename VertexContainer>
+  VVGraph<VertexContent, EdgeContent, Alloc>
+  VVGraph<VertexContent, EdgeContent, Alloc>::subgraph(const VertexContainer& verts) const
+  {
+    typename VertexContainer::const_iterator it;
+    VVGraph result;
+    // First, insert the vertexes in the result graph
+    for(it = verts.begin(); it != verts.end(); ++it) {
+      result.insert(*it);
+    }
+    const NeighborhoodPair* it_orign;
+    typename neighborhood_t::iterator it_n;
+    typename edge_list_t::const_reverse_iterator it_sn;
+    // Then, creates the in and out edges
+    for(it_n = result.neighborhood.begin(); it_n != result.neighborhood.end(); ++it_n) {
+      const vertex_t& v = (*it_n)->vertex;
+      // For each vertex, find out which edges to add
+      it_orign = this->findVertex(v);
+      const edge_list_t& orig_lst = it_orign->single_neighborhood.edges;
+      edge_list_t& lst = (*it_n)->single_neighborhood.edges;
+      // Going backward because it is easier to retrieve the iterator ...
+      for(it_sn = orig_lst.rbegin(); it_sn != orig_lst.rend(); ++it_sn) {
+        // For each existing edge from the vertex, keep only the ones whose
+        // target are on the subgraph
+        if(result.contains(it_sn->target)) {
+          // Insert the incoming edge
+          ineighbor_iterator it_in = result.insertInEdge(v, it_sn->target).first;
+          // Insert the outgoing edge
+          lst.push_front(neighbor_t(it_sn->target, *it_sn));
+        }
       }
+      // At last, update the flag, if any
+      if(it_orign->single_neighborhood.flagged and result.contains(*it_orign->single_neighborhood.flagged)) {
+        const_neighbor_found_t found = this->findInVertex(v, *it_orign->single_neighborhood.flagged);
+        (*it_n)->single_neighborhood.flagged = &(found.it->target);
+      }
     }
-    // At last, update the flag, if any
-    if(it_orign->single_neighborhood.flagged and result.contains(*it_orign->single_neighborhood.flagged)) {
-      const_neighbor_found_t found = this->findInVertex(v, *it_orign->single_neighborhood.flagged);
-      (*it_n)->single_neighborhood.flagged = &(found.it->target);
-    }
+    return result;
   }
-  return result;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-VVGraph<VertexContent, EdgeContent, Alloc>::VVGraph(const VVGraph& copy)
-  : modified_vertices(false)
-{
-  *this = copy;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-bool VVGraph<VertexContent, EdgeContent, Alloc>::operator==(const VVGraph& other) const
-{
-  if(neighborhood.size() != other.neighborhood.size())
-    return false;
-  for(typename neighborhood_t::const_iterator it = neighborhood.begin(); it != neighborhood.end(); ++it) {
-    const vertex_t& v1 = it->vertex;
-    typename lookup_t::const_iterator it_found = other.lookup.find(v1);
-    if(it_found == other.lookup.end())
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  VVGraph<VertexContent, EdgeContent, Alloc>::VVGraph(const VVGraph& copy)
+    : modified_vertices(false)
+  {
+    *this = copy;
+  }
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  bool VVGraph<VertexContent, EdgeContent, Alloc>::operator==(const VVGraph& other) const
+  {
+    if(neighborhood.size() != other.neighborhood.size())
       return false;
-    if(it->single_neighborhood.edges.empty()) {
-      if(!it_found->single_neighborhood.single_neighborhood.edges.empty())
+    for(typename neighborhood_t::const_iterator it = neighborhood.begin(); it != neighborhood.end(); ++it) {
+      const vertex_t& v1 = it->vertex;
+      typename lookup_t::const_iterator it_found = other.lookup.find(v1);
+      if(it_found == other.lookup.end())
         return false;
-    } else {
-      const edge_list_t& lst = it->single_neighborhood.edges;
-      const edge_list_t& olst = it_found->second->single_neighborhood.edges;
-      if(lst.size() != olst.size())
-        return false;
-      const vertex_t& v2 = lst.begin()->target;
-      bool found = false;
-      for(typename edge_list_t::const_iterator it_olst = olst.begin(); it_olst != olst.end(); ++it_olst) {
-        if(it_olst->target == v2) {
-          found = true;
-          for(typename edge_list_t::const_iterator it_lst = lst.begin(); it_lst != lst.end(); ++it_lst) {
-            if(it_lst->target != it_olst->target)
-              return false;
-            ++it_olst;
-            if(it_olst == olst.end())
-              it_olst = olst.begin();
+      if(it->single_neighborhood.edges.empty()) {
+        if(!it_found->single_neighborhood.single_neighborhood.edges.empty())
+          return false;
+      } else {
+        const edge_list_t& lst = it->single_neighborhood.edges;
+        const edge_list_t& olst = it_found->second->single_neighborhood.edges;
+        if(lst.size() != olst.size())
+          return false;
+        const vertex_t& v2 = lst.begin()->target;
+        bool found = false;
+        for(typename edge_list_t::const_iterator it_olst = olst.begin(); it_olst != olst.end(); ++it_olst) {
+          if(it_olst->target == v2) {
+            found = true;
+            for(typename edge_list_t::const_iterator it_lst = lst.begin(); it_lst != lst.end(); ++it_lst) {
+              if(it_lst->target != it_olst->target)
+                return false;
+              ++it_olst;
+              if(it_olst == olst.end())
+                it_olst = olst.begin();
+            }
+            break;
           }
-          break;
         }
+        if(!found)
+          return false;
       }
-      if(!found)
-        return false;
     }
+    return true;
   }
-  return true;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-VVGraph<VertexContent, EdgeContent, Alloc>& VVGraph<VertexContent, EdgeContent, Alloc>::reverse()
-{
-  typename neighborhood_t::iterator it;
-  for(it = neighborhood.begin(); it != neighborhood.end(); ++it) {
-    std::reverse((*it)->single_neighborhood.edges.begin(), (*it)->single_neighborhood.edges.end());
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  VVGraph<VertexContent, EdgeContent, Alloc>& VVGraph<VertexContent, EdgeContent, Alloc>::reverse()
+  {
+    typename neighborhood_t::iterator it;
+    for(it = neighborhood.begin(); it != neighborhood.end(); ++it) {
+      std::reverse((*it)->single_neighborhood.edges.begin(), (*it)->single_neighborhood.edges.end());
+    }
+    return *this;
   }
-  return *this;
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-VVGraph<VertexContent, EdgeContent, Alloc>& VVGraph<VertexContent, EdgeContent, Alloc>::operator=(const VVGraph& other)
-{
-  typename neighborhood_t::const_iterator it_o;
-  typename neighborhood_t::iterator it;
-  for(it = neighborhood.begin(); it != neighborhood.end(); ++it) {
-    NeighborhoodPair::Delete(*it);
-    *it = 0;
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  VVGraph<VertexContent, EdgeContent, Alloc>& VVGraph<VertexContent, EdgeContent, Alloc>::operator=(const VVGraph& other)
+  {
+    typename neighborhood_t::const_iterator it_o;
+    typename neighborhood_t::iterator it;
+    for(it = neighborhood.begin(); it != neighborhood.end(); ++it) {
+      NeighborhoodPair::Delete(*it);
+      *it = 0;
+    }
+    neighborhood.clear();
+    lookup.clear();
+    it = neighborhood.end();
+    for(it_o = other.neighborhood.begin(); it_o != other.neighborhood.end(); ++it_o) {
+      NeighborhoodPair* np = (*it_o)->copy();
+      neighborhood.push_back(np);
+      lookup[(*it_o)->vertex] = np;
+    }
+    return *this;
+  
+    // Copy the structure
+    /*
+     * neighborhood = other.neighborhood;
+     * lookup.clear();
+     * typename neighborhood_t::iterator it;
+     * for(it = neighborhood.begin() ; it != neighborhood.end() ; ++it)
+     *  lookup[it->vertex] = it;
+     * return *this;
+     */
   }
-  neighborhood.clear();
-  lookup.clear();
-  it = neighborhood.end();
-  for(it_o = other.neighborhood.begin(); it_o != other.neighborhood.end(); ++it_o) {
-    NeighborhoodPair* np = (*it_o)->copy();
-    neighborhood.push_back(np);
-    lookup[(*it_o)->vertex] = np;
+  
+  template <typename VertexContent, typename EdgeContent, typename Alloc>
+  void VVGraph<VertexContent, EdgeContent, Alloc>::swap(VVGraph& other)
+  {
+    neighborhood.swap(other.neighborhood);
+    lookup.swap(other.lookup);
   }
-  return *this;
-
-  // Copy the structure
-  /*
-   * neighborhood = other.neighborhood;
-   * lookup.clear();
-   * typename neighborhood_t::iterator it;
-   * for(it = neighborhood.begin() ; it != neighborhood.end() ; ++it)
-   *  lookup[it->vertex] = it;
-   * return *this;
-   */
-}
-
-template <typename VertexContent, typename EdgeContent, typename Alloc>
-void VVGraph<VertexContent, EdgeContent, Alloc>::swap(VVGraph& other)
-{
-  neighborhood.swap(other.neighborhood);
-  lookup.swap(other.lookup);
-}
-
-template <typename Graph> void create_graph_methods(Graph& G)
-{
-  if(G.size()) {
-    if(G.valence(G.any()) > G.size()) {
-      // Call all fcts
-      typename Graph::vertex_t v = G.any();
-      G.erase(v);
-      G.insert(v);
-      G[10];
-      G.reference(v);
-      G.empty();
-      G.anyIn(v);
-      G.valence(v);
-      G.empty(v);
-      G.iAnyIn(v);
-      G.iValence(v);
-      G.iEmpty(v);
-      G.nextTo(v, v);
-      G.prevTo(v, v);
-      G.edge(v, v);
-      G.flag(v, v);
-      G.flagged(v);
-      G.neighbors(v);
-      G.iNeighbors(v);
-      G.source(typename Graph::edge_t());
-      G.target(typename Graph::edge_t());
-      G.eraseEdge(v, v);
-      G.replace(v, v, v);
-      G.spliceAfter(v, v, v);
-      G.spliceBefore(v, v, v);
-      G.insertEdge(v, v);
-      G.eraseAllEdges(v);
-      G.begin();
-      G.end();
-      G.find(v);
-      G.count(v);
-      G.findIn(v, v);
-      {
-        const Graph& cG = G;
-        cG[10];
-        cG.reference(v);
-        cG.empty();
-        cG.anyIn(v);
-        cG.valence(v);
-        cG.empty(v);
-        cG.iAnyIn(v);
-        cG.iValence(v);
-        cG.iEmpty(v);
-        cG.nextTo(v, v);
-        cG.prevTo(v, v);
-        cG.edge(v, v);
-        cG.flagged(v);
-        cG.neighbors(v);
-        cG.iNeighbors(v);
-        cG.source(typename Graph::edge_t());
-        cG.target(typename Graph::edge_t());
-        cG.begin();
-        cG.end();
-        cG.find(v);
-        cG.count(v);
-        cG.findIn(v, v);
+  
+  template <typename Graph> void create_graph_methods(Graph& G)
+  {
+    if(G.size()) {
+      if(G.valence(G.any()) > G.size()) {
+        // Call all fcts
+        typename Graph::vertex_t v = G.any();
+        G.erase(v);
+        G.insert(v);
+        G[10];
+        G.reference(v);
+        G.empty();
+        G.anyIn(v);
+        G.valence(v);
+        G.empty(v);
+        G.iAnyIn(v);
+        G.iValence(v);
+        G.iEmpty(v);
+        G.nextTo(v, v);
+        G.prevTo(v, v);
+        G.edge(v, v);
+        G.flag(v, v);
+        G.flagged(v);
+        G.neighbors(v);
+        G.iNeighbors(v);
+        G.source(typename Graph::edge_t());
+        G.target(typename Graph::edge_t());
+        G.eraseEdge(v, v);
+        G.replace(v, v, v);
+        G.spliceAfter(v, v, v);
+        G.spliceBefore(v, v, v);
+        G.insertEdge(v, v);
+        G.eraseAllEdges(v);
+        G.begin();
+        G.end();
+        G.find(v);
+        G.count(v);
+        G.findIn(v, v);
+        {
+          const Graph& cG = G;
+          cG[10];
+          cG.reference(v);
+          cG.empty();
+          cG.anyIn(v);
+          cG.valence(v);
+          cG.empty(v);
+          cG.iAnyIn(v);
+          cG.iValence(v);
+          cG.iEmpty(v);
+          cG.nextTo(v, v);
+          cG.prevTo(v, v);
+          cG.edge(v, v);
+          cG.flagged(v);
+          cG.neighbors(v);
+          cG.iNeighbors(v);
+          cG.source(typename Graph::edge_t());
+          cG.target(typename Graph::edge_t());
+          cG.begin();
+          cG.end();
+          cG.find(v);
+          cG.count(v);
+          cG.findIn(v, v);
+        }
       }
     }
   }
-}
-} // namespace graph
-} // namespace mgx
 
+}}
+
 #endif
Index: SystemProcess.hpp
===================================================================
--- SystemProcess.hpp	(revision 1255)
+++ SystemProcess.hpp	(revision 1256)
@@ -3,12 +3,10 @@
 
 #include <Config.hpp>
 
-namespace mgx {
-namespace process {
+namespace mgx { namespace process {
 
-void MGX_EXPORT registerSystemProcesses();
-void MGX_EXPORT unregisterSystemProcesses();
+ void MGX_EXPORT registerSystemProcesses();
+ void MGX_EXPORT unregisterSystemProcesses();
 
-} // namespace process
-} // namespace mgx
+}}
 #endif
Index: Information.hpp
===================================================================
--- Information.hpp	(revision 1255)
+++ Information.hpp	(revision 1256)
@@ -17,37 +17,32 @@
       QTextStream __status_msgstrm(&__status_msg); \
       __status_msgstrm << msg;                     \
     }                                              \
-    mgx::Information::Print(__status_msg);         \
+    mgx::Information::print(__status_msg);         \
   } while(false)
 
-#define DEBUG_OUT mgx::Information::out
-
 #define DEBUG_OUTPUT(msg) \
   if(DEBUG)               \
     do {                  \
-      DEBUG_OUT << msg;   \
+      Information::out << msg;   \
     } while(false)
 
 namespace mgx {
-MGX_EXPORT extern bool DEBUG;
+  MGX_EXPORT extern bool DEBUG;
 
-namespace Information {
-MGX_EXPORT extern QTextStream out;
-MGX_EXPORT extern QTextStream err;
-
-struct MGX_EXPORT Event : public QEvent {
-  Event(const QString& msg)
-    : QEvent(QEvent::User)
-    , message(msg)
-  {
+  namespace Information {
+    MGX_EXPORT extern QTextStream out;
+    MGX_EXPORT extern QTextStream err;
+    
+    struct MGX_EXPORT Event : public QEvent {
+      Event(const QString& msg) : QEvent(QEvent::User), message(msg) {}
+    
+      QString message;
+    };
+    
+    MGX_EXPORT void setMainWindow(QMainWindow* wnd);
+    MGX_EXPORT void setStatus(const QString& text);
+    MGX_EXPORT void print(const QString& text);
+    MGX_EXPORT void print(const std::string text);
   }
-
-  QString message;
-};
-
-MGX_EXPORT void setMainWindow(QMainWindow* wnd);
-MGX_EXPORT void Print(const QString& _text);
-MGX_EXPORT void Print(const std::string _text);
-} // namespace Information
-} // namespace mgx
+}
 #endif
Index: MeshProcessHeatMap.hpp
===================================================================
--- MeshProcessHeatMap.hpp	(revision 1255)
+++ MeshProcessHeatMap.hpp	(revision 1256)
@@ -7,587 +7,405 @@
 
 class Ui_LoadHeatMap;
 
-namespace mgx {
-namespace process {
-MGX_EXPORT void getBBox(const HVec3F& pts, Point3f* bBox);
+namespace mgx { namespace process {
 
-///\addtogroup MeshProcess
-///@{
-
-/**
- * \class ComputeHeatMap MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
- *
- * Compute heat map on the current mesh. For details, look at the description of the various parameters.
- */
-class MGX_EXPORT ComputeHeatMap : public QObject, public MeshProcess {
-  Q_OBJECT
-public:
-  ComputeHeatMap(const MeshProcess& process)
-    : Process(process)
-    , QObject()
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms);
-
-  enum MapType { AREA, VOLUME, WALL };
-
-  enum SignalType {
-    GEOMETRY = 0x1,
-    BORDER = 0x2,
-    INTERIOR = 0x4,
-    TOTAL = 0x8,
-    BORDER_TOTAL = 0x10,
-    INTERIOR_TOTAL = 0x20
+  MGX_EXPORT void getBBox(const HVec3F& pts, Point3f* bBox);
+  
+  ///\addtogroup MeshProcess
+  ///@{
+  
+  /**
+   * \class ComputeHeatMap MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
+   *
+   * Compute heat map on the current mesh. For details, look at the description of the various parameters.
+   */
+  class MGX_EXPORT ComputeHeatMap : public QObject, public MeshProcess {
+    Q_OBJECT
+  public:
+    ComputeHeatMap(const MeshProcess& process) : Process(process), QObject(), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms);
+  
+    enum MapType { AREA, VOLUME, WALL };
+  
+    enum SignalType {
+      GEOMETRY = 0x1,
+      BORDER = 0x2,
+      INTERIOR = 0x4,
+      TOTAL = 0x8,
+      BORDER_TOTAL = 0x10,
+      INTERIOR_TOTAL = 0x20
+    };
+  
+    enum PolarityType { NONE, CELL_AVERAGE, WALL_MIN };
+  
+    enum MultiMapType {
+      SINGLE,
+      INCREASING_RATIO,
+      INCREASING_DIFF,
+      DECREASING_RATIO,
+      DECREASING_DIFF,
+      INCREASING_GROWTH,
+      DECREASING_GROWTH
+    };
+  
+    struct ImageHeatMaps {
+      IntFloatMap LabelGeom;         // Label Areas
+      IntFloatMap LabelBordGeom;     // Area of label borders
+      IntFloatMap LabelIntGeom;      // Area of label interiors
+      IntFloatMap LabelTotalSig;     // Label total signal
+      IntFloatMap LabelBordSig;      // Label border signal
+      IntFloatMap LabelIntSig;       // Label interior signal
+      IntFloatMap LabelHeatAmt;      // Label HeatMap temp for change map
+      IntHVec3uMap LabelTris;        // Label triangle lists
+      IntVIdSetMap LabelPts;         // Label triangle list points
+  
+      IntIntFloatMap WallBordGeom;     // Wall border areas
+      IntIntFloatMap WallBordSig;      // Wall border signal
+      IntIntFloatMap WallHeatAmt;      // Wall border signal amt for change map
+    };
+  
+    bool operator()(Mesh* mesh1, Mesh* mesh2, MapType map, SignalType signal, const QString& reportFile, int report,
+                    bool manualRange, float rangeMin, float rangeMax, bool signalAverage, bool globalCoordinates,
+                    PolarityType polarity, MultiMapType multiMapType, float growthTime, float borderSize);
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    QString folder() const { return "Heat Map"; }
+    QString name() const { return "Heat Map"; }
+    QString description() const { return "Generate heat map for the current mesh"; }
+    QStringList parmNames() const
+    {
+      return QStringList() 
+        << "Type" << "Visualize" << "FileName" << "ReportFields" << "Man. Range" << "Range Min"
+        << "Range Max" << "Signal Avg" << "Global Coord" << "Polarity Type" << "Change Map"
+        << "Increasing" << "Diff Type" << "Growth Time" << QString("Border Size(%1)").arg(UM);
+    }
+    QStringList parmDescs() const
+    {
+      return QStringList()
+        << "Area: signal/geometry on curved surfaces,\n"
+           "Volume: for 3D only,\n"
+           "Walls: quantify signal or geometry at cell borders."
+        << "Geometry: cell areas or volume,\n"
+           "Border signal: signal associated with cell borders, within a given distance (Border Size)\n"
+           "Interior signal: total signal of a cell - border signal.\n"
+        << "Path to output file."
+        << "Options to report the following fields in spreadsheet: Geometry, Signal, Border-Interior"
+        << "Manually define the range of the color map."
+        << "Color map lower bound."
+        << "Color map upper bound."
+        << "Option to normalize the signal by cell area or volume"
+        << "Apply the rotation/translation of the stack to the cell center coordinates."
+        << "Experimental option, attempt to determine cell signal polarity based on strength of signal on "
+           "different walls.\n"
+           "Cell Average: compare each wall signal to signal average,\n"
+           "Wall/Min: compare wall signal to the weakest wall signal in the cell."
+        << "Compare two meshes with each other (deformation or change in signal) .\n"
+        << "Increasing: the current mesh is the reference (T0), the other mesh is the changed state (T1),\n"
+           "Decreasing: the other mesh is the reference (T0), the current mesh is the changed state (T1)."
+        << "Ratio: area or signal in changed state(T1) / area or signal in reference (T0),\n"
+           "Difference: area or signal in changed state(T1) - area or signal in reference (T0),\n"
+           "Growth: (Ratio -1)  / growth time.\n"
+        << "Time interval between the two samples." << QString("Border Size(%1)").arg(UM);
+    }
+    QStringList parmDefaults() const
+    {
+      return QStringList() 
+        << "Area" << "Geometry" << "" << "Geometry" << "No" << "0" << "65535" << "Yes"
+        << "No" << "None" << "No" << "Yes" << "Ratio" << ".001" << "1.0";
+    }
+    QIcon icon() const { return QIcon(":/images/MakeHeatMap.png"); }
+  
+    QDialog* dlg;
+  
+  protected slots:
+    void changeMapType(const QString& type);
+    void selectSpreadsheetFile();
+  
+  protected:
+    bool getLabelMaps(ImageHeatMaps& map, Mesh* mesh);
+    MapType mapType;
+    SignalType signal;
+    int report;
+    bool manualRange;
+    float rangeMin;
+    float rangeMax;
+    bool signalAverage;
+    bool globalCoordinates;
+    PolarityType polarity;
+    bool changeMap;
+    MultiMapType multiMapType;
+    float growthTime;
+    float borderSize;
   };
-
-  enum PolarityType { NONE, CELL_AVERAGE, WALL_MIN };
-
-  enum MultiMapType {
-    SINGLE,
-    INCREASING_RATIO,
-    INCREASING_DIFF,
-    DECREASING_RATIO,
-    DECREASING_DIFF,
-    INCREASING_GROWTH,
-    DECREASING_GROWTH
+  
+  /**
+   * \class DeleteHeatRangeLabels MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
+   *
+   * Delete labeling, and possibly cells, if their heat falls within a defined range.
+   */
+  class MGX_EXPORT DeleteHeatRangeLabels : public MeshProcess {
+  public:
+    DeleteHeatRangeLabels(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      float min, max;
+      bool ok = true;
+      if(parms[2].isEmpty())
+        min = std::numeric_limits<float>::quiet_NaN();
+      else
+        min = parms[2].toFloat(&ok);
+      if(not ok)
+        return setErrorMessage("Error, parameter 'Min Heat' must be either empty, or a number");
+      if(parms[3].isEmpty())
+        max = std::numeric_limits<float>::quiet_NaN();
+      else
+        max = parms[3].toFloat(&ok);
+      if(not ok)
+        return setErrorMessage("Error, parameter 'Min Heat' must be either empty, or a number");
+      return (*this)(currentMesh(), stringToBool(parms[0]), stringToBool(parms[1]), min, max);
+    }
+  
+    bool operator()(Mesh* mesh, bool rescale, bool deleteCells, float min, float max);
+  
+    QString folder() const { return "Heat Map"; }
+    QString name() const { return "Delete Heat Range Labels"; }
+    QString description() const { return 
+      "Delete labels with heat within a given range. The heat is given relative to the total range."; }
+    QStringList parmNames() const { return QStringList() 
+      << "Rescale" << "Delete cells" << "Min Heat" << "Max Heat"; }
+    QStringList parmDescs() const { return QStringList()
+      << "Redefine the lower/upper bounds of colormap to fit the range of values."
+      << "Delete vertices within a given range of the color map (Min Heat-Max Heat)."
+      << "Lower bound of color value for which the cells will be deleted (empty for current min)."
+      << "Upper bound of color value for which the cells will be deleted (empty for current max)."; }
+    QStringList parmDefaults() const { return QStringList() << "Yes" << "No" << "" << ""; }
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[0] = booleanChoice();
+      map[1] = booleanChoice();
+      return map;
+    }
+    QIcon icon() const { return QIcon(":/images/ClearStack.png"); }
   };
-
-  struct ImageHeatMaps {
-    IntFloatMap LabelGeom;         // Label Areas
-    IntFloatMap LabelBordGeom;     // Area of label borders
-    IntFloatMap LabelIntGeom;      // Area of label interiors
-    IntFloatMap LabelTotalSig;     // Label total signal
-    IntFloatMap LabelBordSig;      // Label border signal
-    IntFloatMap LabelIntSig;       // Label interior signal
-    IntFloatMap LabelHeatAmt;      // Label HeatMap temp for change map
-    IntHVec3uMap LabelTris;        // Label triangle lists
-    IntVIdSetMap LabelPts;         // Label triangle list points
-
-    IntIntFloatMap WallBordGeom;     // Wall border areas
-    IntIntFloatMap WallBordSig;      // Wall border signal
-    IntIntFloatMap WallHeatAmt;      // Wall border signal amt for change map
+  
+  /**
+   * \class RescaleHeatMap MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
+   *
+   * Rescale the heat map, specifying new lower and upper bound.
+   */
+  class MGX_EXPORT RescaleHeatMap : public MeshProcess {
+  public:
+    RescaleHeatMap(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_HEAT))
+        return false;
+      Mesh* m = currentMesh();
+      bool ok = true;
+      float min, max;
+      if(parms[0].isEmpty())
+        min = std::numeric_limits<float>::quiet_NaN();
+      else
+        min = parms[0].toFloat(&ok);
+      if(not ok)
+        return setErrorMessage("Error, parameter 'Min' must be either empty, or a number");
+      if(parms[1].isEmpty())
+        max = std::numeric_limits<float>::quiet_NaN();
+      else
+        max = parms[1].toFloat(&ok);
+      if(not ok)
+        return setErrorMessage("Error, parameter 'Max' must be either empty, or a number");
+      return (*this)(m, min, max);
+    }
+  
+    bool operator()(Mesh* m, float min, float max);
+  
+    QString folder() const { return "Heat Map"; }
+    QString name() const { return "Rescale Heat Map"; }
+    QString description() const { return "Change the range of the current heat map for display."; }
+    QStringList parmNames() const { return QStringList() << "Min" << "Max"; }
+    QStringList parmDescs() const { return QStringList() 
+      << "Lower bound (empty for current)" << "Upper bound (empty for current)"; }
+    QStringList parmDefaults() const { return QStringList() << "" << ""; }
+    QIcon icon() const { return QIcon(":/images/MakeHeatMap.png"); }
   };
+  
+  /**
+   * \class SaveHeatMap MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
+   *
+   * Save the current heat map in a CSV file.
+   */
+  class MGX_EXPORT SaveHeatMap : public QObject, public MeshProcess {
+    Q_OBJECT
+  public:
+    SaveHeatMap(const MeshProcess& process) : Process(process), QObject(), MeshProcess(process) {}
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_ANY))
+        return false;
+      Mesh* m = currentMesh();
+      return (*this)(m, parms[0]);
+    }
+  
+    bool operator()(Mesh* mesh, const QString& filename);
+  
+    QString folder() const { return "Heat Map"; }
+    QString name() const { return "Save Heat Map"; }
+    QString description() const { return "Save heat map to a file"; }
+    QStringList parmNames() const { return QStringList() << "Filename"; }
+    QStringList parmDescs() const { return QStringList() << "Path to spreadsheat file."; }
+    QStringList parmDefaults() const { return QStringList() << ""; }
+    QIcon icon() const { return QIcon(":/images/MakeHeatMap.png"); }
+  };
+  
+  /**
+   * \class LoadHeatMap MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
+   *
+   * Load the heat map from a CSV file. The CSV file must have the following structure:
+   *
+   *  - The first column must be cell labels (the name doesn't matter)
+   *  - If the heat map is on walls, the second column must be called "Neighbor" and also be cell labels.
+   *  - Each other column is a potential heat. The column name is structured
+   *    either as "name" or "name (unit)". In the second case, the unit will be
+   *    extracted for display.
+   */
+  class MGX_EXPORT LoadHeatMap : public QObject, public MeshProcess {
+    Q_OBJECT
+  public:
+    LoadHeatMap(const MeshProcess& process) : Process(process) , QObject() , MeshProcess(process) {}
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_ANY))
+        return false;
+      Mesh* m = currentMesh();
+      return (*this)(m, parms[0], parms[1].toInt(), parms[2].toFloat());
+    }
+  
+    bool operator()(Mesh* mesh, const QString& filename, int column, float border_size);
+  
+    QString folder() const { return "Heat Map"; }
+    QString name() const { return "Load Heat Map"; }
+    QString description() const { return "Load a heat map file and set the corresponding heat for each label"; }
+    QStringList parmNames() const { return QStringList() 
+      << "Filename" << "Column" << QString("Border size (%1)").arg(UM); }
+    QStringList parmDescs() const { return QStringList() 
+      << "Path to spreadsheet file." 
+      << "Column of the csv file to load for display.\n"
+         "Label: cell labels, Value: original computed values (e.g. growth or signal), Heat: "
+         "values scaled for visualization (always between 0-1)."
+      << "Width of cell outline used for vizualization of 'wall' colormaps"; }
+    QStringList parmDefaults() const { return QStringList() << "" << "2" << "1.0"; }
+    QIcon icon() const { return QIcon(":/images/MakeHeatMap.png"); }
+  
+  public slots:
+    void selectFile(const QString& filename);
+    void selectFile();
+    void selectColumn(int c);
+  
+  protected:
+    QDialog* dlg;
+    Ui_LoadHeatMap* ui;
+    QList<QString> column_unit;
+  };
+  
+  /**
+   * \class SaveParents MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
+   *
+   * Store mapping from each label to a label in a different mesh (parent).
+   */
+  class MGX_EXPORT SaveParents : public MeshProcess {
+  public:
+    SaveParents(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_ANY))
+        return false;
+      Mesh* m = currentMesh();
+      return (*this)(m, parms[0]);
+    }
+  
+    bool operator()(Mesh* mesh, const QString& filename);
+  
+    QString folder() const { return "Lineage Tracking"; }
+    QString name() const { return "Save Parents"; }
+    QString description() const { return "Save map of labels to parents labels to a file"; }
+    QStringList parmNames() const { return QStringList() << "Filename"; }
+    QStringList parmDescs() const { return QStringList() << "Path to label parents file."; }
+    QStringList parmDefaults() const { return QStringList() << ""; }
+    QIcon icon() const { return QIcon(":/images/Parents.png"); }
+  };
+  
+  /**
+   * \class LoadParents MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
+   *
+   * Load mapping from each label to a label in a different mesh (parent).
+   */
+  class MGX_EXPORT LoadParents : public MeshProcess {
+  public:
+    LoadParents(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_ANY))
+        return false;
+      Mesh* m = currentMesh();
+      return (*this)(m, parms[0]);
+    }
+  
+    bool operator()(Mesh* mesh, const QString& filename);
+  
+    QString folder() const { return "Lineage Tracking"; }
+    QString name() const { return "Load Parents"; }
+    QString description() const { return "Load map of labels to parents from a file"; }
+    QStringList parmNames() const { return QStringList() << "Filename"; }
+    QStringList parmDescs() const { return QStringList() << "Path to label parents file."; }
+    QStringList parmDefaults() const { return QStringList() << ""; }
+    QIcon icon() const { return QIcon(":/images/Parents.png"); }
+  };
+  
+  /**
+   * Clear label to parent mapping
+   */
+  class MGX_EXPORT ResetParents : public MeshProcess {
+  public:
+    ResetParents(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList&)
+    {
+      if(!checkState().mesh(MESH_ANY))
+        return false;
+      Mesh* m = currentMesh();
+      return (*this)(m);
+    }
+  
+    bool operator()(Mesh* mesh);
+  
+    QString folder() const { return "Lineage Tracking"; }
+    QString name() const { return "Clear Parents"; }
+    QString description() const { return "Clear mapping from parents to labels"; }
+    QStringList parmNames() const { return QStringList(); }
+    QStringList parmDescs() const { return QStringList(); }
+    QIcon icon() const { return QIcon(":/images/Parents.png"); }
+  };
+  ///@}
+}}
 
-  bool operator()(Mesh* mesh1, Mesh* mesh2, MapType map, SignalType signal, const QString& reportFile, int report,
-                  bool manualRange, float rangeMin, float rangeMax, bool signalAverage, bool globalCoordinates,
-                  PolarityType polarity, MultiMapType multiMapType, float growthTime, float borderSize);
-
-  bool initialize(QStringList& parms, QWidget* parent);
-
-  QString folder() const {
-    return "Heat Map";
-  }
-  QString name() const {
-    return "Heat Map";
-  }
-  QString description() const {
-    return "Generate heat map for the current mesh";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Type"
-                         << "Visualize"
-                         << "FileName"
-                         << "ReportFields"
-                         << "Man. Range"
-                         << "Range Min"
-                         << "Range Max"
-                         << "Signal Avg"
-                         << "Global Coord"
-                         << "Polarity Type"
-                         << "Change Map"
-                         << "Increasing"
-                         << "Diff Type"
-                         << "Growth Time" << QString("Border Size(%1)").arg(UM);
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList()
-           << "Area: signal/geometry on curved surfaces,\n"
-              "Volume: for 3D only,\n"
-              "Walls: quantify signal or geometry at cell borders."
-           << "Geometry: cell areas or volume,\n"
-              "Border signal: signal associated with cell borders, within a given distance (Border Size)\n"
-              "Interior signal: total signal of a cell - border signal.\n"
-           << "Path to output file."
-           << "Options to report the following fields in spreadsheet: Geometry, Signal, Border-Interior"
-           << "Manually define the range of the color map."
-           << "Color map lower bound."
-           << "Color map upper bound."
-           << "Option to normalize the signal by cell area or volume"
-           << "Apply the rotation/translation of the stack to the cell center coordinates."
-           << "Experimental option, attempt to determine cell signal polarity based on strength of signal on "
-              "different walls.\n"
-              "Cell Average: compare each wall signal to signal average,\n"
-              "Wall/Min: compare wall signal to the weakest wall signal in the cell."
-           << "Compare two meshes with each other (deformation or change in signal) .\n"
-           << "Increasing: the current mesh is the reference (T0), the other mesh is the changed state (T1),\n"
-              "Decreasing: the other mesh is the reference (T0), the current mesh is the changed state (T1)."
-           << "Ratio: area or signal in changed state(T1) / area or signal in reference (T0),\n"
-              "Difference: area or signal in changed state(T1) - area or signal in reference (T0),\n"
-              "Growth: (Ratio -1)  / growth time.\n"
-           << "Time interval between the two samples." << QString("Border Size(%1)").arg(UM);
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "Area"
-                         << "Geometry"
-                         << ""
-                         << "Geometry"
-                         << "No"
-                         << "0"
-                         << "65535"
-                         << "Yes"
-                         << "No"
-                         << "None"
-                         << "No"
-                         << "Yes"
-                         << "Ratio"
-                         << ".001"
-                         << "1.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/MakeHeatMap.png");
-  }
-
-  QDialog* dlg;
-
-protected slots:
-  void changeMapType(const QString& type);
-  void selectSpreadsheetFile();
-
-protected:
-  bool getLabelMaps(ImageHeatMaps& map, Mesh* mesh);
-  MapType mapType;
-  SignalType signal;
-  int report;
-  bool manualRange;
-  float rangeMin;
-  float rangeMax;
-  bool signalAverage;
-  bool globalCoordinates;
-  PolarityType polarity;
-  bool changeMap;
-  MultiMapType multiMapType;
-  float growthTime;
-  float borderSize;
-};
-
-/**
- * \class DeleteHeatRangeLabels MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
- *
- * Delete labeling, and possibly cells, if their heat falls within a defined range.
- */
-class MGX_EXPORT DeleteHeatRangeLabels : public MeshProcess {
-public:
-  DeleteHeatRangeLabels(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    float min, max;
-    bool ok = true;
-    if(parms[2].isEmpty())
-      min = std::numeric_limits<float>::quiet_NaN();
-    else
-      min = parms[2].toFloat(&ok);
-    if(not ok)
-      return setErrorMessage("Error, parameter 'Min Heat' must be either empty, or a number");
-    if(parms[3].isEmpty())
-      max = std::numeric_limits<float>::quiet_NaN();
-    else
-      max = parms[3].toFloat(&ok);
-    if(not ok)
-      return setErrorMessage("Error, parameter 'Min Heat' must be either empty, or a number");
-    return (*this)(currentMesh(), stringToBool(parms[0]), stringToBool(parms[1]), min, max);
-  }
-
-  bool operator()(Mesh* mesh, bool rescale, bool deleteCells, float min, float max);
-
-  QString folder() const {
-    return "Heat Map";
-  }
-  QString name() const {
-    return "Delete Heat Range Labels";
-  }
-  QString description() const
-  {
-    return "Delete labels with heat within a given range. The heat is given relative to the total range.";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Rescale"
-                         << "Delete cells"
-                         << "Min Heat"
-                         << "Max Heat";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList()
-           << "Redefine the lower/upper bounds of colormap to fit the range of values."
-           << "Delete vertices within a given range of the color map (Min Heat-Max Heat)."
-           << "Lower bound of color value for which the cells will be deleted (empty for current min)."
-           << "Upper bound of color value for which the cells will be deleted (empty for current max).";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "Yes"
-                         << "No"
-                         << ""
-                         << "";
-  }
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[0] = booleanChoice();
-    map[1] = booleanChoice();
-    return map;
-  }
-  QIcon icon() const {
-    return QIcon(":/images/ClearStack.png");
-  }
-};
-
-/**
- * \class RescaleHeatMap MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
- *
- * Rescale the heat map, specifying new lower and upper bound.
- */
-class MGX_EXPORT RescaleHeatMap : public MeshProcess {
-public:
-  RescaleHeatMap(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_HEAT))
-      return false;
-    Mesh* m = currentMesh();
-    bool ok = true;
-    float min, max;
-    if(parms[0].isEmpty())
-      min = std::numeric_limits<float>::quiet_NaN();
-    else
-      min = parms[0].toFloat(&ok);
-    if(not ok)
-      return setErrorMessage("Error, parameter 'Min' must be either empty, or a number");
-    if(parms[1].isEmpty())
-      max = std::numeric_limits<float>::quiet_NaN();
-    else
-      max = parms[1].toFloat(&ok);
-    if(not ok)
-      return setErrorMessage("Error, parameter 'Max' must be either empty, or a number");
-    return (*this)(m, min, max);
-  }
-
-  bool operator()(Mesh* m, float min, float max);
-
-  QString folder() const {
-    return "Heat Map";
-  }
-  QString name() const {
-    return "Rescale Heat Map";
-  }
-  QString description() const {
-    return "Change the range of the current heat map for display.";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Min"
-                         << "Max";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Lower bound (empty for current)"
-                         << "Upper bound (empty for current)";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << ""
-                         << "";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/MakeHeatMap.png");
-  }
-};
-
-/**
- * \class SaveHeatMap MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
- *
- * Save the current heat map in a CSV file.
- */
-class MGX_EXPORT SaveHeatMap : public QObject, public MeshProcess {
-  Q_OBJECT
-public:
-  SaveHeatMap(const MeshProcess& process)
-    : Process(process)
-    , QObject()
-    , MeshProcess(process)
-  {
-  }
-
-  bool initialize(QStringList& parms, QWidget* parent);
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_ANY))
-      return false;
-    Mesh* m = currentMesh();
-    return (*this)(m, parms[0]);
-  }
-
-  bool operator()(Mesh* mesh, const QString& filename);
-
-  QString folder() const {
-    return "Heat Map";
-  }
-  QString name() const {
-    return "Save Heat Map";
-  }
-  QString description() const {
-    return "Save heat map to a file";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Filename";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Path to spreadsheat file.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/MakeHeatMap.png");
-  }
-};
-
-/**
- * \class LoadHeatMap MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
- *
- * Load the heat map from a CSV file. The CSV file must have the following structure:
- *
- *  - The first column must be cell labels (the name doesn't matter)
- *  - If the heat map is on walls, the second column must be called "Neighbor" and also be cell labels.
- *  - Each other column is a potential heat. The column name is structured
- *    either as "name" or "name (unit)". In the second case, the unit will be
- *    extracted for display.
- */
-class MGX_EXPORT LoadHeatMap : public QObject, public MeshProcess {
-  Q_OBJECT
-public:
-  LoadHeatMap(const MeshProcess& process)
-    : Process(process)
-    , QObject()
-    , MeshProcess(process)
-  {
-  }
-
-  bool initialize(QStringList& parms, QWidget* parent);
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_ANY))
-      return false;
-    Mesh* m = currentMesh();
-    return (*this)(m, parms[0], parms[1].toInt(), parms[2].toFloat());
-  }
-
-  bool operator()(Mesh* mesh, const QString& filename, int column, float border_size);
-
-  QString folder() const {
-    return "Heat Map";
-  }
-  QString name() const {
-    return "Load Heat Map";
-  }
-  QString description() const {
-    return "Load a heat map file and set the corresponding heat for each label";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Filename"
-                         << "Column" << QString("Border size (%1)").arg(UM);
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Path to spreadsheat file."
-                         << "Column of the csv file to load for display.\n"
-              "Label: cell labels, Value: original computed values (e.g. growth or signal), Heat: "
-              "values scaled for visualization (always between 0-1)."
-                         << "Width of cell outline used for vizualization of 'wall' colormaps";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << ""
-                         << "2"
-                         << "1.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/MakeHeatMap.png");
-  }
-
-public slots:
-  void selectFile(const QString& filename);
-  void selectFile();
-  void selectColumn(int c);
-
-protected:
-  QDialog* dlg;
-  Ui_LoadHeatMap* ui;
-  QList<QString> column_unit;
-};
-
-/**
- * \class SaveParents MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
- *
- * Store mapping from each label to a label in a different mesh (parent).
- * \author Gerardo Tauriello
- */
-class MGX_EXPORT SaveParents : public MeshProcess {
-public:
-  SaveParents(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool initialize(QStringList& parms, QWidget* parent);
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_ANY))
-      return false;
-    Mesh* m = currentMesh();
-    return (*this)(m, parms[0]);
-  }
-
-  bool operator()(Mesh* mesh, const QString& filename);
-
-  QString folder() const {
-    return "Lineage Tracking";
-  }
-  QString name() const {
-    return "Save Parents";
-  }
-  QString description() const {
-    return "Save map of labels to parents labels to a file";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Filename";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Path to label parents file.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Parents.png");
-  }
-};
-
-/**
- * \class LoadParents MeshProcessHeatMap.hpp <MeshProcessHeatMap.hpp>
- *
- * Load mapping from each label to a label in a different mesh (parent).
- * \author Gerardo Tauriello
- */
-class MGX_EXPORT LoadParents : public MeshProcess {
-public:
-  LoadParents(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool initialize(QStringList& parms, QWidget* parent);
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_ANY))
-      return false;
-    Mesh* m = currentMesh();
-    return (*this)(m, parms[0]);
-  }
-
-  bool operator()(Mesh* mesh, const QString& filename);
-
-  QString folder() const {
-    return "Lineage Tracking";
-  }
-  QString name() const {
-    return "Load Parents";
-  }
-  QString description() const {
-    return "Load map of labels to parents from a file";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Filename";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Path to label parents file.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Parents.png");
-  }
-};
-
-/**
- * Clear label to parent mapping
- * \author Gerardo Tauriello
- */
-class MGX_EXPORT ClearParents : public MeshProcess {
-public:
-  ClearParents(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList&)
-  {
-    if(!checkState().mesh(MESH_ANY))
-      return false;
-    Mesh* m = currentMesh();
-    return (*this)(m);
-  }
-
-  bool operator()(Mesh* mesh);
-
-  QString folder() const {
-    return "Lineage Tracking";
-  }
-  QString name() const {
-    return "Clear Parents";
-  }
-  QString description() const {
-    return "Clear mapping from parents to labels";
-  }
-  QStringList parmNames() const {
-    return QStringList();
-  }
-  QStringList parmDescs() const {
-    return QStringList();
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Parents.png");
-  }
-};
-///@}
-} // namespace process
-} // namespace mgx
-
 #endif
Index: MeshProcessSignal.cpp
===================================================================
--- MeshProcessSignal.cpp	(revision 1255)
+++ MeshProcessSignal.cpp	(revision 1256)
@@ -5,813 +5,767 @@
 #include "ui_LoadHeatMap.h"
 #include <omp.h>
 
-namespace mgx {
-namespace process {
+namespace mgx { namespace process {
 
-using namespace util;
-
-bool ViewMeshProcess::operator()(const QStringList& parms)
-{
-  QStringList warning;
-
-  Mesh* m = currentMesh();
-
-  if(not m)
-    return setErrorMessage("Error, you need an active mesh");
-
-  if(not parms[0].isEmpty()) {
-    if(stringToBool(parms[0]))
-      m->showSurface();
-    else
-      m->hideSurface();
+  using namespace util;
+  
+  bool ViewMeshProcess::operator()(const QStringList& parms)
+  {
+    QStringList warning;
+  
+    Mesh* m = currentMesh();
+  
+    if(not m)
+      return setErrorMessage("Error, you need an active mesh");
+  
+    if(not parms[0].isEmpty()) {
+      if(stringToBool(parms[0]))
+        m->showSurface();
+      else
+        m->hideSurface();
+    }
+    if(not parms[1].isEmpty()) {
+      if(parms[1] == "Normal")
+        m->showNormal();
+      else if(parms[1] == "Heat")
+        m->showHeat();
+      else if(parms[1] == "Label")
+        m->showLabel();
+      else
+        warning << QString("Invalid surface type '%1'").arg(parms[1]);
+    }
+    if(not parms[2].isEmpty()) {
+      if(parms[2] == "Signal")
+        m->showSignal();
+      else if(parms[2] == "Texture")
+        m->showTexture();
+      else if(parms[2] == "Image")
+        m->showImage();
+      else
+        warning << QString("Invalid signal type '%1'").arg(parms[2]);
+    }
+    if(not parms[3].isEmpty())
+      m->setBlending(stringToBool(parms[3]));
+    if(not parms[4].isEmpty())
+      m->setCulling(stringToBool(parms[4]));
+    if(not parms[5].isEmpty()) {
+      if(stringToBool(parms[5]))
+        m->showMesh();
+      else
+        m->hideMesh();
+    }
+    if(not parms[6].isEmpty()) {
+      if(parms[6] == "All")
+        m->showAllMesh();
+      else if(parms[6] == "Border")
+        m->showBorderMesh();
+      else if(parms[6] == "Cells")
+        m->showCellMesh();
+      else if(parms[6] == "Selected")
+        m->showSelectedMesh();
+      else
+        warning << QString("Invalid mesh view '%1'").arg(parms[6]);
+    }
+    if(not parms[7].isEmpty())
+      m->setShowMeshLines(stringToBool(parms[7]));
+    if(not parms[8].isEmpty())
+      m->setShowMeshPoints(stringToBool(parms[8]));
+    if(not parms[9].isEmpty())
+      m->setShowMeshCellMap(stringToBool(parms[9]));
+    if(not parms[10].isEmpty())
+      m->setScaled(stringToBool(parms[10]));
+    if(not parms[11].isEmpty())
+      m->setTransformed(stringToBool(parms[11]));
+    if(not parms[12].isEmpty())
+      m->setShowBBox(stringToBool(parms[12]));
+    if(parms[13].toFloat() >= 0)
+      m->setBrightness(parms[13].toFloat());
+    if(parms[14].toFloat() >= 0)
+      m->setOpacity(parms[14].toFloat());
+    if(not warning.isEmpty())
+      setWarningMessage(warning.join("\n"));
+    return true;
   }
-  if(not parms[1].isEmpty()) {
-    if(parms[1] == "Normal")
-      m->showNormal();
-    else if(parms[1] == "Heat")
-      m->showHeat();
-    else if(parms[1] == "Label")
-      m->showLabel();
-    else
-      warning << QString("Invalid surface type '%1'").arg(parms[1]);
+  REGISTER_MESH_PROCESS(ViewMeshProcess);
+  
+  Point2f calcSignalBounds(const vvgraph &S)
+  {
+    if(S.size() == 0)
+      return  Point2f(0,0);
+  
+    float minSig = std::numeric_limits<float>::max();
+    float maxSig = std::numeric_limits<float>::min();
+    forall(const vertex &v, S) {
+      if(minSig > v->signal)
+        minSig = v->signal;
+      if(maxSig < v->signal)
+        maxSig = v->signal;
+    }
+    return Point2f(minSig, maxSig);
   }
-  if(not parms[2].isEmpty()) {
-    if(parms[2] == "Signal")
-      m->showSignal();
-    else if(parms[2] == "Texture")
-      m->showTexture();
-    else if(parms[2] == "Image")
-      m->showImage();
-    else
-      warning << QString("Invalid signal type '%1'").arg(parms[2]);
+  
+  void ProjectSignal::projSignal(const Stack* stack, const HVecUS& data, vertex v, float mindist, float maxdist)
+  {
+    Point3f vpos = v->pos;
+    Point3f vnrml = v->nrml;
+    if(stack->showScale() and norm(stack->scale()) != 1.0) {
+      vpos = divide(vpos, stack->scale());
+      vnrml = divide(vnrml, stack->scale());
+    }
+    Point3f pmin = (vpos - vnrml * mindist);
+    Point3f pmax = (vpos - vnrml * maxdist);
+    // Point3i vi = stack->worldToImagei(vpos);
+    Point3i pimin = stack->worldToImagei(pmin);
+    Point3i pimax = stack->worldToImagei(pmax);
+    int steps = int((pimax - pimin).norm() * 2 + 3);
+  
+    float sum = 0;
+    for(int i = 0; i <= steps; i++) {
+      Point3i oi = stack->worldToImagei(pmax + v->nrml * (maxdist - mindist) * float(i) / float(steps));
+      if(stack->boundsOK(oi.x(), oi.y(), oi.z()))
+        sum += data[stack->offset(oi.x(), oi.y(), oi.z())];
+    }
+    v->signal = float(sum) / float(steps);
   }
-  if(not parms[3].isEmpty())
-    m->setBlending(stringToBool(parms[3]));
-  if(not parms[4].isEmpty())
-    m->setCulling(stringToBool(parms[4]));
-  if(not parms[5].isEmpty()) {
-    if(stringToBool(parms[5]))
-      m->showMesh();
+  
+  bool ProjectSignal::operator()(const Store* store, Mesh* mesh, bool useAbsSignal, float mindist, 
+    float maxdist, float absSignalMin, float absSignalMax)
+  {
+    const VtxVec& vs = mesh->activeVertices();
+    mesh->setNormals();
+    const HVecUS& data = store->data();
+    float avgSignal = 0, maxSignal = -FLT_MAX, minSignal = FLT_MAX;
+    const Stack* stack = store->stack();
+  
+    #pragma omp parallel for
+    for(size_t i = 0; i < vs.size(); ++i)
+      projSignal(stack, data, vs[i], mindist, maxdist);
+  
+  
+    if(useAbsSignal)
+      mesh->signalBounds() = Point2f(absSignalMin, absSignalMax);
     else
-      m->hideMesh();
+      mesh->signalBounds() = calcSignalBounds(mesh->graph());
+  
+    SETSTATUS("Signal projection, min:" << mesh->signalBounds().x() << " max:" << mesh->signalBounds().y());
+    mesh->signalUnit() = "";
+    mesh->updateTriangles();
+    return true;
   }
-  if(not parms[6].isEmpty()) {
-    if(parms[6] == "All")
-      m->showAllMesh();
-    else if(parms[6] == "Border")
-      m->showBorderMesh();
-    else if(parms[6] == "Cells")
-      m->showCellMesh();
-    else if(parms[6] == "Selected")
-      m->showSelectedMesh();
-    else
-      warning << QString("Invalid mesh view '%1'").arg(parms[6]);
+  REGISTER_MESH_PROCESS(ProjectSignal);
+  
+  bool SmoothMeshSignal::operator()(Mesh* mesh, uint passes)
+  {
+    vvgraph& S = mesh->graph();
+    const std::vector<vertex>& vs = mesh->activeVertices();
+    if(vs.empty())
+      return true;
+    for(uint i = 0; i < passes; i++) {
+      forall(const vertex& v, vs) {
+        float tarea = 0;
+        v->tsignal = 0;
+        forall(const vertex& n, S.neighbors(v)) {
+          vertex m = S.nextTo(v, n);
+          if(!S.edge(m, n))
+            continue;
+          float a = triangleArea(v->pos, n->pos, m->pos);
+          tarea += a;
+          v->tsignal += a * (v->signal + n->signal + m->signal) / 3.0;
+        }
+        if(tarea > 0)
+          v->tsignal /= tarea;
+        else
+          v->tsignal = v->signal;
+      }
+      forall(const vertex& v, vs)
+        v->signal = v->tsignal;
+    }
+    mesh->updateTriangles();
+    return true;
   }
-  if(not parms[7].isEmpty())
-    m->setShowMeshLines(stringToBool(parms[7]));
-  if(not parms[8].isEmpty())
-    m->setShowMeshPoints(stringToBool(parms[8]));
-  if(not parms[9].isEmpty())
-    m->setShowMeshCellMap(stringToBool(parms[9]));
-  if(not parms[10].isEmpty())
-    m->setScaled(stringToBool(parms[10]));
-  if(not parms[11].isEmpty())
-    m->setTransformed(stringToBool(parms[11]));
-  if(not parms[12].isEmpty())
-    m->setShowBBox(stringToBool(parms[12]));
-  if(parms[13].toFloat() >= 0)
-    m->setBrightness(parms[13].toFloat());
-  if(parms[14].toFloat() >= 0)
-    m->setOpacity(parms[14].toFloat());
-  if(not warning.isEmpty())
-    setWarningMessage(warning.join("\n"));
-  return true;
-}
-REGISTER_MESH_PROCESS(ViewMeshProcess);
+  REGISTER_MESH_PROCESS(SmoothMeshSignal);
 
-Point2f calcSignalBounds(const vvgraph &S)
-{
-  if(S.size() == 0)
-    return  Point2f(0,0);
+  bool MeshBrightness::operator()(Mesh* mesh, float amount)
+  {
+    vvgraph& S = mesh->graph();
+    const std::vector<vertex>& vs = mesh->activeVertices();
+    if(vs.empty())
+      return true;
 
-  float minSig = std::numeric_limits<float>::max();
-  float maxSig = std::numeric_limits<float>::min();
-  forall(const vertex &v, S) {
-    if(minSig > v->signal)
-      minSig = v->signal;
-    if(maxSig < v->signal)
-      maxSig = v->signal;
-  }
-  return Point2f(minSig, maxSig);
-}
+    forall(const vertex& v, vs)
+      v->signal *= amount;
 
-void ProjectSignal::projSignal(const Stack* stack, const HVecUS& data, vertex v, float mindist, float maxdist)
-{
-  Point3f vpos = v->pos;
-  Point3f vnrml = v->nrml;
-  if(stack->showScale() and norm(stack->scale()) != 1.0) {
-    vpos = divide(vpos, stack->scale());
-    vnrml = divide(vnrml, stack->scale());
+    mesh->updateTriangles();
+    return true;
   }
-  Point3f pmin = (vpos - vnrml * mindist);
-  Point3f pmax = (vpos - vnrml * maxdist);
-  // Point3i vi = stack->worldToImagei(vpos);
-  Point3i pimin = stack->worldToImagei(pmin);
-  Point3i pimax = stack->worldToImagei(pmax);
-  int steps = int((pimax - pimin).norm() * 2 + 3);
-
-  float sum = 0;
-  for(int i = 0; i <= steps; i++) {
-    Point3i oi = stack->worldToImagei(pmax + v->nrml * (maxdist - mindist) * float(i) / float(steps));
-    if(stack->boundsOK(oi.x(), oi.y(), oi.z()))
-      sum += data[stack->offset(oi.x(), oi.y(), oi.z())];
+  REGISTER_MESH_PROCESS(MeshBrightness);
+ 
+  bool ClearMeshSignal::operator()(Mesh* mesh, uint value)
+  {
+    const std::vector<vertex>& vs = mesh->activeVertices();
+    if(vs.empty())
+      return true;
+    forall(const vertex& v, vs) {
+      v->signal = value;
+    }
+    SETSTATUS("Mesh signal set to:" << value);
+    mesh->signalUnit() = "";
+    mesh->updateTriangles();
+    return true;
   }
-  v->signal = float(sum) / float(steps);
-}
-
-bool ProjectSignal::operator()(const Store* store, Mesh* mesh, bool useAbsSignal, float mindist, float maxdist,
-                               float absSignalMin, float absSignalMax)
-{
-  const VtxVec& vs = mesh->activeVertices();
-  mesh->setNormals();
-  const HVecUS& data = store->data();
-  float avgSignal = 0, maxSignal = -FLT_MAX, minSignal = FLT_MAX;
-  const Stack* stack = store->stack();
-
-#pragma omp parallel for
-  for(size_t i = 0; i < vs.size(); ++i)
-    projSignal(stack, data, vs[i], mindist, maxdist);
-
-  forall(const vertex& v, vs) {
-    avgSignal += v->signal;
-    if(v->signal > maxSignal)
-      maxSignal = v->signal;
-    if(v->signal < minSignal)
-      minSignal = v->signal;
+  REGISTER_MESH_PROCESS(ClearMeshSignal);
+  
+  ProjectCurvatureOp::ProjectCurvatureOp(const vvgraph& _S, const VtxVec& _vs, std::string _type, float _radius,
+                                         FloatVec& _values, std::vector<Curvature>& _curvs)
+    : S(_S), vs(_vs), type(_type), radius(_radius), values(_values) , curvs(_curvs) {}
+  
+  void ProjectCurvatureOp::operator()(int i)
+  {
+    vertex v = vs[i];
+    VtxSet nbs;
+    Mesh::getNhbd(S, v, radius, nbs);
+  
+    std::vector<Point3f> plist, nlist;
+    plist.push_back(v->pos);
+    nlist.push_back(v->nrml);
+    forall(const vertex& n, nbs) {
+      if(n == v)
+        continue;
+      plist.push_back(n->pos);
+      nlist.push_back(n->nrml);
+    }
+    if(!curvs.empty()) {
+      curvs[i].update(plist, nlist);
+      v->signal = curvs[i].get_curvature();
+    } else {
+      Curvature curv(type);
+      curv.update(plist, nlist);
+      v->signal = curv.get_curvature();
+    }
+    if(!values.empty())
+      values[i] = v->signal;
   }
-
-  if(useAbsSignal) {
-    minSignal = absSignalMin;
-    maxSignal = absSignalMax;
+  
+  bool ProjectCurvature::operator()(Mesh* mesh, QString output, QString type, float radius, bool auto_scale,
+                                    float mincurv, float maxcurv, int percentile)
+  {
+    vvgraph& S = mesh->graph();
+    const std::vector<vertex>& vs = mesh->activeVertices();
+    if(vs.empty())
+      return true;
+    type = type.toLower();
+    if((type == "sumsquare" or type == "anisotropy") and mincurv < 0)
+      mincurv = 0;
+    if(!auto_scale and mincurv >= maxcurv)
+      return true;
+    if(auto_scale) {
+      mincurv = FLT_MAX;
+      maxcurv = -FLT_MAX;
+    }
+  
+    std::vector<float> values(auto_scale ? vs.size() : 0);
+    std::vector<Curvature> curvatures(output.isEmpty() ? 0 : vs.size());
+  
+    Progress progress(QString("Computing curvature for Mesh %1").arg(mesh->userId()),
+                      vs.size() / omp_get_max_threads());
+    ProjectCurvatureOp op(S, vs, type.toStdString(), radius, values, curvatures);
+    #pragma omp parallel for
+    for(size_t i = 0; i < vs.size(); ++i) {
+      if(!progress.advance(i))
+        continue;
+      op(i);
+    }
+    if(!progress.advance(vs.size()))
+      userCancel();
+  
+    if(auto_scale) {
+      std::sort(values.begin(), values.end());
+      int rankmax = values.size() - 1;
+      int rankmin = 0;
+      if(percentile < 100) {
+        rankmax = (values.size() * percentile) / 100;
+        rankmin = values.size() - rankmax;
+      }
+      mincurv = values[rankmin];
+      maxcurv = values[rankmax];
+      if(maxcurv * mincurv < 0) {
+        maxcurv = std::max(fabs(maxcurv), fabs(mincurv));
+        mincurv = -maxcurv;
+      } else if(maxcurv > 0)
+        mincurv = 0;
+      else if(mincurv < 0)
+        maxcurv = 0;
+      else {
+        mincurv = 0;
+        maxcurv = 1;
+      }
+    }
+  
+    if(!output.isEmpty()) {
+      QFile f(output);
+      if(f.open(QIODevice::WriteOnly)) {
+        QTextStream ts(&f);
+        ts << QString("X,Y,Z,X1,Label,Y1,Z1,X2,Y2,Z2,k1 (1/%1),k2 (1/%1)\n").arg(UM);
+        size_t i = 0;
+        forall(const vertex& v, S) {
+          const Point3f& pos = v->pos;
+          Curvature& curv = curvatures[i];
+          Point3f e1, e2;
+          float c1, c2;
+          curv.get_eigenVectors(e1, e2);
+          curv.get_eigenValues(c1, c2);
+          QStringList fields;
+          fields << QString::number(pos.x(), 'g', 10) << QString::number(pos.y(), 'g', 10)
+                 << QString::number(pos.z(), 'g', 10) << QString::number(v->label)
+                 << QString::number(e1.x(), 'g', 10) << QString::number(e1.y(), 'g', 10)
+                 << QString::number(e1.z(), 'g', 10) << QString::number(e2.x(), 'g', 10)
+                 << QString::number(e2.y(), 'g', 10) << QString::number(e2.z(), 'g', 10)
+                 << QString::number(c1, 'g', 10) << QString::number(c2, 'g', 10);
+          ts << fields.join(",") << "\n";
+          ++i;
+        }
+      } else
+        setWarningMessage(QString("Warning, could not open file '%1' for writing. Not output written").arg(output));
+    }
+  
+    if(type == "gaussian" or type == "sumsquare")
+      mesh->signalUnit() = UM_2;
+    else if(type == "anisotropy")
+      mesh->signalUnit() = "";
+    else
+      mesh->signalUnit() = UM_1;
+  
+    mesh->signalBounds() = Point2f(mincurv, maxcurv);
+  
+    mesh->showNormal();
+    mesh->showSignal();
+    mesh->updateTriangles();
+    return true;
   }
-  if(maxSignal == minSignal)
-    maxSignal = minSignal + 1;     // to avoid division by zero
-
-  SETSTATUS("Signal projection, Avg:" << avgSignal / float(vs.size()) << " min:" << minSignal
-                                      << " max:" << maxSignal);
-  mesh->signalUnit() = "";
-  mesh->signalBounds() = Point2f(minSignal, maxSignal);
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(ProjectSignal);
-
-bool SmoothMeshSignal::operator()(Mesh* mesh, uint passes)
-{
-  vvgraph& S = mesh->graph();
-  const std::vector<vertex>& vs = mesh->activeVertices();
-  if(vs.empty())
-    return true;
-  for(uint i = 0; i < passes; i++) {
-    forall(const vertex& v, vs) {
-      float tarea = 0;
-      v->tsignal = 0;
-      forall(const vertex& n, S.neighbors(v)) {
-        vertex m = S.nextTo(v, n);
-        if(!S.edge(m, n))
-          continue;
-        float a = triangleArea(v->pos, n->pos, m->pos);
-        tarea += a;
-        v->tsignal += a * (v->signal + n->signal + m->signal) / 3.0;
+  REGISTER_MESH_PROCESS(ProjectCurvature);
+  
+  MeshGaussianBlurOp::MeshGaussianBlurOp(const vvgraph& _S, const VtxVec& _vs, float _radius)
+    : S(_S) , vs(_vs) , radius(_radius) {}
+  
+  void MeshGaussianBlurOp::operator()(int i)
+  {
+    vertex v = vs[i];
+    float sigma = radius / 2;
+    VtxSet VSet;
+    float den = 0, num = 0, g = 0, ar = 0, wt = 0;
+    Mesh::getNhbd(S, v, radius, VSet);   // Neighbourhood processing
+  
+    // Gaussian blur over the cell
+    forall(const vertex& r, VSet) {
+      if(norm(r->pos - v->pos) < radius) {
+        den = sqrt(6.28 * (pow(sigma, 2)));
+        num = exp(-(pow((norm(r->pos - v->pos)), 2) / (2 * pow(sigma, 2))));
+        g = num / den;
+        ar = ar + (g * (r->signal));
+        wt = wt + g;
       }
-      if(tarea > 0)
-        v->tsignal /= tarea;
-      else
-        v->tsignal = v->signal;
     }
+    v->tsignal = ar / wt;   // Blurring the signal
+  }
+  
+  bool MeshGaussianBlur::operator()(Mesh* mesh, float radius)
+  {
+    vvgraph& S = mesh->graph();
+    const VtxVec& vs = mesh->activeVertices();
+  
+    Progress progress(QString("Gaussian Blur on Mesh %1").arg(mesh->userId()), vs.size() / omp_get_max_threads());
+    MeshGaussianBlurOp op(S, vs, radius);
+    #pragma omp parallel for
+    for(size_t i = 0; i < vs.size(); ++i) {
+      if(!progress.advance(i))
+        continue;
+      op(i);
+    }
+    if(!progress.advance(vs.size()))
+      userCancel();
+  
+    // Update the Signal
     forall(const vertex& v, vs)
       v->signal = v->tsignal;
+  
+    mesh->updateTriangles();
+    return true;
   }
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(SmoothMeshSignal);
-
-bool ClearMeshSignal::operator()(Mesh* mesh, uint value)
-{
-  const std::vector<vertex>& vs = mesh->activeVertices();
-  if(vs.empty())
+  REGISTER_MESH_PROCESS(MeshGaussianBlur);
+  
+  bool MeshDiffGaussians::operator()(Mesh* mesh, float radius1, float radius2)
+  {
+    vvgraph& S = mesh->graph();
+    const VtxVec& vs = mesh->activeVertices();
+  
+    // Find first Gaussian
+    std::vector<float> firstGauss(vs.size());
+    Progress progress(QString("Calculating first Gaussian on Mesh %1").arg(mesh->userId()), vs.size() / omp_get_max_threads());
+    if(radius1 > 0) {
+      MeshGaussianBlurOp op1(S, vs, radius1);
+      #pragma omp parallel for
+      for(size_t i = 0; i < vs.size(); ++i) {
+        if(!progress.advance(i))
+          continue;
+        op1(i);
+      }
+      if(!progress.advance(vs.size()))
+        userCancel();
+  
+      // Save the mesh signal
+      #pragma omp parallel for
+      for(size_t i = 0; i < vs.size(); ++i)
+        firstGauss[i] = vs[i]->tsignal;
+    } else {
+      // Just save the mesh signal
+      #pragma omp parallel for
+      for(size_t i = 0; i < vs.size(); ++i)
+        firstGauss[i] = vs[i]->signal;
+    }
+  
+    // Find second Gaussian
+    progress.restart(QString("Calculating second Gaussian on Mesh %1").arg(mesh->userId()), vs.size() / omp_get_max_threads());
+    MeshGaussianBlurOp op2(S, vs, radius2);
+    #pragma omp parallel for
+    for(size_t i = 0; i < vs.size(); ++i) {
+      if(!progress.advance(i))
+        continue;
+      op2(i);
+    }
+    if(!progress.advance(vs.size()))
+      userCancel();
+  
+    // Update the Signal
+    for(size_t i = 0; i < vs.size(); ++i)
+      vs[i]->signal = firstGauss[i] - vs[i]->tsignal;
+  
+    mesh->signalBounds() = calcSignalBounds(mesh->graph());
+    mesh->updateTriangles();
     return true;
-  forall(const vertex& v, vs) {
-    v->signal = value;
   }
-  SETSTATUS("Mesh signal set to:" << value);
-  mesh->signalUnit() = "";
-  mesh->signalBounds() = Point2f(0, 65535);
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(ClearMeshSignal);
-
-ProjectCurvatureOp::ProjectCurvatureOp(const vvgraph& _S, const VtxVec& _vs, std::string _type, float _radius,
-                                       FloatVec& _values, std::vector<Curvature>& _curvs)
-  : S(_S)
-  , vs(_vs)
-  , type(_type)
-  , radius(_radius)
-  , values(_values)
-  , curvs(_curvs)
-{
-}
-
-void ProjectCurvatureOp::operator()(int i)
-{
-  vertex v = vs[i];
-  VtxSet nbs;
-  Mesh::getNhbd(S, v, radius, nbs);
-
-  std::vector<Point3f> plist, nlist;
-  plist.push_back(v->pos);
-  nlist.push_back(v->nrml);
-  forall(const vertex& n, nbs) {
-    if(n == v)
-      continue;
-    plist.push_back(n->pos);
-    nlist.push_back(n->nrml);
+  REGISTER_MESH_PROCESS(MeshDiffGaussians);
+  
+  MeshLocalMinimaOp::MeshLocalMinimaOp(const vvgraph& _S, const VtxVec& _vs, float _radius, int _label)
+    : S(_S) , vs(_vs) , radius(_radius) , label(_label) {}
+  
+  void MeshLocalMinimaOp::operator()(int i)
+  {
+    vertex v = vs[i];
+    VtxSet VSet;
+    Mesh::getNhbd(S, v, radius, VSet);   // Neighbourhood processing
+  
+    // Finding the lowest v->signal in the set of vertices respective to a cell
+    float lowest = HUGE_VAL;
+    forall(const vertex& r, VSet)
+      if(r->signal < lowest)
+        lowest = r->signal;
+  
+    // Label the vertex at the local minima
+    if(v->signal == lowest)
+      v->label = label;
   }
-  if(!curvs.empty()) {
-    curvs[i].update(plist, nlist);
-    v->signal = curvs[i].get_curvature();
-  } else {
-    Curvature curv(type);
-    curv.update(plist, nlist);
-    v->signal = curv.get_curvature();
-  }
-  if(!values.empty())
-    values[i] = v->signal;
-}
-
-bool ProjectCurvature::operator()(Mesh* mesh, QString output, QString type, float radius, bool auto_scale,
-                                  float mincurv, float maxcurv, int percentile)
-{
-  vvgraph& S = mesh->graph();
-  const std::vector<vertex>& vs = mesh->activeVertices();
-  if(vs.empty())
+  
+  bool MeshLocalMinima::operator()(Mesh* mesh, float radius)
+  {
+    vvgraph& S = mesh->graph();
+    const VtxVec& vs = mesh->activeVertices();
+  
+    Progress progress(QString("Finding Local Minima for Mesh %1").arg(mesh->userId()),
+                      vs.size() / omp_get_max_threads());
+    int startLabel = mesh->nextLabel();
+    MeshLocalMinimaOp op(S, vs, radius, startLabel);
+    #pragma omp parallel for
+    for(size_t i = 0; i < vs.size(); ++i) {
+      if(!progress.advance(i))
+        continue;
+      op(i);
+    }
+    if(!progress.advance(vs.size()))
+      userCancel();
+    for(size_t i = 0; i < vs.size(); ++i)
+      if(vs[i]->label == startLabel) {
+        int label = mesh->nextLabel();
+        vs[i]->label = label;
+        forall(const vertex& n, S.neighbors(vs[i]))
+          n->label = label;
+      }
+  
+    mesh->showLabel();
+    mesh->updateTriangles();
     return true;
-  type = type.toLower();
-  if((type == "sumsquare" or type == "anisotropy") and mincurv < 0)
-    mincurv = 0;
-  if(!auto_scale and mincurv >= maxcurv)
-    return true;
-  if(auto_scale) {
-    mincurv = FLT_MAX;
-    maxcurv = -FLT_MAX;
   }
-
-  std::vector<float> values(auto_scale ? vs.size() : 0);
-  std::vector<Curvature> curvatures(output.isEmpty() ? 0 : vs.size());
-
-  Progress progress(QString("Computing curvature for Mesh %1").arg(mesh->userId()),
-                    vs.size() / omp_get_max_threads());
-  ProjectCurvatureOp op(S, vs, type.toStdString(), radius, values, curvatures);
-#pragma omp parallel for
-  for(size_t i = 0; i < vs.size(); ++i) {
-    if(!progress.advance(i))
-      continue;
-    op(i);
+  REGISTER_MESH_PROCESS(MeshLocalMinima);
+  
+  MeshNormalizeOp::MeshNormalizeOp(const vvgraph& _S, const VtxVec& _vs, float _radius)
+    : S(_S) , vs(_vs) , radius(_radius) {}
+  
+  void MeshNormalizeOp::operator()(int i)
+  {
+    VtxSet VSet;
+    vertex v = vs[i];
+    float min = HUGE_VAL;
+    float max = 0;
+    Mesh::getNhbd(S, v, radius, VSet);
+  
+    // Normalizing the signal of mesh
+    forall(const vertex& n, VSet) {
+      if(min > n->signal)
+        min = n->signal;
+      if(max < n->signal)
+        max = n->signal;
+    }
+    v->tsignal = (v->signal - min) / (max - min);
   }
-  if(!progress.advance(vs.size()))
-    userCancel();
-
-  if(auto_scale) {
-    std::sort(values.begin(), values.end());
-    int rankmax = values.size() - 1;
-    int rankmin = 0;
-    if(percentile < 100) {
-      rankmax = (values.size() * percentile) / 100;
-      rankmin = values.size() - rankmax;
+  
+  bool MeshNormalize::operator()(Mesh* mesh, float radius)
+  {
+    vvgraph& S = mesh->graph();
+    const VtxVec& vs = mesh->activeVertices();
+    Progress progress(QString("Normalizing Signal on Mesh %1").arg(mesh->userId()), vs.size() / omp_get_max_threads());
+    MeshNormalizeOp op(S, vs, radius);
+  
+    #pragma omp parallel for
+    for(size_t i = 0; i < vs.size(); ++i) {
+      if(!progress.advance(i))
+        continue;
+      op(i);
     }
-    mincurv = values[rankmin];
-    maxcurv = values[rankmax];
-    if(maxcurv * mincurv < 0) {
-      maxcurv = std::max(fabs(maxcurv), fabs(mincurv));
-      mincurv = -maxcurv;
-    } else if(maxcurv > 0)
-      mincurv = 0;
-    else if(mincurv < 0)
-      maxcurv = 0;
-    else {
-      mincurv = 0;
-      maxcurv = 1;
+    if(!progress.advance(vs.size()))
+      userCancel();
+  
+    // Update the Signal
+    forall(const vertex& v, vs) {
+      v->signal = v->tsignal * 65535.0;
     }
+  
+    mesh->signalBounds() = calcSignalBounds(S);
+    mesh->updateTriangles();
+    return true;
   }
-
-  if(!output.isEmpty()) {
-    QFile f(output);
-    if(f.open(QIODevice::WriteOnly)) {
-      QTextStream ts(&f);
-      ts << QString("X,Y,Z,X1,Label,Y1,Z1,X2,Y2,Z2,k1 (1/%1),k2 (1/%1)\n").arg(UM);
-      size_t i = 0;
-      forall(const vertex& v, S) {
-        const Point3f& pos = v->pos;
-        Curvature& curv = curvatures[i];
-        Point3f e1, e2;
-        float c1, c2;
-        curv.get_eigenVectors(e1, e2);
-        curv.get_eigenValues(c1, c2);
-        QStringList fields;
-        fields << QString::number(pos.x(), 'g', 10) << QString::number(pos.y(), 'g', 10)
-               << QString::number(pos.z(), 'g', 10) << QString::number(v->label)
-               << QString::number(e1.x(), 'g', 10) << QString::number(e1.y(), 'g', 10)
-               << QString::number(e1.z(), 'g', 10) << QString::number(e2.x(), 'g', 10)
-               << QString::number(e2.y(), 'g', 10) << QString::number(e2.z(), 'g', 10)
-               << QString::number(c1, 'g', 10) << QString::number(c2, 'g', 10);
-        ts << fields.join(",") << "\n";
-        ++i;
-      }
-    } else
-      setWarningMessage(QString("Warning, could not open file '%1' for writing. Not output written").arg(output));
-  }
-
-  if(type == "gaussian" or type == "sumsquare")
-    mesh->signalUnit() = UM_2;
-  else if(type == "anisotropy")
-    mesh->signalUnit() = "";
-  else
-    mesh->signalUnit() = UM_1;
-  mesh->signalBounds() = Point2f(mincurv, maxcurv);
-
-  mesh->showNormal();
-  mesh->showSignal();
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(ProjectCurvature);
-
-MeshGaussianBlurOp::MeshGaussianBlurOp(const vvgraph& _S, const VtxVec& _vs, float _radius)
-  : S(_S)
-  , vs(_vs)
-  , radius(_radius)
-{
-}
-
-void MeshGaussianBlurOp::operator()(int i)
-{
-  vertex v = vs[i];
-  float sigma = radius / 2;
-  VtxSet VSet;
-  float den = 0, num = 0, g = 0, ar = 0, wt = 0;
-  Mesh::getNhbd(S, v, radius, VSet);   // Neighbourhood processing
-
-  // Gaussian blur over the cell
-  forall(const vertex& r, VSet) {
-    if(norm(r->pos - v->pos) < radius) {
-      den = sqrt(6.28 * (pow(sigma, 2)));
-      num = exp(-(pow((norm(r->pos - v->pos)), 2) / (2 * pow(sigma, 2))));
-      g = num / den;
-      ar = ar + (g * (r->signal));
-      wt = wt + g;
+  REGISTER_MESH_PROCESS(MeshNormalize);
+  
+  MeshDilationOp::MeshDilationOp(const vvgraph& _S, const VtxVec& _vs, float _radius)
+    : S(_S) , vs(_vs) , radius(_radius) {}
+  
+  void MeshDilationOp::operator()(int i)
+  {
+    VtxSet VSet;
+    vertex v = vs[i];
+    float max = -FLT_MAX;
+    Mesh::getNhbd(S, v, radius, VSet);
+  
+    // Dilation
+    forall(const vertex& n, VSet)
+      if(max < n->signal)
+        max = n->signal;
+  
+    v->tsignal = max;
+  };
+  
+  bool MeshDilation::operator()(Mesh* mesh, float radius)
+  {
+    vvgraph& S = mesh->graph();
+    const VtxVec& vs = mesh->activeVertices();
+    VtxSet VSet;
+    Progress progress(QString("Dilating Signal on Mesh %1").arg(mesh->userId()), vs.size() / omp_get_max_threads());
+    MeshDilationOp op(S, vs, radius);
+  
+    #pragma omp parallel for
+    for(size_t i = 0; i < vs.size(); ++i) {
+      if(!progress.advance(i))
+        continue;
+      op(i);
     }
+    if(!progress.advance(vs.size()))
+      userCancel();
+  
+    // Update the signal
+    forall(const vertex& v, vs)
+      v->signal = v->tsignal;
+  
+    mesh->updateTriangles();
+    return true;
   }
-  v->tsignal = ar / wt;   // Blurring the signal
-}
-
-bool MeshGaussianBlur::operator()(Mesh* mesh, float radius)
-{
-  vvgraph& S = mesh->graph();
-  const VtxVec& vs = mesh->activeVertices();
-
-  Progress progress(QString("Gaussian Blur on Mesh %1").arg(mesh->userId()), vs.size() / omp_get_max_threads());
-  MeshGaussianBlurOp op(S, vs, radius);
-#pragma omp parallel for
-  for(size_t i = 0; i < vs.size(); ++i) {
-    if(!progress.advance(i))
-      continue;
-    op(i);
-  }
-  if(!progress.advance(vs.size()))
-    userCancel();
-
-  // Update the Signal
-  Point2f sb = mesh->signalBounds();
-  if(sb.x() >= sb.y())
-    sb = mesh->signalBounds() = Point2f(0, 65535);
-  forall(const vertex& v, vs)
-    v->signal = v->tsignal;
-
-  mesh->signalBounds() = calcSignalBounds(mesh->graph());
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(MeshGaussianBlur);
-
-bool MeshDiffGaussians::operator()(Mesh* mesh, float radius1, float radius2)
-{
-  vvgraph& S = mesh->graph();
-  const VtxVec& vs = mesh->activeVertices();
-
-  // Find first Gaussian
-  std::vector<float> firstGauss(vs.size());
-  Progress progress(QString("Calculating first Gaussian on Mesh %1").arg(mesh->userId()), vs.size() / omp_get_max_threads());
-  if(radius1 > 0) {
-    MeshGaussianBlurOp op1(S, vs, radius1);
+  REGISTER_MESH_PROCESS(MeshDilation);
+  
+  MeshErosionOp::MeshErosionOp(const vvgraph& _S, const VtxVec& _vs, float _radius)
+    : S(_S) , vs(_vs) , radius(_radius) {}
+  
+  void MeshErosionOp::operator()(int i)
+  {
+    VtxSet VSet;
+    vertex v = vs[i];
+    float min = FLT_MAX;
+    Mesh::getNhbd(S, v, radius, VSet);
+  
+    // Erosion
+    forall(const vertex& n, VSet)
+      if(min > n->signal)
+        min = n->signal;
+  
+    v->tsignal = min;
+  };
+  
+  bool MeshErosion::operator()(Mesh* mesh, float radius)
+  {
+    vvgraph& S = mesh->graph();
+    const VtxVec& vs = mesh->activeVertices();
+    VtxSet VSet;
+    Progress progress(QString("Eroding Signal on Mesh %1").arg(mesh->userId()), vs.size() / omp_get_max_threads());
+    MeshErosionOp op(S, vs, radius);
+  
     #pragma omp parallel for
     for(size_t i = 0; i < vs.size(); ++i) {
       if(!progress.advance(i))
         continue;
-      op1(i);
+      op(i);
     }
     if(!progress.advance(vs.size()))
       userCancel();
-
-    // Save the mesh signal
+  
+    // Update the signal
+    forall(const vertex& v, vs)
+      v->signal = v->tsignal;
+  
+    mesh->updateTriangles();
+    return true;
+  }
+  REGISTER_MESH_PROCESS(MeshErosion);
+  
+  bool MeshClosing::operator()(Mesh* mesh, float radius)
+  {
+    vvgraph& S = mesh->graph();
+    const VtxVec& vs = mesh->activeVertices();
+    VtxSet VSet;
+    int steps = vs.size() / omp_get_max_threads();
+    Progress progress(QString("Closing Signal on Mesh %1").arg(mesh->userId()), 2 * vs.size() / omp_get_max_threads());
+    MeshDilationOp opD(S, vs, radius);
+  
     #pragma omp parallel for
-    for(size_t i = 0; i < vs.size(); ++i)
-      firstGauss[i] = vs[i]->tsignal;
-  } else {
-    // Just save the mesh signal
+    for(size_t i = 0; i < vs.size(); ++i) {
+      if(!progress.advance(i))
+        continue;
+      opD(i);
+    }
+    if(!progress.advance(steps))
+      userCancel();
+  
+    forall(const vertex& v, vs)
+      v->signal = v->tsignal;
+  
+    MeshErosionOp opE(S, vs, radius);
+  
     #pragma omp parallel for
-    for(size_t i = 0; i < vs.size(); ++i)
-      firstGauss[i] = vs[i]->signal;
-  }
-
-  // Find second Gaussian
-  progress.restart(QString("Calculating second Gaussian on Mesh %1").arg(mesh->userId()), vs.size() / omp_get_max_threads());
-  MeshGaussianBlurOp op2(S, vs, radius2);
-  #pragma omp parallel for
-  for(size_t i = 0; i < vs.size(); ++i) {
-    if(!progress.advance(i))
-      continue;
-    op2(i);
-  }
-  if(!progress.advance(vs.size()))
-    userCancel();
-
-  // Update the Signal
-  for(size_t i = 0; i < vs.size(); ++i)
-    vs[i]->signal = firstGauss[i] - vs[i]->tsignal;
-
-  mesh->signalBounds() = calcSignalBounds(mesh->graph());
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(MeshDiffGaussians);
-
-MeshLocalMinimaOp::MeshLocalMinimaOp(const vvgraph& _S, const VtxVec& _vs, float _radius, int _label)
-  : S(_S)
-  , vs(_vs)
-  , radius(_radius)
-  , label(_label)
-{
-}
-
-void MeshLocalMinimaOp::operator()(int i)
-{
-  vertex v = vs[i];
-  VtxSet VSet;
-  Mesh::getNhbd(S, v, radius, VSet);   // Neighbourhood processing
-
-  // Finding the lowest v->signal in the set of vertices respective to a cell
-  float lowest = HUGE_VAL;
-  forall(const vertex& r, VSet)
-    if(r->signal < lowest)
-      lowest = r->signal;
-
-  // Label the vertex at the local minima
-  if(v->signal == lowest)
-    v->label = label;
-}
-
-bool MeshLocalMinima::operator()(Mesh* mesh, float radius)
-{
-  vvgraph& S = mesh->graph();
-  const VtxVec& vs = mesh->activeVertices();
-
-  Progress progress(QString("Finding Local Minima for Mesh %1").arg(mesh->userId()),
-                    vs.size() / omp_get_max_threads());
-  int startLabel = mesh->nextLabel();
-  MeshLocalMinimaOp op(S, vs, radius, startLabel);
-#pragma omp parallel for
-  for(size_t i = 0; i < vs.size(); ++i) {
-    if(!progress.advance(i))
-      continue;
-    op(i);
-  }
-  if(!progress.advance(vs.size()))
-    userCancel();
-  for(size_t i = 0; i < vs.size(); ++i)
-    if(vs[i]->label == startLabel) {
-      int label = mesh->nextLabel();
-      vs[i]->label = label;
-      forall(const vertex& n, S.neighbors(vs[i]))
-        n->label = label;
+    for(size_t i = 0; i < vs.size(); ++i) {
+      if(!progress.advance(steps + i))
+        continue;
+      opE(i);
     }
-
-  mesh->showLabel();
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(MeshLocalMinima);
-
-MeshNormalizeOp::MeshNormalizeOp(const vvgraph& _S, const VtxVec& _vs, float _radius)
-  : S(_S)
-  , vs(_vs)
-  , radius(_radius)
-{
-}
-
-void MeshNormalizeOp::operator()(int i)
-{
-  VtxSet VSet;
-  vertex v = vs[i];
-  float min = HUGE_VAL;
-  float max = 0;
-  Mesh::getNhbd(S, v, radius, VSet);
-
-  // Normalizing the signal of mesh
-  forall(const vertex& n, VSet) {
-    if(min > n->signal)
-      min = n->signal;
-    if(max < n->signal)
-      max = n->signal;
+    if(!progress.advance(steps * 2))
+      userCancel();
+  
+    // Update the signal
+    forall(const vertex& v, vs)
+      v->signal = v->tsignal;
+  
+    mesh->updateTriangles();
+    return true;
   }
-  v->tsignal = (v->signal - min) / (max - min);
-}
-
-bool MeshNormalize::operator()(Mesh* mesh, float radius)
-{
-  vvgraph& S = mesh->graph();
-  const VtxVec& vs = mesh->activeVertices();
-  Progress progress(QString("Normalizing Signal on Mesh %1").arg(mesh->userId()), vs.size() / omp_get_max_threads());
-  MeshNormalizeOp op(S, vs, radius);
-
-#pragma omp parallel for
-  for(size_t i = 0; i < vs.size(); ++i) {
-    if(!progress.advance(i))
-      continue;
-    op(i);
-  }
-  if(!progress.advance(vs.size()))
-    userCancel();
-
-  // Update the Signal
-  forall(const vertex& v, vs) {
-    v->signal = v->tsignal * 65535.0;
-  }
-
-  mesh->signalBounds() = Point2f(0, 65535.0);
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(MeshNormalize);
-
-MeshDilationOp::MeshDilationOp(const vvgraph& _S, const VtxVec& _vs, float _radius)
-  : S(_S)
-  , vs(_vs)
-  , radius(_radius)
-{
-}
-
-void MeshDilationOp::operator()(int i)
-{
-  VtxSet VSet;
-  vertex v = vs[i];
-  float max = -FLT_MAX;
-  Mesh::getNhbd(S, v, radius, VSet);
-
-  // Dilation
-  forall(const vertex& n, VSet)
-    if(max < n->signal)
-      max = n->signal;
-
-  v->tsignal = max;
-};
-
-bool MeshDilation::operator()(Mesh* mesh, float radius)
-{
-  vvgraph& S = mesh->graph();
-  const VtxVec& vs = mesh->activeVertices();
-  VtxSet VSet;
-  Progress progress(QString("Dilating Signal on Mesh %1").arg(mesh->userId()), vs.size() / omp_get_max_threads());
-  MeshDilationOp op(S, vs, radius);
-
-#pragma omp parallel for
-  for(size_t i = 0; i < vs.size(); ++i) {
-    if(!progress.advance(i))
-      continue;
-    op(i);
-  }
-  if(!progress.advance(vs.size()))
-    userCancel();
-
-  // Update the signal
-  Point2f sb = mesh->signalBounds();
-  if(sb.x() >= sb.y())
-    sb = mesh->signalBounds() = Point2f(0, 65535);
-  forall(const vertex& v, vs) {
-    v->signal = v->tsignal;
-  }
-
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(MeshDilation);
-
-MeshErosionOp::MeshErosionOp(const vvgraph& _S, const VtxVec& _vs, float _radius)
-  : S(_S)
-  , vs(_vs)
-  , radius(_radius)
-{
-}
-
-void MeshErosionOp::operator()(int i)
-{
-  VtxSet VSet;
-  vertex v = vs[i];
-  float min = FLT_MAX;
-  Mesh::getNhbd(S, v, radius, VSet);
-
-  // Erosion
-  forall(const vertex& n, VSet)
-    if(min > n->signal)
-      min = n->signal;
-
-  v->tsignal = min;
-};
-
-bool MeshErosion::operator()(Mesh* mesh, float radius)
-{
-  vvgraph& S = mesh->graph();
-  const VtxVec& vs = mesh->activeVertices();
-  VtxSet VSet;
-  Progress progress(QString("Eroding Signal on Mesh %1").arg(mesh->userId()), vs.size() / omp_get_max_threads());
-  MeshErosionOp op(S, vs, radius);
-
-#pragma omp parallel for
-  for(size_t i = 0; i < vs.size(); ++i) {
-    if(!progress.advance(i))
-      continue;
-    op(i);
-  }
-  if(!progress.advance(vs.size()))
-    userCancel();
-
-  // Update the signal
-  Point2f sb = mesh->signalBounds();
-  if(sb.x() >= sb.y())
-    sb = mesh->signalBounds() = Point2f(0, 65535);
-  forall(const vertex& v, vs) {
-    v->signal = v->tsignal;
-  }
-
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(MeshErosion);
-
-bool MeshClosing::operator()(Mesh* mesh, float radius)
-{
-  vvgraph& S = mesh->graph();
-  const VtxVec& vs = mesh->activeVertices();
-  VtxSet VSet;
-  int steps = vs.size() / omp_get_max_threads();
-  Progress progress(QString("Closing Signal on Mesh %1").arg(mesh->userId()), 2 * vs.size() / omp_get_max_threads());
-  MeshDilationOp opD(S, vs, radius);
-
-#pragma omp parallel for
-  for(size_t i = 0; i < vs.size(); ++i) {
-    if(!progress.advance(i))
-      continue;
-    opD(i);
-  }
-  if(!progress.advance(steps))
-    userCancel();
-
-  forall(const vertex& v, vs)
-    v->signal = v->tsignal;
-
-  MeshErosionOp opE(S, vs, radius);
-
-#pragma omp parallel for
-  for(size_t i = 0; i < vs.size(); ++i) {
-    if(!progress.advance(steps + i))
-      continue;
-    opE(i);
-  }
-  if(!progress.advance(steps * 2))
-    userCancel();
-
-  // Update the signal
-  Point2f sb = mesh->signalBounds();
-  if(sb.x() >= sb.y())
-    sb = mesh->signalBounds() = Point2f(0, 65535);
-  forall(const vertex& v, vs) {
-    v->signal = v->tsignal;
-  }
-
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(MeshClosing);
-
-bool MeshOpening::operator()(Mesh* mesh, float radius)
-{
-  vvgraph& S = mesh->graph();
-  const VtxVec& vs = mesh->activeVertices();
-  VtxSet VSet;
-  int steps = vs.size() / omp_get_max_threads();
-  Progress progress(QString("Opening Signal on Mesh %1").arg(mesh->userId()), 2 * vs.size() / omp_get_max_threads());
-  MeshErosionOp opE(S, vs, radius);
-
-#pragma omp parallel for
-  for(size_t i = 0; i < vs.size(); ++i) {
-    if(!progress.advance(steps + i))
-      continue;
-    opE(i);
-  }
-  if(!progress.advance(steps))
-    userCancel();
-
-  forall(const vertex& v, vs)
-    v->signal = v->tsignal;
-
-  MeshDilationOp opD(S, vs, radius);
-
-#pragma omp parallel for
-  for(size_t i = 0; i < vs.size(); ++i) {
-    if(!progress.advance(i))
-      continue;
-    opD(i);
-  }
-  if(!progress.advance(steps * 2))
-    userCancel();
-
-  // Update the signal
-  Point2f sb = mesh->signalBounds();
-  if(sb.x() >= sb.y())
-    sb = mesh->signalBounds() = Point2f(0, 65535);
-  forall(const vertex& v, vs) {
-    v->signal = v->tsignal;
-  }
-
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(MeshOpening);
-
-bool RescaleSignal::operator()(Mesh* mesh, bool use_zero, float percentile, float minimum, float maximum)
-{
-  if(percentile > 0) {
+  REGISTER_MESH_PROCESS(MeshClosing);
+  
+  bool MeshOpening::operator()(Mesh* mesh, float radius)
+  {
     vvgraph& S = mesh->graph();
-    std::vector<float> values(S.size());
-    int i = 0;
-    forall(const vertex& v, S)
-      values[i++] = v->signal;
-    std::sort(values.begin(), values.end());
-
-    int rankmax = values.size() - 1;
-    int rankmin = 0;
-    if(percentile < 100) {
-      rankmax = (values.size() * percentile) / 100;
-      rankmin = values.size() - rankmax;
+    const VtxVec& vs = mesh->activeVertices();
+    VtxSet VSet;
+    int steps = vs.size() / omp_get_max_threads();
+    Progress progress(QString("Opening Signal on Mesh %1").arg(mesh->userId()), 2 * vs.size() / omp_get_max_threads());
+    MeshErosionOp opE(S, vs, radius);
+  
+    #pragma omp parallel for
+    for(size_t i = 0; i < vs.size(); ++i) {
+      if(!progress.advance(steps + i))
+        continue;
+      opE(i);
     }
-    minimum = values[rankmin];
-    maximum = values[rankmax];
-    if(use_zero) {
-      if(minimum * maximum < 0) {
-        maximum = std::max(fabs(maximum), fabs(minimum));
-        minimum = -maximum;
-      } else if(maximum > 0)
-        minimum = 0;
-      else if(minimum < 0)
-        maximum = 0;
-      else {
-        minimum = 0;
-        maximum = 1;
+    if(!progress.advance(steps))
+      userCancel();
+  
+    forall(const vertex& v, vs)
+      v->signal = v->tsignal;
+  
+    MeshDilationOp opD(S, vs, radius);
+  
+    #pragma omp parallel for
+    for(size_t i = 0; i < vs.size(); ++i) {
+      if(!progress.advance(i))
+        continue;
+      opD(i);
+    }
+    if(!progress.advance(steps * 2))
+      userCancel();
+  
+    // Update the signal
+    forall(const vertex& v, vs)
+      v->signal = v->tsignal;
+  
+    mesh->updateTriangles();
+    return true;
+  }
+  REGISTER_MESH_PROCESS(MeshOpening);
+  
+  bool RescaleSignal::operator()(Mesh* mesh, bool use_zero, float percentile, float minimum, float maximum)
+  {
+    if(percentile > 0) {
+      vvgraph& S = mesh->graph();
+      std::vector<float> values(S.size());
+      int i = 0;
+      forall(const vertex& v, S)
+        values[i++] = v->signal;
+      std::sort(values.begin(), values.end());
+  
+      int rankmax = values.size() - 1;
+      int rankmin = 0;
+      if(percentile < 100) {
+        rankmax = (values.size() * percentile) / 100;
+        rankmin = values.size() - rankmax;
       }
+      minimum = values[rankmin];
+      maximum = values[rankmax];
+      if(use_zero) {
+        if(minimum * maximum < 0) {
+          maximum = std::max(fabs(maximum), fabs(minimum));
+          minimum = -maximum;
+        } else if(maximum > 0)
+          minimum = 0;
+        else if(minimum < 0)
+          maximum = 0;
+        else {
+          minimum = 0;
+          maximum = 1;
+        }
+      }
     }
+  
+    mesh->signalBounds() = Point2f(minimum, maximum);
+    return true;
   }
-  mesh->signalBounds() = Point2f(minimum, maximum);
-  return true;
-}
-
-REGISTER_MESH_PROCESS(RescaleSignal);
-
-bool SetSignalProcess::operator()(Mesh* m, float value, bool rescale, float percentile, bool use_zero)
-{
-  if(rescale and (percentile <= 0 or percentile > 100))
-    return setErrorMessage("Percentile must be greater than 0 and less or equal to 100.");
-  const std::vector<vertex>& vs = m->activeVertices();
-  forall(const vertex& v, vs)
-    v->signal = value;
-  if(rescale) {
-    RescaleSignal rescale(*this);
-    rescale(m, use_zero, percentile, 0, 0);
+  REGISTER_MESH_PROCESS(RescaleSignal);
+  
+  bool SetSignalProcess::operator()(Mesh* m, float value, bool rescale, float percentile, bool use_zero)
+  {
+    if(rescale and (percentile <= 0 or percentile > 100))
+      return setErrorMessage("Percentile must be greater than 0 and less or equal to 100.");
+    const std::vector<vertex>& vs = m->activeVertices();
+    forall(const vertex& v, vs)
+      v->signal = value;
+    if(rescale) {
+      RescaleSignal rescale(*this);
+      rescale(m, use_zero, percentile, 0, 0);
+    }
+    m->updateTriangles();
+    return true;
   }
-  m->updateTriangles();
-  return true;
-}
+  REGISTER_MESH_PROCESS(SetSignalProcess);
 
-REGISTER_MESH_PROCESS(SetSignalProcess);
-} // namespace process
-} // namespace mgx
+}}
Index: CutSurf.cpp
===================================================================
--- CutSurf.cpp	(revision 1255)
+++ CutSurf.cpp	(revision 1256)
@@ -11,481 +11,477 @@
 #endif
 
 namespace mgx {
-using Information::err;
-using qglviewer::Vec;
 
-typedef util::Vector<16, double> Point16d;
-
-CutSurf::CutSurf()
-  : QObject(0)
-  , cut(0)
-  , SceneRadius(-1)
-{
-}
-
-CutSurf::~CutSurf() {
-}
-
-// Read cutting plane parameters
-void CutSurf::readParms(util::Parms& parms, QString section)
-{
-  bool DrawCutSurf, CutSurfGrid;
-  int Mode;
-  Point3f Size;
-  Point2i SurfSize;
-  uint BezPoints;
-  parms(section, "DrawCutSurf", DrawCutSurf, false);
-  if(DrawCutSurf)
-    cut->show();
-  else
-    cut->hide();
-  parms(section, "Mode", Mode, (int)CuttingSurface::PLANE);
-  cut->setMode((CuttingSurface::Mode)Mode);
-  parms(section, "CutSurfGrid", CutSurfGrid, false);
-  if(CutSurfGrid)
-    cut->showGrid();
-  else
-    cut->hideGrid();
-  parms(section, "Material", Material, 0u);
-  parms(section, "Size", Size, Point3f(1.0f, 1.0f, 1.0f));
-  cut->setSize(Size);
-  parms(section, "SurfSize", SurfSize, Point2i(15, 15));
-  cut->setSurfSize(SurfSize);
-  parms(section, "LineWidth", LineWidth, 1.0f);
-  parms(section, "BezPoints", BezPoints, uint(5));
-  if(BezPoints < 4)
-    BezPoints = 4;
-  cut->setBezPoints(BezPoints);
-
-  Matrix4d m = 1;
-  parms(section, "Frame", m, m);
-  cut->frame().setFromMatrix(m.c_data());
-  cut->hasChanged();
-
-  initBez();
-  std::vector<Point3f> bezierT;
-  parms.all(section, "BezPointList", bezierT);
-  cut->setBezierV(bezierT);
-  /*
-   *  emit DrawCutSurfSignal(DrawCutSurf);
-   *  emit ThreeAxisSignal(ThreeAxis);
-   *  emit CutSurfGridSignal(CutSurfGrid);
-   *  emit CutSurfPlaneSignal(CutSurfPlane);
-   *  emit CutSurfBezierSignal(CutSurfBezier);
-   *  emit SizeXSignal(int(Size.x() * 10000.0));
-   *  emit SizeYSignal(int(Size.y() * 10000.0));
-   *  emit SizeZSignal(int(Size.z() * 10000.0));
-   */
-}
-
-// Write cutting plane parameters
-void CutSurf::writeParms(QTextStream& pout, QString section)
-{
-  pout << endl;
-  pout << "[" << section << "]" << endl;
-  pout << "DrawCutSurf: " << (cut->isVisible() ? "true" : "false") << endl;
-  pout << "Mode: " << (int)cut->mode() << endl;
-  pout << "CutSurfGrid: " << (cut->drawGrid() ? "true" : "false") << endl;
-  pout << "Material: " << Material << endl;
-  pout << "Size: " << cut->size() << endl;
-  pout << "SurfSize: " << cut->surfSize() << endl;
-  pout << "LineWidth: " << LineWidth << endl;
-  pout << "BezPoints: " << cut->bezPoints() << endl;
-  pout << "Frame: " << Point16d(cut->frame().matrix()) << endl;
-  const std::vector<Point3f>& bezierV = cut->bezierV();
-  for(size_t i = 0; i < cut->bezPoints() * cut->bezPoints(); i++)
-    pout << "BezPointList: " << bezierV[i] << endl;
-}
-
-void CutSurf::initBez()
-{
-  cut->initBez();
-  selectV.clear();
-}
-
-// Draw cutting surface slot
-void CutSurf::DrawCutSurfSlot(bool val)
-{
-  if(val)
-    cut->show();
-  else
-    cut->hide();
-  emit ViewerUpdateSignal();
-}
-
-// Three axis slot
-void CutSurf::ThreeAxisSlot(bool val)
-{
-  if(val)
-    cut->setMode(CuttingSurface::THREE_AXIS);
-  emit ViewerUpdateSignal();
-}
-
-// Draw surface grid
-void CutSurf::CutSurfGridSlot(bool val)
-{
-  if(val)
-    cut->showGrid();
-  else
-    cut->hideGrid();
-  emit ViewerUpdateSignal();
-}
-
-// Draw cutting plane slot
-void CutSurf::CutSurfPlaneSlot(bool val)
-{
-  if(val)
-    cut->setMode(CuttingSurface::PLANE);
-  emit ViewerUpdateSignal();
-}
-
-// Draw cutting Bezier slot
-void CutSurf::CutSurfBezierSlot(bool val)
-{
-  if(val)
-    cut->setMode(CuttingSurface::BEZIER);
-  emit ViewerUpdateSignal();
-}
-
-float CutSurf::getSize(int val) {
-  return 0.5f * SceneRadius * (float)exp(double(val) / 2000.0);
-}
-
-// Set sizes:
-void CutSurf::SizeXSlot(int val)
-{
-  Point3f s = cut->size();
-  s.x() = getSize(val);
-  cut->setSize(s);
-  emit ViewerUpdateSignal();
-}
-
-void CutSurf::SizeYSlot(int val)
-{
-  Point3f s = cut->size();
-  s.y() = getSize(val);
-  cut->setSize(s);
-  emit ViewerUpdateSignal();
-}
-
-void CutSurf::SizeZSlot(int val)
-{
-  Point3f s = cut->size();
-  s.z() = getSize(val);
-  cut->setSize(s);
-  emit ViewerUpdateSignal();
-}
-
-void CutSurf::drawSurface(ImgData& stk, bool select)
-{
-  switch(cut->mode()) {
-  case CuttingSurface::PLANE:
-  case CuttingSurface::THREE_AXIS: {
-    // Draw surface with texture
-    int axis = (cut->threeAxis() ? 3 : 1);
-
-    typedef void (GLAPIENTRY * colorFct_t)(const GLfloat*);
-    colorFct_t colorFct = select ? glColor3fv : glTexCoord3fv;
-    // void (*colorFct)(const GLfloat *) = select ? &glColor3fv : &glTexCoord3fv;
-
-    const Point3f& Size = cut->size();
-
-    glBegin(GL_QUADS);
-    for(int i = 0; i < axis; i++) {
-      Point3f x(0, 0, 0), y(0, 0, 0), z(0, 0, 0);
-      x[i] = Size[i];
-      y[(i + 1) % 3] = Size[(i + 1) % 3];
-      z[(i + 2) % 3] = Size[(i + 2) % 3];
-
-      glNormal3fv(z.c_data());
-      Point3f tr = x + y;
-      Point3f tl = -x + y;
-      Point3f bl = -x - y;
-      Point3f br = x - y;
-
-      colorFct(Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(tr)))).c_data());
-      glVertex3fv(tr.c_data());
-      colorFct(Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(tl)))).c_data());
-      glVertex3fv(tl.c_data());
-      colorFct(Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(bl)))).c_data());
-      glVertex3fv(bl.c_data());
-      colorFct(Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(br)))).c_data());
-      glVertex3fv(br.c_data());
-    }
-    glEnd();
-  } break;
-  case CuttingSurface::BEZIER: {
-    const Point2i& SurfSize = cut->surfSize();
-    int uSize = SurfSize.x(), vSize = SurfSize.y();
-    glEnable(GL_AUTO_NORMAL);
-    for(int u = 0; u < uSize - 1; u++) {
-      glBegin(GL_TRIANGLE_STRIP);
-      for(int v = 0; v < vSize; v++) {
-        Point3f v0 = cut->evalCoord(float(u) / float(uSize - 1), float(v) / float(vSize - 1));
-        Point3f v1 = cut->evalCoord(float(u + 1) / float(uSize - 1), float(v) / float(vSize - 1));
-
-        if(select) {
-          // For select we'll use the tex coords for the color
-          Point3f col;
-          col = Point3f((Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(v0))))
-                         + Point3f(.5f, .5f, .5f)).c_data());
-          glColor3fv(col.c_data());
-          glVertex3fv(v0.c_data());
-
-          col = Point3f((Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(v1))))
-                         + Point3f(.5f, .5f, .5f)).c_data());
-          glColor3fv(col.c_data());
-          glVertex3fv(v1.c_data());
-        } else {
-          glTexCoord3fv(
-            Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(v0)))).c_data());
-          glVertex3fv(v0.c_data());
-          glTexCoord3fv(
-            Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(v1)))).c_data());
-          glVertex3fv(v1.c_data());
-        }
-      }
-      glEnd();
-    }
+  using Information::err;
+  using qglviewer::Vec;
+  
+  typedef util::Vector<16, double> Point16d;
+  
+  CutSurf::CutSurf() : QObject(0), cut(0), SceneRadius(-1) {}
+  
+  CutSurf::~CutSurf() {}
+  
+  // Read cutting plane parameters
+  void CutSurf::readParms(util::Parms& parms, QString section)
+  {
+    bool DrawCutSurf, CutSurfGrid;
+    int Mode;
+    Point3f Size;
+    Point2i SurfSize;
+    uint BezPoints;
+    parms(section, "DrawCutSurf", DrawCutSurf, false);
+    if(DrawCutSurf)
+      cut->show();
+    else
+      cut->hide();
+    parms(section, "Mode", Mode, (int)CuttingSurface::PLANE);
+    cut->setMode((CuttingSurface::Mode)Mode);
+    parms(section, "CutSurfGrid", CutSurfGrid, false);
+    if(CutSurfGrid)
+      cut->showGrid();
+    else
+      cut->hideGrid();
+    parms(section, "Material", Material, 0u);
+    parms(section, "Size", Size, Point3f(1.0f, 1.0f, 1.0f));
+    cut->setSize(Size);
+    parms(section, "SurfSize", SurfSize, Point2i(15, 15));
+    cut->setSurfSize(SurfSize);
+    parms(section, "LineWidth", LineWidth, 1.0f);
+    parms(section, "BezPoints", BezPoints, uint(5));
+    if(BezPoints < 4)
+      BezPoints = 4;
+    cut->setBezPoints(BezPoints);
+  
+    Matrix4d m = 1;
+    parms(section, "Frame", m, m);
+    cut->frame().setFromMatrix(m.c_data());
+    cut->hasChanged();
+  
+    initBez();
+    std::vector<Point3f> bezierT;
+    parms.all(section, "BezPointList", bezierT);
+    cut->setBezierV(bezierT);
+    /*
+     *  emit DrawCutSurfSignal(DrawCutSurf);
+     *  emit ThreeAxisSignal(ThreeAxis);
+     *  emit CutSurfGridSignal(CutSurfGrid);
+     *  emit CutSurfPlaneSignal(CutSurfPlane);
+     *  emit CutSurfBezierSignal(CutSurfBezier);
+     *  emit SizeXSignal(int(Size.x() * 10000.0));
+     *  emit SizeYSignal(int(Size.y() * 10000.0));
+     *  emit SizeZSignal(int(Size.z() * 10000.0));
+     */
   }
+  
+  // Write cutting plane parameters
+  void CutSurf::writeParms(QTextStream& pout, QString section)
+  {
+    pout << endl;
+    pout << "[" << section << "]" << endl;
+    pout << "DrawCutSurf: " << (cut->isVisible() ? "true" : "false") << endl;
+    pout << "Mode: " << (int)cut->mode() << endl;
+    pout << "CutSurfGrid: " << (cut->drawGrid() ? "true" : "false") << endl;
+    pout << "Material: " << Material << endl;
+    pout << "Size: " << cut->size() << endl;
+    pout << "SurfSize: " << cut->surfSize() << endl;
+    pout << "LineWidth: " << LineWidth << endl;
+    pout << "BezPoints: " << cut->bezPoints() << endl;
+    pout << "Frame: " << Point16d(cut->frame().matrix()) << endl;
+    const std::vector<Point3f>& bezierV = cut->bezierV();
+    for(size_t i = 0; i < cut->bezPoints() * cut->bezPoints(); i++)
+      pout << "BezPointList: " << bezierV[i] << endl;
   }
-}
-
-// Draw cutting plane
-void CutSurf::drawCutSurf(ImgData& stk, bool select, Shader* shader)
-{
-  if(!cut->isVisible() or !stk.isVisible())
-    return;
-
-  glDisable(GL_BLEND);
-  glDisable(GL_TEXTURE_1D);
-  glDisable(GL_TEXTURE_2D);
-  glDisable(GL_TEXTURE_3D);
-  glDisable(GL_CULL_FACE);
-  glEnable(GL_DEPTH_TEST);
-  glDisable(GL_LIGHTING);
-
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glMultMatrixd(cut->frame().matrix());
-
-  if(select) {
-    glRenderMode(GL_RENDER);
-    glDrawBuffer(GL_AUX0);
-    glClearColor(0, 0, 0, 1.0);
-    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-    drawSurface(stk, true);
-  } else if(stk.isVisible()) {
-
-    glEnable(GL_LIGHTING);
-    // glEnable(GL_BLEND);
-    // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-    // glBlendFunc(GL_SRC_ALPHA, GL_ONE);
-    glFrontFace(GL_CCW);
-    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-    stk.setup3DRenderingData(shader);
-
-    shader->setUniform("brightness", GLSLValue(powf(stk.mesh->brightness(), 2.0f)));
-    shader->setUniform("opacity", GLSLValue(stk.mesh->opacity()));
-    shader->setUniform("second_brightness", GLSLValue(powf(stk.mesh->brightness(), 2.0f)));
-    shader->setUniform("second_opacity", GLSLValue(stk.mesh->opacity()));
-    shader->setUniform("blending", GLSLValue(stk.mesh->blending()));
-
-    // First, draw main
-    shader->useShaders();
-    shader->setupUniforms();
-    drawSurface(stk, false);
-    shader->stopUsingShaders();
-
-    stk.unbind3DTex();
+  
+  void CutSurf::initBez()
+  {
+    cut->initBez();
+    selectV.clear();
   }
-
-  if(select)
-    glDrawBuffer(GL_BACK);
-  glPopMatrix();
-}
-
-void CutSurf::drawCutSurfGrid(ImgData& stk)
-{
-  if(!cut->drawGrid())
-    return;
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glMultMatrixd(cut->frame().matrix());
-  glDisable(GL_LIGHTING);
-  glDisable(GL_TEXTURE_3D);
-  glDisable(GL_CULL_FACE);
-
-  glColor4fv(Colors::getColor(Colors::CuttingPlaneGridColor).c_data());
-
-  // Draw the grid
-  switch(cut->mode()) {
-  case CuttingSurface::PLANE:
-  case CuttingSurface::THREE_AXIS: {
-    const Point3f& Size = cut->size();
-    int axis = (cut->threeAxis() ? 3 : 1);
-    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
-    glLineWidth(LineWidth);
-    for(int i = 0; i < axis; i++) {
-      Point3f x(0, 0, 0), y(0, 0, 0), z(0, 0, 0);
-      x[i] = Size[i];
-      y[(i + 1) % 3] = Size[(i + 1) % 3];
-      z[(i + 2) % 3] = Size[(i + 2) % 3];
-
-      glNormal3fv(z.c_data());
-      Point3f tr = x + y;
-      Point3f tl = -x + y;
-      Point3f bl = -x - y;
-      Point3f br = x - y;
-
+  
+  // Draw cutting surface slot
+  void CutSurf::DrawCutSurfSlot(bool val)
+  {
+    if(val)
+      cut->show();
+    else
+      cut->hide();
+    emit ViewerUpdateSignal();
+  }
+  
+  // Three axis slot
+  void CutSurf::ThreeAxisSlot(bool val)
+  {
+    if(val)
+      cut->setMode(CuttingSurface::THREE_AXIS);
+    emit ViewerUpdateSignal();
+  }
+  
+  // Draw surface grid
+  void CutSurf::CutSurfGridSlot(bool val)
+  {
+    if(val)
+      cut->showGrid();
+    else
+      cut->hideGrid();
+    emit ViewerUpdateSignal();
+  }
+  
+  // Draw cutting plane slot
+  void CutSurf::CutSurfPlaneSlot(bool val)
+  {
+    if(val)
+      cut->setMode(CuttingSurface::PLANE);
+    emit ViewerUpdateSignal();
+  }
+  
+  // Draw cutting Bezier slot
+  void CutSurf::CutSurfBezierSlot(bool val)
+  {
+    if(val)
+      cut->setMode(CuttingSurface::BEZIER);
+    emit ViewerUpdateSignal();
+  }
+  
+  float CutSurf::getSize(int val) {
+    return 0.5f * SceneRadius * (float)exp(double(val) / 2000.0);
+  }
+  
+  // Set sizes:
+  void CutSurf::SizeXSlot(int val)
+  {
+    Point3f s = cut->size();
+    s.x() = getSize(val);
+    cut->setSize(s);
+    emit ViewerUpdateSignal();
+  }
+  
+  void CutSurf::SizeYSlot(int val)
+  {
+    Point3f s = cut->size();
+    s.y() = getSize(val);
+    cut->setSize(s);
+    emit ViewerUpdateSignal();
+  }
+  
+  void CutSurf::SizeZSlot(int val)
+  {
+    Point3f s = cut->size();
+    s.z() = getSize(val);
+    cut->setSize(s);
+    emit ViewerUpdateSignal();
+  }
+  
+  void CutSurf::drawSurface(ImgData& stk, bool select)
+  {
+    switch(cut->mode()) {
+    case CuttingSurface::PLANE:
+    case CuttingSurface::THREE_AXIS: {
+      // Draw surface with texture
+      int axis = (cut->threeAxis() ? 3 : 1);
+  
+      typedef void (GLAPIENTRY * colorFct_t)(const GLfloat*);
+      colorFct_t colorFct = select ? glColor3fv : glTexCoord3fv;
+      // void (*colorFct)(const GLfloat *) = select ? &glColor3fv : &glTexCoord3fv;
+  
+      const Point3f& Size = cut->size();
+  
       glBegin(GL_QUADS);
-      glVertex3fv(tr.c_data());
-      glVertex3fv(tl.c_data());
-      glVertex3fv(bl.c_data());
-      glVertex3fv(br.c_data());
+      for(int i = 0; i < axis; i++) {
+        Point3f x(0, 0, 0), y(0, 0, 0), z(0, 0, 0);
+        x[i] = Size[i];
+        y[(i + 1) % 3] = Size[(i + 1) % 3];
+        z[(i + 2) % 3] = Size[(i + 2) % 3];
+  
+        glNormal3fv(z.c_data());
+        Point3f tr = x + y;
+        Point3f tl = -x + y;
+        Point3f bl = -x - y;
+        Point3f br = x - y;
+  
+        colorFct(Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(tr)))).c_data());
+        glVertex3fv(tr.c_data());
+        colorFct(Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(tl)))).c_data());
+        glVertex3fv(tl.c_data());
+        colorFct(Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(bl)))).c_data());
+        glVertex3fv(bl.c_data());
+        colorFct(Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(br)))).c_data());
+        glVertex3fv(br.c_data());
+      }
       glEnd();
+    } break;
+    case CuttingSurface::BEZIER: {
+      const Point2i& SurfSize = cut->surfSize();
+      int uSize = SurfSize.x(), vSize = SurfSize.y();
+      glEnable(GL_AUTO_NORMAL);
+      for(int u = 0; u < uSize - 1; u++) {
+        glBegin(GL_TRIANGLE_STRIP);
+        for(int v = 0; v < vSize; v++) {
+          Point3f v0 = cut->evalCoord(float(u) / float(uSize - 1), float(v) / float(vSize - 1));
+          Point3f v1 = cut->evalCoord(float(u + 1) / float(uSize - 1), float(v) / float(vSize - 1));
+  
+          if(select) {
+            // For select we'll use the tex coords for the color
+            Point3f col;
+            col = Point3f((Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(v0))))
+                           + Point3f(.5f, .5f, .5f)).c_data());
+            glColor3fv(col.c_data());
+            glVertex3fv(v0.c_data());
+  
+            col = Point3f((Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(v1))))
+                           + Point3f(.5f, .5f, .5f)).c_data());
+            glColor3fv(col.c_data());
+            glVertex3fv(v1.c_data());
+          } else {
+            glTexCoord3fv(
+              Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(v0)))).c_data());
+            glVertex3fv(v0.c_data());
+            glTexCoord3fv(
+              Point3f(stk.getFrame().coordinatesOf(cut->frame().inverseCoordinatesOf(Vec(v1)))).c_data());
+            glVertex3fv(v1.c_data());
+          }
+        }
+        glEnd();
+      }
     }
-  } break;
-  case CuttingSurface::BEZIER: {
-    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
-    glLineWidth(LineWidth);
-    int uSize = cut->surfSize().x(), vSize = cut->surfSize().y();
-    glBegin(GL_QUADS);
-    for(int u = 0; u < uSize - 1; u++) {
-      for(int v = 0; v < vSize; v++) {
-        Point3f tl = cut->evalCoord(float(u) / float(uSize - 1), float(v) / float(vSize - 1));
-        Point3f bl = cut->evalCoord(float(u) / float(uSize - 1), float(v + 1) / float(vSize - 1));
-        Point3f br = cut->evalCoord(float(u + 1) / float(uSize - 1), float(v + 1) / float(vSize - 1));
-        Point3f tr = cut->evalCoord(float(u + 1) / float(uSize - 1), float(v) / float(vSize - 1));
-
+    }
+  }
+  
+  // Draw cutting plane
+  void CutSurf::drawCutSurf(ImgData& stk, bool select, Shader* shader)
+  {
+    if(!cut->isVisible() or !stk.isVisible())
+      return;
+  
+    glDisable(GL_BLEND);
+    glDisable(GL_TEXTURE_1D);
+    glDisable(GL_TEXTURE_2D);
+    glDisable(GL_TEXTURE_3D);
+    glDisable(GL_CULL_FACE);
+    glEnable(GL_DEPTH_TEST);
+    glDisable(GL_LIGHTING);
+  
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glMultMatrixd(cut->frame().matrix());
+  
+    if(select) {
+      glRenderMode(GL_RENDER);
+      glDrawBuffer(GL_AUX0);
+      glClearColor(0, 0, 0, 1.0);
+      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+      drawSurface(stk, true);
+    } else if(stk.isVisible()) {
+  
+      glEnable(GL_LIGHTING);
+      // glEnable(GL_BLEND);
+      // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+      // glBlendFunc(GL_SRC_ALPHA, GL_ONE);
+      glFrontFace(GL_CCW);
+      glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+      stk.setup3DRenderingData(shader);
+  
+      shader->setUniform("brightness", GLSLValue(powf(stk.mesh->brightness(), 2.0f)));
+      shader->setUniform("opacity", GLSLValue(stk.mesh->opacity()));
+      shader->setUniform("second_brightness", GLSLValue(powf(stk.mesh->brightness(), 2.0f)));
+      shader->setUniform("second_opacity", GLSLValue(stk.mesh->opacity()));
+      shader->setUniform("blending", GLSLValue(stk.mesh->blending()));
+  
+      // First, draw main
+      shader->useShaders();
+      shader->setupUniforms();
+      drawSurface(stk, false);
+      shader->stopUsingShaders();
+  
+      stk.unbind3DTex();
+    }
+  
+    if(select)
+      glDrawBuffer(GL_BACK);
+    glPopMatrix();
+  }
+  
+  void CutSurf::drawCutSurfGrid(ImgData& stk)
+  {
+    if(!cut->drawGrid())
+      return;
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glMultMatrixd(cut->frame().matrix());
+    glDisable(GL_LIGHTING);
+    glDisable(GL_TEXTURE_3D);
+    glDisable(GL_CULL_FACE);
+  
+    glColor4fv(Colors::getColor(Colors::CuttingPlaneGridColor).c_data());
+  
+    // Draw the grid
+    switch(cut->mode()) {
+    case CuttingSurface::PLANE:
+    case CuttingSurface::THREE_AXIS: {
+      const Point3f& Size = cut->size();
+      int axis = (cut->threeAxis() ? 3 : 1);
+      glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+      glLineWidth(LineWidth);
+      for(int i = 0; i < axis; i++) {
+        Point3f x(0, 0, 0), y(0, 0, 0), z(0, 0, 0);
+        x[i] = Size[i];
+        y[(i + 1) % 3] = Size[(i + 1) % 3];
+        z[(i + 2) % 3] = Size[(i + 2) % 3];
+  
+        glNormal3fv(z.c_data());
+        Point3f tr = x + y;
+        Point3f tl = -x + y;
+        Point3f bl = -x - y;
+        Point3f br = x - y;
+  
+        glBegin(GL_QUADS);
+        glVertex3fv(tr.c_data());
         glVertex3fv(tl.c_data());
         glVertex3fv(bl.c_data());
         glVertex3fv(br.c_data());
-        glVertex3fv(tr.c_data());
+        glEnd();
       }
+    } break;
+    case CuttingSurface::BEZIER: {
+      glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+      glLineWidth(LineWidth);
+      int uSize = cut->surfSize().x(), vSize = cut->surfSize().y();
+      glBegin(GL_QUADS);
+      for(int u = 0; u < uSize - 1; u++) {
+        for(int v = 0; v < vSize; v++) {
+          Point3f tl = cut->evalCoord(float(u) / float(uSize - 1), float(v) / float(vSize - 1));
+          Point3f bl = cut->evalCoord(float(u) / float(uSize - 1), float(v + 1) / float(vSize - 1));
+          Point3f br = cut->evalCoord(float(u + 1) / float(uSize - 1), float(v + 1) / float(vSize - 1));
+          Point3f tr = cut->evalCoord(float(u + 1) / float(uSize - 1), float(v) / float(vSize - 1));
+  
+          glVertex3fv(tl.c_data());
+          glVertex3fv(bl.c_data());
+          glVertex3fv(br.c_data());
+          glVertex3fv(tr.c_data());
+        }
+      }
+      glEnd();
     }
-    glEnd();
+    }
+  
+    // Draw the points if required
+    if(cut->bezier() and stk.mesh->showMeshPoints() and cut->bezPoints()) {
+      glPointSize(ImgData::MeshPointSize);
+      Color3f meshcol = Colors::getColor(stk.MeshColor);
+      Color3f selectcol = Colors::getColor(stk.MeshSelectColor);
+  
+      glBegin(GL_POINTS);
+      for(uint v = 0; v < cut->bezPoints(); v++)
+        for(uint u = 0; u < cut->bezPoints(); u++) {
+          if(selectV.find(cut->idx(u, v)) == selectV.end())
+            glColor3fv(meshcol.data());
+          else
+            glColor3fv(selectcol.data());
+          glVertex3fv(cut->bezierV(u, v).c_data());
+        }
+      glEnd();
+    }
+    glPopMatrix();
   }
-  }
-
-  // Draw the points if required
-  if(cut->bezier() and stk.mesh->showMeshPoints() and cut->bezPoints()) {
-    glPointSize(ImgData::MeshPointSize);
-    Color3f meshcol = Colors::getColor(stk.MeshColor);
-    Color3f selectcol = Colors::getColor(stk.MeshSelectColor);
-
+  
+  void CutSurf::drawSelect()
+  {
+    if(!cut->isVisible() or !cut->bezier() or !ImgData::MeshSelect /*or !ImgData::DrawPoints TODO? */)
+      return;
+  
+    // For Bezier draw the control points
+    glDisable(GL_LIGHTING);
+    glDisable(GL_TEXTURE_1D);
+    glDisable(GL_TEXTURE_2D);
+    glDisable(GL_TEXTURE_3D);
+    glDisable(GL_CULL_FACE);
+    glDisable(GL_DEPTH_TEST);
+  
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glMultMatrixd(cut->frame().matrix());
+  
+    glRenderMode(GL_RENDER);
+    glDrawBuffer(GL_AUX0);
+    glClearColor(0.0, 0.0, 0.0, 1.0);
+    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+    glPointSize(ImgData::MeshPointSize * 2);
+  
     glBegin(GL_POINTS);
     for(uint v = 0; v < cut->bezPoints(); v++)
       for(uint u = 0; u < cut->bezPoints(); u++) {
-        if(selectV.find(cut->idx(u, v)) == selectV.end())
-          glColor3fv(meshcol.data());
-        else
-          glColor3fv(selectcol.data());
+        glColor3ubv(util::vMapColor(cut->idx(u, v)).c_data());
         glVertex3fv(cut->bezierV(u, v).c_data());
       }
     glEnd();
+  
+    glDrawBuffer(GL_BACK);
+    glPopMatrix();
   }
-  glPopMatrix();
-}
-
-void CutSurf::drawSelect()
-{
-  if(!cut->isVisible() or !cut->bezier() or !ImgData::MeshSelect /*or !ImgData::DrawPoints TODO? */)
-    return;
-
-  // For Bezier draw the control points
-  glDisable(GL_LIGHTING);
-  glDisable(GL_TEXTURE_1D);
-  glDisable(GL_TEXTURE_2D);
-  glDisable(GL_TEXTURE_3D);
-  glDisable(GL_CULL_FACE);
-  glDisable(GL_DEPTH_TEST);
-
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glMultMatrixd(cut->frame().matrix());
-
-  glRenderMode(GL_RENDER);
-  glDrawBuffer(GL_AUX0);
-  glClearColor(0.0, 0.0, 0.0, 1.0);
-  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-  glPointSize(ImgData::MeshPointSize * 2);
-
-  glBegin(GL_POINTS);
-  for(uint v = 0; v < cut->bezPoints(); v++)
-    for(uint u = 0; u < cut->bezPoints(); u++) {
-      glColor3ubv(util::vMapColor(cut->idx(u, v)).c_data());
-      glVertex3fv(cut->bezierV(u, v).c_data());
-    }
-  glEnd();
-
-  glDrawBuffer(GL_BACK);
-  glPopMatrix();
-}
-
-// Clear list of selected points
-void CutSurf::clearSelect() {
-  selectV.clear();
-}
-
-// Find selected point in surface
-int CutSurf::findSelectPoint(uint x, uint y)
-{
-  // Draw unique colors in tha BACK buffer
-  drawSelect();
-
-  // Find the color of the pixels drawn in AUX0 buffer
-  Point3GLub pix;
-  GLint viewport[4];
-  glGetIntegerv(GL_VIEWPORT, viewport);
-  glReadBuffer(GL_AUX0);
-  glReadPixels(x, viewport[3] - y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pix);
-  glReadBuffer(GL_FRONT);
-  int i = util::vMapColor(pix);
-  if(i >= int(cut->bezPoints() * cut->bezPoints()))
-    return -1;
-  return (i);
-}
-
-bool CutSurf::showOpaqueSurface(const ImgData& stk)
-{
-  return stk.isVisible() and cut->isVisible() and not stk.mesh->blending();
-}
-
-bool CutSurf::showTransparentSurface(const ImgData& stk)
-{
-  return stk.isVisible() and cut->isVisible() and stk.mesh->blending();
-}
-
-void CutSurf::Reset(double sceneRadius)
-{
-  SceneRadius = sceneRadius;
-  cut->setSize(Point3f(SceneRadius, SceneRadius, SceneRadius));
-
-  if(SceneRadius > 0.0f and (cut->isVisible() or cut->drawGrid())) {
-    switch(cut->mode()) {
-    // case CuttingSurface::PLANE:
-    // case CuttingSurface::THREE_AXIS:
-    //  {
-    //    cut->setSize(Point3f(SceneRadius,SceneRadius,SceneRadius));
-    //  }
-    //  break;
-    case CuttingSurface::BEZIER: {
-      initBez();
-      forall(Point3f& p, cut->bezierV()) {
-        p *= SceneRadius;
+  
+  // Clear list of selected points
+  void CutSurf::clearSelect() {
+    selectV.clear();
+  }
+  
+  // Find selected point in surface
+  int CutSurf::findSelectPoint(uint x, uint y)
+  {
+    // Draw unique colors in tha BACK buffer
+    drawSelect();
+  
+    // Find the color of the pixels drawn in AUX0 buffer
+    Point3GLub pix;
+    GLint viewport[4];
+    glGetIntegerv(GL_VIEWPORT, viewport);
+    glReadBuffer(GL_AUX0);
+    glReadPixels(x, viewport[3] - y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pix);
+    glReadBuffer(GL_FRONT);
+    int i = util::vMapColor(pix);
+    if(i >= int(cut->bezPoints() * cut->bezPoints()))
+      return -1;
+    return (i);
+  }
+  
+  bool CutSurf::showOpaqueSurface(const ImgData& stk)
+  {
+    return stk.isVisible() and cut->isVisible() and not stk.mesh->blending();
+  }
+  
+  bool CutSurf::showTransparentSurface(const ImgData& stk)
+  {
+    return stk.isVisible() and cut->isVisible() and stk.mesh->blending();
+  }
+  
+  void CutSurf::Reset(double sceneRadius)
+  {
+    SceneRadius = sceneRadius;
+    cut->setSize(Point3f(SceneRadius, SceneRadius, SceneRadius));
+  
+    if(SceneRadius > 0.0f and (cut->isVisible() or cut->drawGrid())) {
+      switch(cut->mode()) {
+      // case CuttingSurface::PLANE:
+      // case CuttingSurface::THREE_AXIS:
+      //  {
+      //    cut->setSize(Point3f(SceneRadius,SceneRadius,SceneRadius));
+      //  }
+      //  break;
+      case CuttingSurface::BEZIER: {
+        initBez();
+        forall(Point3f& p, cut->bezierV()) {
+          p *= SceneRadius;
+        }
       }
+      default:
+        break;
+      }
     }
-    default:
-      break;
-    }
+    emit ViewerUpdateSignal();
   }
-  emit ViewerUpdateSignal();
-}
+  
+  void CutSurf::setSceneBoundingBox(const Point3f& bbox)
+  {
+    if(SceneRadius <= 0)
+      SceneRadius = norm(bbox);
+  }
 
-void CutSurf::setSceneBoundingBox(const Point3f& bbox)
-{
-  if(SceneRadius <= 0)
-    SceneRadius = norm(bbox);
 }
-} // namespace mgx
Index: Mesh.hpp
===================================================================
--- Mesh.hpp	(revision 1255)
+++ Mesh.hpp	(revision 1256)
@@ -30,103 +30,103 @@
 
 namespace mgx {
 
-/**
- * Type of the VV graph holding the actual mesh
- */
-typedef graph::VVGraph<VertexData, EdgeData> vvgraph;
-
-/// Type of a vertex
-typedef vvgraph::vertex_t vertex;
-
-/// Type of an edge
-typedef vvgraph::edge_t edge;
-
-typedef unsigned short ushort;
-typedef unsigned int uint;
-typedef unsigned long ulong;
-
-typedef util::Color<float> Colorf;
-
-typedef util::Vector<3, bool> Point3b;
-
-/// Map of an integer to a 3D point
-typedef std::map<int, Point3f> IntPoint3fMap;
-typedef std::unordered_map<int, Point3f> IntPoint3fUMap;
-/// Element in IntPoint3fMap
-typedef std::pair<int, Point3f> IntPoint3fPair;
-/// Map of an integer to a float
-typedef std::map<int, float> IntFloatMap;
-typedef std::unordered_map<int, float> IntFloatUMap;
-/// Element in IntFloatMap
-typedef std::pair<int, float> IntFloatPair;
-/// Map of an integer to another one
-typedef std::map<int, int> IntIntMap;
-typedef std::unordered_map<int, int> IntIntUMap;
-/// Element in IntIntMap
-typedef std::pair<int, int> IntIntPair;
-/// Map of an integer to a host vector of 3 unsigned integers
-typedef std::map<int, HVec3U> IntHVec3uMap;
-typedef std::unordered_map<int, HVec3U> IntHVec3uUMap;
-/// Element in IntHVec3uMap
-typedef std::pair<int, HVec3U> IntHVec3uPair;
-/// Set of vertex ids
-typedef std::set<ulong> VIdSet;
-typedef std::unordered_set<ulong> VIdUSet;
-/// Set of vertices
-typedef std::set<vertex> VtxSet;
-typedef std::unordered_set<vertex> VtxUSet;
-/// Vector of vertices
-typedef std::vector<vertex> VtxVec;
-/// Vector of vvgraphs
-typedef std::vector<vvgraph> VVGraphVec;
-/// Integer, VVGraph pair
-typedef std::pair<int, vvgraph> IntVVGraphPair;
-/// Map of an integer to a vvgraph
-typedef std::map<int, vvgraph> IntVVGraphMap;
-typedef std::unordered_map<int, vvgraph> IntVVGraphUMap;
-/// Map of an integer to a set of vertex ids
-typedef std::map<int, VIdSet> IntVIdSetMap;
-typedef std::unordered_map<int, VIdSet> IntVIdSetUMap;
-/// Element in IntVIdSetMap
-typedef std::pair<int, VIdSet> IntVIdSetPair;
-/// Set of integers
-typedef std::set<int> IntSet;
-typedef std::unordered_set<int> IntUSet;
-/// Vector of integers
-typedef std::vector<int> IntVec;
-/// Vector of floats
-typedef std::vector<float> FloatVec;
-/// Element in IntIntSetMap
-typedef std::pair<int, IntSet> IntIntSetPair;
-/// Map of an integer to a set of integers
-typedef std::map<int, IntSet> IntIntSetMap;
-typedef std::unordered_map<int, IntSet> IntIntSetUMap;
-/// Map of a vertex to an integer
-typedef std::map<vertex, int> VIntMap;
-typedef std::unordered_map<vertex, int> VIntUMap;
-/// Element in IntIntVIdSetMap
-typedef std::pair<IntIntPair, VIdSet> IntIntVIdSetPair;
-/// Element in IntIntFloatMap
-typedef std::pair<IntIntPair, float> IntIntFloatPair;
-/// Map of a pair of integers to a float
-typedef std::map<IntIntPair, float> IntIntFloatMap;
-typedef std::unordered_map<IntIntPair, float> IntIntFloatUMap;
-/// Map of a pair of integers to a set of vertex ids
-typedef std::map<IntIntPair, VIdSet> IntIntVIdSetMap;
-typedef std::unordered_map<IntIntPair, VIdSet> IntIntVIdSetUMap;
-/// Map of an integer to a 3x3 matrix
-typedef std::map<int, Matrix3f> IntMatrix3x3fMap;
-typedef std::unordered_map<int, Matrix3f> IntMatrix3x3fUMap;
-/// Element in IntMatrix3x3fMap
-typedef std::pair<int, Matrix3f> IntMatrix3x3fPair;
-/// Map an integer to a symmetric tensor
-typedef std::map<int, util::SymmetricTensor> IntSymTensorMap;
-typedef std::unordered_map<int, util::SymmetricTensor> IntSymTensorUMap;
-/// Element in IntSymTensorMap
-typedef std::pair<int, util::SymmetricTensor> IntSymTensorPair;
-/// Map of vertex to vertex
-typedef std::map<vertex, vertex> VtxVtxMap;
-typedef std::unordered_map<vertex, vertex> VtxVtxUMap;
+  /**
+   * Type of the VV graph holding the actual mesh
+   */
+  typedef graph::VVGraph<VertexData, EdgeData> vvgraph;
+  
+  /// Type of a vertex
+  typedef vvgraph::vertex_t vertex;
+  
+  /// Type of an edge
+  typedef vvgraph::edge_t edge;
+  
+  typedef unsigned short ushort;
+  typedef unsigned int uint;
+  typedef unsigned long ulong;
+  
+  typedef util::Color<float> Colorf;
+  
+  typedef util::Vector<3, bool> Point3b;
+  
+  /// Map of an integer to a 3D point
+  typedef std::map<int, Point3f> IntPoint3fMap;
+  typedef std::unordered_map<int, Point3f> IntPoint3fUMap;
+  /// Element in IntPoint3fMap
+  typedef std::pair<int, Point3f> IntPoint3fPair;
+  /// Map of an integer to a float
+  typedef std::map<int, float> IntFloatMap;
+  typedef std::unordered_map<int, float> IntFloatUMap;
+  /// Element in IntFloatMap
+  typedef std::pair<int, float> IntFloatPair;
+  /// Map of an integer to another one
+  typedef std::map<int, int> IntIntMap;
+  typedef std::unordered_map<int, int> IntIntUMap;
+  /// Element in IntIntMap
+  typedef std::pair<int, int> IntIntPair;
+  /// Map of an integer to a host vector of 3 unsigned integers
+  typedef std::map<int, HVec3U> IntHVec3uMap;
+  typedef std::unordered_map<int, HVec3U> IntHVec3uUMap;
+  /// Element in IntHVec3uMap
+  typedef std::pair<int, HVec3U> IntHVec3uPair;
+  /// Set of vertex ids
+  typedef std::set<ulong> VIdSet;
+  typedef std::unordered_set<ulong> VIdUSet;
+  /// Set of vertices
+  typedef std::set<vertex> VtxSet;
+  typedef std::unordered_set<vertex> VtxUSet;
+  /// Vector of vertices
+  typedef std::vector<vertex> VtxVec;
+  /// Vector of vvgraphs
+  typedef std::vector<vvgraph> VVGraphVec;
+  /// Integer, VVGraph pair
+  typedef std::pair<int, vvgraph> IntVVGraphPair;
+  /// Map of an integer to a vvgraph
+  typedef std::map<int, vvgraph> IntVVGraphMap;
+  typedef std::unordered_map<int, vvgraph> IntVVGraphUMap;
+  /// Map of an integer to a set of vertex ids
+  typedef std::map<int, VIdSet> IntVIdSetMap;
+  typedef std::unordered_map<int, VIdSet> IntVIdSetUMap;
+  /// Element in IntVIdSetMap
+  typedef std::pair<int, VIdSet> IntVIdSetPair;
+  /// Set of integers
+  typedef std::set<int> IntSet;
+  typedef std::unordered_set<int> IntUSet;
+  /// Vector of integers
+  typedef std::vector<int> IntVec;
+  /// Vector of floats
+  typedef std::vector<float> FloatVec;
+  /// Element in IntIntSetMap
+  typedef std::pair<int, IntSet> IntIntSetPair;
+  /// Map of an integer to a set of integers
+  typedef std::map<int, IntSet> IntIntSetMap;
+  typedef std::unordered_map<int, IntSet> IntIntSetUMap;
+  /// Map of a vertex to an integer
+  typedef std::map<vertex, int> VIntMap;
+  typedef std::unordered_map<vertex, int> VIntUMap;
+  /// Element in IntIntVIdSetMap
+  typedef std::pair<IntIntPair, VIdSet> IntIntVIdSetPair;
+  /// Element in IntIntFloatMap
+  typedef std::pair<IntIntPair, float> IntIntFloatPair;
+  /// Map of a pair of integers to a float
+  typedef std::map<IntIntPair, float> IntIntFloatMap;
+  typedef std::unordered_map<IntIntPair, float> IntIntFloatUMap;
+  /// Map of a pair of integers to a set of vertex ids
+  typedef std::map<IntIntPair, VIdSet> IntIntVIdSetMap;
+  typedef std::unordered_map<IntIntPair, VIdSet> IntIntVIdSetUMap;
+  /// Map of an integer to a 3x3 matrix
+  typedef std::map<int, Matrix3f> IntMatrix3x3fMap;
+  typedef std::unordered_map<int, Matrix3f> IntMatrix3x3fUMap;
+  /// Element in IntMatrix3x3fMap
+  typedef std::pair<int, Matrix3f> IntMatrix3x3fPair;
+  /// Map an integer to a symmetric tensor
+  typedef std::map<int, util::SymmetricTensor> IntSymTensorMap;
+  typedef std::unordered_map<int, util::SymmetricTensor> IntSymTensorUMap;
+  /// Element in IntSymTensorMap
+  typedef std::pair<int, util::SymmetricTensor> IntSymTensorPair;
+  /// Map of vertex to vertex
+  typedef std::map<vertex, vertex> VtxVtxMap;
+  typedef std::unordered_map<vertex, vertex> VtxVtxUMap;
 }
 
 namespace std {
@@ -150,1190 +150,1192 @@
 
 namespace mgx {
 
-namespace process {
-class SetupProcess;
-}
-
-/**
- * \class Mesh Mesh.hpp <Mesh.hpp>
- *
- * This class holds the actual mesh as a VV Graph and all sort of properties
- * for it, including visualization ones.
- *
- * Note that, in MorphoGraphX, the user sees the surface, or the mesh. The
- * surface is continuous, when the mesh is the actual connectivity of the
- * vertices.
- */
-class MGX_EXPORT Mesh {
-  friend class process::SetupProcess;
-
-public:
-  /**
-   * Enumeration of the possible visualisations for the surface
-   */
-  enum SurfView {
-    NORMAL,     ///< Show the color option
-    LABEL,      ///< Show the label of the triangles
-    HEAT,       ///< Show the current heat map
-    PARENT      ///< Show the parent label
-  };
-
-  /**
-   * Enumeration of the possible visualisations for the Mesh
-   */
-  enum MeshView {
-    ALL_MESH,         ///< Show the whole mesh
-    BORDER_MESH,      ///< Show only the mesh border
-    CELL_MESH,        ///< Show only the cell borders (i.e. interface between labels)
-    SELECTED_MESH     ///< Show only the selected part of the mesh
-  };
-
-  /**
-   * Enumeration of the coloring modes possible to display a normal surface
-   */
-  enum Color {
-    SIGNAL,      ///< Color using the signal stored on the vertices
-    TEXTURE,     ///< Color using the 3D texture of the active stack
-    IMAGE        ///< Color using the texture stored with the mesh
-  };
-
-  /**
-   * Create an empty mesh attached to the stack
-   */
-  Mesh(const Stack* stack);
-
-  /**
-   * Create an empty mesh attached to the stack
-   */
-  Mesh(int id, const Stack* stack);
-
-  /**
-   * Copy the mesh
-   */
-  Mesh(const Mesh& copy);
-
-  /**
-   * Mesh destructor
-   */
-  ~Mesh();
-
-  //@{
-  ///\name Global properties
-  /// Properties for both mesh and surface
-
-  /**
-   * Id of the current mesh
-   *
-   * This is the same id used in the Process:mesh(int) method.
-   */
-  int id() const {
-    return _id;
+  namespace process {
+    class SetupProcess;
   }
-
+  
   /**
-   * Change the id of the mesh.
+   * \class Mesh Mesh.hpp <Mesh.hpp>
    *
-   * Please do not use this method for meshes attached to a process.
-   */
-  void setId(int i) {
-    _id = i;
-  }
-
-  /**
-   * Id as seen by the user
+   * This class holds the actual mesh as a VV Graph and all sort of properties
+   * for it, including visualization ones.
    *
-   * This is, typically id()+1
+   * Note that, in MorphoGraphX, the user sees the surface, or the mesh. The
+   * surface is continuous, when the mesh is the actual connectivity of the
+   * vertices.
    */
-  int userId() const {
-    return _id + 1;
-  }
+  class MGX_EXPORT Mesh {
+    friend class process::SetupProcess;
+  
+  public:
+    /**
+     * Enumeration of the possible visualisations for the surface
+     */
+    enum SurfView {
+      NORMAL,     ///< Show the color option
+      LABEL,      ///< Show the label of the triangles
+      HEAT,       ///< Show the current heat map
+      PARENT      ///< Show the parent label
+    };
+  
+    /**
+     * Enumeration of the possible visualisations for the Mesh
+     */
+    enum MeshView {
+      ALL_MESH,         ///< Show the whole mesh
+      BORDER_MESH,      ///< Show only the mesh border
+      CELL_MESH,        ///< Show only the cell borders (i.e. interface between labels)
+      SELECTED_MESH     ///< Show only the selected part of the mesh
+    };
+  
+    /**
+     * Enumeration of the coloring modes possible to display a normal surface
+     */
+    enum Color {
+      SIGNAL,      ///< Color using the signal stored on the vertices
+      TEXTURE,     ///< Color using the 3D texture of the active stack
+      IMAGE        ///< Color using the texture stored with the mesh
+    };
+  
+    /**
+     * Create an empty mesh attached to the stack
+     */
+    Mesh(const Stack* stack);
+  
+    /**
+     * Create an empty mesh attached to the stack
+     */
+    Mesh(int id, const Stack* stack);
+  
+    /**
+     * Copy the mesh
+     */
+    Mesh(const Mesh& copy);
+  
+    /**
+     * Mesh destructor
+     */
+    ~Mesh();
+  
+    //@{
+    ///\name Global properties
+    /// Properties for both mesh and surface
+  
+    /**
+     * Id of the current mesh
+     *
+     * This is the same id used in the Process:mesh(int) method.
+     */
+    int id() const {
+      return _id;
+    }
+  
+    /**
+     * Change the id of the mesh.
+     *
+     * Please do not use this method for meshes attached to a process.
+     */
+    void setId(int i) {
+      _id = i;
+    }
+  
+    /**
+     * Id as seen by the user
+     *
+     * This is, typically id()+1
+     */
+    int userId() const {
+      return _id + 1;
+    }
+  
+    /**
+     * Returns the stack associated to this mesh
+     */
+    const Stack* stack() const {
+      return _stack;
+    }
+  
+    // For now, a mesh is always with the same stack
+    void setStack(const Stack* s);
+  
+    /**
+     * Returns the name of the mesh file
+     */
+    const QString& file() const {
+      return _file;
+    }
 
-  /**
-   * Returns the stack associated to this mesh
-   */
-  const Stack* stack() const {
-    return _stack;
-  }
+    /**
+     * Returns the name of the parent label file
+     */
+    const QString& parentFile() const {
+      return _parentFile;
+    }
 
-  // For now, a mesh is always with the same stack
-  void setStack(const Stack* s);
+    /**
+     * Set the name of the mesh file.
+     *
+     * This is called when the mesh is loaded or saved. Processes that create
+     * a new mesh should call this without a parameter to reset the filename to null.
+     */
+    void setFile(const QString& file = QString());
 
-  /**
-   * Name of the file
-   *
-   * This name correspond usually to the name of the file during the last
-   * load/save and correspond to this mesh.
-   */
-  const QString& file() const {
-    return _file;
-  }
-  /**
-   * Change the name of the file.
-   *
-   * This name correspond usually to the name of the file during the last
-   * load/save and correspond to this mesh. Processes that create a new mesh
-   * should typically either set the file to an empty string, to make it
-   * clear this mesh has never been saved.
-   */
-  void setFile(const QString& file = QString());
+     /**
+     * Set the name of the parent label file.
+     *
+     * This is called when the parent labels are loaded or saved. 
+     */
+    void setParentFile(const QString& file = QString());
 
-  /**
-   * Returns true if the mesh is scaled
-   */
-  bool scaled() const {
-    return _scaled;
-  }
-  /**
-   * Set if the mesh is scaled
-   */
-  void setScaled(bool on = true) {
-    _scaled = on;
-  }
-
-  /**
-   * Returns true if the mesh is transformed
-   */
-  bool transformed() const {
-    return _transformed;
-  }
-  /**
-   * Set if the mesh is transformed
-   */
-  void setTransformed(bool on = true) {
-    _transformed = on;
-  }
-
-  /**
-   * Returns true if the bounding box is shown
-   */
-  bool showBBox() const {
-    return _showBBox;
-  }
-
-  /**
-   * Set if the bounding box is shown
-   */
-  void setShowBBox(bool on = true) {
-    _showBBox = on;
-  }
-
-  /**
-   * Returns the current label, without modifying it
-   */
-  int viewLabel() const {
-    return _currLabel;
-  }
-  /**
-   * Sets the current label
-   */
-  void setLabel(int l)
-  {
-    changed_label = true;
-    _currLabel = l;
-  }
-  /**
-   * Increment the current label and return
-   */
-  int nextLabel()
-  {
-    changed_label = true;
-    return ++_currLabel;
-  }
-  /**
-   * Returns true if the curr label has been changed during this process
-   */
-  bool labelChanged() const {
-    return changed_label;
-  }
-
-  /**
-   * Reference on the map from each label to a label in a different mesh.
-   */
-  IntIntMap& parentLabelMap() {
-    return _parentLabel;
-  }
-  /**
-   * Const reference on the map from each label to a label in a different mesh.
-   */
-  const IntIntMap& parentLabelMap() const {
-    return _parentLabel;
-  }
-  /**
-   * Update ParentLabel map for label to parent_label when grabbing seed.
-   * \author Gerardo Tauriello
-   */
-  // void mapParentLabel(int label, int parent_label) {_parentLabel[label] = parent_label};
-  // HACK
-  //_labelHeat[label] = 1;
-  // heatMapUnit() = "ON/OFF";
-  // heatMapBounds() = Point2f(0, 1);
-
-  /**
-   * Returns true if the mesh has a cell structure
-   *
-   * This means that some vertexes correspond to cell centers and other the
-   * junctions.
-   */
-  bool cells() const {
-    return _cells;
-  }
-  /**
-   * Set if the mesh has a cell structure
-   *
-   * This means that some vertexes correspond to cell centers and other the
-   * junctions.
-   */
-  void setCells(bool value = true) {
-    _cells = value;
-  }
-
-  /**
-   * Reset the whole mesh and its properties.
-   *
-   * In the end, the mesh is empty, so doesn't contain cells, texture and is neither scaled nor transformed.
-   *
-   * The next label stays untouched, as it is important to keep coordination between different meshes/stacks.
-   */
-  void reset();
-
-  //@}
-
-  //@{
-  ///\name Structure
-
-  /**
-   * Get the VV graph representing the topology of the mesh
-   */
-  vvgraph& graph() {
-    return S;
-  }
-  /**
-   * Get the VV graph representing the topology of the mesh
-   */
-  const vvgraph& graph() const {
-    return S;
-  }
-  /**
-   * True if the mesh is empty (i.e. the graph is empty)
-   */
-  bool empty() const {
-    return S.empty();
-  }
-  /**
-   * Returns the number of vertices in the mesh
-   */
-  size_t size() const {
-    return S.size();
-  }
-
-  /**
-   * Returns the label of the triangle (v1,v2,v3)
-   */
-  int getLabel(vertex v1, vertex v2, vertex v3, bool useParentLabel = true) const;
-
-  /**
-   * Returns true if (v,n,m) correspond to a canonical triangle.
-   *
-   * This means it returns true only for one of all the possible triangles
-   * made from v, n and m (i.e. (v,n,m), (v,m,n), ...)
-   */
-  bool uniqueTri(const vertex& v, const vertex& n, const vertex& m) const
-  {
-    if(v <= n or v <= m or n == m or !S.edge(v, n) or !S.edge(v, m) or !S.edge(n, m))
-      return false;
-    else
-      return true;
-  }
-
-  /**
-   * Update the normal of the vertex \c v in the mesh
-   *
-   * Returns false if the normal cannot be computed
-   */
-  bool setNormal(vertex v) {
-    return setNormal(S, v);
-  }
-
-  /**
-   * Update the normal of the vertex \c v in \c S
-   *
-   * Returns false if the normal cannot be computed
-   */
-  static bool setNormal(vvgraph& S, vertex v);
-
-  /**
-   * Update all the normals of the mesh
-   *
-   * Returns false if any normal cannot be computed
-   */
-  bool setNormals();
-
-  /**
-   * Reference on the map from label to a position.
-   *
-   * This position will be intepreted as the center of the label, and used to
-   * draw the label number on the mesh or growth directions on cellular mesh.
-   *
-   */
-  IntPoint3fMap& labelCenter() {
-    return _labelCenter;
-  }
-  /**
-   * Returns the map from label to position
-   */
-  const IntPoint3fMap& labelCenter() const {
-    return _labelCenter;
-  }
-
-  /**
-   * Reference on the map from label to a normal.
-   *
-   * This vector will be intepreted as the normal of the label, and used to
-   * draw the cell axis (e.g. principal directions of growth, MT orientation...).
-   *
-   */
-  IntPoint3fMap& labelNormal() {
-    return _labelNormal;
-  }
-  /**
-   * Returns the map from label to normal
-   */
-  const IntPoint3fMap& labelNormal() const {
-    return _labelNormal;
-  }
-  /**
-   * Reference on the map from label to a position.
-   *
-   * This position will be intepreted as the center of the label, and used to
-   * draw growth directions on a non-cellular mesh.
-   *
-   */
-  IntPoint3fMap& labelCenterVis() {
-    return _labelCenterVis;
-  }
-  /**
-   * Returns the map from label to position
-   */
-  const IntPoint3fMap& labelCenterVis() const {
-    return _labelCenterVis;
-  }
-
-  /**
-   * Reference on the map from label to a normal.
-   *
-   * This vector will be intepreted as the normal of the label, and used to
-   * draw the cell axis (e.g. principal directions of growth, MT orientation...).
-   *
-   */
-  IntPoint3fMap& labelNormalVis() {
-    return _labelNormalVis;
-  }
-  /**
-   * Returns the map from label to position
-   */
-  const IntPoint3fMap& labelNormalVis() const {
-    return _labelNormalVis;
-  }
-
-  /**
-   * Reference on the map from parent label to a position.
-   *
-   * This position will be intepreted as the center of the parent label, and used to
-   * draw the parent label number on the mesh or growth directions on cellular mesh.
-   *
-   */
-  IntPoint3fMap& parentCenter() {
-    return _parentCenter;
-  }
-  /**
-   * Returns the map from parent label to position
-   */
-  const IntPoint3fMap& parentCenter() const {
-    return _parentCenter;
-  }
-
-  /**
-   * Reference on the map from parent label to a normal.
-   *
-   * This vector will be intepreted as the normal of the parent label, and used to
-   * draw the cell axis (e.g. principal directions of growth, MT orientation...).
-   *
-   */
-  IntPoint3fMap& parentNormal() {
-    return _parentNormal;
-  }
-  /**
-   * Returns the map from parent label to normal
-   */
-  const IntPoint3fMap& parentNormal() const {
-    return _parentNormal;
-  }
-  /**
-   * Reference on the map from parent label to a position.
-   *
-   * This position will be intepreted as the center of the parent label, and used to
-   * draw growth directions on a non-cellular mesh.
-   *
-   */
-  IntPoint3fMap& parentCenterVis() {
-    return _parentCenterVis;
-  }
-  /**
-   * Returns the map from parent label to position
-   */
-  const IntPoint3fMap& parentCenterVis() const {
-    return _parentCenterVis;
-  }
-
-  /**
-   * Reference on the map from parent label to a normal.
-   *
-   * This vector will be intepreted as the normal of the parent label, and used to
-   * draw the cell axis (e.g. principal directions of growth, MT orientation...).
-   *
-   */
-  IntPoint3fMap& parentNormalVis() {
-    return _parentNormalVis;
-  }
-  /**
-   * Returns the map from parent label to position
-   */
-  const IntPoint3fMap& parentNormalVis() const {
-    return _parentNormalVis;
-  }
-
-  /**
-   * Reference on the map from labels to the set of neighbor labels.
-   *
-   * A label is neighbors of another ones if they share at least an edge of the mesh.
-   *
-   * \note You shouldn't need to modify this structure directly. You should
-   * instead call Mesh::updateWallGeometry()
-   */
-  IntIntSetMap& labelNeighbors() {
-    return _labelNeighbors;
-  }
-  /**
-   * Returns the map from labels to the set of neighbors labels.
-   */
-  const IntIntSetMap& labelNeighbors() const {
-    return _labelNeighbors;
-  }
-  /**
-   * Reference on the map from each wall to the list of vertexes in the wall.
-   *
-   * A wall is identified as the interface between two labels, and as such, is given as a pair of labels. Note that
-   * there is a difference between the wall (i,j) and (j,i), as the first label is considered as the interior of the
-   * wall, and used as such when calculating the signal along a wall.
-   *
-   * \note You shouldn't need to modify this structure directly. You should
-   * instead call Mesh::updateWallGeometry()
-   */
-  IntIntVIdSetMap& wallVId() {
-    return _wallVId;
-  }
-  /**
-   * Returns the map from each wall to the list of vertexes in the wall.
-   */
-  const IntIntVIdSetMap& wallVId() const {
-    return _wallVId;
-  }
-  /**
-   * Reference on the map from each wall to the length of the wall.
-   *
-   * The length is calculated as the sum of the edges making the wall. This means the number returned is will depend
-   * on the discretization of the surface.
-   *
-   * \note You shouldn't need to modify this structure directly. You should
-   * instead call Mesh::updateWallGeometry()
-   */
-  IntIntFloatMap& wallGeom() {
-    return _wallGeom;
-  }
-  /**
-   * Reference on the map from each wall to the length of the wall.
-   */
-  const IntIntFloatMap& wallGeom() const {
-    return _wallGeom;
-  }
-
-  /**
-   * Update labelNeighbors, wallVId and wallGeom to reflect current data structure
-   * \param borderSize Distance from the wall up to which the triangles are considered part of the wall. This is
-   * important mostly for signal intensity.
-   */
-  void updateWallGeometry(float borderSize);
-
-  /**
-   * True if (v,n,m) is on the border of the \c label.
-   *
-   * \c rp will be set to the wall the triangle is on, if any.
-   */
-  bool isBordTriangle(int label, vertex v, vertex n, vertex m, IntIntPair& rp) const;
-
-  /**
-   * Mark all triangles closer than borderSize from a border as being
-   * a border triangle
-   */
-  void markBorder(float borderSize);
-
-  /**
-   * Search for the vertex closest to position of cell center
-   * fills in labelCenter, labelNormal, labelCenterVis, labelNormalVis
-   */
-  void updateCentersNormals();
-
-  /**
-   * Prepare the axis drawing structures
-   */
-  void prepareAxisDrawing(float scaleAxisLength, Colorf colorPositive, Colorf colorNegative,
-                          const Point3b& showAxis = Point3b(true, true, true));   // ,float DisplayThreshold)
-
-  //@}
-
-  //@{
-  ///\name Surface methods
-  /**
-   * Return the transfer function used to draw the surface in normal mode
-   */
-  TransferFunction surfFct() const {
-    return _surf_fct;
-  }
-  /**
-   * Change the transfer function used to draw the surface in normal mode
-   */
-  void setSurfFct(const TransferFunction& f)
-  {
-    if(_surf_fct != f) {
-      _surf_fct = f;
-      changed_surf_function = true;
+    /**
+     * Returns true if the mesh is scaled
+     */
+    bool scaled() const {
+      return _scaled;
     }
-  }
-  /**
-   * Returns true if the normal transfer function has been changed during the
-   * current process.
-   */
-  bool surfFctChanged() const {
-    return changed_surf_function;
-  }
 
-  /**
-   * Return the transfer function used to draw the surface in heat mode
-   */
-  TransferFunction heatFct() const {
-    return _heat_fct;
-  }
-  /**
-   * Change the transfer function used to draw the surface in heat mode
-   */
-  void setHeatFct(const TransferFunction& f)
-  {
-    if(_heat_fct != f) {
-      _heat_fct = f;
-      changed_heat_function = true;
+    /**
+     * Set if the mesh is scaled
+     */
+    void setScaled(bool on = true) {
+      _scaled = on;
     }
-  }
-  /**
-   * Returns true if the heat transfer function has been changed during the
-   * current process.
-   */
-  bool heatFctChanged() const {
-    return changed_heat_function;
-  }
+  
+    /**
+     * Returns true if the mesh is transformed
+     */
+    bool transformed() const {
+      return _transformed;
+    }
+    /**
+     * Set if the mesh is transformed
+     */
+    void setTransformed(bool on = true) {
+      _transformed = on;
+    }
+  
+    /**
+     * Returns true if the bounding box is shown
+     */
+    bool showBBox() const {
+      return _showBBox;
+    }
+  
+    /**
+     * Set if the bounding box is shown
+     */
+    void setShowBBox(bool on = true) {
+      _showBBox = on;
+    }
+  
+    /**
+     * Returns the current label, without modifying it
+     */
+    int viewLabel() const {
+      return _currLabel;
+    }
+    /**
+     * Sets the current label
+     */
+    void setLabel(int l)
+    {
+      changed_label = true;
+      _currLabel = l;
+    }
+    /**
+     * Increment the current label and return
+     */
+    int nextLabel()
+    {
+      changed_label = true;
+      return ++_currLabel;
+    }
+    /**
+     * Returns true if the curr label has been changed during this process
+     */
+    bool labelChanged() const {
+      return changed_label;
+    }
+  
+    /**
+     * Reference on the map from each label to a label in a different mesh.
+     */
+    IntIntMap& parentLabelMap() {
+      return _parentLabel;
+    }
+    /**
+     * Const reference on the map from each label to a label in a different mesh.
+     */
+    const IntIntMap& parentLabelMap() const {
+      return _parentLabel;
+    }
+    /**
+     * Returns true if the mesh has a cell structure
+     *
+     * This means that some vertexes correspond to cell centers and other the
+     * junctions.
+     */
+    bool cells() const {
+      return _cells;
+    }
+    /**
+     * Set if the mesh has a cell structure
+     *
+     * This means that some vertexes correspond to cell centers and other the
+     * junctions.
+     */
+    void setCells(bool value = true) {
+      _cells = value;
+    }
+  
+    /**
+     * Reset the whole mesh and its properties.
+     *
+     * In the end, the mesh is empty, so doesn't contain cells, texture and is neither scaled nor transformed.
+     *
+     * The next label stays untouched, as it is important to keep coordination between different meshes/stacks.
+     */
+    void reset();
+  
+    //@}
+  
+    //@{
+    ///\name Structure
+  
+    /**
+     * Get the VV graph representing the topology of the mesh
+     */
+    vvgraph& graph() {
+      return S;
+    }
+    /**
+     * Get the VV graph representing the topology of the mesh
+     */
+    const vvgraph& graph() const {
+      return S;
+    }
+    /**
+     * True if the mesh is empty (i.e. the graph is empty)
+     */
+    bool empty() const {
+      return S.empty();
+    }
+    /**
+     * Returns the number of vertices in the mesh
+     */
+    size_t size() const {
+      return S.size();
+    }
+  
+    /**
+     * Returns the label of the triangle (v1,v2,v3)
+     */
+    int getLabel(vertex v1, vertex v2, vertex v3, bool useParentLabel = true) const;
+  
+    /**
+     * Returns true if (v,n,m) correspond to a canonical triangle.
+     *
+     * This means it returns true only for one of all the possible triangles
+     * made from v, n and m (i.e. (v,n,m), (v,m,n), ...)
+     */
+    bool uniqueTri(const vertex& v, const vertex& n, const vertex& m) const
+    {
+      if(v <= n or v <= m or n == m or !S.edge(v, n) or !S.edge(v, m) or !S.edge(n, m))
+        return false;
+      else
+        return true;
+    }
+  
+    /**
+     * Update the normal of the vertex \c v in the mesh
+     *
+     * Returns false if the normal cannot be computed
+     */
+    bool setNormal(vertex v) {
+      return setNormal(S, v);
+    }
+  
+    /**
+     * Update the normal of the vertex \c v in \c S
+     *
+     * Returns false if the normal cannot be computed
+     */
+    static bool setNormal(vvgraph& S, vertex v);
+  
+    /**
+     * Update all the normals of the mesh
+     *
+     * Returns false if any normal cannot be computed
+     */
+    bool setNormals();
+  
+    /**
+     * Reference on the map from label to a position.
+     *
+     * This position will be intepreted as the center of the label, and used to
+     * draw the label number on the mesh or growth directions on cellular mesh.
+     *
+     */
+    IntPoint3fMap& labelCenter() {
+      return _labelCenter;
+    }
+    /**
+     * Returns the map from label to position
+     */
+    const IntPoint3fMap& labelCenter() const {
+      return _labelCenter;
+    }
+  
+    /**
+     * Reference on the map from label to a normal.
+     *
+     * This vector will be intepreted as the normal of the label, and used to
+     * draw the cell axis (e.g. principal directions of growth, MT orientation...).
+     *
+     */
+    IntPoint3fMap& labelNormal() {
+      return _labelNormal;
+    }
+    /**
+     * Returns the map from label to normal
+     */
+    const IntPoint3fMap& labelNormal() const {
+      return _labelNormal;
+    }
+    /**
+     * Reference on the map from label to a position.
+     *
+     * This position will be intepreted as the center of the label, and used to
+     * draw growth directions on a non-cellular mesh.
+     *
+     */
+    IntPoint3fMap& labelCenterVis() {
+      return _labelCenterVis;
+    }
+    /**
+     * Returns the map from label to position
+     */
+    const IntPoint3fMap& labelCenterVis() const {
+      return _labelCenterVis;
+    }
+  
+    /**
+     * Reference on the map from label to a normal.
+     *
+     * This vector will be intepreted as the normal of the label, and used to
+     * draw the cell axis (e.g. principal directions of growth, MT orientation...).
+     *
+     */
+    IntPoint3fMap& labelNormalVis() {
+      return _labelNormalVis;
+    }
+    /**
+     * Returns the map from label to position
+     */
+    const IntPoint3fMap& labelNormalVis() const {
+      return _labelNormalVis;
+    }
+  
+    /**
+     * Reference on the map from parent label to a position.
+     *
+     * This position will be intepreted as the center of the parent label, and used to
+     * draw the parent label number on the mesh or growth directions on cellular mesh.
+     *
+     */
+    IntPoint3fMap& parentCenter() {
+      return _parentCenter;
+    }
+    /**
+     * Returns the map from parent label to position
+     */
+    const IntPoint3fMap& parentCenter() const {
+      return _parentCenter;
+    }
+  
+    /**
+     * Reference on the map from parent label to a normal.
+     *
+     * This vector will be intepreted as the normal of the parent label, and used to
+     * draw the cell axis (e.g. principal directions of growth, MT orientation...).
+     *
+     */
+    IntPoint3fMap& parentNormal() {
+      return _parentNormal;
+    }
+    /**
+     * Returns the map from parent label to normal
+     */
+    const IntPoint3fMap& parentNormal() const {
+      return _parentNormal;
+    }
+    /**
+     * Reference on the map from parent label to a position.
+     *
+     * This position will be intepreted as the center of the parent label, and used to
+     * draw growth directions on a non-cellular mesh.
+     *
+     */
+    IntPoint3fMap& parentCenterVis() {
+      return _parentCenterVis;
+    }
+    /**
+     * Returns the map from parent label to position
+     */
+    const IntPoint3fMap& parentCenterVis() const {
+      return _parentCenterVis;
+    }
+  
+    /**
+     * Reference on the map from parent label to a normal.
+     *
+     * This vector will be intepreted as the normal of the parent label, and used to
+     * draw the cell axis (e.g. principal directions of growth, MT orientation...).
+     *
+     */
+    IntPoint3fMap& parentNormalVis() {
+      return _parentNormalVis;
+    }
+    /**
+     * Returns the map from parent label to position
+     */
+    const IntPoint3fMap& parentNormalVis() const {
+      return _parentNormalVis;
+    }
+  
+    /**
+     * Reference on the map from labels to the set of neighbor labels.
+     *
+     * A label is neighbors of another ones if they share at least an edge of the mesh.
+     *
+     * \note You shouldn't need to modify this structure directly. You should
+     * instead call Mesh::updateWallGeometry()
+     */
+    IntIntSetMap& labelNeighbors() {
+      return _labelNeighbors;
+    }
+    /**
+     * Returns the map from labels to the set of neighbors labels.
+     */
+    const IntIntSetMap& labelNeighbors() const {
+      return _labelNeighbors;
+    }
+    /**
+     * Reference on the map from each wall to the list of vertexes in the wall.
+     *
+     * A wall is identified as the interface between two labels, and as such, is given as a pair of labels. Note that
+     * there is a difference between the wall (i,j) and (j,i), as the first label is considered as the interior of the
+     * wall, and used as such when calculating the signal along a wall.
+     *
+     * \note You shouldn't need to modify this structure directly. You should
+     * instead call Mesh::updateWallGeometry()
+     */
+    IntIntVIdSetMap& wallVId() {
+      return _wallVId;
+    }
+    /**
+     * Returns the map from each wall to the list of vertexes in the wall.
+     */
+    const IntIntVIdSetMap& wallVId() const {
+      return _wallVId;
+    }
+    /**
+     * Reference on the map from each wall to the length of the wall.
+     *
+     * The length is calculated as the sum of the edges making the wall. This means the number returned is will depend
+     * on the discretization of the surface.
+     *
+     * \note You shouldn't need to modify this structure directly. You should
+     * instead call Mesh::updateWallGeometry()
+     */
+    IntIntFloatMap& wallGeom() {
+      return _wallGeom;
+    }
+    /**
+     * Reference on the map from each wall to the length of the wall.
+     */
+    const IntIntFloatMap& wallGeom() const {
+      return _wallGeom;
+    }
+  
+    /**
+     * Update labelNeighbors, wallVId and wallGeom to reflect current data structure
+     * \param borderSize Distance from the wall up to which the triangles are considered part of the wall. This is
+     * important mostly for signal intensity.
+     */
+    void updateWallGeometry(float borderSize);
+  
+    /**
+     * True if (v,n,m) is on the border of the \c label.
+     *
+     * \c rp will be set to the wall the triangle is on, if any.
+     */
+    bool isBordTriangle(int label, vertex v, vertex n, vertex m, IntIntPair& rp) const;
+  
+    /**
+     * Mark all triangles closer than borderSize from a border as being
+     * a border triangle
+     */
+    void markBorder(float borderSize);
+  
+    /**
+     * Search for the vertex closest to position of cell center
+     * fills in labelCenter, labelNormal, labelCenterVis, labelNormalVis
+     */
+    void updateCentersNormals();
+  
+    /**
+     * Prepare the axis drawing structures
+     */
+    void prepareAxisDrawing(float scaleAxisLength, Colorf colorPositive, Colorf colorNegative,
+                            const Point3b& showAxis = Point3b(true, true, true));   // ,float DisplayThreshold)
+  
+    //@}
+  
+    //@{
+    ///\name Surface methods
+    /**
+     * Return the transfer function used to draw the surface in normal mode
+     */
+    TransferFunction surfFct() const {
+      return _surf_fct;
+    }
+    /**
+     * Change the transfer function used to draw the surface in normal mode
+     */
+    void setSurfFct(const TransferFunction& f)
+    {
+      if(_surf_fct != f) {
+        _surf_fct = f;
+        changed_surf_function = true;
+      }
+    }
+    /**
+     * Returns true if the normal transfer function has been changed during the
+     * current process.
+     */
+    bool surfFctChanged() const {
+      return changed_surf_function;
+    }
+  
+    /**
+     * Return the transfer function used to draw the surface in heat mode
+     */
+    TransferFunction heatFct() const {
+      return _heat_fct;
+    }
+    /**
+     * Change the transfer function used to draw the surface in heat mode
+     */
+    void setHeatFct(const TransferFunction& f)
+    {
+      if(_heat_fct != f) {
+        _heat_fct = f;
+        changed_heat_function = true;
+      }
+    }
+    /**
+     * Returns true if the heat transfer function has been changed during the
+     * current process.
+     */
+    bool heatFctChanged() const {
+      return changed_heat_function;
+    }
+  
+    /**
+     * Get the current opacity level of the surface
+     */
+    float opacity() const {
+      return _opacity;
+    }
+    /**
+     * Change the current opactity level of the surface
+     */
+    void setOpacity(float f)
+    {
+      if(f < 0)
+        _opacity = 0;
+      else if(f > 1)
+        _opacity = 1;
+      else
+        _opacity = f;
+    }
+    /**
+     * Get the current brightness of the surface
+     */
+    float brightness() const {
+      return _brightness;
+    }
+    /**
+     * Change the current brightness of the surface
+     */
+    void setBrightness(float f)
+    {
+      if(f < 0)
+        _brightness = 0;
+      else if(f > 1)
+        _brightness = 1;
+      else
+        _brightness = f;
+    }
+  
+    /**
+     * True if the surface is currently visible to the user
+     */
+    bool isSurfaceVisible() const {
+      return _isSurfaceVisible;
+    }
+    /**
+     * Show the surface to the user
+     */
+    void showSurface() {
+      _isSurfaceVisible = true;
+    }
+    /**
+     * Hide the surface from the user
+     */
+    void hideSurface() {
+      _isSurfaceVisible = false;
+    }
+  
+    /**
+     * Show the heat map of the surface, if any
+     */
+    void showNormal() {
+      _show = NORMAL;
+    }
+    /**
+     * Show the labels of the surface triangles
+     */
+    void showLabel() {
+      _show = LABEL;
+    }
+    /**
+     * Show the color of the surface
+     */
+    void showHeat() {
+      _show = HEAT;
+    }
+    /**
+     * Show the color of the surface
+     */
+    void showParent() {
+      _show = PARENT;
+    }
+  
+    /**
+     * Change the view mode
+     */
+    void show(SurfView view) {
+      _show = view;
+    }
+  
+    /**
+     * Set the current color to be the signal (i.e. intensity) on each triangle
+     */
+    void showSignal() {
+      _color = SIGNAL;
+    }
+    /**
+     * Set the current color to be the 3D texture at the position of the point.
+     *
+     * This represent the surface as a cut through the volume. The 3D texture
+     * selected correspond to the current one for the stack attached to this
+     * mesh.
+     */
+    void showTexture() {
+      _color = TEXTURE;
+    }
+  
+    /**
+     * Set the current color to be the texture attached to the mesh.
+     */
+    void showImage() {
+      _color = IMAGE;
+    }
+  
+    /**
+     * Change the color mode
+     */
+    void show(Color color) {
+      _color = color;
+    }
+  
+    /**
+     * Returns if the back surface is culled
+     */
+    bool culling() const {
+      return _culling;
+    }
+    /**
+     * Cull the back surface
+     */
+    void setCulling(bool cul) {
+      _culling = cul;
+    }
+  
+    /**
+     * Return if the surface is rendered blended or not
+     */
+    bool blending() const {
+      return _blending;
+    }
+    /**
+     * Set the blending attribute
+     */
+    void setBlending(bool b) {
+      _blending = b;
+    }
+  
+    /**
+     * Returns the current visualisation for the surface
+     */
+    SurfView toShow() const {
+      return _show;
+    }
+    /**
+     * Returns the current coloring for the surface
+     */
+    Color coloring() const {
+      return _color;
+    }
+  
+    /**
+     * True if the surface has a texture attached to it
+     */
+    bool hasImgTex() const {
+      return _imgtex;
+    }
+    /**
+     * Get the current texture attached to the surface
+     */
+    const QImage& imgTex() const {
+      return _image;
+    }
+    /**
+     * Set the texture attached to the surface
+     */
+    void setImgTex(const QImage& img)
+    {
+      _imgtex = true;
+      _image = img;
+    }
+    /**
+     * Remove any texture attached to the surface
+     */
+    void clearImgTex()
+    {
+      _imgtex = false;
+      _image = QImage();
+    }
+  
+    //@}
+  
+    //@{
+    ///\name Mesh methods
+    /**
+     * Is the mesh currently visible to the user
+     */
+    bool isMeshVisible() const {
+      return _isMeshVisible;
+    }
+    /**
+     * Make the mesh visible to the user
+     */
+    void showMesh() {
+      _isMeshVisible = true;
+    }
+    /**
+     * Hide the mesh from the user
+     */
+    void hideMesh() {
+      _isMeshVisible = false;
+    }
+  
+    /**
+     * Return the current view mode for the mesh
+     */
+    MeshView meshView() const {
+      return _meshView;
+    }
+  
+    /**
+     * Set the mesh view to all
+     */
+    void showAllMesh() {
+      _meshView = ALL_MESH;
+    }
+    /**
+     * Set the mesh view to cell border only
+     */
+    void showCellMesh() {
+      _meshView = CELL_MESH;
+    }
+    /**
+     * Set the mesh view to mesh border only
+     */
+    void showBorderMesh() {
+      _meshView = BORDER_MESH;
+    }
+    /**
+     * Set the mesh view to selected mesh only
+     */
+    void showSelectedMesh() {
+      _meshView = SELECTED_MESH;
+    }
+  
+    /**
+     * Change the mesh view mode
+     */
+    void show(MeshView view) {
+      _meshView = view;
+    }
+  
+    /**
+     * Are mesh lines visible
+     */
+    bool showMeshLines() const {
+      return _showMeshLines;
+    }
+    /**
+     * Are mesh points visible
+     */
+    bool showMeshPoints() const {
+      return _showMeshPoints;
+    }
+    /**
+     * Are cell numbers visible
+     */
+    bool showMeshCellMap() const {
+      return _showMeshCellMap;
+    }
+  
+    /**
+     * Set if the mesh visible at all
+     */
+    void setShowMesh(bool show) {
+      _isMeshVisible = show;
+    }
+    /**
+     * Set if the mesh lines are visible
+     */
+    void setShowMeshLines(bool show) {
+      _showMeshLines = show;
+    }
+    /**
+     * Set if the mesh points are visible
+     */
+    void setShowMeshPoints(bool show) {
+      _showMeshPoints = show;
+    }
+    /**
+     * Set if the cell numbers are visible
+     */
+    void setShowMeshCellMap(bool show) {
+      _showMeshCellMap = show;
+    }
+  
+    /**
+     * Returns a vector with the list of selected vertices.
+     */
+    std::vector<vertex> selectedVertices() const;
+  
+    /**
+     * Returns a vector with the list of active vertices.
+     *
+     * These are either the selected vertices, or all of them if no vertex was selected.
+     */
+    std::vector<vertex> activeVertices() const;
+  
+    // These next two should really be algorithms for the graph as they don't rely on
+    // any Mesh variables.
+    /**
+     * Starting with a set of vertices, extend to connected region
+     */
+    void getConnectedVertices(const vvgraph& S, vvgraph& vSet) const;
+  
+    /**
+     * Get a list of connected regions (3D cells)
+     */
+    int getConnectedRegions(const vvgraph& S, VVGraphVec& cellVId, VIntMap& vtxCell) const;
+  
+    /**
+     * Get the neighborhood of a vertex
+     */
+    static void getNhbd(const vvgraph& S, const vertex& v, float radius, VtxSet& nbs);
+  
+    /**
+     * Correct selection
+     *
+     * Make sure the vertices are "correctly" selected. This means that:
+     *  * border vertices will be selected if all their non-border neighbors are
+     *  * border vertices will be selected if they don't have a non-border neighbors and at least one border neighbor is
+     *  selected
+     *  * if the selection is inclusive, border vertices will be selected if at least one non-border neighbor is
+     *  selected
+     */
+    void correctSelection(bool inclusive);
+  
+    //@}
+  
+    //@{
+    ///\name Updating the graphical representation
+    /**
+     * To be called when the mesh structure changed
+     */
+    void updateAll();
+    /**
+     * To be called if properties of the triangles changed
+     */
+    void updateTriangles();
+    /**
+     * To be called if properties of the lines changed
+     */
+    void updateLines();
+    /**
+     * To be called if the position of the points changed
+     */
+    void updatePositions();
+    /**
+     * To be called if the selection of the points changed
+     */
+    void updateSelection();
+    /** Returns what changed in the current process
+     */
+    int changes() const {
+      return _changed;
+    }
+    //@}
+  
+    //@{
+    /**
+     * \name Heat Map methods
+     * The heat map associate a heat (from 0 to 1) to a label or a wall.
+     *
+     * As the heat is always from 0 to 1, the bounds of the heat map have to be
+     * specified separatly for presentation purposes and correspond to the
+     * actual value associated to 0 and 1.
+     */
+    /** Reference on the map from label to intensity
+     */
+    IntFloatMap& labelHeat() {
+      return _labelHeat;
+    }
+    /** Returns the map from label to intensity
+     */
+    const IntFloatMap& labelHeat() const {
+      return _labelHeat;
+    }
+    /** Reference on the map from wall (i.e. pair of vertex id) to intensity
+     */
+    IntIntFloatMap& wallHeat() {
+      return _wallHeat;
+    }
+    /** Returns the map from wall (i.e. pair of vertex id) to intensity
+     */
+    const IntIntFloatMap& wallHeat() const {
+      return _wallHeat;
+    }
+    /**
+     * Reference on the unit used for the current heat map.
+     *
+     * It is shown on the color bar.
+     */
+    QString& heatMapUnit() {
+      return _heatMapUnit;
+    }
+    /// Returns the unit used for the current heat map
+    const QString& heatMapUnit() const {
+      return _heatMapUnit;
+    }
+    /// Reference on the upper and lower bounds for the heat.
+    Point2f& heatMapBounds() {
+      return _heatMapBounds;
+    }
+    /// Return the upper and lower bounds for the heat.
+    const Point2f& heatMapBounds() const {
+      return _heatMapBounds;
+    }
+  
+    /**
+     * Return the mapping of tensors for each cell
+     *
+     * The tensors are encoded as three vectors: ev1, ev2, evals.
+     * Where ev1 and ev2 are the two first eigenvectors and evals is the vector with the three eigenvalues.
+     */
+    IntSymTensorMap& cellAxis() {
+      return _cellAxis;
+    }
+  
+    /**
+     * Returns the map from label to cells axis (array of 3 Point3f), scaled for visualisation
+     */
+    IntMatrix3x3fMap& cellAxisScaled() {
+      return _cellAxisScaled;
+    }                                                                // added by ALR
+  
+    /**
+     * Returns the map from label to cells axis colors (array of 3 Point3f)
+     */
+    IntMatrix3x3fMap& cellAxisColor() {
+      return _cellAxisColor;
+    }                                                              // added by ALR
+  
+    /** Returns the cell axis width
+     */
+    float& cellAxisWidth() {
+      return _cellAxisWidth;
+    }                                                   // added by ALR
+    /** Returns a reference to the cell axis z-offset for drawing
+     */
+    float& cellAxisOffset() {
+      return _cellAxisOffset;
+    }
+    /**
+     * Return the type of the current cell axis.
+     *
+     * If an empty string, there is no cell axis.
+     */
+    const QString& cellAxisType() const {
+      return _cellAxisType;
+    }
+    /**
+     * Return the type of the current cell axis.
+     *
+     * If an empty string, there is no cell axis.
+     */
+    QString& cellAxisType() {
+      return _cellAxisType;
+    }
+    /**
+     * Unit for the length of the cell axis
+     */
+    const QString& cellAxisUnit() const {
+      return _cellAxisUnit;
+    }
+    /**
+     * Unit for the length of the cell axis
+     */
+    QString& cellAxisUnit() {
+      return _cellAxisUnit;
+    }
+    /**
+     * Remove any cell axis
+     */
+    void clearCellAxis();
+    /** Returns a reference to the map of correspondence between vertices in mesh1 and mesh2 (store vertices positions)
+     */
+    IntMatrix3x3fMap& vvCorrespondance() {
+      return _VVCorrespondance;
+    }                                                                    // added by ALR
+    /** Returns a boolean for visualization of lines between corresponding vertices
+     */
+    bool& showVVCorrespondance() {
+      return _showVVCorrespondance;
+    }                                                                // added by ALR
+  
+    //@}
+  
+    //@{
+    /**
+     * \name Signal methods
+     * The signal spans from 0 to 1, but may correspond to any range of values.
+     * These methods specifies the range and the units.
+     */
+    /**
+     * Reference on the unit used for the signal.
+     *
+     * It is shown on the color bar.
+     */
+    QString& signalUnit() {
+      return _signalUnit;
+    }
+    /// Returns the unit used for the signal
+    const QString& signalUnit() const {
+      return _signalUnit;
+    }
+    /// Reference on the upper and lower bounds for the signal.
+    Point2f& signalBounds() {
+      return _signalBounds;
+    }
+    /// Return the upper and lower bounds for the signal.
+    const Point2f& signalBounds() const {
+      return _signalBounds;
+    }
+    //@}
+  
+    bool needsColorbar() const
+    {
+      return (isSurfaceVisible() and ((toShow() == HEAT and (_labelHeat.size() > 1 or _wallHeat.size() > 1))
+                                      or (toShow() == NORMAL and coloring() == SIGNAL)));
+    }
+  
+    const BoundingBox3f& boundingBox() const {
+      return _bbox;
+    }
+    BoundingBox3f& boundingBox() {
+      return _bbox;
+    }
+    void setBoundingBox(const BoundingBox3f& bbox) {
+      _bbox = bbox;
+    }
+    void updateBBox();
+  
+  private:
+    void resetModified();
+  
+    vvgraph S;
+    TransferFunction _surf_fct, _heat_fct;
+    IntFloatMap _labelHeat;
+    IntIntFloatMap _wallHeat;
+    IntPoint3fMap _labelCenter;
+    IntPoint3fMap _labelCenterVis;
+    IntPoint3fMap _labelNormal;
+    IntPoint3fMap _labelNormalVis;
+    IntPoint3fMap _parentCenter;
+    IntPoint3fMap _parentCenterVis;
+    IntPoint3fMap _parentNormal;
+    IntPoint3fMap _parentNormalVis;
+    IntSymTensorMap _cellAxis;
+    IntMatrix3x3fMap _cellAxisScaled;
+    IntMatrix3x3fMap _cellAxisColor;
+    float _cellAxisWidth;
+    float _cellAxisOffset;
+    QString _cellAxisType;
+    QString _cellAxisUnit;
+    IntMatrix3x3fMap _VVCorrespondance;
+    bool _showVVCorrespondance;
+    IntIntSetMap _labelNeighbors;
+    IntIntVIdSetMap _wallVId;
+    IntIntFloatMap _wallGeom;
+    QString _signalUnit, _heatMapUnit;
+    Point2f _signalBounds, _heatMapBounds;
+    bool changed_surf_function, changed_heat_function;
+    bool changed_label;
+    int _changed;
+    SurfView _show;
+    Color _color;
+    bool _culling, _blending;
+    bool _isSurfaceVisible, _isMeshVisible;
+    int _currLabel;
+    IntIntMap _parentLabel;
+    float _opacity, _brightness;
+    MeshView _meshView;
+    bool _showMeshLines, _showMeshPoints, _showMeshCellMap;
+    bool _cells, _imgtex;
+    QString _file;
+    QString _parentFile;
+    bool _scaled;
+    bool _transformed;
+    bool _showBBox;
+    int _id;
+    const Stack* _stack;
+    QImage _image;
+  
+    BoundingBox3f _bbox;
+  
+    void init();
+  };
+}
 
-  /**
-   * Get the current opacity level of the surface
-   */
-  float opacity() const {
-    return _opacity;
-  }
-  /**
-   * Change the current opactity level of the surface
-   */
-  void setOpacity(float f)
-  {
-    if(f < 0)
-      _opacity = 0;
-    else if(f > 1)
-      _opacity = 1;
-    else
-      _opacity = f;
-  }
-  /**
-   * Get the current brightness of the surface
-   */
-  float brightness() const {
-    return _brightness;
-  }
-  /**
-   * Change the current brightness of the surface
-   */
-  void setBrightness(float f)
-  {
-    if(f < 0)
-      _brightness = 0;
-    else if(f > 1)
-      _brightness = 1;
-    else
-      _brightness = f;
-  }
-
-  /**
-   * True if the surface is currently visible to the user
-   */
-  bool isSurfaceVisible() const {
-    return _isSurfaceVisible;
-  }
-  /**
-   * Show the surface to the user
-   */
-  void showSurface() {
-    _isSurfaceVisible = true;
-  }
-  /**
-   * Hide the surface from the user
-   */
-  void hideSurface() {
-    _isSurfaceVisible = false;
-  }
-
-  /**
-   * Show the heat map of the surface, if any
-   */
-  void showNormal() {
-    _show = NORMAL;
-  }
-  /**
-   * Show the labels of the surface triangles
-   */
-  void showLabel() {
-    _show = LABEL;
-  }
-  /**
-   * Show the color of the surface
-   */
-  void showHeat() {
-    _show = HEAT;
-  }
-  /**
-   * Show the color of the surface
-   */
-  void showParent() {
-    _show = PARENT;
-  }
-
-  /**
-   * Change the view mode
-   */
-  void show(SurfView view) {
-    _show = view;
-  }
-
-  /**
-   * Set the current color to be the signal (i.e. intensity) on each triangle
-   */
-  void showSignal() {
-    _color = SIGNAL;
-  }
-  /**
-   * Set the current color to be the 3D texture at the position of the point.
-   *
-   * This represent the surface as a cut through the volume. The 3D texture
-   * selected correspond to the current one for the stack attached to this
-   * mesh.
-   */
-  void showTexture() {
-    _color = TEXTURE;
-  }
-
-  /**
-   * Set the current color to be the texture attached to the mesh.
-   */
-  void showImage() {
-    _color = IMAGE;
-  }
-
-  /**
-   * Change the color mode
-   */
-  void show(Color color) {
-    _color = color;
-  }
-
-  /**
-   * Returns if the back surface is culled
-   */
-  bool culling() const {
-    return _culling;
-  }
-  /**
-   * Cull the back surface
-   */
-  void setCulling(bool cul) {
-    _culling = cul;
-  }
-
-  /**
-   * Return if the surface is rendered blended or not
-   */
-  bool blending() const {
-    return _blending;
-  }
-  /**
-   * Set the blending attribute
-   */
-  void setBlending(bool b) {
-    _blending = b;
-  }
-
-  /**
-   * Returns the current visualisation for the surface
-   */
-  SurfView toShow() const {
-    return _show;
-  }
-  /**
-   * Returns the current coloring for the surface
-   */
-  Color coloring() const {
-    return _color;
-  }
-
-  /**
-   * True if the surface has a texture attached to it
-   */
-  bool hasImgTex() const {
-    return _imgtex;
-  }
-  /**
-   * Get the current texture attached to the surface
-   */
-  const QImage& imgTex() const {
-    return _image;
-  }
-  /**
-   * Set the texture attached to the surface
-   */
-  void setImgTex(const QImage& img)
-  {
-    _imgtex = true;
-    _image = img;
-  }
-  /**
-   * Remove any texture attached to the surface
-   */
-  void clearImgTex()
-  {
-    _imgtex = false;
-    _image = QImage();
-  }
-
-  //@}
-
-  //@{
-  ///\name Mesh methods
-  /**
-   * Is the mesh currently visible to the user
-   */
-  bool isMeshVisible() const {
-    return _isMeshVisible;
-  }
-  /**
-   * Make the mesh visible to the user
-   */
-  void showMesh() {
-    _isMeshVisible = true;
-  }
-  /**
-   * Hide the mesh from the user
-   */
-  void hideMesh() {
-    _isMeshVisible = false;
-  }
-
-  /**
-   * Return the current view mode for the mesh
-   */
-  MeshView meshView() const {
-    return _meshView;
-  }
-
-  /**
-   * Set the mesh view to all
-   */
-  void showAllMesh() {
-    _meshView = ALL_MESH;
-  }
-  /**
-   * Set the mesh view to cell border only
-   */
-  void showCellMesh() {
-    _meshView = CELL_MESH;
-  }
-  /**
-   * Set the mesh view to mesh border only
-   */
-  void showBorderMesh() {
-    _meshView = BORDER_MESH;
-  }
-  /**
-   * Set the mesh view to selected mesh only
-   */
-  void showSelectedMesh() {
-    _meshView = SELECTED_MESH;
-  }
-
-  /**
-   * Change the mesh view mode
-   */
-  void show(MeshView view) {
-    _meshView = view;
-  }
-
-  /**
-   * Are mesh lines visible
-   */
-  bool showMeshLines() const {
-    return _showMeshLines;
-  }
-  /**
-   * Are mesh points visible
-   */
-  bool showMeshPoints() const {
-    return _showMeshPoints;
-  }
-  /**
-   * Are cell numbers visible
-   */
-  bool showMeshCellMap() const {
-    return _showMeshCellMap;
-  }
-
-  /**
-   * Set if the mesh visible at all
-   */
-  void setShowMesh(bool show) {
-    _isMeshVisible = show;
-  }
-  /**
-   * Set if the mesh lines are visible
-   */
-  void setShowMeshLines(bool show) {
-    _showMeshLines = show;
-  }
-  /**
-   * Set if the mesh points are visible
-   */
-  void setShowMeshPoints(bool show) {
-    _showMeshPoints = show;
-  }
-  /**
-   * Set if the cell numbers are visible
-   */
-  void setShowMeshCellMap(bool show) {
-    _showMeshCellMap = show;
-  }
-
-  /**
-   * Returns a vector with the list of selected vertices.
-   */
-  std::vector<vertex> selectedVertices() const;
-
-  /**
-   * Returns a vector with the list of active vertices.
-   *
-   * These are either the selected vertices, or all of them if no vertex was selected.
-   */
-  std::vector<vertex> activeVertices() const;
-
-  // These next two should really be algorithms for the graph as they don't rely on
-  // any Mesh variables.
-  /**
-   * Starting with a set of vertices, extend to connected region
-   */
-  void getConnectedVertices(const vvgraph& S, vvgraph& vSet) const;
-
-  /**
-   * Get a list of connected regions (3D cells)
-   */
-  int getConnectedRegions(const vvgraph& S, VVGraphVec& cellVId, VIntMap& vtxCell) const;
-
-  /**
-   * Get the neighborhood of a vertex
-   */
-  static void getNhbd(const vvgraph& S, const vertex& v, float radius, VtxSet& nbs);
-
-  /**
-   * Correct selection
-   *
-   * Make sure the vertices are "correctly" selected. This means that:
-   *  * border vertices will be selected if all their non-border neighbors are
-   *  * border vertices will be selected if they don't have a non-border neighbors and at least one border neighbor is
-   *  selected
-   *  * if the selection is inclusive, border vertices will be selected if at least one non-border neighbor is
-   *  selected
-   */
-  void correctSelection(bool inclusive);
-
-  //@}
-
-  //@{
-  ///\name Updating the graphical representation
-  /**
-   * To be called when the mesh structure changed
-   */
-  void updateAll();
-  /**
-   * To be called if properties of the triangles changed
-   */
-  void updateTriangles();
-  /**
-   * To be called if properties of the lines changed
-   */
-  void updateLines();
-  /**
-   * To be called if the position of the points changed
-   */
-  void updatePositions();
-  /**
-   * To be called if the selection of the points changed
-   */
-  void updateSelection();
-  /** Returns what changed in the current process
-   */
-  int changes() const {
-    return _changed;
-  }
-  //@}
-
-  //@{
-  /**
-   * \name Heat Map methods
-   * The heat map associate a heat (from 0 to 1) to a label or a wall.
-   *
-   * As the heat is always from 0 to 1, the bounds of the heat map have to be
-   * specified separatly for presentation purposes and correspond to the
-   * actual value associated to 0 and 1.
-   */
-  /** Reference on the map from label to intensity
-   */
-  IntFloatMap& labelHeat() {
-    return _labelHeat;
-  }
-  /** Returns the map from label to intensity
-   */
-  const IntFloatMap& labelHeat() const {
-    return _labelHeat;
-  }
-  /** Reference on the map from wall (i.e. pair of vertex id) to intensity
-   */
-  IntIntFloatMap& wallHeat() {
-    return _wallHeat;
-  }
-  /** Returns the map from wall (i.e. pair of vertex id) to intensity
-   */
-  const IntIntFloatMap& wallHeat() const {
-    return _wallHeat;
-  }
-  /**
-   * Reference on the unit used for the current heat map.
-   *
-   * It is shown on the color bar.
-   */
-  QString& heatMapUnit() {
-    return _heatMapUnit;
-  }
-  /// Returns the unit used for the current heat map
-  const QString& heatMapUnit() const {
-    return _heatMapUnit;
-  }
-  /// Reference on the upper and lower bounds for the heat.
-  Point2f& heatMapBounds() {
-    return _heatMapBounds;
-  }
-  /// Return the upper and lower bounds for the heat.
-  const Point2f& heatMapBounds() const {
-    return _heatMapBounds;
-  }
-
-  /**
-   * Return the mapping of tensors for each cell
-   *
-   * The tensors are encoded as three vectors: ev1, ev2, evals.
-   * Where ev1 and ev2 are the two first eigenvectors and evals is the vector with the three eigenvalues.
-   */
-  IntSymTensorMap& cellAxis() {
-    return _cellAxis;
-  }
-
-  /**
-   * Returns the map from label to cells axis (array of 3 Point3f), scaled for visualisation
-   */
-  IntMatrix3x3fMap& cellAxisScaled() {
-    return _cellAxisScaled;
-  }                                                                // added by ALR
-
-  /**
-   * Returns the map from label to cells axis colors (array of 3 Point3f)
-   */
-  IntMatrix3x3fMap& cellAxisColor() {
-    return _cellAxisColor;
-  }                                                              // added by ALR
-
-  /** Returns the cell axis width
-   */
-  float& cellAxisWidth() {
-    return _cellAxisWidth;
-  }                                                   // added by ALR
-  /** Returns a reference to the cell axis z-offset for drawing
-   */
-  float& cellAxisOffset() {
-    return _cellAxisOffset;
-  }
-  /**
-   * Return the type of the current cell axis.
-   *
-   * If an empty string, there is no cell axis.
-   */
-  const QString& cellAxisType() const {
-    return _cellAxisType;
-  }
-  /**
-   * Return the type of the current cell axis.
-   *
-   * If an empty string, there is no cell axis.
-   */
-  QString& cellAxisType() {
-    return _cellAxisType;
-  }
-  /**
-   * Unit for the length of the cell axis
-   */
-  const QString& cellAxisUnit() const {
-    return _cellAxisUnit;
-  }
-  /**
-   * Unit for the length of the cell axis
-   */
-  QString& cellAxisUnit() {
-    return _cellAxisUnit;
-  }
-  /**
-   * Remove any cell axis
-   */
-  void clearCellAxis();
-  /** Returns a reference to the map of correspondence between vertices in mesh1 and mesh2 (store vertices positions)
-   */
-  IntMatrix3x3fMap& vvCorrespondance() {
-    return _VVCorrespondance;
-  }                                                                    // added by ALR
-  /** Returns a boolean for visualization of lines between corresponding vertices
-   */
-  bool& showVVCorrespondance() {
-    return _showVVCorrespondance;
-  }                                                                // added by ALR
-
-  //@}
-
-  //@{
-  /**
-   * \name Signal methods
-   * The signal spans from 0 to 1, but may correspond to any range of values.
-   * These methods specifies the range and the units.
-   */
-  /**
-   * Reference on the unit used for the signal.
-   *
-   * It is shown on the color bar.
-   */
-  QString& signalUnit() {
-    return _signalUnit;
-  }
-  /// Returns the unit used for the signal
-  const QString& signalUnit() const {
-    return _signalUnit;
-  }
-  /// Reference on the upper and lower bounds for the signal.
-  Point2f& signalBounds() {
-    return _signalBounds;
-  }
-  /// Return the upper and lower bounds for the signal.
-  const Point2f& signalBounds() const {
-    return _signalBounds;
-  }
-  //@}
-
-  bool needsColorbar() const
-  {
-    return (isSurfaceVisible() and ((toShow() == HEAT and (_labelHeat.size() > 1 or _wallHeat.size() > 1))
-                                    or (toShow() == NORMAL and coloring() == SIGNAL)));
-  }
-
-  const BoundingBox3f& boundingBox() const {
-    return _bbox;
-  }
-  BoundingBox3f& boundingBox() {
-    return _bbox;
-  }
-  void setBoundingBox(const BoundingBox3f& bbox) {
-    _bbox = bbox;
-  }
-  void updateBBox();
-
-private:
-  void resetModified();
-
-  vvgraph S;
-  TransferFunction _surf_fct, _heat_fct;
-  IntFloatMap _labelHeat;
-  IntIntFloatMap _wallHeat;
-  IntPoint3fMap _labelCenter;
-  IntPoint3fMap _labelCenterVis;
-  IntPoint3fMap _labelNormal;
-  IntPoint3fMap _labelNormalVis;
-  IntPoint3fMap _parentCenter;
-  IntPoint3fMap _parentCenterVis;
-  IntPoint3fMap _parentNormal;
-  IntPoint3fMap _parentNormalVis;
-  IntSymTensorMap _cellAxis;
-  IntMatrix3x3fMap _cellAxisScaled;
-  IntMatrix3x3fMap _cellAxisColor;
-  float _cellAxisWidth;
-  float _cellAxisOffset;
-  QString _cellAxisType;
-  QString _cellAxisUnit;
-  IntMatrix3x3fMap _VVCorrespondance;
-  bool _showVVCorrespondance;
-  IntIntSetMap _labelNeighbors;
-  IntIntVIdSetMap _wallVId;
-  IntIntFloatMap _wallGeom;
-  QString _signalUnit, _heatMapUnit;
-  Point2f _signalBounds, _heatMapBounds;
-  bool changed_surf_function, changed_heat_function;
-  bool changed_label;
-  int _changed;
-  SurfView _show;
-  Color _color;
-  bool _culling, _blending;
-  bool _isSurfaceVisible, _isMeshVisible;
-  int _currLabel;
-  IntIntMap _parentLabel;
-  float _opacity, _brightness;
-  MeshView _meshView;
-  bool _showMeshLines, _showMeshPoints, _showMeshCellMap;
-  bool _cells, _imgtex;
-  QString _file;
-  bool _scaled;
-  bool _transformed;
-  bool _showBBox;
-  int _id;
-  const Stack* _stack;
-  QImage _image;
-
-  BoundingBox3f _bbox;
-
-  void init();
-};
-} // namespace mgx
-
-#endif // MESH_HPP
+#endif 
Index: StackProcessFilters.hpp
===================================================================
--- StackProcessFilters.hpp	(revision 1255)
+++ StackProcessFilters.hpp	(revision 1256)
@@ -3,744 +3,695 @@
 
 #include <Process.hpp>
 
-namespace mgx {
-namespace process {
-
-///\addtogroup StackProcess
-///@{
-/**
- * \class AverageStack StackProcessFilters.hpp <StackProcessFilters.hpp>
- *
- * Compute the local average of each voxel of the stack.
- *
- * More precisely, this module perform the convolution of the stack with the
- * square kernel of given radius.
- */
-class MGX_EXPORT AverageStack : public StackProcess {
-public:
-  AverageStack(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Store* input = currentStack()->currentStore();
-    Store* output = currentStack()->work();
-    Point3i r(parms[0].toInt(), parms[1].toInt(), parms[2].toInt());
-    bool res = (*this)(input, output, r, parms[3].toUInt());
-    if(res) {
-      input->hide();
-      output->show();
+namespace mgx { namespace process 
+{
+  ///\addtogroup StackProcess
+  ///@{
+  /**
+   * \class AverageStack StackProcessFilters.hpp <StackProcessFilters.hpp>
+   *
+   * Compute the local average of each voxel of the stack.
+   *
+   * More precisely, this module perform the convolution of the stack with the
+   * square kernel of given radius.
+   */
+  class MGX_EXPORT AverageStack : public StackProcess {
+  public:
+    AverageStack(const StackProcess& process) : Process(process), StackProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Store* input = currentStack()->currentStore();
+      Store* output = currentStack()->work();
+      Point3i r(parms[0].toInt(), parms[1].toInt(), parms[2].toInt());
+      bool res = (*this)(input, output, r, parms[3].toUInt());
+      if(res) {
+        input->hide();
+        output->show();
+      }
+      return res;
     }
-    return res;
-  }
-
-  bool operator()(const Store* input, Store* output, Point3i radius, uint steps);
-
-  QString name() const {
-    return "Average";
-  }
-  QString description() const {
-    return "Average stack data with a square filter.";
-  }
-  QString folder() const {
-    return "Filters";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "X Radius"
-                         << "Y Radius"
-                         << "Z Radius"
-                         << "Steps";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "X Radius"
-                         << "Y Radius"
-                         << "Z Radius"
-                         << "Steps";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "1"
-                         << "1"
-                         << "1"
-                         << "1";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/AvgPix.png");
-  }
-};
-
-/**
- * \class BrightenStack StackProcessFilters.hpp <StackProcessFilters.hpp>
- *
- * Change the global luminosity of the stack. The value of each voxel will be
- * multiplied by the brightening constant. So a value > 1 will brighten the
- * stack, while a value < 1 will darken the stack
- *
- * Useful examples:
- *  - to convert a stack from 12bits to 16bits, use 16;
- *  - to convert a stack from 8bits to 16bits, use 256.
- */
-class MGX_EXPORT BrightenStack : public StackProcess {
-public:
-  BrightenStack(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Stack* s = currentStack();
-    Store* input = s->currentStore();
-    Store* output = s->work();
-    bool res = (*this)(input, output, parms[0].toFloat());
-    if(res) {
-      input->hide();
-      output->show();
+  
+    bool operator()(const Store* input, Store* output, Point3i radius, uint steps);
+  
+    QString name() const { return "Average"; }
+    QString description() const { return "Average stack data with a square filter."; }
+    QString folder() const { return "Filters"; }
+    QStringList parmNames() const { return QStringList() << "X Radius" << "Y Radius" << "Z Radius" << "Steps"; }
+    QStringList parmDescs() const { return QStringList() << "X Radius" << "Y Radius" << "Z Radius" << "Steps"; }
+    QStringList parmDefaults() const { return QStringList() << "1" << "1" << "1" << "1"; }
+    QIcon icon() const { return QIcon(":/images/AvgPix.png"); }
+  };
+  
+  /**
+   * \class BrightenStack StackProcessFilters.hpp <StackProcessFilters.hpp>
+   *
+   * Change the global luminosity of the stack. The value of each voxel will be
+   * multiplied by the brightening constant. So a value > 1 will brighten the
+   * stack, while a value < 1 will darken the stack
+   *
+   * Useful examples:
+   *  - to convert a stack from 12bits to 16bits, use 16;
+   *  - to convert a stack from 8bits to 16bits, use 256.
+   */
+  class MGX_EXPORT BrightenStack : public StackProcess {
+  public:
+    BrightenStack(const StackProcess& process) : Process(process), StackProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Stack* s = currentStack();
+      Store* input = s->currentStore();
+      Store* output = s->work();
+      bool res = (*this)(input, output, parms[0].toFloat());
+      if(res) {
+        input->hide();
+        output->show();
+      }
+      return res;
     }
-    return res;
-  }
-  bool operator()(const Store* input, Store* output, float brightness);
-
-  QString folder() const {
-    return "Filters";
-  }
-  QString name() const {
-    return "Brighten Darken";
-  }
-  QString description() const
-  {
-    return "Brighten or Darken stack.\n"
-           "A value > 1 will brighten the stack, < 1 will darken it."
-           "To convert from 12bits to 16bits stack, use 16."
-           "To convert from 8bits to 16bits stack, use 256.";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Amount";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Amount to multiply voxels";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "2.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Brightness.png");
-  }
-};
-
-/**
- * \class BinarizeStack StackProcessFilters.hpp <StackProcessFilters.hpp>
- *
- * Binarize the stack: set the intensity of any voxel greater than the
- * threshold to 65535 and all other voxels to 0.
- */
-class MGX_EXPORT BinarizeStack : public StackProcess {
-public:
-  BinarizeStack(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Stack* s = currentStack();
-    Store* input = s->currentStore();
-    Store* output = s->work();
-    bool res = (*this)(input, output, parms[0].toUShort());
-    if(res) {
-      input->hide();
-      output->show();
+    bool operator()(const Store* input, Store* output, float brightness);
+  
+    QString folder() const { return "Filters"; }
+    QString name() const { return "Brighten Darken"; }
+    QString description() const { return 
+      "Brighten or Darken stack.\n"
+      "A value > 1 will brighten the stack, < 1 will darken it.\n"
+      "To convert from a 12bit to a 16bit stack, use 16.\n"
+      "To convert from a 8bit to a 16bit stack, use 256.\n"; }
+    QStringList parmNames() const { return QStringList() << "Amount"; }
+    QStringList parmDescs() const { return QStringList() << "Amount to multiply voxels"; }
+    QStringList parmDefaults() const { return QStringList() << "2.0"; }
+    QIcon icon() const { return QIcon(":/images/Brightness.png"); }
+  };
+  
+  /**
+   * \class BinarizeStack StackProcessFilters.hpp <StackProcessFilters.hpp>
+   *
+   * Binarize the stack: set the intensity of any voxel greater than the
+   * threshold to 65535 and all other voxels to 0.
+   */
+  class MGX_EXPORT BinarizeStack : public StackProcess {
+  public:
+    BinarizeStack(const StackProcess& process)
+      : Process(process)
+      , StackProcess(process)
+    {
     }
-    return res;
-  }
-  bool operator()(const Store* input, Store* output, ushort threshold);
-
-  QString folder() const {
-    return "Filters";
-  }
-  QString name() const {
-    return "Binarize";
-  }
-  QString description() const
-  {
-    return "Transform the stack to binary (65535 or 0).\n"
-           "All voxels with an intensity greater than the threshold to 65535, while to others are set to 0.";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Threshold";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Voxels above this threshold will be assigned 1.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "5000";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Brightness.png");
-  }
-};
-
-/**
- * \class ColorGradient StackProcessFilters.hpp <StackProcessFilters.hpp>
- *
- * Compute the gradient of the image in the Z axis of the image.
- */
-class MGX_EXPORT ColorGradient : public StackProcess {
-public:
-  ColorGradient(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Stack* s = currentStack();
-    Store* input = s->currentStore();
-    Store* output = s->work();
-    bool res = (*this)(input, output, parms[0].toFloat());
-    if(res) {
-      input->hide();
-      output->show();
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Stack* s = currentStack();
+      Store* input = s->currentStore();
+      Store* output = s->work();
+      bool res = (*this)(input, output, parms[0].toUShort());
+      if(res) {
+        input->hide();
+        output->show();
+      }
+      return res;
     }
-    return res;
-  }
-  bool operator()(const Store* input, Store* output, float colorGradDiv);
-
-  QString folder() const {
-    return "Filters";
-  }
-  QString name() const {
-    return "Color Gradient";
-  }
-  QString description() const {
-    return "Compute color gradient in Z direction";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Z Divisor";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Factor by which the gradient is divided by.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "5.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/ColorGrad.png");
-  }
-};
-
-/**
- * \class InvertStack StackProcessFilters.hpp <StackProcessFilters.hpp>
- *
- * Invert the intensity of all voxels in the stack.
- */
-class MGX_EXPORT InvertStack : public StackProcess {
-public:
-  InvertStack(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList&)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Stack* s = currentStack();
-    Store* input = s->currentStore();
-    Store* output = s->work();
-    bool res = (*this)(input, output);
-    if(res) {
-      input->hide();
-      output->show();
+    bool operator()(const Store* input, Store* output, ushort threshold);
+  
+    QString folder() const {
+      return "Filters";
     }
-    return res;
-  }
-  bool operator()(const Store* input, Store* output);
-
-  QString folder() const {
-    return "Filters";
-  }
-  QString name() const {
-    return "Invert";
-  }
-  QString description() const {
-    return "Invert the stack";
-  }
-  QStringList parmNames() const {
-    return QStringList();
-  }
-  QStringList parmDescs() const {
-    return QStringList();
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Invert.png");
-  }
-};
-
-/**
- * \class FilterStack StackProcessFilters.hpp <StackProcessFilters.hpp>
- *
- * Clip the intensity of the stack to the interval [Low Threshold, High Threshold].
- */
-class MGX_EXPORT FilterStack : public StackProcess {
-public:
-  FilterStack(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Stack* s = currentStack();
-    Store* input = s->currentStore();
-    Store* output = s->work();
-    bool res = (*this)(input, output, parms[0].toUInt(), parms[1].toUInt());
-    if(res) {
-      input->hide();
-      output->show();
+    QString name() const {
+      return "Binarize";
     }
-    return res;
-  }
-  bool operator()(const Store* input, Store* output, uint lowFilter, uint highFilter);
-
-  QString folder() const {
-    return "Filters";
-  }
-  QString name() const {
-    return "Trim high/low values";
-  }
-  QString description() const
-  {
-    return "Clip the voxel intensities to the interval [Low Threshold, High Threshold].";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Low Threshold"
-                         << "High Threshold";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Lower bound"
-                         << "Upper bound";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "1000"
-                         << "0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Filter.png");
-  }
-};
-
-/**
- * \class GaussianBlurStack StackProcessFilters.hpp <StackProcessFilters.hpp>
- *
- * Blur the stack using a Gaussian kernel or specified radius.
- *
- * The radius given correspond to the standard deviation of the Gaussian
- * kernel along the various axes. The kernel itself will be 3 time as big.
- */
-class MGX_EXPORT GaussianBlurStack : public StackProcess {
-public:
-  GaussianBlurStack(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Stack* s = currentStack();
-    Store* input = s->currentStore();
-    Store* output = s->work();
-    Point3f sigma(parms[0].toFloat(), parms[1].toFloat(), parms[2].toFloat());
-    bool res = (*this)(input, output, sigma);
-    if(res) {
-      input->hide();
-      output->show();
+    QString description() const
+    {
+      return "Transform the stack to binary (65535 or 0).\n"
+             "All voxels with an intensity greater than the threshold to 65535, while to others are set to 0.";
     }
-    return res;
-  }
-  bool operator()(const Store* input, Store* output, Point3f sigma);
-
-  QString folder() const {
-    return "Filters";
-  }
-  QString name() const {
-    return "Gaussian Blur Stack";
-  }
-  QString description() const {
-    return "Blur the stack, radius = 3 x Sigma";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << QString("X Sigma (%1)").arg(UM) << QString("Y Sigma (%1)").arg(UM)
-                         << QString("Z Sigma (%1)").arg(UM);
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << QString("X Sigma (%1)").arg(UM) << QString("Y Sigma (%1)").arg(UM)
-                         << QString("Z Sigma (%1)").arg(UM);
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "0.3"
-                         << "0.3"
-                         << "0.3";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Blur.png");
-  }
-};
-
-/**
- * \class SharpenStack StackProcessFilters.hpp <StackProcessFilters.hpp>
- *
- * Apply an "unsharp" filter to the stack.
- *
- * The unsharp filter consists in subtracting from the image the blured
- * version of itself. The parameters of the filter correspond to the blurring
- * and a multiplicating factor for the blured image.
- */
-class MGX_EXPORT SharpenStack : public StackProcess {
-public:
-  SharpenStack(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Stack* s = currentStack();
-    Store* input = s->currentStore();
-    Store* output = s->work();
-    Point3f sigma(parms[0].toFloat(), parms[1].toFloat(), parms[2].toFloat());
-    bool res = (*this)(input, output, sigma, parms[3].toFloat());
-    if(res) {
-      input->hide();
-      output->show();
+    QStringList parmNames() const {
+      return QStringList() << "Threshold";
     }
-    return res;
-  }
-  bool operator()(const Store* input, Store* output, const Point3f sigma, const float amount);
-
-  QString folder() const {
-    return "Filters";
-  }
-  QString name() const {
-    return "Sharpen Stack";
-  }
-  QString description() const {
-    return "Sharpen the stack, radius = 3 x Sigma";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << QString("X Sigma (%1)").arg(UM) << QString("Y Sigma (%1)").arg(UM)
-                         << QString("Z Sigma (%1)").arg(UM) << "Amount";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << QString("X Sigma (%1)").arg(UM) << QString("Y Sigma (%1)").arg(UM)
-                         << QString("Z Sigma (%1)").arg(UM) << "Amount";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "0.2"
-                         << "0.2"
-                         << "1.0"
-                         << "1.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Sharpen.png");
-  }
-};
-
-/**
- * \class ApplyKernelStack StackProcessFilters.hpp <StackProcessFilters.hpp>
- *
- * Apply a user-defined convolution kernel to the current image.
- *
- * The kernel must be separable, so only 1D kernels for the X, Y and Z axes
- * are specified.
- */
-class MGX_EXPORT ApplyKernelStack : public StackProcess {
-public:
-  ApplyKernelStack(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Stack* s = currentStack();
-    Store* input = s->currentStore();
-    Store* output = s->work();
-    HVecF kernels[3];
-    bool ok;
-    QString fields[3] = { "x", "y", "z" };
-    for(int i = 0; i < 3; i++) {
-      QString str = QString(parms[i]).trimmed();
-      QStringList field_values = str.split(" ", QString::SkipEmptyParts);
-      kernels[i].resize(field_values.size());
-      for(size_t j = 0; j < (size_t)field_values.size(); ++j) {
-        kernels[i][j] = field_values[j].toFloat(&ok);
-        if(not ok)
-          return setErrorMessage(
-            QString("Value %1 of field %2 if not a valid number.").arg(j).arg(fields[i]));
+    QStringList parmDescs() const {
+      return QStringList() << "Voxels above this threshold will be assigned 1.";
+    }
+    QStringList parmDefaults() const {
+      return QStringList() << "5000";
+    }
+    QIcon icon() const {
+      return QIcon(":/images/Brightness.png");
+    }
+  };
+  
+  /**
+   * \class ColorGradient StackProcessFilters.hpp <StackProcessFilters.hpp>
+   *
+   * Compute the gradient of the image in the Z axis of the image.
+   */
+  class MGX_EXPORT ColorGradient : public StackProcess {
+  public:
+    ColorGradient(const StackProcess& process)
+      : Process(process)
+      , StackProcess(process)
+    {
+    }
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Stack* s = currentStack();
+      Store* input = s->currentStore();
+      Store* output = s->work();
+      bool res = (*this)(input, output, parms[0].toFloat());
+      if(res) {
+        input->hide();
+        output->show();
       }
+      return res;
     }
-
-    bool res = (*this)(input, output, kernels[0], kernels[1], kernels[2]);
-    if(res) {
-      input->hide();
-      output->show();
+    bool operator()(const Store* input, Store* output, float colorGradDiv);
+  
+    QString folder() const {
+      return "Filters";
     }
-    return res;
-  }
-  bool operator()(const Store* input, Store* output, const HVecF& kernelX, const HVecF& kernelY,
-                  const HVecF& kernelZ);
-
-  QString folder() const {
-    return "Filters";
-  }
-  QString name() const {
-    return "Apply Separable Kernel";
-  }
-  QString description() const {
-    return "Kernel must have odd number of values";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "X Kernel"
-                         << "Y Kernel"
-                         << "Z Kernel";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "X Kernel"
-                         << "Y Kernel"
-                         << "Z Kernel";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "-.1 1.2 -.1"
-                         << "-.1 1.2 -.1"
-                         << "-.1 1.2 -.1";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Kernel.png");
-  }
-};
-
-/**
- * \class NormalizeStack StackProcessFilters.hpp <StackProcessFilters.hpp>
- *
- * Normalize the intensity of the stack.
- *
- * This process first dilates, then blur the image to obtain a local maximum
- * voxel intensity. The value of the current voxel is then divided by this
- * local maximum.
- */
-class MGX_EXPORT NormalizeStack : public StackProcess {
-public:
-  NormalizeStack(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Stack* s = currentStack();
-    Store* input = s->currentStore();
-    Store* output = s->work();
-    Point3f radius(parms[0].toFloat(), parms[1].toFloat(), parms[2].toFloat());
-    Point3f sigma(parms[3].toFloat(), parms[4].toFloat(), parms[5].toFloat());
-    bool res = (*this)(input, output, radius, sigma, parms[6].toUInt(), parms[7].toFloat());
-    if(res) {
-      input->hide();
-      output->show();
+    QString name() const {
+      return "Color Gradient";
     }
-    return res;
-  }
-  bool operator()(const Store* input, Store* output, Point3f radius, Point3f sigma, uint threshold, float blurFactor);
-
-  QString folder() const {
-    return "Filters";
-  }
-  QString name() const {
-    return "Normalize Stack";
-  }
-  QString description() const {
-    return "Normalize the stack";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << QString("X Radius (%1)").arg(UM) << QString("Y Radius (%1)").arg(UM)
-                         << QString("Z Radius (%1)").arg(UM) << QString("X Sigma (%1)").arg(UM)
-                         << QString("Y Sigma (%1)").arg(UM) << QString("Z Sigma (%1)").arg(UM) << "Threshold"
-                         << "Blur factor";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << QString("X Radius (%1) for the locality of normalization").arg(UM)
-                         << QString("Y Radius (%1) for the locality of normalization").arg(UM)
-                         << QString("Z Radius (%1) for the locality of normalization").arg(UM)
-                         << QString("X Sigma (%1) for pre-blur").arg(UM)
-                         << QString("Y Sigma (%1) for pre-blur").arg(UM)
-                         << QString("Z Sigma (%1) for pre-blur").arg(UM)
-                         << "Threshold under which pixels are cleared considered as background"
-                         << "Relative contribution of blurred vs unblurred dilation";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "5.0"
-                         << "5.0"
-                         << "5.0"
-                         << "0.5"
-                         << "0.5"
-                         << "0.5"
-                         << "10000"
-                         << "0.7";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Normalize.png");
-  }
-};
-
-/**
- * \class CImgGaussianBlurStack StackProcessFilters.hpp <StackProcessFilters.hpp>
- *
- * CImg implementation of the gaussian blur
- */
-class MGX_EXPORT CImgGaussianBlurStack : public StackProcess {
-public:
-  CImgGaussianBlurStack(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Stack* s = currentStack();
-    Store* input = s->currentStore();
-    Store* output = s->work();
-    bool res = (*this)(input, output, parms[0].toUInt());
-    if(res) {
-      input->hide();
-      output->show();
+    QString description() const {
+      return "Compute color gradient in Z direction";
     }
-    return res;
-  }
-
-  bool operator()(const Store* input, Store* output, uint radius);
-
-  QString folder() const {
-    return "CImage";
-  }
-  QString name() const {
-    return "Cimg Gaussian Blur";
-  }
-  QString description() const {
-    return "Cimg Gaussian Blur";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Radius";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Radius";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "5";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Blur.png");
-  }
-};
-
-/**
- * \class CImgLaplaceStack StackProcessFilters.hpp <StackProcessFilters.hpp>
- *
- * Compute the Laplacian of the stack (using CImg).
- */
-class MGX_EXPORT CImgLaplaceStack : public StackProcess {
-public:
-  CImgLaplaceStack(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList&)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Stack* s = currentStack();
-    Store* input = s->currentStore();
-    Store* output = s->work();
-    bool res = (*this)(input, output);
-    if(res) {
-      input->hide();
-      output->show();
+    QStringList parmNames() const {
+      return QStringList() << "Z Divisor";
     }
-    return res;
-  }
-  bool operator()(const Store* input, Store* output);
-
-  QString folder() const {
-    return "CImage";
-  }
-  QString name() const {
-    return "CImg Laplace Transform";
-  }
-  QString description() const {
-    return "CImg Laplace transform of stack";
-  }
-  QStringList parmNames() const {
-    return QStringList();
-  }
-  QStringList parmDescs() const {
-    return QStringList();
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Laplace.png");
-  }
-};
-///@}
+    QStringList parmDescs() const {
+      return QStringList() << "Factor by which the gradient is divided by.";
+    }
+    QStringList parmDefaults() const {
+      return QStringList() << "5.0";
+    }
+    QIcon icon() const {
+      return QIcon(":/images/ColorGrad.png");
+    }
+  };
+  
+  /**
+   * \class InvertStack StackProcessFilters.hpp <StackProcessFilters.hpp>
+   *
+   * Invert the intensity of all voxels in the stack.
+   */
+  class MGX_EXPORT InvertStack : public StackProcess {
+  public:
+    InvertStack(const StackProcess& process)
+      : Process(process)
+      , StackProcess(process)
+    {
+    }
+  
+    bool operator()(const QStringList&)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Stack* s = currentStack();
+      Store* input = s->currentStore();
+      Store* output = s->work();
+      bool res = (*this)(input, output);
+      if(res) {
+        input->hide();
+        output->show();
+      }
+      return res;
+    }
+    bool operator()(const Store* input, Store* output);
+  
+    QString folder() const {
+      return "Filters";
+    }
+    QString name() const {
+      return "Invert";
+    }
+    QString description() const {
+      return "Invert the stack";
+    }
+    QStringList parmNames() const {
+      return QStringList();
+    }
+    QStringList parmDescs() const {
+      return QStringList();
+    }
+    QIcon icon() const {
+      return QIcon(":/images/Invert.png");
+    }
+  };
+  
+  /**
+   * \class FilterStack StackProcessFilters.hpp <StackProcessFilters.hpp>
+   *
+   * Clip the intensity of the stack to the interval [Low Threshold, High Threshold].
+   */
+  class MGX_EXPORT FilterStack : public StackProcess {
+  public:
+    FilterStack(const StackProcess& process)
+      : Process(process)
+      , StackProcess(process)
+    {
+    }
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Stack* s = currentStack();
+      Store* input = s->currentStore();
+      Store* output = s->work();
+      bool res = (*this)(input, output, parms[0].toUInt(), parms[1].toUInt());
+      if(res) {
+        input->hide();
+        output->show();
+      }
+      return res;
+    }
+    bool operator()(const Store* input, Store* output, uint lowFilter, uint highFilter);
+  
+    QString folder() const {
+      return "Filters";
+    }
+    QString name() const {
+      return "Trim high/low values";
+    }
+    QString description() const
+    {
+      return "Clip the voxel intensities to the interval [Low Threshold, High Threshold].";
+    }
+    QStringList parmNames() const
+    {
+      return QStringList() << "Low Threshold"
+                           << "High Threshold";
+    }
+    QStringList parmDescs() const
+    {
+      return QStringList() << "Lower bound"
+                           << "Upper bound";
+    }
+    QStringList parmDefaults() const
+    {
+      return QStringList() << "1000"
+                           << "0";
+    }
+    QIcon icon() const {
+      return QIcon(":/images/Filter.png");
+    }
+  };
+  
+  /**
+   * \class GaussianBlurStack StackProcessFilters.hpp <StackProcessFilters.hpp>
+   *
+   * Blur the stack using a Gaussian kernel or specified radius.
+   *
+   * The radius given correspond to the standard deviation of the Gaussian
+   * kernel along the various axes. The kernel itself will be 3 time as big.
+   */
+  class MGX_EXPORT GaussianBlurStack : public StackProcess {
+  public:
+    GaussianBlurStack(const StackProcess& process)
+      : Process(process)
+      , StackProcess(process)
+    {
+    }
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Stack* s = currentStack();
+      Store* input = s->currentStore();
+      Store* output = s->work();
+      Point3f sigma(parms[0].toFloat(), parms[1].toFloat(), parms[2].toFloat());
+      bool res = (*this)(input, output, sigma);
+      if(res) {
+        input->hide();
+        output->show();
+      }
+      return res;
+    }
+    bool operator()(const Store* input, Store* output, Point3f sigma);
+  
+    QString folder() const {
+      return "Filters";
+    }
+    QString name() const {
+      return "Gaussian Blur Stack";
+    }
+    QString description() const {
+      return "Blur the stack, radius = 3 x Sigma";
+    }
+    QStringList parmNames() const
+    {
+      return QStringList() << QString("X Sigma (%1)").arg(UM) << QString("Y Sigma (%1)").arg(UM)
+                           << QString("Z Sigma (%1)").arg(UM);
+    }
+    QStringList parmDescs() const
+    {
+      return QStringList() << QString("X Sigma (%1)").arg(UM) << QString("Y Sigma (%1)").arg(UM)
+                           << QString("Z Sigma (%1)").arg(UM);
+    }
+    QStringList parmDefaults() const
+    {
+      return QStringList() << "0.3"
+                           << "0.3"
+                           << "0.3";
+    }
+    QIcon icon() const {
+      return QIcon(":/images/Blur.png");
+    }
+  };
+  
+  /**
+   * \class SharpenStack StackProcessFilters.hpp <StackProcessFilters.hpp>
+   *
+   * Apply an "unsharp" filter to the stack.
+   *
+   * The unsharp filter consists in subtracting from the image the blured
+   * version of itself. The parameters of the filter correspond to the blurring
+   * and a multiplicating factor for the blured image.
+   */
+  class MGX_EXPORT SharpenStack : public StackProcess {
+  public:
+    SharpenStack(const StackProcess& process)
+      : Process(process)
+      , StackProcess(process)
+    {
+    }
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Stack* s = currentStack();
+      Store* input = s->currentStore();
+      Store* output = s->work();
+      Point3f sigma(parms[0].toFloat(), parms[1].toFloat(), parms[2].toFloat());
+      bool res = (*this)(input, output, sigma, parms[3].toFloat());
+      if(res) {
+        input->hide();
+        output->show();
+      }
+      return res;
+    }
+    bool operator()(const Store* input, Store* output, const Point3f sigma, const float amount);
+  
+    QString folder() const {
+      return "Filters";
+    }
+    QString name() const {
+      return "Sharpen Stack";
+    }
+    QString description() const {
+      return "Sharpen the stack, radius = 3 x Sigma";
+    }
+    QStringList parmNames() const
+    {
+      return QStringList() << QString("X Sigma (%1)").arg(UM) << QString("Y Sigma (%1)").arg(UM)
+                           << QString("Z Sigma (%1)").arg(UM) << "Amount";
+    }
+    QStringList parmDescs() const
+    {
+      return QStringList() << QString("X Sigma (%1)").arg(UM) << QString("Y Sigma (%1)").arg(UM)
+                           << QString("Z Sigma (%1)").arg(UM) << "Amount";
+    }
+    QStringList parmDefaults() const
+    {
+      return QStringList() << "0.2"
+                           << "0.2"
+                           << "1.0"
+                           << "1.0";
+    }
+    QIcon icon() const {
+      return QIcon(":/images/Sharpen.png");
+    }
+  };
+  
+  /**
+   * \class ApplyKernelStack StackProcessFilters.hpp <StackProcessFilters.hpp>
+   *
+   * Apply a user-defined convolution kernel to the current image.
+   *
+   * The kernel must be separable, so only 1D kernels for the X, Y and Z axes
+   * are specified.
+   */
+  class MGX_EXPORT ApplyKernelStack : public StackProcess {
+  public:
+    ApplyKernelStack(const StackProcess& process)
+      : Process(process)
+      , StackProcess(process)
+    {
+    }
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Stack* s = currentStack();
+      Store* input = s->currentStore();
+      Store* output = s->work();
+      HVecF kernels[3];
+      bool ok;
+      QString fields[3] = { "x", "y", "z" };
+      for(int i = 0; i < 3; i++) {
+        QString str = QString(parms[i]).trimmed();
+        QStringList field_values = str.split(" ", QString::SkipEmptyParts);
+        kernels[i].resize(field_values.size());
+        for(size_t j = 0; j < (size_t)field_values.size(); ++j) {
+          kernels[i][j] = field_values[j].toFloat(&ok);
+          if(not ok)
+            return setErrorMessage(
+              QString("Value %1 of field %2 if not a valid number.").arg(j).arg(fields[i]));
+        }
+      }
+  
+      bool res = (*this)(input, output, kernels[0], kernels[1], kernels[2]);
+      if(res) {
+        input->hide();
+        output->show();
+      }
+      return res;
+    }
+    bool operator()(const Store* input, Store* output, const HVecF& kernelX, const HVecF& kernelY,
+                    const HVecF& kernelZ);
+  
+    QString folder() const {
+      return "Filters";
+    }
+    QString name() const {
+      return "Apply Separable Kernel";
+    }
+    QString description() const {
+      return "Kernel must have odd number of values";
+    }
+    QStringList parmNames() const
+    {
+      return QStringList() << "X Kernel"
+                           << "Y Kernel"
+                           << "Z Kernel";
+    }
+    QStringList parmDescs() const
+    {
+      return QStringList() << "X Kernel"
+                           << "Y Kernel"
+                           << "Z Kernel";
+    }
+    QStringList parmDefaults() const
+    {
+      return QStringList() << "-.1 1.2 -.1"
+                           << "-.1 1.2 -.1"
+                           << "-.1 1.2 -.1";
+    }
+    QIcon icon() const {
+      return QIcon(":/images/Kernel.png");
+    }
+  };
+  
+  /**
+   * \class NormalizeStack StackProcessFilters.hpp <StackProcessFilters.hpp>
+   *
+   * Normalize the intensity of the stack.
+   *
+   * This process first dilates, then blur the image to obtain a local maximum
+   * voxel intensity. The value of the current voxel is then divided by this
+   * local maximum.
+   */
+  class MGX_EXPORT NormalizeStack : public StackProcess {
+  public:
+    NormalizeStack(const StackProcess& process)
+      : Process(process)
+      , StackProcess(process)
+    {
+    }
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Stack* s = currentStack();
+      Store* input = s->currentStore();
+      Store* output = s->work();
+      Point3f radius(parms[0].toFloat(), parms[1].toFloat(), parms[2].toFloat());
+      Point3f sigma(parms[3].toFloat(), parms[4].toFloat(), parms[5].toFloat());
+      bool res = (*this)(input, output, radius, sigma, parms[6].toUInt(), parms[7].toFloat());
+      if(res) {
+        input->hide();
+        output->show();
+      }
+      return res;
+    }
+    bool operator()(const Store* input, Store* output, Point3f radius, Point3f sigma, uint threshold, float blurFactor);
+  
+    QString folder() const {
+      return "Filters";
+    }
+    QString name() const {
+      return "Normalize Stack";
+    }
+    QString description() const {
+      return "Normalize the stack";
+    }
+    QStringList parmNames() const
+    {
+      return QStringList() << QString("X Radius (%1)").arg(UM) << QString("Y Radius (%1)").arg(UM)
+                           << QString("Z Radius (%1)").arg(UM) << QString("X Sigma (%1)").arg(UM)
+                           << QString("Y Sigma (%1)").arg(UM) << QString("Z Sigma (%1)").arg(UM) << "Threshold"
+                           << "Blur factor";
+    }
+    QStringList parmDescs() const
+    {
+      return QStringList() << QString("X Radius (%1) for the locality of normalization").arg(UM)
+                           << QString("Y Radius (%1) for the locality of normalization").arg(UM)
+                           << QString("Z Radius (%1) for the locality of normalization").arg(UM)
+                           << QString("X Sigma (%1) for pre-blur").arg(UM)
+                           << QString("Y Sigma (%1) for pre-blur").arg(UM)
+                           << QString("Z Sigma (%1) for pre-blur").arg(UM)
+                           << "Threshold under which pixels are cleared considered as background"
+                           << "Relative contribution of blurred vs unblurred dilation";
+    }
+    QStringList parmDefaults() const
+    {
+      return QStringList() << "5.0"
+                           << "5.0"
+                           << "5.0"
+                           << "0.5"
+                           << "0.5"
+                           << "0.5"
+                           << "10000"
+                           << "0.7";
+    }
+    QIcon icon() const {
+      return QIcon(":/images/Normalize.png");
+    }
+  };
+  
+  /**
+   * \class CImgGaussianBlurStack StackProcessFilters.hpp <StackProcessFilters.hpp>
+   *
+   * CImg implementation of the gaussian blur
+   */
+  class MGX_EXPORT CImgGaussianBlurStack : public StackProcess {
+  public:
+    CImgGaussianBlurStack(const StackProcess& process)
+      : Process(process)
+      , StackProcess(process)
+    {
+    }
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Stack* s = currentStack();
+      Store* input = s->currentStore();
+      Store* output = s->work();
+      bool res = (*this)(input, output, parms[0].toUInt());
+      if(res) {
+        input->hide();
+        output->show();
+      }
+      return res;
+    }
+  
+    bool operator()(const Store* input, Store* output, uint radius);
+  
+    QString folder() const {
+      return "CImage";
+    }
+    QString name() const {
+      return "Cimg Gaussian Blur";
+    }
+    QString description() const {
+      return "Cimg Gaussian Blur";
+    }
+    QStringList parmNames() const {
+      return QStringList() << "Radius";
+    }
+    QStringList parmDescs() const {
+      return QStringList() << "Radius";
+    }
+    QStringList parmDefaults() const {
+      return QStringList() << "5";
+    }
+    QIcon icon() const {
+      return QIcon(":/images/Blur.png");
+    }
+  };
+  
+  /**
+   * \class CImgLaplaceStack StackProcessFilters.hpp <StackProcessFilters.hpp>
+   *
+   * Compute the Laplacian of the stack (using CImg).
+   */
+  class MGX_EXPORT CImgLaplaceStack : public StackProcess {
+  public:
+    CImgLaplaceStack(const StackProcess& process)
+      : Process(process)
+      , StackProcess(process)
+    {
+    }
+  
+    bool operator()(const QStringList&)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Stack* s = currentStack();
+      Store* input = s->currentStore();
+      Store* output = s->work();
+      bool res = (*this)(input, output);
+      if(res) {
+        input->hide();
+        output->show();
+      }
+      return res;
+    }
+    bool operator()(const Store* input, Store* output);
+  
+    QString folder() const {
+      return "CImage";
+    }
+    QString name() const {
+      return "CImg Laplace Transform";
+    }
+    QString description() const {
+      return "CImg Laplace transform of stack";
+    }
+    QStringList parmNames() const {
+      return QStringList();
+    }
+    QStringList parmDescs() const {
+      return QStringList();
+    }
+    QIcon icon() const {
+      return QIcon(":/images/Laplace.png");
+    }
+  };
+  ///@}
 } // namespace process
 } // namespace mgx
 
Index: SystemProcessSave.hpp
===================================================================
--- SystemProcessSave.hpp	(revision 1255)
+++ SystemProcessSave.hpp	(revision 1256)
@@ -15,871 +15,551 @@
 class QDialog;
 class Ui_SaveMeshDialog;
 class Ui_ExportMeshDialog;
-class Ui_SaveAllDlg;
 class Ui_ExportStackDialog;
 
-namespace mgx {
-namespace process {
-
-/**
- * \class StackSave SystemProcessSave.hpp <SystemProcessSave.hpp>
- *
- * Save the data into a MGXS or INRIA format.
- *
- * Description of the MGXS file format
- * ===================================
- *
- * MGXS is a binary file format to store 3D images with all the metadata needed for proper rendering in MorphoGraphX.
- *
- * There are many versions, from 1.0 to 1.3. This version of MorphoGraphX will always generate MGXS files version 1.3.
- *
- * Each MGXS file starts with the ASCII string `MGXS` followed by a space, the version number in ASCII and another
- * space. For instance, for the current version, the file starts with the ASCII string `"MGXS 1.3 "`.
- *
- * A binary header follows the version number. New versions simply added fields to the header. The header is made of:
- *
- *   Field | Size (bytes) | type  | Version | Description
- * --------|--------------|-------|---------|-------------------------------------------------------------
- * isLabel |     1        | bool  |  1.1    | True if the stack's values are labels and not intensities
- * sxum    |     4        | float |  1.3    | Position of the stack's origin on the X axis, in micrometers
- * syum    |     4        | float |  1.3    | Position of the stack's origin on the Y axis, in micrometers
- * szum    |     4        | float |  1.3    | Position of the stack's origin on the Z axis, in micrometers
- * xsz     |     4        | uint  |  1.0    | Number of voxels along the X axis
- * ysz     |     4        | uint  |  1.0    | Number of voxels along the Y axis
- * zsz     |     4        | uint  |  1.0    | Number of voxels along the Z axis
- * xum     |     4        | float |  1.0    | Resolution along the X axis, in micrometers
- * yum     |     4        | float |  1.0    | Resolution along the Y axis, in micrometers
- * zum     |     4        | float |  1.0    | Resolution along the Z axis, in micrometers
- * datasz  |     8        | uint  |  1.0    | Size in bytes of the data. It should be `2*xsz*ysz*zsz`
- * cl      |     1        | uint  |  1.0    | Compression level
- *
- * If the compression level is 0, the header is then followed by the raw, uncompressed, data. Voxels are ordered
- * C-style (e.g. vertices consecutives along the X axis are consecutive in the file, vertices consecutives along the
- * Y axis are separated by `xsz` voxels in the file, and vertices consecutive in the Z axis are separated by `xsz*ysz`
- * voxels in the files).
- *
- * If the compression level is greater than 0, the stack is cut into slice. Each slice is compressed using the gzip
- * algorithm (using the `qCompress` Qt function). In the file, the size of the compressed slice is written as
- * a 4 bytes unsigned integer, followed by the compressed data. A pseudo code to read the compressed data is:
- *
- *     current_size = 0
- *     while current_size < datasz
- *         slice_size = read 4 bytes
- *         compressed_data = read slice_size bytes
- *         data = uncompress compressed_data
- *         store data
- *         current_size += size of data
- *
- * **Note** before version 1.3, if the stack was labeled, the label numbers were store as big endian. Starting 1.3,
- * they are stores as little endian. Stack intensities are always stored as little endian.
- *
- * \ingroup StackProcess
- */
-class MGX_EXPORT StackSave : public StackProcess {
-public:
-  StackSave(const StackProcess& proc)
-    : Process(proc)
-    , StackProcess(proc)
-  {
-  }
-
-  bool initialize(QStringList& parms, QWidget* parent);
-
-  bool operator()(const QStringList& parms);
+namespace mgx { namespace process {
+  
   /**
-   * Save the stack
-   * \param stack Stack containing the data
-   * \param store Store containing the data
-   * \param filename File in which to save the data, the extension must be
-   * .mgxs or .inr
+   * \class StackSave SystemProcessSave.hpp <SystemProcessSave.hpp>
+   *
+   * Save the data into a MGXS or INRIA format.
+   *
+   * Description of the MGXS file format
+   * ===================================
+   *
+   * MGXS is a binary file format to store 3D images with all the metadata needed for proper rendering in MorphoGraphX.
+   *
+   * There are many versions, from 1.0 to 1.3. This version of MorphoGraphX will always generate MGXS files version 1.3.
+   *
+   * Each MGXS file starts with the ASCII string `MGXS` followed by a space, the version number in ASCII and another
+   * space. For instance, for the current version, the file starts with the ASCII string `"MGXS 1.3 "`.
+   *
+   * A binary header follows the version number. New versions simply added fields to the header. The header is made of:
+   *
+   *   Field | Size (bytes) | type  | Version | Description
+   * --------|--------------|-------|---------|-------------------------------------------------------------
+   * isLabel |     1        | bool  |  1.1    | True if the stack's values are labels and not intensities
+   * sxum    |     4        | float |  1.3    | Position of the stack's origin on the X axis, in micrometers
+   * syum    |     4        | float |  1.3    | Position of the stack's origin on the Y axis, in micrometers
+   * szum    |     4        | float |  1.3    | Position of the stack's origin on the Z axis, in micrometers
+   * xsz     |     4        | uint  |  1.0    | Number of voxels along the X axis
+   * ysz     |     4        | uint  |  1.0    | Number of voxels along the Y axis
+   * zsz     |     4        | uint  |  1.0    | Number of voxels along the Z axis
+   * xum     |     4        | float |  1.0    | Resolution along the X axis, in micrometers
+   * yum     |     4        | float |  1.0    | Resolution along the Y axis, in micrometers
+   * zum     |     4        | float |  1.0    | Resolution along the Z axis, in micrometers
+   * datasz  |     8        | uint  |  1.0    | Size in bytes of the data. It should be `2*xsz*ysz*zsz`
+   * cl      |     1        | uint  |  1.0    | Compression level
+   *
+   * If the compression level is 0, the header is then followed by the raw, uncompressed, data. Voxels are ordered
+   * C-style (e.g. vertices consecutives along the X axis are consecutive in the file, vertices consecutives along the
+   * Y axis are separated by `xsz` voxels in the file, and vertices consecutive in the Z axis are separated by `xsz*ysz`
+   * voxels in the files).
+   *
+   * If the compression level is greater than 0, the stack is cut into slice. Each slice is compressed using the gzip
+   * algorithm (using the `qCompress` Qt function). In the file, the size of the compressed slice is written as
+   * a 4 bytes unsigned integer, followed by the compressed data. A pseudo code to read the compressed data is:
+   *
+   *     current_size = 0
+   *     while current_size < datasz
+   *         slice_size = read 4 bytes
+   *         compressed_data = read slice_size bytes
+   *         data = uncompress compressed_data
+   *         store data
+   *         current_size += size of data
+   *
+   * **Note** before version 1.3, if the stack was labeled, the label numbers were store as big endian. Starting 1.3,
+   * they are stores as little endian. Stack intensities are always stored as little endian.
+   *
+   * \ingroup StackProcess
    */
-  bool operator()(Stack* stack, Store* store, const QString& filename, int compressionLevel = 0);
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Save";
-  }
-  QString description() const {
-    return "Save a stack into a known 3D image format";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Filename"
-                         << "Store"
-                         << "Stack number"
-                         << "Compression Level (0-9)";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Filename"
-                         << "Store"
-                         << "Stack number"
-                         << "Compression Level (0-9)";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << ""
-                         << "Main"
-                         << "0"
-                         << "5";
-  }
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[1] = storeChoice();
-    return map;
-  }
-  QIcon icon() const {
-    return QIcon(":/images/save.png");
-  }
-};
-
-/**
- * \class StackExport SystemProcessSave.hpp <SystemProcessSave.hpp>
- *
- * Export the stack data into a stack of images.
- *
- * \ingroup StackProcess
- */
-class MGX_EXPORT StackExport : public QObject, public StackProcess {
-  Q_OBJECT
-public:
-  StackExport(const StackProcess& proc)
-    : Process(proc)
-    , QObject()
-    , StackProcess(proc)
-  {
-  }
-
-  bool initialize(QStringList& parms, QWidget* parent);
-
-  bool operator()(const QStringList& parms);
+  class MGX_EXPORT StackSave : public StackProcess {
+  public:
+    StackSave(const StackProcess& proc) : Process(proc), StackProcess(proc) {}
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    bool operator()(const QStringList& parms);
+    /**
+     * Save the stack
+     * \param stack Stack containing the data
+     * \param store Store containing the data
+     * \param filename File in which to save the data, the extension must be
+     * .mgxs or .inr
+     */
+    bool operator()(Stack* stack, Store* store, const QString& filename, int compressionLevel = 0);
+    QString folder() const { return "System"; }
+    QString name() const { return "Save"; }
+    QString description() const { return "Save a stack into a known 3D image format"; }
+    QStringList parmNames() const { return QStringList() 
+      << "Filename" << "Store" << "Stack number" << "Compression Level (0-9)"; }
+    QStringList parmDescs() const { return QStringList() 
+      << "Filename" << "Store" << "Stack number" << "Compression Level (0-9)"; }
+    QStringList parmDefaults() const { return QStringList() << "" << "Main" << "0" << "5"; }
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[1] = storeChoice();
+      return map;
+    }
+    QIcon icon() const { return QIcon(":/images/save.png"); }
+  };
+  
   /**
-   * Export the stack
-   * \param stack Stack containing the image
-   * \param store Store containing the image
-   * \param filename Prefix of the file to store the data in
-   * \param type Type of the file. Type must be one of 'DML', 'TIF', 'CIMG' or 'CImg Auto'. If 'CImg Auto', the
-   * actual type will be deduced by the file extension, and the CImg library will try to save it using its own data
-   * formats, Image Magick or Graphics Magick.
-   * \param nb_digit Number of digits to use to generate the file numbering. If 0, it will use an optimal number of
-   * digits.
-   * \param generate_voxel_spacing If true, the process also generate a voxelspacing.txt file for easy import into
-   * VolViewer.
+   * \class StackExport SystemProcessSave.hpp <SystemProcessSave.hpp>
+   *
+   * Export the stack data into a stack of images.
+   *
+   * \ingroup StackProcess
    */
-  bool operator()(Stack* stack, Store* store, const QString& filename, const QString& type,
-                  unsigned int nb_digit, bool generate_voxel_spacing);
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Export";
-  }
-  QString description() const {
-    return "Export a stack into an image sequence.";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Filename"
-                         << "Store"
-                         << "Format"
-                         << "Generate Voxel Spacing"
-                         << "Stack number"
-                         << "NbDigits";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Filename"
-                         << "Store"
-                         << "Format"
-                         << "Generate Voxel Spacing"
-                         << "Stack number"
-                         << "NbDigits";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << ""
-                         << "Main"
-                         << "CImg Auto"
-                         << "No"
-                         << "0"
-                         << "0";
-  }
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[1] = storeChoice();
-    map[3] = booleanChoice();
-    return map;
-  }
-  QIcon icon() const {
-    return QIcon(":/images/save.png");
-  }
-
-protected slots:
-  void selectImageFile();
-  void setImageType(const QString& type);
-
-protected:
-  Ui_ExportStackDialog* ui;
-  QDialog* dlg;
-};
-
-/**
- * \class MeshSave SystemProcessSave.hpp <SystemProcessSave.hpp>
- *
- * Save a mesh into a INRIA or MGXM file.
- *
- * Description of the MGXM file format
- * ===================================
- * MGXM is a binary file format to store triangular meshes with all the data and meta-data used by MorphoGraphX.
- *
- * There are a few versions, from 1.0 to 1.2. This version of MorphoGraphX will always generate MGXM files version
- * 1.2.
- *
- * Each MGXM file starts with the ASCII string `MGXM` followed by a space, the version number in ASCII and another
- * space. For instance, for the current version, the file starts with the ASCII string `"MGXM 1.2 "`.
- *
- * A binary header follows the version number. The header is made of:
- *
- *   Field       | Size (bytes) | type  | Version | Description
- * --------------|--------------|-------|---------|-------------------------------------------------------------
- *  is_cells     |      1       | bool  |  1.2    | If true, the mesh represent 2D cells (see notes)
- *  scale        |      1       | bool  |  1.1    | If true, the mesh has been scaled when saved
- *  transform    |      1       | bool  |  1.1    | If true, the mesh has been transformed rigidly
- *  signalLow    |      4       | float |  1.1    | Lower value of the signal
- *  signalHigh   |      4       | float |  1.1    | Upper value of the signal
- *  signalUnit   |      *       | utf8  |  1.1    | Text of the signal unit (see notes)
- *  header_size  |      4       | uint  |  1.0    | Specified the size in bytes of extra data placed after the header
- *  vertex_cnt   |      4       | uint  |  1.0    | Number of vertices in the mesh
- *  vertex_size  |      4       | uint  |  1.0    | Size in bytes of the structure describing a vertex, minus 12.
- *  edge_size    |      4       | uint  |  1.0    | Size in bytes of the structure describing an edge.
- *
- * The description of the vertices follows the header. For each vertex, a structure of size `vertex_size+12` is
- * written. Only fields fitting in the given size are actually written, and any other data is ignored. Note that the
- * first four field are always there!
- *
- *   Field       | Size (bytes) | type  |  Description
- * --------------|--------------|-------|----------------------------------------------------------------------
- *   Id          |      4       | uint  | Id of the vertex, used to reference it in other places in the file
- *   X           |      4       | float | X position of the vertex
- *   Y           |      4       | float | Y position of the vertex
- *   Z           |      4       | float | Z position of the vertex
- *   label       |      4       | uint  | Label of the vertex
- *   color       |      4       | float | "Color" of the vertex (e.g. like signal, but scaled from 0 to 1)
- *   signal      |      4       | float | Signal of the vertex
- *   type        |      1       | char  | type of vertex `'c'` for center and `'j'` for junction.
- *   selected    |      1       | bool  | If true, the vertex is selected
- *
- * Currently, the edges have no defined fields. For each vertex, the `Id` of the vertex is written, followed by a 32
- * bits unsigned integer for the number of neighbors, and the list of `Id` for each neighbor. Neighbors of a vertex
- * are always written counter-clockwise.
- *
- * Notes on UTF-8 strings
- * ----------------------
- *
- * UTF-8 strings are written as: their size in bytes as a 32 bits unsigned integer, followed by the bytes themselves.
- *
- * Notes on vertex labels
- * ----------------------
- *
- * Vertex are labels to mark which cells they are part of. Boundary vertices are labeled with -1 or -2. -1 mark
- * vertices between cells, and -2 vertices at the border of the whole mesh.
- *
- * Notes on cell mesh
- * ------------------
- *
- * If the mesh is a cell mesh, then each cell has a unique labeled vertex on its center, surrounded by cell-boundary
- * vertices, labels -1 or -2. In this case, labeled vertices have type `'c'` and boundary vertices `'j'`.
- *
- * \ingroup MeshProcess
- */
-class MGX_EXPORT MeshSave : public QObject, public MeshProcess {
-  Q_OBJECT
-public:
-  MeshSave(const MeshProcess& proc)
-    : Process(proc)
-    , QObject()
-    , MeshProcess(proc)
-  {
-  }
-
-  bool operator()(const QStringList& parms);
+  class MGX_EXPORT StackExport : public QObject, public StackProcess {
+    Q_OBJECT
+  public:
+    StackExport(const StackProcess& proc) : Process(proc), QObject(), StackProcess(proc) {}
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    bool operator()(const QStringList& parms);
+    /**
+     * Export the stack
+     * \param stack Stack containing the image
+     * \param store Store containing the image
+     * \param filename Prefix of the file to store the data in
+     * \param type Type of the file. Type must be one of 'DML', 'TIF', 'CIMG' or 'CImg Auto'. If 'CImg Auto', the
+     * actual type will be deduced by the file extension, and the CImg library will try to save it using its own data
+     * formats, Image Magick or Graphics Magick.
+     * \param nb_digit Number of digits to use to generate the file numbering. If 0, it will use an optimal number of
+     * digits.
+     * \param generate_voxel_spacing If true, the process also generate a voxelspacing.txt file for easy import into
+     * VolViewer.
+     */
+    bool operator()(Stack* stack, Store* store, const QString& filename, const QString& type,
+                    unsigned int nb_digit, bool generate_voxel_spacing);
+    QString folder() const { return "System"; }
+    QString name() const { return "Export"; }
+    QString description() const { return "Export a stack into an image sequence."; }
+    QStringList parmNames() const { return QStringList() 
+      << "Filename" << "Store" << "Format" << "Generate Voxel Spacing" << "Stack number" << "NbDigits"; }
+    QStringList parmDescs() const { return QStringList() 
+      << "Filename" << "Store" << "Format" << "Generate Voxel Spacing" << "Stack number" << "NbDigits"; }
+    QStringList parmDefaults() const { return QStringList() 
+      << "" << "Main" << "CImg Auto" << "No" << "0" << "0"; }
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[1] = storeChoice();
+      map[3] = booleanChoice();
+      return map;
+    }
+    QIcon icon() const { return QIcon(":/images/save.png"); }
+  
+  protected slots:
+    void selectImageFile();
+    void setImageType(const QString& type);
+  
+  protected:
+    Ui_ExportStackDialog* ui;
+    QDialog* dlg;
+  };
+  
   /**
-   * Save a mesh
-   * \param mesh Mesh to be saved
-   * \param filename File to save the mesh in. Its extension must be either .inr or .mgmx
-   * \[aram transform Save the transformed positions
+   * \class MeshSave SystemProcessSave.hpp <SystemProcessSave.hpp>
+   *
+   * Save a mesh into a INRIA or MGXM file.
+   *
+   * Description of the MGXM file format
+   * ===================================
+   * MGXM is a binary file format to store triangular meshes with all the data and meta-data used by MorphoGraphX.
+   *
+   * There are a few versions, from 1.0 to 1.2. This version of MorphoGraphX will always generate MGXM files version
+   * 1.2.
+   *
+   * Each MGXM file starts with the ASCII string `MGXM` followed by a space, the version number in ASCII and another
+   * space. For instance, for the current version, the file starts with the ASCII string `"MGXM 1.2 "`.
+   *
+   * A binary header follows the version number. The header is made of:
+   *
+   *   Field       | Size (bytes) | type  | Version | Description
+   * --------------|--------------|-------|---------|-------------------------------------------------------------
+   *  is_cells     |      1       | bool  |  1.2    | If true, the mesh represent 2D cells (see notes)
+   *  scale        |      1       | bool  |  1.1    | If true, the mesh has been scaled when saved
+   *  transform    |      1       | bool  |  1.1    | If true, the mesh has been transformed rigidly
+   *  signalLow    |      4       | float |  1.1    | Lower value of the signal
+   *  signalHigh   |      4       | float |  1.1    | Upper value of the signal
+   *  signalUnit   |      *       | utf8  |  1.1    | Text of the signal unit (see notes)
+   *  header_size  |      4       | uint  |  1.0    | Specified the size in bytes of extra data placed after the header
+   *  vertex_cnt   |      4       | uint  |  1.0    | Number of vertices in the mesh
+   *  vertex_size  |      4       | uint  |  1.0    | Size in bytes of the structure describing a vertex, minus 12.
+   *  edge_size    |      4       | uint  |  1.0    | Size in bytes of the structure describing an edge.
+   *
+   * The description of the vertices follows the header. For each vertex, a structure of size `vertex_size+12` is
+   * written. Only fields fitting in the given size are actually written, and any other data is ignored. Note that the
+   * first four field are always there!
+   *
+   *   Field       | Size (bytes) | type  |  Description
+   * --------------|--------------|-------|----------------------------------------------------------------------
+   *   Id          |      4       | uint  | Id of the vertex, used to reference it in other places in the file
+   *   X           |      4       | float | X position of the vertex
+   *   Y           |      4       | float | Y position of the vertex
+   *   Z           |      4       | float | Z position of the vertex
+   *   label       |      4       | uint  | Label of the vertex
+   *   color       |      4       | float | "Color" of the vertex (e.g. like signal, but scaled from 0 to 1)
+   *   signal      |      4       | float | Signal of the vertex
+   *   type        |      1       | char  | type of vertex `'c'` for center and `'j'` for junction.
+   *   selected    |      1       | bool  | If true, the vertex is selected
+   *
+   * Currently, the edges have no defined fields. For each vertex, the `Id` of the vertex is written, followed by a 32
+   * bits unsigned integer for the number of neighbors, and the list of `Id` for each neighbor. Neighbors of a vertex
+   * are always written counter-clockwise.
+   *
+   * Notes on UTF-8 strings
+   * ----------------------
+   *
+   * UTF-8 strings are written as: their size in bytes as a 32 bits unsigned integer, followed by the bytes themselves.
+   *
+   * Notes on vertex labels
+   * ----------------------
+   *
+   * Vertex are labels to mark which cells they are part of. Boundary vertices are labeled with -1 or -2. -1 mark
+   * vertices between cells, and -2 vertices at the border of the whole mesh.
+   *
+   * Notes on cell mesh
+   * ------------------
+   *
+   * If the mesh is a cell mesh, then each cell has a unique labeled vertex on its center, surrounded by cell-boundary
+   * vertices, labels -1 or -2. In this case, labeled vertices have type `'c'` and boundary vertices `'j'`.
+   *
+   * \ingroup MeshProcess
    */
-  bool operator()(Mesh* mesh, const QString& filename, bool transform);
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Save";
-  }
-  QString description() const {
-    return "Save a mesh into a known mesh format";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Filename"
-                         << "Transform"
-                         << "Mesh number";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Filename"
-                         << "Transform"
-                         << "Mesh number";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/save.png");
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << ""
-                         << "No"
-                         << "0";
-  }
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[1] = map[2] = booleanChoice();
-    return map;
-  }
-  bool initialize(QStringList& parms, QWidget* parent);
-
-protected slots:
-  void selectMeshFile();
-
-protected:
-  QString properFile(QString filename) const;
-  void setMeshFile(const QString& filename);
-  Point3f savedPos(Point3f pos, bool transform, const Stack* stack);
-
-  bool saveMesh(Mesh* mesh, const QString& filename, bool transform);
-
-  QDialog* dlg;
-  Ui_SaveMeshDialog* ui;
-};
-
-/**
- * \class MeshExport SystemProcessSave.hpp <SystemProcessSave.hpp>
- *
- * Export a mesh on various formats: \ref PLY, \ref VTK, \ref text, \ref cells, \ref MeshEdit, \ref STL or \ref OBJ.
- *
- * We will here describe the file formats, or at least how MorphoGraphX uses them.
- *
- * \section PLY PLY format
- *
- * The PLY format is fully described on the website of the Paul Bourke: http://paulbourke.net/dataformats/ply/
- *
- * It is also available on Wikipedia: https://en.wikipedia.org/wiki/PLY_(file_format)
- *
- * MorphoGraphX exports only the two kind of elements described as mandatory: vertex and face.
- *
- * In the case of a cell mesh, each vertex contains only its position (x,y,z). Otherwise, vertices also have their
- * label.
- *
- * In any case, each face contains the list of 0-based index into the vertex elements that form the face, and the
- * label marking which cell the face is a part of. Vertices are oriented counter-clockwise.
- *
- * \section VTK VTK format
- *
- * MorphoGraphX save VTU format, which are XML files for unstructure grids.
- *
- * The file format is quite complex, and fully described in the VTK book and website.
- *
- * MorphoGraphX stores the following properties in addition to the mandatory ones:
- *
- * For each vertex: 'Signal' (float32), 'Normals' (3 floats32), 'Color' (float32) and 'Label' (int32)
- *
- * For each "cell" (e.g. triangles or 2D cells): 'Label' (int32)
- *
- * MorphoGraphX also adds a DataArray to store the heat per VTU "cell". The name is either "Cell Heat" or "Wall Heat".
- *
- * At last, an extra DataArray is created, store the heat per label instead of per cell.
- *
- * \section text "text" format
- *
- * The text format is a trivial ASCII file format. The file contains:
- *
- *     n
- *     vertex 0
- *     vertex 1
- *     ...
- *     vertex n-1
- *     neighbors 0
- *     neighbors 1
- *     ...
- *     neighbors n-1
- *
- * Each vertex is described as:
- *
- *     id x y z label
- *
- * Each neighborhood is described as:
- *
- *     id m id_1 id_2 ... id_m
- *
- * Where `id` is the id of the current vertex, `m` the number of neighbors, and `id_1`, `id_2` are vertex ids as
- * described before. The vertex must be ordered counter-clockwise.
- *
- * \section cells "cells" format
- *
- * This format is very similar to the "text" format. Only each vertex is described as:
- *
- *     id x z y label type
- *
- * Where `type` is `j` for junctions and `c` for cell centers.
- *
- * \section MeshEdit MeshEdit format
- *
- * This file format is the one used by the MeshEdit software. In MorphoGraphX, the file has the following format
- *
- *     MeshVersionFormatted 1
- *     Dimension 3
- *     Vertices
- *     vertex 1
- *     vertex 2
- *     ...
- *     vertex n
- *     Triangles
- *     triangle 1
- *     triangle 2
- *     ...
- *     triangle m
- *     End
- *
- * Each vertex is described as:
- *
- *     x y z label
- *
- * And each triangle is described as:
- *
- *     v0 v1 v2 label
- *
- * Again, the vertices must be ordered counter-clockwise.
- *
- * \section STL STL format
- *
- * The STL file format is the one used in many CAD software, including Abaqus.
- *
- * In MorphoGraphX, the mesh is stored as a single solid called "mgx". The file structure is:
- *
- *     solid mgx
- *     facet 1
- *     facet 2
- *     ...
- *     facet n
- *     endsolid mgx
- *
- * Where each facet is described as:
- *
- *     facet normal nx ny nz
- *       outer loop
- *         vertex vx1 vy1 vz1
- *         vertex vx2 vy2 vz2
- *         vertex vx3 vy3 vz3
- *       endloop
- *     endfacet
- *
- * \section OBJ OBJ format
- *
- * MorphoGraphX can also export files in the WaveFront's OBJ file format.
- *
- * The file has the following structure:
- *
- *     # Triangular mesh created by MorphoGraphX
- *     # Length unit: µm
- *     # Vertices
- *     vertex 1
- *     vertex 2
- *     ...
- *     vertex n
- *     # Triangles
- *     triangle 1
- *     triangle 2
- *     ...
- *     triangle m
- *
- * Each vertex is stored as:
- *
- *     v x y z
- *     vn nx ny nz
- *
- * And each triangle as:
- *
- *     f v1 v2 v3
- *
- * where `v1`, `v2` and `v3` are 1-based index in the vertex array. Also, the vertices are oriented counter-clockwise.
- *
- * \ingroup MeshProcess
- */
-class MGX_EXPORT MeshExport : public QObject, public MeshProcess {
-  Q_OBJECT
-public:
-  MeshExport(const MeshProcess& proc)
-    : Process(proc)
-    , QObject()
-    , MeshProcess(proc)
-  {
-  }
-
-  bool operator()(const QStringList& parms);
+  class MGX_EXPORT MeshSave : public QObject, public MeshProcess {
+    Q_OBJECT
+  public:
+    MeshSave(const MeshProcess& proc) : Process(proc), QObject(), MeshProcess(proc) {}
+  
+    bool operator()(const QStringList& parms);
+    /**
+     * Save a mesh
+     * \param mesh Mesh to be saved
+     * \param filename File to save the mesh in. Its extension must be either .inr or .mgmx
+     * \[aram transform Save the transformed positions
+     */
+    bool operator()(Mesh* mesh, const QString& filename, bool transform);
+    QString folder() const { return "System"; }
+    QString name() const { return "Save"; }
+    QString description() const { return "Save a mesh into a known mesh format"; }
+    QStringList parmNames() const { return QStringList() << "Filename" << "Transform" << "Mesh number"; }
+    QStringList parmDescs() const { return QStringList() << "Filename" << "Transform" << "Mesh number"; }
+    QIcon icon() const { return QIcon(":/images/save.png"); }
+    QStringList parmDefaults() const { return QStringList() << "" << "No" << "0"; }
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[1] = map[2] = booleanChoice();
+      return map;
+    }
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+  protected slots:
+    void selectMeshFile();
+  
+  protected:
+    QString properFile(QString filename) const;
+    void setMeshFile(const QString& filename);
+    Point3f savedPos(Point3f pos, bool transform, const Stack* stack);
+  
+    bool saveMesh(Mesh* mesh, const QString& filename, bool transform);
+  
+    QDialog* dlg;
+    Ui_SaveMeshDialog* ui;
+  };
+  
   /**
-   * Export a mesh
-   * \param mesh Mesh to be exported
-   * \param filename File to save the mesh into
-   * \param type Type (format) of the export.
-   * \param transform Save the transformed positions
+   * \class MeshExport SystemProcessSave.hpp <SystemProcessSave.hpp>
+   *
+   * Export a mesh on various formats: \ref PLY, \ref VTK, \ref text, \ref cells, \ref MeshEdit, \ref STL or \ref OBJ.
+   *
+   * We will here describe the file formats, or at least how MorphoGraphX uses them.
+   *
+   * \section PLY PLY format
+   *
+   * The PLY format is fully described on the website of the Paul Bourke: http://paulbourke.net/dataformats/ply/
+   *
+   * It is also available on Wikipedia: https://en.wikipedia.org/wiki/PLY_(file_format)
+   *
+   * MorphoGraphX exports only the two kind of elements described as mandatory: vertex and face.
+   *
+   * In the case of a cell mesh, each vertex contains only its position (x,y,z). Otherwise, vertices also have their
+   * label.
+   *
+   * In any case, each face contains the list of 0-based index into the vertex elements that form the face, and the
+   * label marking which cell the face is a part of. Vertices are oriented counter-clockwise.
+   *
+   * \section VTK VTK format
+   *
+   * MorphoGraphX save VTU format, which are XML files for unstructure grids.
+   *
+   * The file format is quite complex, and fully described in the VTK book and website.
+   *
+   * MorphoGraphX stores the following properties in addition to the mandatory ones:
+   *
+   * For each vertex: 'Signal' (float32), 'Normals' (3 floats32), 'Color' (float32) and 'Label' (int32)
+   *
+   * For each "cell" (e.g. triangles or 2D cells): 'Label' (int32)
+   *
+   * MorphoGraphX also adds a DataArray to store the heat per VTU "cell". The name is either "Cell Heat" or "Wall Heat".
+   *
+   * At last, an extra DataArray is created, store the heat per label instead of per cell.
+   *
+   * \section text "text" format
+   *
+   * The text format is a trivial ASCII file format. The file contains:
+   *
+   *     n
+   *     vertex 0
+   *     vertex 1
+   *     ...
+   *     vertex n-1
+   *     neighbors 0
+   *     neighbors 1
+   *     ...
+   *     neighbors n-1
+   *
+   * Each vertex is described as:
+   *
+   *     id x y z label
+   *
+   * Each neighborhood is described as:
+   *
+   *     id m id_1 id_2 ... id_m
+   *
+   * Where `id` is the id of the current vertex, `m` the number of neighbors, and `id_1`, `id_2` are vertex ids as
+   * described before. The vertex must be ordered counter-clockwise.
+   *
+   * \section cells "cells" format
+   *
+   * This format is very similar to the "text" format. Only each vertex is described as:
+   *
+   *     id x z y label type
+   *
+   * Where `type` is `j` for junctions and `c` for cell centers.
+   *
+   * \section MeshEdit MeshEdit format
+   *
+   * This file format is the one used by the MeshEdit software. In MorphoGraphX, the file has the following format
+   *
+   *     MeshVersionFormatted 1
+   *     Dimension 3
+   *     Vertices
+   *     vertex 1
+   *     vertex 2
+   *     ...
+   *     vertex n
+   *     Triangles
+   *     triangle 1
+   *     triangle 2
+   *     ...
+   *     triangle m
+   *     End
+   *
+   * Each vertex is described as:
+   *
+   *     x y z label
+   *
+   * And each triangle is described as:
+   *
+   *     v0 v1 v2 label
+   *
+   * Again, the vertices must be ordered counter-clockwise.
+   *
+   * \section STL STL format
+   *
+   * The STL file format is the one used in many CAD software, including Abaqus.
+   *
+   * In MorphoGraphX, the mesh is stored as a single solid called "mgx". The file structure is:
+   *
+   *     solid mgx
+   *     facet 1
+   *     facet 2
+   *     ...
+   *     facet n
+   *     endsolid mgx
+   *
+   * Where each facet is described as:
+   *
+   *     facet normal nx ny nz
+   *       outer loop
+   *         vertex vx1 vy1 vz1
+   *         vertex vx2 vy2 vz2
+   *         vertex vx3 vy3 vz3
+   *       endloop
+   *     endfacet
+   *
+   * \section OBJ OBJ format
+   *
+   * MorphoGraphX can also export files in the WaveFront's OBJ file format.
+   *
+   * The file has the following structure:
+   *
+   *     # Triangular mesh created by MorphoGraphX
+   *     # Length unit: µm
+   *     # Vertices
+   *     vertex 1
+   *     vertex 2
+   *     ...
+   *     vertex n
+   *     # Triangles
+   *     triangle 1
+   *     triangle 2
+   *     ...
+   *     triangle m
+   *
+   * Each vertex is stored as:
+   *
+   *     v x y z
+   *     vn nx ny nz
+   *
+   * And each triangle as:
+   *
+   *     f v1 v2 v3
+   *
+   * where `v1`, `v2` and `v3` are 1-based index in the vertex array. Also, the vertices are oriented counter-clockwise.
+   *
+   * \ingroup MeshProcess
    */
-  bool operator()(Mesh* mesh, const QString& filename, const QString& type, bool transform);
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Export";
-  }
-  QString description() const {
-    return "Export a mesh into a known mesh format";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Filename"
-                         << "Kind"
-                         << "Transform"
-                         << "Mesh number";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Filename"
-                         << "Kind"
-                         << "Transform"
-                         << "Mesh number";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/save.png");
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << ""
-                         << "Text"
-                         << "no"
-                         << "0";
-  }
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[1] = QStringList() << "PLY Binary"
-                           << "PLY Ascii"
-                           << "VTK Mesh Binary"
-                           << "VTK Mesh Ascii"
-                           << "Text"
-                           << "Cells"
-                           << "MeshEdit"
-                           << "STL"
-                           << "OBJ";
-    map[2] = map[3] = booleanChoice();
-    return map;
-  }
-  bool initialize(QStringList& parms, QWidget* parent);
-
-protected slots:
-  void selectMeshFile();
-  void selectMeshType(const QString& type);
-
-protected:
-  QString properFile(QString filename, const QString& type) const;
-  void setMeshFile(const QString& filename);
-  Point3f savedPos(Point3f pos, bool transform, const Stack* stack);
-
-  bool saveText(Mesh* mesh, const QString& filename, bool transform);
-  bool saveCells(Mesh* mesh, const QString& filename, bool transform);
-  bool saveMeshEdit(Mesh* mesh, const QString& filename, bool transform);
-  bool saveMeshSTL(Mesh* mesh, const QString& filename, bool transform);
-  bool saveVTU(Mesh* mesh, const QString& filename, bool transform, bool binary = false);
-  bool saveOBJ(Mesh* mesh, const QString& filename, bool transform);
-  bool savePLY(Mesh* mesh, const QString& filename, bool transform, bool binary = false);
-
-  QDialog* dlg;
-  Ui_ExportMeshDialog* ui;
-};
-
-/**
- * \class SaveViewFile SystemProcessSave.hpp <SystemProcessSave.hpp>
- *
- * Save the view file
- *
- * \ingroup GlobalProcess
- */
-class MGX_EXPORT SaveViewFile : public GlobalProcess {
-public:
-  SaveViewFile(const GlobalProcess& proc)
-    : Process(proc)
-    , GlobalProcess(proc)
-  {
-  }
-
-  bool operator()(const QStringList& parms);
+  class MGX_EXPORT MeshExport : public QObject, public MeshProcess {
+    Q_OBJECT
+  public:
+    MeshExport(const MeshProcess& proc) : Process(proc), QObject(), MeshProcess(proc) {}
+  
+    bool operator()(const QStringList& parms);
+    /**
+     * Export a mesh
+     * \param mesh Mesh to be exported
+     * \param filename File to save the mesh into
+     * \param type Type (format) of the export.
+     * \param transform Save the transformed positions
+     */
+    bool operator()(Mesh* mesh, const QString& filename, const QString& type, bool transform);
+    QString folder() const { return "System"; }
+    QString name() const { return "Export"; }
+    QString description() const { return "Export a mesh into a known mesh format"; }
+    QStringList parmNames() const { return QStringList() << "Filename" << "Kind" << "Transform" << "Mesh number"; }
+    QStringList parmDescs() const { return QStringList() << "Filename" << "Kind" << "Transform" << "Mesh number"; }
+    QIcon icon() const { return QIcon(":/images/save.png"); }
+    QStringList parmDefaults() const { return QStringList() << "" << "Text" << "no" << "0"; }
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[1] = QStringList() << "PLY Binary" << "PLY Ascii" << "VTK Mesh Binary" << "VTK Mesh Ascii"
+                             << "Text" << "Cells" << "MeshEdit" << "STL" << "OBJ";
+      map[2] = map[3] = booleanChoice();
+      return map;
+    }
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+  protected slots:
+    void selectMeshFile();
+    void selectMeshType(const QString& type);
+  
+  protected:
+    QString properFile(QString filename, const QString& type) const;
+    void setMeshFile(const QString& filename);
+    Point3f savedPos(Point3f pos, bool transform, const Stack* stack);
+  
+    bool saveText(Mesh* mesh, const QString& filename, bool transform);
+    bool saveCells(Mesh* mesh, const QString& filename, bool transform);
+    bool saveMeshEdit(Mesh* mesh, const QString& filename, bool transform);
+    bool saveMeshSTL(Mesh* mesh, const QString& filename, bool transform);
+    bool saveVTU(Mesh* mesh, const QString& filename, bool transform, bool binary = false);
+    bool saveOBJ(Mesh* mesh, const QString& filename, bool transform);
+    bool savePLY(Mesh* mesh, const QString& filename, bool transform, bool binary = false);
+  
+    QDialog* dlg;
+    Ui_ExportMeshDialog* ui;
+  };
+  
   /**
+   * \class SaveViewFile SystemProcessSave.hpp <SystemProcessSave.hpp>
+   *
    * Save the view file
-   * \param filename File to save the parameters in
+   *
+   * \ingroup GlobalProcess
    */
-  bool operator()(const QString& filename);
-
-  bool initialize(QStringList& parms, QWidget* parent);
-
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Save View";
-  }
-  QString description() const {
-    return "Save the view file for the current configuration.";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Filename";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Filename";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/save.png");
-  }
-};
-
-/**
- * \class SaveAll SystemProcessSave.hpp <SystemProcessSave.hpp>
- *
- * Save all the data currently loaded.
- *
- * \ingroup GlobalProcess
- */
-class MGX_EXPORT SaveAll : public QObject, public GlobalProcess {
-  Q_OBJECT
-
-public:
-  SaveAll(const GlobalProcess& proc)
-    : Process(proc)
-    , QObject()
-    , GlobalProcess(proc)
-  {
-  }
-
+  class MGX_EXPORT SaveViewFile : public GlobalProcess {
+  public:
+    SaveViewFile(const GlobalProcess& proc) : Process(proc), GlobalProcess(proc) {}
+  
+    bool operator()(const QStringList& parms);
+    /**
+     * Save the view file
+     * \param filename File to save the parameters in
+     */
+    bool operator()(const QString& filename);
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    QString folder() const { return "System"; }
+    QString name() const { return "Save View"; }
+    QString description() const { return "Save the view file for the current configuration."; }
+    QStringList parmNames() const { return QStringList() << "Filename"; }
+    QStringList parmDescs() const { return QStringList() << "Filename"; }
+    QStringList parmDefaults() const { return QStringList() << ""; }
+    QIcon icon() const { return QIcon(":/images/save.png"); }
+  };
+  
   /**
-   * Recognised type of object
+   * \class TakeSnapshot SystemProcessSave.hpp <SystemProcessSave.hpp>
+   *
+   * This process allows scripts and other processes to take snapshots of the current result.
+   *
+   * Parameter       | Description
+   * ----------------|------------
+   * Filename        | Name of the output file. The extension will define will file format is used.
+   * Expend Frustrum | If true and the widht/height ratio is not the same as the screen, the frustrum will be expended
+   * Width           | Width of the image
+   * Height          | Height of the image
+   * Oversampling    | Oversampling factor (see Notes)
+   * Quality         | For lossy file formats, quality of the image on a scale from 0 to 100.
+   *
+   * Note on oversampling
+   * ====================
+   *
+   * If oversampling is not 1, then the scene is rendered on an image with width and height multiplied by the
+   * oversampling. The result is then scaled back to the wanted size, using bilinear filtering.
+   *
+   * \ingroup GlobalProcess
    */
-  enum OBJECT_TYPE { MAIN_STACK, WORK_STACK, MESH, VIEW, ALL };
-
-  /**
-   * Structure describing an object to be saved
-   */
-  struct SaveStruct {
-    OBJECT_TYPE type;     ///< Type of the object
-    int id;               ///< Id of the object (i.e. id used in Process::stack(int) or Process::mesh(int)
-    QString filename;     ///< File to save the object in
-    bool transform;       ///< For mesh only, save transformed positions
+  class MGX_EXPORT TakeSnapshot : public GlobalProcess {
+  public:
+    TakeSnapshot(const GlobalProcess& proc) : Process(proc), GlobalProcess(proc) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      QString filename = parms[0];
+      if(filename.isEmpty())
+        return setErrorMessage("Error, no file name specified.");
+      int width = parms[2].toInt();
+      int height = parms[3].toInt();
+      float overSampling = parms[4].toFloat();
+      int quality = parms[5].toInt();
+      bool expand_frustum = stringToBool(parms[1]);
+      return (*this)(filename, overSampling, width, height, quality, expand_frustum);
+    }
+  
+    bool operator()(QString filename, float overSampling, int width, int height, int quality, bool expand_frustum);
+  
+    QString folder() const { return "System"; }
+    QString name() const { return "Snapshot"; }
+    QString description() const { return "Take a snapshot of the current view"; }
+    QStringList parmNames() const { return QStringList() 
+      << "Filename" << "Expand Frustum" << "Width" << "Height" << "Oversampling" << "Quality"; }
+    QStringList parmDescs() const { return QStringList() 
+      << "Filename" << "Expand Frustum" << "Width" << "Height" << "Oversampling" << "Quality"; }
+    QStringList parmDefaults() const { return QStringList() 
+      << "" << "false" << "0" << "0" << "1.0" << "95"; }
+    QIcon icon() const { return QIcon(":/images/SaveScreenshot.png"); }
   };
 
-  bool initialize(QStringList& parms, QWidget* parent);
-  bool operator()(const QStringList& parms);
-  /**
-   * Save the objects described in the list
-   */
-  bool operator()(const QList<SaveStruct>& tosave, int compressionLevel = 0);
+}}
 
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Save All";
-  }
-  QString description() const {
-    return "Save all or part of the data currently loaded in MGX";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Type"
-                         << "Definition"
-                         << "Compression Level (0-9)";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "'All' to save all the structures, keeping their current file names\n"
-                            "'Defined' to specify in the 'Definition' argument what needs saving and how"
-                         << "A comma-separated list of fields, where each field is of the form KEY=VALUE\n"
-              "The key must be one of:"
-              " - 'MainStack' or 'WorkStack' followed by their user-visible id (i.e. 'MainStack1'\n"
-              "   for the first main stack)\n"
-              " - 'Mesh' preceded optionally by 'Transformed', and followed by the mesh id \n"
-              "   (i.e. 'TransformedMesh1' for the second mesh, transformed)\n"
-              "   The mesh type is by default binary mesh but can be empty, 'Text', 'Cells' \n"
-              "   or 'MeshEdit'. Note that a mesh cannot be saved as a Keyence mesh.\n"
-              " - 'View' for the view file.\n"
-              "The value is the name of the file to save the designated item into."
-                         << "Compression level used for stacks.";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "All"
-                         << ""
-                         << "5";
-  }
-  ParmChoiceMap parnChoices() const
-  {
-    ParmChoiceMap map;
-    map[0] = QStringList() << "All"
-                           << "Defined";
-    return map;
-  }
-  QIcon icon() const {
-    return QIcon(":/images/save.png");
-  }
-
-  static QRegExp type_expr;
-
-public slots:
-  void selectViewFile();
-  void validateViewFile();
-
-protected:
-  Ui_SaveAllDlg* ui;
-  QDialog* dlg;
-};
-
-/**
- * \class ResetAll SystemProcessSave.hpp <SystemProcessSave.hpp>
- *
- * Erase all data and reset all settings to default.
- *
- * \ingroup GlobalProcess
- */
-class MGX_EXPORT ResetAll : public GlobalProcess {
-public:
-  ResetAll(const GlobalProcess& proc)
-    : Process(proc)
-    , GlobalProcess(proc)
-  {
-  }
-
-  bool operator()(const QStringList&) {
-    return (*this)();
-  }
-  bool operator()();
-
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Reset All";
-  }
-  QString description() const {
-    return "Reset all stacks and meshes";
-  }
-  QStringList parmNames() const {
-    return QStringList();
-  }
-  QStringList parmDescs() const {
-    return QStringList();
-  }
-  QIcon icon() const {
-    return QIcon(":/images/ClearStack.png");
-  }
-};
-
-/**
- * \class TakeSnapshot SystemProcessSave.hpp <SystemProcessSave.hpp>
- *
- * This process allows scripts and other processes to take snapshots of the current result.
- *
- * Parameter       | Description
- * ----------------|------------
- * Filename        | Name of the output file. The extension will define will file format is used.
- * Expend Frustrum | If true and the widht/height ratio is not the same as the screen, the frustrum will be expended
- * Width           | Width of the image
- * Height          | Height of the image
- * Oversampling    | Oversampling factor (see Notes)
- * Quality         | For lossy file formats, quality of the image on a scale from 0 to 100.
- *
- * Note on oversampling
- * ====================
- *
- * If oversampling is not 1, then the scene is rendered on an image with width and height multiplied by the
- * oversampling. The result is then scaled back to the wanted size, using bilinear filtering.
- *
- * \ingroup GlobalProcess
- */
-class MGX_EXPORT TakeSnapshot : public GlobalProcess {
-public:
-  TakeSnapshot(const GlobalProcess& proc)
-    : Process(proc)
-    , GlobalProcess(proc)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    QString filename = parms[0];
-    if(filename.isEmpty())
-      return setErrorMessage("Error, no file name specified.");
-    int width = parms[2].toInt();
-    int height = parms[3].toInt();
-    float overSampling = parms[4].toFloat();
-    int quality = parms[5].toInt();
-    bool expand_frustum = stringToBool(parms[1]);
-    return (*this)(filename, overSampling, width, height, quality, expand_frustum);
-  }
-
-  bool operator()(QString filename, float overSampling, int width, int height, int quality, bool expand_frustum);
-
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Snapshot";
-  }
-  QString description() const {
-    return "Take a snapshot of the current view";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Filename"
-                         << "Expand Frustum"
-                         << "Width"
-                         << "Height"
-                         << "Oversampling"
-                         << "Quality";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Filename"
-                         << "Expand Frustum"
-                         << "Width"
-                         << "Height"
-                         << "Oversampling"
-                         << "Quality";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << ""
-                         << "false"
-                         << "0"
-                         << "0"
-                         << "1.0"
-                         << "95";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/SaveScreenshot.png");
-  }
-};
-} // namespace process
-} // namespace mgx
-
 #endif
Index: Process.cpp
===================================================================
--- Process.cpp	(revision 1255)
+++ Process.cpp	(revision 1256)
@@ -15,839 +15,830 @@
 
 static QTextStream err(stderr);
 
-namespace mgx {
+namespace mgx { namespace process {
 
-using namespace util;
-
-namespace process {
-unsigned int Process::processVersion = PROCESS_VERSION;
-
-Process::Process()
-  : p(0)
-{
-}
-
-Process::Process(const Process& p)
-  : p(p.p)
-{
-}
-
-QString Process::pythonCall(const QStringList& parms) const
-{
-  QStringList all_params;
-  forall(QString s, parms)
-    all_params << QString("'%1'").arg(shield_python(s));
-  QString name = this->name();
-  name.replace(' ', "_");
-  return QString("%1.%2(%3)").arg(type()).arg(name).arg(all_params.join(", "));
-}
-
-QString Process::actingFile() const {
-  return p->actingFile;
-}
-
-void Process::actingFile(const QString& filename, bool project_file)
-{
-  if(!filename.isEmpty() and (project_file or file().isEmpty())) {
-    DEBUG_OUTPUT("Entering actingFile (" << filename << ")- project_file = " << project_file << endl);
-    QString dir = getDir(filename);
-    bool changed_dir = (dir != currentPath());
-    setCurrentPath(dir);
-    p->actingFile = filename;
-    DEBUG_OUTPUT("## Change dir to = '" << dir << "'\n"
-                                        << "## Current dir = '" << currentPath() << "'" << endl);
-    if((project_file and file().isEmpty()) or changed_dir) {
-      DEBUG_OUTPUT("Writing MorphoGraphX.py" << endl);
-      QFile f("MorphoGraphX.py");
-      if(f.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
-        QTextStream ss(&f);
-        QDateTime now = QDateTime::currentDateTime();
-        ss << "######## New MorphoGraphX session v" << VERSION << " r" << REVISION << ": "
-           << now.toString("yyyy-MM-dd hh:mm:ss") << endl;
-        ss << p->currentPythonCall << endl;
-        p->changedFolder = true;
-        f.close();
+  using namespace util;
+  unsigned int Process::processVersion = PROCESS_VERSION;
+  
+  Process::Process() : p(0) {}
+  
+  Process::Process(const Process& p) : p(p.p) {}
+  
+  QString Process::pythonCall(const QStringList& parms) const
+  {
+    QStringList all_params;
+    forall(QString s, parms)
+      all_params << QString("'%1'").arg(shield_python(s));
+    QString name = this->name();
+    name.replace(' ', "_");
+    return QString("%1.%2(%3)").arg(type()).arg(name).arg(all_params.join(", "));
+  }
+  
+  QString Process::actingFile() const {
+    return p->actingFile;
+  }
+  
+  void Process::actingFile(const QString& filename, bool project_file)
+  {
+    if(!filename.isEmpty() and (project_file or file().isEmpty())) {
+      DEBUG_OUTPUT("Entering actingFile (" << filename << ")- project_file = " << project_file << endl);
+      QString dir = getDir(filename);
+      bool changed_dir = (dir != currentPath());
+      setCurrentPath(dir);
+      p->actingFile = filename;
+      DEBUG_OUTPUT("## Change dir to = '" << dir << "'\n"
+                                          << "## Current dir = '" << currentPath() << "'" << endl);
+      if((project_file and file().isEmpty()) or changed_dir) {
+        DEBUG_OUTPUT("Writing MorphoGraphX.py" << endl);
+        QFile f("MorphoGraphX.py");
+        if(f.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
+          QTextStream ss(&f);
+          QDateTime now = QDateTime::currentDateTime();
+          ss << "######## New MorphoGraphX session v" << VERSION << " r" << REVISION << ": "
+             << now.toString("yyyy-MM-dd hh:mm:ss") << endl;
+          ss << p->currentPythonCall << endl;
+          p->changedFolder = true;
+          f.close();
+        }
+        DEBUG_OUTPUT("Written MorphoGraphX.py");
       }
-      DEBUG_OUTPUT("Written MorphoGraphX.py");
+      DEBUG_OUTPUT("Leaving actingFile");
     }
-    DEBUG_OUTPUT("Leaving actingFile");
   }
-}
-
-int Process::stackCount() const {
-  return p->_stacks.size();
-}
-
-std::pair<Process::stack_iterator, Process::stack_iterator> Process::stacks()
-{
-  return std::make_pair(p->_stacks.begin(), p->_stacks.end());
-}
-
-std::pair<Process::const_stack_iterator, Process::const_stack_iterator> Process::stacks() const
-{
-  return std::make_pair(p->_stacks.begin(), p->_stacks.end());
-}
-
-Stack* Process::stack(int i)
-{
-  if(i == -1)
-    return currentStack();
-  if(i < 0 or i >= (int)p->_stacks.size())
-    return 0;
-  return p->_stacks[i];
-}
-
-Stack* Process::currentStack()
-{
-  if(currentStackId() == -1)
-    return 0;
-  return p->_stacks[currentStackId()];
-}
-
-int Process::currentStackId() const {
-  return p->current_stack;
-}
-
-void Process::setCurrentStackId(int i)
-{
-  if(i >= -1 and i < (int)p->_stacks.size())
-    p->current_stack = i;
-}
-
-Stack* Process::addStack()
-{
-  Stack* s = new Stack((int)p->_stacks.size());
-  p->_stacks.push_back(s);
-  return s;
-}
-
-bool Process::deleteStack(int i)
-{
-  if(i >= 0 and i < (int)p->_stacks.size()) {
-    delete p->_stacks[i];
-    p->_stacks[i] = 0;
-    p->_stacks.erase(p->_stacks.begin() + i);
-    for(int j = 0; j < (int)p->_stacks.size(); ++j)
-      p->_stacks[j]->setId(j);
-    return true;
+  
+  int Process::stackCount() const {
+    return p->_stacks.size();
   }
-  return false;
-}
-
-int Process::meshCount() const {
-  return p->_meshes.size();
-}
-
-std::pair<Process::mesh_iterator, Process::mesh_iterator> Process::meshes()
-{
-  return std::make_pair(p->_meshes.begin(), p->_meshes.end());
-}
-
-std::pair<Process::const_mesh_iterator, Process::const_mesh_iterator> Process::meshes() const
-{
-  return std::make_pair(p->_meshes.begin(), p->_meshes.end());
-}
-
-Mesh* Process::mesh(int i)
-{
-  if(i == -1)
-    return currentMesh();
-  return p->_meshes[i];
-}
-
-Mesh* Process::currentMesh()
-{
-  if(currentMeshId() == -1)
-    return 0;
-  return p->_meshes[currentMeshId()];
-}
-
-int Process::currentMeshId() const {
-  return p->current_mesh;
-}
-
-void Process::setCurrentMeshId(int i)
-{
-  if(i >= -1 and i < (int)p->_meshes.size())
-    p->current_mesh = i;
-}
-
-Mesh* Process::addMesh(const Stack* stack)
-{
-  Mesh* m = new Mesh((int)p->_meshes.size(), stack);
-  p->_meshes.push_back(m);
-  return m;
-}
-
-bool Process::deleteMesh(int i)
-{
-  if(i >= 0 and i < (int)p->_meshes.size()) {
-    delete p->_meshes[i];
-    p->_meshes[i] = 0;
-    p->_meshes.erase(p->_meshes.begin() + i);
-    for(int j = 0; j < (int)p->_meshes.size(); ++j)
-      p->_meshes[j]->setId(j);
-    return true;
+  
+  std::pair<Process::stack_iterator, Process::stack_iterator> Process::stacks()
+  {
+    return std::make_pair(p->_stacks.begin(), p->_stacks.end());
   }
-  return false;
-}
-
-int Process::selectedLabel() const {
-  return p->selected_label;
-}
-
-void Process::setSelectedLabel(int label) {
-  p->selected_label = label;
-}
-
-float Process::globalBrightness() {
-  return p->global_brightness;
-}
-
-float Process::globalContrast() {
-  return p->global_contrast;
-}
-
-void Process::setGlobalBrightness(float value)
-{
-  if(value > 1)
-    p->global_brightness = 1.0f;
-  else if(value < -1)
-    p->global_brightness = -1.0f;
-  else
-    p->global_brightness = value;
-}
-
-void Process::setGlobalContrast(float value)
-{
-  if(value > 2)
-    p->global_contrast = 2.0f;
-  else if(value < 0)
-    p->global_contrast = 0.0f;
-  else
-    p->global_contrast = value;
-}
-
-bool Process::meshSelection() const {
-  return p->mesh_selection;
-}
-
-bool Process::lineBorderSelection() const {
-  return p->line_border_selection;
-}
-
-bool Process::setErrorMessage(const QString& str)
-{
-  p->error = str;
-  return false;
-}
-
-QString Process::errorMessage() const {
-  return p->error;
-}
-
-void Process::setWarningMessage(const QString& str) {
-  p->warning = str;
-}
-
-QString Process::warningMessage() const {
-  return p->warning;
-}
-
-void Process::updateState()
-{
-  // Hold cuda mem to protect from GL
-  systemCommand(UPDATE_STRUCTURE, QStringList());
-}
-
-bool Process::systemCommand(SystemCommand cmd, const QStringList& parms)
-{
-  QMutexLocker locker(&p->lock);
-  p->success = false;
-  QCoreApplication::postEvent(p->parent, new ProcessSystemCommand(this, cmd, parms));
-  p->updated.wait(&p->lock);
-  return p->success;
-}
-
-bool GlobalProcess::setCurrentStack(int id, bool is_main)
-{
-  if(id >= stackCount()) {
-    setErrorMessage(
-      QString("There are only %1 stacks, cannot made stack %2 the current one").arg(stackCount()).arg(id));
+  
+  std::pair<Process::const_stack_iterator, Process::const_stack_iterator> Process::stacks() const
+  {
+    return std::make_pair(p->_stacks.begin(), p->_stacks.end());
+  }
+  
+  Stack* Process::stack(int i)
+  {
+    if(i == -1)
+      return currentStack();
+    if(i < 0 or i >= (int)p->_stacks.size())
+      return 0;
+    return p->_stacks[i];
+  }
+  
+  Stack* Process::currentStack()
+  {
+    if(currentStackId() == -1)
+      return 0;
+    return p->_stacks[currentStackId()];
+  }
+  
+  int Process::currentStackId() const {
+    return p->current_stack;
+  }
+  
+  void Process::setCurrentStackId(int i)
+  {
+    if(i >= -1 and i < (int)p->_stacks.size())
+      p->current_stack = i;
+  }
+  
+  Stack* Process::addStack()
+  {
+    Stack* s = new Stack((int)p->_stacks.size());
+    p->_stacks.push_back(s);
+    return s;
+  }
+  
+  bool Process::deleteStack(int i)
+  {
+    if(i >= 0 and i < (int)p->_stacks.size()) {
+      delete p->_stacks[i];
+      p->_stacks[i] = 0;
+      p->_stacks.erase(p->_stacks.begin() + i);
+      for(int j = 0; j < (int)p->_stacks.size(); ++j)
+        p->_stacks[j]->setId(j);
+      return true;
+    }
     return false;
   }
-  return systemCommand(SET_CURRENT_STACK, QStringList() << (is_main ? "true" : "false") << QString::number(id));
-}
-
-bool GlobalProcess::resetProject() {
-  return systemCommand(RESET_PROJECT, QStringList());
-}
-
-bool GlobalProcess::takeSnapshot(QString filename, float overSampling, int width, int height, int quality,
-                                 bool expand_frustum)
-{
-  QStringList parms;
-  parms << filename << boolToString(expand_frustum) << QString::number(width) << QString::number(height)
-        << QString::number(quality) << QString::number(overSampling);
-  return systemCommand(TAKE_SNAPSHOT, parms);
-}
-
-void Process::updateViewer() {
-  QCoreApplication::postEvent(p->parent, new ProcessUpdateViewEvent());
-}
-
-Clip* Process::clip1() {
-  return &p->clip1;
-}
-
-Clip* Process::clip2() {
-  return &p->clip2;
-}
-
-Clip* Process::clip3() {
-  return &p->clip3;
-}
-
-const Clip* Process::clip1() const {
-  return &p->clip1;
-}
-
-const Clip* Process::clip2() const {
-  return &p->clip2;
-}
-
-const Clip* Process::clip3() const {
-  return &p->clip3;
-}
-
-CuttingSurface* Process::cuttingSurface() {
-  return &p->cuttingSurface;
-}
-
-const CuttingSurface* Process::cuttingSurface() const {
-  return &p->cuttingSurface;
-}
-
-const QString& Process::file() const {
-  return p->filename;
-}
-
-QMap<QString, ProcessDefinition<StackProcess> > stackProcesses;
-QMap<QString, ProcessDefinition<MeshProcess> > meshProcesses;
-QMap<QString, ProcessDefinition<GlobalProcess> > globalProcesses;
-
-template <typename P>
-static const BaseProcessDefinition* getBaseProcessDefinition(const QMap<QString, ProcessDefinition<P> >& processes,
-                                                             const QString& processName)
-{
-  if(!processes.contains(processName))
-    return 0;
-  BaseProcessDefinition& def = processes[processName];
-  return &def;
-}
-
-template <typename P>
-static BaseProcessDefinition* getBaseProcessDefinition(QMap<QString, ProcessDefinition<P> >& processes,
-                                                       const QString& processName)
-{
-  if(!processes.contains(processName))
-    return 0;
-  BaseProcessDefinition& def = processes[processName];
-  return &def;
-}
-
-BaseProcessDefinition* getBaseProcessDefinition(const QString& processType, const QString& processName)
-{
-  if(processType == "Stack")
-    return getBaseProcessDefinition(stackProcesses, processName);
-  if(processType == "Mesh")
-    return getBaseProcessDefinition(meshProcesses, processName);
-  if(processType == "Global")
-    return getBaseProcessDefinition(globalProcesses, processName);
-  return 0;
-}
-
-bool getLastParms(const Process& proc, QStringList& parms) {
-  return getLastParms(proc.type(), proc.name(), parms);
-}
-
-bool getLastParms(const QString& processType, const QString& processName, QStringList& parms)
-{
-  BaseProcessDefinition* def = getBaseProcessDefinition(processType, processName);
-  if(!def)
+  
+  int Process::meshCount() const {
+    return p->_meshes.size();
+  }
+  
+  std::pair<Process::mesh_iterator, Process::mesh_iterator> Process::meshes()
+  {
+    return std::make_pair(p->_meshes.begin(), p->_meshes.end());
+  }
+  
+  std::pair<Process::const_mesh_iterator, Process::const_mesh_iterator> Process::meshes() const
+  {
+    return std::make_pair(p->_meshes.begin(), p->_meshes.end());
+  }
+  
+  Mesh* Process::mesh(int i)
+  {
+    if(i == -1)
+      return currentMesh();
+    return p->_meshes[i];
+  }
+  
+  Mesh* Process::currentMesh()
+  {
+    if(currentMeshId() == -1)
+      return 0;
+    return p->_meshes[currentMeshId()];
+  }
+  
+  int Process::currentMeshId() const {
+    return p->current_mesh;
+  }
+  
+  void Process::setCurrentMeshId(int i)
+  {
+    if(i >= -1 and i < (int)p->_meshes.size())
+      p->current_mesh = i;
+  }
+  
+  Mesh* Process::addMesh(const Stack* stack)
+  {
+    Mesh* m = new Mesh((int)p->_meshes.size(), stack);
+    p->_meshes.push_back(m);
+    return m;
+  }
+  
+  bool Process::deleteMesh(int i)
+  {
+    if(i >= 0 and i < (int)p->_meshes.size()) {
+      delete p->_meshes[i];
+      p->_meshes[i] = 0;
+      p->_meshes.erase(p->_meshes.begin() + i);
+      for(int j = 0; j < (int)p->_meshes.size(); ++j)
+        p->_meshes[j]->setId(j);
+      return true;
+    }
     return false;
-  parms = def->parms;
-  return true;
-}
-
-bool getDefaultParms(const Process& proc, QStringList& parms)
-{
-  return getDefaultParms(proc.type(), proc.name(), parms);
-}
-
-bool getDefaultParms(const QString& processType, const QString& processName, QStringList& parms)
-{
-  SetupProcess setup;
-  Process* p = setup.makeProcess(processType, processName);
-  if(!p)
+  }
+  
+  int Process::selectedLabel() const {
+    return p->selected_label;
+  }
+  
+  void Process::setSelectedLabel(int label) {
+    p->selected_label = label;
+  }
+  
+  float Process::globalBrightness() {
+    return p->global_brightness;
+  }
+  
+  float Process::globalContrast() {
+    return p->global_contrast;
+  }
+  
+  void Process::setGlobalBrightness(float value)
+  {
+    if(value > 1)
+      p->global_brightness = 1.0f;
+    else if(value < -1)
+      p->global_brightness = -1.0f;
+    else
+      p->global_brightness = value;
+  }
+  
+  void Process::setGlobalContrast(float value)
+  {
+    if(value > 2)
+      p->global_contrast = 2.0f;
+    else if(value < 0)
+      p->global_contrast = 0.0f;
+    else
+      p->global_contrast = value;
+  }
+  
+  bool Process::meshSelection() const {
+    return p->mesh_selection;
+  }
+  
+  bool Process::lineBorderSelection() const {
+    return p->line_border_selection;
+  }
+  
+  bool Process::setErrorMessage(const QString& str)
+  {
+    p->error = str;
     return false;
-  parms = p->parmDefaults();
-  delete p;
-  return true;
-}
-
-bool saveDefaultParms(const Process& proc, const QStringList& parms)
-{
-  return saveDefaultParms(proc.type(), proc.name(), parms);
-}
-
-bool saveDefaultParms(const QString& processType, const QString& processName, const QStringList& parms)
-{
-  BaseProcessDefinition* def = getBaseProcessDefinition(processType, processName);
-  if(!def)
-    return false;
-  if(parms.size() != def->parms.size())
-    return false;
-  def->parms = parms;
-  return true;
-}
-
-bool checkProcessParms(const Process& proc, const QStringList& parms, size_t* nbParms)
-{
-  return checkProcessParms(proc.type(), proc.name(), parms, nbParms);
-}
-
-bool checkProcessParms(const QString& processType, const QString& processName, const QStringList& parms,
-                       size_t* nbParms)
-{
-  BaseProcessDefinition* def = getBaseProcessDefinition(processType, processName);
-  if(!def)
-    return false;
-  if(nbParms)
-    *nbParms = def->parmNames.size();
-  // if(nbNamedStrings) *nbStringsValues = def->nbStringsValues;
-  // if(nbNamedValues) *nbNamedValues = def->nbNamedValues;
-  if(parms.size() != def->parms.size())
-    return false;
-  return true;
-}
-
-template <typename P, typename P1>
-static P* makeProcess(const QMap<QString, ProcessDefinition<P> >& processes, const QString& processName,
-                      const P1& process)
-{
-  if(!processes.contains(processName))
+  }
+  
+  QString Process::errorMessage() const {
+    return p->error;
+  }
+  
+  void Process::setWarningMessage(const QString& str) {
+    p->warning = str;
+  }
+  
+  QString Process::warningMessage() const {
+    return p->warning;
+  }
+  
+  void Process::updateState()
+  {
+    // Hold cuda mem to protect from GL
+    systemCommand(UPDATE_STRUCTURE, QStringList());
+  }
+  
+  bool Process::systemCommand(SystemCommand cmd, const QStringList& parms)
+  {
+    QMutexLocker locker(&p->lock);
+    p->success = false;
+    QCoreApplication::postEvent(p->parent, new ProcessSystemCommand(this, cmd, parms));
+    p->updated.wait(&p->lock);
+    return p->success;
+  }
+  
+  bool GlobalProcess::setCurrentStack(int id, bool is_main)
+  {
+    if(id >= stackCount()) {
+      setErrorMessage(
+        QString("There are only %1 stacks, cannot made stack %2 the current one").arg(stackCount()).arg(id));
+      return false;
+    }
+    return systemCommand(SET_CURRENT_STACK, QStringList() << (is_main ? "true" : "false") << QString::number(id));
+  }
+  
+  bool GlobalProcess::resetProject() {
+    return systemCommand(RESET_PROJECT, QStringList());
+  }
+  
+  bool GlobalProcess::takeSnapshot(QString filename, float overSampling, int width, int height, int quality,
+                                   bool expand_frustum)
+  {
+    QStringList parms;
+    parms << filename << boolToString(expand_frustum) << QString::number(width) << QString::number(height)
+          << QString::number(quality) << QString::number(overSampling);
+    return systemCommand(TAKE_SNAPSHOT, parms);
+  }
+  
+  void Process::updateViewer() {
+    QCoreApplication::postEvent(p->parent, new ProcessUpdateViewEvent());
+  }
+  
+  Clip* Process::clip1() {
+    return &p->clip1;
+  }
+  
+  Clip* Process::clip2() {
+    return &p->clip2;
+  }
+  
+  Clip* Process::clip3() {
+    return &p->clip3;
+  }
+  
+  const Clip* Process::clip1() const {
+    return &p->clip1;
+  }
+  
+  const Clip* Process::clip2() const {
+    return &p->clip2;
+  }
+  
+  const Clip* Process::clip3() const {
+    return &p->clip3;
+  }
+  
+  CuttingSurface* Process::cuttingSurface() {
+    return &p->cuttingSurface;
+  }
+  
+  const CuttingSurface* Process::cuttingSurface() const {
+    return &p->cuttingSurface;
+  }
+  
+  const QString& Process::file() const {
+    return p->filename;
+  }
+  
+  QMap<QString, ProcessDefinition<StackProcess> > stackProcesses;
+  QMap<QString, ProcessDefinition<MeshProcess> > meshProcesses;
+  QMap<QString, ProcessDefinition<GlobalProcess> > globalProcesses;
+  
+  template <typename P>
+  static const BaseProcessDefinition* getBaseProcessDefinition(const QMap<QString, ProcessDefinition<P> >& processes,
+                                                               const QString& processName)
+  {
+    if(!processes.contains(processName))
+      return 0;
+    BaseProcessDefinition& def = processes[processName];
+    return &def;
+  }
+  
+  template <typename P>
+  static BaseProcessDefinition* getBaseProcessDefinition(QMap<QString, ProcessDefinition<P> >& processes,
+                                                         const QString& processName)
+  {
+    if(!processes.contains(processName))
+      return 0;
+    BaseProcessDefinition& def = processes[processName];
+    return &def;
+  }
+  
+  BaseProcessDefinition* getBaseProcessDefinition(const QString& processType, const QString& processName)
+  {
+    if(processType == "Stack")
+      return getBaseProcessDefinition(stackProcesses, processName);
+    if(processType == "Mesh")
+      return getBaseProcessDefinition(meshProcesses, processName);
+    if(processType == "Global")
+      return getBaseProcessDefinition(globalProcesses, processName);
     return 0;
-  P* proc = processes[processName].factory(process);
-  return proc;
-}
-
-Process* Process::makeProcess(const QString& processType, const QString& processName)
-{
-  if(processType == "Stack") {
-    const StackProcess* real_process = dynamic_cast<const StackProcess*>(this);
-    if(real_process)
-      return process::makeProcess(stackProcesses, processName, *real_process);
   }
-  if(processType == "Mesh") {
-    const MeshProcess* real_process = dynamic_cast<const MeshProcess*>(this);
-    if(real_process)
-      return process::makeProcess(meshProcesses, processName, *real_process);
+  
+  bool getLastParms(const Process& proc, QStringList& parms) {
+    return getLastParms(proc.type(), proc.name(), parms);
   }
-  if(processType == "Global") {
-    const GlobalProcess* real_process = dynamic_cast<const GlobalProcess*>(this);
-    if(real_process)
-      return process::makeProcess(globalProcesses, processName, *real_process);
+  
+  bool getLastParms(const QString& processType, const QString& processName, QStringList& parms)
+  {
+    BaseProcessDefinition* def = getBaseProcessDefinition(processType, processName);
+    if(!def)
+      return false;
+    parms = def->parms;
+    return true;
   }
-  return 0;
-}
-
-QStringList listProcesses(const QString& processType)
-{
-  QStringList res;
-
-  if(processType == "Stack") {
-    forall(BaseProcessDefinition& def, stackProcesses)
-      res << def.name;
-  } else if(processType == "Mesh") {
-    forall(BaseProcessDefinition& def, meshProcesses)
-      res << def.name;
-  } else if(processType == "Global") {
-    forall(BaseProcessDefinition& def, globalProcesses)
-      res << def.name;
+  
+  bool getDefaultParms(const Process& proc, QStringList& parms)
+  {
+    return getDefaultParms(proc.type(), proc.name(), parms);
   }
-  return res;
-}
-
-bool validProcessType(const QString& processType)
-{
-  return ((processType == "Stack")or (processType == "Mesh") or (processType == "Global"));
-}
-
-bool validProcessName(const QString& processType, const QString& processName)
-{
-  if(processType == "Stack") {
-    return stackProcesses.contains(processName);
-  } else if(processType == "Mesh") {
-    return meshProcesses.contains(processName);
-  } else if(processType == "Global") {
-    return globalProcesses.contains(processName);
+  
+  bool getDefaultParms(const QString& processType, const QString& processName, QStringList& parms)
+  {
+    SetupProcess setup;
+    Process* p = setup.makeProcess(processType, processName);
+    if(!p)
+      return false;
+    parms = p->parmDefaults();
+    delete p;
+    return true;
   }
-  return false;
-}
-
-bool stringToMainStore(const QString& string)
-{
-  QString s = string.toLower();
-  if(s == "main")
+  
+  bool saveDefaultParms(const Process& proc, const QStringList& parms)
+  {
+    return saveDefaultParms(proc.type(), proc.name(), parms);
+  }
+  
+  bool saveDefaultParms(const QString& processType, const QString& processName, const QStringList& parms)
+  {
+    BaseProcessDefinition* def = getBaseProcessDefinition(processType, processName);
+    if(!def)
+      return false;
+    if(parms.size() != def->parms.size())
+      return false;
+    def->parms = parms;
     return true;
-  return false;
-}
-
-bool stringToWorkStore(const QString& string)
-{
-  QString s = string.toLower();
-  if(s == "work")
+  }
+  
+  bool checkProcessParms(const Process& proc, const QStringList& parms, size_t* nbParms)
+  {
+    return checkProcessParms(proc.type(), proc.name(), parms, nbParms);
+  }
+  
+  bool checkProcessParms(const QString& processType, const QString& processName, const QStringList& parms,
+                         size_t* nbParms)
+  {
+    BaseProcessDefinition* def = getBaseProcessDefinition(processType, processName);
+    if(!def)
+      return false;
+    if(nbParms)
+      *nbParms = def->parmNames.size();
+    // if(nbNamedStrings) *nbStringsValues = def->nbStringsValues;
+    // if(nbNamedValues) *nbNamedValues = def->nbNamedValues;
+    if(parms.size() != def->parms.size())
+      return false;
     return true;
-  return false;
-}
-
-bool stringToBool(const QString& string)
-{
-  static QStringList t = QStringList() << "t"
-                                       << "true"
-                                       << "on"
-                                       << "yes"
-                                       << "y"
-                                       << "1";
-  return t.contains(string.toLower());
-}
-
-bool Process::RunProcess(const QString& processType, const QString& processName, const QStringList& parms) throw()
-{
-  try {
-    std::auto_ptr<Process> proc(makeProcess(processType, processName));
-    if(not proc.get())
-      return setErrorMessage(QString("Error, cannot create process %1.%2").arg(processType).arg(processName));
-    if(!checkProcessParms(processType, processName, parms))
-      return setErrorMessage(
-        QString("Error, incorrect parameters for process %1.%2").arg(processType).arg(processName));
-    ;
-    return RunProcess(*proc, parms);
   }
-  catch(std::exception& ex) {
-    return setErrorMessage(
-      QString("Exception caught while creating process %1.%2: %3").arg(processName).arg(processName).arg(
-        ex.what()));
+  
+  template <typename P, typename P1>
+  static P* makeProcess(const QMap<QString, ProcessDefinition<P> >& processes, const QString& processName,
+                        const P1& process)
+  {
+    if(!processes.contains(processName))
+      return 0;
+    P* proc = processes[processName].factory(process);
+    return proc;
   }
-  catch(...) {
-    return setErrorMessage(
-      QString("Unknown exception caught while creating process %1.%2.").arg(processType).arg(processName));
+  
+  Process* Process::makeProcess(const QString& processType, const QString& processName)
+  {
+    if(processType == "Stack") {
+      const StackProcess* real_process = dynamic_cast<const StackProcess*>(this);
+      if(real_process)
+        return process::makeProcess(stackProcesses, processName, *real_process);
+    }
+    if(processType == "Mesh") {
+      const MeshProcess* real_process = dynamic_cast<const MeshProcess*>(this);
+      if(real_process)
+        return process::makeProcess(meshProcesses, processName, *real_process);
+    }
+    if(processType == "Global") {
+      const GlobalProcess* real_process = dynamic_cast<const GlobalProcess*>(this);
+      if(real_process)
+        return process::makeProcess(globalProcesses, processName, *real_process);
+    }
+    return 0;
   }
-}
-
-bool Process::RunProcess(Process& proc, const QStringList& parms) throw()
-{
-  try {
-    if(!proc(parms))
-      return setErrorMessage(proc.errorMessage());
+  
+  QStringList listProcesses(const QString& processType)
+  {
+    QStringList res;
+  
+    if(processType == "Stack") {
+      forall(BaseProcessDefinition& def, stackProcesses)
+        res << def.name;
+    } else if(processType == "Mesh") {
+      forall(BaseProcessDefinition& def, meshProcesses)
+        res << def.name;
+    } else if(processType == "Global") {
+      forall(BaseProcessDefinition& def, globalProcesses)
+        res << def.name;
+    }
+    return res;
   }
-  catch(QString& err) {
-    return setErrorMessage(QString("Error in %1.%2:\n%3").arg(proc.type()).arg(proc.name()).arg(err));
+  
+  bool validProcessType(const QString& processType)
+  {
+    return ((processType == "Stack")or (processType == "Mesh") or (processType == "Global"));
   }
-  catch(std::string& err) {
-    return setErrorMessage(QString("Error in %1.%2:\n%3").arg(proc.type()).arg(proc.name()).arg(err.c_str()));
+  
+  bool validProcessName(const QString& processType, const QString& processName)
+  {
+    if(processType == "Stack") {
+      return stackProcesses.contains(processName);
+    } else if(processType == "Mesh") {
+      return meshProcesses.contains(processName);
+    } else if(processType == "Global") {
+      return globalProcesses.contains(processName);
+    }
+    return false;
   }
-  catch(std::exception& ex) {
-    return setErrorMessage(QString("Error in %1.%2:\n%3").arg(proc.type()).arg(proc.name()).arg(ex.what()));
+  
+  bool stringToMainStore(const QString& string)
+  {
+    QString s = string.toLower();
+    if(s == "main")
+      return true;
+    return false;
   }
-  catch(...) {
-    setErrorMessage(QString("Error in %1.%2:\nUnknown C++ exception").arg(proc.type()).arg(proc.name()));
+  
+  bool stringToWorkStore(const QString& string)
+  {
+    QString s = string.toLower();
+    if(s == "work")
+      return true;
     return false;
   }
-  return true;
-}
-
-QString Process::stackError(int type, int i)
-{
-  QString msg;
-  if(i == -1)
-    msg = "the selected stack to be %1";
-  else
-    msg = QString("the stack %1 to be %2").arg(i);
-  QStringList what;
-  if(type == STORE_ANY)
-    what << "valid";
-  else {
-    if(type & STACK_NON_EMPTY)
-      what << "non-empty";
-    if(type & STACK_VISIBLE)
-      what << "visible";
-    if(type & STACK_EMPTY)
-      what << "empty";
-    if(type & STACK_SCALED)
-      what << "scaled";
-    if(type & STACK_TRANSFORMED)
-      what << "transformed";
-    if(type & STACK_NON_SCALED)
-      what << "not scaled";
-    if(type & STACK_NON_TRANSFORMED)
-      what << "not transformed";
+  
+  bool stringToBool(const QString& string)
+  {
+    static QStringList t = QStringList() << "t"
+                                         << "true"
+                                         << "on"
+                                         << "yes"
+                                         << "y"
+                                         << "1";
+    return t.contains(string.toLower());
   }
-  return msg.arg(what.join(", "));
-}
-
-QString Process::storeError(int type, int i)
-{
-  QString msg;
-  if(i == -1)
-    msg = "the current%1 stack to be %2";
-  else
-    msg = QString("the%2 stack %1 to be %3").arg(i);
-  QString which;
-  QStringList what;
-  if(type & STORE_WORK)
-    which = " work";
-  else if(type & STORE_MAIN)
-    which = " main";
-  else
-    which = "";
-  if(type == STORE_ANY)
-    what << "valid";
-  else {
-    if(type & STORE_VISIBLE)
-      what << "visible";
-    if(type & STORE_NON_EMPTY)
-      what << "non-empty";
-    if(type & STORE_EMPTY)
-      what << "empty";
-    if(type & STORE_LABEL)
-      what << "labeled";
-    else if(type & STORE_NON_LABEL)
-      what << "non-labeled";
-    if(type & STORE_SCALED)
-      what << "scaled";
-    if(type & STORE_TRANSFORMED)
-      what << "transformed";
-    if(type & STORE_NON_SCALED)
-      what << "not scaled";
-    if(type & STORE_NON_TRANSFORMED)
-      what << "not transformed";
+  
+  bool Process::RunProcess(const QString& processType, const QString& processName, const QStringList& parms) throw()
+  {
+    try {
+      std::auto_ptr<Process> proc(makeProcess(processType, processName));
+      if(not proc.get())
+        return setErrorMessage(QString("Error, cannot create process %1.%2").arg(processType).arg(processName));
+      if(!checkProcessParms(processType, processName, parms))
+        return setErrorMessage(
+          QString("Error, incorrect parameters for process %1.%2").arg(processType).arg(processName));
+      ;
+      return RunProcess(*proc, parms);
+    }
+    catch(std::exception& ex) {
+      return setErrorMessage(
+        QString("Exception caught while creating process %1.%2: %3").arg(processName).arg(processName).arg(
+          ex.what()));
+    }
+    catch(...) {
+      return setErrorMessage(
+        QString("Unknown exception caught while creating process %1.%2.").arg(processType).arg(processName));
+    }
   }
-  return msg.arg(which).arg(what.join(", "));
-}
-
-QString Process::meshError(int type, int i)
-{
-  QString msg;
-  if(i == -1)
-    msg = "the selected mesh to be %1";
-  else
-    msg = QString("the mesh %1 to be %2").arg(i);
-  QStringList what;
-  if(type == MESH_ANY)
-    what << "valid";
-  else {
-    if(type & MESH_VISIBLE)
-      what << "visible";
-    if(type & MESH_NON_EMPTY)
-      what << "non-empty";
-
-    if(type & MESH_HEAT)
-      what << "showing heat";
-    if(type & MESH_LABEL)
-      what << "showing label";
-    if(type & MESH_NORMAL)
-      what << "showing normal";
-    if(type & MESH_SIGNAL)
-      what << "showing signal";
-    if(type & MESH_TEXTURE)
-      what << "showing texture";
-    if(type & MESH_IMAGE)
-      what << "showing image";
-    if(type & MESH_SHOW_MESH)
-      what << "showing mesh";
-    if(type & MESH_SHOW_SURF)
-      what << "showing surface";
-    if(type & MESH_ALL)
-      what << "showing the whole mesh";
-    if(type & MESH_BORDER)
-      what << "showing the border";
-    if(type & MESH_CELLMAP)
-      what << "showing the cell mapping";
-    if(type & MESH_CELLS)
-      what << "a cell mesh";
-    if(type & MESH_IMG_TEX)
-      what << "haveing an image texture";
-    if(type & MESH_SCALED)
-      what << "scaled";
-    if(type & MESH_TRANSFORMED)
-      what << "transformed";
-    if(type & MESH_EMPTY)
-      what << "empty";
-    if(type & MESH_NON_CELLS)
-      what << "not a cell mesh";
-    if(type & MESH_NON_IMG_TEX)
-      what << "nat having an image texture";
-    if(type & MESH_NON_SCALED)
-      what << "not scaled";
-    if(type & MESH_NON_TRANSFORMED)
-      what << "not transformed";
+  
+  bool Process::RunProcess(Process& proc, const QStringList& parms) throw()
+  {
+    try {
+      if(!proc(parms))
+        return setErrorMessage(proc.errorMessage());
+    }
+    catch(QString& err) {
+      return setErrorMessage(QString("Error in %1.%2:\n%3").arg(proc.type()).arg(proc.name()).arg(err));
+    }
+    catch(std::string& err) {
+      return setErrorMessage(QString("Error in %1.%2:\n%3").arg(proc.type()).arg(proc.name()).arg(err.c_str()));
+    }
+    catch(std::exception& ex) {
+      return setErrorMessage(QString("Error in %1.%2:\n%3").arg(proc.type()).arg(proc.name()).arg(ex.what()));
+    }
+    catch(...) {
+      setErrorMessage(QString("Error in %1.%2:\nUnknown C++ exception").arg(proc.type()).arg(proc.name()));
+      return false;
+    }
+    return true;
   }
-  return msg.arg(what.join(", "));
-}
-
-bool Process::stackCheck(int checks, int which)
-{
-  Stack* s = (which == CHECK_CURRENT) ? currentStack() : stack(which);
-  return (s and not (checks & STACK_NON_EMPTY and s->empty())
-          and not (checks & STACK_VISIBLE and not (s->main()->isVisible() or s->work()->isVisible()))
-          and not (checks & STACK_EMPTY and not s->empty())and not (checks & STACK_SCALED and not s->showScale())
-          and not (checks & STACK_TRANSFORMED and not s->showTrans())
-          and not (checks & STACK_NON_SCALED and s->showScale())
-          and not (checks & STACK_NON_TRANSFORMED and s->showTrans()));
-}
-
-bool Process::storeCheck(int checks, int which)
-{
-  Stack* s = (which == CHECK_CURRENT) ? currentStack() : stack(which);
-  if(!s)
-    return false;
-  Store* store = 0;
-  if(checks & STORE_MAIN)
-    store = s->main();
-  else if(checks & STORE_WORK)
-    store = s->work();
-  else
-    store = s->currentStore();
-  return (store and not (checks & STORE_NON_EMPTY and store->empty())
-          and not (checks & STORE_VISIBLE and not store->isVisible())
-          and not (checks & STORE_EMPTY and not store->empty())and not (checks & STORE_LABEL and not store->labels())
-          and not (checks & STORE_NON_LABEL and store->labels())
-          and not (checks & STORE_SCALED and not store->stack()->showScale())
-          and not (checks & STORE_TRANSFORMED and not store->stack()->showTrans())
-          and not (checks & STORE_NON_SCALED and store->stack()->showScale())
-          and not (checks & STORE_NON_TRANSFORMED and store->stack()->showTrans()));
-}
-
-bool Process::meshCheck(int checks, int which)
-{
-  Mesh* m = (which == CHECK_CURRENT) ? currentMesh() : mesh(which);
-  return (m and not (checks & MESH_NON_EMPTY and m->empty())
-          and not (checks & MESH_VISIBLE and not (m->isSurfaceVisible() or m->isMeshVisible()))
-          and not (checks & MESH_HEAT and not (m->toShow() == Mesh::HEAT))
-          and not (checks & MESH_LABEL and not (m->toShow() == Mesh::LABEL))
-          and not (checks & MESH_NORMAL and not (m->toShow() == Mesh::NORMAL))
-          and not (checks & MESH_SIGNAL and not (m->coloring() == Mesh::SIGNAL))
-          and not (checks & MESH_TEXTURE and not (m->coloring() == Mesh::TEXTURE))
-          and not (checks & MESH_IMAGE and not (m->coloring() == Mesh::IMAGE))
-          and not (checks & MESH_SHOW_MESH and not m->isMeshVisible())
-          and not (checks & MESH_SHOW_SURF and not m->isSurfaceVisible())
-          and not (checks & MESH_ALL and not (m->meshView() == Mesh::ALL_MESH))
-          and not (checks & MESH_BORDER and not (m->meshView() == Mesh::BORDER_MESH))
-          and not (checks & MESH_CELLMAP and not (m->meshView() == Mesh::CELL_MESH))
-          and not (checks & MESH_CELLS and not m->cells())and not (checks & MESH_IMG_TEX and not m->hasImgTex())
-          and not (checks & MESH_SCALED and not m->scaled())
-          and not (checks & MESH_TRANSFORMED and not m->transformed())and not (checks & MESH_EMPTY and not m->empty())
-          and not (checks & MESH_NON_CELLS and m->cells())and not (checks & MESH_NON_IMG_TEX and m->hasImgTex())
-          and not (checks & MESH_NON_SCALED and m->scaled())
-          and not (checks & MESH_NON_TRANSFORMED and m->transformed()));
-}
-
-Process::CheckState Process::checkState() {
-  return CheckState(this);
-}
-
-Process::CheckState::CheckState(const CheckState& copy)
-  : reqs(copy.reqs)
-  , process(copy.process)
-{
-}
-
-Process::CheckState::CheckState(Process* proc)
-  : process(proc)
-{
-}
-
-Process::CheckState& Process::CheckState::store(int checks, int which)
-{
-  ProcessReqs r = { CHECK_STORE, checks, which };
-  reqs << r;
-  return *this;
-}
-
-Process::CheckState& Process::CheckState::stack(int checks, int which)
-{
-  ProcessReqs r = { CHECK_STACK, checks, which };
-  reqs << r;
-  return *this;
-}
-
-Process::CheckState& Process::CheckState::mesh(int checks, int which)
-{
-  ProcessReqs r = { CHECK_MESH, checks, which };
-  reqs << r;
-  return *this;
-}
-
-void Process::CheckState::setError()
-{
-  QStringList msgs;
-  forall(const ProcessReqs& r, reqs) {
-    switch(r.type) {
-    case CHECK_STACK:
-      msgs << process->stackError(r.checks, r.which);
-      break;
-    case CHECK_STORE:
-      msgs << process->storeError(r.checks, r.which);
-      break;
-    case CHECK_MESH:
-      msgs << process->meshError(r.checks, r.which);
-    default:
-      break;
+  
+  QString Process::stackError(int type, int i)
+  {
+    QString msg;
+    if(i == -1)
+      msg = "the selected stack to be %1";
+    else
+      msg = QString("the stack %1 to be %2").arg(i);
+    QStringList what;
+    if(type == STORE_ANY)
+      what << "valid";
+    else {
+      if(type & STACK_NON_EMPTY)
+        what << "non-empty";
+      if(type & STACK_VISIBLE)
+        what << "visible";
+      if(type & STACK_EMPTY)
+        what << "empty";
+      if(type & STACK_SCALED)
+        what << "scaled";
+      if(type & STACK_TRANSFORMED)
+        what << "transformed";
+      if(type & STACK_NON_SCALED)
+        what << "not scaled";
+      if(type & STACK_NON_TRANSFORMED)
+        what << "not transformed";
     }
+    return msg.arg(what.join(", "));
   }
-  QString msg = QString("This process requires %1").arg(msgs.join(" ; "));
-  process->setErrorMessage(msg);
-}
-
-Process::CheckState::operator bool()
-{
-  forall(const ProcessReqs& r, reqs) {
-    switch(r.type) {
-    case CHECK_STACK:
-      if(!process->stackCheck(r.checks, r.which)) {
-        setError();
-        return false;
+  
+  QString Process::storeError(int type, int i)
+  {
+    QString msg;
+    if(i == -1)
+      msg = "the current%1 stack to be %2";
+    else
+      msg = QString("the%2 stack %1 to be %3").arg(i);
+    QString which;
+    QStringList what;
+    if(type & STORE_WORK)
+      which = " work";
+    else if(type & STORE_MAIN)
+      which = " main";
+    else
+      which = "";
+    if(type == STORE_ANY)
+      what << "valid";
+    else {
+      if(type & STORE_VISIBLE)
+        what << "visible";
+      if(type & STORE_NON_EMPTY)
+        what << "non-empty";
+      if(type & STORE_EMPTY)
+        what << "empty";
+      if(type & STORE_LABEL)
+        what << "labeled";
+      else if(type & STORE_NON_LABEL)
+        what << "non-labeled";
+      if(type & STORE_SCALED)
+        what << "scaled";
+      if(type & STORE_TRANSFORMED)
+        what << "transformed";
+      if(type & STORE_NON_SCALED)
+        what << "not scaled";
+      if(type & STORE_NON_TRANSFORMED)
+        what << "not transformed";
+    }
+    return msg.arg(which).arg(what.join(", "));
+  }
+  
+  QString Process::meshError(int type, int i)
+  {
+    QString msg;
+    if(i == -1)
+      msg = "the selected mesh to be %1";
+    else
+      msg = QString("the mesh %1 to be %2").arg(i);
+    QStringList what;
+    if(type == MESH_ANY)
+      what << "valid";
+    else {
+      if(type & MESH_VISIBLE)
+        what << "visible";
+      if(type & MESH_NON_EMPTY)
+        what << "non-empty";
+  
+      if(type & MESH_HEAT)
+        what << "showing heat";
+      if(type & MESH_LABEL)
+        what << "showing labels";
+      if(type & MESH_PARENT)
+        what << "showing parents";
+      if(type & MESH_LABEL_PARENT)
+        what << "showing labels or parents";
+      if(type & MESH_NORMAL)
+        what << "showing normal";
+      if(type & MESH_SIGNAL)
+        what << "showing signal";
+      if(type & MESH_TEXTURE)
+        what << "showing texture";
+      if(type & MESH_IMAGE)
+        what << "showing image";
+      if(type & MESH_SHOW_MESH)
+        what << "showing mesh";
+      if(type & MESH_SHOW_SURF)
+        what << "showing surface";
+      if(type & MESH_ALL)
+        what << "showing the whole mesh";
+      if(type & MESH_BORDER)
+        what << "showing the border";
+      if(type & MESH_CELLMAP)
+        what << "showing the cell mapping";
+      if(type & MESH_CELLS)
+        what << "a cell mesh";
+      if(type & MESH_IMG_TEX)
+        what << "haveing an image texture";
+      if(type & MESH_SCALED)
+        what << "scaled";
+      if(type & MESH_TRANSFORMED)
+        what << "transformed";
+      if(type & MESH_EMPTY)
+        what << "empty";
+      if(type & MESH_NON_CELLS)
+        what << "not a cell mesh";
+      if(type & MESH_NON_IMG_TEX)
+        what << "nat having an image texture";
+      if(type & MESH_NON_SCALED)
+        what << "not scaled";
+      if(type & MESH_NON_TRANSFORMED)
+        what << "not transformed";
+    }
+    return msg.arg(what.join(", "));
+  }
+  
+  bool Process::stackCheck(int checks, int which)
+  {
+    Stack* s = (which == CHECK_CURRENT) ? currentStack() : stack(which);
+    return (s and not (checks & STACK_NON_EMPTY and s->empty())
+            and not (checks & STACK_VISIBLE and not (s->main()->isVisible() or s->work()->isVisible()))
+            and not (checks & STACK_EMPTY and not s->empty())and not (checks & STACK_SCALED and not s->showScale())
+            and not (checks & STACK_TRANSFORMED and not s->showTrans())
+            and not (checks & STACK_NON_SCALED and s->showScale())
+            and not (checks & STACK_NON_TRANSFORMED and s->showTrans()));
+  }
+  
+  bool Process::storeCheck(int checks, int which)
+  {
+    Stack* s = (which == CHECK_CURRENT) ? currentStack() : stack(which);
+    if(!s)
+      return false;
+    Store* store = 0;
+    if(checks & STORE_MAIN)
+      store = s->main();
+    else if(checks & STORE_WORK)
+      store = s->work();
+    else
+      store = s->currentStore();
+    return (store and not (checks & STORE_NON_EMPTY and store->empty())
+            and not (checks & STORE_VISIBLE and not store->isVisible())
+            and not (checks & STORE_EMPTY and not store->empty())and not (checks & STORE_LABEL and not store->labels())
+            and not (checks & STORE_NON_LABEL and store->labels())
+            and not (checks & STORE_SCALED and not store->stack()->showScale())
+            and not (checks & STORE_TRANSFORMED and not store->stack()->showTrans())
+            and not (checks & STORE_NON_SCALED and store->stack()->showScale())
+            and not (checks & STORE_NON_TRANSFORMED and store->stack()->showTrans()));
+  }
+  
+  bool Process::meshCheck(int checks, int which)
+  {
+    Mesh* m = (which == CHECK_CURRENT) ? currentMesh() : mesh(which);
+    return (m and not (checks & MESH_NON_EMPTY and m->empty())
+            and not (checks & MESH_VISIBLE and not (m->isSurfaceVisible() or m->isMeshVisible()))
+            and not (checks & MESH_HEAT and not (m->toShow() == Mesh::HEAT))
+            and not (checks & MESH_LABEL and not (m->toShow() == Mesh::LABEL))
+            and not (checks & MESH_PARENT and not (m->toShow() == Mesh::PARENT))
+            and not (checks & MESH_LABEL_PARENT and not (m->toShow() == Mesh::LABEL or m->toShow() == Mesh::PARENT))
+            and not (checks & MESH_NORMAL and not (m->toShow() == Mesh::NORMAL))
+            and not (checks & MESH_SIGNAL and not (m->coloring() == Mesh::SIGNAL))
+            and not (checks & MESH_TEXTURE and not (m->coloring() == Mesh::TEXTURE))
+            and not (checks & MESH_IMAGE and not (m->coloring() == Mesh::IMAGE))
+            and not (checks & MESH_SHOW_MESH and not m->isMeshVisible())
+            and not (checks & MESH_SHOW_SURF and not m->isSurfaceVisible())
+            and not (checks & MESH_ALL and not (m->meshView() == Mesh::ALL_MESH))
+            and not (checks & MESH_BORDER and not (m->meshView() == Mesh::BORDER_MESH))
+            and not (checks & MESH_CELLMAP and not (m->meshView() == Mesh::CELL_MESH))
+            and not (checks & MESH_CELLS and not m->cells())and not (checks & MESH_IMG_TEX and not m->hasImgTex())
+            and not (checks & MESH_SCALED and not m->scaled())
+            and not (checks & MESH_TRANSFORMED and not m->transformed())and not (checks & MESH_EMPTY and not m->empty())
+            and not (checks & MESH_NON_CELLS and m->cells())and not (checks & MESH_NON_IMG_TEX and m->hasImgTex())
+            and not (checks & MESH_NON_SCALED and m->scaled())
+            and not (checks & MESH_NON_TRANSFORMED and m->transformed()));
+  }
+  
+  Process::CheckState Process::checkState() {
+    return CheckState(this);
+  }
+  
+  Process::CheckState::CheckState(const CheckState& copy) : reqs(copy.reqs) , process(copy.process) {}
+  
+  Process::CheckState::CheckState(Process* proc) : process(proc) {}
+  
+  Process::CheckState& Process::CheckState::store(int checks, int which)
+  {
+    ProcessReqs r = { CHECK_STORE, checks, which };
+    reqs << r;
+    return *this;
+  }
+  
+  Process::CheckState& Process::CheckState::stack(int checks, int which)
+  {
+    ProcessReqs r = { CHECK_STACK, checks, which };
+    reqs << r;
+    return *this;
+  }
+  
+  Process::CheckState& Process::CheckState::mesh(int checks, int which)
+  {
+    ProcessReqs r = { CHECK_MESH, checks, which };
+    reqs << r;
+    return *this;
+  }
+  
+  void Process::CheckState::setError()
+  {
+    QStringList msgs;
+    forall(const ProcessReqs& r, reqs) {
+      switch(r.type) {
+      case CHECK_STACK:
+        msgs << process->stackError(r.checks, r.which);
+        break;
+      case CHECK_STORE:
+        msgs << process->storeError(r.checks, r.which);
+        break;
+      case CHECK_MESH:
+        msgs << process->meshError(r.checks, r.which);
+      default:
+        break;
       }
-      break;
-    case CHECK_STORE:
-      if(!process->storeCheck(r.checks, r.which)) {
-        setError();
-        return false;
+    }
+    QString msg = QString("This process requires %1").arg(msgs.join(" ; "));
+    process->setErrorMessage(msg);
+  }
+  
+  Process::CheckState::operator bool()
+  {
+    forall(const ProcessReqs& r, reqs) {
+      switch(r.type) {
+      case CHECK_STACK:
+        if(!process->stackCheck(r.checks, r.which)) {
+          setError();
+          return false;
+        }
+        break;
+      case CHECK_STORE:
+        if(!process->storeCheck(r.checks, r.which)) {
+          setError();
+          return false;
+        }
+        break;
+      case CHECK_MESH:
+        if(!process->meshCheck(r.checks, r.which)) {
+          setError();
+          return false;
+        }
+      default:
+        break;
       }
-      break;
-    case CHECK_MESH:
-      if(!process->meshCheck(r.checks, r.which)) {
-        setError();
-        return false;
-      }
-    default:
-      break;
     }
+    return true;
   }
-  return true;
-}
-
-#if defined(WIN32)
-template <>
-Registration<StackProcess>::factoryList Registration<StackProcess>::factories
-  = Registration<StackProcess>::factoryList();
-template <>
-Registration<MeshProcess>::factoryList Registration<MeshProcess>::factories = Registration<MeshProcess>::factoryList();
-template <>
-Registration<GlobalProcess>::factoryList Registration<GlobalProcess>::factories
-  = Registration<GlobalProcess>::factoryList();
-#endif
-} // namespace process
-} // namespace mgx
+  
+  #if defined(WIN32)
+    template <>
+    Registration<StackProcess>::factoryList Registration<StackProcess>::factories
+      = Registration<StackProcess>::factoryList();
+    template <>
+    Registration<MeshProcess>::factoryList Registration<MeshProcess>::factories 
+      = Registration<MeshProcess>::factoryList();
+    template <>
+    Registration<GlobalProcess>::factoryList Registration<GlobalProcess>::factories
+      = Registration<GlobalProcess>::factoryList();
+  #endif
+}}
Index: GUI.ui
===================================================================
--- GUI.ui	(revision 1255)
+++ GUI.ui	(revision 1256)
@@ -5656,7 +5656,7 @@
      <x>0</x>
      <y>0</y>
      <width>1412</width>
-     <height>25</height>
+     <height>27</height>
     </rect>
    </property>
    <widget class="QMenu" name="menu_File">
@@ -5669,10 +5669,6 @@
     <addaction name="separator"/>
     <addaction name="menuFileEditPaths"/>
     <addaction name="separator"/>
-    <addaction name="menuFileSaveAll"/>
-    <addaction name="menuFileReloadAll"/>
-    <addaction name="menuFileResetAll"/>
-    <addaction name="separator"/>
     <addaction name="menuExit"/>
     <addaction name="actionDebug_Dialog"/>
    </widget>
@@ -6310,16 +6306,6 @@
     <string>Swap the display of surfaces (useful when cosegmenting)</string>
    </property>
   </action>
-  <action name="menuFileSaveAll">
-   <property name="text">
-    <string>Save All ...</string>
-   </property>
-  </action>
-  <action name="menuFileReloadAll">
-   <property name="text">
-    <string>Reload All</string>
-   </property>
-  </action>
   <action name="menuStack1Export">
    <property name="text">
     <string>Export</string>
@@ -6560,11 +6546,6 @@
     <string>Import</string>
    </property>
   </action>
-  <action name="menuFileResetAll">
-   <property name="text">
-    <string>Reset All</string>
-   </property>
-  </action>
   <action name="actionDoxygen">
    <property name="text">
     <string>Doxygen</string>
Index: MeshProcessCreation.cpp
===================================================================
--- MeshProcessCreation.cpp	(revision 1255)
+++ MeshProcessCreation.cpp	(revision 1256)
@@ -16,867 +16,874 @@
 // Number of evals per progress check for marching cubes
 const int EVAL_PROGRESS = 10000;
 
-namespace mgx {
-namespace process {
-typedef util::Vector<3, vertex> Vtx3;
-typedef util::Vector<4, vertex> Vtx4;
-typedef util::Vector<5, vertex> Vtx5;
-typedef util::Vector<7, vertex> Vtx7;
-
-bool evalCheckProgress(Progress& progress)
-{
-  static int count = 0;
-  if(count++ >= EVAL_PROGRESS) {
-    count = 0;
-    if(!progress.advance(0))
-      return false;
-  }
-  return true;
-}
-
-template <size_t n> void makeNhbd(vvgraph& S, util::Vector<n, vertex> V)
-{
-  S.insertEdge(V[0], V[1]);
-  for(size_t i = 2; i < n; ++i)
-    S.spliceAfter(V[0], V[i - 1], V[i]);
-}
-
-// 3D surface evaluation function for marching cubes
-int getStackData(const Stack* stack, const Store* store, Point3f& p)
-{
-  Point3f pf = stack->worldToImagef(p);
-  // Be careful of float->int conversion when we are below 0
-  for(int i = 0; i < 3; i++)
-    if(pf[i] < 0)
-      pf[i] -= 1;
-  int x = int(pf.x());
-  int y = int(pf.y());
-  int z = int(pf.z());
-
-  // Decide which stack to use
-  const HVecUS& data = store->data();
-  if(!stack->boundsOK(x, y, z))
-    return (0);
-  else
-    return (data[stack->offset(x, y, z)]);
-}
-
-// Implicit surface evaluator functions, return true if inside
-bool MarchingCubeSurface::eval(Point3f p)
-{
-  if(!evalCheckProgress(progress))
-    userCancel();
-  int d = getStackData(_stack, _store, p);
-  if(d >= _threshold)
+namespace mgx { namespace process {
+  
+  typedef util::Vector<3, vertex> Vtx3;
+  typedef util::Vector<4, vertex> Vtx4;
+  typedef util::Vector<5, vertex> Vtx5;
+  typedef util::Vector<7, vertex> Vtx7;
+  
+  bool evalCheckProgress(Progress& progress)
+  {
+    static int count = 0;
+    if(count++ >= EVAL_PROGRESS) {
+      count = 0;
+      if(!progress.advance(0))
+        return false;
+    }
     return true;
-  else
-    return false;
-}
-
-bool MarchingCubeSurface::operator()(Mesh* mesh, const Store* store, float cubeSize, int threshold)
-{
-  // Store threshold for eval
-  if(threshold <= 0)
-    threshold = 1;
-  _threshold = threshold;
-
-  // Setup progress bar
-  progress.restart(QString("Marching Cubes Surface on Stack %1").arg(mesh->userId()), 0);
-
-  // Clear mesh
-  vvgraph& S = mesh->graph();
-  mesh->reset();
-
-  mesh->updateAll();
-  mesh->showLabel();
-
-  // Find bounding box
-  _store = store;
-  _stack = store->stack();
-  const HVecUS& data = store->data();
-  Point3u size = _stack->size();
-
-  // Count pixels and create bounding region(s)
-  long pixCount = 0;
-  BoundingBox3u bBox;
-  Progress progress(QString("Finding object bounds-%1").arg(mesh->userId()), size.z());
-  const ushort* pdata = data.data();
-  int i = 0;
-  for(uint z = 0; z < size.z(); z++) {
-    if(!progress.advance(z))
-      userCancel();
-    for(uint y = 0; y < size.y(); y++) {
-      for(uint x = 0; x < size.x(); x++, ++pdata, ++i) {
-        // For normal march only count "inside" pixels
-        if(*pdata < threshold)
-          continue;
-        pixCount++;
-
-        // Find bounding box
-        if(pixCount == 1) {
-          bBox = BoundingBox3u(Point3u(x, y, z));
-        } else {
-          bBox |= Point3u(x, y, z);
-        }
-      }
-    }
   }
-
-  // Polygonizer object
-  std::vector<Point3f> vertList;
-  std::vector<Point3i> triList;
-  util::Polygonizer pol(*this, cubeSize, _stack->step(), vertList, triList);
-
-  // Get bounding box in world coordinates
-  BoundingBox3f bBoxWorld = _stack->imageToWorld(bBox);
-
-  SETSTATUS("Computing segmentation for threshold " << threshold << " with bBox of: " << bBoxWorld[0] << " - "
-                                                    << bBoxWorld[1] << " cube size:" << cubeSize
-                                                    << " pixel count:" << pixCount);
-
-  // Call polygonizer, catch any errors
-  triList.clear();
-  Point3f marchBBox[2] = { bBoxWorld.pmin(), bBoxWorld.pmax() };
-  pol.march(marchBBox);
-
-  // Points to VVe vertices
-  std::vector<vertex> vertices;
-  vertices.resize(vertList.size());
-  for(size_t i = 0; i < vertList.size(); ++i) {
-    vertex v;
-    v->pos = vertList[i];
-    v->saveId = i;
-    v->label = 0;
-    vertices[i] = v;
+  
+  template <size_t n> void makeNhbd(vvgraph& S, util::Vector<n, vertex> V)
+  {
+    S.insertEdge(V[0], V[1]);
+    for(size_t i = 2; i < n; ++i)
+      S.spliceAfter(V[0], V[i - 1], V[i]);
   }
-
-  // Insert vertices and triangles into mesh
-  if(!meshFromTriangles(S, vertices, triList)) {
-    setErrorMessage("Error, cannot add all the triangles");
-    return false;
+  
+  // 3D surface evaluation function for marching cubes
+  int getStackData(const Stack* stack, const Store* store, Point3f& p)
+  {
+    Point3f pf = stack->worldToImagef(p);
+    // Be careful of float->int conversion when we are below 0
+    for(int i = 0; i < 3; i++)
+      if(pf[i] < 0)
+        pf[i] -= 1;
+    int x = int(pf.x());
+    int y = int(pf.y());
+    int z = int(pf.z());
+  
+    // Decide which stack to use
+    const HVecUS& data = store->data();
+    if(!stack->boundsOK(x, y, z))
+      return (0);
+    else
+      return (data[stack->offset(x, y, z)]);
   }
-
-  SETSTATUS("Triangles added:" << triList.size() << ", vertices:" << S.size());
-
-  return true;
-}
-REGISTER_MESH_PROCESS(MarchingCubeSurface);
-
-bool MarchingCube3D::eval(Point3f p)
-{
-  if(!evalCheckProgress(progress))
-    userCancel();
-  int d = getStackData(_stack, _store, p);
-  if(d == _label)
-    return true;
-  else
-    return false;
-}
-
-bool MarchingCube3D::operator()(Mesh* mesh, const Store* store, float cubeSize, int minVoxels, int smooth,
-                                int singleLabel)
-{
-  bool single = false;
-  if(singleLabel > 0)
-    single = true;
-
-  // Setup progress bar
-  progress.restart(QString("Marching Cubes 3D on Stack %1").arg(mesh->userId()), 0);
-
-  typedef std::pair<int, int> IntIntPair;
-  typedef std::map<int, int> IntIntMap;
-  typedef util::Vector<2, Point3i> Point3i2;
-  typedef std::pair<int, Point3i2> IntPoint3i2Pair;
-  typedef std::map<int, Point3i2> IntPoint3i2Map;
-
-  // Clear mesh
-  vvgraph& S = mesh->graph();
-  vvgraph D;
-
-  // If re-marching a single label, delete the old mesh part, otherwise reset it
-  if(single) {
-    forall(const vertex& v, S)
-      if(v->label == singleLabel)
-        D.insert(v);
-    mesh->getConnectedVertices(S, D);
-    forall(const vertex& v, D)
-      S.erase(v);
-  } else
+  
+  // Implicit surface evaluator functions, return true if inside
+  bool MarchingCubeSurface::eval(Point3f p)
+  {
+    if(!evalCheckProgress(progress))
+      userCancel();
+    int d = getStackData(_stack, _store, p);
+    if(d >= _threshold)
+      return true;
+    else
+      return false;
+  }
+  
+  bool MarchingCubeSurface::operator()(Mesh* mesh, const Store* store, float cubeSize, int threshold)
+  {
+    // Store threshold for eval
+    if(threshold <= 0)
+      threshold = 1;
+    _threshold = threshold;
+  
+    // Setup progress bar
+    progress.restart(QString("Marching Cubes Surface on Stack %1").arg(mesh->userId()), 0);
+  
+    // Clear mesh
+    vvgraph& S = mesh->graph();
     mesh->reset();
-
-  mesh->updateAll();
-  mesh->showLabel();
-
-  // Find bounding box
-  _store = store;
-  _stack = store->stack();
-  const HVecUS& data = store->data();
-  Point3u size = _stack->size();
-
-  // Count pixels and create bounding region(s)
-  if(minVoxels <= 0)
-    minVoxels = 1;
-  int labelCount = 0;
-  std::vector<long> pixCnt(65536, 0);
-  std::vector<BoundingBox3u> bBoxImg(65536, BoundingBox3u());
-  const ushort* pdata = data.data();
-  int i = 0;
-  for(uint z = 0; z < size.z(); z++) {
-    for(uint y = 0; y < size.y(); y++) {
-      for(uint x = 0; x < size.x(); x++, ++pdata, ++i) {
-        // Count pixels
-        int label = *pdata;
-        if(single and label != singleLabel)
-          continue;
-        pixCnt[label]++;
-        if(pixCnt[label] == minVoxels)
-          labelCount++;
-
-        // Find bounding box
-        if(pixCnt[label] == 1) {
-          bBoxImg[label] = BoundingBox3u(Point3u(x, y, z));
-        } else {
-          bBoxImg[label] |= Point3u(x, y, z);
+  
+    // Find bounding box
+    _store = store;
+    _stack = store->stack();
+    const HVecUS& data = store->data();
+    Point3u size = _stack->size();
+  
+    // Count pixels and create bounding region(s)
+    long pixCount = 0;
+    BoundingBox3u bBox;
+    Progress progress(QString("Finding object bounds-%1").arg(mesh->userId()), size.z());
+    const ushort* pdata = data.data();
+    int i = 0;
+    for(uint z = 0; z < size.z(); z++) {
+      if(!progress.advance(z))
+        userCancel();
+      for(uint y = 0; y < size.y(); y++) {
+        for(uint x = 0; x < size.x(); x++, ++pdata, ++i) {
+          // For normal march only count "inside" pixels
+          if(*pdata < threshold)
+            continue;
+          pixCount++;
+  
+          // Find bounding box
+          if(pixCount == 1) {
+            bBox = BoundingBox3u(Point3u(x, y, z));
+          } else {
+            bBox |= Point3u(x, y, z);
+          }
         }
       }
     }
-  }
-
-  // Polygonizer object
-  std::vector<Point3f> vertList;
-  std::vector<Point3i> triList;
-  util::Polygonizer pol(*this, cubeSize, _stack->step(), vertList, triList);
-
-  // Call marching cubes for each label
-  int maxLabel = 0;
-  int startLabel = 1;
-  if(single)
-    startLabel = singleLabel;
-  int endLabel = 65535;
-  if(single)
-    endLabel = singleLabel;
-
-  for(int label = startLabel; label <= endLabel; ++label) {
-    if(pixCnt[label] < minVoxels)
-      continue;
-    if(label > maxLabel)
-      maxLabel = label;
-
+  
+    // Polygonizer object
+    std::vector<Point3f> vertList;
+    std::vector<Point3i> triList;
+    util::Polygonizer pol(*this, cubeSize, _stack->step(), vertList, triList);
+  
     // Get bounding box in world coordinates
-    BoundingBox3f bBox = _stack->imageToWorld(bBoxImg[label]);
-    Point3f bBoxWorld[2] = { bBox.pmin(), bBox.pmax() };
-
-    SETSTATUS("Computing segmentation for label " << label << " with bbox of: " << bBoxWorld[0] << " - "
-                                                  << bBoxWorld[1] << " cube size:" << cubeSize
-                                                  << " pixels:" << pixCnt[label]);
-
-    // Store label for eval
-    _label = label;
-
-    // Call polygonizer
+    BoundingBox3f bBoxWorld = _stack->imageToWorld(bBox);
+  
+    SETSTATUS("Computing segmentation for threshold " << threshold << " with bBox of: " << bBoxWorld[0] 
+      << " - " << bBoxWorld[1] << " cube size:" << cubeSize << " pixel count:" << pixCount);
+  
+    // Call polygonizer, catch any errors
     triList.clear();
-    pol.march(bBoxWorld);
-
+    Point3f marchBBox[2] = { bBoxWorld.pmin(), bBoxWorld.pmax() };
+    pol.march(marchBBox);
+  
     // Points to VVe vertices
     std::vector<vertex> vertices;
-    // For now generate new vertices each time through
-    std::map<int, int> vertMap;
-    std::map<int, int>::iterator vertIter;
-    forall(Point3i& tri, triList) {
-      for(int i = 0; i < 3; i++) {
-        if((vertIter = vertMap.find(tri[i])) != vertMap.end()) {
-          tri[i] = vertIter->second;
-        } else {
-          vertex v;
-          v->pos = vertList[tri[i]];
-          v->saveId = tri[i];
-          v->label = label;
-          vertMap[tri[i]] = vertices.size();
-          tri[i] = vertices.size();
-          vertices.push_back(v);
-        }
-      }
+    vertices.resize(vertList.size());
+    for(size_t i = 0; i < vertList.size(); ++i) {
+      vertex v;
+      v->pos = vertList[i];
+      v->saveId = i;
+      v->label = 0;
+      v->signal = 1.0;
+      vertices[i] = v;
     }
-
+  
     // Insert vertices and triangles into mesh
     if(!meshFromTriangles(S, vertices, triList)) {
       setErrorMessage("Error, cannot add all the triangles");
       return false;
     }
-
-    SETSTATUS("Label:" << label << ", triangles added:" << triList.size() << ", vertices:" << S.size());
+  
+    SETSTATUS("Triangles added:" << triList.size() << ", vertices:" << S.size());
+  
+    mesh->signalBounds() = Point2f(0.0, 1.0);
+    mesh->updateAll();
+    mesh->showLabel();
+  
+    return true;
   }
-
-  // smooth points but keep them attached
-  if(!single) {
-    for(int i = 0; i < smooth; i++) {
-      std::map<int, Point3f> posMap;
-      std::map<int, int> cntMap;
+  REGISTER_MESH_PROCESS(MarchingCubeSurface);
+  
+  bool MarchingCube3D::eval(Point3f p)
+  {
+    if(!evalCheckProgress(progress))
+      userCancel();
+    int d = getStackData(_stack, _store, p);
+    if(d == _label)
+      return true;
+    else
+      return false;
+  }
+  
+  bool MarchingCube3D::operator()(Mesh* mesh, const Store* store, float cubeSize, int minVoxels, int smooth,
+                                  int singleLabel)
+  {
+    bool single = false;
+    if(singleLabel > 0)
+      single = true;
+  
+    // Setup progress bar
+    progress.restart(QString("Marching Cubes 3D on Stack %1").arg(mesh->userId()), 0);
+  
+    typedef std::pair<int, int> IntIntPair;
+    typedef std::map<int, int> IntIntMap;
+    typedef util::Vector<2, Point3i> Point3i2;
+    typedef std::pair<int, Point3i2> IntPoint3i2Pair;
+    typedef std::map<int, Point3i2> IntPoint3i2Map;
+  
+    // Clear mesh
+    vvgraph& S = mesh->graph();
+    vvgraph D;
+  
+    // If re-marching a single label, delete the old mesh part, otherwise reset it
+    if(single) {
       forall(const vertex& v, S)
-        forall(const vertex& n, S.neighbors(v)) {
-          posMap[v->saveId] += n->pos;
-          cntMap[v->saveId]++;
+        if(v->label == singleLabel)
+          D.insert(v);
+      mesh->getConnectedVertices(S, D);
+      forall(const vertex& v, D)
+        S.erase(v);
+    } else
+      mesh->reset();
+  
+    // Find bounding box
+    _store = store;
+    _stack = store->stack();
+    const HVecUS& data = store->data();
+    Point3u size = _stack->size();
+  
+    // Count pixels and create bounding region(s)
+    if(minVoxels <= 0)
+      minVoxels = 1;
+    int labelCount = 0;
+    std::vector<long> pixCnt(65536, 0);
+    std::vector<BoundingBox3u> bBoxImg(65536, BoundingBox3u());
+    const ushort* pdata = data.data();
+    int i = 0;
+    for(uint z = 0; z < size.z(); z++) {
+      for(uint y = 0; y < size.y(); y++) {
+        for(uint x = 0; x < size.x(); x++, ++pdata, ++i) {
+          // Count pixels
+          int label = *pdata;
+          if(single and label != singleLabel)
+            continue;
+          pixCnt[label]++;
+          if(pixCnt[label] == minVoxels)
+            labelCount++;
+  
+          // Find bounding box
+          if(pixCnt[label] == 1) {
+            bBoxImg[label] = BoundingBox3u(Point3u(x, y, z));
+          } else {
+            bBoxImg[label] |= Point3u(x, y, z);
+          }
         }
-      forall(const vertex& v, S)
-        v->pos = posMap[v->saveId] / cntMap[v->saveId];
+      }
     }
-  }
-
-  // Update next label if required
-  if(maxLabel > mesh->viewLabel())
-    mesh->setLabel(maxLabel + 1);
-
-  return true;
-}
-REGISTER_MESH_PROCESS(MarchingCube3D);
-
-bool CuttingSurfMesh::operator()(Mesh* mesh)
-{
-  CuttingSurface* cutSurf = cuttingSurface();
-  if(!cutSurf) {
-    setErrorMessage("You need an active cutting surface to convert it into a mesh");
-    return false;
-  }
-  std::vector<Point3f> points;
-  int uSize = 0, vSize = 0;
-  cutSurf->getSurfPoints(&mesh->stack()->frame(), points, uSize, vSize);
-  if(points.empty() or uSize < 2 or vSize < 2)
+  
+    // Polygonizer object
+    std::vector<Point3f> vertList;
+    std::vector<Point3i> triList;
+    util::Polygonizer pol(*this, cubeSize, _stack->step(), vertList, triList);
+  
+    // Call marching cubes for each label
+    int maxLabel = 0;
+    int startLabel = 1;
+    if(single)
+      startLabel = singleLabel;
+    int endLabel = 65535;
+    if(single)
+      endLabel = singleLabel;
+  
+    for(int label = startLabel; label <= endLabel; ++label) {
+      if(pixCnt[label] < minVoxels)
+        continue;
+      if(label > maxLabel)
+        maxLabel = label;
+  
+      // Get bounding box in world coordinates
+      BoundingBox3f bBox = _stack->imageToWorld(bBoxImg[label]);
+      Point3f bBoxWorld[2] = { bBox.pmin(), bBox.pmax() };
+  
+      SETSTATUS("Computing segmentation for label " << label << " with bbox of: " << bBoxWorld[0] << " - "
+                                                    << bBoxWorld[1] << " cube size:" << cubeSize
+                                                    << " pixels:" << pixCnt[label]);
+  
+      // Store label for eval
+      _label = label;
+  
+      // Call polygonizer
+      triList.clear();
+      pol.march(bBoxWorld);
+  
+      // Points to VVe vertices
+      std::vector<vertex> vertices;
+      // For now generate new vertices each time through
+      std::map<int, int> vertMap;
+      std::map<int, int>::iterator vertIter;
+      forall(Point3i& tri, triList) {
+        for(int i = 0; i < 3; i++) {
+          if((vertIter = vertMap.find(tri[i])) != vertMap.end()) {
+            tri[i] = vertIter->second;
+          } else {
+            vertex v;
+            v->pos = vertList[tri[i]];
+            v->saveId = tri[i];
+            v->label = label;
+            v->signal = 1.0;
+            vertMap[tri[i]] = vertices.size();
+            tri[i] = vertices.size();
+            vertices.push_back(v);
+          }
+        }
+      }
+  
+      // Insert vertices and triangles into mesh
+      if(!meshFromTriangles(S, vertices, triList)) {
+        setErrorMessage("Error, cannot add all the triangles");
+        return false;
+      }
+  
+      SETSTATUS("Label:" << label << ", triangles added:" << triList.size() << ", vertices:" << S.size());
+    }
+  
+    // smooth points but keep them attached
+    if(!single) {
+      for(int i = 0; i < smooth; i++) {
+        std::map<int, Point3f> posMap;
+        std::map<int, int> cntMap;
+        forall(const vertex& v, S)
+          forall(const vertex& n, S.neighbors(v)) {
+            posMap[v->saveId] += n->pos;
+            cntMap[v->saveId]++;
+          }
+        forall(const vertex& v, S)
+          v->pos = posMap[v->saveId] / cntMap[v->saveId];
+      }
+    }
+  
+    // Update next label if required
+    if(maxLabel > mesh->viewLabel())
+      mesh->setLabel(maxLabel + 1);
+  
+    mesh->signalBounds() = Point2f(0.0, 1.0);
+    mesh->updateAll();
+    mesh->showLabel();
+  
     return true;
-
-  // Create a new graph
-  vvgraph S;
-
-  std::vector<vertex> empty_vector(vSize, vertex(0));   // VC++ bug requires this
-  std::vector<std::vector<vertex> > vtx(uSize, empty_vector);
-
-  // Create the vertices and fill in the position
-  for(int u = 0; u < uSize; u++) {
-    for(int v = 0; v < vSize; v++) {
-      vertex a;
-      S.insert(a);
-      vtx[u][v] = a;
-      a->pos = points[u * vSize + v];
-      a->txpos.x() = float(u) / float(uSize - 1);
-      a->txpos.y() = float(v) / float(vSize - 1);
-    }
   }
-
-  // Connect neighborhoods
-  for(int u = 0; u < uSize; u++)
-    for(int v = 0; v < vSize; v++) {
-      if(u == 0 and v == vSize - 1)       // top left corner;
-        makeNhbd(S, Vtx3(vtx[u][v], vtx[u][v - 1], vtx[u + 1][v]));
-      else if(u == 0 and v == 0)       // bottom left corner
-        makeNhbd(S, Vtx3(vtx[u][v], vtx[u + 1][v], vtx[u][v + 1]));
-      else if(u == uSize - 1 and v == 0)       // bottom right corner
-        makeNhbd(S, Vtx3(vtx[u][v], vtx[u][v + 1], vtx[u - 1][v]));
-      else if(u == uSize - 1 and v == vSize - 1)       // top right corner
-        makeNhbd(S, Vtx3(vtx[u][v], vtx[u - 1][v], vtx[u][v - 1]));
-      else if(v == vSize - 1)       // top edge
-        makeNhbd(S, Vtx4(vtx[u][v], vtx[u - 1][v], vtx[u][v - 1], vtx[u + 1][v]));
-      else if(u == 0)       // left edge
-        makeNhbd(S, Vtx4(vtx[u][v], vtx[u][v - 1], vtx[u + 1][v], vtx[u][v + 1]));
-      else if(v == 0)       // bottom edge
-        makeNhbd(S, Vtx4(vtx[u][v], vtx[u + 1][v], vtx[u][v + 1], vtx[u - 1][v]));
-      else if(u == uSize - 1)       // right edge
-        makeNhbd(S, Vtx4(vtx[u][v], vtx[u][v + 1], vtx[u - 1][v], vtx[u][v - 1]));
-      else       // Interior vertex
-        makeNhbd(S, Vtx5(vtx[u][v], vtx[u + 1][v], vtx[u][v + 1], vtx[u - 1][v], vtx[u][v - 1]));
+  REGISTER_MESH_PROCESS(MarchingCube3D);
+  
+  bool CuttingSurfMesh::operator()(Mesh* mesh)
+  {
+    CuttingSurface* cutSurf = cuttingSurface();
+    if(!cutSurf) {
+      setErrorMessage("You need an active cutting surface to convert it into a mesh");
+      return false;
     }
-
-  // At this point we have a quad mesh, triangulate it (nicely)
-  vvgraph T = S;
-  forall(const vertex& v, T)
-    forall(const vertex& n, T.neighbors(v)) {
-      vertex m = S.nextTo(v, n);
-      vertex w = S.nextTo(m, v);
-      // Unique quad found
-      if(w == S.prevTo(n, v) and v > w and n > m) {
+    std::vector<Point3f> points;
+    int uSize = 0, vSize = 0;
+    cutSurf->getSurfPoints(&mesh->stack()->frame(), points, uSize, vSize);
+    if(points.empty() or uSize < 2 or vSize < 2)
+      return true;
+  
+    // Create a new graph
+    vvgraph S;
+  
+    std::vector<vertex> empty_vector(vSize, vertex(0));   // VC++ bug requires this
+    std::vector<std::vector<vertex> > vtx(uSize, empty_vector);
+  
+    // Create the vertices and fill in the position
+    for(int u = 0; u < uSize; u++) {
+      for(int v = 0; v < vSize; v++) {
         vertex a;
-        a->pos = (v->pos + w->pos + n->pos + m->pos) / 4.0f;
-        a->txpos = (v->txpos + w->txpos + n->txpos + m->txpos) / 4.0f;
         S.insert(a);
-        makeNhbd(S, Vtx5(a, v, n, w, m));
-
-        S.spliceAfter(v, n, a);
-        S.spliceAfter(n, w, a);
-        S.spliceAfter(w, m, a);
-        S.spliceAfter(m, v, a);
+        vtx[u][v] = a;
+        a->pos = points[u * vSize + v];
+        a->txpos.x() = float(u) / float(uSize - 1);
+        a->txpos.y() = float(v) / float(vSize - 1);
+        a->signal = 1.0;
       }
     }
-
-  mesh->graph().swap(S);
-
-  mesh->setCells(false);
-  SETSTATUS("Mesh " << mesh->userId() << " made from cutting surface");
-  mesh->updateAll();
-  return true;
-}
-REGISTER_MESH_PROCESS(CuttingSurfMesh);
-
-namespace {
-
-// Return an ordered pair (a,b) such that a <= b
-template <typename T> util::Vector<2, T> makePair(const T& a, const T& b)
-{
-  if(a <= b)
-    return util::Vector<2, T>(a, b);
-  return util::Vector<2, T>(b, a);
-}
-
-// Return an ordered triplet (a,b,c) such that a <= b <= c
-template <typename T> util::Vector<3, T> makeTriplet(const T& a, const T& b, const T& c)
-{
-  if(a <= b) {
-    if(b <= c)
-      return util::Vector<3, T>(a, b, c);
-    if(a <= c)
-      return util::Vector<3, T>(a, c, b);
-    return util::Vector<3, T>(c, a, b);
+  
+    // Connect neighborhoods
+    for(int u = 0; u < uSize; u++)
+      for(int v = 0; v < vSize; v++) {
+        if(u == 0 and v == vSize - 1)       // top left corner;
+          makeNhbd(S, Vtx3(vtx[u][v], vtx[u][v - 1], vtx[u + 1][v]));
+        else if(u == 0 and v == 0)       // bottom left corner
+          makeNhbd(S, Vtx3(vtx[u][v], vtx[u + 1][v], vtx[u][v + 1]));
+        else if(u == uSize - 1 and v == 0)       // bottom right corner
+          makeNhbd(S, Vtx3(vtx[u][v], vtx[u][v + 1], vtx[u - 1][v]));
+        else if(u == uSize - 1 and v == vSize - 1)       // top right corner
+          makeNhbd(S, Vtx3(vtx[u][v], vtx[u - 1][v], vtx[u][v - 1]));
+        else if(v == vSize - 1)       // top edge
+          makeNhbd(S, Vtx4(vtx[u][v], vtx[u - 1][v], vtx[u][v - 1], vtx[u + 1][v]));
+        else if(u == 0)       // left edge
+          makeNhbd(S, Vtx4(vtx[u][v], vtx[u][v - 1], vtx[u + 1][v], vtx[u][v + 1]));
+        else if(v == 0)       // bottom edge
+          makeNhbd(S, Vtx4(vtx[u][v], vtx[u + 1][v], vtx[u][v + 1], vtx[u - 1][v]));
+        else if(u == uSize - 1)       // right edge
+          makeNhbd(S, Vtx4(vtx[u][v], vtx[u][v + 1], vtx[u - 1][v], vtx[u][v - 1]));
+        else       // Interior vertex
+          makeNhbd(S, Vtx5(vtx[u][v], vtx[u + 1][v], vtx[u][v + 1], vtx[u - 1][v], vtx[u][v - 1]));
+      }
+  
+    // At this point we have a quad mesh, triangulate it (nicely)
+    vvgraph T = S;
+    forall(const vertex& v, T)
+      forall(const vertex& n, T.neighbors(v)) {
+        vertex m = S.nextTo(v, n);
+        vertex w = S.nextTo(m, v);
+        // Unique quad found
+        if(w == S.prevTo(n, v) and v > w and n > m) {
+          vertex a;
+          a->pos = (v->pos + w->pos + n->pos + m->pos) / 4.0f;
+          a->txpos = (v->txpos + w->txpos + n->txpos + m->txpos) / 4.0f;
+          S.insert(a);
+          makeNhbd(S, Vtx5(a, v, n, w, m));
+  
+          S.spliceAfter(v, n, a);
+          S.spliceAfter(n, w, a);
+          S.spliceAfter(w, m, a);
+          S.spliceAfter(m, v, a);
+        }
+      }
+  
+    mesh->graph().swap(S);
+  
+    SETSTATUS("Mesh " << mesh->userId() << " made from cutting surface");
+  
+    mesh->setCells(false);
+    mesh->signalBounds() = Point2f(0.0, 1.0);
+    mesh->showLabel();
+    mesh->updateAll();
+    return true;
   }
-  if(b <= c) {
-    if(c <= a)
-      return util::Vector<3, T>(b, c, a);
-    return util::Vector<3, T>(b, a, c);
-  }
-  return util::Vector<3, T>(c, b, a);
-}
-
-enum CORNER_POSITION { BOTTOM_LEFT = 0, BOTTOM_RIGHT = 1, TOP_RIGHT = 2, TOP_LEFT = 3, INVALID_POS = -1 };
-
-CORNER_POSITION turn_cw(CORNER_POSITION c)
-{
-  switch(c) {
-  case BOTTOM_LEFT:
-    return TOP_LEFT;
-  case BOTTOM_RIGHT:
-    return BOTTOM_LEFT;
-  case TOP_RIGHT:
-    return BOTTOM_RIGHT;
-  case TOP_LEFT:
-    return TOP_RIGHT;
-  default:
-    throw QString("Programming error: invalid corner position in turn_cw");
-  }
-}
-
-CORNER_POSITION turn_ccw(CORNER_POSITION c)
-{
-  switch(c) {
-  case BOTTOM_LEFT:
-    return BOTTOM_RIGHT;
-  case BOTTOM_RIGHT:
-    return TOP_RIGHT;
-  case TOP_RIGHT:
-    return TOP_LEFT;
-  case TOP_LEFT:
-    return BOTTOM_LEFT;
-  default:
-    throw QString("Programming error: invalid corner position in turn_cw");
-  }
-}
-
-typedef util::Vector<4, ushort> Point4us;
-
-/*
- * Read-only 2D data holder with helper methods
- *
- * The corners are named after the pixel on their top-right. So the corner (x,y) is such that:
- *
- *    (x-1,y)  |  (x,y)
- *   ----------*--------
- *   (x-1,y-1) | (x,y-1)
- *
- */
-struct Data2D {
-
-  // Structure holding an edge with its shape which cells its separate
-  struct Edge {
-    Point2u cells;                 // Cells the edge separate
-    std::vector<vertex> shape;     // The edge itself, including end points
-  };
-
-  Data2D(const Store* store, vvgraph& S_, uint zslice, float ml)
-    : data(store->data())
-    , S(S_)
-    , minLength(ml)
-    , minLengthSq(ml * ml)
-    , centers(65536, Point3f())
-    , sizes(65536, 0u)
-    , cells(65536, vertex(0))
-    , cell_joints(65536)
-  {
-    const Stack* stk = store->stack();
-    size = Point2u(stk->size());
-    step = Point2f(stk->step());
-    origin = stk->origin() + 0.5 * stk->step() + zslice * stk->step().z();
-    offset = zslice * step.x() * step.y();
-    xdir = Point3f(step.x(), 0, 0);
-    ydir = Point3f(0, step.y(), 0);
-    pixelArea = step.x() * step.y();
-  }
-
-  ushort operator()(int x, int y) const
-  {
-    if(x >= 0 and y >= 0 and x < (int)size.x() and y < (int)size.y())
-      return data[y * size.x() + x + offset];
-    return 0;
-  }
-
-  // Return the position at the bottom left of the (x,y) corner
-  ushort bottomLeft(int x, int y) const {
-    return (*this)(x - 1, y - 1);
-  }
-  ushort bottomLeft(Point2i pos) const {
-    return bottomLeft(pos.x(), pos.y());
-  }
-
-  // Return the position at the bottom right of the (x,y) corner
-  ushort bottomRight(int x, int y) const {
-    return (*this)(x, y - 1);
-  }
-  ushort bottomRight(Point2i pos) const {
-    return bottomRight(pos.x(), pos.y());
-  }
-
-  // Return the position at the top left of the (x,y) corner
-  ushort topLeft(int x, int y) const {
-    return (*this)(x - 1, y);
-  }
-  ushort topLeft(Point2i pos) const {
-    return topLeft(pos.x(), pos.y());
-  }
-
-  // Return the position at the top right of the (x,y) corner
-  ushort topRight(int x, int y) const {
-    return (*this)(x, y);
-  }
-  ushort topRight(Point2i pos) const {
-    return topRight(pos.x(), pos.y());
-  }
-
-  /*
-   * Return the cells around a corner as:
-   *
-   *  3 | 2
-   *  --+--
-   *  0 | 1
-   *
-   * which correspond to the CORNER_POSITION enumeration.
-   */
-  Point4us cornerCells(int x, int y) const
-  {
-    return Point4us(bottomLeft(x, y), bottomRight(x, y), topRight(x, y), topLeft(x, y));
-  }
-
-  template <typename T> Point3f imageToWorld(T x, T y) const {
-    return origin + float(x) * xdir + float(y) * ydir;
-  }
-
-  template <typename T> Point3f imageToWorld(const util::Vector<2, T>& pos) const {
-    return imageToWorld(pos.x(), pos.y());
-  }
-
-  const HVecUS& data;
-  vvgraph& S;
-  size_t offset;
-  Point2u size;
-  Point2f step;
-  Point3f origin;
-  Point3f xdir;
-  Point3f ydir;
-  float minLength, minLengthSq;
-  float pixelArea;
-
-  /* Find edges in the store, starting from a given point:
-   * The second parameter is the identity of the cells as:
-   *
-   *   3 | 2
-   *   --+--
-   *   0 | 1
-   *
-   * which correspond to the CORNER_POSITION enumeration.
-   *
-   * Warning: The function should only be called if there are at least three different cells around.
-   */
-  void findEdges(Point2u startCorner, Point4us cells)
-  {
-    if((cells[TOP_RIGHT] == cells[BOTTOM_LEFT])or (cells[TOP_LEFT] == cells[BOTTOM_RIGHT])) {
-      ushort c = (cells[TOP_RIGHT] == cells[BOTTOM_LEFT] ? cells[TOP_RIGHT] : cells[TOP_LEFT]);
-      QString errorMsg("Error at position (%1,%2): the cell %3 appears in two opposite corners.");
-      throw errorMsg.arg(startCorner.x()).arg(startCorner.y()).arg(c);
+  REGISTER_MESH_PROCESS(CuttingSurfMesh);
+  
+  namespace {
+  
+    // Return an ordered pair (a,b) such that a <= b
+    template <typename T> util::Vector<2, T> makePair(const T& a, const T& b)
+    {
+      if(a <= b)
+        return util::Vector<2, T>(a, b);
+      return util::Vector<2, T>(b, a);
     }
-
-    vertex v = joint(startCorner);
-    std::vector<size_t>& known_edges = joint_edges[v];
-    size_t prev_lab = cells[3];
-    for(int i = 0; i < 4; ++i) {
-      if(cells[i] != prev_lab) {
-        cell_joints[cells[i]].insert(v);
-        cell_joints[prev_lab].insert(v);
-
-        // Check if we already know about the edge
-        Point2u pc = Point2u(cells[i], prev_lab);
-        Point2u opc = Point2u(prev_lab, cells[i]);
-        bool found = false;
-        for(size_t j = 0; j < known_edges.size(); ++j) {
-          Point2u kc = edges[known_edges[j]].cells;
-          if(kc == pc or kc == opc) {
-            found = true;
-            break;
-          }
-        }
-        if(not found) {
-          Edge e = makeEdge(startCorner, cells, CORNER_POSITION(i));
-          size_t new_edge = edges.size();
-          edges.push_back(e);
-          known_edges.push_back(new_edge);
-          joint_edges[e.shape.back()].push_back(new_edge);           // add to the other end
-
-          /*
-           * Information::out << "Created edge from " << e.shape.front().num() << " to "
-           *  << e.shape.back().num() << " between cell " << cells[i] << " and cell "
-           *  << cells[turn_cw(CORNER_POSITION(i))] << endl;
-           */
-        }
+    
+    // Return an ordered triplet (a,b,c) such that a <= b <= c
+    template <typename T> util::Vector<3, T> makeTriplet(const T& a, const T& b, const T& c)
+    {
+      if(a <= b) {
+        if(b <= c)
+          return util::Vector<3, T>(a, b, c);
+        if(a <= c)
+          return util::Vector<3, T>(a, c, b);
+        return util::Vector<3, T>(c, a, b);
       }
-      prev_lab = cells[i];
+      if(b <= c) {
+        if(c <= a)
+          return util::Vector<3, T>(b, c, a);
+        return util::Vector<3, T>(b, a, c);
+      }
+      return util::Vector<3, T>(c, b, a);
     }
-  }
-
-  vertex joint(Point2u pos)
-  {
-    std::map<Point2u, vertex>::const_iterator found = joints.find(pos);
-    if(found != joints.end())
-      return found->second;
-
-    vertex v;
-    v->pos = imageToWorld(Point2f(pos) - Point2f(.5, .5));
-    v->nrml = Point3f(0, 0, 1);
-    v->label = -1;
-    v->type = 'j';
-    S.insert(v);
-    joints[pos] = v;
-    inv_joints[v] = pos;
-    return v;
-  }
-
-  // See description of the next function to know what is happening
-  void moveAlong(Point2i& cur, Point4us& cells, CORNER_POSITION c)
-  {
-    switch(c) {
-    case TOP_LEFT:
-      cur.y()++;
-      cells[BOTTOM_LEFT] = cells[TOP_LEFT];
-      cells[BOTTOM_RIGHT] = cells[TOP_RIGHT];
-      cells[TOP_LEFT] = topLeft(cur);
-      cells[TOP_RIGHT] = topRight(cur);
-      break;
-    case TOP_RIGHT:
-      cur.x()++;
-      cells[TOP_LEFT] = cells[TOP_RIGHT];
-      cells[BOTTOM_LEFT] = cells[BOTTOM_RIGHT];
-      cells[TOP_RIGHT] = topRight(cur);
-      cells[BOTTOM_RIGHT] = bottomRight(cur);
-      break;
-    case BOTTOM_RIGHT:
-      cur.y()--;
-      cells[TOP_LEFT] = cells[BOTTOM_LEFT];
-      cells[TOP_RIGHT] = cells[BOTTOM_RIGHT];
-      cells[BOTTOM_LEFT] = bottomLeft(cur);
-      cells[BOTTOM_RIGHT] = bottomRight(cur);
-      break;
-    case BOTTOM_LEFT:
-      cur.x()--;
-      cells[TOP_RIGHT] = cells[TOP_LEFT];
-      cells[BOTTOM_RIGHT] = cells[BOTTOM_LEFT];
-      cells[TOP_LEFT] = topLeft(cur);
-      cells[BOTTOM_LEFT] = bottomLeft(cur);
-      break;
-    default:
-      throw QString("Programming error: invalid corner position in moveAlong");
+    
+    enum CORNER_POSITION { BOTTOM_LEFT = 0, BOTTOM_RIGHT = 1, TOP_RIGHT = 2, TOP_LEFT = 3, INVALID_POS = -1 };
+    
+    CORNER_POSITION turn_cw(CORNER_POSITION c)
+    {
+      switch(c) {
+      case BOTTOM_LEFT:
+        return TOP_LEFT;
+      case BOTTOM_RIGHT:
+        return BOTTOM_LEFT;
+      case TOP_RIGHT:
+        return BOTTOM_RIGHT;
+      case TOP_LEFT:
+        return TOP_RIGHT;
+      default:
+        throw QString("Programming error: invalid corner position in turn_cw");
+      }
     }
-  }
-
-  Edge makeEdge(Point2i start, Point4us cells, CORNER_POSITION cell_pos)
-  {
-    ushort toFollow = cells[cell_pos];
-    ushort opposite = cells[turn_cw(cell_pos)];
-    Edge e;
-    e.cells = Point2u(toFollow, opposite);
-    e.shape.push_back(joint(start));
-    size_t max = size.x() * size.y();     // We can never make more iterations than that!
-
-    /*  The idea is to follow the edge going counter-clockwise always!
+    
+    CORNER_POSITION turn_ccw(CORNER_POSITION c)
+    {
+      switch(c) {
+      case BOTTOM_LEFT:
+        return BOTTOM_RIGHT;
+      case BOTTOM_RIGHT:
+        return TOP_RIGHT;
+      case TOP_RIGHT:
+        return TOP_LEFT;
+      case TOP_LEFT:
+        return BOTTOM_LEFT;
+      default:
+        throw QString("Programming error: invalid corner position in turn_cw");
+      }
+    }
+    
+    typedef util::Vector<4, ushort> Point4us;
+    
+    /*
+     * Read-only 2D data holder with helper methods
      *
-     *  For this, we can see that we have four cases for the movement, depending on the position of the current
-     *  pixel with respect to the current corner.
+     * The corners are named after the pixel on their top-right. So the corner (x,y) is such that:
      *
-     *  Movement cases: The current cell is marked with 'X'.
-     *  Then, if 'F' has the current label, it will be the next position.
-     *  If not, and the 'S' has the current label, it will be the next position.
-     *  Otherwise, the current cell is the current position.
+     *    (x-1,y)  |  (x,y)
+     *   ----------*--------
+     *   (x-1,y-1) | (x,y-1)
      *
-     *  The current corner is marked with '#' and the next corner with '^'
-     *
-     *  Top-left -- move up
-     *
-     *  ·-·-·
-     *  |S|F|
-     *  ·-^-·
-     *  |X| |
-     *  ·-#-·
-     *
-     *  Top-Right -- move right
-     *
-     *  ·-·-·
-     *  |X|S|
-     *  #-^-·
-     *  | |F|
-     *  ·-·-·
-     *
-     *  Bottom-Right -- move down
-     *
-     *  ·-#-·
-     *  | |X|
-     *  ·-^-·
-     *  |F|S|
-     *  ·-·-·
-     *
-     *  Bottom-Left -- move left
-     *
-     *  ·-·-·
-     *  |F| |
-     *  ·-^-#
-     *  |S|X|
-     *  ·-·-·
-     *
-     *  Note that:
-     *   - 'S' has the same position relative to '^' than 'X' to '#'
-     *   - 'F' is the next position clockwise
-     *   - 'X' the next position counter-clockwise
-     *   - if the cell clockwise from the new one is not of the opposite color, this is the end
      */
-    Point2i prev = start;
-    Point2i cur = start;
-    bool foundEnd = false;
-    for(size_t cnt = 0; not foundEnd and cnt < max; ++cnt) {
-      moveAlong(cur, cells, cell_pos);
-
-      if(cells[cell_pos] == toFollow) {
-        CORNER_POSITION next_pos = turn_cw(cell_pos);
-        if(cells[next_pos] == toFollow)
-          cell_pos = next_pos;
-        else if(cells[next_pos] != opposite)
-          foundEnd = true;
-      } else if(cells[cell_pos] != opposite)
-        foundEnd = true;
-      else
-        cell_pos = turn_ccw(cell_pos);         // Move back to the previous position
-
-      if(minLength >= 0 and normsq(multiply(step, Point2f(cur) - Point2f(prev))) >= minLengthSq) {
-        vertex j;
-        j->type = 'j';
-        j->label = -1;
-        j->pos = imageToWorld(Point2f(cur) - Point2f(.5, .5));
-        j->nrml = Point3f(0, 0, 1);
-        e.shape.push_back(j);
-        prev = cur;
+    struct Data2D {
+    
+      // Structure holding an edge with its shape which cells its separate
+      struct Edge {
+        Point2u cells;                 // Cells the edge separate
+        std::vector<vertex> shape;     // The edge itself, including end points
+      };
+    
+      Data2D(const Store* store, vvgraph& S_, uint zslice, float ml)
+        : data(store->data())
+        , S(S_)
+        , minLength(ml)
+        , minLengthSq(ml * ml)
+        , centers(65536, Point3f())
+        , sizes(65536, 0u)
+        , cells(65536, vertex(0))
+        , cell_joints(65536)
+      {
+        const Stack* stk = store->stack();
+        size = Point2u(stk->size());
+        step = Point2f(stk->step());
+        origin = stk->origin() + 0.5 * stk->step() + zslice * stk->step().z();
+        offset = zslice * step.x() * step.y();
+        xdir = Point3f(step.x(), 0, 0);
+        ydir = Point3f(0, step.y(), 0);
+        pixelArea = step.x() * step.y();
       }
+    
+      ushort operator()(int x, int y) const
+      {
+        if(x >= 0 and y >= 0 and x < (int)size.x() and y < (int)size.y())
+          return data[y * size.x() + x + offset];
+        return 0;
+      }
+    
+      // Return the position at the bottom left of the (x,y) corner
+      ushort bottomLeft(int x, int y) const {
+        return (*this)(x - 1, y - 1);
+      }
+      ushort bottomLeft(Point2i pos) const {
+        return bottomLeft(pos.x(), pos.y());
+      }
+    
+      // Return the position at the bottom right of the (x,y) corner
+      ushort bottomRight(int x, int y) const {
+        return (*this)(x, y - 1);
+      }
+      ushort bottomRight(Point2i pos) const {
+        return bottomRight(pos.x(), pos.y());
+      }
+    
+      // Return the position at the top left of the (x,y) corner
+      ushort topLeft(int x, int y) const {
+        return (*this)(x - 1, y);
+      }
+      ushort topLeft(Point2i pos) const {
+        return topLeft(pos.x(), pos.y());
+      }
+    
+      // Return the position at the top right of the (x,y) corner
+      ushort topRight(int x, int y) const {
+        return (*this)(x, y);
+      }
+      ushort topRight(Point2i pos) const {
+        return topRight(pos.x(), pos.y());
+      }
+    
+      /*
+       * Return the cells around a corner as:
+       *
+       *  3 | 2
+       *  --+--
+       *  0 | 1
+       *
+       * which correspond to the CORNER_POSITION enumeration.
+       */
+      Point4us cornerCells(int x, int y) const
+      {
+        return Point4us(bottomLeft(x, y), bottomRight(x, y), topRight(x, y), topLeft(x, y));
+      }
+    
+      template <typename T> Point3f imageToWorld(T x, T y) const {
+        return origin + float(x) * xdir + float(y) * ydir;
+      }
+    
+      template <typename T> Point3f imageToWorld(const util::Vector<2, T>& pos) const {
+        return imageToWorld(pos.x(), pos.y());
+      }
+    
+      const HVecUS& data;
+      vvgraph& S;
+      size_t offset;
+      Point2u size;
+      Point2f step;
+      Point3f origin;
+      Point3f xdir;
+      Point3f ydir;
+      float minLength, minLengthSq;
+      float pixelArea;
+    
+      /* Find edges in the store, starting from a given point:
+       * The second parameter is the identity of the cells as:
+       *
+       *   3 | 2
+       *   --+--
+       *   0 | 1
+       *
+       * which correspond to the CORNER_POSITION enumeration.
+       *
+       * Warning: The function should only be called if there are at least three different cells around.
+       */
+      void findEdges(Point2u startCorner, Point4us cells)
+      {
+        if((cells[TOP_RIGHT] == cells[BOTTOM_LEFT])or (cells[TOP_LEFT] == cells[BOTTOM_RIGHT])) {
+          ushort c = (cells[TOP_RIGHT] == cells[BOTTOM_LEFT] ? cells[TOP_RIGHT] : cells[TOP_LEFT]);
+          QString errorMsg("Error at position (%1,%2): the cell %3 appears in two opposite corners.");
+          throw errorMsg.arg(startCorner.x()).arg(startCorner.y()).arg(c);
+        }
+    
+        vertex v = joint(startCorner);
+        std::vector<size_t>& known_edges = joint_edges[v];
+        size_t prev_lab = cells[3];
+        for(int i = 0; i < 4; ++i) {
+          if(cells[i] != prev_lab) {
+            cell_joints[cells[i]].insert(v);
+            cell_joints[prev_lab].insert(v);
+    
+            // Check if we already know about the edge
+            Point2u pc = Point2u(cells[i], prev_lab);
+            Point2u opc = Point2u(prev_lab, cells[i]);
+            bool found = false;
+            for(size_t j = 0; j < known_edges.size(); ++j) {
+              Point2u kc = edges[known_edges[j]].cells;
+              if(kc == pc or kc == opc) {
+                found = true;
+                break;
+              }
+            }
+            if(not found) {
+              Edge e = makeEdge(startCorner, cells, CORNER_POSITION(i));
+              size_t new_edge = edges.size();
+              edges.push_back(e);
+              known_edges.push_back(new_edge);
+              joint_edges[e.shape.back()].push_back(new_edge);           // add to the other end
+    
+              /*
+               * Information::out << "Created edge from " << e.shape.front().num() << " to "
+               *  << e.shape.back().num() << " between cell " << cells[i] << " and cell "
+               *  << cells[turn_cw(CORNER_POSITION(i))] << endl;
+               */
+            }
+          }
+          prev_lab = cells[i];
+        }
+      }
+    
+      vertex joint(Point2u pos)
+      {
+        std::map<Point2u, vertex>::const_iterator found = joints.find(pos);
+        if(found != joints.end())
+          return found->second;
+    
+        vertex v;
+        v->pos = imageToWorld(Point2f(pos) - Point2f(.5, .5));
+        v->nrml = Point3f(0, 0, 1);
+        v->label = -1;
+        v->type = 'j';
+        S.insert(v);
+        joints[pos] = v;
+        inv_joints[v] = pos;
+        return v;
+      }
+    
+      // See description of the next function to know what is happening
+      void moveAlong(Point2i& cur, Point4us& cells, CORNER_POSITION c)
+      {
+        switch(c) {
+        case TOP_LEFT:
+          cur.y()++;
+          cells[BOTTOM_LEFT] = cells[TOP_LEFT];
+          cells[BOTTOM_RIGHT] = cells[TOP_RIGHT];
+          cells[TOP_LEFT] = topLeft(cur);
+          cells[TOP_RIGHT] = topRight(cur);
+          break;
+        case TOP_RIGHT:
+          cur.x()++;
+          cells[TOP_LEFT] = cells[TOP_RIGHT];
+          cells[BOTTOM_LEFT] = cells[BOTTOM_RIGHT];
+          cells[TOP_RIGHT] = topRight(cur);
+          cells[BOTTOM_RIGHT] = bottomRight(cur);
+          break;
+        case BOTTOM_RIGHT:
+          cur.y()--;
+          cells[TOP_LEFT] = cells[BOTTOM_LEFT];
+          cells[TOP_RIGHT] = cells[BOTTOM_RIGHT];
+          cells[BOTTOM_LEFT] = bottomLeft(cur);
+          cells[BOTTOM_RIGHT] = bottomRight(cur);
+          break;
+        case BOTTOM_LEFT:
+          cur.x()--;
+          cells[TOP_RIGHT] = cells[TOP_LEFT];
+          cells[BOTTOM_RIGHT] = cells[BOTTOM_LEFT];
+          cells[TOP_LEFT] = topLeft(cur);
+          cells[BOTTOM_LEFT] = bottomLeft(cur);
+          break;
+        default:
+          throw QString("Programming error: invalid corner position in moveAlong");
+        }
+      }
+    
+      Edge makeEdge(Point2i start, Point4us cells, CORNER_POSITION cell_pos)
+      {
+        ushort toFollow = cells[cell_pos];
+        ushort opposite = cells[turn_cw(cell_pos)];
+        Edge e;
+        e.cells = Point2u(toFollow, opposite);
+        e.shape.push_back(joint(start));
+        size_t max = size.x() * size.y();     // We can never make more iterations than that!
+    
+        /*  The idea is to follow the edge going counter-clockwise always!
+         *
+         *  For this, we can see that we have four cases for the movement, depending on the position of the current
+         *  pixel with respect to the current corner.
+         *
+         *  Movement cases: The current cell is marked with 'X'.
+         *  Then, if 'F' has the current label, it will be the next position.
+         *  If not, and the 'S' has the current label, it will be the next position.
+         *  Otherwise, the current cell is the current position.
+         *
+         *  The current corner is marked with '#' and the next corner with '^'
+         *
+         *  Top-left -- move up
+         *
+         *  ·-·-·
+         *  |S|F|
+         *  ·-^-·
+         *  |X| |
+         *  ·-#-·
+         *
+         *  Top-Right -- move right
+         *
+         *  ·-·-·
+         *  |X|S|
+         *  #-^-·
+         *  | |F|
+         *  ·-·-·
+         *
+         *  Bottom-Right -- move down
+         *
+         *  ·-#-·
+         *  | |X|
+         *  ·-^-·
+         *  |F|S|
+         *  ·-·-·
+         *
+         *  Bottom-Left -- move left
+         *
+         *  ·-·-·
+         *  |F| |
+         *  ·-^-#
+         *  |S|X|
+         *  ·-·-·
+         *
+         *  Note that:
+         *   - 'S' has the same position relative to '^' than 'X' to '#'
+         *   - 'F' is the next position clockwise
+         *   - 'X' the next position counter-clockwise
+         *   - if the cell clockwise from the new one is not of the opposite color, this is the end
+         */
+        Point2i prev = start;
+        Point2i cur = start;
+        bool foundEnd = false;
+        for(size_t cnt = 0; not foundEnd and cnt < max; ++cnt) {
+          moveAlong(cur, cells, cell_pos);
+    
+          if(cells[cell_pos] == toFollow) {
+            CORNER_POSITION next_pos = turn_cw(cell_pos);
+            if(cells[next_pos] == toFollow)
+              cell_pos = next_pos;
+            else if(cells[next_pos] != opposite)
+              foundEnd = true;
+          } else if(cells[cell_pos] != opposite)
+            foundEnd = true;
+          else
+            cell_pos = turn_ccw(cell_pos);         // Move back to the previous position
+    
+          if(minLength >= 0 and normsq(multiply(step, Point2f(cur) - Point2f(prev))) >= minLengthSq) {
+            vertex j;
+            j->type = 'j';
+            j->label = -1;
+            j->pos = imageToWorld(Point2f(cur) - Point2f(.5, .5));
+            j->nrml = Point3f(0, 0, 1);
+            e.shape.push_back(j);
+            prev = cur;
+          }
+        }
+    
+        if(!foundEnd) {
+          QString msg("Couldn't find the end of the edge between %1 and %2, starting from (%3,%4) and arrived at "
+                      "(%5,%6)");
+          throw msg.arg(toFollow).arg(opposite).arg(prev.x()).arg(prev.y()).arg(cur.x()).arg(cur.y());
+        }
+    
+        if(minLength >= 0 and normsq(multiply(step, Point2f(cur) - Point2f(prev))) < 0.25 * minLengthSq) {
+          if(e.shape.size() > 1)       // never remove the first vertex!
+            e.shape.pop_back();
+        }
+    
+        e.shape.push_back(joint(cur));
+        // Information::out << "found edge" << endl;
+    
+        // Add the inside vertices
+        for(size_t i = 0; i < e.shape.size(); ++i)
+          S.insert(e.shape[i]);
+    
+        return e;
+      }
+    
+      // Useful data structures
+    
+      std::vector<Point3f> centers;                         // Center of the cells by label
+      std::vector<size_t> sizes;                            // Size of the cells in pixles by label
+      std::vector<vertex> cells;                            // Vertex representing the cells by label
+      std::vector<util::set_vector<vertex> > cell_joints;   // List of joints for each cell
+    
+      std::map<Point2u, vertex> joints;                     // Vertex representing each joint
+      std::map<vertex, Point2u> inv_joints;                 // Reverse the joint map
+      std::map<vertex, std::vector<size_t> > joint_edges;   // Give the list of edges for a vertex
+      std::map<Point2u, Point4i> oriented_cells;            // Ordered list of cells around a corner
+      std::vector<Edge> edges;                              // List of edges
+    
+    private: // Preventing copy
+      Data2D(const Data2D&);
+      Data2D& operator=(const Data2D&);
+    };
+    
+    Point4i oriented4Cells(int c0, int c1, int c2, int c3)
+    {
+      if(c0 <= c1) {
+        if(c0 <= c2) {
+          if(c0 <= c3)
+            return Point4i(c0, c1, c2, c3);
+        } else if(c2 <= c3)
+          return Point4i(c2, c3, c0, c1);
+      } else if(c1 <= c2) {
+        if(c1 <= c3)
+          return Point4i(c1, c2, c3, c0);
+      } else if(c2 <= c3)
+        return Point4i(c2, c3, c0, c1);
+      return Point4i(c3, c0, c1, c2);
     }
-
-    if(!foundEnd) {
-      QString msg("Couldn't find the end of the edge between %1 and %2, starting from (%3,%4) and arrived at "
-                  "(%5,%6)");
-      throw msg.arg(toFollow).arg(opposite).arg(prev.x()).arg(prev.y()).arg(cur.x()).arg(cur.y());
+    
+    Point4i oriented3Cells(int c0, int c1, int c2)
+    {
+      if(c0 <= c1 and c0 <= c2)
+        return Point4i(c0, c1, c2, -1);
+      if(c1 <= c2)
+        return Point4i(c1, c2, c0, -1);
+      return Point4i(c2, c0, c1, -1);
     }
-
-    if(minLength >= 0 and normsq(multiply(step, Point2f(cur) - Point2f(prev))) < 0.25 * minLengthSq) {
-      if(e.shape.size() > 1)       // never remove the first vertex!
-        e.shape.pop_back();
+    
+    void insertLabel(std::vector<ushort>& labels, ushort label)
+    {
+      bool found = false;
+      for(size_t i = 0; i < labels.size(); ++i)
+        if(labels[i] == label) {
+          found = true;
+          break;
+        }
+      if(!found)
+        labels.push_back(label);
     }
-
-    e.shape.push_back(joint(cur));
-    // Information::out << "found edge" << endl;
-
-    // Add the inside vertices
-    for(size_t i = 0; i < e.shape.size(); ++i)
-      S.insert(e.shape[i]);
-
-    return e;
+    
+    template <typename Iterator>
+    bool insertInCell(vvgraph& S, vertex c, vertex j, vertex jn, Iterator first, Iterator last,
+                      util::set_vector<vertex>& js)
+    {
+      bool has_looped = false;
+      if(js.count(jn)) {
+        js.erase(jn);
+        S.spliceAfter(c, j, jn);
+      } else
+        has_looped = true;
+      ++first;
+      --last;
+      for(Iterator it = first; it != last; ++it)
+        S.spliceBefore(c, jn, *it);
+      return has_looped;
+    }
   }
 
-  // Useful data structures
-
-  std::vector<Point3f> centers;                         // Center of the cells by label
-  std::vector<size_t> sizes;                            // Size of the cells in pixles by label
-  std::vector<vertex> cells;                            // Vertex representing the cells by label
-  std::vector<util::set_vector<vertex> > cell_joints;   // List of joints for each cell
-
-  std::map<Point2u, vertex> joints;                     // Vertex representing each joint
-  std::map<vertex, Point2u> inv_joints;                 // Reverse the joint map
-  std::map<vertex, std::vector<size_t> > joint_edges;   // Give the list of edges for a vertex
-  std::map<Point2u, Point4i> oriented_cells;            // Ordered list of cells around a corner
-  std::vector<Edge> edges;                              // List of edges
-
-private: // Preventing copy
-  Data2D(const Data2D&);
-  Data2D& operator=(const Data2D&);
-};
-
-Point4i oriented4Cells(int c0, int c1, int c2, int c3)
-{
-  if(c0 <= c1) {
-    if(c0 <= c2) {
-      if(c0 <= c3)
-        return Point4i(c0, c1, c2, c3);
-    } else if(c2 <= c3)
-      return Point4i(c2, c3, c0, c1);
-  } else if(c1 <= c2) {
-    if(c1 <= c3)
-      return Point4i(c1, c2, c3, c0);
-  } else if(c2 <= c3)
-    return Point4i(c2, c3, c0, c1);
-  return Point4i(c3, c0, c1, c2);
-}
-
-Point4i oriented3Cells(int c0, int c1, int c2)
-{
-  if(c0 <= c1 and c0 <= c2)
-    return Point4i(c0, c1, c2, -1);
-  if(c1 <= c2)
-    return Point4i(c1, c2, c0, -1);
-  return Point4i(c2, c0, c1, -1);
-}
-
-void insertLabel(std::vector<ushort>& labels, ushort label)
-{
-  bool found = false;
-  for(size_t i = 0; i < labels.size(); ++i)
-    if(labels[i] == label) {
-      found = true;
-      break;
-    }
-  if(!found)
-    labels.push_back(label);
-}
-
-template <typename Iterator>
-bool insertInCell(vvgraph& S, vertex c, vertex j, vertex jn, Iterator first, Iterator last,
-                  util::set_vector<vertex>& js)
-{
-  bool has_looped = false;
-  if(js.count(jn)) {
-    js.erase(jn);
-    S.spliceAfter(c, j, jn);
-  } else
-    has_looped = true;
-  ++first;
-  --last;
-  for(Iterator it = first; it != last; ++it)
-    S.spliceBefore(c, jn, *it);
-  return has_looped;
-}
-} // namespace
-} // namespace process
-} // namespace mgx
+}}
Index: PythonProcess.cpp
===================================================================
--- PythonProcess.cpp	(revision 1255)
+++ PythonProcess.cpp	(revision 1256)
@@ -10,510 +10,506 @@
 #include <stdio.h>
 #include <structmember.h>
 
-namespace mgx {
-namespace process {
+#pragma GCC diagnostic ignored "-Wwrite-strings"
 
-static PyObject* printFactory(PyObject* self)
+namespace mgx { namespace process 
 {
-  mgx_Factory& factory = reinterpret_cast<mgx_Factory_Python*>(self)->intern;
-  QString type = factory.type;
-  QStringList procs = listProcesses(type);
-  forall(QString& p, procs)
-    p = QString("'%1'").arg(p);
-
-  QString result = QString("<%1 factory - %2>").arg(type, procs.join(", "));
-  return Py_BuildValue("s", result.toAscii().data());
-}
-
-static PyObject* showProc(PyObject* self)
-{
-  mgx_Process& process = reinterpret_cast<mgx_Process_Python*>(self)->intern;
-  QString type = process.type;
-  QString name = process.name;
-  QString result = QString("%1.%2[%3]").arg(type).arg(name).arg(process.numParms);
-  return Py_BuildValue("s", result.toAscii().data());
-}
-
-static PyObject* runProcess(PyObject* self, PyObject* args, PyObject*)
-{
-  mgx_Process& proc = reinterpret_cast<mgx_Process_Python*>(self)->intern;
-  if(not proc.process) {
-    PyErr_SetString(
-      PyExc_ValueError,
-      "You can't use this process for launching. It hasn't been created using of the process repository.");
-    return NULL;
+  static PyObject* printFactory(PyObject* self)
+  {
+    mgx_Factory& factory = reinterpret_cast<mgx_Factory_Python*>(self)->intern;
+    QString type = factory.type;
+    QStringList procs = listProcesses(type);
+    forall(QString& p, procs)
+      p = QString("'%1'").arg(p);
+  
+    QString result = QString("<%1 factory - %2>").arg(type, procs.join(", "));
+    return Py_BuildValue("s", result.toAscii().data());
   }
-  Py_ssize_t s = PyTuple_Size(args);
-  int expected = proc.numParms;
-  if(s < expected) {
-    QString err = (QString("Argument count mismatch for process %1.%2:\n  Expected: %3\n  Provided: %4")
-                   .arg(proc.type)
-                   .arg(proc.name)
-                   .arg(expected)
-                   .arg(s));
-    PyErr_SetString(PyExc_ValueError, err.toAscii().data());
-    return NULL;
+  
+  static PyObject* showProc(PyObject* self)
+  {
+    mgx_Process& process = reinterpret_cast<mgx_Process_Python*>(self)->intern;
+    QString type = process.type;
+    QString name = process.name;
+    QString result = QString("%1.%2[%3]").arg(type).arg(name).arg(process.numParms);
+    return Py_BuildValue("s", result.toAscii().data());
   }
-  QStringList parms;
-  bool parsing_strings = true;
-  for(int i = 0; i < s; ++i) {
-    PyObject* obj = PyTuple_GetItem(args, i);
-    if(obj) {
-      if(PyFloat_Check(obj)) {
-        parsing_strings = false;
-        float f = (float)PyFloat_AsDouble(obj);
-        if(PyErr_Occurred())
-          return NULL;
-        parms << QString::number(f);
-      } else if(PyInt_Check(obj)) {
-        parsing_strings = false;
-        long l = PyInt_AsLong(obj);
-        if(l == -1 and PyErr_Occurred())
-          return NULL;
-        float f = (float)l;
-        parms << QString::number(f);
-      } else {
-        if(!parsing_strings) {
-          PyErr_SetString(PyExc_ValueError,
-                          "Error, string arguments should be put first, and then floating points ones");
-          return NULL;
+  
+  static PyObject* runProcess(PyObject* self, PyObject* args, PyObject*)
+  {
+    mgx_Process& proc = reinterpret_cast<mgx_Process_Python*>(self)->intern;
+    if(not proc.process) {
+      PyErr_SetString(
+        PyExc_ValueError,
+        "You can't use this process for launching. It hasn't been created using of the process repository.");
+      return NULL;
+    }
+    Py_ssize_t s = PyTuple_Size(args);
+    int expected = proc.numParms;
+    if(s < expected) {
+      QString err = (QString("Argument count mismatch for process %1.%2:\n  Expected: %3\n  Provided: %4")
+                    .arg(proc.type).arg(proc.name).arg(expected).arg(s));
+      PyErr_SetString(PyExc_ValueError, err.toAscii().data());
+      return NULL;
+    }
+    QStringList parms;
+    bool parsing_strings = true;
+    for(int i = 0; i < s; ++i) {
+      PyObject* obj = PyTuple_GetItem(args, i);
+      if(obj) {
+        if(PyFloat_Check(obj)) {
+          parsing_strings = false;
+          float f = (float)PyFloat_AsDouble(obj);
+          if(PyErr_Occurred())
+            return NULL;
+          parms << QString::number(f);
+        } else if(PyInt_Check(obj)) {
+          parsing_strings = false;
+          long l = PyInt_AsLong(obj);
+          if(l == -1 and PyErr_Occurred())
+            return NULL;
+          float f = (float)l;
+          parms << QString::number(f);
+        } else {
+          if(!parsing_strings) {
+            PyErr_SetString(PyExc_ValueError,
+                            "Error, string arguments should be put first, and then floating points ones");
+            return NULL;
+          }
+          PyObject* str = PyObject_Str(obj);
+          if(!str)
+            return NULL;
+          char* val = PyString_AsString(str);
+          if(!val)
+            return NULL;
+          parms << QString::fromLocal8Bit(val);
+          Py_DECREF(str);
         }
-        PyObject* str = PyObject_Str(obj);
-        if(!str)
-          return NULL;
-        char* val = PyString_AsString(str);
-        if(!val)
-          return NULL;
-        parms << QString::fromLocal8Bit(val);
-        Py_DECREF(str);
-      }
-    } else
+      } else
+        return NULL;
+    }
+    if(parms.size() < proc.numParms) {
+      QString err = QString("Error, the process expect at least %1 strings, and only %2 where given")
+        .arg(proc.numParms).arg(parms.size());
+      PyErr_SetString(PyExc_ValueError, err.toLocal8Bit().data());
       return NULL;
+    }
+    if(!proc.process->RunProcess(proc.type, proc.name, parms)) {
+      PyErr_SetString(PyExc_RuntimeError, proc.process->errorMessage().toLocal8Bit().data());
+      return NULL;
+    }
+    Py_INCREF(Py_None);
+    return Py_None;
   }
-  if(parms.size() < proc.numParms) {
-    QString err = QString("Error, the process expect at least %1 strings, and only %2 where given")
-      .arg(proc.numParms)
-      .arg(parms.size());
-    PyErr_SetString(PyExc_ValueError, err.toLocal8Bit().data());
-    return NULL;
+  
+  static void Factory_dealloc(mgx_Factory_Python* factory)
+  {
+    Py_XDECREF(factory->fact_dict);
+    factory->fact_dict = 0;
+    factory->intern.~mgx_Factory();
+    factory->ob_type->tp_free((PyObject*)factory);
   }
-  if(!proc.process->RunProcess(proc.type, proc.name, parms)) {
-    PyErr_SetString(PyExc_RuntimeError, proc.process->errorMessage().toLocal8Bit().data());
-    return NULL;
+  
+  static void Process_dealloc(mgx_Process_Python* proc)
+  {
+    Py_XDECREF(proc->descr);
+    proc->descr = 0;
+    proc->intern.~mgx_Process();
+    proc->ob_type->tp_free((PyObject*)proc);
   }
-  Py_INCREF(Py_None);
-  return Py_None;
-}
-
-static void Factory_dealloc(mgx_Factory_Python* factory)
-{
-  Py_XDECREF(factory->fact_dict);
-  factory->fact_dict = 0;
-  factory->intern.~mgx_Factory();
-  factory->ob_type->tp_free((PyObject*)factory);
-}
-
-static void Process_dealloc(mgx_Process_Python* proc)
-{
-  Py_XDECREF(proc->descr);
-  proc->descr = 0;
-  proc->intern.~mgx_Process();
-  proc->ob_type->tp_free((PyObject*)proc);
-}
-
-static PyMethodDef module_methods[] = { { 0, 0, 0, 0 } };
-
-static int mgx_Factory_init(mgx_Factory_Python* self, PyObject* args, PyObject*)
-{
-  const char* type_name;
-
-  if(!PyArg_ParseTuple(args, "s", &type_name))
-    return -1;
-
-  QString type = QString::fromAscii(type_name);
-  if(!validProcessType(type)) {
-    PyErr_SetString(PyExc_NameError, "No process factory exist with this name");
-    return -1;
+  
+  static PyMethodDef module_methods[] = { { 0, 0, 0, 0 } };
+  
+  static int mgx_Factory_init(mgx_Factory_Python* self, PyObject* args, PyObject*)
+  {
+    const char* type_name;
+  
+    if(!PyArg_ParseTuple(args, "s", &type_name))
+      return -1;
+  
+    QString type = QString::fromAscii(type_name);
+    if(!validProcessType(type)) {
+      PyErr_SetString(PyExc_NameError, "No process factory exist with this name");
+      return -1;
+    }
+  
+    PyObject* f_dict = PyDict_New();
+  
+    self->fact_dict = f_dict;
+    self->intern.type = type;
+    self->intern.process = 0;
+  
+    return 0;
   }
-
-  PyObject* f_dict = PyDict_New();
-
-  self->fact_dict = f_dict;
-  self->intern.type = type;
-  self->intern.process = 0;
-
-  return 0;
-}
-
-static int mgx_Process_init(mgx_Process_Python* self, PyObject* args, PyObject*)
-{
-  const char* type_name, *proc_name;
-
-  if(!PyArg_ParseTuple(args, "ss", &type_name, &proc_name))
-    return -1;
-
-  QString type = QString::fromAscii(type_name);
-  if(!validProcessType(type)) {
-    PyErr_SetString(PyExc_NameError, "No process factory exist with this name");
-    return -1;
+  
+  static int mgx_Process_init(mgx_Process_Python* self, PyObject* args, PyObject*)
+  {
+    const char* type_name, *proc_name;
+  
+    if(!PyArg_ParseTuple(args, "ss", &type_name, &proc_name))
+      return -1;
+  
+    QString type = QString::fromAscii(type_name);
+    if(!validProcessType(type)) {
+      PyErr_SetString(PyExc_NameError, "No process factory exist with this name");
+      return -1;
+    }
+  
+    QString name = QString::fromAscii(proc_name);
+    name.replace('_', " ");
+  
+    BaseProcessDefinition* def = getBaseProcessDefinition(type, name);
+    if(not def) {
+      PyErr_SetString(PyExc_NameError, "No such process");
+      return -1;
+    }
+    self->intern.type = type;
+    self->intern.name = name;
+    self->intern.numParms = def->parmNames.size();
+    // self->intern.nbNamedValues = def->nbNamedValues;
+    self->intern.process = 0;
+  
+    QStringList arguments, defaults;
+    forall(const QString& arg, def->parmNames)
+      arguments << QString("'%1'").arg(arg);
+    forall(const QString& str, def->parms)
+      defaults << QString("'%1'").arg(str);
+  
+    QString descr = (QString("%1\nParameters: %2\nDefaults: %3").arg(def->description).arg(arguments.join(", ")).arg(
+                       defaults.join(", ")));
+    PyObject* doc = PyString_FromString(descr.toLocal8Bit().data());
+    self->descr = doc;
+  
+    return 0;
   }
-
-  QString name = QString::fromAscii(proc_name);
-  name.replace('_', " ");
-
-  BaseProcessDefinition* def = getBaseProcessDefinition(type, name);
-  if(not def) {
-    PyErr_SetString(PyExc_NameError, "No such process");
-    return -1;
+  
+  static PyObject* mgx_Factory_new(PyTypeObject* type, PyObject*, PyObject*)
+  {
+    mgx_Factory_Python* self;
+  
+    self = (mgx_Factory_Python*)type->tp_alloc(type, 0);
+    if(self != NULL) {
+      new (&self->intern)mgx_Factory();
+    }
+  
+    return (PyObject*)self;
   }
-  self->intern.type = type;
-  self->intern.name = name;
-  self->intern.numParms = def->parmNames.size();
-  // self->intern.nbNamedValues = def->nbNamedValues;
-  self->intern.process = 0;
-
-  QStringList arguments, defaults;
-  forall(const QString& arg, def->parmNames)
-    arguments << QString("'%1'").arg(arg);
-  forall(const QString& str, def->parms)
-    defaults << QString("'%1'").arg(str);
-
-  QString descr = (QString("%1\nParameters: %2\nDefaults: %3").arg(def->description).arg(arguments.join(", ")).arg(
-                     defaults.join(", ")));
-  PyObject* doc = PyString_FromString(descr.toLocal8Bit().data());
-  self->descr = doc;
-
-  return 0;
-}
-
-static PyObject* mgx_Factory_new(PyTypeObject* type, PyObject*, PyObject*)
-{
-  mgx_Factory_Python* self;
-
-  self = (mgx_Factory_Python*)type->tp_alloc(type, 0);
-  if(self != NULL) {
-    new (&self->intern)mgx_Factory();
+  
+  static PyObject* mgx_Process_new(PyTypeObject* type, PyObject*, PyObject*)
+  {
+    mgx_Process_Python* self;
+  
+    self = (mgx_Process_Python*)type->tp_alloc(type, 0);
+    if(self != NULL) {
+      new (&self->intern)mgx_Process();
+    }
+  
+    return (PyObject*)self;
   }
-
-  return (PyObject*)self;
-}
-
-static PyObject* mgx_Process_new(PyTypeObject* type, PyObject*, PyObject*)
-{
-  mgx_Process_Python* self;
-
-  self = (mgx_Process_Python*)type->tp_alloc(type, 0);
-  if(self != NULL) {
-    new (&self->intern)mgx_Process();
+  
+  static PyObject* fact_getdict(mgx_Factory_Python* self)
+  {
+    if(self->fact_dict == NULL) {
+      self->fact_dict = PyDict_New();
+      if(self->fact_dict == NULL)
+        return NULL;
+    }
+    Py_INCREF(self->fact_dict);
+    return self->fact_dict;
   }
-
-  return (PyObject*)self;
-}
-
-static PyObject* fact_getdict(mgx_Factory_Python* self)
-{
-  if(self->fact_dict == NULL) {
-    self->fact_dict = PyDict_New();
-    if(self->fact_dict == NULL)
-      return NULL;
+  
+  static PyGetSetDef fact_getsetlist[] = { { "__dict__", (getter)fact_getdict, NULL, "Dictionnary" }, { NULL } };
+  
+  PyTypeObject factory_type = { PyObject_HEAD_INIT(NULL) 0,                /*ob_size*/
+                                "mgx.Factory",                            /*tp_name*/
+                                sizeof(mgx_Factory_Python),               /*tp_basicsize*/
+                                0,                                        /*tp_itemsize*/
+                                (destructor)Factory_dealloc,              /*tp_dealloc*/
+                                0,                                        /*tp_print*/
+                                0,                                        /*tp_getattr*/
+                                0,                                        /*tp_setattr*/
+                                0,                                        /*tp_compare*/
+                                0,                                        /*tp_repr*/
+                                0,                                        /*tp_as_number*/
+                                0,                                        /*tp_as_sequence*/
+                                0,                                        /*tp_as_mapping*/
+                                0,                                        /*tp_hash */
+                                0,                                        /*tp_call*/
+                                printFactory,                             /*tp_str*/
+                                PyObject_GenericGetAttr,                  /*tp_getattro*/
+                                PyObject_GenericSetAttr,                  /*tp_setattro*/
+                                0,                                        /*tp_as_buffer*/
+                                Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
+                                "Access to MorphoGraphX processes",       /* tp_doc */
+                                0,                                        /* tp_traverse */
+                                0,                                        /* tp_clear */
+                                0,                                        /* tp_richcompare */
+                                0,                                        /* tp_weaklistoffset */
+                                0,                                        /* tp_iter */
+                                0,                                        /* tp_iternext */
+                                0,                                        /* tp_methods */
+                                0,                                        /* tp_members */
+                                fact_getsetlist,                          /* tp_getset */
+                                0,                                        /* tp_base */
+                                0,                                        /* tp_dict */
+                                0,                                        /* tp_descr_get */
+                                0,                                        /* tp_descr_set */
+                                offsetof(mgx_Factory_Python, fact_dict),  /* tp_dictoffset */
+                                (initproc)mgx_Factory_init,               /* tp_init */
+                                0,                                        /* tp_alloc */
+                                mgx_Factory_new,                          /* tp_new */
+                                0,                                        0, 0, 0, 0, 0, 0, 0, 0 };
+  
+  static PyMemberDef proc_memberlist[] = { { "doc", T_OBJECT, offsetof(mgx_Process_Python, descr), READONLY, "" },
+                                           { "description", T_OBJECT, offsetof(mgx_Process_Python, descr), READONLY, "" },
+                                           { NULL } };
+  
+  PyTypeObject process_type = { PyObject_HEAD_INIT(NULL) 0,          /*ob_size*/
+                                "mgx.Process",                      /*tp_name*/
+                                sizeof(mgx_Process_Python),         /*tp_basicsize*/
+                                0,                                  /*tp_itemsize*/
+                                (destructor)Process_dealloc,        /*tp_dealloc*/
+                                0,                                  /*tp_print*/
+                                0,                                  /*tp_getattr*/
+                                0,                                  /*tp_setattr*/
+                                0,                                  /*tp_compare*/
+                                0,                                  /*tp_repr*/
+                                0,                                  /*tp_as_number*/
+                                0,                                  /*tp_as_sequence*/
+                                0,                                  /*tp_as_mapping*/
+                                0,                                  /*tp_hash */
+                                runProcess,                         /*tp_call*/
+                                showProc,                           /*tp_str*/
+                                0,                                  /*tp_getattro*/
+                                0,                                  /*tp_setattro*/
+                                0,                                  /*tp_as_buffer*/
+                                Py_TPFLAGS_DEFAULT,                 /*tp_flags*/
+                                "Access to MorphoGraphX processes", /* tp_doc */
+                                0,                                  /* tp_traverse */
+                                0,                                  /* tp_clear */
+                                0,                                  /* tp_richcompare */
+                                0,                                  /* tp_weaklistoffset */
+                                0,                                  /* tp_iter */
+                                0,                                  /* tp_iternext */
+                                0,                                  /* tp_methods */
+                                proc_memberlist,                    /* tp_members */
+                                0,                                  /* tp_getset */
+                                0,                                  /* tp_base */
+                                0,                                  /* tp_dict */
+                                0,                                  /* tp_descr_get */
+                                0,                                  /* tp_descr_set */
+                                0,                                  /* tp_dictoffset */
+                                (initproc)mgx_Process_init,         /* tp_init */
+                                0,                                  /* tp_alloc */
+                                mgx_Process_new,                    /* tp_new */
+                                0,                                  0, 0, 0, 0, 0, 0, 0, 0 };
+  
+  bool PythonProcess::addFactory(char* name)
+  {
+    PyObject* fact_arg = Py_BuildValue("(s)", name);
+    if(!fact_arg) {
+      setErrorMessage("Could not create arguments to create factory");
+      return false;
+    }
+    PyObject* pyFactory = PyObject_Call((PyObject*)&factory_type, fact_arg, 0);
+    Py_DECREF(fact_arg);
+    if(!pyFactory) {
+      setErrorMessage(QString("Cannot create %1 factory object").arg(name));
+      return false;
+    }
+    mgx_Factory& factory = reinterpret_cast<mgx_Factory_Python*>(pyFactory)->intern;
+    factory.process = this;
+    // Get list of processes and add them to the factory
+    QString processType = QString::fromAscii(name);
+    QStringList processNames = listProcesses(processType);
+    forall(QString processName, processNames) {
+      mgx_Process_Python* proc = createProcess(factory.type, processName);
+      proc->intern.process = this;
+      processName.replace(' ', "_");
+      if(PyObject_SetAttrString(pyFactory, processName.toAscii().data(), (PyObject*)proc) == -1) {
+        PyErr_Print();
+        setErrorMessage(QString("Could not set attribute %1 to factory %2").arg(processName).arg(processType));
+        return false;
+      }
+    }
+    // Add the factory to the modules (main and mgx)
+    Py_INCREF(pyFactory);
+    if(PyModule_AddObject(module, name, pyFactory)) {
+      Py_DECREF(pyFactory);
+      setErrorMessage(QString("Cannot add %1 factory object to the mgx module").arg(name));
+      return false;
+    }
+    if(PyModule_AddObject(main, name, pyFactory)) {
+      Py_DECREF(pyFactory);
+      setErrorMessage(QString("Cannot add %1 factory object to the __main__ module").arg(name));
+      return false;
+    }
+    return true;
   }
-  Py_INCREF(self->fact_dict);
-  return self->fact_dict;
-}
-
-static PyGetSetDef fact_getsetlist[] = { { "__dict__", (getter)fact_getdict, NULL, "Dictionnary" }, { NULL } };
-
-PyTypeObject factory_type = { PyObject_HEAD_INIT(NULL) 0,                /*ob_size*/
-                              "mgx.Factory",                            /*tp_name*/
-                              sizeof(mgx_Factory_Python),               /*tp_basicsize*/
-                              0,                                        /*tp_itemsize*/
-                              (destructor)Factory_dealloc,              /*tp_dealloc*/
-                              0,                                        /*tp_print*/
-                              0,                                        /*tp_getattr*/
-                              0,                                        /*tp_setattr*/
-                              0,                                        /*tp_compare*/
-                              0,                                        /*tp_repr*/
-                              0,                                        /*tp_as_number*/
-                              0,                                        /*tp_as_sequence*/
-                              0,                                        /*tp_as_mapping*/
-                              0,                                        /*tp_hash */
-                              0,                                        /*tp_call*/
-                              printFactory,                             /*tp_str*/
-                              PyObject_GenericGetAttr,                  /*tp_getattro*/
-                              PyObject_GenericSetAttr,                  /*tp_setattro*/
-                              0,                                        /*tp_as_buffer*/
-                              Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
-                              "Access to MorphoGraphX processes",       /* tp_doc */
-                              0,                                        /* tp_traverse */
-                              0,                                        /* tp_clear */
-                              0,                                        /* tp_richcompare */
-                              0,                                        /* tp_weaklistoffset */
-                              0,                                        /* tp_iter */
-                              0,                                        /* tp_iternext */
-                              0,                                        /* tp_methods */
-                              0,                                        /* tp_members */
-                              fact_getsetlist,                          /* tp_getset */
-                              0,                                        /* tp_base */
-                              0,                                        /* tp_dict */
-                              0,                                        /* tp_descr_get */
-                              0,                                        /* tp_descr_set */
-                              offsetof(mgx_Factory_Python, fact_dict),  /* tp_dictoffset */
-                              (initproc)mgx_Factory_init,               /* tp_init */
-                              0,                                        /* tp_alloc */
-                              mgx_Factory_new,                          /* tp_new */
-                              0,                                        0, 0, 0, 0, 0, 0, 0, 0 };
-
-static PyMemberDef proc_memberlist[] = { { "doc", T_OBJECT, offsetof(mgx_Process_Python, descr), READONLY, "" },
-                                         { "description", T_OBJECT, offsetof(mgx_Process_Python, descr), READONLY, "" },
-                                         { NULL } };
-
-PyTypeObject process_type = { PyObject_HEAD_INIT(NULL) 0,          /*ob_size*/
-                              "mgx.Process",                      /*tp_name*/
-                              sizeof(mgx_Process_Python),         /*tp_basicsize*/
-                              0,                                  /*tp_itemsize*/
-                              (destructor)Process_dealloc,        /*tp_dealloc*/
-                              0,                                  /*tp_print*/
-                              0,                                  /*tp_getattr*/
-                              0,                                  /*tp_setattr*/
-                              0,                                  /*tp_compare*/
-                              0,                                  /*tp_repr*/
-                              0,                                  /*tp_as_number*/
-                              0,                                  /*tp_as_sequence*/
-                              0,                                  /*tp_as_mapping*/
-                              0,                                  /*tp_hash */
-                              runProcess,                         /*tp_call*/
-                              showProc,                           /*tp_str*/
-                              0,                                  /*tp_getattro*/
-                              0,                                  /*tp_setattro*/
-                              0,                                  /*tp_as_buffer*/
-                              Py_TPFLAGS_DEFAULT,                 /*tp_flags*/
-                              "Access to MorphoGraphX processes", /* tp_doc */
-                              0,                                  /* tp_traverse */
-                              0,                                  /* tp_clear */
-                              0,                                  /* tp_richcompare */
-                              0,                                  /* tp_weaklistoffset */
-                              0,                                  /* tp_iter */
-                              0,                                  /* tp_iternext */
-                              0,                                  /* tp_methods */
-                              proc_memberlist,                    /* tp_members */
-                              0,                                  /* tp_getset */
-                              0,                                  /* tp_base */
-                              0,                                  /* tp_dict */
-                              0,                                  /* tp_descr_get */
-                              0,                                  /* tp_descr_set */
-                              0,                                  /* tp_dictoffset */
-                              (initproc)mgx_Process_init,         /* tp_init */
-                              0,                                  /* tp_alloc */
-                              mgx_Process_new,                    /* tp_new */
-                              0,                                  0, 0, 0, 0, 0, 0, 0, 0 };
-
-bool PythonProcess::addFactory(char* name)
-{
-  PyObject* fact_arg = Py_BuildValue("(s)", name);
-  if(!fact_arg) {
-    setErrorMessage("Could not create arguments to create factory");
-    return false;
+  
+  bool PythonProcess::removeFactory(char* name)
+  {
+    PyObject* d1 = PyModule_GetDict(module);
+    PyObject* d2 = PyModule_GetDict(main);
+    PyDict_DelItemString(d1, name);
+    PyDict_DelItemString(d2, name);
+    return true;
   }
-  PyObject* pyFactory = PyObject_Call((PyObject*)&factory_type, fact_arg, 0);
-  Py_DECREF(fact_arg);
-  if(!pyFactory) {
-    setErrorMessage(QString("Cannot create %1 factory object").arg(name));
-    return false;
-  }
-  mgx_Factory& factory = reinterpret_cast<mgx_Factory_Python*>(pyFactory)->intern;
-  factory.process = this;
-  // Get list of processes and add them to the factory
-  QString processType = QString::fromAscii(name);
-  QStringList processNames = listProcesses(processType);
-  forall(QString processName, processNames) {
-    mgx_Process_Python* proc = createProcess(factory.type, processName);
-    proc->intern.process = this;
-    processName.replace(' ', "_");
-    if(PyObject_SetAttrString(pyFactory, processName.toAscii().data(), (PyObject*)proc) == -1) {
-      PyErr_Print();
-      setErrorMessage(QString("Could not set attribute %1 to factory %2").arg(processName).arg(processType));
+  
+  bool PythonProcess::initPython(const QString& filename)
+  {
+    main = PyImport_AddModule("__main__");
+    if(main == NULL) {
+      setErrorMessage("Cannot import __main__ module");
       return false;
     }
-  }
-  // Add the factory to the modules (main and mgx)
-  Py_INCREF(pyFactory);
-  if(PyModule_AddObject(module, name, pyFactory)) {
-    Py_DECREF(pyFactory);
-    setErrorMessage(QString("Cannot add %1 factory object to the mgx module").arg(name));
-    return false;
-  }
-  if(PyModule_AddObject(main, name, pyFactory)) {
-    Py_DECREF(pyFactory);
-    setErrorMessage(QString("Cannot add %1 factory object to the __main__ module").arg(name));
-    return false;
-  }
-  return true;
-}
-
-bool PythonProcess::removeFactory(char* name)
-{
-  PyObject* d1 = PyModule_GetDict(module);
-  PyObject* d2 = PyModule_GetDict(main);
-  PyDict_DelItemString(d1, name);
-  PyDict_DelItemString(d2, name);
-  return true;
-}
-
-bool PythonProcess::initPython(const QString& filename)
-{
-  main = PyImport_AddModule("__main__");
-  if(main == NULL) {
-    setErrorMessage("Cannot import __main__ module");
-    return false;
-  }
-  main_dict = PyModule_GetDict(main);
-  PyObject* f = PyString_FromString(filename.toLocal8Bit().data());
-  if(f == NULL) {
-    setErrorMessage("Cannot create the Python's string for the file name");
-    return false;
-  }
-  if(PyDict_SetItemString(main_dict, "__file__", f) < 0) {
+    main_dict = PyModule_GetDict(main);
+    PyObject* f = PyString_FromString(filename.toLocal8Bit().data());
+    if(f == NULL) {
+      setErrorMessage("Cannot create the Python's string for the file name");
+      return false;
+    }
+    if(PyDict_SetItemString(main_dict, "__file__", f) < 0) {
+      Py_DECREF(f);
+      setErrorMessage("Cannot set the __main__ module's filename");
+      return false;
+    }
     Py_DECREF(f);
-    setErrorMessage("Cannot set the __main__ module's filename");
-    return false;
+    if(PyType_Ready(&factory_type) < 0) {
+      setErrorMessage("Factory type is not ready");
+      return false;
+    }
+  
+    if(PyType_Ready(&process_type) < 0) {
+      setErrorMessage("Process type is not ready");
+      return false;
+    }
+  
+    module = Py_InitModule3("mgx", module_methods, "Module to access MorphoGraphX processes.");
+    if(module == NULL) {
+      setErrorMessage("Could not create mgx module");
+      return false;
+    }
+    Py_INCREF(&factory_type);
+    PyModule_AddObject(module, "Factory", (PyObject*)&factory_type);
+    Py_INCREF(&process_type);
+    PyModule_AddObject(module, "Process", (PyObject*)&process_type);
+  
+    if(!addFactory("Stack"))
+      return false;
+    if(!addFactory("Mesh"))
+      return false;
+    if(!addFactory("Global"))
+      return false;
+    return true;
   }
-  Py_DECREF(f);
-  if(PyType_Ready(&factory_type) < 0) {
-    setErrorMessage("Factory type is not ready");
-    return false;
+  
+  bool PythonProcess::finalizePython()
+  {
+    removeFactory("Stack");
+    removeFactory("Mesh");
+    removeFactory("Global");
+    return true;
   }
-
-  if(PyType_Ready(&process_type) < 0) {
-    setErrorMessage("Process type is not ready");
-    return false;
+  
+  mgx_Process_Python* PythonProcess::createProcess(const QString& type, const QString& name)
+  {
+    PyObject* args = Py_BuildValue("(ss)", type.toAscii().data(), name.toAscii().data());
+    if(!args)
+      return NULL;
+    PyObject* obj = PyObject_Call((PyObject*)&process_type, args, 0);
+    Py_DECREF(args);
+    return (mgx_Process_Python*)obj;
   }
-
-  module = Py_InitModule3("mgx", module_methods, "Module to access MorphoGraphX processes.");
-  if(module == NULL) {
-    setErrorMessage("Could not create mgx module");
-    return false;
+  
+  QString PythonProcess::getTraceBack(PyObject* tb, int limit)
+  {
+    QString err;
+    PyTracebackObject* tb1 = (PyTracebackObject*)tb;
+    int depth = 0;
+    while(tb1 != NULL) {
+      depth++;
+      tb1 = tb1->tb_next;
+    }
+    tb1 = (PyTracebackObject*)tb;
+    while(tb1 != NULL) {
+      if(depth <= limit) {
+        const char* fn = PyString_AsString(tb1->tb_frame->f_code->co_filename);
+        int lo = tb1->tb_lineno;
+        const char* co = PyString_AsString(tb1->tb_frame->f_code->co_name);
+        err += QString("  File \"%1\", line %2, in %3\n").arg(fn).arg(lo).arg(co);
+      }
+      depth--;
+      tb1 = tb1->tb_next;
+    }
+    return err;
   }
-  Py_INCREF(&factory_type);
-  PyModule_AddObject(module, "Factory", (PyObject*)&factory_type);
-  Py_INCREF(&process_type);
-  PyModule_AddObject(module, "Process", (PyObject*)&process_type);
-
-  if(!addFactory("Stack"))
-    return false;
-  if(!addFactory("Mesh"))
-    return false;
-  if(!addFactory("Global"))
-    return false;
-  return true;
-}
-
-bool PythonProcess::finalizePython()
-{
-  removeFactory("Stack");
-  removeFactory("Mesh");
-  removeFactory("Global");
-  return true;
-}
-
-mgx_Process_Python* PythonProcess::createProcess(const QString& type, const QString& name)
-{
-  PyObject* args = Py_BuildValue("(ss)", type.toAscii().data(), name.toAscii().data());
-  if(!args)
-    return NULL;
-  PyObject* obj = PyObject_Call((PyObject*)&process_type, args, 0);
-  Py_DECREF(args);
-  return (mgx_Process_Python*)obj;
-}
-
-QString PythonProcess::getTraceBack(PyObject* tb, int limit)
-{
-  QString err;
-  PyTracebackObject* tb1 = (PyTracebackObject*)tb;
-  int depth = 0;
-  while(tb1 != NULL) {
-    depth++;
-    tb1 = tb1->tb_next;
+  
+  bool PythonProcess::initialize(QStringList& parms, QWidget* parent)
+  {
+    QString filename = QFileDialog::getOpenFileName(parent, "Choose python script to execute", parms[0],
+                                                    "Python scripts (*.py);;All files (*.*)");
+    // check file
+    if(filename.isEmpty())
+      return false;
+    // ok all good
+    parms[0] = filename;
+  
+    return true;
   }
-  tb1 = (PyTracebackObject*)tb;
-  while(tb1 != NULL) {
-    if(depth <= limit) {
-      const char* fn = PyString_AsString(tb1->tb_frame->f_code->co_filename);
-      int lo = tb1->tb_lineno;
-      const char* co = PyString_AsString(tb1->tb_frame->f_code->co_name);
-      err += QString("  File \"%1\", line %2, in %3\n").arg(fn).arg(lo).arg(co);
+  
+  bool PythonProcess::operator()(QString filename)
+  {
+    bool success = false;
+    filename = util::resolvePath(filename);
+    FILE* file = fopen(filename.toLocal8Bit().data(), "rt");
+    if(not file) {
+      setErrorMessage(QString("Cannot open file '%1' for reading").arg(filename));
+      return false;
     }
-    depth--;
-    tb1 = tb1->tb_next;
-  }
-  return err;
-}
-
-bool PythonProcess::initialize(QStringList& parms, QWidget* parent)
-{
-  QString filename = QFileDialog::getOpenFileName(parent, "Choose python script to execute", parms[0],
-                                                  "Python scripts (*.py);;All files (*.*)");
-  // check file
-  if(filename.isEmpty())
-    return false;
-  // ok all good
-  parms[0] = filename;
-
-  return true;
-}
-
-bool PythonProcess::operator()(QString filename)
-{
-  bool success = false;
-  filename = util::resolvePath(filename);
-  FILE* file = fopen(filename.toLocal8Bit().data(), "rt");
-  if(not file) {
-    setErrorMessage(QString("Cannot open file '%1' for reading").arg(filename));
-    return false;
-  }
-  Py_Initialize();
-  do {
-    // First, add the __main__ module and set its file name to the file loaded
-    if(!initPython(filename))
-      break;
-    PyObject* res
-      = PyRun_FileExFlags(file, filename.toLocal8Bit().data(), Py_file_input, main_dict, main_dict, true, 0);
-    if(res == NULL) {
-      PyObject* exc, *val, *tb;
-      PyErr_Fetch(&exc, &val, &tb);
-      if(!exc)
-        setErrorMessage("Unknown error in Python code");
-      else {
-        // Now, get the exception string
-        QString err;
-        PyErr_NormalizeException(&exc, &val, &tb);
-        if(tb and tb != Py_None) {
-          err += "Traceback (most recent call last):\n";
-          err += getTraceBack(tb, 10);
+    Py_Initialize();
+    do {
+      // First, add the __main__ module and set its file name to the file loaded
+      if(!initPython(filename))
+        break;
+      PyObject* res
+        = PyRun_FileExFlags(file, filename.toLocal8Bit().data(), Py_file_input, main_dict, main_dict, true, 0);
+      if(res == NULL) {
+        PyObject* exc, *val, *tb;
+        PyErr_Fetch(&exc, &val, &tb);
+        if(!exc)
+          setErrorMessage("Unknown error in Python code");
+        else {
+          // Now, get the exception string
+          QString err;
+          PyErr_NormalizeException(&exc, &val, &tb);
+          if(tb and tb != Py_None) {
+            err += "Traceback (most recent call last):\n";
+            err += getTraceBack(tb, 10);
+          }
+          PyObject* str = PyObject_Str(val);
+          if(str) {
+            PyObject* exc_str = PyObject_GetAttrString(exc, "__name__");
+            char* s_exc = PyString_AsString(exc_str);
+            char* s_val = PyString_AsString(str);
+            setErrorMessage(err + QString("%1: %2").arg(s_exc).arg(s_val));
+            Py_DECREF(exc_str);
+            Py_DECREF(str);
+          } else
+            setErrorMessage("Unknown exception in Python code");
         }
-        PyObject* str = PyObject_Str(val);
-        if(str) {
-          PyObject* exc_str = PyObject_GetAttrString(exc, "__name__");
-          char* s_exc = PyString_AsString(exc_str);
-          char* s_val = PyString_AsString(str);
-          setErrorMessage(err + QString("%1: %2").arg(s_exc).arg(s_val));
-          Py_DECREF(exc_str);
-          Py_DECREF(str);
-        } else
-          setErrorMessage("Unknown exception in Python code");
+      } else {
+        Py_DECREF(res);
+        success = true;
       }
-    } else {
-      Py_DECREF(res);
-      success = true;
-    }
-  } while(false);
-  PyErr_Clear();
-  if(PyDict_DelItemString(main_dict, "__file__"))
+    } while(false);
     PyErr_Clear();
-  finalizePython();
-  Py_Finalize();
-  return success;
-}
+    if(PyDict_DelItemString(main_dict, "__file__"))
+      PyErr_Clear();
+    finalizePython();
+    Py_Finalize();
+    return success;
+  }
+  REGISTER_GLOBAL_PROCESS(PythonProcess);
 
-REGISTER_GLOBAL_PROCESS(PythonProcess);
-} // namespace process
-} // namespace mgx
+}}
Index: MorphoViewer.cpp
===================================================================
--- MorphoViewer.cpp	(revision 1255)
+++ MorphoViewer.cpp	(revision 1256)
@@ -31,19 +31,14 @@
   = { 1.0 / 16.0, 2.0 / 16.0, 1.0 / 16.0, 2.0 / 16.0, 4.0 / 16.0, 2.0 / 16.0, 1.0 / 16.0, 2.0 / 16.0, 1.0 / 16.0 };
 
 MGXKeyFrameInterpolator::MGXKeyFrameInterpolator(Frame* fr)
-  : KeyFrameInterpolator(fr)
+  : KeyFrameInterpolator(fr) {}
+
+void MGXKeyFrameInterpolator::interpolateAtTime(float time) 
 {
-}
-
-void MGXKeyFrameInterpolator::interpolateAtTime(float time) {
   KeyFrameInterpolator::interpolateAtTime(time);
 }
 
-MGXCameraFrame::MGXCameraFrame()
-  : qglviewer::ManipulatedCameraFrame()
-  , _zoom(0)
-{
-}
+MGXCameraFrame::MGXCameraFrame() : qglviewer::ManipulatedCameraFrame(), _zoom(0) {}
 
 void MGXCameraFrame::wheelEvent(QWheelEvent* const event, Camera* const camera)
 {
@@ -73,8 +68,7 @@
   action_ = QGLViewer::NO_MOUSE_ACTION;
 }
 
-MGXCamera::MGXCamera()
-  : qglviewer::Camera()
+MGXCamera::MGXCamera() : qglviewer::Camera()
 {
   setType(qglviewer::Camera::ORTHOGRAPHIC);
   _frame = new MGXCameraFrame();
@@ -99,67 +93,40 @@
   qglviewer::Camera::fitSphere(center, radius);
 }
 
-void MGXCamera::addKeyFrameToPath(int i) {
+void MGXCamera::addKeyFrameToPath(int i) 
+{
   Camera::addKeyFrameToPath(i);
 }
 
-void MGXCamera::playPath(int i) {
+void MGXCamera::playPath(int i) 
+{
   Camera::playPath(i);
 }
 
-void MGXCamera::deletePath(int i) {
+void MGXCamera::deletePath(int i) 
+{
   Camera::deletePath(i);
 }
 
-void MGXCamera::resetPath(int i) {
+void MGXCamera::resetPath(int i) 
+{
   Camera::resetPath(i);
 }
 
-void MGXCamera::drawAllPaths() {
+void MGXCamera::drawAllPaths() 
+{
   Camera::drawAllPaths();
 }
 
 MorphoViewer::MorphoViewer(QWidget* parent)
-  : QGLViewer(parent)
-  , quitting(false)
-  , DrawCellMap(false)
-  , DrawClipBox(false)
-  , pixelEditCursor(false)
-  , pixelRadius(1)
-  , selectMode(NONE)
-  , shiftPressed(false)
-  , altPressed(false)
-  , controlPressed(false)
-  , leftButton(false)
-  , pixelEdit(false)
-  , pickVolLabel(false)
-  , deleteVolLabel(false)
-  , deletePckdLabel(false)
-  , fillVolLabel(false)
-  , meshSelect(false)
-  , addNewSeed(false)
-  , addCurrentSeed(false)
-  , pickLabel(true)
-  , selectLabel(false)
-  , selectConnected(false)
-  , grabSeed(false)
-  , fillLabel(false)
-  , stack1(NULL)
-  , stack2(NULL)
-  , cutSurf(NULL)
-  , FlySpeed(0.005f)
-  , selectedLabel(0)
-  , sampling(2)
-  , fast_draw(false)
-  , MaxNbPeels(20)
-  , GlobalBrightness(0.0)
-  , GlobalContrast(1.0)
-  , UnsharpStrength(1.0)
-  , Spinning(10000)
-  , _camera(new MGXCamera())
-  , SceneRadius(1e7)
-  , initialized(false)
-  , lastInitCamera(0)
+  : QGLViewer(parent), quitting(false), DrawCellMap(false), DrawClipBox(false), pixelEditCursor(false),
+    pixelRadius(1), selectMode(NONE), shiftPressed(false), altPressed(false), controlPressed(false),
+    leftButton(false), pixelEdit(false), pickVolLabel(false), deleteVolLabel(false), deletePckdLabel(false),
+    fillVolLabel(false), meshSelect(false), addNewSeed(false), addCurrentSeed(false), pickLabel(true),
+    selectLabel(false), selectConnected(false), grabSeed(false), fillLabel(false), stack1(NULL),
+    stack2(NULL), cutSurf(NULL), FlySpeed(0.005f), selectedLabel(0), sampling(2), fast_draw(false),
+    MaxNbPeels(20), GlobalBrightness(0.0), GlobalContrast(1.0), UnsharpStrength(1.0), Spinning(10000),
+    _camera(new MGXCamera()), SceneRadius(1e7), initialized(false), lastInitCamera(0)
 {
   initObject(parent);
   setCamera(_camera);
@@ -224,14 +191,13 @@
 {
   // Check multi-sampling is de-activate, but in practice it seems useless ..
   if(format().sampleBuffers()) {
-    QMessageBox::critical(this, "Problem with OpenGL context",
-                          "Multi-sampling is activated in your OpenGL context.\n"
-                          "Make sure your drivers are not setup to overide application preferences.\n"
-                          "Note that as long as this persists, selection will not work properly in MorphoGraphX.");
+    QMessageBox::critical(this, 
+      "There is a Problem with the OpenGL context", 
+      "Multi-sampling is activated in the OpenGL context.\n"
+      "Make sure your drivers are not setup to override application preferences.\n"
+      "Note that as long as this persists, selection will not work properly in MorphoGraphX.");
   }
 
-  // Information::out << "Initializing OpenGL context" << endl;
-
   GLenum err = glewInit();
   if(GLEW_OK != err) {
     SETSTATUS("Error initializing GLEW:" << glewGetErrorString(err));
@@ -363,7 +329,6 @@
   camera()->setSceneCenter(Vec(0, 0, 0));
   camera()->centerScene();
   camera()->showEntireScene();
-  camera()->frame()->setSpinningSensitivity(Spinning);
 
   // Color3f clearColor = Colors::getColor(Colors::BackgroundColor);
   // glClearColor(clearColor.r(), clearColor.g(), clearColor.b(), 1.0);
@@ -1818,7 +1783,7 @@
   parms(section, "DrawCellMap", DrawCellMap, false);
   parms(section, "DrawClipBox", DrawClipBox, false);
   parms(section, "Spinning", Spinning, 10000.0f);
-  // parms(section, "SceneRadius", SceneRadius, 1.5f);
+  camera()->frame()->setSpinningSensitivity(Spinning);
   parms(section, "FlySpeed", FlySpeed, .005f);
   parms(section, "Brightness", GlobalBrightness, .0f);
   parms(section, "Contrast", GlobalContrast, 1.0f);
@@ -1828,6 +1793,12 @@
   parms(section, "MaxNbPeels", MaxNbPeels, 10);
   if(MaxNbPeels < 1)
     MaxNbPeels = 1;
+  CameraFrame = Matrix4d::identity();;
+  CameraFrame[3][2] = -1000;
+  parms(section, "CameraFrame", CameraFrame, CameraFrame);
+  camera()->setFromModelViewMatrix(CameraFrame.data());
+  parms(section, "SceneRadius", SceneRadius, 500.0f);
+  camera()->setSceneRadius(SceneRadius);
 
   clip1.readParms(parms, "Clip1");
   clip2.readParms(parms, "Clip2");
@@ -1842,7 +1813,6 @@
   pout << "DrawCellMap: " << (DrawCellMap ? "true" : "false") << endl;
   pout << "DrawClipBox: " << (DrawClipBox ? "true" : "false") << endl;
   pout << "Spinning: " << Spinning << endl;
-  // pout << "SceneRadius: " << SceneRadius << endl;
   pout << "FlySpeed: " << FlySpeed << endl;
   pout << "Brightness: " << GlobalBrightness << endl;
   pout << "Contrast: " << GlobalContrast << endl;
@@ -1850,6 +1820,9 @@
   pout << "Specular: " << Specular << endl;
   pout << "UnsharpStrength: " << UnsharpStrength << endl;
   pout << "MaxNbPeels: " << MaxNbPeels << endl;
+  camera()->getModelViewMatrix(CameraFrame.data());
+  pout << "CameraFrame: " << CameraFrame << endl;
+  pout << "SceneRadius: " << SceneRadius << endl;
   pout << endl;
 
   clip1.writeParms(pout, "Clip1");
@@ -2655,6 +2628,7 @@
   // Label vs parent radio button checked
   bool showParent = stk->mesh->toShow() == Mesh::PARENT;
   bool showLabel = stk->mesh->toShow() == Mesh::LABEL;
+  bool showHeat = stk->mesh->toShow() == Mesh::HEAT;
 
   // Carry out selection actions based on checked option
   if(pickLabel) {
@@ -2661,7 +2635,10 @@
     // Set current label (color)
     if((showLabel or showParent) and label >= 0) {
       setLabel(label);
-      SETSTATUS("Picked " << (showParent ? "parent" : "label ") << label);
+      SETSTATUS("Picked " << (showParent ? "parent " : "label ") << label);
+    } else if(showHeat and label > 0) {
+      if(stk->mesh->labelHeat().count(label) > 0)
+        SETSTATUS("Label " << label << " has heat value:" << stk->mesh->labelHeat()[label]);
     }
   } else if(addNewSeed) {
     // Add a new seed
@@ -2712,7 +2689,7 @@
   } else if(selectLabel) {
     if(label > 0) {
       if(showLabel or showParent) {
-        if(controlPressed and !shiftPressed)
+        if(controlPressed)
           unselectMeshLabel(label);
         else
           selectMeshLabel(label, !shiftPressed);
@@ -2846,7 +2823,7 @@
       }
     } else if(showLabel and selectLabel) {
       if(label > 0) {
-        if(controlPressed and !shiftPressed)
+        if(controlPressed)
           unselectMeshLabel(label);
         else
           selectMeshLabel(label, false);
@@ -3261,16 +3238,9 @@
 
 void MorphoViewer::setSceneBoundingBox(const Point3f& bbox)
 {
-  static bool firsttime = true;
   if(norm(bbox) > 0) {
     SceneRadius = norm(bbox);
     emit changeSceneRadius(SceneRadius);
-
-    if(firsttime) {
-      setSceneRadius(SceneRadius);
-      showEntireScene();
-      firsttime = false;
-    }
   }
   updateAll();
 }
Index: MeshProcessSignal.hpp
===================================================================
--- MeshProcessSignal.hpp	(revision 1255)
+++ MeshProcessSignal.hpp	(revision 1256)
@@ -7,978 +7,671 @@
 
 class Ui_LoadHeatMap;
 
-namespace mgx {
-namespace process {
-typedef std::map<int, HVec3U> IntHVec3UMap;
+namespace mgx { namespace process {
 
-///\addtogroup MeshProcess
-///@{
-/**
- * \class ViewMeshProcess MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * This process is used to change how the mesh is seen. Mostly useful to
- * write scripts taking screenshots.
- */
-class MGX_EXPORT ViewMeshProcess : public MeshProcess {
-public:
-  ViewMeshProcess(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
+  typedef std::map<int, HVec3U> IntHVec3UMap;
+  
+  ///\addtogroup MeshProcess
+  ///@{
+  /**
+   * \class ViewMeshProcess MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * This process is used to change how the mesh is seen. Mostly useful to
+   * write scripts taking screenshots.
+   */
+  class MGX_EXPORT ViewMeshProcess : public MeshProcess {
+  public:
+    ViewMeshProcess(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms);
+  
+    QString folder() const { return "System"; }
+    QString name() const { return "View"; }
+    QString description() const { return 
+      "Modify how the current mesh is viewed. Useful for scripts."; }
+    QStringList parmNames() const { return QStringList() 
+      << "Show Surface" << "Surface Type" << "Signal Type" << "Blend" << "Cull"
+      << "Show Mesh" << "Mesh View" << "Show Lines" << "Show Points" << "Show Map"
+      << "Scale" << "Transform" << "BBox" << "Brightness" << "Opacity";
+    }
+    QStringList parmDescs() const { return QStringList() 
+      << "Draw mesh as a continuous surface."
+      << "Nrml: show projected signal, Labels: color triangles according to assigned "
+         "labels, Parents: color triangles with parent labels, Heat: color triangles "
+         "with computed heat map (e.g. growth)"
+      << "Signal: show projected signal, Tex: Use 3D stack as texture, Img: Use 2D "
+         "texture (height map)."
+      << "Semi-transparent mesh, for example to superimpose to meshes or view the "
+         "stack through the mesh."
+      << "Color the triangles (with signal or labels) only on the top of the mesh."
+      << "Draw triangle edges and nodes"
+      << "All: draw all triangles. Border: draw outside edge of the mesh only. "
+         "Cells: draw cell outlines only. Selected: draw selected nodes only. "
+      << "Show connecting lines between nodes in the mesh."
+      << "Show mesh nodes."
+      << "Mapping of text on the labels (e.g. label number)"
+      << "Change scaling of mesh/stacks, independently in 3 directions (x,y,z). NB: "
+      << "a stack saved with 'Scale' turned on will have a modified voxel size, "
+         "while saved meshes are unaffected. "
+      << "Apply rotation and translation to the mesh/stack."
+      << "Display the bounding box (i.e. total size) of a stack."
+      << "Brightness of signal, labels or heat"
+      << "Opacity of signal, labels or heat";
+    }
+  
+    QStringList parmDefaults() const { return QStringList() 
+      << "" << "" << "" << "" << "" << "" << "" << "" << "" << ""
+      << "" << "" << "" << "-1" << "-1"; }
+  
+    ParmChoiceMap parmChoice() const
+    {
+      QStringList bools = QStringList() << "" << booleanChoice();
+      ParmChoiceMap map;
+      map[0] = bools;
+      map[1] = QStringList() << "" << "Normal" << "Heat" << "Label";
+      map[2] = QStringList() << "" << "Signal" << "Texture" << "Image";
+      map[3] = map[4] = map[5] = bools;
+      map[6] = QStringList() << "" << "All" << "Border" << "Cells" << "Selected";
+      map[7] = map[8] = map[9] = map[10] = map[11] = map[12] = bools;
+      return map;
+    }
+    QIcon icon() const { return QIcon(":/images/Palette.png"); }
+  };
+  
+  /**
+   * \class ProjectSignal MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Project stack signal onto the current mesh.
+   */
+  class MGX_EXPORT ProjectSignal : public MeshProcess {
+  public:
+    ProjectSignal(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().store(STORE_NON_LABEL).mesh(MESH_NON_EMPTY))
+        return false;
+      return (*this)(currentStack()->currentStore(), currentMesh(), stringToBool(parms[0]), 
+        parms[1].toFloat(), parms[2].toFloat(), parms[3].toFloat(), parms[4].toFloat());
+    }
+  
+    bool operator()(const Store* store, Mesh* mesh, bool useAbsSignal, float minDist, 
+      float maxDist, float absSignalMin, float absSignalMax);
+    void projSignal(const Stack* stack, const HVecUS& data, vertex v, float mindist, float maxdist);
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Project Signal"; }
+    QString description() const { return "Project signal onto mesh, perpendicular to its curved surface."; }
+    QStringList parmNames() const { return QStringList() 
+      << "Use absolute" << QString("Min Dist (%1)").arg(UM) << QString("Max Dist (%1)").arg(UM)
+      << "Min Signal" << "Max Signal";
+    }
+    QStringList parmDescs() const { return QStringList() 
+      << "Use absolute values of signal, instead of normalizing it, useful for signal quantification."
+      << "Distance (triangle-voxel) above which the signal is projected."
+      << "Maximal distance (triangle-voxel) used for signal projection."
+      << "Lower bound of signal value if 'Use absolute' is chosen"
+      << "Upper bound of projected signal value.";
+    }
+    QStringList parmDefaults() const { return QStringList() << "No" << "2.0" << "6.0" << "0.0" << "60000.0"; }
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[0] = booleanChoice();
+      return map;
+    }
+    QIcon icon() const { return QIcon(":/images/ProjectColor.png"); }
+  };
+  
+  /**
+   * \class SmoothMeshSignal MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Smooth the mesh signal using local averaging.
+   */
+  class MGX_EXPORT SmoothMeshSignal : public MeshProcess {
+  public:
+    SmoothMeshSignal(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      return (*this)(currentMesh(), parms[0].toUInt());
+    }
+  
+    bool operator()(Mesh* mesh, uint passes);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Smooth Mesh Signal"; }
+    QString description() const { return "Averages the signal of each node, based on its immediate neighbors."; }
+    QStringList parmNames() const { return QStringList() << "Passes"; }
+    QStringList parmDescs() const { return QStringList() << "Number of smoothing iterations."; }
+    QStringList parmDefaults() const { return QStringList() << "3"; }
+    QIcon icon() const { return QIcon(":/images/SmoothColor.png"); }
+  };
 
-  bool operator()(const QStringList& parms);
+  /**
+   * \class BrightenMesh MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Change the brightness of the signal.
+   */
+  class MGX_EXPORT MeshBrightness : public MeshProcess {
+  public:
+    MeshBrightness(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      return (*this)(currentMesh(), parms[0].toFloat());
+    }
+  
+    bool operator()(Mesh* mesh, float amount);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Mesh Brighness"; }
+    QString description() const { return "Changes the brightness of the signal on a mesh."; }
+    QStringList parmNames() const { return QStringList() << "Amount"; }
+    QStringList parmDescs() const { return QStringList() << "Amount to multiply the signal, >1 is brighter"; }
+    QStringList parmDefaults() const { return QStringList() << "2.0"; }
+    QIcon icon() const { return QIcon(":/images/Brightness.png"); }
+  }; 
 
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "View";
-  }
-  QString description() const {
-    return "Modify how the current mesh is viewed. Useful for scripts.";
-  }
+  /**
+   * \class ClearMeshSignal MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Clear the mesh signal to a defined value.
+   */
+  class MGX_EXPORT ClearMeshSignal : public MeshProcess {
+  public:
+    ClearMeshSignal(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      return (*this)(currentMesh(), parms[0].toUInt());
+    }
+  
+    bool operator()(Mesh* mesh, uint value);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Clear Mesh Signal"; }
+    QString description() const { return "Erase the signal on the mesh"; }
+    QStringList parmNames() const { return QStringList() << "Value"; }
+    QStringList parmDescs() const { return QStringList() << "Assign this signal value to the mesh."; }
+    QStringList parmDefaults() const { return QStringList() << "50000"; }
+    QIcon icon() const { return QIcon(":/images/ClearSignal.png"); }
+  };
+  
+  /**
+   * \class ProjectCurvature MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Set the mesh signal to be the curvature of the mesh. The process can also
+   * output a CSV file with the full curvature tensor for each vertex.
+   */
+  class MGX_EXPORT ProjectCurvature : public MeshProcess {
+  public:
+    ProjectCurvature(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      bool ok;
+      float neighborhood = parms[2].toFloat(&ok);
+      if(not ok)
+        return setErrorMessage("Error, parameter 'Neighborhood' must be a number");
+      float mincurv = parms[4].toFloat(&ok);
+      if(not ok)
+        return setErrorMessage("Error, parameter 'Min Curv' must be a number");
+      float maxcurv = parms[5].toFloat(&ok);
+      if(not ok)
+        return setErrorMessage("Error, parameter 'Max Curv' must be a number");
+      float percentile = parms[6].toFloat(&ok);
+      if(not ok)
+        return setErrorMessage("Error, parameter 'Percentile' must be a number");
+      return (*this)(currentMesh(), parms[0], parms[1], neighborhood, stringToBool(parms[3]), mincurv, maxcurv,
+                     percentile);
+    }
+  
+    bool operator()(Mesh* mesh, QString output, QString type, float neighborhood, bool auto_scale, float mincurv,
+                    float maxcurv, int percentile);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Project Mesh Curvature"; }
+    QString description() const { return 
+      "Compute curvature at each node of the mesh, for a given neighborhood size. "
+      "Curvature values are stored as signal.";
+    }
+    QStringList parmNames() const { return QStringList() 
+      << "Output" << "Type" << QString("Neighborhood (%1)").arg(UM) << "AutoScale"
+      << "Min Curv" << "Max Curv" << "Autoscale percentile";
+    }
+    QStringList parmDescs() const { return QStringList() 
+      << "Name of output file, if desired."
+      << "Minimal = minCurv, Maximal = maxCurv, Gaussian = maxCurv * minCurv, "
+         "SumSquare = maxCurv^2 + minCurv^2, Average = (maxCurv + minCurv)/2, "
+         "SignedAverageAbs = sign(max or min) x (abs(maxCurv) + abs(minCurv))/2"
+      << QString("Neighborhood (%1)").arg(UM)
+      << "Clip max and min signal range according to curvature distribution"
+      << "Minimal curvature value displayed"
+      << "Maximal curvature value displayed"
+      << "Auto-scale signal range based on curvature percentile";
+    }
+    QStringList parmDefaults() const { return QStringList() 
+      << "" << "Gaussian" << "3.0" << "Yes" << "-50.0" << "50.0" << "85"; }
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[1] = QStringList() << "Minimal" << "Maximal" << "Gaussian" << "SumSquare" << "Average" << "SignedAverageAbs";
+      map[3] = booleanChoice();
+      return map;
+    }
+    QIcon icon() const { return QIcon(":/images/Curvature.png"); }
+  };
+  
+  /**
+   * \class MeshGaussianBlur MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Smooth the mesh signal using a gaussian kernel.
+   */
+  class MGX_EXPORT MeshGaussianBlur : public MeshProcess {
+  public:
+    MeshGaussianBlur(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      return (*this)(currentMesh(), parms[0].toFloat());
+    }
+  
+    bool operator()(Mesh* mesh, float radius);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Gaussian Blur"; }
+    QString description() const { return "Apply Gaussian Blur to mesh signal"; }
+    QStringList parmNames() const { return QStringList() << QString("Radius (%1)").arg(UM); }
+    QStringList parmDescs() const { return QStringList() 
+      << "Size of neighborhood used for Gaussian blur. The blur function standard "
+         "deviation is given by sigma = radius/2. ";
+    }
+    QStringList parmDefaults() const { return QStringList() << "2.0"; }
+    QIcon icon() const { return QIcon(":/images/Blur.png"); }
+  };
+  
+  /**
+   * \class MeshDiffGaussians MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Calculate a difference of Gaussians on mesh.
+   */
+  class MGX_EXPORT MeshDiffGaussians : public MeshProcess {
+  public:
+    MeshDiffGaussians(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      return (*this)(currentMesh(), parms[0].toFloat(), parms[1].toFloat());
+    }
+  
+    bool operator()(Mesh* mesh, float radius1, float radius2);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Difference of Gaussians"; }
+    QString description() const { return "Calculate a difference of Gaussians for the mesh signal"; }
+    QStringList parmNames() const { return QStringList() << QString("Radius1 (%1)").arg(UM) << QString("Radius2 (%1)").arg(UM); }
+    QStringList parmDescs() const { return QStringList() << "Size of first neighborhood" << "Size of second neighborhood"; }
+    QStringList parmDefaults() const { return QStringList() << "1.0" << "5.0"; }
+    QIcon icon() const { return QIcon(":/images/Blur.png"); }
+  };
+  
+  /**
+   * \class MeshLocalMinima MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Find the local minima in the current mesh.
+   */
+  class MGX_EXPORT MeshLocalMinima : public MeshProcess {
+  public:
+    MeshLocalMinima(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      return (*this)(currentMesh(), parms[0].toFloat());
+    }
+  
+    bool operator()(Mesh* mesh, float radius);
+  
+    QString folder() const { return "Segmentation"; }
+    QString name() const { return "Auto-Seeding"; }
+    QString description() const { return "Put a seed at local minima of mesh signal."; }
+    QStringList parmNames() const { return QStringList() << QString("Radius (%1)").arg(UM); }
+    QStringList parmDescs() const { return QStringList() 
+      << "Size of neighborhood used for search of local minima. Typically, "
+         "the radius of smallest cells in the sample.";
+    }
+    QStringList parmDefaults() const { return QStringList() << "3.0"; }
+    QIcon icon() const { return QIcon(":/images/LocalMinima.png"); }
+  };
+  
+  /**
+   * \claass MeshNormalize MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Local normalization of the mesh signal.
+   */
+  class MGX_EXPORT MeshNormalize : public MeshProcess {
+  public:
+    MeshNormalize(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      return (*this)(currentMesh(), parms[0].toFloat());
+    }
+  
+    bool operator()(Mesh* mesh, float radius);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Normalize Signal"; }
+    QString description() const { return "Normalize mesh signal locally."; }
+    QStringList parmNames() const { return QStringList() << QString("Radius (%1)").arg(UM); }
+    QStringList parmDescs() const { return QStringList() << "Size of neighborhood used for normalization."; }
+    QStringList parmDefaults() const { return QStringList() << "5.0"; }
+    QIcon icon() const { return QIcon(":/images/Normalize.png"); }
+  };
+  
+  /**
+   * \class MeshDilation MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Morphological dilation on the mesh, using a spherical kernel. This process
+   * replace the signal intensity on each vertex with the maximum within a
+   * given distance.
+   */
+  class MeshDilation : public MeshProcess {
+  public:
+    MeshDilation(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      return (*this)(currentMesh(), parms[0].toFloat());
+    }
+  
+    bool operator()(Mesh* mesh, float radius);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Dilate Signal"; }
+    QString description() const { return "Morphological dilation of signal on mesh."; }
+    QStringList parmNames() const { return QStringList() << QString("Radius (%1)").arg(UM); }
+    QStringList parmDescs() const { return QStringList() << "Size of neighborhood used for dilation."; }
+    QStringList parmDefaults() const { return QStringList() << "1.0"; }
+    QIcon icon() const { return QIcon(":/images/Dilate.png"); }
+  };
+  
+  /**
+   * \class MeshErosion MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Morphological erosion on the mesh, using a spherical kernel. This process
+   * replace the signal intensity on each vertex with the minimum within a
+   * given distance.
+   */
+  class MeshErosion : public MeshProcess {
+  public:
+    MeshErosion(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      return (*this)(currentMesh(), parms[0].toFloat());
+    }
+  
+    bool operator()(Mesh* mesh, float radius);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Erode Signal"; }
+    QString description() const { return "Apply morphological erosion to mesh signal (opposite to Dilate Signal)."; }
+    QStringList parmNames() const { return QStringList() << QString("Radius (%1)").arg(UM); }
+    QStringList parmDescs() const { return QStringList() << "Size of neighborhood used for erosion."; }
+    QStringList parmDefaults() const { return QStringList() << "1.0"; }
+    QIcon icon() const { return QIcon(":/images/Erode.png"); }
+  };
+  
+  /**
+   * \class MeshClosing MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Morphological closing on the mesh. This process is equivalent to call the
+   * MeshDilation followed by MeshErosion with the same size.
+   */
+  class MeshClosing : public MeshProcess {
+  public:
+    MeshClosing(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      return (*this)(currentMesh(), parms[0].toFloat());
+    }
+  
+    bool operator()(Mesh* mesh, float radius);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Close Signal"; }
+    QString description() const { return "Apply morphological dilation followed by erosion to mesh signal."; }
+    QStringList parmNames() const { return QStringList() << QString::fromWCharArray(L"Radius (\xb5m)"); }
+    QStringList parmDescs() const { return QStringList() << "Size of neighborhood used for dilation/erosion."; }
+    QStringList parmDefaults() const { return QStringList() << "1.0"; }
+    QIcon icon() const { return QIcon(":/images/Closing.png"); }
+  };
+  
+  /**
+   * \class MeshOpening MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Morphological opening on the mesh. This process is equivalent to call the
+   * MeshErosion followed by MeshDilation with the same size.
+   */
+  class MeshOpening : public MeshProcess {
+  public:
+    MeshOpening(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      return (*this)(currentMesh(), parms[0].toFloat());
+    }
+  
+    bool operator()(Mesh* mesh, float radius);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Open Signal"; }
+    QString description() const { return "Apply morphological erosion followed by dilation to mesh signal."; }
+    QStringList parmNames() const { return QStringList() << QString::fromWCharArray(L"Radius (\xb5m)"); }
+    QStringList parmDescs() const { return QStringList() << "Size of neighborhood used for erosion/dilation."; }
+    QStringList parmDefaults() const { return QStringList() << "1.0"; }
+    QIcon icon() const { return QIcon(":/images/Opening.png"); }
+  };
+  
+  class MGX_EXPORT RescaleSignal : public MeshProcess {
+  public:
+    RescaleSignal(const MeshProcess& process) : Process(process) , MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY))
+        return false;
+      bool ok;
+      float percentile = parms[1].toFloat(&ok);
+      if(!ok)
+        return setErrorMessage("Error, argument 'Percentile' must be a number");
+      float minimum = parms[2].toFloat(&ok);
+      if(!ok)
+        return setErrorMessage("Error, argument 'Minimum' must be a number");
+      float maximum = parms[3].toFloat(&ok);
+      if(!ok)
+        return setErrorMessage("Error, argument 'Maximum' must be a number");
+      return (*this)(currentMesh(), stringToBool(parms[0]), percentile, minimum, maximum);
+    }
+  
+    bool operator()(Mesh* mesh, bool use_zero, float percentile, float minimum, float maximum);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Rescale Signal"; }
+    QString description() const { return 
+        "Change the colorbar of the signal.\n"
+        "If percentile is set to 0, it uses the minimum and maximum arguments.\n"
+        "Only the visualization is affected, the signal projection remains unchanged";
+    }
+    QStringList parmNames() const { return QStringList() 
+      << "Zero as reference" << "Percentile" << "Minimum" << "Maximum";
+    }
+    QStringList parmDescs() const { return QStringList()
+      << "If true, 0 will be used as a reference.\n"
+         "If the signal is all positive (resp. negative), 0 will be added as a minimum (resp. maximum).\n"
+         "If the signal is both positive and negative, 0 will be place at the center of the range"
+      << "Keep only this percentage of the signal to compute the range."
+      << "If the percentile specified is 0, uses this as the minimum value for the range"
+      << "If the percentile specified is 0, uses this as the maximum value for the range";
+    }
+    QStringList parmDefaults() const { return QStringList() << "No" << "99" << "0" << "1"; }
+  
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[0] = booleanChoice();
+      return map;
+    }
+  
+    QIcon icon() const { return QIcon(":/images/Normalize.png"); }
+  };
+  
+  /**
+   * \class SetSignalProcess MeshProcessSignal.hpp <MeshProcessSignal.hpp>
+   *
+   * Set the signal to a given value for all currently active vertices.
+   */
+  class MGX_EXPORT SetSignalProcess : public MeshProcess {
+  public:
+    SetSignalProcess(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(not checkState().mesh(MESH_VISIBLE))
+        return false;
+      bool ok;
+      float value = parms[0].toFloat(&ok);
+      if(not ok)
+        return setErrorMessage("Parameter 'Value' must be a number");
+      float percentile = parms[2].toFloat(&ok);
+      if(not ok)
+        return setErrorMessage("Parameter 'Percentile' must be a number");
+      return (*this)(currentMesh(), value, stringToBool(parms[1]), percentile, stringToBool(parms[3]));
+    }
+  
+    bool operator()(Mesh* m, float value, bool rescale, float percentile, bool use_zero);
+  
+    QString folder() const { return "Signal"; }
+    QString name() const { return "Set Signal"; }
+    QString description() const { return "Set the signal for the whole mesh, or for the currently selected part of it."; }
+  
+    QStringList parmNames() const { return QStringList() << "Value" << "Rescale" << "Percentile" << "Use zero"; }
+    QStringList parmDescs() const { return QStringList() 
+      << "New value for the signal"
+      << "If true, the signal bounds will be rescaled"
+      << "If rescaling, which percentile to use?"
+      << "If rescaling, should we use zero as reference?";
+    }
+    QStringList parmDefaults() const { return QStringList() << "1" << "Yes" << "100" << "No"; }
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[1] = booleanChoice();
+      map[3] = booleanChoice();
+      return map;
+    }
+    QIcon icon() const { return QIcon(":/images/Sharpen.png"); }
+  };
+  
+  ///@}
+  
+  class MGX_EXPORT ProjectCurvatureOp {
+  public:
+    ProjectCurvatureOp(const vvgraph& S, const VtxVec& vs, std::string type, float radius, FloatVec& values,
+                       std::vector<util::Curvature>& curvs);
+    void operator()(int i);
+  
+  private:
+    const vvgraph& S;
+    const VtxVec& vs;
+    std::string type;
+    float radius;
+    FloatVec& values;
+    std::vector<util::Curvature>& curvs;
+  };
+  
+  class MGX_EXPORT MeshGaussianBlurOp {
+  public:
+    MeshGaussianBlurOp(const vvgraph& S, const VtxVec& vs, float radius);
+    void operator()(int i);
+  
+  private:
+    const vvgraph& S;
+    const VtxVec& vs;
+    float radius;
+  };
+  
+  class MGX_EXPORT MeshLocalMinimaOp {
+  public:
+    MeshLocalMinimaOp(const vvgraph& S, const VtxVec& vs, float radius, int startLabel);
+    void operator()(int i);
+  
+  private:
+    const vvgraph& S;
+    const VtxVec& vs;
+    float radius;
+    int label;
+  };
+  
+  class MGX_EXPORT MeshNormalizeOp {
+  public:
+    MeshNormalizeOp(const vvgraph& S, const VtxVec& vs, float radius);
+  
+    void operator()(int i);
+  
+  private:
+    const vvgraph& S;
+    const VtxVec& vs;
+    float radius;
+  };
+  
+  class MeshDilationOp {
+  public:
+    MeshDilationOp(const vvgraph& S, const VtxVec& vs, float radius);
+    void operator()(int vi);
+  
+  private:
+    const vvgraph& S;
+    const VtxVec& vs;
+    float radius;
+  };
+  
+  class MeshErosionOp {
+  public:
+    MeshErosionOp(const vvgraph& S, const VtxVec& vs, float radius);
+    void operator()(int vi);
+  
+  private:
+    const vvgraph& S;
+    const VtxVec& vs;
+    float radius;
+  };
 
-  QStringList parmNames() const
-  {
-    return QStringList() << "Show Surface"
-                         << "Surface Type"
-                         << "Signal Type"
-                         << "Blend"
-                         << "Cull"
-                         << "Show Mesh"
-                         << "Mesh View"
-                         << "Show Lines"
-                         << "Show Points"
-                         << "Show Map"
-                         << "Scale"
-                         << "Transform"
-                         << "BBox"
-                         << "Brightness"
-                         << "Opacity";
-  }
+}} 
 
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Draw mesh as a continuous surface."
-                         << "Nrml: show projected signal, Labels: color triangles according to assigned "
-              "labels, Parents: color triangles with parent labels, Heat: color triangles "
-              "with computed heat map (e.g. growth)"
-                         << "Signal: show projected signal, Tex: Use 3D stack as texture, Img: Use 2D "
-              "texture (height map)."
-                         << "Semi-transparent mesh, for example to superimpose to meshes or view the "
-              "stack through the mesh."
-                         << "Color the triangles (with signal or labels) only on the top of the mesh."
-                         << "Draw triangle edges and nodes"
-                         << "All: draw all triangles. Border: draw outside edge of the mesh only. "
-              "Cells: draw cell outlines only. Selected: draw selected nodes only. "
-                         << "Show connecting lines between nodes in the mesh."
-                         << "Show mesh nodes."
-                         << "Mapping of text on the labels (e.g. label number)"
-                         << "Change scaling of mesh/stacks, independently in 3 directions (x,y,z). NB: "
-                         << "a stack saved with 'Scale' turned on will have a modified voxel size, "
-              "while saved meshes are unaffected. "
-                         << "Apply rotation and translation to the mesh/stack."
-                         << "Display the bounding box (i.e. total size) of a stack."
-                         << "Brightness of signal, labels or heat"
-                         << "Opacity of signal, labels or heat";
-  }
-
-  QStringList parmDefaults() const
-  {
-    return QStringList() << ""
-                         << ""
-                         << ""
-                         << ""
-                         << ""
-                         << ""
-                         << ""
-                         << ""
-                         << ""
-                         << ""
-                         << ""
-                         << ""
-                         << ""
-                         << "-1"
-                         << "-1";
-  }
-
-  ParmChoiceMap parmChoice() const
-  {
-    QStringList bools = QStringList() << "" << booleanChoice();
-    ParmChoiceMap map;
-    map[0] = bools;
-    map[1] = QStringList() << ""
-                           << "Normal"
-                           << "Heat"
-                           << "Label";
-    map[2] = QStringList() << ""
-                           << "Signal"
-                           << "Texture"
-                           << "Image";
-    map[3] = map[4] = map[5] = bools;
-    map[6] = QStringList() << ""
-                           << "All"
-                           << "Border"
-                           << "Cells"
-                           << "Selected";
-    map[7] = map[8] = map[9] = map[10] = map[11] = map[12] = bools;
-    return map;
-  }
-
-  QIcon icon() const {
-    return QIcon(":/images/Palette.png");
-  }
-};
-
-/**
- * \class ProjectSignal MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Project stack signal onto the current mesh.
- */
-class MGX_EXPORT ProjectSignal : public MeshProcess {
-public:
-  ProjectSignal(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().store(STORE_NON_LABEL).mesh(MESH_NON_EMPTY))
-      return false;
-    return (*this)(currentStack()->currentStore(), currentMesh(), stringToBool(parms[0]), parms[1].toFloat(),
-                   parms[2].toFloat(), parms[3].toFloat(), parms[4].toFloat());
-  }
-
-  bool operator()(const Store* store, Mesh* mesh, bool useAbsSignal, float minDist, float maxDist, float absSignalMin,
-                  float absSignalMax);
-  void projSignal(const Stack* stack, const HVecUS& data, vertex v, float mindist, float maxdist);
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Project Signal";
-  }
-  QString description() const {
-    return "Project signal onto mesh, perpendicular to its curved surface.";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Use absolute" << QString("Min Dist (%1)").arg(UM) << QString("Max Dist (%1)").arg(UM)
-                         << "Min Signal"
-                         << "Max Signal";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Use absolute values of signal, instead of normalizing it. "
-                            "Useful for signal quantification!"
-                         << "Distance (triangle-voxel) above which the signal is projected."
-                         << "Maximal distance (triangle-voxel) used for signal projection."
-                         << "Lower bound of signal value if 'Use absolute' is chosen"
-                         << "Upper bound of projected signal value.";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "No"
-                         << "2.0"
-                         << "6.0"
-                         << "0.0"
-                         << "60000.0";
-  }
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[0] = booleanChoice();
-    return map;
-  }
-  QIcon icon() const {
-    return QIcon(":/images/ProjectColor.png");
-  }
-};
-
-/**
- * \class SmoothMeshSignal MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Smooth the mesh signal using local averaging.
- */
-class MGX_EXPORT SmoothMeshSignal : public MeshProcess {
-public:
-  SmoothMeshSignal(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    return (*this)(currentMesh(), parms[0].toUInt());
-  }
-
-  bool operator()(Mesh* mesh, uint passes);
-
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Smooth Mesh Signal";
-  }
-  QString description() const {
-    return "Averages the signal of each node, based on its immediate neighbors.";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Passes";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Number of smoothing iterations.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "3";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/SmoothColor.png");
-  }
-};
-
-/**
- * \class ClearMeshSignal MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Clear the mesh signal to a defined value.
- */
-class MGX_EXPORT ClearMeshSignal : public MeshProcess {
-public:
-  ClearMeshSignal(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    return (*this)(currentMesh(), parms[0].toUInt());
-  }
-
-  bool operator()(Mesh* mesh, uint value);
-
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Clear Mesh Signal";
-  }
-  QString description() const {
-    return "Erase the signal on the mesh";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Value";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Assign this signal value to the entire mesh.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "50000";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/ClearSignal.png");
-  }
-};
-
-/**
- * \class ProjectCurvature MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Set the mesh signal to be the curvature of the mesh. The process can also
- * output a CSV file with the full curvature tensor for each vertex.
- */
-class MGX_EXPORT ProjectCurvature : public MeshProcess {
-public:
-  ProjectCurvature(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    bool ok;
-    float neighborhood = parms[2].toFloat(&ok);
-    if(not ok)
-      return setErrorMessage("Error, parameter 'Neighborhood' must be a number");
-    float mincurv = parms[4].toFloat(&ok);
-    if(not ok)
-      return setErrorMessage("Error, parameter 'Min Curv' must be a number");
-    float maxcurv = parms[5].toFloat(&ok);
-    if(not ok)
-      return setErrorMessage("Error, parameter 'Max Curv' must be a number");
-    float percentile = parms[6].toFloat(&ok);
-    if(not ok)
-      return setErrorMessage("Error, parameter 'Percentile' must be a number");
-    return (*this)(currentMesh(), parms[0], parms[1], neighborhood, stringToBool(parms[3]), mincurv, maxcurv,
-                   percentile);
-  }
-
-  bool operator()(Mesh* mesh, QString output, QString type, float neighborhood, bool auto_scale, float mincurv,
-                  float maxcurv, int percentile);
-
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Project Mesh Curvature";
-  }
-  QString description() const
-  {
-    return "Compute curvature at each node of the mesh, for a given neighborhood size. "
-           "Curvature values are stored as signal.";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Output"
-                         << "Type" << QString("Neighborhood (%1)").arg(UM) << "AutoScale"
-                         << "Min Curv"
-                         << "Max Curv"
-                         << "Autoscale percentile";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Name of output file, if desired."
-                         << "Minimal = minCurv, Maximal = maxCurv, Gaussian = maxCurv * minCurv, "
-              "SumSquare = maxCurv^2 + minCurv^2, Average = (maxCurv + minCurv)/2, "
-              "SignedAverageAbs = sign(max or min) x (abs(maxCurv) + abs(minCurv))/2"
-                         << QString("Neighborhood (%1)").arg(UM)
-                         << "Clip max and min signal range according to curvature distribution"
-                         << "Minimal curvature value displayed"
-                         << "Maximal curvature value displayed"
-                         << "Auto-scale signal range based on curvature percentile";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << ""
-                         << "Gaussian"
-                         << "3.0"
-                         << "Yes"
-                         << "-50.0"
-                         << "50.0"
-                         << "85";
-  }
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[1] = QStringList() << "Minimal"
-                           << "Maximal"
-                           << "Gaussian"
-                           << "SumSquare"
-                           << "Average"
-                           << "SignedAverageAbs";
-    map[3] = booleanChoice();
-    return map;
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Curvature.png");
-  }
-};
-
-/**
- * \class MeshGaussianBlur MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Smooth the mesh signal using a gaussian kernel.
- */
-class MGX_EXPORT MeshGaussianBlur : public MeshProcess {
-public:
-  MeshGaussianBlur(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    return (*this)(currentMesh(), parms[0].toFloat());
-  }
-
-  bool operator()(Mesh* mesh, float radius);
-
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Gaussian Blur";
-  }
-  QString description() const {
-    return "Apply Gaussian Blur to mesh signal";
-  }
-  QStringList parmNames() const {
-    return QStringList() << QString("Radius (%1)").arg(UM);
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Size of neighborhood used for Gaussian blur. The blur function standard "
-                            "deviation is given by sigma = radius/2. ";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "2.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Blur.png");
-  }
-};
-
-/**
- * \class MeshDiffGaussians MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Calculate a difference of Gaussians on mesh.
- */
-class MGX_EXPORT MeshDiffGaussians : public MeshProcess {
-public:
-  MeshDiffGaussians(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    return (*this)(currentMesh(), parms[0].toFloat(), parms[1].toFloat());
-  }
-
-  bool operator()(Mesh* mesh, float radius1, float radius2);
-
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Difference of Gaussians";
-  }
-  QString description() const {
-    return "Calculate a difference of Gaussians for the mesh signal";
-  }
-  QStringList parmNames() const {
-    return QStringList() << QString("Radius1 (%1)").arg(UM) << QString("Radius2 (%1)").arg(UM);
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Size of first neighborhood" << "Size of second neighborhood";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "1.0" << "5.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Blur.png");
-  }
-};
-
-/**
- * \class MeshLocalMinima MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Find the local minima in the current mesh.
- */
-class MGX_EXPORT MeshLocalMinima : public MeshProcess {
-public:
-  MeshLocalMinima(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    return (*this)(currentMesh(), parms[0].toFloat());
-  }
-
-  bool operator()(Mesh* mesh, float radius);
-
-  QString folder() const {
-    return "Segmentation";
-  }
-  QString name() const {
-    return "Auto-Seeding";
-  }
-  QString description() const {
-    return "Put a seed at local minima of mesh signal.";
-  }
-  QStringList parmNames() const {
-    return QStringList() << QString("Radius (%1)").arg(UM);
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Size of neighborhood used for search of local minima. Typically, "
-                            "the radius of smallest cells in the sample.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "3.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/LocalMinima.png");
-  }
-};
-
-/**
- * \claass MeshNormalize MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Local normalization of the mesh signal.
- */
-class MGX_EXPORT MeshNormalize : public MeshProcess {
-public:
-  MeshNormalize(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    return (*this)(currentMesh(), parms[0].toFloat());
-  }
-
-  bool operator()(Mesh* mesh, float radius);
-
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Normalize Signal";
-  }
-  QString description() const {
-    return "Normalize mesh signal locally.";
-  }
-  QStringList parmNames() const {
-    return QStringList() << QString("Radius (%1)").arg(UM);
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Size of neighborhood used for normalization.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "5.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Normalize.png");
-  }
-};
-
-/**
- * \class MeshDilation MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Morphological dilation on the mesh, using a spherical kernel. This process
- * replace the signal intensity on each vertex with the maximum within a
- * given distance.
- */
-class MeshDilation : public MeshProcess {
-public:
-  MeshDilation(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    return (*this)(currentMesh(), parms[0].toFloat());
-  }
-
-  bool operator()(Mesh* mesh, float radius);
-
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Dilate Signal";
-  }
-  QString description() const {
-    return "Morphological dilation of signal on mesh.";
-  }
-  QStringList parmNames() const {
-    return QStringList() << QString("Radius (%1)").arg(UM);
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Size of neighborhood used for dilation.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "1.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Dilate.png");
-  }
-};
-
-/**
- * \class MeshErosion MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Morphological erosion on the mesh, using a spherical kernel. This process
- * replace the signal intensity on each vertex with the minimum within a
- * given distance.
- */
-class MeshErosion : public MeshProcess {
-public:
-  MeshErosion(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    return (*this)(currentMesh(), parms[0].toFloat());
-  }
-
-  bool operator()(Mesh* mesh, float radius);
-
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Erode Signal";
-  }
-  QString description() const {
-    return "Apply morphological erosion to mesh signal (opposite to Dilate Signal).";
-  }
-  QStringList parmNames() const {
-    return QStringList() << QString("Radius (%1)").arg(UM);
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Size of neighborhood used for erosion.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "1.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Erode.png");
-  }
-};
-
-/**
- * \class MeshClosing MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Morphological closing on the mesh. This process is equivalent to call the
- * MeshDilation followed by MeshErosion with the same size.
- */
-class MeshClosing : public MeshProcess {
-public:
-  MeshClosing(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    return (*this)(currentMesh(), parms[0].toFloat());
-  }
-
-  bool operator()(Mesh* mesh, float radius);
-
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Close Signal";
-  }
-  QString description() const {
-    return "Apply morphological dilation followed by erosion to mesh signal.";
-  }
-  QStringList parmNames() const {
-    return QStringList() << QString::fromWCharArray(L"Radius (\xb5m)");
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Size of neighborhood used for dilation/erosion.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "1.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Closing.png");
-  }
-};
-
-/**
- * \class MeshOpening MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Morphological opening on the mesh. This process is equivalent to call the
- * MeshErosion followed by MeshDilation with the same size.
- */
-class MeshOpening : public MeshProcess {
-public:
-  MeshOpening(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    return (*this)(currentMesh(), parms[0].toFloat());
-  }
-
-  bool operator()(Mesh* mesh, float radius);
-
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Open Signal";
-  }
-  QString description() const {
-    return "Apply morphological erosion followed by dilation to mesh signal.";
-  }
-  QStringList parmNames() const {
-    return QStringList() << QString::fromWCharArray(L"Radius (\xb5m)");
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Size of neighborhood used for erosion/dilation.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "1.0";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Opening.png");
-  }
-};
-
-class MGX_EXPORT RescaleSignal : public MeshProcess {
-public:
-  RescaleSignal(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY))
-      return false;
-    bool ok;
-    float percentile = parms[1].toFloat(&ok);
-    if(!ok)
-      return setErrorMessage("Error, argument 'Percentile' must be a number");
-    float minimum = parms[2].toFloat(&ok);
-    if(!ok)
-      return setErrorMessage("Error, argument 'Minimum' must be a number");
-    float maximum = parms[3].toFloat(&ok);
-    if(!ok)
-      return setErrorMessage("Error, argument 'Maximum' must be a number");
-    return (*this)(currentMesh(), stringToBool(parms[0]), percentile, minimum, maximum);
-  }
-
-  bool operator()(Mesh* mesh, bool use_zero, float percentile, float minimum, float maximum);
-
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Rescale Signal";
-  }
-  QString description() const
-  {
-    return "Change the colorbar of the signal.\n"
-           "If percentile is set to 0, it uses the minimum and maximum arguments.";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Zero as reference"
-                         << "Percentile"
-                         << "Minimum"
-                         << "Maximum";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList()
-           << "If true, 0 will be used as a reference.\n"
-              "If the signal is all positive (resp. negative), 0 will be added as a minimum (resp. maximum).\n"
-              "If the signal is both positive and negative, 0 will be place at the center of the range"
-           << "Keep only this percentage of the signal to compute the range."
-           << "If the percentile specified is 0, uses this as the minimum value for the range"
-           << "If the percentile specified is 0, uses this as the maximum value for the range";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "No"
-                         << "99"
-                         << "0"
-                         << "1";
-  }
-
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[0] = booleanChoice();
-    return map;
-  }
-
-  QIcon icon() const {
-    return QIcon(":/images/Normalize.png");
-  }
-};
-
-/**
- * \class SetSignalProcess MeshProcessSignal.hpp <MeshProcessSignal.hpp>
- *
- * Set the signal to a given value for all currently active vertices.
- */
-class MGX_EXPORT SetSignalProcess : public MeshProcess {
-public:
-  SetSignalProcess(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& parms)
-  {
-    if(not checkState().mesh(MESH_VISIBLE))
-      return false;
-    bool ok;
-    float value = parms[0].toFloat(&ok);
-    if(not ok)
-      return setErrorMessage("Parameter 'Value' must be a number");
-    float percentile = parms[2].toFloat(&ok);
-    if(not ok)
-      return setErrorMessage("Parameter 'Percentile' must be a number");
-    return (*this)(currentMesh(), value, stringToBool(parms[1]), percentile, stringToBool(parms[3]));
-  }
-
-  bool operator()(Mesh* m, float value, bool rescale, float percentile, bool use_zero);
-
-  QString folder() const {
-    return "Signal";
-  }
-  QString name() const {
-    return "Set Signal";
-  }
-  QString description() const
-  {
-    return "Set the signal for the whole mesh, or for the currently selected part of it.";
-  }
-
-  QStringList parmNames() const
-  {
-    return QStringList() << "Value"
-                         << "Rescale"
-                         << "Percentile"
-                         << "Use zero";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "New value for the signal"
-                         << "If true, the signal bounds will be rescaled"
-                         << "If rescaling, which percentile to use?"
-                         << "If rescaling, should we use zero as reference?";
-  }
-
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "1"
-                         << "Yes"
-                         << "100"
-                         << "No";
-  }
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[1] = booleanChoice();
-    map[3] = booleanChoice();
-    return map;
-  }
-
-  QIcon icon() const {
-    return QIcon(":/images/Sharpen.png");
-  }
-};
-
-///@}
-
-class MGX_EXPORT ProjectCurvatureOp {
-public:
-  ProjectCurvatureOp(const vvgraph& S, const VtxVec& vs, std::string type, float radius, FloatVec& values,
-                     std::vector<util::Curvature>& curvs);
-  void operator()(int i);
-
-private:
-  const vvgraph& S;
-  const VtxVec& vs;
-  std::string type;
-  float radius;
-  FloatVec& values;
-  std::vector<util::Curvature>& curvs;
-};
-
-class MGX_EXPORT MeshGaussianBlurOp {
-public:
-  MeshGaussianBlurOp(const vvgraph& S, const VtxVec& vs, float radius);
-  void operator()(int i);
-
-private:
-  const vvgraph& S;
-  const VtxVec& vs;
-  float radius;
-};
-
-class MGX_EXPORT MeshLocalMinimaOp {
-public:
-  MeshLocalMinimaOp(const vvgraph& S, const VtxVec& vs, float radius, int startLabel);
-  void operator()(int i);
-
-private:
-  const vvgraph& S;
-  const VtxVec& vs;
-  float radius;
-  int label;
-};
-
-class MGX_EXPORT MeshNormalizeOp {
-public:
-  MeshNormalizeOp(const vvgraph& S, const VtxVec& vs, float radius);
-
-  void operator()(int i);
-
-private:
-  const vvgraph& S;
-  const VtxVec& vs;
-  float radius;
-};
-
-class MeshDilationOp {
-public:
-  MeshDilationOp(const vvgraph& S, const VtxVec& vs, float radius);
-  void operator()(int vi);
-
-private:
-  const vvgraph& S;
-  const VtxVec& vs;
-  float radius;
-};
-
-class MeshErosionOp {
-public:
-  MeshErosionOp(const vvgraph& S, const VtxVec& vs, float radius);
-  void operator()(int vi);
-
-private:
-  const vvgraph& S;
-  const VtxVec& vs;
-  float radius;
-};
-} // namespace process
-} // namespace mgx
-
 #endif
Index: CutSurf.hpp
===================================================================
--- CutSurf.hpp	(revision 1255)
+++ CutSurf.hpp	(revision 1256)
@@ -11,93 +11,93 @@
 #include <Parms.hpp>
 
 namespace mgx {
-typedef util::Color<float> Color3f;
-class Shader;
-class ImgData;
-class Stack;
 
-typedef util::Vector<2, int> Point2i;
-typedef util::Vector<3, float> Point3f;
-
-// Class to handle rotatable cutting plane.
-class MGX_EXPORT CutSurf : public QObject {
-  Q_OBJECT
-public:
-  CutSurf();
-  ~CutSurf();
-
-  CuttingSurface* cut;
-
-  std::set<uint> selectV;   // List of selected vertices
-
-protected:
-  uint BlendSlices;
-  uint Material;
-  float LineWidth;
-
-  void drawSurface(ImgData& stk, bool select);
-
-public:
-  // Read clipping plane parameters
-  void readParms(util::Parms& parms, QString section);
-
-  // write parms to file
-  void writeParms(QTextStream& out, QString section);
-
-  // Draw cutting plane
-  void drawCutSurf(ImgData& stk, bool select, Shader* shader = 0);
-  void drawCutSurfGrid(ImgData& stk);
-  void drawSelect();
-
-  // Get frame
-  qglviewer::ManipulatedFrame* getFrame() {
-    return &cut->frame();
-  }
-
-  // Clear selection
-  void clearSelect();
-
-  // Find the spline point selected
-  int findSelectPoint(uint x, uint y);
-
-  // Return true if the cutting surface is opaque if drawn for this stack
-  bool showOpaqueSurface(const ImgData& stk);
-
-  // Return true if the cutting surface is transparent if drawn for this stack
-  bool showTransparentSurface(const ImgData& stk);
-
-  float getSceneRadius() {
-    return SceneRadius;
+  typedef util::Color<float> Color3f;
+  class Shader;
+  class ImgData;
+  class Stack;
+  
+  // Class to handle rotatable cutting plane.
+  class MGX_EXPORT CutSurf : public QObject {
+    Q_OBJECT
+  public:
+    CutSurf();
+    ~CutSurf();
+  
+    CuttingSurface* cut;
+  
+    std::set<uint> selectV;   // List of selected vertices
+  
+  protected:
+    uint BlendSlices;
+    uint Material;
+    float LineWidth;
+  
+    void drawSurface(ImgData& stk, bool select);
+  
+  public:
+    // Read clipping plane parameters
+    void readParms(util::Parms& parms, QString section);
+  
+    // write parms to file
+    void writeParms(QTextStream& out, QString section);
+  
+    // Draw cutting plane
+    void drawCutSurf(ImgData& stk, bool select, Shader* shader = 0);
+    void drawCutSurfGrid(ImgData& stk);
+    void drawSelect();
+  
+    // Get frame
+    qglviewer::ManipulatedFrame* getFrame() {
+      return &cut->frame();
+    }
+  
+    // Clear selection
+    void clearSelect();
+  
+    // Find the spline point selected
+    int findSelectPoint(uint x, uint y);
+  
+    // Return true if the cutting surface is opaque if drawn for this stack
+    bool showOpaqueSurface(const ImgData& stk);
+  
+    // Return true if the cutting surface is transparent if drawn for this stack
+    bool showTransparentSurface(const ImgData& stk);
+  
+    float getSceneRadius() {
+      return SceneRadius;
+    };
+  
+  protected:
+    void initBez();
+    double SceneRadius;
+    float getSize(int val);
+  
+  public slots:
+    // Set sizes
+    void DrawCutSurfSlot(bool val);
+    void ThreeAxisSlot(bool val);
+    void CutSurfGridSlot(bool val);
+    void CutSurfPlaneSlot(bool val);
+    void CutSurfBezierSlot(bool val);
+    void SizeXSlot(int val);
+    void SizeYSlot(int val);
+    void SizeZSlot(int val);
+    void Reset(double sceneRadius);
+    void setSceneBoundingBox(const Point3f& bbox);
+  
+  signals:
+    void DrawCutSurfSignal(bool val);
+    void ThreeAxisSignal(bool val);
+    void CutSurfGridSignal(bool val);
+    void CutSurfPlaneSignal(bool val);
+    void CutSurfBezierSignal(bool val);
+    void SizeXSignal(int val);
+    void SizeYSignal(int val);
+    void SizeZSignal(int val);
+    void ViewerUpdateSignal();
   };
 
-protected:
-  void initBez();
-  double SceneRadius;
-  float getSize(int val);
+}
 
-public slots:
-  // Set sizes
-  void DrawCutSurfSlot(bool val);
-  void ThreeAxisSlot(bool val);
-  void CutSurfGridSlot(bool val);
-  void CutSurfPlaneSlot(bool val);
-  void CutSurfBezierSlot(bool val);
-  void SizeXSlot(int val);
-  void SizeYSlot(int val);
-  void SizeZSlot(int val);
-  void Reset(double sceneRadius);
-  void setSceneBoundingBox(const Point3f& bbox);
-
-signals:
-  void DrawCutSurfSignal(bool val);
-  void ThreeAxisSignal(bool val);
-  void CutSurfGridSignal(bool val);
-  void CutSurfPlaneSignal(bool val);
-  void CutSurfBezierSignal(bool val);
-  void SizeXSignal(int val);
-  void SizeYSignal(int val);
-  void SizeZSignal(int val);
-  void ViewerUpdateSignal();
-};
-} // namespace mgx
-#endif /*CUTTING_SURFACE_H*/
+#endif
Index: About.cpp
===================================================================
--- About.cpp	(revision 1255)
+++ About.cpp	(revision 1256)
@@ -7,21 +7,22 @@
 {
   return QString(
     "<h2>MorphoGraphX " VERSION " r" REVISION "</h2>"
-                                              "A tool for 2.5 & 3D cell segmentation, image processing, and more!<br><br>"
-                                              "Copyright \xA9 2012-2015 Richard S. Smith and collaborators.<br><br>"
-                                              "MorphoGraphX is licensed under the "
-                                              "<html><style type='text/css'></style><a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU "
-                                              "GPLv2.</a></html><br><br>"
-                                              "Please visit "
-                                              "<html><style type='text/css'></style><a href='http://www.MorphoGraphX.org'>MorphoGraphX.org</a></html>"
-                                              " for more information.<br><br>"
-                                              "If you use MorphoGraphX in your research, please "
-                                              "<html><style type='text/css'></style><a href='http://elifesciences.org'>reference</a></html>"
-                                              " us.<br><br>"
-                                              "Funding support:<dl>"
-                                              "\xb7 SystemsX.ch & the Swiss National Science Foundation<br>"
-                                              "\xb7 Max Planck Society<br>"
-                                              "\xb7 Human Frontiers Science Program<br>");
+    "A tool for 2.5 & 3D cell segmentation, image processing, and more!<br><br>"
+    "Copyright \xA9 2012-2015 Richard S. Smith and collaborators.<br><br>"
+    "MorphoGraphX is licensed under the "
+    "<html><style type='text/css'></style><a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU "
+    "GPLv2.</a></html><br><br>"
+    "Please visit "
+    "<html><style type='text/css'></style><a href='http://www.MorphoGraphX.org'>MorphoGraphX.org</a></html>"
+    " for more information.<br><br>"
+    "If you use MorphoGraphX in your research, please "
+    "<html><style type='text/css'></style><a href='http://dx.doi.org/10.7554/eLife.05864'>reference</a></html>"
+    " us.<br><br>"
+    "Funding support:<dl>"
+    "\xb7 SystemsX.ch & the Swiss National Science Foundation (SNF)<br>"
+    "\xb7 Max Planck Institute for Plant Breeding Research (MPIPZ)<br>"
+    "\xb7 German Federal Ministry of Education and Research (BMBF)<br>"
+    "\xb7 Human Frontiers Science Program (HFSP)<br>");
 }
 
 QString introText()
Index: ImageData.cpp
===================================================================
--- ImageData.cpp	(revision 1255)
+++ ImageData.cpp	(revision 1256)
@@ -16,3976 +16,3945 @@
 
 namespace mgx {
 
-typedef util::Vector<16, double> Point16d;
+  typedef util::Vector<16, double> Point16d;
+  
+  using Information::err;
+  
+  using namespace std;
+  using namespace util;
+  
+  // Static class varaibles
+  int ImgData::PixelEditRadius = 25;
+  int ImgData::PixelEditMaxPix = 1024000;
+  int ImgData::ClearColor = 0;
+  uint ImgData::Slices = 500u;
+  uint ImgData::TileCount = 20u;
+  Point3u ImgData::MaxTexSize = Point3u(2048u, 2048u, 2048u);
+  float ImgData::ZOffset = .0001f;
+  bool ImgData::SeedStack = false;
+  
+  float ImgData::DrawNormals = 0.0f;
+  float ImgData::DrawZeroLabels = 0.0f;
+  float ImgData::DrawNhbds = 0.0f;
+  float ImgData::DrawOffset = 2.0f;
+  bool ImgData::DeleteBadVertex = false;
+  bool ImgData::FillWorkData = false;
+  std::vector<Colorf> ImgData::LabelColors; // = std::vector<Point3f>(1);
+  
+  bool ImgData::MeshSelect;
+  ScaleBar ImgData::scaleBar;
+  Colorbar ImgData::colorBar;
+  
+  float ImgData::MeshPointSize = 1.0f;
+  float ImgData::MeshLineWidth = 1.0f;
+  
+  #ifdef WIN32
+  #  define FileDialogOptions QFileDialog::DontUseNativeDialog
+  #else
+  const int FileDialogOptions = 0;
+  #endif
+  
+  ImgData::ImgData(int id, QWidget* _parent)
+    : StackId(id), Main16Bit(false), Work16Bit(false), needUpdateLines(false), needUpdateTris(false),
+      newMainColorMap(true), newWorkColorMap(true), newSurfColorMap(true), newHeatColorMap(true),
+      mainDataTexId(0), workDataTexId(0), dataTexColor(0), surfTexId(0), heatTexId(0),
+      imgTexId(0), mcmapTexId(0), wcmapTexId(0), labelTexId(0), lineId(0), TCount(0),
+      LCount(0), VCount(0), posVAid(0), nrmlVAid(0), selVAid(0), texVAid(0), imgVAid(0),
+      pntsVAid(0), pcolVAid(0), pselVAid(0), texMap(0), parent(_parent), min(0), max(1),
+      labelWallBordMin(0), labelWallBordMax(1), pixelRadius(1), marchLabel(0), LoadMeshAdd(false),
+      meshShift(0), marchData(0), EnableRotate(false), readOnce(true), changed(false), pixelsChanged(false)
+  {
+    parent = _parent;
+    surfTransferDlg = new gui::TransferFunctionDlg(parent);
+    heatTransferDlg = new gui::TransferFunctionDlg(parent);
+    workTransferDlg = new gui::TransferFunctionDlg(parent);
+    mainTransferDlg = new gui::TransferFunctionDlg(parent);
+  }
+  
+  void ImgData::init(Stack* s, Mesh* m)
+  {
+    stack = s;
+    mesh = m;
+    mainTransferDlg->setDefaultTransferFunction(stack->main()->transferFct());
+    workTransferDlg->setDefaultTransferFunction(stack->work()->transferFct());
+    surfTransferDlg->setDefaultTransferFunction(mesh->surfFct());
+    heatTransferDlg->setDefaultTransferFunction(mesh->heatFct());
+    updateMainColorMap();
+    updateWorkColorMap();
+    updateSurfColorMap();
+    updateHeatColorMap();
+  }
+  
+  ImgData::~ImgData()
+  {
+    // Delete VBOs
+    if(posVAid)
+      glDeleteBuffers(1, &posVAid);
+    if(nrmlVAid)
+      glDeleteBuffers(1, &nrmlVAid);
+    if(texVAid)
+      glDeleteBuffers(1, &texVAid);
+    if(imgVAid)
+      glDeleteBuffers(1, &imgVAid);
+    if(selVAid)
+      glDeleteBuffers(1, &selVAid);
+    if(pntsVAid)
+      glDeleteBuffers(1, &pntsVAid);
+    if(pcolVAid)
+      glDeleteBuffers(1, &pcolVAid);
+    if(pselVAid)
+      glDeleteBuffers(1, &pselVAid);
+  
+    // Delete textures
+    if(mainDataTexId)
+      glDeleteTextures(1, &mainDataTexId);
+    if(workDataTexId)
+      glDeleteTextures(1, &workDataTexId);
+    if(surfTexId)
+      glDeleteTextures(1, &surfTexId);
+    if(heatTexId)
+      glDeleteTextures(1, &heatTexId);
+    if(imgTexId)
+      glDeleteTextures(1, &imgTexId);
+  
+    delete mainTransferDlg;
+    delete workTransferDlg;
+    delete surfTransferDlg;
+    delete heatTransferDlg;
+  }
+  
+  // Set parameters for function
+  void ImgData::readParms(util::Parms& parms, QString section)
+  {
+    Section = section;
+  
+    QString StackFile, WorkStackFile, MeshFile, ParentFile;
+    parms(section, "StackFile", StackFile, QString(""));
+    if(!StackFile.isEmpty())
+      StackFile = absoluteFilePath(StackFile);
+    stack->main()->setFile(StackFile);
+    parms(section, "WorkStackFile", WorkStackFile, QString(""));
+    if(!WorkStackFile.isEmpty())
+      WorkStackFile = absoluteFilePath(WorkStackFile);
+    stack->work()->setFile(WorkStackFile);
+    parms(section, "MeshFile", MeshFile, QString(""));
+    if(!MeshFile.isEmpty())
+      MeshFile = absoluteFilePath(MeshFile);
+    mesh->setFile(MeshFile);
+    parms(section, "ParentFile", ParentFile, QString(""));
+    if(!ParentFile.isEmpty())
+      ParentFile = absoluteFilePath(ParentFile);
+    mesh->setParentFile(ParentFile); 
 
-using Information::err;
-
-using namespace std;
-using namespace util;
-
-// Static class varaibles
-int ImgData::PixelEditRadius = 25;
-int ImgData::PixelEditMaxPix = 1024000;
-int ImgData::ClearColor = 0;
-uint ImgData::Slices = 500u;
-uint ImgData::TileCount = 20u;
-Point3u ImgData::MaxTexSize = Point3u(2048u, 2048u, 2048u);
-float ImgData::ZOffset = .0001f;
-bool ImgData::SeedStack = false;
-
-float ImgData::DrawNormals = 0.0f;
-float ImgData::DrawZeroLabels = 0.0f;
-float ImgData::DrawNhbds = 0.0f;
-float ImgData::DrawOffset = 2.0f;
-bool ImgData::DeleteBadVertex = false;
-bool ImgData::FillWorkData = false;
-std::vector<Colorf> ImgData::LabelColors; // = std::vector<Point3f>(1);
-
-bool ImgData::MeshSelect;
-ScaleBar ImgData::scaleBar;
-Colorbar ImgData::colorBar;
-
-float ImgData::MeshPointSize = 1.0f;
-float ImgData::MeshLineWidth = 1.0f;
-
-#ifdef WIN32
-#  define FileDialogOptions QFileDialog::DontUseNativeDialog
-#else
-const int FileDialogOptions = 0;
-#endif
-
-ImgData::ImgData(int id, QWidget* _parent)
-  : StackId(id)
-  , Main16Bit(false)
-  , Work16Bit(false)
-  , needUpdateLines(false)
-  , needUpdateTris(false)
-  , newMainColorMap(true)
-  , newWorkColorMap(true)
-  , newSurfColorMap(true)
-  , newHeatColorMap(true)
-  , mainDataTexId(0)
-  , workDataTexId(0)
-  , dataTexColor(0)
-  , surfTexId(0)
-  , heatTexId(0)
-  , imgTexId(0)
-  , mcmapTexId(0)
-  , wcmapTexId(0)
-  , labelTexId(0)
-  , lineId(0)
-  , TCount(0)
-  , LCount(0)
-  , VCount(0)
-  , posVAid(0)
-  , nrmlVAid(0)
-  , selVAid(0)
-  , texVAid(0)
-  , imgVAid(0)
-  , pntsVAid(0)
-  , pcolVAid(0)
-  , pselVAid(0)
-  , texMap(0)
-  , parent(_parent)
-  , min(0)
-  , max(1)
-  , labelWallBordMin(0)
-  , labelWallBordMax(1)
-  , pixelRadius(1)
-  , marchLabel(0)
-  , LoadMeshAdd(false)
-  , meshShift(0)
-  , marchData(0)
-  , EnableRotate(false)
-  , readOnce(true)
-  , changed(false)
-  , pixelsChanged(false)
-{
-  parent = _parent;
-  surfTransferDlg = new gui::TransferFunctionDlg(parent);
-  heatTransferDlg = new gui::TransferFunctionDlg(parent);
-  workTransferDlg = new gui::TransferFunctionDlg(parent);
-  mainTransferDlg = new gui::TransferFunctionDlg(parent);
-}
-
-void ImgData::init(Stack* s, Mesh* m)
-{
-  stack = s;
-  mesh = m;
-  mainTransferDlg->setDefaultTransferFunction(stack->main()->transferFct());
-  workTransferDlg->setDefaultTransferFunction(stack->work()->transferFct());
-  surfTransferDlg->setDefaultTransferFunction(mesh->surfFct());
-  heatTransferDlg->setDefaultTransferFunction(mesh->heatFct());
-  updateMainColorMap();
-  updateWorkColorMap();
-  updateSurfColorMap();
-  updateHeatColorMap();
-}
-
-ImgData::~ImgData()
-{
-  // Delete VBOs
-  if(posVAid)
-    glDeleteBuffers(1, &posVAid);
-  if(nrmlVAid)
-    glDeleteBuffers(1, &nrmlVAid);
-  if(texVAid)
-    glDeleteBuffers(1, &texVAid);
-  if(imgVAid)
-    glDeleteBuffers(1, &imgVAid);
-  if(selVAid)
-    glDeleteBuffers(1, &selVAid);
-  if(pntsVAid)
-    glDeleteBuffers(1, &pntsVAid);
-  if(pcolVAid)
-    glDeleteBuffers(1, &pcolVAid);
-  if(pselVAid)
-    glDeleteBuffers(1, &pselVAid);
-
-  // Delete textures
-  if(mainDataTexId)
-    glDeleteTextures(1, &mainDataTexId);
-  if(workDataTexId)
-    glDeleteTextures(1, &workDataTexId);
-  if(surfTexId)
-    glDeleteTextures(1, &surfTexId);
-  if(heatTexId)
-    glDeleteTextures(1, &heatTexId);
-  if(imgTexId)
-    glDeleteTextures(1, &imgTexId);
-
-  delete mainTransferDlg;
-  delete workTransferDlg;
-  delete surfTransferDlg;
-  delete heatTransferDlg;
-}
-
-// Set parameters for function
-void ImgData::readParms(util::Parms& parms, QString section)
-{
-  Section = section;
-
-  QString StackFile, WorkStackFile, MeshFile;
-  parms(section, "StackFile", StackFile, QString(""));
-  if(!StackFile.isEmpty())
-    StackFile = absoluteFilePath(StackFile);
-  stack->main()->setFile(StackFile);
-  parms(section, "WorkStackFile", WorkStackFile, QString(""));
-  if(!WorkStackFile.isEmpty())
-    WorkStackFile = absoluteFilePath(WorkStackFile);
-  stack->work()->setFile(WorkStackFile);
-  parms(section, "MeshFile", MeshFile, QString(""));
-  if(!MeshFile.isEmpty())
-    MeshFile = absoluteFilePath(MeshFile);
-  mesh->setFile(MeshFile);
-
-  bool MainShow;
-  parms(section, "MainShow", MainShow, true);
-  if(MainShow)
-    stack->main()->show();
-  else
-    stack->main()->hide();
-  float MainBright;
-  parms(section, "MainBright", MainBright, 1.0f);
-  stack->main()->setBrightness(MainBright);
-  float MainOpacity;
-  parms(section, "MainOpacity", MainOpacity, 0.8f);
-  stack->main()->setOpacity(MainOpacity);
-  parms(section, "Main16Bit", Main16Bit, false);
-  bool MainLabels;
-  parms(section, "MainLabels", MainLabels, false);
-  stack->main()->setLabels(MainLabels);
-
-  bool WorkShow;
-  parms(section, "WorkShow", WorkShow, false);
-  if(WorkShow)
-    stack->work()->show();
-  else
-    stack->work()->hide();
-  float WorkBright;
-  parms(section, "WorkBright", WorkBright, 1.0f);
-  stack->work()->setBrightness(WorkBright);
-  float WorkOpacity;
-  parms(section, "WorkOpacity", WorkOpacity, 0.8f);
-  stack->work()->setOpacity(WorkOpacity);
-  parms(section, "Work16Bit", Work16Bit, false);
-  bool WorkLabels;
-  parms(section, "WorkLabels", WorkLabels, false);
-  stack->work()->setLabels(WorkLabels);
-
-  if(WorkStackFile == StackFile) {
-    stack->work()->setFile(QString());
-    if(WorkShow) {
+    bool MainShow;
+    parms(section, "MainShow", MainShow, true);
+    if(MainShow)
       stack->main()->show();
+    else
+      stack->main()->hide();
+    float MainBright;
+    parms(section, "MainBright", MainBright, 1.0f);
+    stack->main()->setBrightness(MainBright);
+    float MainOpacity;
+    parms(section, "MainOpacity", MainOpacity, 0.8f);
+    stack->main()->setOpacity(MainOpacity);
+    parms(section, "Main16Bit", Main16Bit, false);
+    bool MainLabels;
+    parms(section, "MainLabels", MainLabels, false);
+    stack->main()->setLabels(MainLabels);
+  
+    bool WorkShow;
+    parms(section, "WorkShow", WorkShow, false);
+    if(WorkShow)
+      stack->work()->show();
+    else
       stack->work()->hide();
+    float WorkBright;
+    parms(section, "WorkBright", WorkBright, 1.0f);
+    stack->work()->setBrightness(WorkBright);
+    float WorkOpacity;
+    parms(section, "WorkOpacity", WorkOpacity, 0.8f);
+    stack->work()->setOpacity(WorkOpacity);
+    parms(section, "Work16Bit", Work16Bit, false);
+    bool WorkLabels;
+    parms(section, "WorkLabels", WorkLabels, false);
+    stack->work()->setLabels(WorkLabels);
+  
+    if(WorkStackFile == StackFile) {
+      stack->work()->setFile(QString());
+      if(WorkShow) {
+        stack->main()->show();
+        stack->work()->hide();
+      }
     }
+  
+    bool SurfShow;
+    parms(section, "SurfShow", SurfShow, true);
+    if(SurfShow)
+      mesh->showSurface();
+    else
+      mesh->hideSurface();
+    float SurfBright;
+    parms(section, "SurfBright", SurfBright, 1.0f);
+    mesh->setBrightness(SurfBright);
+    float SurfOpacity;
+    parms(section, "SurfOpacity", SurfOpacity, 1.0f);
+    mesh->setOpacity(SurfOpacity);
+    bool SurfCull, SurfBlend;
+    parms(section, "SurfBlend", SurfBlend, false);
+    parms(section, "SurfCull", SurfCull, true);
+    mesh->setCulling(SurfCull);
+    mesh->setBlending(SurfBlend);
+  
+    int SurfView;
+    parms(section, "SurfView", SurfView, (int)Mesh::LABEL);
+    mesh->show((Mesh::SurfView)SurfView);
+  
+    int SurfColor;
+    parms(section, "SurfColor", SurfColor, (int)Mesh::SIGNAL);
+    mesh->show((Mesh::Color)SurfColor);
+  
+    bool MeshShow, MeshPoints, MeshLines;
+    parms(section, "MeshShow", MeshShow, false);
+    mesh->setShowMesh(MeshShow);
+    parms(section, "MeshPoints", MeshPoints, true);
+    mesh->setShowMeshPoints(MeshPoints);
+    parms(section, "MeshLines", MeshLines, true);
+    mesh->setShowMeshLines(MeshLines);
+    int mvm;
+    parms(section, "MeshViewMode", mvm, (int)Mesh::SELECTED_MESH);
+    mesh->show((Mesh::MeshView)mvm);
+  
+    bool CellMap, ShowTrans, ShowBBox;   //, ShowScale, TieScales;
+    Point3f Scale = Point3f(1.0, 1.0, 1.0);
+    // float Scale;
+    parms(section, "CellMap", CellMap, false);
+    mesh->setShowMeshCellMap(CellMap);
+    parms(section, "ShowTrans", ShowTrans, false);
+    stack->setShowTrans(ShowTrans);
+    parms(section, "ShowBBox", ShowBBox, false);
+    stack->setShowBBox(ShowBBox);
+    // parms(section, "ShowScale", ShowScale, false);// ALR: we don't load ShowScale so that there is no scaling when
+    // launching mgxv file
+    // stack->setShowScale(ShowScale);
+    // parms(section, "TieScales", TieScales, false);
+    // stack->setTieScales(TieScales);
+    parms(section, "ScaleX", Scale.x(), 1.0f);
+    parms(section, "ScaleY", Scale.y(), 1.0f);
+    parms(section, "ScaleZ", Scale.z(), 1.0f);
+  
+    bool LoadMeshScaleUm, LoadMeshTransform;
+    parms(section, "LoadMeshScaleUm", LoadMeshScaleUm, true);
+    mesh->setScaled(LoadMeshScaleUm);
+    parms(section, "LoadMeshTransform", LoadMeshTransform, false);
+    mesh->setTransformed(LoadMeshTransform);
+    parms(section, "LoadMeshAdd", LoadMeshAdd, false);
+    parms(section, "MeshShift", meshShift, 0.f);
+  
+    QString sf;
+    parms(section, "MainColorMap", sf, QString());
+    TransferFunction mainTransferFct = stack->main()->transferFct();
+    mainTransferFct.clear();
+    if(not sf.isEmpty()) {
+      QString qsf = unshield(sf);
+      mainTransferFct = TransferFunction::load(qsf);
+    }
+    if(mainTransferFct.empty()) {
+      if(Section == "Stack1")
+        mainTransferFct = TransferFunction::scale_green();
+      else
+        mainTransferFct = TransferFunction::scale_red();
+    }
+    mainTransferDlg->setTransferFunction(mainTransferFct);
+    stack->main()->setTransferFct(mainTransferFct);
+    updateMainColorMap();
+  
+    QString sf2;
+    parms(section, "WorkColorMap", sf2, QString());
+    TransferFunction workTransferFct = stack->work()->transferFct();
+    workTransferFct.clear();
+    if(not sf2.isEmpty()) {
+      QString qsf = unshield(sf2);
+      workTransferFct = TransferFunction::load(qsf);
+    }
+    if(workTransferFct.empty()) {
+      if(Section == "Stack1")
+        workTransferFct = TransferFunction::scale_cyan();
+      else
+        workTransferFct = TransferFunction::scale_yellow();
+    }
+    workTransferDlg->setTransferFunction(workTransferFct);
+    stack->work()->setTransferFct(workTransferFct);
+    updateWorkColorMap();
+  
+    QString sf3;
+    parms(section, "SurfColorMap", sf3, QString());
+    TransferFunction surfTransferFct = mesh->surfFct();
+    surfTransferFct.clear();
+    if(not sf3.isEmpty()) {
+      QString qsf = unshield(sf3);
+      surfTransferFct = TransferFunction::load(qsf);
+    }
+    if(surfTransferFct.empty())
+      surfTransferFct = TransferFunction::scale_gray();
+    surfTransferDlg->setTransferFunction(surfTransferFct);
+    mesh->setSurfFct(surfTransferFct);
+    updateSurfColorMap();
+  
+    QString sf4;
+    parms(section, "HeatColorMap", sf4, QString());
+    TransferFunction heatTransferFct = mesh->heatFct();
+    heatTransferFct.clear();
+    if(not sf4.isEmpty()) {
+      QString qsf = unshield(sf4);
+      heatTransferFct = TransferFunction::load(qsf);
+    }
+    if(heatTransferFct.empty())
+      heatTransferFct = TransferFunction::jet();
+    heatTransferDlg->setTransferFunction(heatTransferFct);
+    mesh->setHeatFct(heatTransferFct);
+    updateHeatColorMap();
+  
+    Matrix4d m = 1;
+    parms(section, "Frame", m, m);
+    stack->frame().setFromMatrix(m.c_data());
+    m = 1;
+    parms(section, "Trans", m, m);
+    stack->trans().setFromMatrix(m.c_data());
+  
+    if(section == "Stack1") {
+      MeshColor = Colors::Mesh1Color;
+      MeshBorderColor = Colors::Mesh1BorderColor;
+      // MeshPointColor = Colors::Mesh1PointColor;
+      MeshSelectColor = Colors::Mesh1SelectColor;
+    } else {
+      MeshColor = Colors::Mesh2Color;
+      MeshBorderColor = Colors::Mesh2BorderColor;
+      // MeshPointColor = Colors::Mesh2PointColor;
+      MeshSelectColor = Colors::Mesh2SelectColor;
+    }
   }
-
-  bool SurfShow;
-  parms(section, "SurfShow", SurfShow, true);
-  if(SurfShow)
-    mesh->showSurface();
-  else
-    mesh->hideSurface();
-  float SurfBright;
-  parms(section, "SurfBright", SurfBright, 1.0f);
-  mesh->setBrightness(SurfBright);
-  float SurfOpacity;
-  parms(section, "SurfOpacity", SurfOpacity, 1.0f);
-  mesh->setOpacity(SurfOpacity);
-  bool SurfCull, SurfBlend;
-  parms(section, "SurfBlend", SurfBlend, false);
-  parms(section, "SurfCull", SurfCull, true);
-  mesh->setCulling(SurfCull);
-  mesh->setBlending(SurfBlend);
-
-  int SurfView;
-  parms(section, "SurfView", SurfView, (int)Mesh::LABEL);
-  mesh->show((Mesh::SurfView)SurfView);
-
-  int SurfColor;
-  parms(section, "SurfColor", SurfColor, (int)Mesh::SIGNAL);
-  mesh->show((Mesh::Color)SurfColor);
-
-  bool MeshShow, MeshPoints, MeshLines;
-  parms(section, "MeshShow", MeshShow, false);
-  mesh->setShowMesh(MeshShow);
-  parms(section, "MeshPoints", MeshPoints, true);
-  mesh->setShowMeshPoints(MeshPoints);
-  parms(section, "MeshLines", MeshLines, true);
-  mesh->setShowMeshLines(MeshLines);
-  int mvm;
-  parms(section, "MeshViewMode", mvm, (int)Mesh::SELECTED_MESH);
-  mesh->show((Mesh::MeshView)mvm);
-
-  bool CellMap, ShowTrans, ShowBBox;   //, ShowScale, TieScales;
-  Point3f Scale = Point3f(1.0, 1.0, 1.0);
-  // float Scale;
-  parms(section, "CellMap", CellMap, false);
-  mesh->setShowMeshCellMap(CellMap);
-  parms(section, "ShowTrans", ShowTrans, false);
-  stack->setShowTrans(ShowTrans);
-  parms(section, "ShowBBox", ShowBBox, false);
-  stack->setShowBBox(ShowBBox);
-  // parms(section, "ShowScale", ShowScale, false);// ALR: we don't load ShowScale so that there is no scaling when
-  // launching mgxv file
-  // stack->setShowScale(ShowScale);
-  // parms(section, "TieScales", TieScales, false);
-  // stack->setTieScales(TieScales);
-  parms(section, "ScaleX", Scale.x(), 1.0f);
-  parms(section, "ScaleY", Scale.y(), 1.0f);
-  parms(section, "ScaleZ", Scale.z(), 1.0f);
-
-  bool LoadMeshScaleUm, LoadMeshTransform;
-  parms(section, "LoadMeshScaleUm", LoadMeshScaleUm, true);
-  mesh->setScaled(LoadMeshScaleUm);
-  parms(section, "LoadMeshTransform", LoadMeshTransform, false);
-  mesh->setTransformed(LoadMeshTransform);
-  parms(section, "LoadMeshAdd", LoadMeshAdd, false);
-  parms(section, "MeshShift", meshShift, 0.f);
-
-  QString sf;
-  parms(section, "MainColorMap", sf, QString());
-  TransferFunction mainTransferFct = stack->main()->transferFct();
-  mainTransferFct.clear();
-  if(not sf.isEmpty()) {
-    QString qsf = unshield(sf);
-    mainTransferFct = TransferFunction::load(qsf);
+  
+  void ImgData::setSurfColorMap(const TransferFunction& fct) {
+    surfTransferDlg->setTransferFunction(fct);
   }
-  if(mainTransferFct.empty()) {
-    if(Section == "Stack1")
-      mainTransferFct = TransferFunction::scale_green();
-    else
-      mainTransferFct = TransferFunction::scale_red();
+  
+  void ImgData::setHeatColorMap(const TransferFunction& fct) {
+    heatTransferDlg->setTransferFunction(fct);
   }
-  mainTransferDlg->setTransferFunction(mainTransferFct);
-  stack->main()->setTransferFct(mainTransferFct);
-  updateMainColorMap();
-
-  QString sf2;
-  parms(section, "WorkColorMap", sf2, QString());
-  TransferFunction workTransferFct = stack->work()->transferFct();
-  workTransferFct.clear();
-  if(not sf2.isEmpty()) {
-    QString qsf = unshield(sf2);
-    workTransferFct = TransferFunction::load(qsf);
+  
+  void ImgData::setWorkColorMap(const TransferFunction& fct) {
+    workTransferDlg->setTransferFunction(fct);
   }
-  if(workTransferFct.empty()) {
-    if(Section == "Stack1")
-      workTransferFct = TransferFunction::scale_cyan();
-    else
-      workTransferFct = TransferFunction::scale_yellow();
+  
+  void ImgData::setMainColorMap(const TransferFunction& fct) {
+    mainTransferDlg->setTransferFunction(fct);
   }
-  workTransferDlg->setTransferFunction(workTransferFct);
-  stack->work()->setTransferFct(workTransferFct);
-  updateWorkColorMap();
-
-  QString sf3;
-  parms(section, "SurfColorMap", sf3, QString());
-  TransferFunction surfTransferFct = mesh->surfFct();
-  surfTransferFct.clear();
-  if(not sf3.isEmpty()) {
-    QString qsf = unshield(sf3);
-    surfTransferFct = TransferFunction::load(qsf);
+  
+  // Set parameters for function
+  void ImgData::writeParms(QTextStream& pout, QString section)
+  {
+    Section = section;
+  
+    pout << endl;
+    pout << "[" << section << "]" << endl;
+  
+    pout << "StackFile: " << stripCurrentDir(stack->main()->file()) << endl;
+    pout << "WorkStackFile: " << stripCurrentDir(stack->work()->file()) << endl;
+    pout << "MeshFile: " << stripCurrentDir(mesh->file()) << endl;
+    pout << "ParentFile: " << stripCurrentDir(mesh->parentFile()) << endl;
+  
+    pout << "MainShow: " << (stack->main()->isVisible() ? "true" : "false") << endl;
+    pout << "MainBright:" << stack->main()->brightness() << endl;
+    pout << "MainOpacity:" << stack->main()->opacity() << endl;
+    pout << "Main16Bit:" << (Main16Bit ? "true" : "false") << endl;
+    pout << "MainLabels:" << (stack->main()->labels() ? "true" : "false") << endl;
+  
+    pout << "WorkShow: " << (stack->work()->isVisible() ? "true" : "false") << endl;
+    pout << "WorkBright:" << stack->work()->brightness() << endl;
+    pout << "WorkOpacity:" << stack->work()->opacity() << endl;
+    pout << "Work16Bit:" << (Work16Bit ? "true" : "false") << endl;
+    pout << "WorkLabels:" << (stack->work()->labels() ? "true" : "false") << endl;
+  
+    pout << "SurfShow:" << (mesh->isSurfaceVisible() ? "true" : "false") << endl;
+    pout << "SurfBright:" << mesh->brightness() << endl;
+    pout << "SurfOpacity:" << mesh->opacity() << endl;
+    pout << "SurfBlend:" << (mesh->blending() ? "true" : "false") << endl;
+    pout << "SurfCull:" << (mesh->culling() ? "true" : "false") << endl;
+  
+    pout << "SurfView:" << (int)mesh->toShow() << endl;
+  
+    pout << "SurfColor:" << (int)mesh->coloring() << endl;
+  
+    pout << "MeshShow:" << (mesh->isMeshVisible() ? "true" : "false") << endl;
+    pout << "MeshViewMode:" << (int)mesh->meshView() << endl;
+    pout << "MeshPoints:" << (mesh->showMeshPoints() ? "true" : "false") << endl;
+    pout << "MeshLines:" << (mesh->showMeshLines() ? "true" : "false") << endl;
+  
+    pout << "CellMap:" << (mesh->showMeshCellMap() ? "true" : "false") << endl;
+    pout << "ShowTrans:" << (stack->showTrans() ? "true" : "false") << endl;
+    pout << "ShowBBox:" << (stack->showBBox() ? "true" : "false") << endl;
+    pout << "ShowScale:" << (stack->showScale() ? "true" : "false") << endl;
+    pout << "TieScales:" << (stack->tieScales() ? "true" : "false") << endl;
+    pout << "ScaleX:" << stack->scale().x() << endl;
+    pout << "ScaleY:" << stack->scale().y() << endl;
+    pout << "ScaleZ:" << stack->scale().z() << endl;
+    pout << "Scale:" << norm(stack->scale()) << endl;
+  
+    pout << "LoadMeshAdd: " << (LoadMeshAdd ? "true" : "false") << endl;
+    pout << "LoadMeshScaleUm: " << (mesh->scaled() ? "true" : "false") << endl;
+    pout << "LoadMeshTransform: " << (mesh->transformed() ? "true" : "false") << endl;
+    pout << "MeshShift: " << meshShift << endl;
+  
+    QString qsf = shield(stack->main()->transferFct().dump());
+    pout << "MainColorMap: " << qsf << endl;
+    qsf = shield(stack->work()->transferFct().dump());
+    pout << "WorkColorMap: " << qsf << endl;
+    qsf = shield(mesh->surfFct().dump());
+    pout << "SurfColorMap: " << qsf << endl;
+    qsf = shield(mesh->heatFct().dump());
+    pout << "HeatColorMap: " << qsf << endl;
+  
+    pout << "Frame: " << Point16d(stack->frame().matrix()) << endl;
+    pout << "Trans: " << Point16d(stack->trans().matrix()) << endl;
+    pout << endl;
   }
-  if(surfTransferFct.empty())
-    surfTransferFct = TransferFunction::scale_gray();
-  surfTransferDlg->setTransferFunction(surfTransferFct);
-  mesh->setSurfFct(surfTransferFct);
-  updateSurfColorMap();
-
-  QString sf4;
-  parms(section, "HeatColorMap", sf4, QString());
-  TransferFunction heatTransferFct = mesh->heatFct();
-  heatTransferFct.clear();
-  if(not sf4.isEmpty()) {
-    QString qsf = unshield(sf4);
-    heatTransferFct = TransferFunction::load(qsf);
+  
+  // Set stack sizes
+  void ImgData::updateStackSize()
+  {
+    if(stack->empty())
+      unloadTex();
+  
+    emit changeSize(stack->size(), stack->step(), stack->origin());
   }
-  if(heatTransferFct.empty())
-    heatTransferFct = TransferFunction::jet();
-  heatTransferDlg->setTransferFunction(heatTransferFct);
-  mesh->setHeatFct(heatTransferFct);
-  updateHeatColorMap();
-
-  Matrix4d m = 1;
-  parms(section, "Frame", m, m);
-  stack->frame().setFromMatrix(m.c_data());
-  m = 1;
-  parms(section, "Trans", m, m);
-  stack->trans().setFromMatrix(m.c_data());
-
-  if(section == "Stack1") {
-    MeshColor = Colors::Mesh1Color;
-    MeshBorderColor = Colors::Mesh1BorderColor;
-    // MeshPointColor = Colors::Mesh1PointColor;
-    MeshSelectColor = Colors::Mesh1SelectColor;
-  } else {
-    MeshColor = Colors::Mesh2Color;
-    MeshBorderColor = Colors::Mesh2BorderColor;
-    // MeshPointColor = Colors::Mesh2PointColor;
-    MeshSelectColor = Colors::Mesh2SelectColor;
+  
+  static void drawPlane(Shader* shader, Point3f imageSize, Point3u texSize, Point3f Origin, float scaling, int Slices,
+                        GLboolean hasClip1, GLboolean hasClip2, GLboolean hasClip3, Point3f c1, Point3f c2, Point3f c3,
+                        Point3f c4)
+  {
+    shader->setUniform("origin", GLSLValue(vec3(Origin)));
+    shader->setUniform("imageSize", GLSLValue(vec3(imageSize)));
+    shader->setUniform("scaling", GLSLValue(scaling));
+    shader->setUniform("texSize", GLSLValue(ivec3(texSize)));
+    shader->setUniform("slices", GLSLValue(float(Slices) / 10000.f));
+    shader->setUniform("has_clipped", GLSLValue(ivec3(hasClip1, hasClip2, hasClip3)));
+    shader->useShaders();
+    shader->setupUniforms();
+  
+    glBegin(GL_QUADS);
+    glColor4f(1, 1, 1, 1);
+    glVertex3fv(c4.c_data());
+    glVertex3fv(c3.c_data());
+    glVertex3fv(c2.c_data());
+    glVertex3fv(c1.c_data());
+    glEnd();
+  
+    shader->stopUsingShaders();
   }
-}
-
-void ImgData::setSurfColorMap(const TransferFunction& fct) {
-  surfTransferDlg->setTransferFunction(fct);
-}
-
-void ImgData::setHeatColorMap(const TransferFunction& fct) {
-  heatTransferDlg->setTransferFunction(fct);
-}
-
-void ImgData::setWorkColorMap(const TransferFunction& fct) {
-  workTransferDlg->setTransferFunction(fct);
-}
-
-void ImgData::setMainColorMap(const TransferFunction& fct) {
-  mainTransferDlg->setTransferFunction(fct);
-}
-
-// Set parameters for function
-void ImgData::writeParms(QTextStream& pout, QString section)
-{
-  Section = section;
-
-  pout << endl;
-  pout << "[" << section << "]" << endl;
-
-  pout << "StackFile: " << stripCurrentDir(stack->main()->file()) << endl;
-  pout << "WorkStackFile: " << stripCurrentDir(stack->work()->file()) << endl;
-  pout << "MeshFile: " << stripCurrentDir(mesh->file()) << endl;
-
-  pout << "MainShow: " << (stack->main()->isVisible() ? "true" : "false") << endl;
-  pout << "MainBright:" << stack->main()->brightness() << endl;
-  pout << "MainOpacity:" << stack->main()->opacity() << endl;
-  pout << "Main16Bit:" << (Main16Bit ? "true" : "false") << endl;
-  pout << "MainLabels:" << (stack->main()->labels() ? "true" : "false") << endl;
-
-  pout << "WorkShow: " << (stack->work()->isVisible() ? "true" : "false") << endl;
-  pout << "WorkBright:" << stack->work()->brightness() << endl;
-  pout << "WorkOpacity:" << stack->work()->opacity() << endl;
-  pout << "Work16Bit:" << (Work16Bit ? "true" : "false") << endl;
-  pout << "WorkLabels:" << (stack->work()->labels() ? "true" : "false") << endl;
-
-  pout << "SurfShow:" << (mesh->isSurfaceVisible() ? "true" : "false") << endl;
-  pout << "SurfBright:" << mesh->brightness() << endl;
-  pout << "SurfOpacity:" << mesh->opacity() << endl;
-  pout << "SurfBlend:" << (mesh->blending() ? "true" : "false") << endl;
-  pout << "SurfCull:" << (mesh->culling() ? "true" : "false") << endl;
-
-  pout << "SurfView:" << (int)mesh->toShow() << endl;
-
-  pout << "SurfColor:" << (int)mesh->coloring() << endl;
-
-  pout << "MeshShow:" << (mesh->isMeshVisible() ? "true" : "false") << endl;
-  pout << "MeshViewMode:" << (int)mesh->meshView() << endl;
-  pout << "MeshPoints:" << (mesh->showMeshPoints() ? "true" : "false") << endl;
-  pout << "MeshLines:" << (mesh->showMeshLines() ? "true" : "false") << endl;
-
-  pout << "CellMap:" << (mesh->showMeshCellMap() ? "true" : "false") << endl;
-  pout << "ShowTrans:" << (stack->showTrans() ? "true" : "false") << endl;
-  pout << "ShowBBox:" << (stack->showBBox() ? "true" : "false") << endl;
-  pout << "ShowScale:" << (stack->showScale() ? "true" : "false") << endl;
-  pout << "TieScales:" << (stack->tieScales() ? "true" : "false") << endl;
-  pout << "ScaleX:" << stack->scale().x() << endl;
-  pout << "ScaleY:" << stack->scale().y() << endl;
-  pout << "ScaleZ:" << stack->scale().z() << endl;
-  pout << "Scale:" << norm(stack->scale()) << endl;
-
-  pout << "LoadMeshAdd: " << (LoadMeshAdd ? "true" : "false") << endl;
-  pout << "LoadMeshScaleUm: " << (mesh->scaled() ? "true" : "false") << endl;
-  pout << "LoadMeshTransform: " << (mesh->transformed() ? "true" : "false") << endl;
-  pout << "MeshShift: " << meshShift << endl;
-
-  QString qsf = shield(stack->main()->transferFct().dump());
-  pout << "MainColorMap: " << qsf << endl;
-  qsf = shield(stack->work()->transferFct().dump());
-  pout << "WorkColorMap: " << qsf << endl;
-  qsf = shield(mesh->surfFct().dump());
-  pout << "SurfColorMap: " << qsf << endl;
-  qsf = shield(mesh->heatFct().dump());
-  pout << "HeatColorMap: " << qsf << endl;
-
-  pout << "Frame: " << Point16d(stack->frame().matrix()) << endl;
-  pout << "Trans: " << Point16d(stack->trans().matrix()) << endl;
-  pout << endl;
-}
-
-// Set stack sizes
-void ImgData::updateStackSize()
-{
-  if(stack->empty())
-    unloadTex();
-
-  emit changeSize(stack->size(), stack->step(), stack->origin());
-}
-
-static void drawPlane(Shader* shader, Point3f imageSize, Point3u texSize, Point3f Origin, float scaling, int Slices,
-                      GLboolean hasClip1, GLboolean hasClip2, GLboolean hasClip3, Point3f c1, Point3f c2, Point3f c3,
-                      Point3f c4)
-{
-  shader->setUniform("origin", GLSLValue(vec3(Origin)));
-  shader->setUniform("imageSize", GLSLValue(vec3(imageSize)));
-  shader->setUniform("scaling", GLSLValue(scaling));
-  shader->setUniform("texSize", GLSLValue(ivec3(texSize)));
-  shader->setUniform("slices", GLSLValue(float(Slices) / 10000.f));
-  shader->setUniform("has_clipped", GLSLValue(ivec3(hasClip1, hasClip2, hasClip3)));
-  shader->useShaders();
-  shader->setupUniforms();
-
-  glBegin(GL_QUADS);
-  glColor4f(1, 1, 1, 1);
-  glVertex3fv(c4.c_data());
-  glVertex3fv(c3.c_data());
-  glVertex3fv(c2.c_data());
-  glVertex3fv(c1.c_data());
-  glEnd();
-
-  shader->stopUsingShaders();
-}
-
-void ImgData::setupVolumeShader(Shader& shader, int pos)
-{
-  QString color_fct = "vec4 color(vec3 texCoord) { \n";
-  if(isMainVisible() and isWorkVisible()) {
-    if(stack->main()->labels())
-      color_fct += "  vec4 c1 = (brightness > 0.0) ? premulColor(index_color1(texCoord)) : vec4(0,0,0,1);\n";
-    else
-      color_fct += "  vec4 c1 = (brightness > 0.0) ? premulColor(colormap_color1(texCoord)) : vec4(0,0,0,1);\n";
-    if(stack->work()->labels())
-      color_fct
-        += "  vec4 c2 = (second_brightness > 0.0) ? premulColor(index_color2(texCoord)) : vec4(0,0,0,1);\n";
-    else
-      color_fct
-        += "  vec4 c2 = (second_brightness > 0.0) ? premulColor(colormap_color2(texCoord)) : vec4(0,0,0,1);\n";
-    color_fct += "  return mixColors(c1, c2);\n}\n";
-  } else if(isMainVisible()) {
-    if(stack->main()->labels())
-      color_fct += "  return (brightness > 0.0) ? premulColor(index_color1(texCoord)) : vec4(0,0,0,1);\n}\n";
-    else
-      color_fct += "  return (brightness > 0.0) ? premulColor(colormap_color1(texCoord)) : vec4(0,0,0,1);\n}\n";
-  } else if(isWorkVisible()) {
-    if(stack->work()->labels())
-      color_fct
-        += "  return (second_brightness > 0.0) ? premulColor(index_color2(texCoord)) : vec4(0,0,0,1);\n}\n";
-    else
-      color_fct
-        += "  return (second_brightness > 0.0) ? premulColor(colormap_color2(texCoord)) : vec4(0,0,0,1);\n}\n";
-  } else
-    color_fct += "  return vec4(0,0,0,1);\n}\n";
-  shader.changeFragmentShaderCode(pos, color_fct);
-}
-
-void ImgData::setup3DRenderingData(Shader* shader)
-{
-  // When drawing 3D seeds, we need to also draw the main stack
-  if(stack->main()->isVisible() and mainDataTexId) {
-    bind3DTex(mainDataTexId);
-
-    setupMainColorMap();
-
-    float brightness = powf(stack->main()->brightness(), 2.0f);
-    float opacity = powf(stack->main()->opacity(), 2.0f);
-    shader->setUniform("brightness", GLSLValue(brightness));
-    shader->setUniform("opacity", GLSLValue(opacity));
+  
+  void ImgData::setupVolumeShader(Shader& shader, int pos)
+  {
+    QString color_fct = "vec4 color(vec3 texCoord) { \n";
+    if(isMainVisible() and isWorkVisible()) {
+      if(stack->main()->labels())
+        color_fct += "  vec4 c1 = (brightness > 0.0) ? premulColor(index_color1(texCoord)) : vec4(0,0,0,1);\n";
+      else
+        color_fct += "  vec4 c1 = (brightness > 0.0) ? premulColor(colormap_color1(texCoord)) : vec4(0,0,0,1);\n";
+      if(stack->work()->labels())
+        color_fct
+          += "  vec4 c2 = (second_brightness > 0.0) ? premulColor(index_color2(texCoord)) : vec4(0,0,0,1);\n";
+      else
+        color_fct
+          += "  vec4 c2 = (second_brightness > 0.0) ? premulColor(colormap_color2(texCoord)) : vec4(0,0,0,1);\n";
+      color_fct += "  return mixColors(c1, c2);\n}\n";
+    } else if(isMainVisible()) {
+      if(stack->main()->labels())
+        color_fct += "  return (brightness > 0.0) ? premulColor(index_color1(texCoord)) : vec4(0,0,0,1);\n}\n";
+      else
+        color_fct += "  return (brightness > 0.0) ? premulColor(colormap_color1(texCoord)) : vec4(0,0,0,1);\n}\n";
+    } else if(isWorkVisible()) {
+      if(stack->work()->labels())
+        color_fct
+          += "  return (second_brightness > 0.0) ? premulColor(index_color2(texCoord)) : vec4(0,0,0,1);\n}\n";
+      else
+        color_fct
+          += "  return (second_brightness > 0.0) ? premulColor(colormap_color2(texCoord)) : vec4(0,0,0,1);\n}\n";
+    } else
+      color_fct += "  return vec4(0,0,0,1);\n}\n";
+    shader.changeFragmentShaderCode(pos, color_fct);
   }
-
-  if(stack->work()->isVisible() and workDataTexId) {
-    bind3DTex(workDataTexId, Shader::AT_SECOND_TEX3D);
-
-    setupWorkColorMap2();
-
-    float brightness = powf(stack->work()->brightness(), 2.0f);
-    float opacity = powf(stack->work()->opacity(), 2.0f);
-    shader->setUniform("second_brightness", GLSLValue(brightness));
-    shader->setUniform("second_opacity", GLSLValue(opacity));
+  
+  void ImgData::setup3DRenderingData(Shader* shader)
+  {
+    // When drawing 3D seeds, we need to also draw the main stack
+    if(stack->main()->isVisible() and mainDataTexId) {
+      bind3DTex(mainDataTexId);
+  
+      setupMainColorMap();
+  
+      float brightness = powf(stack->main()->brightness(), 2.0f);
+      float opacity = powf(stack->main()->opacity(), 2.0f);
+      shader->setUniform("brightness", GLSLValue(brightness));
+      shader->setUniform("opacity", GLSLValue(opacity));
+    }
+  
+    if(stack->work()->isVisible() and workDataTexId) {
+      bind3DTex(workDataTexId, Shader::AT_SECOND_TEX3D);
+  
+      setupWorkColorMap2();
+  
+      float brightness = powf(stack->work()->brightness(), 2.0f);
+      float opacity = powf(stack->work()->opacity(), 2.0f);
+      shader->setUniform("second_brightness", GLSLValue(brightness));
+      shader->setUniform("second_opacity", GLSLValue(opacity));
+    }
   }
-}
-
-void ImgData::drawStack(Shader* shader)
-{
-  if(!isVisible() or !(mainDataTexId or workDataTexId)
-     or ((stack->main()->opacity() == 0 or !isMainVisible())and (stack->work()->opacity() == 0 or !isWorkVisible())))
-    return;
-
-  glEnable(GL_AUTO_NORMAL);
-  glDisable(GL_LIGHTING);
-  // glDisable(GL_DEPTH_TEST);
-  // glEnable(GL_MULTISAMPLE); // RSS screws up selection
-  glDisable(GL_BLEND);
-
-  glFrontFace(GL_CCW);
-  glPolygonMode(GL_FRONT, GL_FILL);
-
-  glDisable(GL_TEXTURE_1D);
-  glDisable(GL_TEXTURE_2D);
-  glDisable(GL_TEXTURE_3D);
-
-  // Choose blending function
-  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-  // glBlendFunc(GL_SRC_ALPHA, GL_ONE);
-
-  // glBlendEquation(GL_MAX);
-  // glBlendEquationSeparate(GL_MAX, GL_MIN);
-
-  // Set matrix
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glMultMatrixd(getFrame().worldMatrix());
-
-  GLdouble mv[16], proj[16];
-  GLint viewport[4];
-  glGetDoublev(GL_MODELVIEW_MATRIX, mv);
-  glGetDoublev(GL_PROJECTION_MATRIX, proj);
-  glGetIntegerv(GL_VIEWPORT, viewport);
-
-  // Get unit vectors in x,y,z direction
-  Point3f x(mv[0], mv[4], mv[8]);
-  Point3f y(mv[1], mv[5], mv[9]);
-  Point3f z(mv[2], mv[6], mv[10]);
-  // Vertex array for quads
-  std::vector<Point3f> vtxVA;
-
-  // Render object aligned or view aligned
-  const Point3f& Size = stack->worldSize();
-  double x2 = Size.x() * Size.x() / 4;
-  double y2 = Size.y() * Size.y() / 4;
-  double z2 = Size.z() * Size.z() / 4;
-  float dis = sqrt(x2 + y2 + z2);
-  z *= dis;
-  x *= dis;
-  y *= dis;
-
-  Shader::activeTexture(Shader::AT_LABEL_TEX);
-  glBindTexture(GL_TEXTURE_1D, labelTexId);
-  Shader::activeTexture(Shader::AT_NONE);
-
-  GLdouble winX = viewport[2];
-  GLdouble winY = viewport[3];
-
-  typedef util::Vector<3, GLdouble> Point3GLd;
-  Point3GLd c1, c2, c3, c4;
-  gluUnProject(0, 0, 0, mv, proj, viewport, &c1.x(), &c1.y(), &c1.z());
-  gluUnProject(0, winY, 0, mv, proj, viewport, &c2.x(), &c2.y(), &c2.z());
-  gluUnProject(winX, winY, 0, mv, proj, viewport, &c3.x(), &c3.y(), &c3.z());
-  gluUnProject(winX, 0, 0, mv, proj, viewport, &c4.x(), &c4.y(), &c4.z());
-
-  GLboolean clip1, clip2, clip3;
-  glGetBooleanv(GL_CLIP_PLANE0, &clip1);
-  glGetBooleanv(GL_CLIP_PLANE2, &clip2);
-  glGetBooleanv(GL_CLIP_PLANE4, &clip3);
-
-  setup3DRenderingData(shader);
-
-  drawPlane(shader, Size, stack->size(), stack->origin(), stack->scale().x(),   // ALR: not sure what to do here
-            Slices, clip1, clip2, clip3, Point3f(c1), Point3f(c2), Point3f(c3), Point3f(c4));
-
-  // drawPlane(shader, Size, stack->size(), stack->origin(), stack->scale(),
-  //          Slices,
-  //          clip1, clip2, clip3,
-  //          Point3f(c1), Point3f(c2), Point3f(c3), Point3f(c4));
-  unbind3DTex();
-
-  // glBlendEquation(GL_FUNC_ADD);
-  glDisable(GL_BLEND);
-  glMatrixMode(GL_MODELVIEW);
-  glPopMatrix();
-  REPORT_GL_ERROR("drawStack");
-}
-
-void ImgData::drawBBox()
-{
-  if(!stack->showBBox() or !(mainDataTexId or workDataTexId))
-    return;
-  glDisable(GL_LIGHTING);
-  glDisable(GL_TEXTURE_1D);
-  glDisable(GL_TEXTURE_2D);
-  glDisable(GL_TEXTURE_3D);
-  glDisable(GL_BLEND);
-  glDisable(GL_ALPHA_TEST);
-  glDisable(GL_AUTO_NORMAL);
-  glEnable(GL_DEPTH_TEST);
-
-  glLineWidth(MeshLineWidth);
-
-  glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
-
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glMultMatrixd(getFrame().worldMatrix());
-
-  Colorf c = Colors::getColor((StackId == 0) ? Colors::Stack1BBoxColor : Colors::Stack2BBoxColor);
-
-  glColor4fv(c.c_data());
-
-  const Point3f& Origin = stack->origin();
-  Point3f c1 = Origin;
-  Point3f c2 = Origin + stack->worldSize();
-
-  glBegin(GL_QUADS);
-  glVertex3f(c1.x(), c1.y(), c1.z());
-  glVertex3f(c1.x(), c2.y(), c1.z());
-  glVertex3f(c2.x(), c2.y(), c1.z());
-  glVertex3f(c2.x(), c1.y(), c1.z());
-
-  glVertex3f(c1.x(), c1.y(), c2.z());
-  glVertex3f(c1.x(), c2.y(), c2.z());
-  glVertex3f(c2.x(), c2.y(), c2.z());
-  glVertex3f(c2.x(), c1.y(), c2.z());
-  glEnd();
-
-  glBegin(GL_LINES);
-  glVertex3f(c1.x(), c1.y(), c1.z());
-  glVertex3f(c1.x(), c1.y(), c2.z());
-
-  glVertex3f(c1.x(), c2.y(), c1.z());
-  glVertex3f(c1.x(), c2.y(), c2.z());
-
-  glVertex3f(c2.x(), c2.y(), c1.z());
-  glVertex3f(c2.x(), c2.y(), c2.z());
-
-  glVertex3f(c2.x(), c1.y(), c1.z());
-  glVertex3f(c2.x(), c1.y(), c2.z());
-  glEnd();
-
-  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-  glMatrixMode(GL_MODELVIEW);
-  glPopMatrix();
-  REPORT_GL_ERROR("drawBBox");
-}
-
-// Draw mesh wireframe
-void ImgData::drawMesh(bool select)
-{
-  vvgraph& S = mesh->graph();
-  if(S.empty() or !mesh->isMeshVisible() or (select and !MeshSelect))
-    return;
-
-  glDisable(GL_LIGHTING);
-  glDisable(GL_TEXTURE_1D);
-  glDisable(GL_TEXTURE_2D);
-  glDisable(GL_TEXTURE_3D);
-  glDisable(GL_BLEND);
-  glDisable(GL_ALPHA_TEST);
-  glDisable(GL_AUTO_NORMAL);
-  glEnable(GL_DEPTH_TEST);
-  // glEnable(GL_MULTISAMPLE);
-  glFrontFace(GL_CCW);
-
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glMultMatrixd(getFrame().worldMatrix());
-  // if(stack->scale() != 1.0)
-  if(stack->scale() != Point3f(1.0, 1.0, 1.0))
-    glScaled(stack->scale().x(), stack->scale().y(), stack->scale().z());
-  // glScaled(stack->scale(), stack->scale(), stack->scale());
-
-  if(mesh->showMeshLines() and !select) {
+  
+  void ImgData::drawStack(Shader* shader)
+  {
+    if(!isVisible() or !(mainDataTexId or workDataTexId)
+       or ((stack->main()->opacity() == 0 or !isMainVisible())and (stack->work()->opacity() == 0 or !isWorkVisible())))
+      return;
+  
+    glEnable(GL_AUTO_NORMAL);
+    glDisable(GL_LIGHTING);
+    // glDisable(GL_DEPTH_TEST);
+    // glEnable(GL_MULTISAMPLE); // RSS screws up selection
+    glDisable(GL_BLEND);
+  
+    glFrontFace(GL_CCW);
+    glPolygonMode(GL_FRONT, GL_FILL);
+  
+    glDisable(GL_TEXTURE_1D);
+    glDisable(GL_TEXTURE_2D);
+    glDisable(GL_TEXTURE_3D);
+  
+    // Choose blending function
+    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+    // glBlendFunc(GL_SRC_ALPHA, GL_ONE);
+  
+    // glBlendEquation(GL_MAX);
+    // glBlendEquationSeparate(GL_MAX, GL_MIN);
+  
+    // Set matrix
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glMultMatrixd(getFrame().worldMatrix());
+  
+    GLdouble mv[16], proj[16];
+    GLint viewport[4];
+    glGetDoublev(GL_MODELVIEW_MATRIX, mv);
+    glGetDoublev(GL_PROJECTION_MATRIX, proj);
+    glGetIntegerv(GL_VIEWPORT, viewport);
+  
+    // Get unit vectors in x,y,z direction
+    Point3f x(mv[0], mv[4], mv[8]);
+    Point3f y(mv[1], mv[5], mv[9]);
+    Point3f z(mv[2], mv[6], mv[10]);
+    // Vertex array for quads
+    std::vector<Point3f> vtxVA;
+  
+    // Render object aligned or view aligned
+    const Point3f& Size = stack->worldSize();
+    double x2 = Size.x() * Size.x() / 4;
+    double y2 = Size.y() * Size.y() / 4;
+    double z2 = Size.z() * Size.z() / 4;
+    float dis = sqrt(x2 + y2 + z2);
+    z *= dis;
+    x *= dis;
+    y *= dis;
+  
+    Shader::activeTexture(Shader::AT_LABEL_TEX);
+    glBindTexture(GL_TEXTURE_1D, labelTexId);
+    Shader::activeTexture(Shader::AT_NONE);
+  
+    GLdouble winX = viewport[2];
+    GLdouble winY = viewport[3];
+  
+    typedef util::Vector<3, GLdouble> Point3GLd;
+    Point3GLd c1, c2, c3, c4;
+    gluUnProject(0, 0, 0, mv, proj, viewport, &c1.x(), &c1.y(), &c1.z());
+    gluUnProject(0, winY, 0, mv, proj, viewport, &c2.x(), &c2.y(), &c2.z());
+    gluUnProject(winX, winY, 0, mv, proj, viewport, &c3.x(), &c3.y(), &c3.z());
+    gluUnProject(winX, 0, 0, mv, proj, viewport, &c4.x(), &c4.y(), &c4.z());
+  
+    GLboolean clip1, clip2, clip3;
+    glGetBooleanv(GL_CLIP_PLANE0, &clip1);
+    glGetBooleanv(GL_CLIP_PLANE2, &clip2);
+    glGetBooleanv(GL_CLIP_PLANE4, &clip3);
+  
+    setup3DRenderingData(shader);
+  
+    drawPlane(shader, Size, stack->size(), stack->origin(), stack->scale().x(),   // ALR: not sure what to do here
+              Slices, clip1, clip2, clip3, Point3f(c1), Point3f(c2), Point3f(c3), Point3f(c4));
+  
+    // drawPlane(shader, Size, stack->size(), stack->origin(), stack->scale(),
+    //          Slices,
+    //          clip1, clip2, clip3,
+    //          Point3f(c1), Point3f(c2), Point3f(c3), Point3f(c4));
+    unbind3DTex();
+  
+    // glBlendEquation(GL_FUNC_ADD);
+    glDisable(GL_BLEND);
+    glMatrixMode(GL_MODELVIEW);
+    glPopMatrix();
+    REPORT_GL_ERROR("drawStack");
+  }
+  
+  void ImgData::drawBBox()
+  {
+    if(!stack->showBBox() or !(mainDataTexId or workDataTexId))
+      return;
+    glDisable(GL_LIGHTING);
+    glDisable(GL_TEXTURE_1D);
+    glDisable(GL_TEXTURE_2D);
+    glDisable(GL_TEXTURE_3D);
+    glDisable(GL_BLEND);
+    glDisable(GL_ALPHA_TEST);
+    glDisable(GL_AUTO_NORMAL);
+    glEnable(GL_DEPTH_TEST);
+  
     glLineWidth(MeshLineWidth);
-    glEnableClientState(GL_VERTEX_ARRAY);
-    glEnableClientState(GL_COLOR_ARRAY);
-
-    glBindBufferARB(GL_ARRAY_BUFFER_ARB, pntsVAid);
-    glVertexPointer(3, GL_FLOAT, 0, 0);
-    glBindBufferARB(GL_ARRAY_BUFFER_ARB, pcolVAid);
-    glColorPointer(3, GL_UNSIGNED_BYTE, 0, 0);
-    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
-    switch(mesh->meshView()) {
-    case Mesh::ALL_MESH:
-      glDrawElements(GL_LINES, lineVA.size(), GL_UNSIGNED_INT, &lineVA[0]);
-      break;
-    case Mesh::BORDER_MESH:
-      glDrawElements(GL_LINES, lbrdVA.size(), GL_UNSIGNED_INT, &lbrdVA[0]);
-      break;
-    case Mesh::CELL_MESH:
-      glDrawElements(GL_LINES, lcellVA.size(), GL_UNSIGNED_INT, &lcellVA[0]);
-      break;
-    case Mesh::SELECTED_MESH:
-      glDrawElements(GL_LINES, lselVA.size(), GL_UNSIGNED_INT, &lselVA[0]);
-      break;
-    }
-    glDisableClientState(GL_VERTEX_ARRAY);
-    glDisableClientState(GL_COLOR_ARRAY);
+  
+    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+  
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glMultMatrixd(getFrame().worldMatrix());
+  
+    Colorf c = Colors::getColor((StackId == 0) ? Colors::Stack1BBoxColor : Colors::Stack2BBoxColor);
+  
+    glColor4fv(c.c_data());
+  
+    const Point3f& Origin = stack->origin();
+    Point3f c1 = Origin;
+    Point3f c2 = Origin + stack->worldSize();
+  
+    glBegin(GL_QUADS);
+    glVertex3f(c1.x(), c1.y(), c1.z());
+    glVertex3f(c1.x(), c2.y(), c1.z());
+    glVertex3f(c2.x(), c2.y(), c1.z());
+    glVertex3f(c2.x(), c1.y(), c1.z());
+  
+    glVertex3f(c1.x(), c1.y(), c2.z());
+    glVertex3f(c1.x(), c2.y(), c2.z());
+    glVertex3f(c2.x(), c2.y(), c2.z());
+    glVertex3f(c2.x(), c1.y(), c2.z());
+    glEnd();
+  
+    glBegin(GL_LINES);
+    glVertex3f(c1.x(), c1.y(), c1.z());
+    glVertex3f(c1.x(), c1.y(), c2.z());
+  
+    glVertex3f(c1.x(), c2.y(), c1.z());
+    glVertex3f(c1.x(), c2.y(), c2.z());
+  
+    glVertex3f(c2.x(), c2.y(), c1.z());
+    glVertex3f(c2.x(), c2.y(), c2.z());
+  
+    glVertex3f(c2.x(), c1.y(), c1.z());
+    glVertex3f(c2.x(), c1.y(), c2.z());
+    glEnd();
+  
+    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+    glMatrixMode(GL_MODELVIEW);
+    glPopMatrix();
+    REPORT_GL_ERROR("drawBBox");
   }
-
-  if(mesh->showMeshPoints()) {
-    glEnableClientState(GL_VERTEX_ARRAY);
-    glEnableClientState(GL_COLOR_ARRAY);
-
-    if(select) {
-      glRenderMode(GL_RENDER);
-      glDrawBuffer(GL_AUX0);
-      glClearColor(0, 0, 0, 1.0);
-      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-      glPointSize(MeshPointSize * 2);
-    } else
-      glPointSize(MeshPointSize);
-
-    if(select or (mesh->meshView() == Mesh::ALL_MESH)) {
+  
+  // Draw mesh wireframe
+  void ImgData::drawMesh(bool select)
+  {
+    vvgraph& S = mesh->graph();
+    if(S.empty() or !mesh->isMeshVisible() or (select and !MeshSelect))
+      return;
+  
+    glDisable(GL_LIGHTING);
+    glDisable(GL_TEXTURE_1D);
+    glDisable(GL_TEXTURE_2D);
+    glDisable(GL_TEXTURE_3D);
+    glDisable(GL_BLEND);
+    glDisable(GL_ALPHA_TEST);
+    glDisable(GL_AUTO_NORMAL);
+    glEnable(GL_DEPTH_TEST);
+    // glEnable(GL_MULTISAMPLE);
+    glFrontFace(GL_CCW);
+  
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glMultMatrixd(getFrame().worldMatrix());
+    // if(stack->scale() != 1.0)
+    if(stack->scale() != Point3f(1.0, 1.0, 1.0))
+      glScaled(stack->scale().x(), stack->scale().y(), stack->scale().z());
+    // glScaled(stack->scale(), stack->scale(), stack->scale());
+  
+    if(mesh->showMeshLines() and !select) {
+      glLineWidth(MeshLineWidth);
+      glEnableClientState(GL_VERTEX_ARRAY);
+      glEnableClientState(GL_COLOR_ARRAY);
+  
       glBindBufferARB(GL_ARRAY_BUFFER_ARB, pntsVAid);
       glVertexPointer(3, GL_FLOAT, 0, 0);
-      glBindBufferARB(GL_ARRAY_BUFFER_ARB, select ? pselVAid : pcolVAid);
-      glColorPointer(3, GL_UNSIGNED_BYTE, 0, 0);
-      glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
-      glDrawArrays(GL_POINTS, 0, pntsVA.size());
-    } else {
-      glBindBufferARB(GL_ARRAY_BUFFER_ARB, pntsVAid);
-      glVertexPointer(3, GL_FLOAT, 0, 0);
       glBindBufferARB(GL_ARRAY_BUFFER_ARB, pcolVAid);
       glColorPointer(3, GL_UNSIGNED_BYTE, 0, 0);
       glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
       switch(mesh->meshView()) {
+      case Mesh::ALL_MESH:
+        glDrawElements(GL_LINES, lineVA.size(), GL_UNSIGNED_INT, &lineVA[0]);
+        break;
       case Mesh::BORDER_MESH:
-        glDrawElements(GL_POINTS, pbrdVA.size(), GL_UNSIGNED_INT, &pbrdVA[0]);
+        glDrawElements(GL_LINES, lbrdVA.size(), GL_UNSIGNED_INT, &lbrdVA[0]);
         break;
       case Mesh::CELL_MESH:
-        glDrawElements(GL_POINTS, pcellVA.size(), GL_UNSIGNED_INT, &pcellVA[0]);
+        glDrawElements(GL_LINES, lcellVA.size(), GL_UNSIGNED_INT, &lcellVA[0]);
         break;
       case Mesh::SELECTED_MESH:
-        glDrawElements(GL_POINTS, pselVA.size(), GL_UNSIGNED_INT, &pselVA[0]);
-      default:
+        glDrawElements(GL_LINES, lselVA.size(), GL_UNSIGNED_INT, &lselVA[0]);
         break;
       }
+      glDisableClientState(GL_VERTEX_ARRAY);
+      glDisableClientState(GL_COLOR_ARRAY);
     }
-    if(select)
-      glDrawBuffer(GL_BACK);
-
-    glDisableClientState(GL_VERTEX_ARRAY);
-    glDisableClientState(GL_COLOR_ARRAY);
-  }
-
-  if(DrawNormals > 0) {
-    glLineWidth(MeshLineWidth);
-    Color3f col = Colors::getColor(MeshBorderColor);
-    glColor3fv(col.data());
-    glBegin(GL_LINES);
-    forall(const vertex& v, S) {
-      glVertex3fv(v->pos.c_data());
-      glVertex3fv((v->pos + DrawNormals * v->nrml).c_data());
+  
+    if(mesh->showMeshPoints()) {
+      glEnableClientState(GL_VERTEX_ARRAY);
+      glEnableClientState(GL_COLOR_ARRAY);
+  
+      if(select) {
+        glRenderMode(GL_RENDER);
+        glDrawBuffer(GL_AUX0);
+        glClearColor(0, 0, 0, 1.0);
+        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+        glPointSize(MeshPointSize * 2);
+      } else
+        glPointSize(MeshPointSize);
+  
+      if(select or (mesh->meshView() == Mesh::ALL_MESH)) {
+        glBindBufferARB(GL_ARRAY_BUFFER_ARB, pntsVAid);
+        glVertexPointer(3, GL_FLOAT, 0, 0);
+        glBindBufferARB(GL_ARRAY_BUFFER_ARB, select ? pselVAid : pcolVAid);
+        glColorPointer(3, GL_UNSIGNED_BYTE, 0, 0);
+        glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
+        glDrawArrays(GL_POINTS, 0, pntsVA.size());
+      } else {
+        glBindBufferARB(GL_ARRAY_BUFFER_ARB, pntsVAid);
+        glVertexPointer(3, GL_FLOAT, 0, 0);
+        glBindBufferARB(GL_ARRAY_BUFFER_ARB, pcolVAid);
+        glColorPointer(3, GL_UNSIGNED_BYTE, 0, 0);
+        glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
+        switch(mesh->meshView()) {
+        case Mesh::BORDER_MESH:
+          glDrawElements(GL_POINTS, pbrdVA.size(), GL_UNSIGNED_INT, &pbrdVA[0]);
+          break;
+        case Mesh::CELL_MESH:
+          glDrawElements(GL_POINTS, pcellVA.size(), GL_UNSIGNED_INT, &pcellVA[0]);
+          break;
+        case Mesh::SELECTED_MESH:
+          glDrawElements(GL_POINTS, pselVA.size(), GL_UNSIGNED_INT, &pselVA[0]);
+        default:
+          break;
+        }
+      }
+      if(select)
+        glDrawBuffer(GL_BACK);
+  
+      glDisableClientState(GL_VERTEX_ARRAY);
+      glDisableClientState(GL_COLOR_ARRAY);
     }
-    glEnd();
+  
+    if(DrawNormals > 0) {
+      glLineWidth(MeshLineWidth);
+      Color3f col = Colors::getColor(MeshBorderColor);
+      glColor3fv(col.data());
+      glBegin(GL_LINES);
+      forall(const vertex& v, S) {
+        glVertex3fv(v->pos.c_data());
+        glVertex3fv((v->pos + DrawNormals * v->nrml).c_data());
+      }
+      glEnd();
+    }
+    if(DrawZeroLabels > 0) {
+      glLineWidth(MeshLineWidth);
+      Color3f col = Colors::getColor(MeshBorderColor);
+      glColor3fv(col.data());
+      glBegin(GL_LINES);
+      forall(const vertex& v, S) {
+        if(v->label != 0)
+          continue;
+        glVertex3fv(v->pos.c_data());
+        glVertex3fv((v->pos + DrawZeroLabels * v->nrml).c_data());
+      }
+      glEnd();
+    }
+    if(DrawNhbds > 0) {
+      glLineWidth(MeshLineWidth);
+      Color3f col = Colors::getColor(MeshBorderColor);
+      glColor3fv(col.data());
+      glBegin(GL_LINES);
+      forall(const vertex& v, S) {
+        float d = .1f;
+        forall(const vertex& n, S.neighbors(v)) {
+          Point3f a = (n->pos - v->pos).normalize();
+          glVertex3fv(v->pos.c_data());
+          glVertex3fv((v->pos + DrawNhbds * (d * a + .1f * v->nrml)).c_data());
+          d += .1f;
+        }
+      }
+      glEnd();
+    }
+    /*
+     * if(MeshBorderV) {
+     *  glLineWidth(MeshLineWidth);
+     *  Color3f col = Colors::getColor(MeshBorderColor);
+     *  col /= 255.0;
+     *  glColor3fv(col.data());
+     *  glBegin(GL_LINES);
+     *  forall(const vertex &v, S) {
+     *    if(v->minb != 0) {
+     *      vertex minb(v->minb);
+     *      glVertex3fv(v->pos.c_data());
+     *      glVertex3fv(minb->pos.c_data());
+     *    }
+     *  }
+     *  glEnd();
+     *}
+     */
+    glMatrixMode(GL_MODELVIEW);
+    glPopMatrix();
+    glDisable(GL_POLYGON_OFFSET_FILL);
+    glDisable(GL_POLYGON_OFFSET_LINE);
+    REPORT_GL_ERROR("drawMesh");
   }
-  if(DrawZeroLabels > 0) {
-    glLineWidth(MeshLineWidth);
-    Color3f col = Colors::getColor(MeshBorderColor);
-    glColor3fv(col.data());
-    glBegin(GL_LINES);
-    forall(const vertex& v, S) {
-      if(v->label != 0)
-        continue;
-      glVertex3fv(v->pos.c_data());
-      glVertex3fv((v->pos + DrawZeroLabels * v->nrml).c_data());
+  
+  // Draw line in between pairs of junctions of two corresponding cell meshes (used in MeshProcessGrowth)
+  void ImgData::drawVertexVertexLine(ImgData* otherstack)
+  {
+    const vvgraph& S1 = this->mesh->graph();
+    const vvgraph& S2 = otherstack->mesh->graph();
+  
+    IntMatrix3x3fMap& VVCorrespondance = this->mesh->vvCorrespondance();
+  
+    if(!this->mesh->isMeshVisible() and !otherstack->mesh->isMeshVisible() and !this->mesh->isSurfaceVisible()
+       and !otherstack->mesh->isSurfaceVisible())
+      return;
+  
+    if(S1.empty() or S2.empty() or VVCorrespondance.empty()) {
+      DEBUG_OUTPUT("VVcorrespondance empty");
+      return;
     }
-    glEnd();
-  }
-  if(DrawNhbds > 0) {
-    glLineWidth(MeshLineWidth);
-    Color3f col = Colors::getColor(MeshBorderColor);
-    glColor3fv(col.data());
+  
+    bool showlines = this->mesh->showVVCorrespondance();
+    if(!showlines)
+      return;
+  
+    // stack matrices
+    Matrix4d st1 = ~Matrix4d(getFrame().worldMatrix());
+    Matrix4d st2 = ~Matrix4d(otherstack->getFrame().worldMatrix());
+  
+    glLineWidth(1);
+    glColor3f(1., 1., 1.);
+    glDisable(GL_LIGHTING);
     glBegin(GL_LINES);
-    forall(const vertex& v, S) {
-      float d = .1f;
-      forall(const vertex& n, S.neighbors(v)) {
-        Point3f a = (n->pos - v->pos).normalize();
-        glVertex3fv(v->pos.c_data());
-        glVertex3fv((v->pos + DrawNhbds * (d * a + .1f * v->nrml)).c_data());
-        d += .1f;
+    for(int i = 1; i <= (int)VVCorrespondance.size(); i++) {
+      if(VVCorrespondance.count(i) > 0) {
+        Point4f v1pos = Point4f(VVCorrespondance[i][0]);
+        Point4f v2pos = Point4f(VVCorrespondance[i][1]);
+        v1pos.t() = v2pos.t() = 1.0f;
+        // Clipping planes, point normal form
+        Point4f v1pos_transf = st1 * v1pos;
+        Point4f v2pos_transf = st2 * v2pos;
+        glVertex4fv(v1pos_transf.c_data());
+        glVertex4fv(v2pos_transf.c_data());
       }
     }
     glEnd();
+    glEnable(GL_LIGHTING);
+    REPORT_GL_ERROR("drawVertexVertexLine");
   }
-  /*
-   * if(MeshBorderV) {
-   *  glLineWidth(MeshLineWidth);
-   *  Color3f col = Colors::getColor(MeshBorderColor);
-   *  col /= 255.0;
-   *  glColor3fv(col.data());
-   *  glBegin(GL_LINES);
-   *  forall(const vertex &v, S) {
-   *    if(v->minb != 0) {
-   *      vertex minb(v->minb);
-   *      glVertex3fv(v->pos.c_data());
-   *      glVertex3fv(minb->pos.c_data());
-   *    }
-   *  }
-   *  glEnd();
-   *}
-   */
-  glMatrixMode(GL_MODELVIEW);
-  glPopMatrix();
-  glDisable(GL_POLYGON_OFFSET_FILL);
-  glDisable(GL_POLYGON_OFFSET_LINE);
-  REPORT_GL_ERROR("drawMesh");
-}
-
-// Draw line in between pairs of junctions of two corresponding cell meshes (used in MeshProcessGrowth)
-void ImgData::drawVertexVertexLine(ImgData* otherstack)
-{
-  const vvgraph& S1 = this->mesh->graph();
-  const vvgraph& S2 = otherstack->mesh->graph();
-
-  IntMatrix3x3fMap& VVCorrespondance = this->mesh->vvCorrespondance();
-
-  if(!this->mesh->isMeshVisible() and !otherstack->mesh->isMeshVisible() and !this->mesh->isSurfaceVisible()
-     and !otherstack->mesh->isSurfaceVisible())
-    return;
-
-  if(S1.empty() or S2.empty() or VVCorrespondance.empty()) {
-    DEBUG_OUTPUT("VVcorrespondance empty");
-    return;
-  }
-
-  bool showlines = this->mesh->showVVCorrespondance();
-  if(!showlines)
-    return;
-
-  // stack matrices
-  Matrix4d st1 = ~Matrix4d(getFrame().worldMatrix());
-  Matrix4d st2 = ~Matrix4d(otherstack->getFrame().worldMatrix());
-
-  glLineWidth(1);
-  glColor3f(1., 1., 1.);
-  glDisable(GL_LIGHTING);
-  glBegin(GL_LINES);
-  for(int i = 1; i <= (int)VVCorrespondance.size(); i++) {
-    if(VVCorrespondance.count(i) > 0) {
-      Point4f v1pos = Point4f(VVCorrespondance[i][0]);
-      Point4f v2pos = Point4f(VVCorrespondance[i][1]);
-      v1pos.t() = v2pos.t() = 1.0f;
-      // Clipping planes, point normal form
-      Point4f v1pos_transf = st1 * v1pos;
-      Point4f v2pos_transf = st2 * v2pos;
-      glVertex4fv(v1pos_transf.c_data());
-      glVertex4fv(v2pos_transf.c_data());
-    }
-  }
-  glEnd();
-  glEnable(GL_LIGHTING);
-  REPORT_GL_ERROR("drawVertexVertexLine");
-}
-
-// Draw cell axis (3 lines). The color is defined separately for each axis in each cell
-void ImgData::drawCellAxis()
-{
-  if(!mesh->isMeshVisible() and !mesh->isSurfaceVisible())
-    return;
-
-  const vvgraph& S = mesh->graph();
-  const IntMatrix3x3fMap& cellAxisScaled = mesh->cellAxisScaled();
-  const IntMatrix3x3fMap& cellAxisColor = mesh->cellAxisColor();
-  float cellAxisOffset = mesh->cellAxisOffset();
-
-  if(S.empty() or cellAxisScaled.empty())
-    return;
-
-  // Compute the color and positions of all the lines
-  const IntPoint3fMap& centers
-    = ((mesh->cellAxisType() == "PDG" and !mesh->parentLabelMap().empty()) ? mesh->parentCenterVis()
-       : mesh->labelCenterVis());
-  const IntPoint3fMap& normals
-    = ((mesh->cellAxisType() == "PDG" and !mesh->parentLabelMap().empty()) ? mesh->parentNormalVis()
-       : mesh->labelNormalVis());
-
-  std::vector<Point3f> colors, points;
-  // draw the 3 axis for each cell
-  forall(const IntPoint3fPair& lc, centers) {
-    int label = lc.first;
-    IntMatrix3x3fMap::const_iterator found_axis = cellAxisScaled.find(label);
-    IntMatrix3x3fMap::const_iterator found_color = cellAxisColor.find(label);
-    IntPoint3fMap::const_iterator found_normal = normals.find(label);
-    if(found_axis != cellAxisScaled.end() and found_color != cellAxisColor.end()) {
-      const Point3f& c = lc.second;
-      const Matrix3f& axis = found_axis->second;
-      const Matrix3f& col = found_color->second;
-
-      Point3f offset;
-      if(found_normal != normals.end())
-        offset = found_normal->second * cellAxisOffset;
-
-      for(size_t i = 0; i < 3; ++i) {
-        Point3f ax(axis[i]);
-        Point3f color(col[i]);
-
-        if(norm(ax) > 0) {
-          colors.push_back(color);
-          colors.push_back(color);
-          colors.push_back(color);
-          colors.push_back(color);
-
-          // normalize the offset to make sure the angle will be the same for all axis
-          Point3f off = offset * norm(ax);
-          points.push_back(c);
-          points.push_back(c - ax + off);
-          points.push_back(c);
-          points.push_back(c + ax + off);
+  
+  // Draw cell axis (3 lines). The color is defined separately for each axis in each cell
+  void ImgData::drawCellAxis()
+  {
+    if(!mesh->isMeshVisible() and !mesh->isSurfaceVisible())
+      return;
+  
+    const vvgraph& S = mesh->graph();
+    const IntMatrix3x3fMap& cellAxisScaled = mesh->cellAxisScaled();
+    const IntMatrix3x3fMap& cellAxisColor = mesh->cellAxisColor();
+    float cellAxisOffset = mesh->cellAxisOffset();
+  
+    if(S.empty() or cellAxisScaled.empty())
+      return;
+  
+    // Compute the color and positions of all the lines
+    const IntPoint3fMap& centers
+      = ((mesh->cellAxisType() == "PDG" and !mesh->parentLabelMap().empty()) ? mesh->parentCenterVis()
+         : mesh->labelCenterVis());
+    const IntPoint3fMap& normals
+      = ((mesh->cellAxisType() == "PDG" and !mesh->parentLabelMap().empty()) ? mesh->parentNormalVis()
+         : mesh->labelNormalVis());
+  
+    std::vector<Point3f> colors, points;
+    // draw the 3 axis for each cell
+    forall(const IntPoint3fPair& lc, centers) {
+      int label = lc.first;
+      IntMatrix3x3fMap::const_iterator found_axis = cellAxisScaled.find(label);
+      IntMatrix3x3fMap::const_iterator found_color = cellAxisColor.find(label);
+      IntPoint3fMap::const_iterator found_normal = normals.find(label);
+      if(found_axis != cellAxisScaled.end() and found_color != cellAxisColor.end()) {
+        const Point3f& c = lc.second;
+        const Matrix3f& axis = found_axis->second;
+        const Matrix3f& col = found_color->second;
+  
+        Point3f offset;
+        if(found_normal != normals.end())
+          offset = found_normal->second * cellAxisOffset;
+  
+        for(size_t i = 0; i < 3; ++i) {
+          Point3f ax(axis[i]);
+          Point3f color(col[i]);
+  
+          if(norm(ax) > 0) {
+            colors.push_back(color);
+            colors.push_back(color);
+            colors.push_back(color);
+            colors.push_back(color);
+  
+            // normalize the offset to make sure the angle will be the same for all axis
+            Point3f off = offset * norm(ax);
+            points.push_back(c);
+            points.push_back(c - ax + off);
+            points.push_back(c);
+            points.push_back(c + ax + off);
+          }
         }
       }
     }
-  }
-
-  // Draw the lines
-
-  // to follow camera and object transformation:
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glMultMatrixd(getFrame().worldMatrix());
-  // if(stack->scale() != 1.0)
-  if(norm(stack->scale()) != 1.0)
-    glScaled(stack->scale().x(), stack->scale().y(), stack->scale().z());
-  // glScaled(stack->scale(), stack->scale(), stack->scale());
-
-  glLineWidth(mesh->cellAxisWidth());
-  glDisable(GL_LIGHTING);
-
-  glEnableClientState(GL_COLOR_ARRAY);
-  glEnableClientState(GL_VERTEX_ARRAY);
-
-  glColorPointer(3, GL_FLOAT, 0, &colors.front());
-  glVertexPointer(3, GL_FLOAT, 0, &points.front());
-  glDrawArrays(GL_LINES, 0, points.size());
-
-  glDisableClientState(GL_COLOR_ARRAY);
-  glDisableClientState(GL_VERTEX_ARRAY);
-
-  glEnable(GL_LIGHTING);
-
-  glPopMatrix();   // to follow camera and object transformation
-  REPORT_GL_ERROR("drawCellAxis");
-}
-
-// Function for back-to-front sorting of triangles
-bool bToFCompare(const std::pair<float, uint>& p1, const std::pair<float, uint>& p2) {
-  return p1.first < p2.first;
-}
-
-// Draw mesh shaded, with and without select
-void ImgData::drawSurf(bool select, Shader* texture_shader, Shader* label_shader, Shader* volume_shader)
-{
-  vvgraph& S = mesh->graph();
-  if(S.empty() or (!select and !mesh->isSurfaceVisible())
-     or (select and MeshSelect))   // or (opaque_only and SurfBlend))
-    return;
-
-  glDisable(GL_LIGHTING);
-  glDisable(GL_TEXTURE_1D);
-  glDisable(GL_TEXTURE_2D);
-  glDisable(GL_TEXTURE_3D);
-  glDisable(GL_BLEND);
-  glDisable(GL_AUTO_NORMAL);
-  glDisable(GL_CULL_FACE);
-  // glDisable(GL_COLOR_MATERIAL);
-  glEnable(GL_DEPTH_TEST);
-  glFrontFace(GL_CCW);
-  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-
-  // glEnable(GL_POLYGON_OFFSET_FILL);
-  // glEnable(GL_POLYGON_OFFSET_LINE);
-  // glPolygonOffset(0.0f,DrawOffset*(StackId+1.0f));
-
-  // glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
-  glEnableClientState(GL_VERTEX_ARRAY);
-  if(select) {
+  
+    // Draw the lines
+  
+    // to follow camera and object transformation:
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glMultMatrixd(getFrame().worldMatrix());
+    // if(stack->scale() != 1.0)
+    if(norm(stack->scale()) != 1.0)
+      glScaled(stack->scale().x(), stack->scale().y(), stack->scale().z());
+    // glScaled(stack->scale(), stack->scale(), stack->scale());
+  
+    glLineWidth(mesh->cellAxisWidth());
+    glDisable(GL_LIGHTING);
+  
     glEnableClientState(GL_COLOR_ARRAY);
-  } else {
-    glEnableClientState(GL_NORMAL_ARRAY);
-    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+    glEnableClientState(GL_VERTEX_ARRAY);
+  
+    glColorPointer(3, GL_FLOAT, 0, &colors.front());
+    glVertexPointer(3, GL_FLOAT, 0, &points.front());
+    glDrawArrays(GL_LINES, 0, points.size());
+  
+    glDisableClientState(GL_COLOR_ARRAY);
+    glDisableClientState(GL_VERTEX_ARRAY);
+  
+    glEnable(GL_LIGHTING);
+  
+    glPopMatrix();   // to follow camera and object transformation
+    REPORT_GL_ERROR("drawCellAxis");
   }
-
-  // First bind positions
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, posVAid);
-  glVertexPointer(3, GL_FLOAT, 0, 0);
-
-  Shader* shader = 0;
-  Shader::activeTexture(Shader::AT_NONE);
-
-  // Set matrix, scale if required
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glMultMatrixd(getFrame().worldMatrix());
-  if(stack->scale() != Point3f(1.0, 1.0, 1.0))
-    glScaled(stack->scale().x(), stack->scale().y(), stack->scale().z());
-  // if(stack->scale() != 1.0)
-  //  glScaled(stack->scale(), stack->scale(), stack->scale());
-
-  // Now do colors and/or texture
-  if(select) {
-    glRenderMode(GL_RENDER);
-    glDrawBuffer(GL_AUX0);
-
-    glClearColor(0, 0, 0, 1);
-    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-    glBindBufferARB(GL_ARRAY_BUFFER_ARB, selVAid);
-    glColorPointer(3, GL_UNSIGNED_BYTE, 0, 0);
-  } else {
-    setupSurfColorMap();
-    setupHeatColorMap();
-    setupLabelColorMap();
-    glEnable(GL_LIGHTING);
-    if(mesh->culling())
-      glEnable(GL_CULL_FACE);
+  
+  // Function for back-to-front sorting of triangles
+  bool bToFCompare(const std::pair<float, uint>& p1, const std::pair<float, uint>& p2) {
+    return p1.first < p2.first;
+  }
+  
+  // Draw mesh shaded, with and without select
+  void ImgData::drawSurf(bool select, Shader* texture_shader, Shader* label_shader, Shader* volume_shader)
+  {
+    vvgraph& S = mesh->graph();
+    if(S.empty() or (!select and !mesh->isSurfaceVisible())
+       or (select and MeshSelect))   // or (opaque_only and SurfBlend))
+      return;
+  
+    glDisable(GL_LIGHTING);
+    glDisable(GL_TEXTURE_1D);
+    glDisable(GL_TEXTURE_2D);
+    glDisable(GL_TEXTURE_3D);
+    glDisable(GL_BLEND);
+    glDisable(GL_AUTO_NORMAL);
+    glDisable(GL_CULL_FACE);
     // glDisable(GL_COLOR_MATERIAL);
-    glBindBufferARB(GL_ARRAY_BUFFER_ARB, nrmlVAid);
-    glNormalPointer(GL_FLOAT, 0, 0);
-    if(mesh->coloring() == Mesh::IMAGE and mesh->hasImgTex()) {
-      shader = texture_shader;
-
-      glColor4f(0, 0, 0, 1);
-      bind2DTex(imgTexId);
-
-      shader->setUniform("tex", GLSLValue(Shader::AT_TEX2D));
-      shader->setUniform("blending", GLSLValue(mesh->blending()));
-
-      glBindBufferARB(GL_ARRAY_BUFFER_ARB, imgVAid);
-      glTexCoordPointer(2, GL_FLOAT, 0, 0);
-      glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
-    } else if(mesh->coloring() == Mesh::TEXTURE) {
-      shader = volume_shader;
-
-      setup3DRenderingData(shader);
-
-      shader->setUniform("blending", GLSLValue(mesh->blending()));
-
-      // Scale texture coordinate!
-      glMatrixMode(GL_TEXTURE);
-      glPushMatrix();
-      glMatrixMode(GL_MODELVIEW);
-
-      glColor4f(1, 1, 1, 1);
-      glBindBufferARB(GL_ARRAY_BUFFER_ARB, posVAid);
-      glTexCoordPointer(3, GL_FLOAT, 0, 0);
-      glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
+    glEnable(GL_DEPTH_TEST);
+    glFrontFace(GL_CCW);
+    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+  
+    // glEnable(GL_POLYGON_OFFSET_FILL);
+    // glEnable(GL_POLYGON_OFFSET_LINE);
+    // glPolygonOffset(0.0f,DrawOffset*(StackId+1.0f));
+  
+    // glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
+    glEnableClientState(GL_VERTEX_ARRAY);
+    if(select) {
+      glEnableClientState(GL_COLOR_ARRAY);
     } else {
-      Point2f& signalBounds = mesh->signalBounds();
-      if(signalBounds[1] <= signalBounds[0])
-        signalBounds[1] = signalBounds[0] + 1;
-      Point2f& heatMapBounds = mesh->heatMapBounds();
-      if(heatMapBounds[1] <= heatMapBounds[0])
-        heatMapBounds[1] = heatMapBounds[0] + 1;
-      // The normal case (including labels and heatmap)
-      shader = label_shader;
-      shader->setUniform("labels", GLSLValue(mesh->toShow() == Mesh::LABEL or mesh->toShow() == Mesh::PARENT));
-      shader->setUniform("heatmap", GLSLValue(mesh->toShow() == Mesh::HEAT));
-      // shader->setUniform("surfcolormap", GLSLValue(Shader::AT_SURF_TEX));
-      // shader->setUniform("labelcolormap", GLSLValue(Shader::AT_LABEL_TEX));
-      // shader->setUniform("heatcolormap", GLSLValue(Shader::AT_HEAT_TEX));
-      shader->setUniform("blending", GLSLValue(mesh->blending()));
-      shader->setUniform("signalBounds", GLSLValue(signalBounds));
-      shader->setUniform("heatBounds", GLSLValue(heatMapBounds));
-      shader->setUniform("infinity", GLSLValue(std::numeric_limits<float>::infinity()));
-
-      glColor4f(1, 1, 1, 1);
-      glMatrixMode(GL_TEXTURE);
-      glLoadIdentity();
-      glBindBufferARB(GL_ARRAY_BUFFER_ARB, texVAid);
-      glTexCoordPointer(3, GL_FLOAT, 0, 0);
+      glEnableClientState(GL_NORMAL_ARRAY);
+      glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+    }
+  
+    // First bind positions
+    glBindBufferARB(GL_ARRAY_BUFFER_ARB, posVAid);
+    glVertexPointer(3, GL_FLOAT, 0, 0);
+  
+    Shader* shader = 0;
+    Shader::activeTexture(Shader::AT_NONE);
+  
+    // Set matrix, scale if required
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glMultMatrixd(getFrame().worldMatrix());
+    if(stack->scale() != Point3f(1.0, 1.0, 1.0))
+      glScaled(stack->scale().x(), stack->scale().y(), stack->scale().z());
+    // if(stack->scale() != 1.0)
+    //  glScaled(stack->scale(), stack->scale(), stack->scale());
+  
+    // Now do colors and/or texture
+    if(select) {
+      glRenderMode(GL_RENDER);
+      glDrawBuffer(GL_AUX0);
+  
+      glClearColor(0, 0, 0, 1);
+      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+      glBindBufferARB(GL_ARRAY_BUFFER_ARB, selVAid);
+      glColorPointer(3, GL_UNSIGNED_BYTE, 0, 0);
+    } else {
+      setupSurfColorMap();
       setupHeatColorMap();
-
-      glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
-      glMatrixMode(GL_MODELVIEW);
+      setupLabelColorMap();
+      glEnable(GL_LIGHTING);
+      if(mesh->culling())
+        glEnable(GL_CULL_FACE);
+      // glDisable(GL_COLOR_MATERIAL);
+      glBindBufferARB(GL_ARRAY_BUFFER_ARB, nrmlVAid);
+      glNormalPointer(GL_FLOAT, 0, 0);
+      if(mesh->coloring() == Mesh::IMAGE and mesh->hasImgTex()) {
+        shader = texture_shader;
+  
+        glColor4f(0, 0, 0, 1);
+        bind2DTex(imgTexId);
+  
+        shader->setUniform("tex", GLSLValue(Shader::AT_TEX2D));
+        shader->setUniform("blending", GLSLValue(mesh->blending()));
+  
+        glBindBufferARB(GL_ARRAY_BUFFER_ARB, imgVAid);
+        glTexCoordPointer(2, GL_FLOAT, 0, 0);
+        glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
+      } else if(mesh->coloring() == Mesh::TEXTURE) {
+        shader = volume_shader;
+  
+        setup3DRenderingData(shader);
+  
+        shader->setUniform("blending", GLSLValue(mesh->blending()));
+  
+        // Scale texture coordinate!
+        glMatrixMode(GL_TEXTURE);
+        glPushMatrix();
+        glMatrixMode(GL_MODELVIEW);
+  
+        glColor4f(1, 1, 1, 1);
+        glBindBufferARB(GL_ARRAY_BUFFER_ARB, posVAid);
+        glTexCoordPointer(3, GL_FLOAT, 0, 0);
+        glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
+      } else {
+        Point2f& signalBounds = mesh->signalBounds();
+        if(signalBounds[1] <= signalBounds[0])
+          signalBounds[1] = signalBounds[0] + 1;
+        Point2f& heatMapBounds = mesh->heatMapBounds();
+        if(heatMapBounds[1] <= heatMapBounds[0])
+          heatMapBounds[1] = heatMapBounds[0] + 1;
+        // The normal case (including labels and heatmap)
+        shader = label_shader;
+        shader->setUniform("labels", GLSLValue(mesh->toShow() == Mesh::LABEL or mesh->toShow() == Mesh::PARENT));
+        shader->setUniform("heatmap", GLSLValue(mesh->toShow() == Mesh::HEAT));
+        // shader->setUniform("surfcolormap", GLSLValue(Shader::AT_SURF_TEX));
+        // shader->setUniform("labelcolormap", GLSLValue(Shader::AT_LABEL_TEX));
+        // shader->setUniform("heatcolormap", GLSLValue(Shader::AT_HEAT_TEX));
+        shader->setUniform("blending", GLSLValue(mesh->blending()));
+        shader->setUniform("signalBounds", GLSLValue(signalBounds));
+        shader->setUniform("heatBounds", GLSLValue(heatMapBounds));
+        shader->setUniform("infinity", GLSLValue(std::numeric_limits<float>::infinity()));
+  
+        glColor4f(1, 1, 1, 1);
+        glMatrixMode(GL_TEXTURE);
+        glLoadIdentity();
+        glBindBufferARB(GL_ARRAY_BUFFER_ARB, texVAid);
+        glTexCoordPointer(3, GL_FLOAT, 0, 0);
+        setupHeatColorMap();
+  
+        glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
+        glMatrixMode(GL_MODELVIEW);
+      }
     }
-  }
-
-  if(shader) {
-    shader->setUniform("brightness", GLSLValue(powf(mesh->brightness(), 2.0f)));
-    shader->setUniform("opacity", GLSLValue(mesh->opacity()));
+  
+    if(shader) {
+      shader->setUniform("brightness", GLSLValue(powf(mesh->brightness(), 2.0f)));
+      shader->setUniform("opacity", GLSLValue(mesh->opacity()));
+      if(mesh->coloring() == Mesh::TEXTURE) {
+        shader->setUniform("second_brightness", GLSLValue(powf(mesh->brightness(), 2.0f)));
+        shader->setUniform("second_opacity", GLSLValue(mesh->opacity()));
+      }
+      const BoundingBox3f& bbox = mesh->boundingBox();
+      float meshSize = norm(bbox[1] - bbox[0]);
+      shader->setUniform("shift", GLSLValue(meshShift * meshSize));
+      shader->useShaders();
+      shader->setupUniforms();
+      setupSurfColorMap();
+    }
+  
+    glDrawArrays(GL_TRIANGLES, 0, posVA.size());
+  
+    if(select) {
+      glDisableClientState(GL_COLOR_ARRAY);
+      glDrawBuffer(GL_BACK);
+    } else {
+      if(shader)
+        shader->stopUsingShaders();
+      glDisableClientState(GL_NORMAL_ARRAY);
+      glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+    }
+    glDisableClientState(GL_VERTEX_ARRAY);
+  
     if(mesh->coloring() == Mesh::TEXTURE) {
-      shader->setUniform("second_brightness", GLSLValue(powf(mesh->brightness(), 2.0f)));
-      shader->setUniform("second_opacity", GLSLValue(mesh->opacity()));
+      glMatrixMode(GL_TEXTURE);
+      glPopMatrix();
     }
-    const BoundingBox3f& bbox = mesh->boundingBox();
-    float meshSize = norm(bbox[1] - bbox[0]);
-    shader->setUniform("shift", GLSLValue(meshShift * meshSize));
-    shader->useShaders();
-    shader->setupUniforms();
-    setupSurfColorMap();
-  }
-
-  glDrawArrays(GL_TRIANGLES, 0, posVA.size());
-
-  if(select) {
-    glDisableClientState(GL_COLOR_ARRAY);
-    glDrawBuffer(GL_BACK);
-  } else {
-    if(shader)
-      shader->stopUsingShaders();
-    glDisableClientState(GL_NORMAL_ARRAY);
-    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-  }
-  glDisableClientState(GL_VERTEX_ARRAY);
-
-  if(mesh->coloring() == Mesh::TEXTURE) {
-    glMatrixMode(GL_TEXTURE);
+  
+    glMatrixMode(GL_MODELVIEW);
     glPopMatrix();
+    unbind3DTex();
+    unbind2DTex();
+  
+    glDisable(GL_POLYGON_OFFSET_FILL);
+    glDisable(GL_POLYGON_OFFSET_LINE);
+    REPORT_GL_ERROR("drawSurf");
   }
-
-  glMatrixMode(GL_MODELVIEW);
-  glPopMatrix();
-  unbind3DTex();
-  unbind2DTex();
-
-  glDisable(GL_POLYGON_OFFSET_FILL);
-  glDisable(GL_POLYGON_OFFSET_LINE);
-  REPORT_GL_ERROR("drawSurf");
-}
-
-// Compute area of 2D triangle
-float triangleArea2D(Point2f a, Point2f b, Point2f c)
-{
-  return fabs(((b.x() - a.x()) * (c.y() - a.y()) - (c.x() - a.x()) * (b.y() - a.y())) / 2.0);
-}
-
-// Subdivide bisect, recursively divide to prevent degenerate triangles
-void ImgData::subdivideBisect(vertex v1, vertex v2, vertex v3)
-{
-  // v1, v2, v3 must be in order
-  vertex a(0), b(0), c(0);
-
-  // Find longest edge and divide
-  a = v1;
-  b = v2;
-  c = v3;
-  if((v2->pos - v3->pos).norm() > (a->pos - b->pos).norm()) {
-    a = v2;
-    b = v3;
-    c = v1;
-  } else if((v3->pos - v1->pos).norm() > (a->pos - b->pos).norm()) {
-    a = v3;
-    b = v1;
-    c = v2;
+  
+  // Compute area of 2D triangle
+  float triangleArea2D(Point2f a, Point2f b, Point2f c)
+  {
+    return fabs(((b.x() - a.x()) * (c.y() - a.y()) - (c.x() - a.x()) * (b.y() - a.y())) / 2.0);
   }
-
-  vvgraph& S = mesh->graph();
-
-  // Insert vertex in long edge if not already there
-  if(S.edge(a, b)) {
-    vertex d;
-    d->type = 'j';
-    S.insert(d);
-    S.insertEdge(d, a);
-    S.insertEdge(d, b);
-    d->pos = (a->pos + b->pos) / 2.0;
-    d->signal = (a->signal + b->signal) / 2.0;
-    d->txpos = (a->txpos + b->txpos) / 2.0;
-    if(a->label == b->label)
-      d->label = a->label;
-    S.replace(a, b, d);
-    S.replace(b, a, d);
-  } else {
-    // Already there, must be the last triangle
-    vertex d = S.prevTo(a, c);
-    S.spliceAfter(c, a, d);
-    S.spliceBefore(d, a, c);
-    return;
-  }
-
-  // Create dividing edge
-  vertex d(0);
-  if(S.edge(a, c)) {
-    d = S.prevTo(a, c);
-    S.spliceAfter(c, a, d);
-    S.spliceBefore(d, a, c);
-    vertex v = S.nextTo(c, d);
-    // If edge c,b split by v, connect d to v
-    if(v != b) {
-      S.spliceBefore(d, c, v);
-      S.spliceAfter(v, c, d);
+  
+  // Subdivide bisect, recursively divide to prevent degenerate triangles
+  void ImgData::subdivideBisect(vertex v1, vertex v2, vertex v3)
+  {
+    // v1, v2, v3 must be in order
+    vertex a(0), b(0), c(0);
+  
+    // Find longest edge and divide
+    a = v1;
+    b = v2;
+    c = v3;
+    if((v2->pos - v3->pos).norm() > (a->pos - b->pos).norm()) {
+      a = v2;
+      b = v3;
+      c = v1;
+    } else if((v3->pos - v1->pos).norm() > (a->pos - b->pos).norm()) {
+      a = v3;
+      b = v1;
+      c = v2;
     }
-  } else if(S.edge(b, c)) {
-    d = S.nextTo(b, c);
-    S.spliceBefore(c, b, d);
-    S.spliceAfter(d, b, c);
-    vertex v = S.prevTo(c, d);
-    // If edge c,a split by v, connect d to v
-    if(v != a) {
-      S.spliceAfter(d, c, v);
-      S.spliceBefore(v, c, d);
+  
+    vvgraph& S = mesh->graph();
+  
+    // Insert vertex in long edge if not already there
+    if(S.edge(a, b)) {
+      vertex d;
+      d->type = 'j';
+      S.insert(d);
+      S.insertEdge(d, a);
+      S.insertEdge(d, b);
+      d->pos = (a->pos + b->pos) / 2.0;
+      d->signal = (a->signal + b->signal) / 2.0;
+      d->txpos = (a->txpos + b->txpos) / 2.0;
+      if(a->label == b->label)
+        d->label = a->label;
+      S.replace(a, b, d);
+      S.replace(b, a, d);
+    } else {
+      // Already there, must be the last triangle
+      vertex d = S.prevTo(a, c);
+      S.spliceAfter(c, a, d);
+      S.spliceBefore(d, a, c);
+      return;
     }
-  } else {
-    throw(QString("subdivideBisect::Error:Both incoming short edges divided"));
+  
+    // Create dividing edge
+    vertex d(0);
+    if(S.edge(a, c)) {
+      d = S.prevTo(a, c);
+      S.spliceAfter(c, a, d);
+      S.spliceBefore(d, a, c);
+      vertex v = S.nextTo(c, d);
+      // If edge c,b split by v, connect d to v
+      if(v != b) {
+        S.spliceBefore(d, c, v);
+        S.spliceAfter(v, c, d);
+      }
+    } else if(S.edge(b, c)) {
+      d = S.nextTo(b, c);
+      S.spliceBefore(c, b, d);
+      S.spliceAfter(d, b, c);
+      vertex v = S.prevTo(c, d);
+      // If edge c,a split by v, connect d to v
+      if(v != a) {
+        S.spliceAfter(d, c, v);
+        S.spliceBefore(v, c, d);
+      }
+    } else {
+      throw(QString("subdivideBisect::Error:Both incoming short edges divided"));
+    }
+  
+    // Find neighbor
+    vertex n(0);
+    if(S.prevTo(a, d) == S.nextTo(b, d)) {
+      n = S.prevTo(a, d);
+      // Neighbor already divided
+      if(S.edge(d, n))
+        return;
+      subdivideBisect(b, a, n);
+    }
   }
-
-  // Find neighbor
-  vertex n(0);
-  if(S.prevTo(a, d) == S.nextTo(b, d)) {
-    n = S.prevTo(a, d);
-    // Neighbor already divided
-    if(S.edge(d, n))
+  
+  // Get all vertices close to a set of border vertices
+  void ImgData::markBorder(float borderSize)
+  {
+    vvgraph& S = mesh->graph();
+    if(S.empty())
       return;
-    subdivideBisect(b, a, n);
-  }
-}
-
-// Get all vertices close to a set of border vertices
-void ImgData::markBorder(float borderSize)
-{
-  vvgraph& S = mesh->graph();
-  if(S.empty())
-    return;
-
-  SETSTATUS("Finding border vertices");
-
-  try {
-    // For cellular mesh we will mark all vertices
-    if(mesh->cells()) {
-      int bcount = 0;
-      forall(const vertex& v, S)
-        if(v->type == 'j') {
-          v->minb = v.id();
-          bcount++;
-        } else
-          v->minb = S.anyIn(v).id();
-      SETSTATUS("Border vertices:" << bcount << ", vertices near border:" << S.size() << " (cellular mesh)");
-    } else {
-      // Process non cellular mesh, first all border vertices in R
-      std::set<vertex> R;
-      forall(const vertex& v, S)
-        if(v->label == -1) {
-          R.insert(v);
-          v->minb = v.id();
-        } else
-          v->minb = 0;
-      uint bsize = R.size();
-
-      // Start with border vertices and propogate
-      std::set<vertex> T = R;       // Temp list
-      std::set<vertex> D;           // delete list
-      std::set<vertex> I;           // insert list
-
-      uint rsize;
-      do {
-        rsize = R.size();
-        forall(const vertex& v, T) {
-          // If a vertex doesn't add any neighbors, we'll assume it is interior
-          bool del = true;
-          forall(const vertex& n, S.neighbors(v)) {
-            // If not in border front
-            if(R.find(n) == R.end()) {
-              vertex w = vertex(v->minb);
-              if(w.isNull()) {
-                Information::out << "markBorder::Error:Null vertex w" << endl;
-                continue;
-              }
-              vertex minb = w;
-              double min = (n->pos - w->pos).norm();
-              // forall(const vertex &m, S.neighbors(w))
-              forall(const vertex& m, S.neighbors(n)) {
-                if(m->minb != 0) {
-                  vertex mb(m->minb);
-                  if(mb.isNull()) {
-                    Information::out << "markBorder::Error:Null vertex mb" << endl;
-                    continue;
+  
+    SETSTATUS("Finding border vertices");
+  
+    try {
+      // For cellular mesh we will mark all vertices
+      if(mesh->cells()) {
+        int bcount = 0;
+        forall(const vertex& v, S)
+          if(v->type == 'j') {
+            v->minb = v.id();
+            bcount++;
+          } else
+            v->minb = S.anyIn(v).id();
+        SETSTATUS("Border vertices:" << bcount << ", vertices near border:" << S.size() << " (cellular mesh)");
+      } else {
+        // Process non cellular mesh, first all border vertices in R
+        std::set<vertex> R;
+        forall(const vertex& v, S)
+          if(v->label == -1) {
+            R.insert(v);
+            v->minb = v.id();
+          } else
+            v->minb = 0;
+        uint bsize = R.size();
+  
+        // Start with border vertices and propogate
+        std::set<vertex> T = R;       // Temp list
+        std::set<vertex> D;           // delete list
+        std::set<vertex> I;           // insert list
+  
+        uint rsize;
+        do {
+          rsize = R.size();
+          forall(const vertex& v, T) {
+            // If a vertex doesn't add any neighbors, we'll assume it is interior
+            bool del = true;
+            forall(const vertex& n, S.neighbors(v)) {
+              // If not in border front
+              if(R.find(n) == R.end()) {
+                vertex w = vertex(v->minb);
+                if(w.isNull()) {
+                  Information::out << "markBorder::Error:Null vertex w" << endl;
+                  continue;
+                }
+                vertex minb = w;
+                double min = (n->pos - w->pos).norm();
+                // forall(const vertex &m, S.neighbors(w))
+                forall(const vertex& m, S.neighbors(n)) {
+                  if(m->minb != 0) {
+                    vertex mb(m->minb);
+                    if(mb.isNull()) {
+                      Information::out << "markBorder::Error:Null vertex mb" << endl;
+                      continue;
+                    }
+                    double dis = (n->pos - mb->pos).norm();
+                    if(dis < min) {
+                      min = dis;
+                      minb = mb;
+                    }
                   }
-                  double dis = (n->pos - mb->pos).norm();
-                  if(dis < min) {
-                    min = dis;
-                    minb = mb;
-                  }
                 }
+                if(min <= borderSize) {
+                  n->minb = minb.id();
+                  R.insert(n);
+                  I.insert(n);
+                }
+                del = false;
               }
-              if(min <= borderSize) {
-                n->minb = minb.id();
-                R.insert(n);
-                I.insert(n);
-              }
-              del = false;
             }
+            if(del)
+              D.insert(v);
           }
-          if(del)
-            D.insert(v);
-        }
-        forall(const vertex& v, I)
-          T.insert(v);
-        forall(const vertex& v, D)
-          T.erase(v);
-        I.clear();
-        D.clear();
-      } while(rsize < R.size());       // Do till R stops growing
-      SETSTATUS("Border vertices:" << bsize << ", vertices near border:" << R.size());
+          forall(const vertex& v, I)
+            T.insert(v);
+          forall(const vertex& v, D)
+            T.erase(v);
+          I.clear();
+          D.clear();
+        } while(rsize < R.size());       // Do till R stops growing
+        SETSTATUS("Border vertices:" << bsize << ", vertices near border:" << R.size());
+      }
     }
+    catch(QString mesg) {
+      throw(QString("markBorders::Unknow exception-" + mesg));
+    }
+    catch(...) {
+      throw(QString("markBorders::Unknow exception"));
+    }
   }
-  catch(QString mesg) {
-    throw(QString("markBorders::Unknow exception-" + mesg));
+  
+  bool ImgData::isBordTriangle(int label, vertex v, vertex n, vertex m, IntIntPair& wall)
+  {
+    return mesh->isBordTriangle(label, v, n, m, wall);
+    /*
+     *  if(WallVId.empty() or v->minb == 0 or n->minb == 0 or m->minb == 0)
+     *    return(false);
+     *
+     *  // Search through neighbor list and sum signal and area
+     *  forall(int lab, LabelNeighbors[label]) {
+     *    IntIntPair p(label, lab);
+     *    VIdSet &VtxSet = WallVId[p];
+     *
+     *    // If triangle belongs to this side of wall
+     *    int count = 0;
+     *    if(VtxSet.find(v->minb) != VtxSet.end())
+     *      count++;
+     *    if(VtxSet.find(n->minb) != VtxSet.end())
+     *      count++;
+     *    if(VtxSet.find(m->minb) != VtxSet.end())
+     *      count++;
+     *    if(count < 2)
+     *      continue;
+     *
+     *    wall = p;
+     *    return true;
+     *  }
+     *  return(false);
+     */
   }
-  catch(...) {
-    throw(QString("markBorders::Unknow exception"));
+  
+  // Reset mesh
+  void ImgData::resetMesh()
+  {
+    mesh->reset();
+    fillVBOs();
   }
-}
-
-bool ImgData::isBordTriangle(int label, vertex v, vertex n, vertex m, IntIntPair& wall)
-{
-  return mesh->isBordTriangle(label, v, n, m, wall);
-  /*
-   *  if(WallVId.empty() or v->minb == 0 or n->minb == 0 or m->minb == 0)
-   *    return(false);
-   *
-   *  // Search through neighbor list and sum signal and area
-   *  forall(int lab, LabelNeighbors[label]) {
-   *    IntIntPair p(label, lab);
-   *    VIdSet &VtxSet = WallVId[p];
-   *
-   *    // If triangle belongs to this side of wall
-   *    int count = 0;
-   *    if(VtxSet.find(v->minb) != VtxSet.end())
-   *      count++;
-   *    if(VtxSet.find(n->minb) != VtxSet.end())
-   *      count++;
-   *    if(VtxSet.find(m->minb) != VtxSet.end())
-   *      count++;
-   *    if(count < 2)
-   *      continue;
-   *
-   *    wall = p;
-   *    return true;
-   *  }
-   *  return(false);
-   */
-}
-
-// Reset mesh
-void ImgData::resetMesh()
-{
-  mesh->reset();
-  fillVBOs();
-}
-// Load mesh from a file
-// Routines to connect neighborhoods
-void ImgData::makeNhbd(vvgraph& S, vertex v, vertex n1, vertex n2, vertex n3, vertex n4)
-{
-  S.insertEdge(v, n1);
-  S.spliceAfter(v, n1, n2);
-  S.spliceAfter(v, n2, n3);
-  S.spliceAfter(v, n3, n4);
-}
-
-void ImgData::makeNhbd(vvgraph& S, vertex v, vertex n1, vertex n2, vertex n3, vertex n4, vertex n5, vertex n6)
-{
-  S.insertEdge(v, n1);
-  S.spliceAfter(v, n1, n2);
-  S.spliceAfter(v, n2, n3);
-  S.spliceAfter(v, n3, n4);
-  S.spliceAfter(v, n4, n5);
-  S.spliceAfter(v, n5, n6);
-}
-
-void ImgData::makeNhbd(std::vector<vertex>& vtxs)
-{
-  vvgraph& S = mesh->graph();
-  vertex v = vtxs[0];
-  vertex pn(0);
-  for(uint i = 1; i < vtxs.size(); i++) {
-    vertex n = vtxs[i];
-    if(i == 1)
-      S.insertEdge(v, n);
-    else
-      S.spliceAfter(v, pn, n);
-    pn = n;
+  // Load mesh from a file
+  // Routines to connect neighborhoods
+  void ImgData::makeNhbd(vvgraph& S, vertex v, vertex n1, vertex n2, vertex n3, vertex n4)
+  {
+    S.insertEdge(v, n1);
+    S.spliceAfter(v, n1, n2);
+    S.spliceAfter(v, n2, n3);
+    S.spliceAfter(v, n3, n4);
   }
-}
-
-// Get points for ICP
-int ImgData::getPointsICP(std::vector<Point3f>& pts, qglviewer::Frame& frame)
-{
-  vvgraph& S = mesh->graph();
-  int count = 0;
-  if(mesh->isMeshVisible() and !S.empty()) {
-    forall(const vertex& v, S) {
-      // Choose vertices based on what is shown in gui
-      if((mesh->meshView() != Mesh::SELECTED_MESH)and !v->selected)
-        continue;
-      if((mesh->meshView() != Mesh::BORDER_MESH)and !v->margin)
-        continue;
-      if((mesh->meshView() != Mesh::CELL_MESH) and v->label != -1)
-        continue;
-      count++;
-      pts.push_back(Point3f(frame.inverseCoordinatesOf(qglviewer::Vec(v->pos))));
+  
+  void ImgData::makeNhbd(vvgraph& S, vertex v, vertex n1, vertex n2, vertex n3, vertex n4, vertex n5, vertex n6)
+  {
+    S.insertEdge(v, n1);
+    S.spliceAfter(v, n1, n2);
+    S.spliceAfter(v, n2, n3);
+    S.spliceAfter(v, n3, n4);
+    S.spliceAfter(v, n4, n5);
+    S.spliceAfter(v, n5, n6);
+  }
+  
+  void ImgData::makeNhbd(std::vector<vertex>& vtxs)
+  {
+    vvgraph& S = mesh->graph();
+    vertex v = vtxs[0];
+    vertex pn(0);
+    for(uint i = 1; i < vtxs.size(); i++) {
+      vertex n = vtxs[i];
+      if(i == 1)
+        S.insertEdge(v, n);
+      else
+        S.spliceAfter(v, pn, n);
+      pn = n;
     }
   }
-  return count;
-}
-
-// Reset stack data
-void ImgData::resetStack()
-{
-  stack->reset();
-  unloadTex();
-  emit stackUnloaded();
-}
-
-// Initialize controls
-void ImgData::initControls(QWidget* viewer)
-{
-  // Transfer functions
-  connect(workTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), this,
-          SLOT(updateWorkColorMap(const TransferFunction &)));
-  connect(mainTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), this,
-          SLOT(updateMainColorMap(const TransferFunction &)));
-  connect(surfTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), this,
-          SLOT(updateSurfColorMap(const TransferFunction &)));
-  connect(heatTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), this,
-          SLOT(updateHeatColorMap(const TransferFunction &)));
-
-  connect(workTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), viewer, SLOT(UpdateSlot()));
-  connect(mainTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), viewer, SLOT(UpdateSlot()));
-  connect(surfTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), viewer, SLOT(UpdateSlot()));
-  connect(heatTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), viewer, SLOT(UpdateSlot()));
-}
-
-// Determine if triangle is labeled, all vertices labelled and the same (or -1 = boundary)
-int ImgData::getLabel(vertex v1, vertex v2, vertex v3, bool useParentLabel) const
-{
-  return mesh->getLabel(v1, v2, v3, useParentLabel);
-}
-
-void ImgData::unloadTex()
-{
-  if(mainDataTexId)
-    glDeleteTextures(1, &mainDataTexId);
-  if(workDataTexId)
-    glDeleteTextures(1, &workDataTexId);
-  if(mcmapTexId)
-    glDeleteTextures(1, &mcmapTexId);
-  if(wcmapTexId)
-    glDeleteTextures(1, &wcmapTexId);
-  if(surfTexId)
-    glDeleteTextures(1, &surfTexId);
-  if(heatTexId)
-    glDeleteTextures(1, &heatTexId);
-
-  surfTexId = heatTexId = wcmapTexId = mcmapTexId = mainDataTexId = workDataTexId = 0;
-
-  // Histograms require update
-  invalidateHistogram(MainHist);
-  invalidateHistogram(WorkHist);
-  invalidateHistogram(SurfHist);
-  invalidateHistogram(HeatHist);
-}
-
-// Get decimation factors for each dimension
-Point3u ImgData::getTexStep()
-{
-  Point3u step;
-  for(uint i = 0; i < 3; i++) {
-    step[i] = stack->size()[i] / MaxTexSize[i];
-    if(stack->size()[i] % MaxTexSize[i] > 0)
-      step[i]++;
+  
+  // Get points for ICP
+  int ImgData::getPointsICP(std::vector<Point3f>& pts, qglviewer::Frame& frame)
+  {
+    vvgraph& S = mesh->graph();
+    int count = 0;
+    if(mesh->isMeshVisible() and !S.empty()) {
+      forall(const vertex& v, S) {
+        // Choose vertices based on what is shown in gui
+        if((mesh->meshView() != Mesh::SELECTED_MESH)and !v->selected)
+          continue;
+        if((mesh->meshView() != Mesh::BORDER_MESH)and !v->margin)
+          continue;
+        if((mesh->meshView() != Mesh::CELL_MESH) and v->label != -1)
+          continue;
+        count++;
+        pts.push_back(Point3f(frame.inverseCoordinatesOf(qglviewer::Vec(v->pos))));
+      }
+    }
+    return count;
   }
-  return (step);
-}
-
-// Load data into texture, handle decimation if texture too big
-void ImgData::load3DTexData(const GLuint texId, const Point3u size, const ushort* data)
-{
-  if(swapTextureBytes(texId))
-    glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_TRUE);
-  // Find if any dimension need to be decimated
-  Point3u step = getTexStep();
-  if(step == Point3u(1u, 1u, 1u)) {
-    GLsizei width = size.x();
-
-    if(width % 4 == 0)
-      glPixelStorei(GL_UNPACK_ALIGNMENT, 8);
-    else if(width % 2 != 0)
-      glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
-
-    glTexImage3D(GL_TEXTURE_3D, 0, internalFormat(texId), size.x(), size.y(), size.z(), 0, GL_ALPHA,
-                 GL_UNSIGNED_SHORT, data);
-  } else {
-    Point3u sz = Point3u(size.x() / step.x(), size.y() / step.y(), size.z() / step.z());
-
-    HVecUS tpix(size_t(sz.x()) * sz.y() * sz.z());
-    ushort* p = tpix.data();
-
-    // Decimate array
-    for(uint z = step.z() / 2; z < sz.z() * step.z(); z += step.z())
-      for(uint y = step.y() / 2; y < sz.y() * step.y(); y += step.y())
-        for(uint x = step.x() / 2; x < sz.x() * step.x(); x += step.x())
-          *p++ = data[offset(x, y, z)];
-
-    GLsizei width = sz.x();
-
-    if(width % 4 == 0)
-      glPixelStorei(GL_UNPACK_ALIGNMENT, 8);
-    else if(width % 2 != 0)
-      glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
-
-    // Load smaller texture
-    glTexImage3D(GL_TEXTURE_3D, 0, internalFormat(texId), sz.x(), sz.y(), sz.z(), 0, GL_ALPHA, GL_UNSIGNED_SHORT,
-                 tpix.data());
+  
+  // Reset stack data
+  void ImgData::resetStack()
+  {
+    stack->reset();
+    unloadTex();
+    emit stackUnloaded();
   }
-  glPixelStorei(GL_UNPACK_ALIGNMENT, 4);   // Restore default
-  if(swapTextureBytes(texId))
-    glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
-
-  // Histograms require update
-  if(texId == mainDataTexId)
+  
+  // Initialize controls
+  void ImgData::initControls(QWidget* viewer)
+  {
+    // Transfer functions
+    connect(workTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), this,
+            SLOT(updateWorkColorMap(const TransferFunction &)));
+    connect(mainTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), this,
+            SLOT(updateMainColorMap(const TransferFunction &)));
+    connect(surfTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), this,
+            SLOT(updateSurfColorMap(const TransferFunction &)));
+    connect(heatTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), this,
+            SLOT(updateHeatColorMap(const TransferFunction &)));
+  
+    connect(workTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), viewer, SLOT(UpdateSlot()));
+    connect(mainTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), viewer, SLOT(UpdateSlot()));
+    connect(surfTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), viewer, SLOT(UpdateSlot()));
+    connect(heatTransferDlg, SIGNAL(changedTransferFunction(const TransferFunction &)), viewer, SLOT(UpdateSlot()));
+  }
+  
+  // Determine if triangle is labeled, all vertices labelled and the same (or -1 = boundary)
+  int ImgData::getLabel(vertex v1, vertex v2, vertex v3, bool useParentLabel) const
+  {
+    return mesh->getLabel(v1, v2, v3, useParentLabel);
+  }
+  
+  void ImgData::unloadTex()
+  {
+    if(mainDataTexId)
+      glDeleteTextures(1, &mainDataTexId);
+    if(workDataTexId)
+      glDeleteTextures(1, &workDataTexId);
+    if(mcmapTexId)
+      glDeleteTextures(1, &mcmapTexId);
+    if(wcmapTexId)
+      glDeleteTextures(1, &wcmapTexId);
+    if(surfTexId)
+      glDeleteTextures(1, &surfTexId);
+    if(heatTexId)
+      glDeleteTextures(1, &heatTexId);
+  
+    surfTexId = heatTexId = wcmapTexId = mcmapTexId = mainDataTexId = workDataTexId = 0;
+  
+    // Histograms require update
     invalidateHistogram(MainHist);
-  else if(texId == workDataTexId)
     invalidateHistogram(WorkHist);
-
-  glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, interpolation(mainDataTexId));
-  glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, interpolation(mainDataTexId));
-  glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
-  glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
-  glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);
-  float anisotropy;
-  glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &anisotropy);
-  glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropy);
-}
-
-void ImgData::reloadTex(GLuint texId)
-{
-  if(texId == 0 or stack->storeSize() == 0
-     or (texId == mainDataTexId and stack->main()->data().size() != stack->storeSize())
-     or (texId == workDataTexId and stack->work()->data().size() != stack->storeSize())) {
-    unloadTex();
-    return;
+    invalidateHistogram(SurfHist);
+    invalidateHistogram(HeatHist);
   }
-
-  glBindTexture(GL_TEXTURE_3D, texId);
-  HVecUS& wdata = stack->work()->data();
-  HVecUS& mdata = stack->main()->data();
-  const ushort* data = (texId == mainDataTexId) ? mdata.data() : wdata.data();
-  load3DTexData(texId, stack->size(), data);
-}
-
-// Update a section of a texture defined in image coordinates by a bounding box
-void ImgData::updateTex(GLuint texId, BoundingBox3i bBox)
-{
-  if(texId == 0 or stack->storeSize() == 0 or stack->main()->data().size() != stack->storeSize()
-     or stack->work()->data().size() != stack->storeSize())
-    return;
-
-  HVecUS& data = (texId == mainDataTexId ? stack->main()->data() : stack->work()->data());
-
-  Point3i base(bBox[0].x(), bBox[0].y(), bBox[0].z());
-  Point3i bsz(bBox[1].x() - bBox[0].x(), bBox[1].y() - bBox[0].y(), bBox[1].z() - bBox[0].z());
-
-  if(swapTextureBytes(texId))
-    glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_TRUE);
-  // Get factor to decimate texture if required
-  Point3u step = getTexStep();
-  // Enlarge bounding box to multiples of steps
-  if(step != Point3u(1u, 1u, 1u)) {
-    base.x() -= base.x() % step.x();
-    base.y() -= base.y() % step.y();
-    base.z() -= base.z() % step.z();
-    bsz.x() += base.x() % step.x();
-    bsz.y() += base.y() % step.y();
-    bsz.z() += base.z() % step.z();
-    if(bsz.x() % step.x() > 0)
-      bsz.x() = bsz.x() / step.x() + 1;
-    else
-      bsz.x() /= step.x();
-    if(bsz.y() % step.y() > 0)
-      bsz.y() = bsz.y() / step.y() + 1;
-    else
-      bsz.y() /= step.y();
-    if(bsz.z() % step.z() > 0)
-      bsz.z() = bsz.z() / step.z() + 1;
-    else
-      bsz.z() /= step.z();
-
-    HVecUS tpix(size_t(bsz.x()) * bsz.y() * bsz.z());
-
-    ushort* p = tpix.data();
-    for(uint z = base.z() + step.z() / 2; z < base.z() + bsz.z() * step.z(); z += step.z())
-      for(uint y = base.y() + step.y() / 2; y < base.y() + bsz.y() * step.y(); y += step.y())
-        for(uint x = base.x() + step.x() / 2; x < base.x() + bsz.x() * step.x(); x += step.x())
-          *p++ = data[offset(x, y, z)];
-
-    glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
-
-    // Load texture subimage
-    glBindTexture(GL_TEXTURE_3D, texId);
-    glTexSubImage3D(GL_TEXTURE_3D, 0, base.x() / step.x(), base.y() / step.y(), base.z() / step.z(), bsz.x(),
-                    bsz.y(), bsz.z(), GL_ALPHA, GL_UNSIGNED_SHORT, tpix.data());
-    glBindTexture(GL_TEXTURE_3D, 0);
-
-    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);     // Restore default
-  } else {
-    // Update only the part needed
-    glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
-
-    glBindTexture(GL_TEXTURE_3D, texId);
-    glPixelStorei(GL_UNPACK_ROW_LENGTH, stack->size().x());
-    glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, stack->size().y());
-    glTexSubImage3D(GL_TEXTURE_3D, 0, base.x(), base.y(), base.z(), bsz.x(), bsz.y(), bsz.z(), GL_ALPHA,
-                    GL_UNSIGNED_SHORT, &data[offset(base.x(), base.y(), base.z())]);
-    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
-    glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
-    glBindTexture(GL_TEXTURE_3D, 0);
-
-    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);     // Restore default
+  
+  // Get decimation factors for each dimension
+  Point3u ImgData::getTexStep()
+  {
+    Point3u step;
+    for(uint i = 0; i < 3; i++) {
+      step[i] = stack->size()[i] / MaxTexSize[i];
+      if(stack->size()[i] % MaxTexSize[i] > 0)
+        step[i]++;
+    }
+    return (step);
   }
-  if(swapTextureBytes(texId))
-    glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
-
-  // Histograms require update
-  if(texId == mainDataTexId)
-    invalidateHistogram(MainHist);
-  else if(texId == workDataTexId)
-    invalidateHistogram(WorkHist);
-}
-
-void ImgData::reloadMainTex(const BoundingBox3i& bbox)
-{
-  if(mainDataTexId) {
-    reloadTex(mainDataTexId);
-    if(bbox.empty() or bbox.size() == stack->size()) {
-      DEBUG_OUTPUT("Reload the whole main texture" << endl);
-      reloadTex(mainDataTexId);
+  
+  // Load data into texture, handle decimation if texture too big
+  void ImgData::load3DTexData(const GLuint texId, const Point3u size, const ushort* data)
+  {
+    if(swapTextureBytes(texId))
+      glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_TRUE);
+    // Find if any dimension need to be decimated
+    Point3u step = getTexStep();
+    if(step == Point3u(1u, 1u, 1u)) {
+      GLsizei width = size.x();
+  
+      if(width % 4 == 0)
+        glPixelStorei(GL_UNPACK_ALIGNMENT, 8);
+      else if(width % 2 != 0)
+        glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
+  
+      glTexImage3D(GL_TEXTURE_3D, 0, internalFormat(texId), size.x(), size.y(), size.z(), 0, GL_ALPHA,
+                   GL_UNSIGNED_SHORT, data);
     } else {
-      DEBUG_OUTPUT("Reload the main texture for box: " << bbox << endl);
-      updateTex(mainDataTexId, bbox);
+      Point3u sz = Point3u(size.x() / step.x(), size.y() / step.y(), size.z() / step.z());
+  
+      HVecUS tpix(size_t(sz.x()) * sz.y() * sz.z());
+      ushort* p = tpix.data();
+  
+      // Decimate array
+      for(uint z = step.z() / 2; z < sz.z() * step.z(); z += step.z())
+        for(uint y = step.y() / 2; y < sz.y() * step.y(); y += step.y())
+          for(uint x = step.x() / 2; x < sz.x() * step.x(); x += step.x())
+            *p++ = data[offset(x, y, z)];
+  
+      GLsizei width = sz.x();
+  
+      if(width % 4 == 0)
+        glPixelStorei(GL_UNPACK_ALIGNMENT, 8);
+      else if(width % 2 != 0)
+        glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
+  
+      // Load smaller texture
+      glTexImage3D(GL_TEXTURE_3D, 0, internalFormat(texId), sz.x(), sz.y(), sz.z(), 0, GL_ALPHA, GL_UNSIGNED_SHORT,
+                   tpix.data());
     }
-  } else {
-    if(stack->storeSize() == 0 or stack->main()->data().size() != stack->storeSize()) {
-      Information::out << "Error cannot reload main tex as SizeXYZ = " << stack->storeSize()
-                       << " and MainData.size() = " << stack->main()->data().size() << endl;
+    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);   // Restore default
+    if(swapTextureBytes(texId))
+      glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
+  
+    // Histograms require update
+    if(texId == mainDataTexId)
+      invalidateHistogram(MainHist);
+    else if(texId == workDataTexId)
+      invalidateHistogram(WorkHist);
+  
+    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, interpolation(mainDataTexId));
+    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, interpolation(mainDataTexId));
+    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
+    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
+    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);
+    float anisotropy;
+    glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &anisotropy);
+    glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropy);
+  }
+  
+  void ImgData::reloadTex(GLuint texId)
+  {
+    if(texId == 0 or stack->storeSize() == 0
+       or (texId == mainDataTexId and stack->main()->data().size() != stack->storeSize())
+       or (texId == workDataTexId and stack->work()->data().size() != stack->storeSize())) {
       unloadTex();
       return;
     }
-    SETSTATUS("Creating new texture of size " << stack->size());
-    glGenTextures(1, &mainDataTexId);
-    glBindTexture(GL_TEXTURE_3D, mainDataTexId);
+  
+    glBindTexture(GL_TEXTURE_3D, texId);
+    HVecUS& wdata = stack->work()->data();
     HVecUS& mdata = stack->main()->data();
-    load3DTexData(mainDataTexId, stack->size(), mdata.data());
+    const ushort* data = (texId == mainDataTexId) ? mdata.data() : wdata.data();
+    load3DTexData(texId, stack->size(), data);
   }
-}
-
-void ImgData::reloadWorkTex(const BoundingBox3i& bbox)
-{
-  if(workDataTexId) {
-    if(bbox.empty() or bbox.size() == stack->size()) {
-      DEBUG_OUTPUT("Reload the whole work texture" << endl);
-      reloadTex(workDataTexId);
+  
+  // Update a section of a texture defined in image coordinates by a bounding box
+  void ImgData::updateTex(GLuint texId, BoundingBox3i bBox)
+  {
+    if(texId == 0 or stack->storeSize() == 0 or stack->main()->data().size() != stack->storeSize()
+       or stack->work()->data().size() != stack->storeSize())
+      return;
+  
+    HVecUS& data = (texId == mainDataTexId ? stack->main()->data() : stack->work()->data());
+  
+    Point3i base(bBox[0].x(), bBox[0].y(), bBox[0].z());
+    Point3i bsz(bBox[1].x() - bBox[0].x(), bBox[1].y() - bBox[0].y(), bBox[1].z() - bBox[0].z());
+  
+    if(swapTextureBytes(texId))
+      glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_TRUE);
+    // Get factor to decimate texture if required
+    Point3u step = getTexStep();
+    // Enlarge bounding box to multiples of steps
+    if(step != Point3u(1u, 1u, 1u)) {
+      base.x() -= base.x() % step.x();
+      base.y() -= base.y() % step.y();
+      base.z() -= base.z() % step.z();
+      bsz.x() += base.x() % step.x();
+      bsz.y() += base.y() % step.y();
+      bsz.z() += base.z() % step.z();
+      if(bsz.x() % step.x() > 0)
+        bsz.x() = bsz.x() / step.x() + 1;
+      else
+        bsz.x() /= step.x();
+      if(bsz.y() % step.y() > 0)
+        bsz.y() = bsz.y() / step.y() + 1;
+      else
+        bsz.y() /= step.y();
+      if(bsz.z() % step.z() > 0)
+        bsz.z() = bsz.z() / step.z() + 1;
+      else
+        bsz.z() /= step.z();
+  
+      HVecUS tpix(size_t(bsz.x()) * bsz.y() * bsz.z());
+  
+      ushort* p = tpix.data();
+      for(uint z = base.z() + step.z() / 2; z < base.z() + bsz.z() * step.z(); z += step.z())
+        for(uint y = base.y() + step.y() / 2; y < base.y() + bsz.y() * step.y(); y += step.y())
+          for(uint x = base.x() + step.x() / 2; x < base.x() + bsz.x() * step.x(); x += step.x())
+            *p++ = data[offset(x, y, z)];
+  
+      glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
+  
+      // Load texture subimage
+      glBindTexture(GL_TEXTURE_3D, texId);
+      glTexSubImage3D(GL_TEXTURE_3D, 0, base.x() / step.x(), base.y() / step.y(), base.z() / step.z(), bsz.x(),
+                      bsz.y(), bsz.z(), GL_ALPHA, GL_UNSIGNED_SHORT, tpix.data());
+      glBindTexture(GL_TEXTURE_3D, 0);
+  
+      glPixelStorei(GL_UNPACK_ALIGNMENT, 4);     // Restore default
     } else {
-      DEBUG_OUTPUT("Reload the work texture for box: " << bbox << endl);
-      updateTex(workDataTexId, bbox);
+      // Update only the part needed
+      glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
+  
+      glBindTexture(GL_TEXTURE_3D, texId);
+      glPixelStorei(GL_UNPACK_ROW_LENGTH, stack->size().x());
+      glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, stack->size().y());
+      glTexSubImage3D(GL_TEXTURE_3D, 0, base.x(), base.y(), base.z(), bsz.x(), bsz.y(), bsz.z(), GL_ALPHA,
+                      GL_UNSIGNED_SHORT, &data[offset(base.x(), base.y(), base.z())]);
+      glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
+      glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0);
+      glBindTexture(GL_TEXTURE_3D, 0);
+  
+      glPixelStorei(GL_UNPACK_ALIGNMENT, 4);     // Restore default
     }
-  } else {
-    if(stack->storeSize() == 0 or stack->work()->data().size() != stack->storeSize()) {
-      Information::out << "Error cannot reload work tex as SizeXYZ = " << stack->storeSize()
-                       << " and WorkData.size() = " << stack->main()->data().size() << endl;
+    if(swapTextureBytes(texId))
+      glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE);
+  
+    // Histograms require update
+    if(texId == mainDataTexId)
+      invalidateHistogram(MainHist);
+    else if(texId == workDataTexId)
+      invalidateHistogram(WorkHist);
+  }
+  
+  void ImgData::reloadMainTex(const BoundingBox3i& bbox)
+  {
+    if(mainDataTexId) {
+      reloadTex(mainDataTexId);
+      if(bbox.empty() or bbox.size() == stack->size()) {
+        DEBUG_OUTPUT("Reload the whole main texture" << endl);
+        reloadTex(mainDataTexId);
+      } else {
+        DEBUG_OUTPUT("Reload the main texture for box: " << bbox << endl);
+        updateTex(mainDataTexId, bbox);
+      }
+    } else {
+      if(stack->storeSize() == 0 or stack->main()->data().size() != stack->storeSize()) {
+        Information::out << "Error cannot reload main tex as SizeXYZ = " << stack->storeSize()
+                         << " and MainData.size() = " << stack->main()->data().size() << endl;
+        unloadTex();
+        return;
+      }
+      SETSTATUS("Creating new texture of size " << stack->size());
+      glGenTextures(1, &mainDataTexId);
+      glBindTexture(GL_TEXTURE_3D, mainDataTexId);
+      HVecUS& mdata = stack->main()->data();
+      load3DTexData(mainDataTexId, stack->size(), mdata.data());
+    }
+  }
+  
+  void ImgData::reloadWorkTex(const BoundingBox3i& bbox)
+  {
+    if(workDataTexId) {
+      if(bbox.empty() or bbox.size() == stack->size()) {
+        DEBUG_OUTPUT("Reload the whole work texture" << endl);
+        reloadTex(workDataTexId);
+      } else {
+        DEBUG_OUTPUT("Reload the work texture for box: " << bbox << endl);
+        updateTex(workDataTexId, bbox);
+      }
+    } else {
+      if(stack->storeSize() == 0 or stack->work()->data().size() != stack->storeSize()) {
+        Information::out << "Error cannot reload work tex as SizeXYZ = " << stack->storeSize()
+                         << " and WorkData.size() = " << stack->main()->data().size() << endl;
+        unloadTex();
+        return;
+      }
+      glGenTextures(1, &workDataTexId);
+      glBindTexture(GL_TEXTURE_3D, workDataTexId);
+      HVecUS& wdata = stack->work()->data();
+      load3DTexData(workDataTexId, stack->size(), wdata.data());
+    }
+  }
+  
+  void ImgData::loadTex()
+  {
+    if(stack->storeSize() == 0 or stack->main()->data().size() != stack->storeSize()
+       or stack->work()->data().size() != stack->storeSize()) {
       unloadTex();
       return;
     }
-    glGenTextures(1, &workDataTexId);
+  
+    // Main stack
+    if(!mainDataTexId)
+      glGenTextures(1, &mainDataTexId);
+    glBindTexture(GL_TEXTURE_3D, mainDataTexId);
+    HVecUS& mdata = stack->main()->data();
+    load3DTexData(mainDataTexId, stack->size(), mdata.data());
+    // Work stack
+    if(!workDataTexId)
+      glGenTextures(1, &workDataTexId);
     glBindTexture(GL_TEXTURE_3D, workDataTexId);
     HVecUS& wdata = stack->work()->data();
     load3DTexData(workDataTexId, stack->size(), wdata.data());
   }
-}
-
-void ImgData::loadTex()
-{
-  if(stack->storeSize() == 0 or stack->main()->data().size() != stack->storeSize()
-     or stack->work()->data().size() != stack->storeSize()) {
-    unloadTex();
-    return;
+  
+  // Bind the stack texture
+  void ImgData::bind3DTex(GLuint texId, Shader::ActiveTextures atexId)
+  {
+    if(texId) {
+      glMatrixMode(GL_TEXTURE);
+      glLoadIdentity();
+      const Point3f& Size = multiply(stack->step(), Point3f(stack->size()));
+      glScaled(1 / Size.x(), 1 / Size.y(), 1 / Size.z());
+      Point3f Origin = stack->origin();
+      glTranslatef(-Origin.x(), -Origin.y(), -Origin.z());
+      Shader::activeTexture(atexId);
+      glBindTexture(GL_TEXTURE_3D, texId);
+      glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, interpolation(texId));
+      glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, interpolation(texId));
+      Shader::activeTexture(Shader::AT_NONE);
+      glBindTexture(GL_TEXTURE_3D, 0);
+      glMatrixMode(GL_MODELVIEW);
+    }
   }
-
-  // Main stack
-  if(!mainDataTexId)
-    glGenTextures(1, &mainDataTexId);
-  glBindTexture(GL_TEXTURE_3D, mainDataTexId);
-  HVecUS& mdata = stack->main()->data();
-  load3DTexData(mainDataTexId, stack->size(), mdata.data());
-  // Work stack
-  if(!workDataTexId)
-    glGenTextures(1, &workDataTexId);
-  glBindTexture(GL_TEXTURE_3D, workDataTexId);
-  HVecUS& wdata = stack->work()->data();
-  load3DTexData(workDataTexId, stack->size(), wdata.data());
-}
-
-// Bind the stack texture
-void ImgData::bind3DTex(GLuint texId, Shader::ActiveTextures atexId)
-{
-  if(texId) {
+  
+  // Bind the stack texture
+  void ImgData::bind2DTex(GLuint texId)
+  {
+    if(texId) {
+      glMatrixMode(GL_TEXTURE);
+      glLoadIdentity();
+      Shader::activeTexture(Shader::AT_TEX2D);
+      glBindTexture(GL_TEXTURE_2D, texId);
+      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, interpolation(texId));
+      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, interpolation(texId));
+      Shader::activeTexture(Shader::AT_NONE);
+      glBindTexture(GL_TEXTURE_2D, 0);
+      glMatrixMode(GL_MODELVIEW);
+    }
+  }
+  
+  void ImgData::unbind3DTex()
+  {
     glMatrixMode(GL_TEXTURE);
     glLoadIdentity();
-    const Point3f& Size = multiply(stack->step(), Point3f(stack->size()));
-    glScaled(1 / Size.x(), 1 / Size.y(), 1 / Size.z());
-    Point3f Origin = stack->origin();
-    glTranslatef(-Origin.x(), -Origin.y(), -Origin.z());
-    Shader::activeTexture(atexId);
-    glBindTexture(GL_TEXTURE_3D, texId);
-    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, interpolation(texId));
-    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, interpolation(texId));
+    Shader::activeTexture(Shader::AT_TEX3D);
+    glBindTexture(GL_TEXTURE_3D, 0);
+    Shader::activeTexture(Shader::AT_SECOND_TEX3D);
+    glBindTexture(GL_TEXTURE_3D, 0);
     Shader::activeTexture(Shader::AT_NONE);
-    glBindTexture(GL_TEXTURE_3D, 0);
     glMatrixMode(GL_MODELVIEW);
   }
-}
-
-// Bind the stack texture
-void ImgData::bind2DTex(GLuint texId)
-{
-  if(texId) {
+  
+  void ImgData::unbind2DTex()
+  {
     glMatrixMode(GL_TEXTURE);
     glLoadIdentity();
     Shader::activeTexture(Shader::AT_TEX2D);
-    glBindTexture(GL_TEXTURE_2D, texId);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, interpolation(texId));
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, interpolation(texId));
+    glBindTexture(GL_TEXTURE_2D, 0);
     Shader::activeTexture(Shader::AT_NONE);
-    glBindTexture(GL_TEXTURE_2D, 0);
     glMatrixMode(GL_MODELVIEW);
   }
-}
-
-void ImgData::unbind3DTex()
-{
-  glMatrixMode(GL_TEXTURE);
-  glLoadIdentity();
-  Shader::activeTexture(Shader::AT_TEX3D);
-  glBindTexture(GL_TEXTURE_3D, 0);
-  Shader::activeTexture(Shader::AT_SECOND_TEX3D);
-  glBindTexture(GL_TEXTURE_3D, 0);
-  Shader::activeTexture(Shader::AT_NONE);
-  glMatrixMode(GL_MODELVIEW);
-}
-
-void ImgData::unbind2DTex()
-{
-  glMatrixMode(GL_TEXTURE);
-  glLoadIdentity();
-  Shader::activeTexture(Shader::AT_TEX2D);
-  glBindTexture(GL_TEXTURE_2D, 0);
-  Shader::activeTexture(Shader::AT_NONE);
-  glMatrixMode(GL_MODELVIEW);
-}
-
-// Load a texture image (for Keyence)
-void ImgData::loadImgTex(const QImage& image)
-{
-  if(image.isNull() or image.width() <= 0 or image.height() <= 0)
-    return;
-
-  if(imgTexId)
-    glDeleteTextures(1, &imgTexId);
-  glGenTextures(1, &imgTexId);
-  glBindTexture(GL_TEXTURE_2D, imgTexId);
-
-  std::vector<float> pix(image.width() * image.height() * 3);
-  float* px = &pix[0];
-  for(int y = image.height() - 1; y >= 0; y--)
-    for(int x = 0; x < image.width(); x++) {
-      *px++ = float(qRed(image.pixel(x, y))) / 255.0;
-      *px++ = float(qGreen(image.pixel(x, y))) / 255.0;
-      *px++ = float(qBlue(image.pixel(x, y))) / 255.0;
+  
+  // Load a texture image (for Keyence)
+  void ImgData::loadImgTex(const QImage& image)
+  {
+    if(image.isNull() or image.width() <= 0 or image.height() <= 0)
+      return;
+  
+    if(imgTexId)
+      glDeleteTextures(1, &imgTexId);
+    glGenTextures(1, &imgTexId);
+    glBindTexture(GL_TEXTURE_2D, imgTexId);
+  
+    std::vector<float> pix(image.width() * image.height() * 3);
+    float* px = &pix[0];
+    for(int y = image.height() - 1; y >= 0; y--)
+      for(int x = 0; x < image.width(); x++) {
+        *px++ = float(qRed(image.pixel(x, y))) / 255.0;
+        *px++ = float(qGreen(image.pixel(x, y))) / 255.0;
+        *px++ = float(qBlue(image.pixel(x, y))) / 255.0;
+      }
+  
+    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width(), image.height(), 0, GL_RGB, GL_FLOAT, &pix[0]);
+  
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);
+  }
+  
+  void ImgData::initTex()
+  {
+    // Initialize 1D index texture
+    LabelColorsChanged = true;
+    reloadLabelTex();
+  }
+  
+  void ImgData::reloadLabelTex()
+  {
+    if(LabelColorsChanged) {
+      if(!labelTexId)
+        glGenTextures(1, &labelTexId);
+      glBindTexture(GL_TEXTURE_1D, labelTexId);
+  
+      if(!LabelColors.empty())
+        glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB, LabelColors.size(), 0, GL_RGBA, GL_FLOAT, &LabelColors[0]);
+      else
+        glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB, 0, 0, GL_RGB, GL_FLOAT, 0);
+      glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+      glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+      glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+      glBindTexture(GL_TEXTURE_1D, 0);
+      LabelColorsChanged = false;
     }
-
-  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width(), image.height(), 0, GL_RGB, GL_FLOAT, &pix[0]);
-
-  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
-  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
-  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);
-}
-
-void ImgData::initTex()
-{
-  // Initialize 1D index texture
-  LabelColorsChanged = true;
-  reloadLabelTex();
-}
-
-void ImgData::reloadLabelTex()
-{
-  if(LabelColorsChanged) {
-    if(!labelTexId)
-      glGenTextures(1, &labelTexId);
-    glBindTexture(GL_TEXTURE_1D, labelTexId);
-
-    if(!LabelColors.empty())
-      glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB, LabelColors.size(), 0, GL_RGBA, GL_FLOAT, &LabelColors[0]);
-    else
-      glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB, 0, 0, GL_RGB, GL_FLOAT, 0);
-    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
-    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
-    glBindTexture(GL_TEXTURE_1D, 0);
-    LabelColorsChanged = false;
   }
-}
-
-void ImgData::correctSelection(bool inclusive) {
-  mesh->correctSelection(inclusive);
-}
-
-// Select vertices with a specified label
-// Repeat used for "select on mesh" option on "Edit Labels" dialog
-void ImgData::selectLabel(int label, int repeat)
-{
-  vvgraph& S = mesh->graph();
-  if(!mesh->isSurfaceVisible() or S.empty())
-    return;
-
-  bool empty = true;
-  vvgraph M;
-  if(repeat > 0) {
+  
+  void ImgData::correctSelection(bool inclusive) {
+    mesh->correctSelection(inclusive);
+  }
+  
+  // Select vertices with a specified label
+  // Repeat used for "select on mesh" option on "Edit Labels" dialog
+  void ImgData::selectLabel(int label, int repeat)
+  {
+    vvgraph& S = mesh->graph();
+    if(!mesh->isSurfaceVisible() or S.empty())
+      return;
+  
+    bool empty = true;
+    vvgraph M;
+    if(repeat > 0) {
+      forall(const vertex& v, S)
+        if((v->label % repeat) == label and !v->selected) {
+          empty = false;
+          v->selected = true;
+        }
+    } else {
+      forall(const vertex& v, S)
+        if(v->label == label and !v->selected) {
+          empty = false;
+          v->selected = true;
+        }
+    }
+    if(empty)
+      return;
+    updateSelection();
+  }
+  
+  // Unselect vertices with a specified label
+  void ImgData::unselectLabel(int label)
+  {
+    vvgraph& S = mesh->graph();
+    if(!mesh->isSurfaceVisible() or S.empty())
+      return;
+  
+    bool empty = true;
+    vvgraph M;
     forall(const vertex& v, S)
-      if((v->label % repeat) == label and !v->selected) {
+      if(v->label == label and v->selected) {
         empty = false;
-        v->selected = true;
+        v->selected = false;
       }
-  } else {
-    forall(const vertex& v, S)
-      if(v->label == label and !v->selected) {
-        empty = false;
-        v->selected = true;
-      }
+    if(empty)
+      return;
+    updateSelection();
   }
-  if(empty)
-    return;
-  updateSelection();
-}
-
-// Unselect vertices with a specified label
-void ImgData::unselectLabel(int label)
-{
-  vvgraph& S = mesh->graph();
-  if(!mesh->isSurfaceVisible() or S.empty())
-    return;
-
-  bool empty = true;
-  vvgraph M;
-  forall(const vertex& v, S)
-    if(v->label == label and v->selected) {
-      empty = false;
-      v->selected = false;
-    }
-  if(empty)
-    return;
-  updateSelection();
-}
-
-// Select vertices with a specified parent
-void ImgData::selectParent(int parent, int repeat)
-{
-  vvgraph& S = mesh->graph();
-  if(!mesh->isSurfaceVisible() or S.empty())
-    return;
-
-  bool empty = true;
-  if(repeat > 0) {
-    IntIntMap& parentMap = mesh->parentLabelMap();
-    forall(const vertex& v, S) {
-      IntIntMap::iterator it = parentMap.find(v->label);
-      if(it != parentMap.end() and it->second % repeat == parent and !v->selected) {
-        empty = false;
-        v->selected = true;
+  
+  // Select vertices with a specified parent
+  void ImgData::selectParent(int parent, int repeat)
+  {
+    vvgraph& S = mesh->graph();
+    if(!mesh->isSurfaceVisible() or S.empty())
+      return;
+  
+    bool empty = true;
+    if(repeat > 0) {
+      IntIntMap& parentMap = mesh->parentLabelMap();
+      forall(const vertex& v, S) {
+        IntIntMap::iterator it = parentMap.find(v->label);
+        if(it != parentMap.end() and it->second % repeat == parent and !v->selected) {
+          empty = false;
+          v->selected = true;
+        }
       }
+    } else {
+      IntIntMap& parentMap = mesh->parentLabelMap();
+      forall(const vertex& v, S) {
+        IntIntMap::iterator it = parentMap.find(v->label);
+        if(it != parentMap.end() and it->second == parent and !v->selected) {
+          empty = false;
+          v->selected = true;
+        }
+      }
     }
-  } else {
+    if(empty)
+      return;
+    updateSelection();
+  }
+  
+  // Unselect vertices with a specified parent
+  void ImgData::unselectParent(int parent)
+  {
+    vvgraph& S = mesh->graph();
+    if(!mesh->isSurfaceVisible() or S.empty())
+      return;
+  
+    bool empty = true;
     IntIntMap& parentMap = mesh->parentLabelMap();
     forall(const vertex& v, S) {
       IntIntMap::iterator it = parentMap.find(v->label);
-      if(it != parentMap.end() and it->second == parent and !v->selected) {
+      if(it != parentMap.end() and it->second == parent and v->selected) {
         empty = false;
-        v->selected = true;
+        v->selected = false;
       }
     }
+    if(empty)
+      return;
+    updateSelection();
   }
-  if(empty)
-    return;
-  updateSelection();
-}
-
-// Unselect vertices with a specified parent
-void ImgData::unselectParent(int parent)
-{
-  vvgraph& S = mesh->graph();
-  if(!mesh->isSurfaceVisible() or S.empty())
-    return;
-
-  bool empty = true;
-  IntIntMap& parentMap = mesh->parentLabelMap();
-  forall(const vertex& v, S) {
-    IntIntMap::iterator it = parentMap.find(v->label);
-    if(it != parentMap.end() and it->second == parent and v->selected) {
-      empty = false;
-      v->selected = false;
-    }
-  }
-  if(empty)
-    return;
-  updateSelection();
-}
-
-// Select connected vertices
-void ImgData::selectConnected(std::vector<uint>& vList, bool unselect)
-{
-  vvgraph& S = mesh->graph();
-  if(!mesh->isSurfaceVisible() or S.empty() or vList.empty())
-    return;
-
-  vvgraph V;
-  forall(uint u, vList) {
-    vertex v = idVA[u];
-    V.insert(v);
-  }
-  mesh->getConnectedVertices(S, V);
-  forall(const vertex& v, V)
-    v->selected = !unselect;
-  updateSelection();
-}
-
-void ImgData::fillLabel(int label, int currlabel)
-{
-  // Make some checks
-  if(label <= 0 or label == currlabel)
-    return;
-  if(!mesh->isSurfaceVisible() or mesh->toShow() != Mesh::LABEL)
-    return;
-  vvgraph& S = mesh->graph();
-  if(S.empty())
-    return;
-  mesh->setLabel(std::max(currlabel, mesh->viewLabel()));
-
-  // If workstack has labels on and if do 3D label fill as well
-  bool do3DFill = isWorkVisible() and stack->work()->labels();
-  BoundingBox3f bBox(Point3f(FLT_MAX, FLT_MAX, FLT_MAX), Point3f(-FLT_MAX, -FLT_MAX, -FLT_MAX));
-
-  // Find all vertices with current label and set to new label
-  std::set<vertex> M;
-  forall(const vertex& v, S)
-    if(v->label == label) {
-      v->label = currlabel;
-      M.insert(v);
-    }
-  // If none do nothing.
-  if(M.empty())
-    return;
-
-  // Expand set to include neighbors, find bound box for 3D if reqd
-  std::set<vertex> T = M;
-  forall(const vertex& v, T) {
-    if(do3DFill)
-      bBox |= v->pos;
-    forall(const vertex& n, S.neighbors(v))
-      M.insert(n);
-  }
-
-  // Clear cell axis, cell center for new label
-  mesh->labelCenter().erase(label);
-  mesh->labelNormal().erase(label);
-  mesh->labelCenterVis().erase(label);
-  mesh->labelNormalVis().erase(label);
-  mesh->cellAxis().erase(label);
-  mesh->cellAxisScaled().erase(label);
-  // Clear cell axis, cell center for current label
-  mesh->labelCenter().erase(currlabel);
-  mesh->labelNormal().erase(currlabel);
-  mesh->labelCenterVis().erase(currlabel);
-  mesh->labelNormalVis().erase(currlabel);
-  mesh->cellAxis().erase(currlabel);
-  mesh->cellAxisScaled().erase(currlabel);
-  // Clear parent label
-  IntIntMap::iterator p = mesh->parentLabelMap().find(label);
-  if(p != mesh->parentLabelMap().end()) {
-    int lparent = p->second;
-    mesh->parentCenter().erase(lparent);
-    mesh->parentNormal().erase(lparent);
-    mesh->parentCenterVis().erase(lparent);
-    mesh->parentNormalVis().erase(lparent);
-    mesh->parentLabelMap().erase(label);
-  }
-  // Clear parent label
-  IntIntMap::iterator cp = mesh->parentLabelMap().find(currlabel);
-  if(cp != mesh->parentLabelMap().end()) {
-    int currparent = cp->second;
-    mesh->parentCenter().erase(currparent);
-    mesh->parentNormal().erase(currparent);
-    mesh->parentCenterVis().erase(currparent);
-    mesh->parentNormalVis().erase(currparent);
-    mesh->parentLabelMap().erase(currlabel);
-  }
-
-  // Update margin
-  markMargin(M, true);
-  postUpdateImgData(true, true);
-
-  // Labels are stored byte swapped in the texture to allow the use of 8 bit textures.
-  uint stklabel = ((uint(label) & 0xFF) << 8) + (uint(label) >> 8);
-  uint stkcurrlabel = ((uint(currlabel) & 0xFF) << 8) + (uint(currlabel) >> 8);
-
-  // Do 3D label fill if required
-  if(do3DFill and label >= 0 and currlabel >= 0 and label < 65536 and currlabel < 65536) {
-    // Convert bounding box to tex coords.
-    BoundingBox3i bBoxTex(worldToImagei(bBox[0]) - Point3i(1, 1, 1), worldToImagei(bBox[1]) + Point3i(1, 1, 1));
-    bBoxTex &= BoundingBox3i(Point3i(0, 0, 0), stack->size());
-
-    // Update label in work tex
-    HVecUS& wdata = stack->work()->data();
-    for(int i = bBoxTex[0].x(); i < bBoxTex[1].x(); i++)
-      for(int j = bBoxTex[0].y(); j < bBoxTex[1].y(); j++)
-        for(int k = bBoxTex[0].z(); k < bBoxTex[1].z(); k++) {
-          if(wdata[offset(i, j, k)] == stklabel)
-            wdata[offset(i, j, k)] = stkcurrlabel;
-        }
-    updateTex(workDataTexId, bBoxTex);
-  }
-}
-
-void ImgData::setParent(int label, int parentLabel)
-{
-  bool changed = false;
-
-  if(parentLabel == 0) {
-    mesh->parentLabelMap().erase(label);
-    changed = true;
-  } else if(mesh->parentLabelMap()[label] != parentLabel) {
-    mesh->parentLabelMap()[label] = parentLabel;
-    changed = true;
-  }
-
-  // See if we added something, and update GUI if required
-  if(changed)
-    postUpdateImgData(false, true);
-}
-
-void ImgData::addSeed(int label, std::vector<uint>& vList)
-{
-  if(!mesh->isSurfaceVisible() or mesh->toShow() != Mesh::LABEL or vList.empty())
-    return;
-
-  mesh->setLabel(std::max(label, mesh->viewLabel()));
-
-  // Only lablel unlabeled vertices
-  if(mesh->cells()) {
-    std::set<uint> vset;
+  
+  // Select connected vertices
+  void ImgData::selectConnected(std::vector<uint>& vList, bool unselect)
+  {
+    vvgraph& S = mesh->graph();
+    if(!mesh->isSurfaceVisible() or S.empty() or vList.empty())
+      return;
+  
+    vvgraph V;
     forall(uint u, vList) {
       vertex v = idVA[u];
-      if(v->type == 'c') {
-        vset.insert(u);
-
-        // Find all triangles that contain the center vertex
-        for(uint i = 0; i < selVA.size(); i += 3)
-          for(uint j = 0; j < 3; j++)
-            if(idVA[i + j] == idVA[u])
-              for(uint k = 0; k < 3; k++)
-                vset.insert(i + k);
-      }
+      V.insert(v);
     }
-    std::vector<uint> tlist;
-    forall(uint u, vset)
-      tlist.push_back(u);
-    updLabel(label, tlist);
-  } else
-    updLabel(label, vList);
-}
-
-// Fill selection with current
-void ImgData::fillSelect(int label)
-{
-  vvgraph& S = mesh->graph();
-  if(S.empty() or !mesh->isSurfaceVisible())
-    return;
-
-  if(mesh->toShow() == Mesh::LABEL) {
+    mesh->getConnectedVertices(S, V);
+    forall(const vertex& v, V)
+      v->selected = !unselect;
+    updateSelection();
+  }
+  
+  void ImgData::fillLabel(int label, int currlabel)
+  {
+    // Make some checks
+    if(label <= 0 or label == currlabel)
+      return;
+    if(!mesh->isSurfaceVisible() or mesh->toShow() != Mesh::LABEL)
+      return;
+    vvgraph& S = mesh->graph();
+    if(S.empty())
+      return;
+    mesh->setLabel(std::max(currlabel, mesh->viewLabel()));
+  
+    // If workstack has labels on and if do 3D label fill as well
+    bool do3DFill = isWorkVisible() and stack->work()->labels();
+    BoundingBox3f bBox(Point3f(FLT_MAX, FLT_MAX, FLT_MAX), Point3f(-FLT_MAX, -FLT_MAX, -FLT_MAX));
+  
+    // Find all vertices with current label and set to new label
     std::set<vertex> M;
-    forall(uint u, selectV) {
-      vertex v = pidVA[u];
-      if(v->label != label) {
-        v->label = label;
+    forall(const vertex& v, S)
+      if(v->label == label) {
+        v->label = currlabel;
         M.insert(v);
       }
+    // If none do nothing.
+    if(M.empty())
+      return;
+  
+    // Expand set to include neighbors, find bound box for 3D if reqd
+    std::set<vertex> T = M;
+    forall(const vertex& v, T) {
+      if(do3DFill)
+        bBox |= v->pos;
+      forall(const vertex& n, S.neighbors(v))
+        M.insert(n);
     }
+  
+    // Clear cell axis, cell center for new label
+    mesh->labelCenter().erase(label);
+    mesh->labelNormal().erase(label);
+    mesh->labelCenterVis().erase(label);
+    mesh->labelNormalVis().erase(label);
+    mesh->cellAxis().erase(label);
+    mesh->cellAxisScaled().erase(label);
+    // Clear cell axis, cell center for current label
+    mesh->labelCenter().erase(currlabel);
+    mesh->labelNormal().erase(currlabel);
+    mesh->labelCenterVis().erase(currlabel);
+    mesh->labelNormalVis().erase(currlabel);
+    mesh->cellAxis().erase(currlabel);
+    mesh->cellAxisScaled().erase(currlabel);
+    // Clear parent label
+    IntIntMap::iterator p = mesh->parentLabelMap().find(label);
+    if(p != mesh->parentLabelMap().end()) {
+      int lparent = p->second;
+      mesh->parentCenter().erase(lparent);
+      mesh->parentNormal().erase(lparent);
+      mesh->parentCenterVis().erase(lparent);
+      mesh->parentNormalVis().erase(lparent);
+      mesh->parentLabelMap().erase(label);
+    }
+    // Clear parent label
+    IntIntMap::iterator cp = mesh->parentLabelMap().find(currlabel);
+    if(cp != mesh->parentLabelMap().end()) {
+      int currparent = cp->second;
+      mesh->parentCenter().erase(currparent);
+      mesh->parentNormal().erase(currparent);
+      mesh->parentCenterVis().erase(currparent);
+      mesh->parentNormalVis().erase(currparent);
+      mesh->parentLabelMap().erase(currlabel);
+    }
+  
+    // Update margin
     markMargin(M, true);
-    updateLines();
-  } else if(mesh->toShow() == Mesh::PARENT) {
-    forall(uint u, selectV) {
-      vertex v = pidVA[u];
-      mesh->parentLabelMap()[v->label] = label;
+    postUpdateImgData(true, true);
+  
+    // Labels are stored byte swapped in the texture to allow the use of 8 bit textures.
+    uint stklabel = ((uint(label) & 0xFF) << 8) + (uint(label) >> 8);
+    uint stkcurrlabel = ((uint(currlabel) & 0xFF) << 8) + (uint(currlabel) >> 8);
+  
+    // Do 3D label fill if required
+    if(do3DFill and label >= 0 and currlabel >= 0 and label < 65536 and currlabel < 65536) {
+      // Convert bounding box to tex coords.
+      BoundingBox3i bBoxTex(worldToImagei(bBox[0]) - Point3i(1, 1, 1), worldToImagei(bBox[1]) + Point3i(1, 1, 1));
+      bBoxTex &= BoundingBox3i(Point3i(0, 0, 0), stack->size());
+  
+      // Update label in work tex
+      HVecUS& wdata = stack->work()->data();
+      for(int i = bBoxTex[0].x(); i < bBoxTex[1].x(); i++)
+        for(int j = bBoxTex[0].y(); j < bBoxTex[1].y(); j++)
+          for(int k = bBoxTex[0].z(); k < bBoxTex[1].z(); k++) {
+            if(wdata[offset(i, j, k)] == stklabel)
+              wdata[offset(i, j, k)] = stkcurrlabel;
+          }
+      updateTex(workDataTexId, bBoxTex);
     }
-  } else
-    return;
-
-  postUpdateImgData(false, true);
-}
-
-// Delete Label
-void ImgData::deleteLabel(int label)
-{
-  vvgraph& S = mesh->graph();
-  if(S.empty())
-    return;
-
-  std::vector<vertex> T;
-
-  if(MeshSelect) {
-    if(mesh->showMeshPoints()) {
+  }
+  
+  void ImgData::setParent(int label, int parentLabel)
+  {
+    bool changed = false;
+  
+    if(parentLabel == 0) {
+      mesh->parentLabelMap().erase(label);
+      changed = true;
+    } else if(mesh->parentLabelMap()[label] != parentLabel) {
+      mesh->parentLabelMap()[label] = parentLabel;
+      changed = true;
+    }
+  
+    // See if we added something, and update GUI if required
+    if(changed)
+      postUpdateImgData(false, true);
+  }
+  
+  void ImgData::addSeed(int label, std::vector<uint>& vList)
+  {
+    if(!mesh->isSurfaceVisible() or mesh->toShow() != Mesh::LABEL or vList.empty())
+      return;
+  
+    mesh->setLabel(std::max(label, mesh->viewLabel()));
+  
+    // Only lablel unlabeled vertices
+    if(mesh->cells()) {
+      std::set<uint> vset;
+      forall(uint u, vList) {
+        vertex v = idVA[u];
+        if(v->type == 'c') {
+          vset.insert(u);
+  
+          // Find all triangles that contain the center vertex
+          for(uint i = 0; i < selVA.size(); i += 3)
+            for(uint j = 0; j < 3; j++)
+              if(idVA[i + j] == idVA[u])
+                for(uint k = 0; k < 3; k++)
+                  vset.insert(i + k);
+        }
+      }
+      std::vector<uint> tlist;
+      forall(uint u, vset)
+        tlist.push_back(u);
+      updLabel(label, tlist);
+    } else
+      updLabel(label, vList);
+  }
+  
+  // Fill selection with current
+  void ImgData::fillSelect(int label)
+  {
+    vvgraph& S = mesh->graph();
+    if(S.empty() or !mesh->isSurfaceVisible())
+      return;
+  
+    if(mesh->toShow() == Mesh::LABEL) {
+      std::set<vertex> M;
       forall(uint u, selectV) {
         vertex v = pidVA[u];
-        T.push_back(v);
+        if(v->label != label) {
+          v->label = label;
+          M.insert(v);
+        }
       }
-      selectV.clear();
-    }
-  } else if(mesh->isSurfaceVisible() and mesh->toShow() == Mesh::LABEL) {
-    // Clear any interior border lines
-    //    markMargin(true);
-    // Label delete, remove all vertices with this label
-    // or all border vertices connected only to other border vertices or this label
-    forall(const vertex& v, S) {
-      if(v->label == label)
-        T.push_back(v);
-      else if(v->label == -1) {
-        bool remove = true;
-        forall(const vertex& n, S.neighbors(v)) {
-          if(n->label != label and n->label != -1) {
-            remove = false;
-            break;
+      markMargin(M, true);
+      updateLines();
+    } else if(mesh->toShow() == Mesh::PARENT) {
+      forall(uint u, selectV) {
+        vertex v = pidVA[u];
+        mesh->parentLabelMap()[v->label] = label;
+      }
+    } else
+      return;
+  
+    postUpdateImgData(false, true);
+  }
+  
+  // Delete Label
+  void ImgData::deleteLabel(int label)
+  {
+    vvgraph& S = mesh->graph();
+    if(S.empty())
+      return;
+  
+    std::vector<vertex> T;
+  
+    if(MeshSelect) {
+      if(mesh->showMeshPoints()) {
+        forall(uint u, selectV) {
+          vertex v = pidVA[u];
+          T.push_back(v);
+        }
+        selectV.clear();
+      }
+    } else if(mesh->isSurfaceVisible() and mesh->toShow() == Mesh::LABEL) {
+      // Clear any interior border lines
+      //    markMargin(true);
+      // Label delete, remove all vertices with this label
+      // or all border vertices connected only to other border vertices or this label
+      forall(const vertex& v, S) {
+        if(v->label == label)
+          T.push_back(v);
+        else if(v->label == -1) {
+          bool remove = true;
+          forall(const vertex& n, S.neighbors(v)) {
+            if(n->label != label and n->label != -1) {
+              remove = false;
+              break;
+            }
           }
+          if(remove)
+            T.push_back(v);
         }
-        if(remove)
-          T.push_back(v);
       }
-    }
-  } else
-    return;
-
-  // Now delete them
-  forall(const vertex& v, T)
-    S.erase(v);
-
-  // Delete any singletons
-  T.clear();
-  forall(const vertex& v, S)
-    if(S.valence(v) <= 1)
-      T.push_back(v);
-  forall(const vertex& v, T)
-    S.erase(v);
-
-  fillVBOs();
-  if(MeshSelect and mesh->showMeshPoints())
-    SETSTATUS(Section << " deleted selected vertices");
-  else
-    SETSTATUS(Section << " deleted label:" << label);
-}
-
-// Mark margin vertices and border labels, set normals, count triangles and fill Point Id for VBOs
-void ImgData::marginNormalsVBOs()
-{
-  vvgraph& S = mesh->graph();
-  if(S.empty())
-    return;
-
-  size_t nb_bad_normal = 0;
-  VCount = LCount = TCount = 0;
-  int nextLabel = mesh->viewLabel();
-
-  // Mark margin and borders
-  uint vcnt = 0;
-  pidVA.resize(S.size());
-  forall(const vertex& v, S) {
-    VCount++;
-    // Save vertex id
-    pidVA[vcnt] = v;
-    v->saveId = vcnt++;
-
-    // Clear normal
-    v->nrml = Point3f(0, 0, 0);
-
-    v->margin = false;
-    // All vertices with valence <= 2 are border and margin
-    if(S.valence(v) <= 2) {
-      v->margin = true;
-      if(v->type != 'l')
-        v->label = -1;
-    }
-
-    int label = 0, labcount = 0, zcount = 0;
-    forall(const vertex& n, S.neighbors(v)) {
-      if(uniqueLine(S, v, n))
-        LCount++;
-
-      vertex m = S.nextTo(v, n);
-      // add to normal
-      if(n != m and S.edge(n, m)) {
-        Point3f vn = n->pos - v->pos;
-        Point3f vm = m->pos - v->pos;
-        if(S.nextTo(n, m) != v)
-          v->nrml -= vn.cross(vm);
-        else
-          v->nrml += vn.cross(vm);
-      }
-      if(uniqueTri(S, v, n, m))
-        TCount++;
-
-      // If there is no edge between a pair of vertices next to each other
-      // in a neighborhood, they must be on the margin
-      if(!S.edge(n, m)) {
+    } else
+      return;
+  
+    // Now delete them
+    forall(const vertex& v, T)
+      S.erase(v);
+  
+    // Delete any singletons
+    T.clear();
+    forall(const vertex& v, S)
+      if(S.valence(v) <= 1)
+        T.push_back(v);
+    forall(const vertex& v, T)
+      S.erase(v);
+  
+    fillVBOs();
+    if(MeshSelect and mesh->showMeshPoints())
+      SETSTATUS(Section << " deleted selected vertices");
+    else
+      SETSTATUS(Section << " deleted label:" << label);
+  }
+  
+  // Mark margin vertices and border labels, set normals, count triangles and fill Point Id for VBOs
+  void ImgData::marginNormalsVBOs()
+  {
+    vvgraph& S = mesh->graph();
+    if(S.empty())
+      return;
+  
+    size_t nb_bad_normal = 0;
+    VCount = LCount = TCount = 0;
+    int nextLabel = mesh->viewLabel();
+  
+    // Mark margin and borders
+    uint vcnt = 0;
+    pidVA.resize(S.size());
+    forall(const vertex& v, S) {
+      VCount++;
+      // Save vertex id
+      pidVA[vcnt] = v;
+      v->saveId = vcnt++;
+  
+      // Clear normal
+      v->nrml = Point3f(0, 0, 0);
+  
+      v->margin = false;
+      // All vertices with valence <= 2 are border and margin
+      if(S.valence(v) <= 2) {
         v->margin = true;
         if(v->type != 'l')
           v->label = -1;
+      }
+  
+      int label = 0, labcount = 0, zcount = 0;
+      forall(const vertex& n, S.neighbors(v)) {
+        if(uniqueLine(S, v, n))
+          LCount++;
+  
+        vertex m = S.nextTo(v, n);
+        // add to normal
+        if(n != m and S.edge(n, m)) {
+          Point3f vn = n->pos - v->pos;
+          Point3f vm = m->pos - v->pos;
+          if(S.nextTo(n, m) != v)
+            v->nrml -= vn.cross(vm);
+          else
+            v->nrml += vn.cross(vm);
+        }
+        if(uniqueTri(S, v, n, m))
+          TCount++;
+  
+        // If there is no edge between a pair of vertices next to each other
+        // in a neighborhood, they must be on the margin
+        if(!S.edge(n, m)) {
+          v->margin = true;
+          if(v->type != 'l')
+            v->label = -1;
+          continue;
+        }
+        if(n->label == 0)
+          zcount++;
+        else if(n->label > 0 and n->label != label) {
+          labcount++;
+          label = n->label;
+        }
+      }
+      // Check for 0 normals
+      if(v->nrml.norm() == 0) {
+        ++nb_bad_normal;
+        v->nrml = Point3f(0, 0, 0);
+      } else
+        v->nrml.normalize();
+  
+      // Check for nan
+      if(fabs(1.0 - v->nrml.norm()) < 1e-4)
+        ;
+      else {
+        ++nb_bad_normal;
+        v->nrml = Point3f(0, 0, 0);
+      }
+  
+      // Margin vertices always have border label
+      if(v->margin)
         continue;
+      // Adjacent to more than one label means a cell boundary
+      if(labcount > 1 and v->type != 'l')
+        v->label = -1;
+      // Clear hanging border lines,
+      if(v->label == -1) {
+        // On zero labeled area clear
+        if(labcount == 0)
+          v->label = 0;
+        else if(labcount == 1 and zcount == 0)
+          v->label = label;
       }
-      if(n->label == 0)
-        zcount++;
-      else if(n->label > 0 and n->label != label) {
-        labcount++;
-        label = n->label;
+      if(v->label > nextLabel)
+        nextLabel = v->label;
+    }
+    if(nextLabel > mesh->viewLabel())
+      mesh->setLabel(nextLabel);
+    if(nb_bad_normal > 0)
+      SETSTATUS("markMargin:Error Bad normal for " << nb_bad_normal << " vertices");
+  }
+  
+  void ImgData::updateTris(vvgraph& T)
+  {
+    if(T.empty())
+      return;
+  
+    int nextLabel = mesh->viewLabel();
+    std::vector<uint> vList;
+    forall(const vertex& v, T) {
+      uint idx = vMap[v];
+      while(idx < idVA.size() and v == idVA[idx]) {
+        vertex n(idVA[idx + 1]), m(idVA[idx + 2]);
+        int label = getLabel(v, n, m);
+        texVA[idx] = texCoord(label, v, v, n, m);
+        vList.push_back(idx++);
+        texVA[idx] = texCoord(label, n, v, n, m);
+        vList.push_back(idx++);
+        texVA[idx] = texCoord(label, m, v, n, m);
+        vList.push_back(idx++);
       }
+      if(v->label > nextLabel)
+        nextLabel = v->label;
     }
-    // Check for 0 normals
-    if(v->nrml.norm() == 0) {
-      ++nb_bad_normal;
-      v->nrml = Point3f(0, 0, 0);
-    } else
-      v->nrml.normalize();
-
-    // Check for nan
-    if(fabs(1.0 - v->nrml.norm()) < 1e-4)
-      ;
-    else {
-      ++nb_bad_normal;
-      v->nrml = Point3f(0, 0, 0);
+    if(nextLabel > mesh->viewLabel())
+      mesh->setLabel(nextLabel);
+  
+    // Write texture data to video memory
+    glBindBufferARB(GL_ARRAY_BUFFER_ARB, texVAid);
+    Point3f* tp = (Point3f*)(glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB));
+    if(!tp) {
+      REPORT_GL_ERROR("glMapBufferARB(texVAid) - using glBufferDataARB");
+      glBufferDataARB(GL_ARRAY_BUFFER_ARB, texVA.size() * sizeof(Point3f), &texVA[0], GL_STATIC_DRAW_ARB);
+    } else {
+      forall(uint u, vList)
+        tp[u] = texVA[u];
+      glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
     }
-
-    // Margin vertices always have border label
-    if(v->margin)
-      continue;
-    // Adjacent to more than one label means a cell boundary
-    if(labcount > 1 and v->type != 'l')
-      v->label = -1;
-    // Clear hanging border lines,
-    if(v->label == -1) {
-      // On zero labeled area clear
-      if(labcount == 0)
-        v->label = 0;
-      else if(labcount == 1 and zcount == 0)
-        v->label = label;
-    }
-    if(v->label > nextLabel)
-      nextLabel = v->label;
+  
+    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
   }
-  if(nextLabel > mesh->viewLabel())
-    mesh->setLabel(nextLabel);
-  if(nb_bad_normal > 0)
-    SETSTATUS("markMargin:Error Bad normal for " << nb_bad_normal << " vertices");
-}
-
-void ImgData::updateTris(vvgraph& T)
-{
-  if(T.empty())
-    return;
-
-  int nextLabel = mesh->viewLabel();
-  std::vector<uint> vList;
-  forall(const vertex& v, T) {
-    uint idx = vMap[v];
-    while(idx < idVA.size() and v == idVA[idx]) {
-      vertex n(idVA[idx + 1]), m(idVA[idx + 2]);
+  
+  void ImgData::updateTris()
+  {
+    needUpdateTris = false;
+    if(idVA.empty())
+      return;
+  
+    int nextLabel = mesh->viewLabel();
+    uint tcnt = 0;
+    for(size_t i = 0; i < idVA.size(); i += 3) {
+      if(tcnt >= texVA.size())
+        throw(QString("updateTris:Error Triangle index too large"));
+  
+      vertex v(idVA[i]), n(idVA[i + 1]), m(idVA[i + 2]);
       int label = getLabel(v, n, m);
-      texVA[idx] = texCoord(label, v, v, n, m);
-      vList.push_back(idx++);
-      texVA[idx] = texCoord(label, n, v, n, m);
-      vList.push_back(idx++);
-      texVA[idx] = texCoord(label, m, v, n, m);
-      vList.push_back(idx++);
+      texVA[tcnt++] = texCoord(label, v, v, n, m);
+      texVA[tcnt++] = texCoord(label, n, v, n, m);
+      texVA[tcnt++] = texCoord(label, m, v, n, m);
+      if(label > nextLabel)
+        nextLabel = label;
     }
-    if(v->label > nextLabel)
-      nextLabel = v->label;
-  }
-  if(nextLabel > mesh->viewLabel())
-    mesh->setLabel(nextLabel);
-
-  // Write texture data to video memory
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, texVAid);
-  Point3f* tp = (Point3f*)(glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB));
-  if(!tp) {
-    REPORT_GL_ERROR("glMapBufferARB(texVAid) - using glBufferDataARB");
+    if(nextLabel > mesh->viewLabel())
+      mesh->setLabel(nextLabel);
+  
+    glBindBufferARB(GL_ARRAY_BUFFER_ARB, texVAid);
     glBufferDataARB(GL_ARRAY_BUFFER_ARB, texVA.size() * sizeof(Point3f), &texVA[0], GL_STATIC_DRAW_ARB);
-  } else {
-    forall(uint u, vList)
-      tp[u] = texVA[u];
-    glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
+    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
   }
-
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
-}
-
-void ImgData::updateTris()
-{
-  needUpdateTris = false;
-  if(idVA.empty())
-    return;
-
-  int nextLabel = mesh->viewLabel();
-  uint tcnt = 0;
-  for(size_t i = 0; i < idVA.size(); i += 3) {
-    if(tcnt >= texVA.size())
-      throw(QString("updateTris:Error Triangle index too large"));
-
-    vertex v(idVA[i]), n(idVA[i + 1]), m(idVA[i + 2]);
-    int label = getLabel(v, n, m);
-    texVA[tcnt++] = texCoord(label, v, v, n, m);
-    texVA[tcnt++] = texCoord(label, n, v, n, m);
-    texVA[tcnt++] = texCoord(label, m, v, n, m);
-    if(label > nextLabel)
-      nextLabel = label;
-  }
-  if(nextLabel > mesh->viewLabel())
-    mesh->setLabel(nextLabel);
-
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, texVAid);
-  glBufferDataARB(GL_ARRAY_BUFFER_ARB, texVA.size() * sizeof(Point3f), &texVA[0], GL_STATIC_DRAW_ARB);
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
-}
-
-void ImgData::updatePos()
-{
-  if(idVA.empty() or pidVA.empty())
-    return;
-
-  int nextLabel = mesh->viewLabel();
-
-  // Update positions for line and point drawing
-  BoundingBox3f bBox(Point3f(FLT_MAX, FLT_MAX, FLT_MAX), Point3f(-FLT_MAX, -FLT_MAX, -FLT_MAX));
-  for(size_t i = 0; i < pidVA.size(); i++) {
-    vertex v(pidVA[i]);
-    bBox |= v->pos;
-    pntsVA[i] = v->pos;
-    if(v->label > nextLabel)
-      nextLabel = v->label;
-  }
-  mesh->setBoundingBox(bBox);
-
-  // Update positions for triangles
-  uint tcnt = 0;
-  float step = std::max(stack->step().x(), std::max(stack->step().y(), stack->step().z()));
-  for(size_t i = 0; i < idVA.size(); i += 3) {
-    if(tcnt >= texVA.size())
-      throw(QString("updateTex:Error Triangle index too large"));
-
-    vertex v(idVA[i]), n(idVA[i + 1]), m(idVA[i + 2]);
-    int label = getLabel(v, n, m);
-
-    posVA[tcnt] = v->pos - ZOffset * step * v->nrml;
-    nrmlVA[tcnt] = v->nrml;
-    texVA[tcnt++] = texCoord(label, v, v, n, m);
-
-    posVA[tcnt] = n->pos - ZOffset * step * n->nrml;
-    nrmlVA[tcnt] = n->nrml;
-    texVA[tcnt++] = texCoord(label, n, v, n, m);
-
-    posVA[tcnt] = m->pos - ZOffset * step * m->nrml;
-    nrmlVA[tcnt] = m->nrml;
-    texVA[tcnt++] = texCoord(label, m, v, n, m);
-
-    if(label > nextLabel)
-      nextLabel = label;
-  }
-  if(nextLabel > mesh->viewLabel())
-    mesh->setLabel(nextLabel);
-
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, posVAid);
-  glBufferDataARB(GL_ARRAY_BUFFER_ARB, posVA.size() * sizeof(Point3f), &posVA[0], GL_STATIC_DRAW_ARB);
-
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, nrmlVAid);
-  glBufferDataARB(GL_ARRAY_BUFFER_ARB, nrmlVA.size() * sizeof(Point3f), &nrmlVA[0], GL_STATIC_DRAW_ARB);
-
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, pntsVAid);
-  glBufferDataARB(GL_ARRAY_BUFFER_ARB, pntsVA.size() * sizeof(Point3f), &pntsVA[0], GL_STATIC_DRAW_ARB);
-
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
-}
-
-// Update point and lines VAs for cells and borders
-void ImgData::updateLines()
-{
-  needUpdateLines = false;
-  if(pidVA.empty())
-    return;
-
-  try {
-    vvgraph& S = mesh->graph();
-    pbrdVA.clear();
-    pcellVA.clear();
-    pselVA.clear();
-    lbrdVA.clear();
-    lcellVA.clear();
-    lselVA.clear();
-
+  
+  void ImgData::updatePos()
+  {
+    if(idVA.empty() or pidVA.empty())
+      return;
+  
+    int nextLabel = mesh->viewLabel();
+  
+    // Update positions for line and point drawing
+    BoundingBox3f bBox(Point3f(FLT_MAX, FLT_MAX, FLT_MAX), Point3f(-FLT_MAX, -FLT_MAX, -FLT_MAX));
     for(size_t i = 0; i < pidVA.size(); i++) {
-      // Border points, should be small
       vertex v(pidVA[i]);
-      if(v->selected)
-        pselVA.push_back(v->saveId);
-      if(v->margin) {
-        pcolVA[i] = pColor(v);
-        pbrdVA.push_back(v->saveId);
-        pcellVA.push_back(v->saveId);
-      } else if(v->label == -1) {
-        pcolVA[i] = pColor(v);
-        pcellVA.push_back(v->saveId);
-      } else if(!v->selected)
-        continue;
-
-      forall(const vertex& n, S.neighbors(v)) {
-        // Make arrays for lines
-        if(uniqueLine(S, v, n)) {
-          // Border lines
-          if(v->margin and n->margin) {
-            lbrdVA.push_back(v->saveId);
-            lbrdVA.push_back(n->saveId);
-            lcellVA.push_back(v->saveId);
-            lcellVA.push_back(n->saveId);
-          } else if(v->label == -1 and n->label == -1) {
-            lcellVA.push_back(v->saveId);
-            lcellVA.push_back(n->saveId);
-          }
-          if(v->selected) {
-            lselVA.push_back(v->saveId);
-            lselVA.push_back(n->saveId);
-          }
-        }
-      }
-    }
-  }
-  catch(QString msg) {
-    SETSTATUS("updateLines::Error " << msg);
-  }
-  catch(...) {
-    SETSTATUS("updateLines::Error unknown exception");
-  }
-}
-
-// Fill the vertex array
-void ImgData::fillVBOs()
-{
-  vvgraph& S = mesh->graph();
-  float step = std::max(stack->step().x(), std::max(stack->step().y(), stack->step().z()));
-
-  // Leave if nothing to draw
-  if(S.empty())
-    return;
-  try {
-    // Also counts triangles and fills in pidVA[]
-    marginNormalsVBOs();
-
-    // Vertex arrays for points
-    pntsVA.resize(S.size());
-    pcolVA.resize(S.size());
-    pselcolVA.resize(S.size());
-    pbrdVA.clear();
-    pcellVA.clear();
-    pselVA.clear();
-
-    // Vertex arrays for lines
-    lineVA.resize(LCount * 2);
-    lbrdVA.clear();
-    lcellVA.clear();
-    lselVA.clear();
-
-    // Vertex arrays for triangles
-    idVA.resize(TCount * 3);
-    posVA.resize(TCount * 3);
-    nrmlVA.resize(TCount * 3);
-    selVA.resize(TCount * 3);
-    texVA.resize(TCount * 3);
-    imgVA.resize(TCount * 3);
-    vMap.clear();
-
-    BoundingBox3f bBox(Point3f(FLT_MAX, FLT_MAX, FLT_MAX), Point3f(-FLT_MAX, -FLT_MAX, -FLT_MAX));
-
-    uint vcnt = 0, lcnt = 0, tcnt = 0, pcol = 0, ucol = 0;
-    vertex pv(0);
-    forall(const vertex& v, pidVA) {
-      // Make arrays for points
-      pntsVA[vcnt] = v->pos;
-      pselcolVA[vcnt] = vMapColor(pcol++);
-      pcolVA[vcnt++] = pColor(v);
-
       bBox |= v->pos;
-
-      // Border points, should be small
-      if(v->margin) {
-        pbrdVA.push_back(v->saveId);
-        pcellVA.push_back(v->saveId);
-      } else if(v->label == -1)
-        pcellVA.push_back(v->saveId);
-      if(v->selected)
-        pselVA.push_back(v->saveId);
-
-      // Do lines
-      forall(const vertex& n, S.neighbors(v)) {
-        // Make arrays for lines
-        if(uniqueLine(S, v, n)) {
-          if(int(lcnt) >= LCount * 2)
-            throw(QString("Line count exceeded"));
-
-          lineVA[lcnt++] = v->saveId;
-          lineVA[lcnt++] = n->saveId;
-
-          // Border lines, should be small
-          if(v->margin and n->margin) {
-            lbrdVA.push_back(v->saveId);
-            lbrdVA.push_back(n->saveId);
-            lcellVA.push_back(v->saveId);
-            lcellVA.push_back(n->saveId);
-          } else if(v->label == -1 and n->label == -1) {
-            lcellVA.push_back(v->saveId);
-            lcellVA.push_back(n->saveId);
-          }
-          if(v->selected) {
-            lselVA.push_back(v->saveId);
-            lselVA.push_back(n->saveId);
-          }
-        }
-
-        vertex m = S.nextTo(v, n);
-        if(!uniqueTri(S, v, n, m))
-          continue;
-
-        if(int(tcnt) >= TCount * 3)
-          throw(QString("Triangle count exceeded"));
-
-        // Draw based on label
-        int label = getLabel(v, n, m);
-
-        if(v != pv) {
-          vMap[v] = tcnt;
-          pv = v;
-        }
-        idVA[tcnt] = v;
-        posVA[tcnt] = v->pos - ZOffset * step * v->nrml;
-        nrmlVA[tcnt] = v->nrml;
-        selVA[tcnt] = vMapColor(ucol);
-        texVA[tcnt] = texCoord(label, v, v, n, m);
-        imgVA[tcnt++] = v->txpos;
-
-        idVA[tcnt] = n;
-        posVA[tcnt] = n->pos - ZOffset * step * n->nrml;
-        nrmlVA[tcnt] = n->nrml;
-        selVA[tcnt] = vMapColor(ucol);
-        texVA[tcnt] = texCoord(label, n, v, n, m);
-        imgVA[tcnt++] = n->txpos;
-
-        idVA[tcnt] = m;
-        posVA[tcnt] = m->pos - ZOffset * step * m->nrml;
-        nrmlVA[tcnt] = m->nrml;
-        selVA[tcnt] = vMapColor(ucol++);
-        texVA[tcnt] = texCoord(label, m, v, n, m);
-        imgVA[tcnt++] = m->txpos;
-      }
+      pntsVA[i] = v->pos;
+      if(v->label > nextLabel)
+        nextLabel = v->label;
     }
     mesh->setBoundingBox(bBox);
-
-    // Set up Vertex Buffer Object to put data onto graphics card
-    if(!posVAid)
-      glGenBuffersARB(1, &posVAid);
+  
+    // Update positions for triangles
+    uint tcnt = 0;
+    float step = std::max(stack->step().x(), std::max(stack->step().y(), stack->step().z()));
+    for(size_t i = 0; i < idVA.size(); i += 3) {
+      if(tcnt >= texVA.size())
+        throw(QString("updateTex:Error Triangle index too large"));
+  
+      vertex v(idVA[i]), n(idVA[i + 1]), m(idVA[i + 2]);
+      int label = getLabel(v, n, m);
+  
+      posVA[tcnt] = v->pos - ZOffset * step * v->nrml;
+      nrmlVA[tcnt] = v->nrml;
+      texVA[tcnt++] = texCoord(label, v, v, n, m);
+  
+      posVA[tcnt] = n->pos - ZOffset * step * n->nrml;
+      nrmlVA[tcnt] = n->nrml;
+      texVA[tcnt++] = texCoord(label, n, v, n, m);
+  
+      posVA[tcnt] = m->pos - ZOffset * step * m->nrml;
+      nrmlVA[tcnt] = m->nrml;
+      texVA[tcnt++] = texCoord(label, m, v, n, m);
+  
+      if(label > nextLabel)
+        nextLabel = label;
+    }
+    if(nextLabel > mesh->viewLabel())
+      mesh->setLabel(nextLabel);
+  
     glBindBufferARB(GL_ARRAY_BUFFER_ARB, posVAid);
     glBufferDataARB(GL_ARRAY_BUFFER_ARB, posVA.size() * sizeof(Point3f), &posVA[0], GL_STATIC_DRAW_ARB);
-    if(!nrmlVAid)
-      glGenBuffersARB(1, &nrmlVAid);
+  
     glBindBufferARB(GL_ARRAY_BUFFER_ARB, nrmlVAid);
     glBufferDataARB(GL_ARRAY_BUFFER_ARB, nrmlVA.size() * sizeof(Point3f), &nrmlVA[0], GL_STATIC_DRAW_ARB);
-    if(!texVAid)
-      glGenBuffersARB(1, &texVAid);
-    glBindBufferARB(GL_ARRAY_BUFFER_ARB, texVAid);
-    glBufferDataARB(GL_ARRAY_BUFFER_ARB, texVA.size() * sizeof(Point3f), &texVA[0], GL_STATIC_DRAW_ARB);
-    if(!imgVAid)
-      glGenBuffersARB(1, &imgVAid);
-    glBindBufferARB(GL_ARRAY_BUFFER_ARB, imgVAid);
-    glBufferDataARB(GL_ARRAY_BUFFER_ARB, imgVA.size() * sizeof(Point2f), &imgVA[0], GL_STATIC_DRAW_ARB);
-    if(!selVAid)
-      glGenBuffersARB(1, &selVAid);
-    glBindBufferARB(GL_ARRAY_BUFFER_ARB, selVAid);
-    glBufferDataARB(GL_ARRAY_BUFFER_ARB, selVA.size() * sizeof(Point3GLub), &selVA[0], GL_STATIC_DRAW_ARB);
-    if(!pntsVAid)
-      glGenBuffersARB(1, &pntsVAid);
+  
     glBindBufferARB(GL_ARRAY_BUFFER_ARB, pntsVAid);
     glBufferDataARB(GL_ARRAY_BUFFER_ARB, pntsVA.size() * sizeof(Point3f), &pntsVA[0], GL_STATIC_DRAW_ARB);
-    if(!pcolVAid)
-      glGenBuffersARB(1, &pcolVAid);
-    glBindBufferARB(GL_ARRAY_BUFFER_ARB, pcolVAid);
-    glBufferDataARB(GL_ARRAY_BUFFER_ARB, pcolVA.size() * sizeof(Point3GLub), &pcolVA[0], GL_STATIC_DRAW_ARB);
-    if(!pselVAid)
-      glGenBuffersARB(1, &pselVAid);
-    glBindBufferARB(GL_ARRAY_BUFFER_ARB, pselVAid);
-    glBufferDataARB(GL_ARRAY_BUFFER_ARB, pselcolVA.size() * sizeof(Point3GLub), &pselcolVA[0], GL_STATIC_DRAW_ARB);
-
+  
     glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
   }
-  catch(QString msg) {
-    SETSTATUS("fillVBOs::Error " << msg);
+  
+  // Update point and lines VAs for cells and borders
+  void ImgData::updateLines()
+  {
+    needUpdateLines = false;
+    if(pidVA.empty())
+      return;
+  
+    try {
+      vvgraph& S = mesh->graph();
+      pbrdVA.clear();
+      pcellVA.clear();
+      pselVA.clear();
+      lbrdVA.clear();
+      lcellVA.clear();
+      lselVA.clear();
+  
+      for(size_t i = 0; i < pidVA.size(); i++) {
+        // Border points, should be small
+        vertex v(pidVA[i]);
+        if(v->selected)
+          pselVA.push_back(v->saveId);
+        if(v->margin) {
+          pcolVA[i] = pColor(v);
+          pbrdVA.push_back(v->saveId);
+          pcellVA.push_back(v->saveId);
+        } else if(v->label == -1) {
+          pcolVA[i] = pColor(v);
+          pcellVA.push_back(v->saveId);
+        } else if(!v->selected)
+          continue;
+  
+        forall(const vertex& n, S.neighbors(v)) {
+          // Make arrays for lines
+          if(uniqueLine(S, v, n)) {
+            // Border lines
+            if(v->margin and n->margin) {
+              lbrdVA.push_back(v->saveId);
+              lbrdVA.push_back(n->saveId);
+              lcellVA.push_back(v->saveId);
+              lcellVA.push_back(n->saveId);
+            } else if(v->label == -1 and n->label == -1) {
+              lcellVA.push_back(v->saveId);
+              lcellVA.push_back(n->saveId);
+            }
+            if(v->selected) {
+              lselVA.push_back(v->saveId);
+              lselVA.push_back(n->saveId);
+            }
+          }
+        }
+      }
+    }
+    catch(QString msg) {
+      SETSTATUS("updateLines::Error " << msg);
+    }
+    catch(...) {
+      SETSTATUS("updateLines::Error unknown exception");
+    }
   }
-  catch(...) {
-    SETSTATUS("fillVBOs::Error unknown exception");
+  
+  // Fill the vertex array
+  void ImgData::fillVBOs()
+  {
+    vvgraph& S = mesh->graph();
+    float step = std::max(stack->step().x(), std::max(stack->step().y(), stack->step().z()));
+  
+    // Leave if nothing to draw
+    if(S.empty())
+      return;
+    try {
+      // Also counts triangles and fills in pidVA[]
+      marginNormalsVBOs();
+  
+      // Vertex arrays for points
+      pntsVA.resize(S.size());
+      pcolVA.resize(S.size());
+      pselcolVA.resize(S.size());
+      pbrdVA.clear();
+      pcellVA.clear();
+      pselVA.clear();
+  
+      // Vertex arrays for lines
+      lineVA.resize(LCount * 2);
+      lbrdVA.clear();
+      lcellVA.clear();
+      lselVA.clear();
+  
+      // Vertex arrays for triangles
+      idVA.resize(TCount * 3);
+      posVA.resize(TCount * 3);
+      nrmlVA.resize(TCount * 3);
+      selVA.resize(TCount * 3);
+      texVA.resize(TCount * 3);
+      imgVA.resize(TCount * 3);
+      vMap.clear();
+  
+      BoundingBox3f bBox(Point3f(FLT_MAX, FLT_MAX, FLT_MAX), Point3f(-FLT_MAX, -FLT_MAX, -FLT_MAX));
+  
+      uint vcnt = 0, lcnt = 0, tcnt = 0, pcol = 0, ucol = 0;
+      vertex pv(0);
+      forall(const vertex& v, pidVA) {
+        // Make arrays for points
+        pntsVA[vcnt] = v->pos;
+        pselcolVA[vcnt] = vMapColor(pcol++);
+        pcolVA[vcnt++] = pColor(v);
+  
+        bBox |= v->pos;
+  
+        // Border points, should be small
+        if(v->margin) {
+          pbrdVA.push_back(v->saveId);
+          pcellVA.push_back(v->saveId);
+        } else if(v->label == -1)
+          pcellVA.push_back(v->saveId);
+        if(v->selected)
+          pselVA.push_back(v->saveId);
+  
+        // Do lines
+        forall(const vertex& n, S.neighbors(v)) {
+          // Make arrays for lines
+          if(uniqueLine(S, v, n)) {
+            if(int(lcnt) >= LCount * 2)
+              throw(QString("Line count exceeded"));
+  
+            lineVA[lcnt++] = v->saveId;
+            lineVA[lcnt++] = n->saveId;
+  
+            // Border lines, should be small
+            if(v->margin and n->margin) {
+              lbrdVA.push_back(v->saveId);
+              lbrdVA.push_back(n->saveId);
+              lcellVA.push_back(v->saveId);
+              lcellVA.push_back(n->saveId);
+            } else if(v->label == -1 and n->label == -1) {
+              lcellVA.push_back(v->saveId);
+              lcellVA.push_back(n->saveId);
+            }
+            if(v->selected) {
+              lselVA.push_back(v->saveId);
+              lselVA.push_back(n->saveId);
+            }
+          }
+  
+          vertex m = S.nextTo(v, n);
+          if(!uniqueTri(S, v, n, m))
+            continue;
+  
+          if(int(tcnt) >= TCount * 3)
+            throw(QString("Triangle count exceeded"));
+  
+          // Draw based on label
+          int label = getLabel(v, n, m);
+  
+          if(v != pv) {
+            vMap[v] = tcnt;
+            pv = v;
+          }
+          idVA[tcnt] = v;
+          posVA[tcnt] = v->pos - ZOffset * step * v->nrml;
+          nrmlVA[tcnt] = v->nrml;
+          selVA[tcnt] = vMapColor(ucol);
+          texVA[tcnt] = texCoord(label, v, v, n, m);
+          imgVA[tcnt++] = v->txpos;
+  
+          idVA[tcnt] = n;
+          posVA[tcnt] = n->pos - ZOffset * step * n->nrml;
+          nrmlVA[tcnt] = n->nrml;
+          selVA[tcnt] = vMapColor(ucol);
+          texVA[tcnt] = texCoord(label, n, v, n, m);
+          imgVA[tcnt++] = n->txpos;
+  
+          idVA[tcnt] = m;
+          posVA[tcnt] = m->pos - ZOffset * step * m->nrml;
+          nrmlVA[tcnt] = m->nrml;
+          selVA[tcnt] = vMapColor(ucol++);
+          texVA[tcnt] = texCoord(label, m, v, n, m);
+          imgVA[tcnt++] = m->txpos;
+        }
+      }
+      mesh->setBoundingBox(bBox);
+  
+      // Set up Vertex Buffer Object to put data onto graphics card
+      if(!posVAid)
+        glGenBuffersARB(1, &posVAid);
+      glBindBufferARB(GL_ARRAY_BUFFER_ARB, posVAid);
+      glBufferDataARB(GL_ARRAY_BUFFER_ARB, posVA.size() * sizeof(Point3f), &posVA[0], GL_STATIC_DRAW_ARB);
+      if(!nrmlVAid)
+        glGenBuffersARB(1, &nrmlVAid);
+      glBindBufferARB(GL_ARRAY_BUFFER_ARB, nrmlVAid);
+      glBufferDataARB(GL_ARRAY_BUFFER_ARB, nrmlVA.size() * sizeof(Point3f), &nrmlVA[0], GL_STATIC_DRAW_ARB);
+      if(!texVAid)
+        glGenBuffersARB(1, &texVAid);
+      glBindBufferARB(GL_ARRAY_BUFFER_ARB, texVAid);
+      glBufferDataARB(GL_ARRAY_BUFFER_ARB, texVA.size() * sizeof(Point3f), &texVA[0], GL_STATIC_DRAW_ARB);
+      if(!imgVAid)
+        glGenBuffersARB(1, &imgVAid);
+      glBindBufferARB(GL_ARRAY_BUFFER_ARB, imgVAid);
+      glBufferDataARB(GL_ARRAY_BUFFER_ARB, imgVA.size() * sizeof(Point2f), &imgVA[0], GL_STATIC_DRAW_ARB);
+      if(!selVAid)
+        glGenBuffersARB(1, &selVAid);
+      glBindBufferARB(GL_ARRAY_BUFFER_ARB, selVAid);
+      glBufferDataARB(GL_ARRAY_BUFFER_ARB, selVA.size() * sizeof(Point3GLub), &selVA[0], GL_STATIC_DRAW_ARB);
+      if(!pntsVAid)
+        glGenBuffersARB(1, &pntsVAid);
+      glBindBufferARB(GL_ARRAY_BUFFER_ARB, pntsVAid);
+      glBufferDataARB(GL_ARRAY_BUFFER_ARB, pntsVA.size() * sizeof(Point3f), &pntsVA[0], GL_STATIC_DRAW_ARB);
+      if(!pcolVAid)
+        glGenBuffersARB(1, &pcolVAid);
+      glBindBufferARB(GL_ARRAY_BUFFER_ARB, pcolVAid);
+      glBufferDataARB(GL_ARRAY_BUFFER_ARB, pcolVA.size() * sizeof(Point3GLub), &pcolVA[0], GL_STATIC_DRAW_ARB);
+      if(!pselVAid)
+        glGenBuffersARB(1, &pselVAid);
+      glBindBufferARB(GL_ARRAY_BUFFER_ARB, pselVAid);
+      glBufferDataARB(GL_ARRAY_BUFFER_ARB, pselcolVA.size() * sizeof(Point3GLub), &pselcolVA[0], GL_STATIC_DRAW_ARB);
+  
+      glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
+    }
+    catch(QString msg) {
+      SETSTATUS("fillVBOs::Error " << msg);
+    }
+    catch(...) {
+      SETSTATUS("fillVBOs::Error unknown exception");
+    }
   }
-}
-
-// Update a list of vertex positions in the VBO
-void ImgData::updPos(std::set<uint>& vList, bool points)
-{
-  if(vList.empty())
-    return;
-  vvgraph& S = mesh->graph();
-
-  // Find out which tables to update
-  uint pVAid = points ? pntsVAid : posVAid;
-  std::vector<vertex>& iVA = points ? pidVA : idVA;
-  std::vector<Point3f>& pVA = points ? pntsVA : posVA;
-
-  // Update normals including neighbors
-  std::set<vertex> nlist;
-  forall(uint u, vList) {
-    vertex v = iVA[u];
-    nlist.insert(v);
-    forall(const vertex& n, S.neighbors(v))
-      nlist.insert(n);
-  }
-
-  // Update vertex position in Vertex array table
-  forall(uint u, vList) {
-    vertex v = iVA[u];
-    pVA[u] = v->pos;
-  }
-
-  // Write data to GPU
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, pVAid);
-  Point3f* mp = (Point3f*)glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY);
-  if(!mp) {
-    REPORT_GL_ERROR("glMapBufferARB(pVAid) - using glBufferDataARB");
-    glBufferDataARB(GL_ARRAY_BUFFER_ARB, pVA.size() * sizeof(Point3f), &pVA[0], GL_STATIC_DRAW_ARB);
-  } else {
-    forall(uint u, vList)
-      mp[u] = pVA[u];
-    glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
-  }
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
-}
-
-// Find selected triangle in triangle select mode (!MeshSelect)
-void ImgData::findSelectTriangle(uint x, uint y, std::vector<uint>& vList, int& label, bool useParentLabel)
-{
-  // Draw unique colors in tha AUX0 buffer
-  drawSurf(true);
-
-  // Find the color of the pixels drawn in BACK buffer
-  Point3GLub pix;
-  GLint viewport[4];
-  glGetIntegerv(GL_VIEWPORT, viewport);
-  glReadBuffer(GL_AUX0);
-  glReadPixels(x, viewport[3] - y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pix);
-  glReadBuffer(GL_FRONT);
-  int u = vMapColor(pix);
-  // Return if nothing selected
-  if(u < 0)
-    return;
-
-  u *= 3;
-  if(u + 3 > int(idVA.size())) {
-    Information::out << "findSelectTriangle:Error Index too large, tri idx:" << u << " idVA size:" << idVA.size()
-                     << endl;
-    return;
-  }
-  // Return triangle and label for selected color
-  for(uint i = 0; i < 3; i++)
-    vList.push_back(u + i);
-  label = getLabel(idVA[u], idVA[u + 1], idVA[u + 2], useParentLabel);
-}
-
-// Trim bounding box with a clip plane in point normal form
-void ImgData::bBoxClip(BoundingBox3f& bBox, Point3f p, Point3f n)
-{
-  int x, y, z;
-  Point3f u1, u2, pt;
-  float dir, s;
-
-  // check x direction, find which line to test
-  dir = n * Point3f(1.0f, 0.0f, 0.0f);
-  y = (n.y() > 0 ? 1 : 0);
-  z = (n.z() > 0 ? 1 : 0);
-  u1 = Point3f(bBox[0].x(), bBox[y].y(), bBox[z].z());
-  u2 = Point3f(bBox[1].x(), bBox[y].y(), bBox[z].z());
-  if(planeLineIntersect(p, n, u1, u2, s, pt)) {
-    if(dir > 0) {     // outside points in positive x dir
-      if(pt.x() > bBox[0].x())
-        bBox[0].x() = pt.x();
-    } else {
-      if(pt.x() < bBox[1].x())
-        bBox[1].x() = pt.x();
+  
+  // Update a list of vertex positions in the VBO
+  void ImgData::updPos(std::set<uint>& vList, bool points)
+  {
+    if(vList.empty())
+      return;
+    vvgraph& S = mesh->graph();
+  
+    // Find out which tables to update
+    uint pVAid = points ? pntsVAid : posVAid;
+    std::vector<vertex>& iVA = points ? pidVA : idVA;
+    std::vector<Point3f>& pVA = points ? pntsVA : posVA;
+  
+    // Update normals including neighbors
+    std::set<vertex> nlist;
+    forall(uint u, vList) {
+      vertex v = iVA[u];
+      nlist.insert(v);
+      forall(const vertex& n, S.neighbors(v))
+        nlist.insert(n);
     }
-  }
-  // check y direction, find which line to test
-  dir = n * Point3f(0.0f, 1.0f, 0.0f);
-  x = (n.x() > 0 ? 1 : 0);
-  z = (n.z() > 0 ? 1 : 0);
-  u1 = Point3f(bBox[x].x(), bBox[0].y(), bBox[z].z());
-  u2 = Point3f(bBox[x].x(), bBox[1].y(), bBox[z].z());
-  if(planeLineIntersect(p, n, u1, u2, s, pt)) {
-    if(dir > 0) {
-      if(pt.y() > bBox[0].y())
-        bBox[0].y() = pt.y();
+  
+    // Update vertex position in Vertex array table
+    forall(uint u, vList) {
+      vertex v = iVA[u];
+      pVA[u] = v->pos;
+    }
+  
+    // Write data to GPU
+    glBindBufferARB(GL_ARRAY_BUFFER_ARB, pVAid);
+    Point3f* mp = (Point3f*)glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY);
+    if(!mp) {
+      REPORT_GL_ERROR("glMapBufferARB(pVAid) - using glBufferDataARB");
+      glBufferDataARB(GL_ARRAY_BUFFER_ARB, pVA.size() * sizeof(Point3f), &pVA[0], GL_STATIC_DRAW_ARB);
     } else {
-      if(pt.y() < bBox[1].y())
-        bBox[1].y() = pt.y();
+      forall(uint u, vList)
+        mp[u] = pVA[u];
+      glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
     }
+    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
   }
-  // check z direction, find which line to test
-  dir = n * Point3f(0.0f, 0.0f, 1.0f);
-  x = (n.x() > 0 ? 1 : 0);
-  y = (n.y() > 0 ? 1 : 0);
-  u1 = Point3f(bBox[x].x(), bBox[y].y(), bBox[0].z());
-  u2 = Point3f(bBox[x].x(), bBox[y].y(), bBox[1].z());
-  if(planeLineIntersect(p, n, u1, u2, s, pt)) {
-    if(dir > 0) {
-      if(pt.z() > bBox[0].z())
-        bBox[0].z() = pt.z();
-    } else {
-      if(pt.z() < bBox[1].z())
-        bBox[1].z() = pt.z();
+  
+  // Find selected triangle in triangle select mode (!MeshSelect)
+  void ImgData::findSelectTriangle(uint x, uint y, std::vector<uint>& vList, int& label, bool useParentLabel)
+  {
+    // Draw unique colors in tha AUX0 buffer
+    drawSurf(true);
+  
+    // Find the color of the pixels drawn in BACK buffer
+    Point3GLub pix;
+    GLint viewport[4];
+    glGetIntegerv(GL_VIEWPORT, viewport);
+    glReadBuffer(GL_AUX0);
+    glReadPixels(x, viewport[3] - y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pix);
+    glReadBuffer(GL_FRONT);
+    int u = vMapColor(pix);
+    // Return if nothing selected
+    if(u < 0)
+      return;
+  
+    u *= 3;
+    if(u + 3 > int(idVA.size())) {
+      Information::out << "findSelectTriangle:Error Index too large, tri idx:" << u << " idVA size:" << idVA.size()
+                       << endl;
+      return;
     }
+    // Return triangle and label for selected color
+    for(uint i = 0; i < 3; i++)
+      vList.push_back(u + i);
+    label = getLabel(idVA[u], idVA[u + 1], idVA[u + 2], useParentLabel);
   }
-}
-
-//  Calculate bounding box from clipping planes (in point normal form)
-void ImgData::bBoxFromClip()
-{
-  // clear, set to entire texture
-  Point3f Origin = stack->origin();
-  const Point3f& Size = stack->size();
-  bBox[0] = Origin;
-  bBox[1] = Origin + Size;
-
-  // Test all 6 planes (twice)
-  for(int i = 0; i < 2; i++)
-    for(int pln = 0; pln < 6; pln++) {
-      if(!clipDo[pln / 2])
-        continue;
-
-      Point3f n(pn[pln].x(), pn[pln].y(), pn[pln].z());
-      float d = pn[pln][3];
-      bBoxClip(bBox, n * -d, n);
+  
+  // Trim bounding box with a clip plane in point normal form
+  void ImgData::bBoxClip(BoundingBox3f& bBox, Point3f p, Point3f n)
+  {
+    int x, y, z;
+    Point3f u1, u2, pt;
+    float dir, s;
+  
+    // check x direction, find which line to test
+    dir = n * Point3f(1.0f, 0.0f, 0.0f);
+    y = (n.y() > 0 ? 1 : 0);
+    z = (n.z() > 0 ? 1 : 0);
+    u1 = Point3f(bBox[0].x(), bBox[y].y(), bBox[z].z());
+    u2 = Point3f(bBox[1].x(), bBox[y].y(), bBox[z].z());
+    if(planeLineIntersect(p, n, u1, u2, s, pt)) {
+      if(dir > 0) {     // outside points in positive x dir
+        if(pt.x() > bBox[0].x())
+          bBox[0].x() = pt.x();
+      } else {
+        if(pt.x() < bBox[1].x())
+          bBox[1].x() = pt.x();
+      }
     }
-}
-
-// Setup data for clipping test
-void ImgData::getClipTestData(ClipRegion& clip1, ClipRegion& clip2, ClipRegion& clip3)
-{
-  Clip* c1 = clip1.clip;
-  Clip* c2 = clip2.clip;
-  Clip* c3 = clip3.clip;
-  // Indicator if in use
-  clipDo[0] = (c1->enabled() or c1->grid() ? 1 : 0);
-  clipDo[1] = (c2->enabled() or c2->grid() ? 1 : 0);
-  clipDo[2] = (c3->enabled() or c3->grid() ? 1 : 0);
-
-  // Frame matrix
-  frm = Matrix4d(getFrame().worldMatrix());
-
-  // Clip plane matrices
-  clm[0] = Matrix4d(c1->frame().inverse().worldMatrix());
-  clm[1] = Matrix4d(c2->frame().inverse().worldMatrix());
-  clm[2] = Matrix4d(c3->frame().inverse().worldMatrix());
-
-  // Clipping planes, point normal form
-  pn[0] = Point4f(frm * clm[0] * Point4f(c1->normal().x(), c1->normal().y(), c1->normal().z(), c1->width()));
-  pn[1] = Point4f(frm * clm[0] * Point4f(-c1->normal().x(), -c1->normal().y(), -c1->normal().z(), c1->width()));
-  pn[2] = Point4f(frm * clm[1] * Point4f(c2->normal().x(), c2->normal().y(), c2->normal().z(), c2->width()));
-  pn[3] = Point4f(frm * clm[1] * Point4f(-c2->normal().x(), -c2->normal().y(), -c2->normal().z(), c2->width()));
-  pn[4] = Point4f(frm * clm[2] * Point4f(c3->normal().x(), c3->normal().y(), c3->normal().z(), c3->width()));
-  pn[5] = Point4f(frm * clm[2] * Point4f(-c3->normal().x(), -c3->normal().y(), -c3->normal().z(), c3->width()));
-
-  // Put in host vector
-  Hpn.resize(6);
-  for(int i = 0; i < 6; i++)
-    Hpn[i] = pn[i];
-}
-
-void ImgData::pixelEditStart(ClipRegion& clip1, ClipRegion& clip2, ClipRegion& clip3)
-{
-  if(stack->work()->isVisible()) {
-    // Setup matrices and planes for clip test
-    getClipTestData(clip1, clip2, clip3);
-
-    // If 3D seeding, increment label number
-    if(FillWorkData and stack->work()->isVisible() and SeedStack and stack->work()->labels()) {
-      int lab = stack->nextLabel();
-      SETSTATUS("Adding seed " << lab);
+    // check y direction, find which line to test
+    dir = n * Point3f(0.0f, 1.0f, 0.0f);
+    x = (n.x() > 0 ? 1 : 0);
+    z = (n.z() > 0 ? 1 : 0);
+    u1 = Point3f(bBox[x].x(), bBox[0].y(), bBox[z].z());
+    u2 = Point3f(bBox[x].x(), bBox[1].y(), bBox[z].z());
+    if(planeLineIntersect(p, n, u1, u2, s, pt)) {
+      if(dir > 0) {
+        if(pt.y() > bBox[0].y())
+          bBox[0].y() = pt.y();
+      } else {
+        if(pt.y() < bBox[1].y())
+          bBox[1].y() = pt.y();
+      }
     }
-
-    // Setup texture update area
-    bBoxTex[0] = Point3i(stack->size().x(), stack->size().y(), stack->size().z());
-    bBoxTex[1] = Point3i(0, 0, 0);
+    // check z direction, find which line to test
+    dir = n * Point3f(0.0f, 0.0f, 1.0f);
+    x = (n.x() > 0 ? 1 : 0);
+    y = (n.y() > 0 ? 1 : 0);
+    u1 = Point3f(bBox[x].x(), bBox[y].y(), bBox[0].z());
+    u2 = Point3f(bBox[x].x(), bBox[y].y(), bBox[1].z());
+    if(planeLineIntersect(p, n, u1, u2, s, pt)) {
+      if(dir > 0) {
+        if(pt.z() > bBox[0].z())
+          bBox[0].z() = pt.z();
+      } else {
+        if(pt.z() < bBox[1].z())
+          bBox[1].z() = pt.z();
+      }
+    }
   }
-}
-
-void ImgData::pixelEditStop()
-{
-  // Reload the texture to see the edit result
-  if(stack->work()->isVisible() and pixelsChanged)
-    updateTex(workDataTexId, bBoxTex);
-  pixelsChanged = false;
-}
-
-void ImgData::pixelEdit(float pixelRadius, const Point3f& p, const Point3f& px, const Point3f& py, const Point3f& pz,
-                        bool doCut, int currentLabel)
-{
-  Point3f Origin = stack->origin();
-  if(stack->work()->isVisible()) {
-    // Clear bounding box, set to entire texture
+  
+  //  Calculate bounding box from clipping planes (in point normal form)
+  void ImgData::bBoxFromClip()
+  {
+    // clear, set to entire texture
+    Point3f Origin = stack->origin();
+    const Point3f& Size = stack->size();
     bBox[0] = Origin;
-    bBox[1] = Origin + multiply(Point3f(stack->size()), stack->step());
-    // Trim bounding box to clip planes
-    for(int i = 0; i < 2; i++) {
-      // Test all 6 planes (twice)
+    bBox[1] = Origin + Size;
+  
+    // Test all 6 planes (twice)
+    for(int i = 0; i < 2; i++)
       for(int pln = 0; pln < 6; pln++) {
         if(!clipDo[pln / 2])
           continue;
-
+  
         Point3f n(pn[pln].x(), pn[pln].y(), pn[pln].z());
         float d = pn[pln][3];
         bBoxClip(bBox, n * -d, n);
       }
-      bBoxClip(bBox, p - pixelRadius * px, px);
-      bBoxClip(bBox, p + pixelRadius * px, -px);
-      bBoxClip(bBox, p - pixelRadius * py, py);
-      bBoxClip(bBox, p + pixelRadius * py, -py);
-      if(doCut) {
-        bBoxClip(bBox, p - pixelRadius * pz, pz);
-        bBoxClip(bBox, p + pixelRadius * pz, -pz);
+  }
+  
+  // Setup data for clipping test
+  void ImgData::getClipTestData(ClipRegion& clip1, ClipRegion& clip2, ClipRegion& clip3)
+  {
+    Clip* c1 = clip1.clip;
+    Clip* c2 = clip2.clip;
+    Clip* c3 = clip3.clip;
+    // Indicator if in use
+    clipDo[0] = (c1->enabled() or c1->grid() ? 1 : 0);
+    clipDo[1] = (c2->enabled() or c2->grid() ? 1 : 0);
+    clipDo[2] = (c3->enabled() or c3->grid() ? 1 : 0);
+  
+    // Frame matrix
+    frm = Matrix4d(getFrame().worldMatrix());
+  
+    // Clip plane matrices
+    clm[0] = Matrix4d(c1->frame().inverse().worldMatrix());
+    clm[1] = Matrix4d(c2->frame().inverse().worldMatrix());
+    clm[2] = Matrix4d(c3->frame().inverse().worldMatrix());
+  
+    // Clipping planes, point normal form
+    pn[0] = Point4f(frm * clm[0] * Point4f(c1->normal().x(), c1->normal().y(), c1->normal().z(), c1->width()));
+    pn[1] = Point4f(frm * clm[0] * Point4f(-c1->normal().x(), -c1->normal().y(), -c1->normal().z(), c1->width()));
+    pn[2] = Point4f(frm * clm[1] * Point4f(c2->normal().x(), c2->normal().y(), c2->normal().z(), c2->width()));
+    pn[3] = Point4f(frm * clm[1] * Point4f(-c2->normal().x(), -c2->normal().y(), -c2->normal().z(), c2->width()));
+    pn[4] = Point4f(frm * clm[2] * Point4f(c3->normal().x(), c3->normal().y(), c3->normal().z(), c3->width()));
+    pn[5] = Point4f(frm * clm[2] * Point4f(-c3->normal().x(), -c3->normal().y(), -c3->normal().z(), c3->width()));
+  
+    // Put in host vector
+    Hpn.resize(6);
+    for(int i = 0; i < 6; i++)
+      Hpn[i] = pn[i];
+  }
+  
+  void ImgData::pixelEditStart(ClipRegion& clip1, ClipRegion& clip2, ClipRegion& clip3)
+  {
+    if(stack->work()->isVisible()) {
+      // Setup matrices and planes for clip test
+      getClipTestData(clip1, clip2, clip3);
+  
+      // If 3D seeding, increment label number
+      if(FillWorkData and stack->work()->isVisible() and SeedStack and stack->work()->labels()) {
+        int lab = stack->nextLabel();
+        SETSTATUS("Adding seed " << lab);
       }
-    }
-
-    // Get bounding box in image coordinates and pad a pixel
-    Point3i imgSize(stack->size().x(), stack->size().y(), stack->size().z());
-    Point3i base = worldToImagei(bBox[0]) - Point3i(1, 1, 1);
-    Point3i end = worldToImagei(bBox[1]) + Point3i(1, 1, 1);
-
-    // Check bounds and update bound box for texture update
-    for(int i = 0; i < 3; i++) {
-      base[i] = std::max(base[i], 0);
-      end[i] = std::min(end[i], imgSize[i]);
-      bBoxTex[0][i] = std::min(bBoxTex[0][i], base[i]);
-      bBoxTex[1][i] = std::max(bBoxTex[1][i], end[i]);
-    }
-    Point3i size = end - base;
-
-    // Call cuda
-    if(size.x() > 0 and size.y() > 0 and size.z() > 0) {
-      ushort pixval = 0x0;
-      if(FillWorkData) {
-        if(stack->work()->labels()) {
-          if(SeedStack)
-            pixval = stack->viewLabel();
-          else
-            pixval = currentLabel;
-        } else
-          pixval = 0xFFFF;
-      }
-      pixelEditGPU(base, size, imgSize, stack->step(), Origin, p, pz, pixelRadius, pixval, clipDo, Hpn,
-                   stack->work()->data());
-      pixelsChanged = true;
-    }
-    if(pixelsChanged
-       and size_t(bBoxTex[1].x() - bBoxTex[0].x()) * (bBoxTex[1].y() - bBoxTex[0].y())
-       * (bBoxTex[1].z() - bBoxTex[0].z()) < size_t(PixelEditMaxPix)) {
-      updateTex(workDataTexId, bBoxTex);
-      pixelsChanged = false;
+  
+      // Setup texture update area
       bBoxTex[0] = Point3i(stack->size().x(), stack->size().y(), stack->size().z());
       bBoxTex[1] = Point3i(0, 0, 0);
     }
   }
-}
-
-// Find selected point in mesh select mode (MeshSelect)
-int ImgData::findSelectPoint(uint x, uint y)
-{
-  // Draw unique colors in the BACK buffer
-  drawMesh(true);
-  drawSurf(true);
-  // Find the color of the pixels drawn in AUX0 buffer
-  Point3GLub pix;
-  GLint viewport[4];
-  glGetIntegerv(GL_VIEWPORT, viewport);
-  glReadBuffer(GL_AUX0);
-  glReadPixels(x, viewport[3] - y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pix);
-  glReadBuffer(GL_FRONT);
-  int i = vMapColor(pix);
-  if(i >= int(pidVA.size())) {
-    Information::out << "findSelectPoint::Error Index too large, point idx:" << i << " pidVA size:" << pidVA.size()
-                     << endl;
-    return -1;
+  
+  void ImgData::pixelEditStop()
+  {
+    // Reload the texture to see the edit result
+    if(stack->work()->isVisible() and pixelsChanged)
+      updateTex(workDataTexId, bBoxTex);
+    pixelsChanged = false;
   }
-  return (i);
-}
-
-// Average a list of vertices to find select point
-bool ImgData::findSeedPoint(uint x, uint y, CutSurf& cutSurf, Point3f& p)
-{
-  if(!SeedStack)
-    return (false);
-
-  vvgraph& S = mesh->graph();
-  p = Point3f(0, 0, 0);
-  if(cutSurf.cut->isVisible()) {
-    cutSurf.drawCutSurf(*this, true);
-    // Pixel color is x,y,z
+  
+  void ImgData::pixelEdit(float pixelRadius, const Point3f& p, const Point3f& px, const Point3f& py, const Point3f& pz,
+                          bool doCut, int currentLabel)
+  {
+    Point3f Origin = stack->origin();
+    if(stack->work()->isVisible()) {
+      // Clear bounding box, set to entire texture
+      bBox[0] = Origin;
+      bBox[1] = Origin + multiply(Point3f(stack->size()), stack->step());
+      // Trim bounding box to clip planes
+      for(int i = 0; i < 2; i++) {
+        // Test all 6 planes (twice)
+        for(int pln = 0; pln < 6; pln++) {
+          if(!clipDo[pln / 2])
+            continue;
+  
+          Point3f n(pn[pln].x(), pn[pln].y(), pn[pln].z());
+          float d = pn[pln][3];
+          bBoxClip(bBox, n * -d, n);
+        }
+        bBoxClip(bBox, p - pixelRadius * px, px);
+        bBoxClip(bBox, p + pixelRadius * px, -px);
+        bBoxClip(bBox, p - pixelRadius * py, py);
+        bBoxClip(bBox, p + pixelRadius * py, -py);
+        if(doCut) {
+          bBoxClip(bBox, p - pixelRadius * pz, pz);
+          bBoxClip(bBox, p + pixelRadius * pz, -pz);
+        }
+      }
+  
+      // Get bounding box in image coordinates and pad a pixel
+      Point3i imgSize(stack->size().x(), stack->size().y(), stack->size().z());
+      Point3i base = worldToImagei(bBox[0]) - Point3i(1, 1, 1);
+      Point3i end = worldToImagei(bBox[1]) + Point3i(1, 1, 1);
+  
+      // Check bounds and update bound box for texture update
+      for(int i = 0; i < 3; i++) {
+        base[i] = std::max(base[i], 0);
+        end[i] = std::min(end[i], imgSize[i]);
+        bBoxTex[0][i] = std::min(bBoxTex[0][i], base[i]);
+        bBoxTex[1][i] = std::max(bBoxTex[1][i], end[i]);
+      }
+      Point3i size = end - base;
+  
+      // Call cuda
+      if(size.x() > 0 and size.y() > 0 and size.z() > 0) {
+        ushort pixval = 0x0;
+        if(FillWorkData) {
+          if(stack->work()->labels()) {
+            if(SeedStack)
+              pixval = stack->viewLabel();
+            else
+              pixval = currentLabel;
+          } else
+            pixval = 0xFFFF;
+        }
+        pixelEditGPU(base, size, imgSize, stack->step(), Origin, p, pz, pixelRadius, pixval, clipDo, Hpn,
+                     stack->work()->data());
+        pixelsChanged = true;
+      }
+      if(pixelsChanged
+         and size_t(bBoxTex[1].x() - bBoxTex[0].x()) * (bBoxTex[1].y() - bBoxTex[0].y())
+         * (bBoxTex[1].z() - bBoxTex[0].z()) < size_t(PixelEditMaxPix)) {
+        updateTex(workDataTexId, bBoxTex);
+        pixelsChanged = false;
+        bBoxTex[0] = Point3i(stack->size().x(), stack->size().y(), stack->size().z());
+        bBoxTex[1] = Point3i(0, 0, 0);
+      }
+    }
+  }
+  
+  // Find selected point in mesh select mode (MeshSelect)
+  int ImgData::findSelectPoint(uint x, uint y)
+  {
+    // Draw unique colors in the BACK buffer
+    drawMesh(true);
+    drawSurf(true);
+    // Find the color of the pixels drawn in AUX0 buffer
+    Point3GLub pix;
     GLint viewport[4];
     glGetIntegerv(GL_VIEWPORT, viewport);
     glReadBuffer(GL_AUX0);
-    glReadPixels(x, viewport[3] - y, 1, 1, GL_RGB, GL_FLOAT, &p);
+    glReadPixels(x, viewport[3] - y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pix);
     glReadBuffer(GL_FRONT);
-    p -= Point3f(.5f, .5f, .5f);
-  } else if(mesh->isSurfaceVisible() and !S.empty()) {
-    std::vector<uint> vList;
-    int label;
-    findSelectTriangle(x, y, vList, label);
-    if(vList.empty())
+    int i = vMapColor(pix);
+    if(i >= int(pidVA.size())) {
+      Information::out << "findSelectPoint::Error Index too large, point idx:" << i << " pidVA size:" << pidVA.size()
+                       << endl;
+      return -1;
+    }
+    return (i);
+  }
+  
+  // Average a list of vertices to find select point
+  bool ImgData::findSeedPoint(uint x, uint y, CutSurf& cutSurf, Point3f& p)
+  {
+    if(!SeedStack)
       return (false);
-    forall(uint u, vList) {
-      if(u < idVA.size()) {
-        vertex v = idVA[u];
-        p += v->pos;
+  
+    vvgraph& S = mesh->graph();
+    p = Point3f(0, 0, 0);
+    if(cutSurf.cut->isVisible()) {
+      cutSurf.drawCutSurf(*this, true);
+      // Pixel color is x,y,z
+      GLint viewport[4];
+      glGetIntegerv(GL_VIEWPORT, viewport);
+      glReadBuffer(GL_AUX0);
+      glReadPixels(x, viewport[3] - y, 1, 1, GL_RGB, GL_FLOAT, &p);
+      glReadBuffer(GL_FRONT);
+      p -= Point3f(.5f, .5f, .5f);
+    } else if(mesh->isSurfaceVisible() and !S.empty()) {
+      std::vector<uint> vList;
+      int label;
+      findSelectTriangle(x, y, vList, label);
+      if(vList.empty())
+        return (false);
+      forall(uint u, vList) {
+        if(u < idVA.size()) {
+          vertex v = idVA[u];
+          p += v->pos;
+        }
       }
+      p /= vList.size();
     }
-    p /= vList.size();
+    return (true);
   }
-  return (true);
-}
-
-void ImgData::updateSelection()
-{
-  vvgraph& S = mesh->graph();
-  selectV.clear();
-  pselVA.clear();
-  lselVA.clear();
-  for(uint u = 0; u < pidVA.size(); ++u) {
-    vertex v = pidVA[u];
-    if(v->selected) {
-      selectV.insert(u);
-      pselVA.push_back(v->saveId);
-      forall(const vertex& n, S.neighbors(v)) {
-        lselVA.push_back(v->saveId);
-        lselVA.push_back(n->saveId);
+  
+  void ImgData::updateSelection()
+  {
+    vvgraph& S = mesh->graph();
+    selectV.clear();
+    pselVA.clear();
+    lselVA.clear();
+    for(uint u = 0; u < pidVA.size(); ++u) {
+      vertex v = pidVA[u];
+      if(v->selected) {
+        selectV.insert(u);
+        pselVA.push_back(v->saveId);
+        forall(const vertex& n, S.neighbors(v)) {
+          lselVA.push_back(v->saveId);
+          lselVA.push_back(n->saveId);
+        }
       }
     }
+    updColor();
+    postUpdateImgData(true, false);
   }
-  updColor();
-  postUpdateImgData(true, false);
-}
-
-// Clear mesh selection
-void ImgData::clearMeshSelect()
-{
-  std::vector<uint> vList;
-  forall(uint u, selectV) {
-    vertex v = pidVA[u];
-    if(v->selected) {
-      v->selected = false;
-      vList.push_back(u);
+  
+  // Clear mesh selection
+  void ImgData::clearMeshSelect()
+  {
+    std::vector<uint> vList;
+    forall(uint u, selectV) {
+      vertex v = pidVA[u];
+      if(v->selected) {
+        v->selected = false;
+        vList.push_back(u);
+      }
     }
+    selectV.clear();
+    if(vList.size() > 0)
+      updColor(vList);
+    pselVA.clear();
+    lselVA.clear();
+    postUpdateImgData(true, false);
   }
-  selectV.clear();
-  if(vList.size() > 0)
-    updColor(vList);
-  pselVA.clear();
-  lselVA.clear();
-  postUpdateImgData(true, false);
-}
-
-// Remove points from selection
-void ImgData::removeSelect(const std::vector<uint>& vList)
-{
-  forall(uint u, vList) {
-    if(u >= pidVA.size())
-      continue;
-    vertex v = pidVA[u];
-    v->selected = false;
-  }
-  updateSelection();
-}
-
-// Add point to selection
-void ImgData::addSelect(const std::vector<uint>& vList)
-{
-  std::vector<uint> slist;
-  forall(uint u, vList) {
-    if(u >= pidVA.size())
-      continue;
-    vertex v = pidVA[u];
-    std::set<uint>::iterator i = selectV.find(u);
-    if(i == selectV.end()) {
-      selectV.insert(u);
-      if(!v->selected) {
-        v->selected = true;
-        slist.push_back(u);
-      }
+  
+  // Remove points from selection
+  void ImgData::removeSelect(const std::vector<uint>& vList)
+  {
+    forall(uint u, vList) {
+      if(u >= pidVA.size())
+        continue;
+      vertex v = pidVA[u];
+      v->selected = false;
     }
+    updateSelection();
   }
-  if(selectV.size() == 1) {
-    SETSTATUS("Vertex label: " << pidVA[*(selectV.begin())]->label);
-  } else if(selectV.size() == 2) {
-    std::set<uint>::iterator i = selectV.begin();
-    vertex v1 = pidVA[*i++];
-    vertex v2 = pidVA[*i];
-    SETSTATUS("Distance bewteen vertices: " << (v1->pos - v2->pos).norm() << "um");
-  } else
-    SETSTATUS(selectV.size() << " vertex(es) selected");
-
-  vvgraph& S = mesh->graph();
-  if(slist.size() > 0) {
-    forall(uint u, slist) {
+  
+  // Add point to selection
+  void ImgData::addSelect(const std::vector<uint>& vList)
+  {
+    std::vector<uint> slist;
+    forall(uint u, vList) {
+      if(u >= pidVA.size())
+        continue;
       vertex v = pidVA[u];
-      pselVA.push_back(u);
-      forall(const vertex& n, S.neighbors(v)) {
-        lselVA.push_back(u);
-        lselVA.push_back(n->saveId);
+      std::set<uint>::iterator i = selectV.find(u);
+      if(i == selectV.end()) {
+        selectV.insert(u);
+        if(!v->selected) {
+          v->selected = true;
+          slist.push_back(u);
+        }
       }
     }
-    updColor(vList);
-    postUpdateImgData(true, false);
+    if(selectV.size() == 1) {
+      SETSTATUS("Vertex label: " << pidVA[*(selectV.begin())]->label);
+    } else if(selectV.size() == 2) {
+      std::set<uint>::iterator i = selectV.begin();
+      vertex v1 = pidVA[*i++];
+      vertex v2 = pidVA[*i];
+      SETSTATUS("Distance bewteen vertices: " << (v1->pos - v2->pos).norm() << "um");
+    } else
+      SETSTATUS(selectV.size() << " vertex(es) selected");
+  
+    vvgraph& S = mesh->graph();
+    if(slist.size() > 0) {
+      forall(uint u, slist) {
+        vertex v = pidVA[u];
+        pselVA.push_back(u);
+        forall(const vertex& n, S.neighbors(v)) {
+          lselVA.push_back(u);
+          lselVA.push_back(n->saveId);
+        }
+      }
+      updColor(vList);
+      postUpdateImgData(true, false);
+    }
   }
-}
-
-void ImgData::updColor()
-{
-  std::vector<uint> idx(pidVA.size());
-  for(uint i = 0; i < pidVA.size(); ++i)
-    idx[i] = i;
-  updColor(idx);
-}
-
-// Update selection colors for points
-void ImgData::updColor(const std::vector<uint>& vList)
-{
-  if(vList.empty())
-    return;
-
-  forall(uint u, vList) {
-    vertex v = pidVA[u];
-    pcolVA[u] = pColor(v);
+  
+  void ImgData::updColor()
+  {
+    std::vector<uint> idx(pidVA.size());
+    for(uint i = 0; i < pidVA.size(); ++i)
+      idx[i] = i;
+    updColor(idx);
   }
-
-  // Write color data to video memory
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, pcolVAid);
-  Point3GLub* cp = (Point3GLub*)(glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB));
-  if(!cp) {
-    REPORT_GL_ERROR("glMapBufferARB(pcolVAid) - using glBufferDataARB");
-    glBufferDataARB(GL_ARRAY_BUFFER_ARB, pcolVA.size() * sizeof(Point3GLub), &pcolVA[0], GL_STATIC_DRAW_ARB);
-  } else {
-    forall(uint u, vList)
-      cp[u] = pcolVA[u];
-    glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
+  
+  // Update selection colors for points
+  void ImgData::updColor(const std::vector<uint>& vList)
+  {
+    if(vList.empty())
+      return;
+  
+    forall(uint u, vList) {
+      vertex v = pidVA[u];
+      pcolVA[u] = pColor(v);
+    }
+  
+    // Write color data to video memory
+    glBindBufferARB(GL_ARRAY_BUFFER_ARB, pcolVAid);
+    Point3GLub* cp = (Point3GLub*)(glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB));
+    if(!cp) {
+      REPORT_GL_ERROR("glMapBufferARB(pcolVAid) - using glBufferDataARB");
+      glBufferDataARB(GL_ARRAY_BUFFER_ARB, pcolVA.size() * sizeof(Point3GLub), &pcolVA[0], GL_STATIC_DRAW_ARB);
+    } else {
+      forall(uint u, vList)
+        cp[u] = pcolVA[u];
+      glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
+    }
+    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
   }
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
-}
-
-// Update a list of vertex labels
-void ImgData::updLabel(int label, std::vector<uint>& vList)
-{
-  // Update vertex arrays
-  bool changed = false;
-  std::set<vertex> M;
-  forall(uint u, vList) {
-    vertex v(idVA[u]);
-    if((!mesh->cells() or v->type == 'c')) {
-      v->label = label;
-      M.insert(v);
-      changed = true;
+  
+  // Update a list of vertex labels
+  void ImgData::updLabel(int label, std::vector<uint>& vList)
+  {
+    // Update vertex arrays
+    bool changed = false;
+    std::set<vertex> M;
+    forall(uint u, vList) {
+      vertex v(idVA[u]);
+      if((!mesh->cells() or v->type == 'c')) {
+        v->label = label;
+        M.insert(v);
+        changed = true;
+      }
+      texVA[u] = texCoord(label, v);
     }
-    texVA[u] = texCoord(label, v);
+    if(!changed)
+      return;
+  
+    markMargin(M, true);
+    needUpdateLines = true;
+  
+    // Write texture data to video memory
+    glBindBufferARB(GL_ARRAY_BUFFER_ARB, texVAid);
+    Point3f* tp = (Point3f*)(glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB));
+    if(!tp) {
+      REPORT_GL_ERROR("glMapBufferARB(texVAid) - using glBufferDataARB");
+      glBufferDataARB(GL_ARRAY_BUFFER_ARB, texVA.size() * sizeof(Point3f), &texVA[0], GL_STATIC_DRAW_ARB);
+    } else {
+      forall(uint u, vList)
+        tp[u] = texVA[u];
+      glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
+    }
+  
+    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
   }
-  if(!changed)
-    return;
-
-  markMargin(M, true);
-  needUpdateLines = true;
-
-  // Write texture data to video memory
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, texVAid);
-  Point3f* tp = (Point3f*)(glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB));
-  if(!tp) {
-    REPORT_GL_ERROR("glMapBufferARB(texVAid) - using glBufferDataARB");
-    glBufferDataARB(GL_ARRAY_BUFFER_ARB, texVA.size() * sizeof(Point3f), &texVA[0], GL_STATIC_DRAW_ARB);
-  } else {
-    forall(uint u, vList)
-      tp[u] = texVA[u];
-    glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
+  
+  void ImgData::updateHistogram(std::vector<double>& hist, const HVecUS& data, std::pair<double, double>& minMaxValues,
+                                int max_data, int size)
+  {
+    hist.clear();
+    if(data.empty())
+      return;
+    hist.resize(size, 0);
+    minMaxValues.first = HUGE_VAL;
+    minMaxValues.second = -HUGE_VAL;
+    for(HVecUS::const_iterator it = data.begin(); it != data.end(); ++it) {
+      int val = (*it * size) / max_data;
+      hist[val]++;
+      if(*it < minMaxValues.first)
+        minMaxValues.first = *it;
+      if(*it > minMaxValues.second)
+        minMaxValues.second = *it;
+    }
+    minMaxValues.first /= max_data;
+    minMaxValues.second /= max_data;
   }
-
-  glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
-}
-
-void ImgData::updateHistogram(std::vector<double>& hist, const HVecUS& data, std::pair<double, double>& minMaxValues,
-                              int max_data, int size)
-{
-  hist.clear();
-  if(data.empty())
-    return;
-  hist.resize(size, 0);
-  minMaxValues.first = HUGE_VAL;
-  minMaxValues.second = -HUGE_VAL;
-  for(HVecUS::const_iterator it = data.begin(); it != data.end(); ++it) {
-    int val = (*it * size) / max_data;
-    hist[val]++;
-    if(*it < minMaxValues.first)
-      minMaxValues.first = *it;
-    if(*it > minMaxValues.second)
-      minMaxValues.second = *it;
-  }
-  minMaxValues.first /= max_data;
-  minMaxValues.second /= max_data;
-}
-
-// Add a triangle to the VV mesh when converting from triangle list (triangles must be oriented)
-bool ImgData::addTriangle(std::vector<vertex>& vertices, Point3i tri)
-{
-  vertex x = vertices[tri.x()];
-  vertex y = vertices[tri.y()];
-  vertex z = vertices[tri.z()];
-  vvgraph& S = mesh->graph();
-  if(S.valence(x) == 0) {
-    S.insertEdge(x, y);
-    S.spliceAfter(x, y, z);
-  } else {
-    bool yinx = S.edge(x, y);
-    bool zinx = S.edge(x, z);
-
-    if(yinx and zinx) {     // Triangle already there
-      if(S.nextTo(x, y) != z)
-        SETSTATUS("addTriangle::Error:Error in nhbd");
-      return true;
-    } else if(yinx) {
+  
+  // Add a triangle to the VV mesh when converting from triangle list (triangles must be oriented)
+  bool ImgData::addTriangle(std::vector<vertex>& vertices, Point3i tri)
+  {
+    vertex x = vertices[tri.x()];
+    vertex y = vertices[tri.y()];
+    vertex z = vertices[tri.z()];
+    vvgraph& S = mesh->graph();
+    if(S.valence(x) == 0) {
+      S.insertEdge(x, y);
       S.spliceAfter(x, y, z);
-      return true;
-    } else if(zinx) {
-      S.spliceBefore(x, z, y);
-      return true;
+    } else {
+      bool yinx = S.edge(x, y);
+      bool zinx = S.edge(x, z);
+  
+      if(yinx and zinx) {     // Triangle already there
+        if(S.nextTo(x, y) != z)
+          SETSTATUS("addTriangle::Error:Error in nhbd");
+        return true;
+      } else if(yinx) {
+        S.spliceAfter(x, y, z);
+        return true;
+      } else if(zinx) {
+        S.spliceBefore(x, z, y);
+        return true;
+      }
     }
+    return false;   // Did not insert triangle
   }
-  return false;   // Did not insert triangle
-}
-
-// Create a mesh from vertex and triangle lists
-void ImgData::meshFromTriangles(std::vector<vertex>& vertices, std::vector<Point3i>& triangles)
-{
-  vvgraph& S = mesh->graph();
-  // Insert vertices into mesh
-  forall(const vertex& v, vertices)
-    S.insert(v);
-
-  // Make triangle list with all orientations.
-  std::vector<Point3i> tris;
-  forall(const Point3i tri, triangles) {
-    tris.push_back(tri);
-    tris.push_back(Point3i(tri.y(), tri.z(), tri.x()));
-    tris.push_back(Point3i(tri.z(), tri.x(), tri.y()));
-  }
-
-  // Extract neighborhood from triangles,  make multiple passes until list empty
-  int count = 1;
-  int totcnt = 0;
-  while(count > 0) {
-    count = 0;
-    for(size_t i = 0; i < tris.size(); i++) {
-      if(tris[i] != Point3i(0, 0, 0)) {
-        if(addTriangle(vertices, tris[i])) {
-          count++;
-          tris[i] = Point3i(0, 0, 0);
+  
+  // Create a mesh from vertex and triangle lists
+  void ImgData::meshFromTriangles(std::vector<vertex>& vertices, std::vector<Point3i>& triangles)
+  {
+    vvgraph& S = mesh->graph();
+    // Insert vertices into mesh
+    forall(const vertex& v, vertices)
+      S.insert(v);
+  
+    // Make triangle list with all orientations.
+    std::vector<Point3i> tris;
+    forall(const Point3i tri, triangles) {
+      tris.push_back(tri);
+      tris.push_back(Point3i(tri.y(), tri.z(), tri.x()));
+      tris.push_back(Point3i(tri.z(), tri.x(), tri.y()));
+    }
+  
+    // Extract neighborhood from triangles,  make multiple passes until list empty
+    int count = 1;
+    int totcnt = 0;
+    while(count > 0) {
+      count = 0;
+      for(size_t i = 0; i < tris.size(); i++) {
+        if(tris[i] != Point3i(0, 0, 0)) {
+          if(addTriangle(vertices, tris[i])) {
+            count++;
+            tris[i] = Point3i(0, 0, 0);
+          }
         }
       }
+      totcnt += count;
     }
-    totcnt += count;
   }
-}
-
-// Check graph for missing edges
-void ImgData::chkGraph()
-{
-  vvgraph& S = mesh->graph();
-  int count = 0;
-  forall(const vertex& v, S)
-    forall(const vertex& n, S.neighbors(v))
-      if(!S.edge(n, v))
-        count++;
-
-  if(count > 0)
-    SETSTATUS("chkGraph::Warning:Mesh has " << count << " missing edges");
-
-  forall(const vertex& v, S) {
-    float norm = v->pos.norm();
-    if(norm == norm)
-      ;
-    else
-      SETSTATUS("chkGraph::Warning:Bad vertex (nan)");
+  
+  // Check graph for missing edges
+  void ImgData::chkGraph()
+  {
+    vvgraph& S = mesh->graph();
+    int count = 0;
+    forall(const vertex& v, S)
+      forall(const vertex& n, S.neighbors(v))
+        if(!S.edge(n, v))
+          count++;
+  
+    if(count > 0)
+      SETSTATUS("chkGraph::Warning:Mesh has " << count << " missing edges");
+  
+    forall(const vertex& v, S) {
+      float norm = v->pos.norm();
+      if(norm == norm)
+        ;
+      else
+        SETSTATUS("chkGraph::Warning:Bad vertex (nan)");
+    }
   }
-}
-
-// Mark margin vertices and border labels
-void ImgData::markMargin(std::set<vertex>& M, bool remborders)
-{
-  vvgraph& S = mesh->graph();
-  if(M.empty() or S.empty())
-    return;
-
-  // Mark margin and borders
-  forall(const vertex& v, M) {
-    v->margin = false;
-    // All vertices with valence <= 2 are border and margin
-    if(S.valence(v) <= 2) {
-      v->margin = true;
-      if(v->type != 'l')
-        v->label = -1;
-      continue;
-    }
-
-    int label = 0, labcount = 0, zcount = 0;
-    forall(const vertex& n, S.neighbors(v)) {
-      // If there is no edge between a pair of vertices next to each other
-      // in a neighborhood, they must be on the margin
-      vertex m = S.nextTo(v, n);
-      if(!S.edge(n, m)) {
+  
+  // Mark margin vertices and border labels
+  void ImgData::markMargin(std::set<vertex>& M, bool remborders)
+  {
+    vvgraph& S = mesh->graph();
+    if(M.empty() or S.empty())
+      return;
+  
+    // Mark margin and borders
+    forall(const vertex& v, M) {
+      v->margin = false;
+      // All vertices with valence <= 2 are border and margin
+      if(S.valence(v) <= 2) {
         v->margin = true;
         if(v->type != 'l')
           v->label = -1;
-        break;
+        continue;
       }
-      if(n->label == 0)
-        zcount++;
-      else if(n->label > 0 and n->label != label) {
-        labcount++;
-        label = n->label;
+  
+      int label = 0, labcount = 0, zcount = 0;
+      forall(const vertex& n, S.neighbors(v)) {
+        // If there is no edge between a pair of vertices next to each other
+        // in a neighborhood, they must be on the margin
+        vertex m = S.nextTo(v, n);
+        if(!S.edge(n, m)) {
+          v->margin = true;
+          if(v->type != 'l')
+            v->label = -1;
+          break;
+        }
+        if(n->label == 0)
+          zcount++;
+        else if(n->label > 0 and n->label != label) {
+          labcount++;
+          label = n->label;
+        }
       }
+      // Margin vertices always have border label
+      if(v->margin)
+        continue;
+      // Adjacent to more than one label means a cell boundary
+      if(labcount > 1 and v->type != 'l')
+        v->label = -1;
+      // Clear hanging border lines,
+      if(v->label == -1 and remborders) {
+        // On zero labeled area, only clear if remborders set (so we can draw)
+        if(labcount == 0)
+          v->label = 0;
+        else if(labcount == 1 and zcount == 0)
+          v->label = label;
+      }
     }
-    // Margin vertices always have border label
-    if(v->margin)
-      continue;
-    // Adjacent to more than one label means a cell boundary
-    if(labcount > 1 and v->type != 'l')
-      v->label = -1;
-    // Clear hanging border lines,
-    if(v->label == -1 and remborders) {
-      // On zero labeled area, only clear if remborders set (so we can draw)
-      if(labcount == 0)
-        v->label = 0;
-      else if(labcount == 1 and zcount == 0)
-        v->label = label;
+  }
+  
+  // Project signal onto mesh vertices
+  void ImgData::projSignal(HVecUS& data, vertex v, float mindist, float maxdist)
+  {
+    Point3f vpos = divide(v->pos, stack->scale());
+    Point3f vnrml = divide(v->nrml, stack->scale());
+    // ALR: why do we divide pos and nrml again by scale?
+    if(stack->scale() != Point3f(1.0, 1.0, 1.0)) {
+      vpos = divide(vpos, stack->scale());
+      vnrml = divide(vnrml, stack->scale());
     }
+    Point3f pmin = (vpos - vnrml * mindist);
+    Point3f pmax = (vpos - vnrml * maxdist);
+    // Point3i vi = worldToImagei(vpos);
+    Point3i pimin = worldToImagei(pmin);
+    Point3i pimax = worldToImagei(pmax);
+    int steps = int((pimax - pimin).norm() * 2 + 3);
+  
+    float sum = 0;
+    for(int i = 0; i <= steps; i++) {
+      Point3i oi = worldToImagei(pmax + v->nrml * (maxdist - mindist) * float(i) / float(steps));
+      if(boundsOK(oi.x(), oi.y(), oi.z()))
+        sum += data[offset(oi.x(), oi.y(), oi.z())];
+    }
+    v->signal = float(sum) / float(steps);
   }
-}
-
-// Project signal onto mesh vertices
-void ImgData::projSignal(HVecUS& data, vertex v, float mindist, float maxdist)
-{
-  Point3f vpos = divide(v->pos, stack->scale());
-  Point3f vnrml = divide(v->nrml, stack->scale());
-  // ALR: why do we divide pos and nrml again by scale?
-  if(stack->scale() != Point3f(1.0, 1.0, 1.0)) {
-    vpos = divide(vpos, stack->scale());
-    vnrml = divide(vnrml, stack->scale());
+  
+  void ImgData::updateSurfHistogram()
+  {
+    if(SurfHist.empty()) {
+      // TODO
+    }
   }
-  Point3f pmin = (vpos - vnrml * mindist);
-  Point3f pmax = (vpos - vnrml * maxdist);
-  // Point3i vi = worldToImagei(vpos);
-  Point3i pimin = worldToImagei(pmin);
-  Point3i pimax = worldToImagei(pmax);
-  int steps = int((pimax - pimin).norm() * 2 + 3);
-
-  float sum = 0;
-  for(int i = 0; i <= steps; i++) {
-    Point3i oi = worldToImagei(pmax + v->nrml * (maxdist - mindist) * float(i) / float(steps));
-    if(boundsOK(oi.x(), oi.y(), oi.z()))
-      sum += data[offset(oi.x(), oi.y(), oi.z())];
+  
+  void ImgData::updateHeatHistogram()
+  {
+    if(HeatHist.empty()) {
+      // TODO
+    }
   }
-  v->signal = float(sum) / float(steps);
-}
-
-void ImgData::updateSurfHistogram()
-{
-  if(SurfHist.empty()) {
-    // TODO
+  void ImgData::updateWorkHistogram()
+  {
+    if(WorkHist.empty())
+      updateHistogram(WorkHist, stack->work()->data(), workBounds);
   }
-}
-
-void ImgData::updateHeatHistogram()
-{
-  if(HeatHist.empty()) {
-    // TODO
+  
+  void ImgData::updateMainHistogram()
+  {
+    if(MainHist.empty())
+      updateHistogram(MainHist, stack->main()->data(), mainBounds);
   }
-}
-void ImgData::updateWorkHistogram()
-{
-  if(WorkHist.empty())
-    updateHistogram(WorkHist, stack->work()->data(), workBounds);
-}
-
-void ImgData::updateMainHistogram()
-{
-  if(MainHist.empty())
-    updateHistogram(MainHist, stack->main()->data(), mainBounds);
-}
-
-void ImgData::editMainTransferFunction(QWidget*)
-{
-  updateMainHistogram();
-  mainTransferDlg->changeHistogram(MainHist);
-  mainTransferDlg->changeBounds(mainBounds);
-  mainTransferDlg->setTransferFunction(stack->main()->transferFct());
-  if(mainTransferDlg->exec() == QDialog::Accepted) {
-    emit changedInterface();
-    stack->main()->setTransferFct(mainTransferDlg->transferFunction());
-    updateMainColorMap();
+  
+  void ImgData::editMainTransferFunction(QWidget*)
+  {
+    updateMainHistogram();
+    mainTransferDlg->changeHistogram(MainHist);
+    mainTransferDlg->changeBounds(mainBounds);
+    mainTransferDlg->setTransferFunction(stack->main()->transferFct());
+    if(mainTransferDlg->exec() == QDialog::Accepted) {
+      emit changedInterface();
+      stack->main()->setTransferFct(mainTransferDlg->transferFunction());
+      updateMainColorMap();
+    }
   }
-}
-
-void ImgData::editWorkTransferFunction(QWidget*)
-{
-  updateWorkHistogram();
-  workTransferDlg->changeHistogram(WorkHist);
-  workTransferDlg->changeBounds(workBounds);
-  workTransferDlg->setTransferFunction(stack->work()->transferFct());
-  if(workTransferDlg->exec() == QDialog::Accepted) {
-    emit changedInterface();
-    stack->work()->setTransferFct(workTransferDlg->transferFunction());
+  
+  void ImgData::editWorkTransferFunction(QWidget*)
+  {
+    updateWorkHistogram();
+    workTransferDlg->changeHistogram(WorkHist);
+    workTransferDlg->changeBounds(workBounds);
+    workTransferDlg->setTransferFunction(stack->work()->transferFct());
+    if(workTransferDlg->exec() == QDialog::Accepted) {
+      emit changedInterface();
+      stack->work()->setTransferFct(workTransferDlg->transferFunction());
+      updateWorkColorMap();
+    }
+  }
+  
+  void ImgData::editSurfTransferFunction(QWidget*)
+  {
+    updateSurfHistogram();
+    surfTransferDlg->changeHistogram(SurfHist);
+    surfTransferDlg->setTransferFunction(mesh->surfFct());
+    if(surfTransferDlg->exec() == QDialog::Accepted) {
+      emit changedInterface();
+      mesh->setSurfFct(surfTransferDlg->transferFunction());
+      updateSurfColorMap();
+    }
+  }
+  
+  void ImgData::editHeatTransferFunction(QWidget*)
+  {
+    updateHeatHistogram();
+    heatTransferDlg->changeHistogram(HeatHist);
+    heatTransferDlg->setTransferFunction(mesh->heatFct());
+    if(heatTransferDlg->exec() == QDialog::Accepted) {
+      emit changedInterface();
+      mesh->setHeatFct(heatTransferDlg->transferFunction());
+      updateHeatColorMap();
+    }
+  }
+  
+  void ImgData::updateColorMap(bool& newColorMap, std::vector<TransferFunction::Colorf>& ColorMap,
+                               const TransferFunction& transferFct)
+  {
+    static const int n = 4096;
+    ColorMap.resize(n);
+    double dc = 1.0 / (n - 1);
+    for(int i = 0; i < n; ++i) {
+      ColorMap[i] = transferFct.rgba(i * dc);
+    }
+    newColorMap = true;
+  }
+  
+  void ImgData::setupColorMap(bool& newColorMap, GLuint& texId, const std::vector<TransferFunction::Colorf>& ColorMap,
+                              Shader::ActiveTextures activeTex)
+  {
+    if(newColorMap or !texId) {
+      newColorMap = false;
+      if(!texId)
+        glGenTextures(1, &texId);
+      glBindTexture(GL_TEXTURE_1D, texId);
+      glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA16, ColorMap.size(), 0, GL_RGBA, GL_FLOAT, &ColorMap[0]);
+      glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+      glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+      glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+      glBindTexture(GL_TEXTURE_1D, 0);
+    }
+    Shader::activeTexture(activeTex);
+    glBindTexture(GL_TEXTURE_1D, texId);
+    Shader::activeTexture(Shader::AT_NONE);
+  }
+  
+  void ImgData::updateWorkColorMap(const TransferFunction& fct)
+  {
+    stack->work()->setTransferFct(fct);
     updateWorkColorMap();
   }
-}
-
-void ImgData::editSurfTransferFunction(QWidget*)
-{
-  updateSurfHistogram();
-  surfTransferDlg->changeHistogram(SurfHist);
-  surfTransferDlg->setTransferFunction(mesh->surfFct());
-  if(surfTransferDlg->exec() == QDialog::Accepted) {
-    emit changedInterface();
-    mesh->setSurfFct(surfTransferDlg->transferFunction());
+  
+  void ImgData::updateMainColorMap(const TransferFunction& fct)
+  {
+    stack->main()->setTransferFct(fct);
+    updateMainColorMap();
+  }
+  
+  void ImgData::updateSurfColorMap(const TransferFunction& fct)
+  {
+    mesh->setSurfFct(fct);
     updateSurfColorMap();
   }
-}
-
-void ImgData::editHeatTransferFunction(QWidget*)
-{
-  updateHeatHistogram();
-  heatTransferDlg->changeHistogram(HeatHist);
-  heatTransferDlg->setTransferFunction(mesh->heatFct());
-  if(heatTransferDlg->exec() == QDialog::Accepted) {
-    emit changedInterface();
-    mesh->setHeatFct(heatTransferDlg->transferFunction());
+  
+  void ImgData::updateHeatColorMap(const TransferFunction& fct)
+  {
+    mesh->setHeatFct(fct);
     updateHeatColorMap();
   }
-}
-
-void ImgData::updateColorMap(bool& newColorMap, std::vector<TransferFunction::Colorf>& ColorMap,
-                             const TransferFunction& transferFct)
-{
-  static const int n = 4096;
-  ColorMap.resize(n);
-  double dc = 1.0 / (n - 1);
-  for(int i = 0; i < n; ++i) {
-    ColorMap[i] = transferFct.rgba(i * dc);
+  
+  void ImgData::setColorMap(const QString& pth, bool work)
+  {
+    QFile f(pth);
+    if(!f.open(QIODevice::ReadOnly)) {
+      err << "Error, cannot open file '" << pth << "' for reading" << endl;
+      return;
+    }
+    QTextStream ts(&f);
+    QString content = ts.readAll();
+    TransferFunction fct = TransferFunction::load(content);
+    if(fct.empty()) {
+      err << "Error, file '" << pth << "' doesn't contain a valid transfer function" << endl;
+      return;
+    }
+    if(work)
+      workTransferDlg->setTransferFunction(fct);
+    else
+      mainTransferDlg->setTransferFunction(fct);
   }
-  newColorMap = true;
-}
-
-void ImgData::setupColorMap(bool& newColorMap, GLuint& texId, const std::vector<TransferFunction::Colorf>& ColorMap,
-                            Shader::ActiveTextures activeTex)
-{
-  if(newColorMap or !texId) {
-    newColorMap = false;
-    if(!texId)
-      glGenTextures(1, &texId);
-    glBindTexture(GL_TEXTURE_1D, texId);
-    glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA16, ColorMap.size(), 0, GL_RGBA, GL_FLOAT, &ColorMap[0]);
-    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
-    glBindTexture(GL_TEXTURE_1D, 0);
+  
+  void ImgData::setWork16Bit(bool val)
+  {
+    if(val != Work16Bit) {
+      Work16Bit = val;
+      reloadTex(workDataTexId);
+    }
   }
-  Shader::activeTexture(activeTex);
-  glBindTexture(GL_TEXTURE_1D, texId);
-  Shader::activeTexture(Shader::AT_NONE);
-}
-
-void ImgData::updateWorkColorMap(const TransferFunction& fct)
-{
-  stack->work()->setTransferFct(fct);
-  updateWorkColorMap();
-}
-
-void ImgData::updateMainColorMap(const TransferFunction& fct)
-{
-  stack->main()->setTransferFct(fct);
-  updateMainColorMap();
-}
-
-void ImgData::updateSurfColorMap(const TransferFunction& fct)
-{
-  mesh->setSurfFct(fct);
-  updateSurfColorMap();
-}
-
-void ImgData::updateHeatColorMap(const TransferFunction& fct)
-{
-  mesh->setHeatFct(fct);
-  updateHeatColorMap();
-}
-
-void ImgData::setColorMap(const QString& pth, bool work)
-{
-  QFile f(pth);
-  if(!f.open(QIODevice::ReadOnly)) {
-    err << "Error, cannot open file '" << pth << "' for reading" << endl;
-    return;
+  
+  void ImgData::setMain16Bit(bool val)
+  {
+    if(val != Main16Bit) {
+      Main16Bit = val;
+      reloadTex(mainDataTexId);
+    }
   }
-  QTextStream ts(&f);
-  QString content = ts.readAll();
-  TransferFunction fct = TransferFunction::load(content);
-  if(fct.empty()) {
-    err << "Error, file '" << pth << "' doesn't contain a valid transfer function" << endl;
-    return;
+  
+  // Return texture info for a vertex, used when triangle context not known (messes up wall heat map)
+  Point3f ImgData::texCoord(int label, vertex v)
+  {
+    if(label <= 0)
+      return Point3f(0.0f, v->signal, 0.0f);
+  
+    const IntFloatMap& LabelHeat = mesh->labelHeat();
+    float retlab = float(label);
+    const Point2f& heatMapBounds = mesh->heatMapBounds();
+    IntFloatMap::const_iterator found = LabelHeat.find(label);
+    if(found == LabelHeat.end())
+      return Point3f(retlab, v->signal, 0.0f);
+  
+    // Vertex has a cell based heatmap
+    float heat = trim(found->second, heatMapBounds[0], heatMapBounds[1]);
+    // Use a negative label to represent a valid heat value
+    return Point3f(-retlab, v->signal, heat);
   }
-  if(work)
-    workTransferDlg->setTransferFunction(fct);
-  else
-    mainTransferDlg->setTransferFunction(fct);
-}
-
-void ImgData::setWork16Bit(bool val)
-{
-  if(val != Work16Bit) {
-    Work16Bit = val;
-    reloadTex(workDataTexId);
+  
+  // Return texture info for a vertex with triangle context. This allows to color walls.
+  Point3f ImgData::texCoord(int label, vertex v, vertex a, vertex b, vertex c)
+  {
+    const IntIntFloatMap& WallHeat = mesh->wallHeat();
+    if(WallHeat.empty())
+      return texCoord(label, v);
+  
+    IntIntPair wall;
+    const Point2f& heatMapBounds = mesh->heatMapBounds();
+    float retlab = float(label);
+    bool is_bord = isBordTriangle(label, a, b, c, wall);
+    IntIntFloatMap::const_iterator found = WallHeat.end();
+    if(is_bord)
+      found = WallHeat.find(wall);
+    if(found == WallHeat.end())
+      return Point3f(retlab, v->signal, 0.0f);
+  
+    // Vertex has a wall heat
+    float heat = trim(found->second, heatMapBounds[0], heatMapBounds[1]);
+    return Point3f(-retlab, v->signal, heat);
   }
-}
-
-void ImgData::setMain16Bit(bool val)
-{
-  if(val != Main16Bit) {
-    Main16Bit = val;
-    reloadTex(mainDataTexId);
+  
+  // Slots for stack controls
+  // Main stack
+  void ImgData::MainShowSlot(bool val)
+  {
+    if(val != stack->main()->isVisible()) {
+      if(val)
+        stack->main()->show();
+      else
+        stack->main()->hide();
+      emit changedInterface();
+      emit viewerUpdate();
+    }
   }
-}
-
-// Return texture info for a vertex, used when triangle context not known (messes up wall heat map)
-Point3f ImgData::texCoord(int label, vertex v)
-{
-  if(label <= 0)
-    return Point3f(0.0f, v->signal, 0.0f);
-
-  const IntFloatMap& LabelHeat = mesh->labelHeat();
-  float retlab = float(label);
-  const Point2f& heatMapBounds = mesh->heatMapBounds();
-  IntFloatMap::const_iterator found = LabelHeat.find(label);
-  if(found == LabelHeat.end())
-    return Point3f(retlab, v->signal, 0.0f);
-
-  // Vertex has a cell based heatmap
-  float heat = trim(found->second, heatMapBounds[0], heatMapBounds[1]);
-  // Use a negative label to represent a valid heat value
-  return Point3f(-retlab, v->signal, heat);
-}
-
-// Return texture info for a vertex with triangle context. This allows to color walls.
-Point3f ImgData::texCoord(int label, vertex v, vertex a, vertex b, vertex c)
-{
-  const IntIntFloatMap& WallHeat = mesh->wallHeat();
-  if(WallHeat.empty())
-    return texCoord(label, v);
-
-  IntIntPair wall;
-  const Point2f& heatMapBounds = mesh->heatMapBounds();
-  float retlab = float(label);
-  bool is_bord = isBordTriangle(label, a, b, c, wall);
-  IntIntFloatMap::const_iterator found = WallHeat.end();
-  if(is_bord)
-    found = WallHeat.find(wall);
-  if(found == WallHeat.end())
-    return Point3f(retlab, v->signal, 0.0f);
-
-  // Vertex has a wall heat
-  float heat = trim(found->second, heatMapBounds[0], heatMapBounds[1]);
-  return Point3f(-retlab, v->signal, heat);
-}
-
-// Slots for stack controls
-// Main stack
-void ImgData::MainShowSlot(bool val)
-{
-  if(val != stack->main()->isVisible()) {
-    if(val)
-      stack->main()->show();
-    else
-      stack->main()->hide();
-    emit changedInterface();
-    emit viewerUpdate();
+  
+  void ImgData::MainBrightSlot(int val)
+  {
+    float v = float(val) / 10000.0;
+    if(stack->main()->brightness() != v) {
+      stack->main()->setBrightness(v);
+      emit changedInterface();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::MainBrightSlot(int val)
-{
-  float v = float(val) / 10000.0;
-  if(stack->main()->brightness() != v) {
-    stack->main()->setBrightness(v);
-    emit changedInterface();
-    emit viewerUpdate();
+  
+  void ImgData::MainOpacitySlot(int val)
+  {
+    float v = float(val) / 10000.0;
+    if(stack->main()->opacity() != v) {
+      stack->main()->setOpacity(v);
+      emit changedInterface();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::MainOpacitySlot(int val)
-{
-  float v = float(val) / 10000.0;
-  if(stack->main()->opacity() != v) {
-    stack->main()->setOpacity(v);
-    emit changedInterface();
-    emit viewerUpdate();
+  
+  void ImgData::MainLabelsSlot(bool val)
+  {
+    if(val != stack->main()->labels()) {
+      emit changedInterface();
+      stack->main()->setLabels(val);
+      reloadMainTex();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::MainLabelsSlot(bool val)
-{
-  if(val != stack->main()->labels()) {
-    emit changedInterface();
-    stack->main()->setLabels(val);
-    reloadMainTex();
-    emit viewerUpdate();
+  
+  void ImgData::Main16BitSlot(bool val)
+  {
+    if(val != Main16Bit) {
+      emit changedInterface();
+      Main16Bit = val;
+      reloadMainTex();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::Main16BitSlot(bool val)
-{
-  if(val != Main16Bit) {
-    emit changedInterface();
-    Main16Bit = val;
-    reloadMainTex();
-    emit viewerUpdate();
+  
+  // Work stack
+  void ImgData::WorkShowSlot(bool val)
+  {
+    if(val != stack->work()->isVisible()) {
+      emit changedInterface();
+      if(val)
+        stack->work()->show();
+      else
+        stack->work()->hide();
+      emit viewerUpdate();
+    }
   }
-}
-
-// Work stack
-void ImgData::WorkShowSlot(bool val)
-{
-  if(val != stack->work()->isVisible()) {
-    emit changedInterface();
-    if(val)
-      stack->work()->show();
-    else
-      stack->work()->hide();
-    emit viewerUpdate();
+  
+  void ImgData::WorkBrightSlot(int val)
+  {
+    float v = float(val) / 10000.0;
+    if(stack->work()->brightness() != v) {
+      emit changedInterface();
+      stack->work()->setBrightness(v);
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::WorkBrightSlot(int val)
-{
-  float v = float(val) / 10000.0;
-  if(stack->work()->brightness() != v) {
-    emit changedInterface();
-    stack->work()->setBrightness(v);
-    emit viewerUpdate();
+  
+  void ImgData::WorkOpacitySlot(int val)
+  {
+    float v = float(val) / 10000.0;
+    if(stack->work()->opacity() != v) {
+      emit changedInterface();
+      stack->work()->setOpacity(v);
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::WorkOpacitySlot(int val)
-{
-  float v = float(val) / 10000.0;
-  if(stack->work()->opacity() != v) {
-    emit changedInterface();
-    stack->work()->setOpacity(v);
-    emit viewerUpdate();
+  
+  void ImgData::WorkLabelsSlot(bool val)
+  {
+    if(val != stack->work()->labels()) {
+      emit changedInterface();
+      stack->work()->setLabels(val);
+      reloadWorkTex();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::WorkLabelsSlot(bool val)
-{
-  if(val != stack->work()->labels()) {
-    emit changedInterface();
-    stack->work()->setLabels(val);
-    reloadWorkTex();
-    emit viewerUpdate();
+  
+  void ImgData::Work16BitSlot(bool val)
+  {
+    if(val != Work16Bit) {
+      emit changedInterface();
+      Work16Bit = val;
+      reloadWorkTex();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::Work16BitSlot(bool val)
-{
-  if(val != Work16Bit) {
-    emit changedInterface();
-    Work16Bit = val;
-    reloadWorkTex();
-    emit viewerUpdate();
+  
+  // Surface
+  void ImgData::SurfShowSlot(bool val)
+  {
+    if(val != mesh->isSurfaceVisible()) {
+      emit changedInterface();
+      if(val)
+        mesh->showSurface();
+      else
+        mesh->hideSurface();
+      emit viewerUpdate();
+    }
   }
-}
-
-// Surface
-void ImgData::SurfShowSlot(bool val)
-{
-  if(val != mesh->isSurfaceVisible()) {
-    emit changedInterface();
-    if(val)
-      mesh->showSurface();
-    else
-      mesh->hideSurface();
-    emit viewerUpdate();
+  
+  void ImgData::SurfBrightSlot(int val)
+  {
+    float v = float(val) / 10000.0;
+    if(mesh->brightness() != v) {
+      emit changedInterface();
+      mesh->setBrightness(v);
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::SurfBrightSlot(int val)
-{
-  float v = float(val) / 10000.0;
-  if(mesh->brightness() != v) {
-    emit changedInterface();
-    mesh->setBrightness(v);
-    emit viewerUpdate();
+  
+  void ImgData::SurfOpacitySlot(int val)
+  {
+    float v = float(val) / 10000.0;
+    if(mesh->opacity() != v) {
+      emit changedInterface();
+      mesh->setOpacity(v);
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::SurfOpacitySlot(int val)
-{
-  float v = float(val) / 10000.0;
-  if(mesh->opacity() != v) {
-    emit changedInterface();
-    mesh->setOpacity(v);
-    emit viewerUpdate();
+  
+  void ImgData::SurfBlendSlot(bool val)
+  {
+    if(val != mesh->blending()) {
+      emit changedInterface();
+      mesh->setBlending(val);
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::SurfBlendSlot(bool val)
-{
-  if(val != mesh->blending()) {
-    emit changedInterface();
-    mesh->setBlending(val);
-    emit viewerUpdate();
+  
+  void ImgData::SurfNormalSlot(bool val)
+  {
+    if(val and mesh->toShow() != Mesh::NORMAL) {
+      emit changedInterface();
+      bool updTris = (mesh->toShow() == Mesh::PARENT);
+      mesh->showNormal();
+      if(updTris)
+        updateTris();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::SurfNormalSlot(bool val)
-{
-  if(val and mesh->toShow() != Mesh::NORMAL) {
-    emit changedInterface();
-    bool updTris = (mesh->toShow() == Mesh::PARENT);
-    mesh->showNormal();
-    if(updTris)
-      updateTris();
-    emit viewerUpdate();
+  
+  void ImgData::SurfLabelSlot(bool val)
+  {
+    if(val and mesh->toShow() != Mesh::LABEL) {
+      emit changedInterface();
+      bool updTris = (mesh->toShow() == Mesh::PARENT);
+      mesh->showLabel();
+      if(updTris)
+        updateTris();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::SurfLabelSlot(bool val)
-{
-  if(val and mesh->toShow() != Mesh::LABEL) {
-    emit changedInterface();
-    bool updTris = (mesh->toShow() == Mesh::PARENT);
-    mesh->showLabel();
-    if(updTris)
-      updateTris();
-    emit viewerUpdate();
+  
+  void ImgData::SurfHeatSlot(bool val)
+  {
+    if(val and mesh->toShow() != Mesh::HEAT) {
+      emit changedInterface();
+      bool updTris = (mesh->toShow() == Mesh::PARENT);
+      mesh->showHeat();
+      if(updTris)
+        updateTris();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::SurfHeatSlot(bool val)
-{
-  if(val and mesh->toShow() != Mesh::HEAT) {
-    emit changedInterface();
-    bool updTris = (mesh->toShow() == Mesh::PARENT);
-    mesh->showHeat();
-    if(updTris)
-      updateTris();
-    emit viewerUpdate();
+  
+  void ImgData::SurfParentSlot(bool val)
+  {
+    if(val and mesh->toShow() != Mesh::PARENT) {
+      emit changedInterface();
+      bool updTris = (mesh->toShow() != Mesh::PARENT);
+      mesh->showParent();
+      if(updTris)
+        updateTris();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::SurfParentSlot(bool val)
-{
-  if(val and mesh->toShow() != Mesh::PARENT) {
-    emit changedInterface();
-    bool updTris = (mesh->toShow() != Mesh::PARENT);
-    mesh->showParent();
-    if(updTris)
-      updateTris();
-    emit viewerUpdate();
+  
+  void ImgData::SurfSignalSlot(bool val)
+  {
+    if(val and mesh->coloring() != Mesh::SIGNAL) {
+      emit changedInterface();
+      mesh->showSignal();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::SurfSignalSlot(bool val)
-{
-  if(val and mesh->coloring() != Mesh::SIGNAL) {
-    emit changedInterface();
-    mesh->showSignal();
-    emit viewerUpdate();
+  
+  void ImgData::SurfTextureSlot(bool val)
+  {
+    if(val and mesh->coloring() != Mesh::TEXTURE) {
+      emit changedInterface();
+      mesh->showTexture();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::SurfTextureSlot(bool val)
-{
-  if(val and mesh->coloring() != Mesh::TEXTURE) {
-    emit changedInterface();
-    mesh->showTexture();
-    emit viewerUpdate();
+  
+  void ImgData::SurfImageSlot(bool val)
+  {
+    if(val and mesh->coloring() != Mesh::IMAGE) {
+      emit changedInterface();
+      mesh->showImage();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::SurfImageSlot(bool val)
-{
-  if(val and mesh->coloring() != Mesh::IMAGE) {
-    emit changedInterface();
-    mesh->showImage();
-    emit viewerUpdate();
+  
+  void ImgData::SurfCullSlot(bool val)
+  {
+    if(val != mesh->culling()) {
+      emit changedInterface();
+      mesh->setCulling(val);
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::SurfCullSlot(bool val)
-{
-  if(val != mesh->culling()) {
-    emit changedInterface();
-    mesh->setCulling(val);
-    emit viewerUpdate();
+  
+  // Mesh
+  void ImgData::MeshShowSlot(bool val)
+  {
+    if(val != mesh->isMeshVisible()) {
+      emit changedInterface();
+      if(val)
+        mesh->showMesh();
+      else
+        mesh->hideMesh();
+      emit viewerUpdate();
+    }
   }
-}
-
-// Mesh
-void ImgData::MeshShowSlot(bool val)
-{
-  if(val != mesh->isMeshVisible()) {
-    emit changedInterface();
-    if(val)
-      mesh->showMesh();
-    else
-      mesh->hideMesh();
-    emit viewerUpdate();
+  
+  void ImgData::ChangeMeshViewModeSlot(int mode)
+  {
+    if(mode < 4) {
+      MeshViewModeEnum m = (MeshViewModeEnum)mode;
+      if(m != mesh->meshView()) {
+        mesh->show(m);
+        emit viewerUpdate();
+        emit changedInterface();
+      }
+    }
   }
-}
-
-void ImgData::ChangeMeshViewModeSlot(int mode)
-{
-  if(mode < 4) {
-    MeshViewModeEnum m = (MeshViewModeEnum)mode;
-    if(m != mesh->meshView()) {
-      mesh->show(m);
+  
+  void ImgData::MeshLinesSlot(bool val)
+  {
+    if(val != mesh->showMeshLines()) {
+      emit changedInterface();
+      mesh->setShowMeshLines(val);
       emit viewerUpdate();
+    }
+  }
+  
+  void ImgData::MeshPointsSlot(bool val)
+  {
+    if(val != mesh->showMeshPoints()) {
       emit changedInterface();
+      mesh->setShowMeshPoints(val);
+      emit viewerUpdate();
     }
   }
-}
-
-void ImgData::MeshLinesSlot(bool val)
-{
-  if(val != mesh->showMeshLines()) {
-    emit changedInterface();
-    mesh->setShowMeshLines(val);
-    emit viewerUpdate();
+  
+  void ImgData::CellMapSlot(bool val)
+  {
+    if(val != mesh->showMeshCellMap()) {
+      emit changedInterface();
+      mesh->setShowMeshCellMap(val);
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::MeshPointsSlot(bool val)
-{
-  if(val != mesh->showMeshPoints()) {
-    emit changedInterface();
-    mesh->setShowMeshPoints(val);
-    emit viewerUpdate();
+  
+  void ImgData::ShowTransSlot(bool val)
+  {
+    if(val != stack->showTrans()) {
+      emit changedInterface();
+      stack->setShowTrans(val);
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::CellMapSlot(bool val)
-{
-  if(val != mesh->showMeshCellMap()) {
-    emit changedInterface();
-    mesh->setShowMeshCellMap(val);
-    emit viewerUpdate();
+  
+  void ImgData::ShowBBoxSlot(bool val)
+  {
+    if(val != stack->showBBox()) {
+      emit changedInterface();
+      stack->setShowBBox(val);
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::ShowTransSlot(bool val)
-{
-  if(val != stack->showTrans()) {
-    emit changedInterface();
-    stack->setShowTrans(val);
-    emit viewerUpdate();
+  
+  void ImgData::ShowScaleSlot(bool val)
+  {
+    if(val != stack->showScale()) {
+      emit changedInterface();
+      stack->setShowScale(val);
+      updateStackSize();
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::ShowBBoxSlot(bool val)
-{
-  if(val != stack->showBBox()) {
-    emit changedInterface();
-    stack->setShowBBox(val);
-    emit viewerUpdate();
+  
+  void ImgData::TieScalesSlot(bool val)
+  {
+    if(val != stack->tieScales()) {
+      emit changedInterface();
+      stack->setTieScales(val);
+      emit viewerUpdate();
+    }
   }
-}
-
-void ImgData::ShowScaleSlot(bool val)
-{
-  if(val != stack->showScale()) {
-    emit changedInterface();
-    stack->setShowScale(val);
-    updateStackSize();
-    emit viewerUpdate();
+  
+  // Map back and forth between slider and scale
+  int ImgData::toSliderScale(float s) {
+    return int((s - 1.0f) * 15000.0f);
   }
-}
-
-void ImgData::TieScalesSlot(bool val)
-{
-  if(val != stack->tieScales()) {
-    emit changedInterface();
-    stack->setTieScales(val);
-    emit viewerUpdate();
+  
+  float ImgData::fromSliderScale(int i) {
+    return 1.0f + float(i) / 15000.0f;
   }
-}
-
-// Map back and forth between slider and scale
-int ImgData::toSliderScale(float s) {
-  return int((s - 1.0f) * 15000.0f);
-}
-
-float ImgData::fromSliderScale(int i) {
-  return 1.0f + float(i) / 15000.0f;
-}
-
-// Scale slots in x,y,z
-void ImgData::ScaleSlotX(int val)
-{
-  float newScale = fromSliderScale(val);
-  if(newScale != stack->scale().x()) {
-    emit changedInterface();
-    if(!stack->tieScales())
-      stack->setScale(Point3f(newScale, stack->scale().y(), stack->scale().z()));
-    else
-      stack->setScale(Point3f(newScale, newScale, newScale));
-    updateStackSize();
-    emit updateSliderScale();
-    emit viewerUpdate();
+  
+  // Scale slots in x,y,z
+  void ImgData::ScaleSlotX(int val)
+  {
+    float newScale = fromSliderScale(val);
+    if(newScale != stack->scale().x()) {
+      emit changedInterface();
+      if(!stack->tieScales())
+        stack->setScale(Point3f(newScale, stack->scale().y(), stack->scale().z()));
+      else
+        stack->setScale(Point3f(newScale, newScale, newScale));
+      updateStackSize();
+      emit updateSliderScale();
+      emit viewerUpdate();
+    }
   }
-}
-void ImgData::ScaleSlotY(int val)
-{
-  float newScale = fromSliderScale(val);
-  if(newScale != stack->scale().y()) {
-    emit changedInterface();
-    if(!stack->tieScales())
-      stack->setScale(Point3f(stack->scale().x(), newScale, stack->scale().z()));
-    else
-      stack->setScale(Point3f(newScale, newScale, newScale));
-    updateStackSize();
-    emit updateSliderScale();
-    emit viewerUpdate();
+  void ImgData::ScaleSlotY(int val)
+  {
+    float newScale = fromSliderScale(val);
+    if(newScale != stack->scale().y()) {
+      emit changedInterface();
+      if(!stack->tieScales())
+        stack->setScale(Point3f(stack->scale().x(), newScale, stack->scale().z()));
+      else
+        stack->setScale(Point3f(newScale, newScale, newScale));
+      updateStackSize();
+      emit updateSliderScale();
+      emit viewerUpdate();
+    }
   }
-}
-void ImgData::ScaleSlotZ(int val)
-{
-  float newScale = fromSliderScale(val);
-  if(newScale != stack->scale().z()) {
-    emit changedInterface();
-    if(!stack->tieScales())
-      stack->setScale(Point3f(stack->scale().x(), stack->scale().y(), newScale));
-    else
-      stack->setScale(Point3f(newScale, newScale, newScale));
-    updateStackSize();
-    emit updateSliderScale();
-    emit viewerUpdate();
+  void ImgData::ScaleSlotZ(int val)
+  {
+    float newScale = fromSliderScale(val);
+    if(newScale != stack->scale().z()) {
+      emit changedInterface();
+      if(!stack->tieScales())
+        stack->setScale(Point3f(stack->scale().x(), stack->scale().y(), newScale));
+      else
+        stack->setScale(Point3f(newScale, newScale, newScale));
+      updateStackSize();
+      emit updateSliderScale();
+      emit viewerUpdate();
+    }
   }
-}
-Point3f ImgData::imageGradientI(Point3i ipos)
-{
-  uint ix = ipos.x();
-  uint iy = ipos.y();
-  uint iz = ipos.z();
-  Point3d grad(0.0);
-  const Point3f& Size = stack->size();
-  double xScale = (Size.x() / stack->size().x()) * 2.0;
-  double yScale = (Size.y() / stack->size().y()) * 2.0;
-  double zScale = (Size.z() / stack->size().z()) * 2.0;
-  HVecUS& Data = currentData();
-  grad[0] = (Data[offset(ix, iy, iz) + 1] - Data[offset(ix, iy, iz) - 1]) / xScale;
-  grad[1] = (Data[offset(ix, iy, iz) + stack->size().x()] - Data[offset(ix, iy, iz) - stack->size().x()]) / yScale;
-  grad[2] = (Data[offset(ix, iy, iz) + stack->size().x() * stack->size().y()]
-             - Data[offset(ix, iy, iz) - stack->size().x() * stack->size().y()]) / zScale;
-  return grad;
-}
-
-Point3f ImgData::imageGradientW(Point3d worldpos)
-{
-  Point3i ipos = worldToImagei(worldpos);
-  return imageGradientI(ipos);
-}
-
-uint ImgData::imageLevel(Point3d worldpos)
-{
-  HVecUS& Data = currentData();
-  Point3i ipos = worldToImagei(worldpos);
-  return Data[offset(ipos)];
-}
-
-Point2i ImgData::imageMinMax()
-{
-  HVecUS& Data = currentData();
-  uint min = 65535;
-  uint max = 0;
-  for(size_t i = 0; i < stack->storeSize(); ++i) {
-    uint val = Data[i];
-    if(val > max)
-      max = val;
-    if(val < min)
-      min = val;
+  Point3f ImgData::imageGradientI(Point3i ipos)
+  {
+    uint ix = ipos.x();
+    uint iy = ipos.y();
+    uint iz = ipos.z();
+    Point3d grad(0.0);
+    const Point3f& Size = stack->size();
+    double xScale = (Size.x() / stack->size().x()) * 2.0;
+    double yScale = (Size.y() / stack->size().y()) * 2.0;
+    double zScale = (Size.z() / stack->size().z()) * 2.0;
+    HVecUS& Data = currentData();
+    grad[0] = (Data[offset(ix, iy, iz) + 1] - Data[offset(ix, iy, iz) - 1]) / xScale;
+    grad[1] = (Data[offset(ix, iy, iz) + stack->size().x()] - Data[offset(ix, iy, iz) - stack->size().x()]) / yScale;
+    grad[2] = (Data[offset(ix, iy, iz) + stack->size().x() * stack->size().y()]
+               - Data[offset(ix, iy, iz) - stack->size().x() * stack->size().y()]) / zScale;
+    return grad;
   }
-  return Point2i(min, max);
-}
-
-void ImgData::updateImgData()
-{
-  if(needUpdateLines)
-    updateLines();
-  if(needUpdateTris)
-    updateTris();
-}
-
-void ImgData::postUpdateImgData(bool lines, bool tris)
-{
-  bool changed = false;
-  if(lines and !needUpdateLines) {
-    needUpdateLines = lines;
-    changed = true;
+  
+  Point3f ImgData::imageGradientW(Point3d worldpos)
+  {
+    Point3i ipos = worldToImagei(worldpos);
+    return imageGradientI(ipos);
   }
-  if(tris and !needUpdateTris) {
-    needUpdateTris = tris;
-    changed = true;
+  
+  uint ImgData::imageLevel(Point3d worldpos)
+  {
+    HVecUS& Data = currentData();
+    Point3i ipos = worldToImagei(worldpos);
+    return Data[offset(ipos)];
   }
-  if(changed)
-    QCoreApplication::postEvent(parent, new UpdateImgDataEvent());
+  
+  Point2i ImgData::imageMinMax()
+  {
+    HVecUS& Data = currentData();
+    uint min = 65535;
+    uint max = 0;
+    for(size_t i = 0; i < stack->storeSize(); ++i) {
+      uint val = Data[i];
+      if(val > max)
+        max = val;
+      if(val < min)
+        min = val;
+    }
+    return Point2i(min, max);
+  }
+  
+  void ImgData::updateImgData()
+  {
+    if(needUpdateLines)
+      updateLines();
+    if(needUpdateTris)
+      updateTris();
+  }
+  
+  void ImgData::postUpdateImgData(bool lines, bool tris)
+  {
+    bool changed = false;
+    if(lines and !needUpdateLines) {
+      needUpdateLines = lines;
+      changed = true;
+    }
+    if(tris and !needUpdateTris) {
+      needUpdateTris = tris;
+      changed = true;
+    }
+    if(changed)
+      QCoreApplication::postEvent(parent, new UpdateImgDataEvent());
+  }
+
 }
-} // namespace mgx
Index: MorphoGraphX.cpp
===================================================================
--- MorphoGraphX.cpp	(revision 1255)
+++ MorphoGraphX.cpp	(revision 1256)
@@ -59,19 +59,11 @@
 QString MorphoGraphX::AppDir = QString();
 QLabel* MorphoGraphX::ActiveStack;
 
-MorphoGraphX::~MorphoGraphX() {
-}
+MorphoGraphX::~MorphoGraphX() {}
 
 MorphoGraphX::MorphoGraphX(QString appdir)
-  : QMainWindow()
-  , stack1(0, this)
-  , stack2(1, this)
-  , readOnce(true)
-  , needSaving(false)
-  , currentProcess(0)
-  , currentSetup(0)
-  , processThread(0)
-  , editPathsDlg(0)
+  : QMainWindow() , stack1(0, this) , stack2(1, this) , readOnce(true) , needSaving(false),
+    currentProcess(0), currentSetup(0), processThread(0), editPathsDlg(0)
 {
   setAcceptDrops(true);
   // StartSession();
@@ -642,10 +634,7 @@
   connect(ui.menuFileOpen, SIGNAL(triggered()), this, SLOT(FileOpenSlot()));
   connect(ui.menuFileSave, SIGNAL(triggered()), this, SLOT(FileSaveSlot()));
   connect(ui.menuFileSaveAs, SIGNAL(triggered()), this, SLOT(FileSaveAsSlot()));
-  connect(ui.menuFileSaveAll, SIGNAL(triggered()), this, SLOT(FileSaveAllSlot()));
-  connect(ui.menuFileReloadAll, SIGNAL(triggered()), this, SLOT(FileReloadAllSlot()));
   connect(ui.menuFileEditPaths, SIGNAL(triggered()), this, SLOT(FileEditPathsSlot()));
-  connect(ui.menuFileResetAll, SIGNAL(triggered()), this, SLOT(FileResetAllSlot()));
   connect(ui.menuExit, SIGNAL(triggered()), this, SLOT(ExitSlot()));
 
   // Stack menu
@@ -1198,38 +1187,11 @@
   LaunchProcess("Global", "Load View", parms, true);
 }
 
-void MorphoGraphX::FileOpen(const QString& filename) {
+void MorphoGraphX::FileOpen(const QString& filename) 
+{
   LoadView(filename);
 }
 
-void MorphoGraphX::FileSaveAllSlot()
-{
-  QStringList parms;
-  if(!process::getLastParms("Global", "Save All", parms)) {
-    QMessageBox::critical(this, "Error saving all", "There is no Global process named 'Save All'");
-    return;
-  }
-  parms[0] = "All";
-  parms[1] = "";
-  LaunchProcess("Global", "Save All", parms);
-}
-
-void MorphoGraphX::FileResetAllSlot()
-{
-  QStringList parms;
-  if(!process::getLastParms("Global", "Reset All", parms)) {
-    QMessageBox::critical(this, "Error reset all", "There is no Global process named 'Reset All'");
-    return;
-  }
-  LaunchProcess("Global", "Reset All", parms);
-}
-
-void MorphoGraphX::FileReloadAllSlot()
-{
-  QStringList parms;
-  LaunchProcess("Global", "Load All", parms);
-}
-
 void MorphoGraphX::FileEditPathsSlot()
 {
   if(editPathsDlg) {
@@ -1286,7 +1248,7 @@
     return;
   }
   QString fn = getMeshName(stack);
-  if(!fn.isEmpty())
+  //if(!fn.isEmpty())
     parms[0] = fn;
   parms[5] = QString::number(stack);
   LaunchProcess("Mesh", "Import", parms, true, true);
@@ -1316,7 +1278,7 @@
     return;
   }
   QString fn = getMeshName(stack);
-  if(!fn.isEmpty())
+  //if(!fn.isEmpty())
     parms[0] = fn;
   parms[3] = QString::number(stack);
   LaunchProcess("Mesh", "Export", parms, true, true);
@@ -1330,7 +1292,7 @@
     return;
   }
   QString fn = getMeshName(stack);
-  if(!fn.isEmpty())
+  //if(!fn.isEmpty())
     parms[0] = fn;
   parms[3] = QString::number(stack);
   LaunchProcess("Mesh", "Load", parms, true, true);
@@ -1344,7 +1306,7 @@
     return;
   }
   QString fn = getMeshName(stack);
-  if(!fn.isEmpty())
+  //if(!fn.isEmpty())
     parms[0] = fn;
   parms[2] = QString::number(stack);
   LaunchProcess("Mesh", "Save", parms, true, true);
@@ -1382,7 +1344,7 @@
     return;
   }
   QString fn = getStackName(main, stack);
-  if(!fn.isEmpty())
+  //if(!fn.isEmpty())
     parms[0] = fn;
   parms[1] = (main ? "Main" : "Work");
   parms[2] = QString::number(stack);
@@ -1407,7 +1369,7 @@
     return;
   }
   QString fn = getStackName(main, stack);
-  if(!fn.isEmpty())
+  //if(!fn.isEmpty())
     parms[0] = fn;
   parms[1] = (main ? "Main" : "Work");
   parms[2] = QString::number(stack);
@@ -1657,6 +1619,12 @@
   // Set icon
   dlg.setIconPixmap(QPixmap(":/images/Icon.png"));
   dlg.setTextFormat(Qt::RichText);
+
+  // Because setMinimumWidth() does not work
+  QSpacerItem spacer(600, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
+  QGridLayout* layout = (QGridLayout*)dlg.layout();
+  layout->addItem(&spacer, layout->rowCount(), 0, 1, layout->columnCount());
+
   dlg.exec();
 }
 
@@ -3308,7 +3276,7 @@
   }
   Information::Event* ie = dynamic_cast<Information::Event*>(e);
   if(ie) {
-    Information::Print(ie->message);
+    Information::setStatus(ie->message);
     return true;
   }
   ProcessSystemCommand* se = dynamic_cast<ProcessSystemCommand*>(e);
Index: MeshProcessLineage.cpp
===================================================================
--- MeshProcessLineage.cpp	(revision 1255)
+++ MeshProcessLineage.cpp	(revision 1256)
@@ -2,278 +2,128 @@
 
 #include "Progress.hpp"
 
-namespace mgx {
-namespace process {
-bool SaveParents::initialize(QStringList& parms, QWidget* parent)
-{
-  QString filename
-    = QFileDialog::getSaveFileName(parent, "Select file to save labels in", parms[0], "CSV files (*.csv)");
-  // check filename
-  if(filename.isEmpty())
-    return false;
-  // check ending, add suffix if required
-  QString suffix = ".csv";
-  if(filename.right(suffix.size()) != suffix)
-    filename.append(suffix);
-
-  parms[0] = filename;
-  return true;
-}
-
-bool SaveParents::operator()(Mesh* mesh, const QString& filename)
-{
-  const IntIntMap& parentLabel = mesh->parentLabelMap();
-  if(parentLabel.size() == 0) {
-    setErrorMessage(QString("There are no parent labels").arg(filename));
-    return false;
-  }
-
-  QFile file(filename);
-
-  if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
-    setErrorMessage(QString("File '%1' cannot be opened for writing").arg(filename));
-    return false;
-  }
-  QTextStream out(&file);
-  out << "Label, Parent Label" << endl;
-
-  // store to file
-  SETSTATUS("Storing " << parentLabel.size() << " parent labels to file " << filename);
-  forall(const IntIntPair& p, parentLabel) {
-    int label = p.first;
-    int parent = p.second;
-    out << label << "," << parent << endl;
-  }
-
-  file.close();
-  return true;
-}
-REGISTER_MESH_PROCESS(SaveParents);
-
-bool LoadParents::initialize(QStringList& parms, QWidget* parent)
-{
-  QString filename
-    = QFileDialog::getOpenFileName(parent, "Choose parent label file to load", parms[0], "CSV files (*.csv)");
-
-  // check file
-  if(filename.isEmpty())
-    return false;
-
-  QFile file(filename);
-  if(!file.open(QIODevice::ReadOnly)) {
-    QMessageBox::critical(parent, "Error opening file",
-                          QString("File '%1' cannot be opened for reading").arg(filename));
-    return false;
-  }
-  QTextStream ss(&file);
-  QString line = ss.readLine();
-  QStringList fields = line.split(",");
-  if(fields.size() != 2) {
-    QMessageBox::critical(parent, "Error reading file",
-                          QString("File '%1' should be a CSV file with 2 columns").arg(filename));
-    return false;
-  }
-
-  // ok now we're happy
-  parms[0] = filename;
-  return true;
-}
-
-bool LoadParents::operator()(Mesh* mesh, const QString& filename)
-{
-  QFile file(filename);
-  if(!file.open(QIODevice::ReadOnly)) {
-    setErrorMessage(QString("File '%1' cannot be opened for reading").arg(filename));
-    return false;
-  }
-  QTextStream ss(&file);
-  QString line = ss.readLine();
-  QStringList fields = line.split(",");
-  if(fields.size() != 2) {
-    setErrorMessage(QString("File '%1' should be a CSV file with 2 columns").arg(filename));
-    return false;
-  }
-
-  // read file
-  IntIntMap parentLabel;
-  IntFloatMap labelHeat;
-  int line_nb = 1;
-  while(ss.status() == QTextStream::Ok) {
-    ++line_nb;
-    fields = ss.readLine().split(",");
-    if(fields.size() != 2)
-      break;
-    bool ok;
-    int label = fields[0].toInt(&ok);
-    if(!ok) {
-      setErrorMessage(QString("Error line %1: the first column is not an integer number but '%2'")
-                      .arg(line_nb)
-                      .arg(fields[0].trimmed()));
+namespace mgx { namespace process {
+  
+  // Eliminate from parentLabelMap labels which are not in mesh1 or mesh2
+  bool CorrectParents::operator()(Mesh* mesh1, Mesh* mesh2)
+  {
+    IntIntMap& daughterParentMap = mesh2->parentLabelMap();
+    if(daughterParentMap.size() == 0) {
+      setErrorMessage(QString("No parent labels on second mesh"));
       return false;
     }
-    int parent = fields[1].toInt(&ok);
-    if(!ok) {
-      setErrorMessage(QString("Error line %1: the second column is not an integer number but '%2'")
-                      .arg(line_nb)
-                      .arg(fields[1].trimmed()));
-      return false;
+  
+    vvgraph S1 = mesh1->graph();
+    vvgraph S2 = mesh2->graph();
+  
+    // Check the parentLabelMap for cells which are not in the mesh1 or mesh2
+    IntIntMap daughterParentMaptemp;
+    std::set<int> labelsS1;
+    std::set<int> labelsS2;
+    std::set<int> problemsS1;
+    std::set<int> problemsS2;
+    forall(vertex c, S1)
+      if(c->label > 0)
+        labelsS1.insert(c->label);
+    forall(vertex c, S2)
+      if(c->label > 0)
+        labelsS2.insert(c->label);
+    for(IntIntMap::iterator it = daughterParentMap.begin(); it != daughterParentMap.end(); it++) {
+      int lParent = it->second;
+      int lDaughter = it->first;
+      if(labelsS1.count(lParent) == 0)
+        problemsS1.insert(lParent);
+      if(labelsS2.count(lDaughter) == 0)
+        problemsS2.insert(lDaughter);
+      if(labelsS1.count(lParent) != 0 and labelsS2.count(lDaughter) != 0)
+        daughterParentMaptemp[lDaughter] = lParent;
     }
-    parentLabel[label] = parent;
-    labelHeat[label] = 1;
-    // SETSTATUS("Seed " << parent << " to be mapped to local label " << label);
+    daughterParentMap = daughterParentMaptemp;
+  
+    if(problemsS1.size() > 0 or problemsS2.size() > 0) {
+      Information::out << "problems with parentLabelMap. Some labels in the map are not present in the mesh:\n"
+                       << "in mesh1, the following labels do not exist:\n";
+      forall(int l, problemsS1)
+        Information::out << l << ", ";
+      Information::out << "\nin mesh2, the following labels do not exist:\n";
+      forall(int l, problemsS2)
+        Information::out << l << ", ";
+      Information::out << endl;
+    }
+    return true;
   }
-  // done
-  SETSTATUS(parentLabel.size() << " parent labels loaded from file " << filename);
-
-  // clear tables related to parents
-  mesh->parentCenter().clear();
-  mesh->parentCenterVis().clear();
-  mesh->parentNormal().clear();
-  mesh->parentNormalVis().clear();
-
-  // store it
-  mesh->parentLabelMap() = parentLabel;
-  mesh->labelHeat() = labelHeat;
-  mesh->heatMapUnit() = "ON/OFF";
-  mesh->heatMapBounds() = Point2f(0, 1);
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(LoadParents);
-
-bool ClearParents::operator()(Mesh* mesh)
-{
-  mesh->parentLabelMap().clear();
-  mesh->parentCenter().clear();
-  mesh->parentCenterVis().clear();
-  mesh->parentNormal().clear();
-  mesh->parentNormalVis().clear();
-  mesh->labelHeat().clear();
-  mesh->updateTriangles();
-  return true;
-}
-REGISTER_MESH_PROCESS(ClearParents);
-
-// Eliminate from parentLabelMap labels which are not in mesh1 or mesh2
-bool CorrectParents::operator()(Mesh* mesh1, Mesh* mesh2)
-{
-  IntIntMap& daughterParentMap = mesh2->parentLabelMap();
-  if(daughterParentMap.size() == 0) {
-    setErrorMessage(QString("No parent labels on second mesh"));
-    return false;
+  REGISTER_MESH_PROCESS(CorrectParents);
+  
+  // Make a heat map based on how many daughter cells a parent cell has
+  bool HeatMapDaughterCells::operator()(Mesh* mesh)
+  {
+    vvgraph& S = mesh->graph();
+  
+    IntIntMap parents = mesh->parentLabelMap();
+    IntSet labels;
+  
+    // get list of labels
+    forall(const vertex& v, S)
+      if(v->label > 0)
+        labels.insert(v->label);
+  
+    IntFloatMap daughters;
+  
+    // find how daughters each parent has
+    forall(IntIntPair p, parents)
+      if(p.first > 0 and p.second > 0)
+        daughters[p.second] += 1;
+  
+    // Build heat map
+    IntFloatMap labelDaughters;
+    forall(IntIntPair p, parents)
+      if(p.first > 0 and p.second > 0 and daughters[p.second] > 0)
+        labelDaughters[p.first] = daughters[p.second];
+  
+    // Go over all the volumes to find the min and max
+    float dmin = 1, dmax = 1;
+  
+    forall(const IntFloatPair& v, labelDaughters) {
+      if(v.second < dmin)
+        dmin = v.second;
+      if(v.second > dmax)
+        dmax = v.second;
+    }
+  
+    if(dmax <= dmin)
+      dmax = dmin + 1;
+  
+    // Set the map bounds. A heat of 0 will be interpreted has vol_min, and a heat of 1 as vol_max.
+    mesh->heatMapBounds() = Point2f(dmin, dmax);
+    // Unit of the heat map
+    mesh->heatMapUnit() = QString("#");
+    // Set the values
+    mesh->labelHeat() = labelDaughters;
+    // Tell the system the triangles have changed (here, the heat map)
+    mesh->updateTriangles();
+  
+    return true;
   }
-
-  vvgraph S1 = mesh1->graph();
-  vvgraph S2 = mesh2->graph();
-
-  // Check the parentLabelMap for cells which are not in the mesh1 or mesh2
-  IntIntMap daughterParentMaptemp;
-  std::set<int> labelsS1;
-  std::set<int> labelsS2;
-  std::set<int> problemsS1;
-  std::set<int> problemsS2;
-  forall(vertex c, S1)
-    if(c->label > 0)
-      labelsS1.insert(c->label);
-  forall(vertex c, S2)
-    if(c->label > 0)
-      labelsS2.insert(c->label);
-  for(IntIntMap::iterator it = daughterParentMap.begin(); it != daughterParentMap.end(); it++) {
-    int lParent = it->second;
-    int lDaughter = it->first;
-    if(labelsS1.count(lParent) == 0)
-      problemsS1.insert(lParent);
-    if(labelsS2.count(lDaughter) == 0)
-      problemsS2.insert(lDaughter);
-    if(labelsS1.count(lParent) != 0 and labelsS2.count(lDaughter) != 0)
-      daughterParentMaptemp[lDaughter] = lParent;
+  REGISTER_MESH_PROCESS(HeatMapDaughterCells);
+  
+  // Copy parent labels overtop of labels
+  bool CopyParentsToLabels::operator()(Mesh* mesh)
+  {
+    vvgraph& S = mesh->graph();
+    IntIntMap& parents = mesh->parentLabelMap();
+    forall(const vertex& v, S)
+      if(v->label > 0) {
+        if(parents[v->label] > 0)
+          v->label = parents[v->label];
+        else
+          v->label = 0;
+      }
+  
+    parents.clear();
+  
+    mesh->updateAll();
+    return true;
   }
-  daughterParentMap = daughterParentMaptemp;
+  REGISTER_MESH_PROCESS(CopyParentsToLabels);
 
-  if(problemsS1.size() > 0 or problemsS2.size() > 0) {
-    Information::out << "problems with parentLabelMap. Some labels in the map are not present in the mesh:\n"
-                     << "in mesh1, the following labels do not exist:\n";
-    forall(int l, problemsS1)
-      Information::out << l << ", ";
-    Information::out << "\nin mesh2, the following labels do not exist:\n";
-    forall(int l, problemsS2)
-      Information::out << l << ", ";
-    Information::out << endl;
-  }
-  return true;
-}
-REGISTER_MESH_PROCESS(CorrectParents);
-
-// Make a heat map based on how many daughter cells a parent cell has
-bool HeatMapDaughterCells::operator()(Mesh* mesh)
-{
-  vvgraph& S = mesh->graph();
-
-  IntIntMap parents = mesh->parentLabelMap();
-  IntSet labels;
-
-  // get list of labels
-  forall(const vertex& v, S)
-    if(v->label > 0)
-      labels.insert(v->label);
-
-  IntFloatMap daughters;
-
-  // find how daughters each parent has
-  forall(IntIntPair p, parents)
-    if(p.first > 0 and p.second > 0)
-      daughters[p.second] += 1;
-
-  // Build heat map
-  IntFloatMap labelDaughters;
-  forall(IntIntPair p, parents)
-    if(p.first > 0 and p.second > 0 and daughters[p.second] > 0)
-      labelDaughters[p.first] = daughters[p.second];
-
-  // Go over all the volumes to find the min and max
-  float dmin = 1, dmax = 1;
-
-  forall(const IntFloatPair& v, labelDaughters) {
-    if(v.second < dmin)
-      dmin = v.second;
-    if(v.second > dmax)
-      dmax = v.second;
-  }
-
-  if(dmax <= dmin)
-    dmax = dmin + 1;
-
-  // Set the map bounds. A heat of 0 will be interpreted has vol_min, and a heat of 1 as vol_max.
-  mesh->heatMapBounds() = Point2f(dmin, dmax);
-  // Unit of the heat map
-  mesh->heatMapUnit() = QString("#");
-  // Set the values
-  mesh->labelHeat() = labelDaughters;
-  // Tell the system the triangles have changed (here, the heat map)
-  mesh->updateTriangles();
-
-  return true;
-}
-REGISTER_MESH_PROCESS(HeatMapDaughterCells);
-
-// Copy parent labels overtop of labels
-bool CopyParentsToLabels::operator()(Mesh* mesh)
-{
-  vvgraph& S = mesh->graph();
-  IntIntMap& parents = mesh->parentLabelMap();
-  forall(const vertex& v, S)
-    if(v->label > 0) {
-      if(parents[v->label] > 0)
-        v->label = parents[v->label];
-      else
-        v->label = 0;
-    }
-
-  parents.clear();
-
-  mesh->updateAll();
-  return true;
-}
-REGISTER_MESH_PROCESS(CopyParentsToLabels);
-} // namespace process
-} // namespace mgx
+}}
Index: Process.hpp
===================================================================
--- Process.hpp	(revision 1255)
+++ Process.hpp	(revision 1256)
@@ -36,8 +36,10 @@
  * Number identifying the running version of the process API.
  * This makes sure the loaded processes will run with the current API. Otherwise, an error informing correctly the user
  * will be shown in the standard error.
+ *
+ * This is set to the SVN revision number that triggered a change in the process interface 
  */
-#define PROCESS_VERSION 0x000001
+#define PROCESS_VERSION 1243
 
 /**
  * \mainpage MorphoGraphX Plug-in documentation
@@ -88,1273 +90,1245 @@
  *
  * This namespace contains all the API of MorphoGraphX
  */
-namespace mgx {
-/**
- * \namespace process
- *
- * This namespace contains all the classes needed to define processes.
- *
- * To create a new process, you first need to decide the category of the process:
- * Stack, Mesh or Global. Remember it will appear in the appropriate section. Also,
- * stack processes will be able to access only 3D data, and mesh
- * processes only the meshes. Here is a template of a minimal stack process:
- *
- * \section Basics
- *
- * \code
- * class DoNothing : public StackProcess
- * {
- * public:
- *   // Only the copy constructor is needed
- *   DoNothing(const StackProcess& proc)
- *     : Process(proc)
- *     , StackProcess(proc)
- *   { }
- *   // Define what the class do ... here it's nothing
- *   bool operator()(const QStringList&) { return true; }
- *
- *   // Now define the properties of the process
- *   QString name() const { return "Nothing"; }
- *   QString description() const { return "This process really does nothing."; }
- *   QStringList parmNames() const { return QStringList(); }
- *   QStringList parmDescs() const { return QStringList(); }
- * };
- * \endcode
- *
- * Then, in the implementation file, you need to add:
- * \code
- * REGISTER_STACK_PROCESS(DoNothing);
- * \endcode
- * Which will take care of registering the process to the system when the
- * library is loaded.
- *
- * \section Recommendations
- *
- * Beside the minimal process, it is recommended to structure the process in two functions:
- * the first one taking generic arguments (i.e. a string list and a float list), the other
- * one taking specific arguments. This way, your process will
- * be easier to use from another C++ process.
- *
- * Also, to help providing meaningful (and uniform) error messages, and to help you
- * testing the current state of the process, the checkState() method is provided.
- *
- * The structure then typically becomes:
- *
- * \code
- * class DoSomething : public StackProcess
- * {
- * public:
- *    DoSomething(const StackProcess& proc)
- *      : Process(proc)
- *      , StackProcess(proc)
- *    { }
- *
- *    // the operator() with generic arguments is mandatory to work
- *    bool operator()(const QStringList& parms)
- *    {
- *      if(!checkState().stack(STACK_NON_EMPTY)
- *                      .store(STORE_LABEL | STORE_WORK)
- *                      .mesh(MESH_NON_EMPTY))
- *        return false;
- *      Store *store = currentStack()->work();
- *      bool isneeded = stringToBool(parms[1]);
- *      QString aname = parms[2];
- *      float param = parms[3].toFloat();
- *      if((*this)(store, isneeded, aname, param))
- *      {
- *        work->show();
- *        return true;
- *      }
- *      return false;
- *    }
- *
- *    // The operator() with specialized arguments is recommended to be used by other C++ processes
- *    bool operator()(Store *store, bool isneeded, const QString& aname, float param)
- *    {
- *      // Do what is needed
- *      store->changed();
- *      return true;
- *    }
- *
- *    // Properties of the process
- *    QString name() const { return "DoSomething"; }
- *
- *    QString description() const { return "A process that does something"; }
- *
- *    // This time, we have four parameters
- *    QStringList parmNames() const {
- *      return QStringList() << "Store" << "Needed" << "Name" << "Param";
- *    }
- *
- *    // Defaults for paramters
- *    QStringList parmDefaults() const {
- *      return QStringList() << "Work" << "Yes" << "" << "0.0";
- *    }
- *
- *    // Some of the parms come from a choice list
- *    ParmChoiceMap parmChoice() const
- *    {
- *      ParmChoiceMap choice;
- *      choice[0] = storeChoice(); // Helper function to list "main" and "work"
- *      choice[1] = booleanChoice(); // Helper function to list "yes" and "no"
- *      return choice;
- *    }
- * };
- * \endcode
- */
-namespace process {
-/**
- * Type of the dictionary giving the list of possible strings for each argument.
- *
- * If the choice is free, the position should just not be present in the dictionnary.
- * \ingroup ProcessUtils
- */
-typedef QHash<int, QStringList> ParmChoiceMap;
-
-#ifndef DOXYGEN
-enum SystemCommand { LOAD_VIEW = 1, SAVE_VIEW, UPDATE_STRUCTURE, SET_CURRENT_STACK, TAKE_SNAPSHOT, RESET_PROJECT };
-
-class PrivateProcess;
-class SetupProcess;
-class GlobalProcess;
-#endif
-
-/**
- * \class UserCancelException Process.hpp <Process.hpp>
- *
- * Exception launched when a user clicks the Cancel button.
- * When writing your own processes, you should use the userCancel() method.
- * \ingroup ProcessUtils
- */
-class MGX_EXPORT UserCancelException : public std::exception {
-public:
-  UserCancelException()
-    : std::exception()
-  {
-  }
-
-  const char* what() const throw() {
-    return "Process canceled by user.";
-  }
-};
-
-/**
- * \class Process Process.hpp <Process.hpp>
- *
- * This is the main process class, the one all process inherit from.
- * Note that you should \b never inherit this class directly, as it won't
- * allow anything to be done. Instead, you should inherit one of the daughter
- * class: StackProcess, MeshProcess or GlobalProcess.
- * \ingroup ProcessUtils
- */
-class MGX_EXPORT Process {
-public:
-  static unsigned int processVersion;
-
-  typedef std::vector<Stack*>::iterator stack_iterator;
-  typedef std::vector<Stack*>::const_iterator const_stack_iterator;
-
-  typedef std::vector<Mesh*>::iterator mesh_iterator;
-  typedef std::vector<Mesh*>::const_iterator const_mesh_iterator;
-
+namespace mgx { namespace process {
   /**
-   * Default constructor.
-   */
-  Process();
-  /**
-   * Copy constructor.
+   * \namespace process
    *
-   * Note that you will always need to call this constructor explicitly from your process,
-   * as Process is inherited virtually. So all leaf class need to initialize it.
-   */
-  Process(const Process& p);
-  /**
-   * Virtual destructor
-   */
-  virtual ~Process() {
-  }
-
-  /**
-   * Method to be called anytime a file is acted on (i.e. saved/loaded).
+   * This namespace contains all the classes needed to define processes.
    *
-   * If needed, it will set the current folder to the one containing the file and start a session
+   * To create a new process, you first need to decide the category of the process:
+   * Stack, Mesh or Global. Remember it will appear in the appropriate section. Also,
+   * stack processes will be able to access only 3D data, and mesh
+   * processes only the meshes. Here is a template of a minimal stack process:
    *
-   * If it is a project file (i.e. ending in mgxv), then project_file should be set to true to force the change in
-   * folder.
-   */
-  void actingFile(const QString& filename, bool project_file = false);
-
-  /**
-   * Get the file currently defining the path of the system
-   */
-  QString actingFile() const;
-
-  /**
-   * Return the python call describing the current process
-   */
-  QString pythonCall(const QStringList& parms) const;
-
-  /**
-   * Number of stacks available to the process
-   */
-  int stackCount() const;
-  /**
-   * Returns the ith stack, or 0 if there is no such stack.
-   */
-  Stack* stack(int i);
-  /**
-   * Returns the current stack (i.e. the stack currently selected by the user).
-   */
-  Stack* currentStack();
-  /**
-   * Return the id (i.e. number) of the current stack.
-   */
-  int currentStackId() const;
-  /**
-   * Change which stack is current.
-   */
-  void setCurrentStackId(int i);
-
-  /// Iterate over all the stacks
-  std::pair<stack_iterator, stack_iterator> stacks();
-  /// Iterate over all the stacks
-  std::pair<const_stack_iterator, const_stack_iterator> stacks() const;
-
-  /**
-   * Add a new stack to the process
-   */
-  Stack* addStack();
-
-  /**
-   * Delete the stack of given id
+   * \section Basics
    *
-   * \note The current implementation assumes there are at least two stacks always available
-   */
-  bool deleteStack(int i);
-
-  /**
-   * Returns the number of mesh available to the process
-   */
-  int meshCount() const;
-  /**
-   * Returns the ith mesh
-   */
-  Mesh* mesh(int i);
-  /**
-   * Returns the current mesh (i.e. the mesh currently selected by the user)
-   */
-  Mesh* currentMesh();
-  /**
-   * Returns the id (i.e. number) of the current mesh
-   */
-  int currentMeshId() const;
-  /**
-   * Change which mesh is current
-   */
-  void setCurrentMeshId(int i);
-
-  /// Iterate over all the meshs
-  std::pair<mesh_iterator, mesh_iterator> meshes();
-  /// Iterate over all the meshs
-  std::pair<const_mesh_iterator, const_mesh_iterator> meshes() const;
-
-  /**
-   * Add a mesh to the process for the given stack
-   */
-  Mesh* addMesh(const Stack* stack);
-
-  /**
-   * Remove a mesh from the process
-   */
-  bool deleteMesh(int i);
-
-  /**
-   * Get the current selected label
-   */
-  int selectedLabel() const;
-
-  /**
-   * Change the current selected label
-   */
-  void setSelectedLabel(int label);
-
-  /**
-   * Return the current setting for the global brightness level
-   */
-  float globalBrightness();
-
-  /**
-   * Return the current setting for the global contrast level
-   */
-  float globalContrast();
-
-  /**
-   * Change the current setting for the global brightness level
+   * \code
+   * class DoNothing : public StackProcess
+   * {
+   * public:
+   *   // Only the copy constructor is needed
+   *   DoNothing(const StackProcess& proc)
+   *     : Process(proc)
+   *     , StackProcess(proc)
+   *   { }
+   *   // Define what the class do ... here it's nothing
+   *   bool operator()(const QStringList&) { return true; }
    *
-   * The brightness is clamped to the range [-1;1]
-   */
-  void setGlobalBrightness(float value);
-
-  /**
-   * Change the current setting for the global contrast level
+   *   // Now define the properties of the process
+   *   QString name() const { return "Nothing"; }
+   *   QString description() const { return "This process really does nothing."; }
+   *   QStringList parmNames() const { return QStringList(); }
+   *   QStringList parmDescs() const { return QStringList(); }
+   * };
+   * \endcode
    *
-   * The contrast is clamped to the range [0;2]
-   */
-  void setGlobalContrast(float value);
-
-  /**
-   * Returns if the user has mesh selection active
-   */
-  bool meshSelection() const;
-  /**
-   * Returns is the user has line border selection active
-   */
-  bool lineBorderSelection() const;
-
-  /**
-   * Update the state of the application from the current data.
-   * The process is paused until it's done.
-   */
-  void updateState();
-  /**
-   * Force the viewer to refresh, without pausing the process.
-   */
-  void updateViewer();
-
-  /**
-   * Set an error message that will be displayed if the process returns false.
-   */
-  bool setErrorMessage(const QString& str);
-
-  /**
-   * Get the current error message
-   */
-  QString errorMessage() const;
-
-  /**
-   * Set a warning message that will be displayed if the process returns true.
-   */
-  void setWarningMessage(const QString& str);
-  /**
-   * Get the current warning message
-   */
-  QString warningMessage() const;
-
-  /**
-   * Throw an exception informing the system that the user canceled the current process.
-   */
-  void userCancel() const {
-    throw UserCancelException();
-  }
-
-  /**
-   * Get the name of the file that was used to load the current process (i.e. the mgxv file), if any.
-   */
-  const QString& file() const;
-
-  /**
-   * Return the object defining the first clipping region
-   */
-  Clip* clip1();
-  /**
-   * Return the object defining the second clipping region
-   */
-  Clip* clip2();
-  /**
-   * Return the object defining the third clipping region
-   */
-  Clip* clip3();
-
-  /**
-   * Return the object defining the first clipping region
-   */
-  const Clip* clip1() const;
-  /**
-   * Return the object defining the second clipping region
-   */
-  const Clip* clip2() const;
-  /**
-   * Return the object defining the third clipping region
-   */
-  const Clip* clip3() const;
-
-  /**
-   * Return the cutting surface.
-   */
-  CuttingSurface* cuttingSurface();
-  /**
-   * Return the cutting surface.
-   */
-  const CuttingSurface* cuttingSurface() const;
-
-  //@{
-  //\name Methods needed to launch other processes
-
-  /**
-   * Creates a process object by name
-   */
-  Process* makeProcess(const QString& processType, const QString& processName);
-
-  /**
-   * Launch a process with generic arguments.
+   * Then, in the implementation file, you need to add:
+   * \code
+   * REGISTER_STACK_PROCESS(DoNothing);
+   * \endcode
+   * Which will take care of registering the process to the system when the
+   * library is loaded.
    *
-   * Note that exceptions are filtered and converted into an error message and the process returning false.
-   */
-  bool RunProcess(Process& proc, const QStringList& parms) throw();
-
-  /**
-   * Launch a process by name
+   * \section Recommendations
    *
-   * Note that exceptions are filtered and converted into an error message and the process returning false.
-   */
-  bool RunProcess(const QString& processType, const QString& processName, const QStringList& parms) throw();
-  //@}
-
-  /**
-   * Returns a string identifying the process type.
-   */
-  virtual QString type() const = 0;
-
-  // @{ Functions to be defined by the user
-
-  /**
-   * Implementation of the process with generic arguments.
+   * Beside the minimal process, it is recommended to structure the process in two functions:
+   * the first one taking generic arguments (i.e. a string list and a float list), the other
+   * one taking specific arguments. This way, your process will
+   * be easier to use from another C++ process.
    *
-   * The number of arguments is guaranteed to be at least as many as the ones named in the process.
-   */
-  virtual bool operator()(const QStringList& parms) = 0;
-  /**
-   * Returns the name of the process. Note that the name must be a valid identifier in Python once the spaces are
-   * replaced by underscores. Also, all underscore in the name will be replaced by spaces for user presentation.
-   */
-  virtual QString name() const = 0;
-  /**
-   * Returns a description of the process for the GUI.
-   */
-  virtual QString description() const = 0;
-  /**
-   * Folder in which to place the process.
+   * Also, to help providing meaningful (and uniform) error messages, and to help you
+   * testing the current state of the process, the checkState() method is provided.
    *
-   * Subfolders can be specified by placing '/' in the path
+   * The structure then typically becomes:
    *
-   * \note This is a purely presentation parameter. It doesn't allow two processes to have the same name if they are
-   * in different folders.
-   */
-  virtual QString folder() const {
-    return QString();
-  }
-  /**
-   * List of named parameters.
+   * \code
+   * class DoSomething : public StackProcess
+   * {
+   * public:
+   *    DoSomething(const StackProcess& proc)
+   *      : Process(proc)
+   *      , StackProcess(proc)
+   *    { }
    *
-   * There must be as many parameters than defaults.
-   */
-  virtual QStringList parmNames() const = 0;
-  /**
-   * List of parameters descriptions.
+   *    // the operator() with generic arguments is mandatory to work
+   *    bool operator()(const QStringList& parms)
+   *    {
+   *      if(!checkState().stack(STACK_NON_EMPTY)
+   *                      .store(STORE_LABEL | STORE_WORK)
+   *                      .mesh(MESH_NON_EMPTY))
+   *        return false;
+   *      Store *store = currentStack()->work();
+   *      bool isneeded = stringToBool(parms[1]);
+   *      QString aname = parms[2];
+   *      float param = parms[3].toFloat();
+   *      if((*this)(store, isneeded, aname, param))
+   *      {
+   *        work->show();
+   *        return true;
+   *      }
+   *      return false;
+   *    }
    *
-   * There must be as many parameters than defaults.
-   */
-  virtual QStringList parmDescs() const {
-    return QStringList();
-  }
-  /**
-   * List of default parms.
-   */
-  virtual QStringList parmDefaults() const {
-    return QStringList();
-  }
-  /**
-   * Purely for GUI purposes, provides for some of the parms parameter a choice. In this case, the user will be
-   * presented with a combo box presenting the provided list. Note that no mechanism forces the user to choose one
-   * of this choice.
-   */
-  virtual ParmChoiceMap parmChoice() const {
-    return ParmChoiceMap();
-  }
-  /**
-   * Icon to use to represent the process in the GUI.
+   *    // The operator() with specialized arguments is recommended to be used by other C++ processes
+   *    bool operator()(Store *store, bool isneeded, const QString& aname, float param)
+   *    {
+   *      // Do what is needed
+   *      store->changed();
+   *      return true;
+   *    }
    *
-   * Note that to use an icon present in the resources, you must precede the path with a colon (i.e.
-   * ":/images/myicon.png".
-   */
-  virtual QIcon icon() const {
-    return QIcon();
-  }
-  /**
-   * This is an optional method that is called only when a process is launched from the GUI.
+   *    // Properties of the process
+   *    QString name() const { return "DoSomething"; }
    *
-   * If reimplemented, it receives a potential argument list, and should provide a GUI for editing it. Once the user
-   * finishing the edition, this method should modify the provided arguments and return true. If the user aborts,
-   * the method should return false. Note that returning false does not produce an error.
+   *    QString description() const { return "A process that does something"; }
    *
-   * \param parms List of arguments
-   * \param parent Pointer to the parent widget. If the configure method creates a GUI, it should be a child of this
-   * widget.
+   *    // This time, we have four parameters
+   *    QStringList parmNames() const {
+   *      return QStringList() << "Store" << "Needed" << "Name" << "Param";
+   *    }
+   *
+   *    // Defaults for paramters
+   *    QStringList parmDefaults() const {
+   *      return QStringList() << "Work" << "Yes" << "" << "0.0";
+   *    }
+   *
+   *    // Some of the parms come from a choice list
+   *    ParmChoiceMap parmChoice() const
+   *    {
+   *      ParmChoiceMap choice;
+   *      choice[0] = storeChoice(); // Helper function to list "main" and "work"
+   *      choice[1] = booleanChoice(); // Helper function to list "yes" and "no"
+   *      return choice;
+   *    }
+   * };
+   * \endcode
    */
-  virtual bool initialize(QStringList& /*parms*/, QWidget* /*parent*/) {
-    return true;
-  }
-  // @}
-
   /**
-   * Helper function that provides a list of choices for a boolean argument
+   * Type of the dictionary giving the list of possible strings for each argument.
+   *
+   * If the choice is free, the position should just not be present in the dictionnary.
+   * \ingroup ProcessUtils
    */
-  QStringList booleanChoice() const
-  {
-    return QStringList() << "Yes"
-                         << "No";
-  }
+  typedef QHash<int, QStringList> ParmChoiceMap;
+  
+  #ifndef DOXYGEN
+  enum SystemCommand { LOAD_VIEW = 1, SAVE_VIEW, UPDATE_STRUCTURE, SET_CURRENT_STACK, TAKE_SNAPSHOT, RESET_PROJECT };
+  
+  class PrivateProcess;
+  class SetupProcess;
+  class GlobalProcess;
+  #endif
+  
   /**
-   * Helper function that provides a list of choices for choosing from the main or work stack
+   * \class UserCancelException Process.hpp <Process.hpp>
+   *
+   * Exception launched when a user clicks the Cancel button.
+   * When writing your own processes, you should use the userCancel() method.
+   * \ingroup ProcessUtils
    */
-  QStringList storeChoice() const
-  {
-    return QStringList() << "Main"
-                         << "Work";
-  }
-
-  /**
-   * Returns the number of named string for this process
-   */
-  virtual uint numParms() const {
-    return parmDefaults().size();
-  }
-
-  //@{
-  //\name Methods to get and check elements
-
-  /**
-   * Enumeration for the bitfield that identifies stack properties
-   */
-  enum StackCheckType {
-    STACK_ANY = 0,              ///< Any stack
-    STACK_NON_EMPTY = 0x01,     ///< Non-empty stack
-    STACK_VISIBLE = 0x02,       ///< Visible stack
-    STACK_EMPTY = 0x04,         ///< Empty stack
-
-    STACK_SCALED = 0x08,              ///< Scaled stack
-    STACK_TRANSFORMED = 0x10,         ///< Transformed stack
-    STACK_NON_SCALED = 0x20,          ///< Non-Scaled stack
-    STACK_NON_TRANSFORMED = 0x40,     ///< Non-Transformed stack
+  class MGX_EXPORT UserCancelException : public std::exception {
+  public:
+    UserCancelException()
+      : std::exception()
+    {
+    }
+  
+    const char* what() const throw() {
+      return "Process canceled by user.";
+    }
   };
-
+  
   /**
-   * Enumeration for the bitfield that identifies store properties
-   */
-  enum StoreCheckType {
-    STORE_ANY = 0,                ///< Any store
-    STORE_NON_EMPTY = 0x0001,     ///< Non-Empty store
-    STORE_VISIBLE = 0x0002,       ///< Visible store
-    STORE_EMPTY = 0x0004,         ///< Empty store
-
-    STORE_LABEL = 0x0008,         ///< Label store
-    STORE_NON_LABEL = 0x0010,     ///< Non-Label store
-
-    STORE_SCALED = 0x0020,              ///< Scaled store
-    STORE_TRANSFORMED = 0x0040,         ///< Transformed store
-    STORE_NON_SCALED = 0x0080,          ///< Non-Scaled store
-    STORE_NON_TRANSFORMED = 0x0100,     ///< Non-Transformed store
-
-    STORE_WORK = 0x1000,     ///< Work store
-    STORE_MAIN = 0x2000,     ///< Main store
-  };
-
-  /**
-   * Enumeration for the bitfield that identifies mesh properties
-   */
-  enum MeshCheckType {
-    MESH_ANY = 0,                  ///< Any mesh
-    MESH_NON_EMPTY = 0x000001,     ///< Non-empty mesh
-    MESH_VISIBLE = 0x000002,       ///< Either mesh or surface are visible
-
-    MESH_HEAT = 0x000004,       ///< Show the heat map
-    MESH_LABEL = 0x000008,      ///< Show the label
-    MESH_NORMAL = 0x000010,     ///< Show the normal
-
-    MESH_SIGNAL = 0x000020,      ///< Show the signal
-    MESH_TEXTURE = 0x000040,     ///< Show the texture
-    MESH_IMAGE = 0x000080,       ///< Show the image
-
-    MESH_SHOW_MESH = 0x000100,     ///< Show the mesh
-    MESH_SHOW_SURF = 0x000200,     ///< Show the surface
-
-    MESH_ALL = 0x000400,         ///< Show the all mesh
-    MESH_BORDER = 0x000800,      ///< Show border only
-    MESH_CELLMAP = 0x001000,     ///< Show the cell map
-
-    MESH_CELLS = 0x002000,           ///< This mesh is a cell mesh
-    MESH_IMG_TEX = 0x004000,         ///< This mesh has a texture
-    MESH_SCALED = 0x008000,          ///< This mesh is scaled
-    MESH_TRANSFORMED = 0x010000,     ///< This mesh is transformed
-
-    MESH_EMPTY = 0x020000,               ///< Empty mesh
-    MESH_NON_CELLS = 0x040000,           ///< This mesh is not a cell mesh
-    MESH_NON_IMG_TEX = 0x080000,         ///< This mesh doesn't have an image texture
-    MESH_NON_SCALED = 0x100000,          ///< This mesh is non-scaled
-    MESH_NON_TRANSFORMED = 0x200000,     ///< This mesh is non-transformed
-  };
-
-  /**
-   * Enumeration of the type of checks that can be performed
-   */
-  enum CheckType {
-    CHECK_STACK = 0,     ///< Check stack properties
-    CHECK_STORE = 1,     ///< Check store properties
-    CHECK_MESH = 2       ///< Check mesh properties
-  };
-
-  enum CheckWhich {
-    CHECK_CURRENT = -1     ///< Constant marking the element to check is the current one
-  };
-
-  /**
-   * \class CheckState
+   * \class Process Process.hpp <Process.hpp>
    *
-   * Class that construct a state check on the current process.
+   * This is the main process class, the one all process inherit from.
+   * Note that you should \b never inherit this class directly, as it won't
+   * allow anything to be done. Instead, you should inherit one of the daughter
+   * class: StackProcess, MeshProcess or GlobalProcess.
+   * \ingroup ProcessUtils
    */
-  class MGX_EXPORT CheckState {
-public:
-    CheckState(const CheckState& copy);
-    CheckState(Process* process);
-
+  class MGX_EXPORT Process {
+  public:
+    static unsigned int processVersion;
+  
+    typedef std::vector<Stack*>::iterator stack_iterator;
+    typedef std::vector<Stack*>::const_iterator const_stack_iterator;
+  
+    typedef std::vector<Mesh*>::iterator mesh_iterator;
+    typedef std::vector<Mesh*>::const_iterator const_mesh_iterator;
+  
     /**
-     * Add a check for a store
+     * Default constructor.
      */
-    CheckState& store(int checks = STORE_ANY, int which = CHECK_CURRENT);
+    Process();
     /**
-     * Add a check for a stack
+     * Copy constructor.
+     *
+     * Note that you will always need to call this constructor explicitly from your process,
+     * as Process is inherited virtually. So all leaf class need to initialize it.
      */
-    CheckState& stack(int checks = STACK_ANY, int which = CHECK_CURRENT);
+    Process(const Process& p);
     /**
-     * Add a check for a mesh
+     * Virtual destructor
      */
-    CheckState& mesh(int checks = MESH_ANY, int which = CHECK_CURRENT);
-
+    virtual ~Process() {
+    }
+  
     /**
-     * A CheckState object converts to true if the checks hold on the current process
+     * Method to be called anytime a file is acted on (i.e. saved/loaded).
+     *
+     * If needed, it will set the current folder to the one containing the file and start a session
+     *
+     * If it is a project file (i.e. ending in mgxv), then project_file should be set to true to force the change in
+     * folder.
      */
-    operator bool();
+    void actingFile(const QString& filename, bool project_file = false);
+  
+    /**
+     * Get the file currently defining the path of the system
+     */
+    QString actingFile() const;
+  
+    /**
+     * Return the python call describing the current process
+     */
+    QString pythonCall(const QStringList& parms) const;
+  
+    /**
+     * Number of stacks available to the process
+     */
+    int stackCount() const;
+    /**
+     * Returns the ith stack, or 0 if there is no such stack.
+     */
+    Stack* stack(int i);
+    /**
+     * Returns the current stack (i.e. the stack currently selected by the user).
+     */
+    Stack* currentStack();
+    /**
+     * Return the id (i.e. number) of the current stack.
+     */
+    int currentStackId() const;
+    /**
+     * Change which stack is current.
+     */
+    void setCurrentStackId(int i);
+  
+    /// Iterate over all the stacks
+    std::pair<stack_iterator, stack_iterator> stacks();
+    /// Iterate over all the stacks
+    std::pair<const_stack_iterator, const_stack_iterator> stacks() const;
+  
+    /**
+     * Add a new stack to the process
+     */
+    Stack* addStack();
+  
+    /**
+     * Delete the stack of given id
+     *
+     * \note The current implementation assumes there are at least two stacks always available
+     */
+    bool deleteStack(int i);
+  
+    /**
+     * Returns the number of mesh available to the process
+     */
+    int meshCount() const;
+    /**
+     * Returns the ith mesh
+     */
+    Mesh* mesh(int i);
+    /**
+     * Returns the current mesh (i.e. the mesh currently selected by the user)
+     */
+    Mesh* currentMesh();
+    /**
+     * Returns the id (i.e. number) of the current mesh
+     */
+    int currentMeshId() const;
+    /**
+     * Change which mesh is current
+     */
+    void setCurrentMeshId(int i);
+  
+    /// Iterate over all the meshs
+    std::pair<mesh_iterator, mesh_iterator> meshes();
+    /// Iterate over all the meshs
+    std::pair<const_mesh_iterator, const_mesh_iterator> meshes() const;
+  
+    /**
+     * Add a mesh to the process for the given stack
+     */
+    Mesh* addMesh(const Stack* stack);
+  
+    /**
+     * Remove a mesh from the process
+     */
+    bool deleteMesh(int i);
+  
+    /**
+     * Get the current selected label
+     */
+    int selectedLabel() const;
+  
+    /**
+     * Change the current selected label
+     */
+    void setSelectedLabel(int label);
+  
+    /**
+     * Return the current setting for the global brightness level
+     */
+    float globalBrightness();
+  
+    /**
+     * Return the current setting for the global contrast level
+     */
+    float globalContrast();
+  
+    /**
+     * Change the current setting for the global brightness level
+     *
+     * The brightness is clamped to the range [-1;1]
+     */
+    void setGlobalBrightness(float value);
+  
+    /**
+     * Change the current setting for the global contrast level
+     *
+     * The contrast is clamped to the range [0;2]
+     */
+    void setGlobalContrast(float value);
+  
+    /**
+     * Returns if the user has mesh selection active
+     */
+    bool meshSelection() const;
+    /**
+     * Returns is the user has line border selection active
+     */
+    bool lineBorderSelection() const;
+  
+    /**
+     * Update the state of the application from the current data.
+     * The process is paused until it's done.
+     */
+    void updateState();
+    /**
+     * Force the viewer to refresh, without pausing the process.
+     */
+    void updateViewer();
+  
+    /**
+     * Set an error message that will be displayed if the process returns false.
+     */
+    bool setErrorMessage(const QString& str);
+  
+    /**
+     * Get the current error message
+     */
+    QString errorMessage() const;
+  
+    /**
+     * Set a warning message that will be displayed if the process returns true.
+     */
+    void setWarningMessage(const QString& str);
+    /**
+     * Get the current warning message
+     */
+    QString warningMessage() const;
+  
+    /**
+     * Throw an exception informing the system that the user canceled the current process.
+     */
+    void userCancel() const {
+      throw UserCancelException();
+    }
+  
+    /**
+     * Get the name of the file that was used to load the current process (i.e. the mgxv file), if any.
+     */
+    const QString& file() const;
+  
+    /**
+     * Return the object defining the first clipping region
+     */
+    Clip* clip1();
+    /**
+     * Return the object defining the second clipping region
+     */
+    Clip* clip2();
+    /**
+     * Return the object defining the third clipping region
+     */
+    Clip* clip3();
+  
+    /**
+     * Return the object defining the first clipping region
+     */
+    const Clip* clip1() const;
+    /**
+     * Return the object defining the second clipping region
+     */
+    const Clip* clip2() const;
+    /**
+     * Return the object defining the third clipping region
+     */
+    const Clip* clip3() const;
+  
+    /**
+     * Return the cutting surface.
+     */
+    CuttingSurface* cuttingSurface();
+    /**
+     * Return the cutting surface.
+     */
+    const CuttingSurface* cuttingSurface() const;
+  
+    //@{
+    //\name Methods needed to launch other processes
+  
+    /**
+     * Creates a process object by name
+     */
+    Process* makeProcess(const QString& processType, const QString& processName);
+  
+    /**
+     * Launch a process with generic arguments.
+     *
+     * Note that exceptions are filtered and converted into an error message and the process returning false.
+     */
+    bool RunProcess(Process& proc, const QStringList& parms) throw();
+  
+    /**
+     * Launch a process by name
+     *
+     * Note that exceptions are filtered and converted into an error message and the process returning false.
+     */
+    bool RunProcess(const QString& processType, const QString& processName, const QStringList& parms) throw();
+    //@}
+  
+    /**
+     * Returns a string identifying the process type.
+     */
+    virtual QString type() const = 0;
+  
+    // @{ Functions to be defined by the user
+  
+    /**
+     * Implementation of the process with generic arguments.
+     *
+     * The number of arguments is guaranteed to be at least as many as the ones named in the process.
+     */
+    virtual bool operator()(const QStringList& parms) = 0;
+    /**
+     * Returns the name of the process. Note that the name must be a valid identifier in Python once the spaces are
+     * replaced by underscores. Also, all underscore in the name will be replaced by spaces for user presentation.
+     */
+    virtual QString name() const = 0;
+    /**
+     * Returns a description of the process for the GUI.
+     */
+    virtual QString description() const = 0;
+    /**
+     * Folder in which to place the process.
+     *
+     * Subfolders can be specified by placing '/' in the path
+     *
+     * \note This is a purely presentation parameter. It doesn't allow two processes to have the same name if they are
+     * in different folders.
+     */
+    virtual QString folder() const {
+      return QString();
+    }
+    /**
+     * List of named parameters.
+     *
+     * There must be as many parameters than defaults.
+     */
+    virtual QStringList parmNames() const = 0;
+    /**
+     * List of parameters descriptions.
+     *
+     * There must be as many parameters than defaults.
+     */
+    virtual QStringList parmDescs() const {
+      return QStringList();
+    }
+    /**
+     * List of default parms.
+     */
+    virtual QStringList parmDefaults() const {
+      return QStringList();
+    }
+    /**
+     * Purely for GUI purposes, provides for some of the parms parameter a choice. In this case, the user will be
+     * presented with a combo box presenting the provided list. Note that no mechanism forces the user to choose one
+     * of this choice.
+     */
+    virtual ParmChoiceMap parmChoice() const {
+      return ParmChoiceMap();
+    }
+    /**
+     * Icon to use to represent the process in the GUI.
+     *
+     * Note that to use an icon present in the resources, you must precede the path with a colon (i.e.
+     * ":/images/myicon.png".
+     */
+    virtual QIcon icon() const {
+      return QIcon();
+    }
+    /**
+     * This is an optional method that is called only when a process is launched from the GUI.
+     *
+     * If reimplemented, it receives a potential argument list, and should provide a GUI for editing it. Once the user
+     * finishing the edition, this method should modify the provided arguments and return true. If the user aborts,
+     * the method should return false. Note that returning false does not produce an error.
+     *
+     * \param parms List of arguments
+     * \param parent Pointer to the parent widget. If the configure method creates a GUI, it should be a child of this
+     * widget.
+     */
+    virtual bool initialize(QStringList& /*parms*/, QWidget* /*parent*/) {
+      return true;
+    }
+    // @}
+  
+    /**
+     * Helper function that provides a list of choices for a boolean argument
+     */
+    QStringList booleanChoice() const
+    {
+      return QStringList() << "Yes"
+                           << "No";
+    }
+    /**
+     * Helper function that provides a list of choices for choosing from the main or work stack
+     */
+    QStringList storeChoice() const
+    {
+      return QStringList() << "Main"
+                           << "Work";
+    }
+  
+    /**
+     * Returns the number of named string for this process
+     */
+    virtual uint numParms() const {
+      return parmDefaults().size();
+    }
+  
+    //@{
+    //\name Methods to get and check elements
+  
+    /**
+     * Enumeration for the bitfield that identifies stack properties
+     */
+    enum StackCheckType {
+      STACK_ANY = 0,              ///< Any stack
+      STACK_NON_EMPTY = 0x01,     ///< Non-empty stack
+      STACK_VISIBLE = 0x02,       ///< Visible stack
+      STACK_EMPTY = 0x04,         ///< Empty stack
+  
+      STACK_SCALED = 0x08,              ///< Scaled stack
+      STACK_TRANSFORMED = 0x10,         ///< Transformed stack
+      STACK_NON_SCALED = 0x20,          ///< Non-Scaled stack
+      STACK_NON_TRANSFORMED = 0x40,     ///< Non-Transformed stack
+    };
+  
+    /**
+     * Enumeration for the bitfield that identifies store properties
+     */
+    enum StoreCheckType {
+      STORE_ANY = 0,                ///< Any store
+      STORE_NON_EMPTY = 0x0001,     ///< Non-Empty store
+      STORE_VISIBLE = 0x0002,       ///< Visible store
+      STORE_EMPTY = 0x0004,         ///< Empty store
+  
+      STORE_LABEL = 0x0008,         ///< Label store
+      STORE_NON_LABEL = 0x0010,     ///< Non-Label store
+  
+      STORE_SCALED = 0x0020,              ///< Scaled store
+      STORE_TRANSFORMED = 0x0040,         ///< Transformed store
+      STORE_NON_SCALED = 0x0080,          ///< Non-Scaled store
+      STORE_NON_TRANSFORMED = 0x0100,     ///< Non-Transformed store
+  
+      STORE_WORK = 0x1000,     ///< Work store
+      STORE_MAIN = 0x2000      ///< Main store
+    };
+  
+    /**
+     * Enumeration for the bitfield that identifies mesh properties
+     */
+    enum MeshCheckType {
+      MESH_ANY = 0,                  ///< Any mesh
+      MESH_NON_EMPTY = 0x000001,     ///< Non-empty mesh
+      MESH_VISIBLE = 0x000002,       ///< Either mesh or surface are visible
+  
+      MESH_HEAT = 0x000004,       ///< Show the heat map
+      MESH_LABEL = 0x000008,      ///< Show the label
+      MESH_NORMAL = 0x000010,     ///< Show the normal
+  
+      MESH_SIGNAL = 0x000020,      ///< Show the signal
+      MESH_TEXTURE = 0x000040,     ///< Show the texture
+      MESH_IMAGE = 0x000080,       ///< Show the image
+  
+      MESH_SHOW_MESH = 0x000100,     ///< Show the mesh
+      MESH_SHOW_SURF = 0x000200,     ///< Show the surface
+  
+      MESH_ALL = 0x000400,         ///< Show the all mesh
+      MESH_BORDER = 0x000800,      ///< Show border only
+      MESH_CELLMAP = 0x001000,     ///< Show the cell map
+  
+      MESH_CELLS = 0x002000,           ///< This mesh is a cell mesh
+      MESH_IMG_TEX = 0x004000,         ///< This mesh has a texture
+      MESH_SCALED = 0x008000,          ///< This mesh is scaled
+      MESH_TRANSFORMED = 0x010000,     ///< This mesh is transformed
+  
+      MESH_EMPTY = 0x020000,               ///< Empty mesh
+      MESH_NON_CELLS = 0x040000,           ///< This mesh is not a cell mesh
+      MESH_NON_IMG_TEX = 0x080000,         ///< This mesh doesn't have an image texture
+      MESH_NON_SCALED = 0x100000,          ///< This mesh is non-scaled
+      MESH_NON_TRANSFORMED = 0x200000,     ///< This mesh is non-transformed
 
-protected:
-    void setError();
-
-    struct ProcessReqs {
-      int type;
-      int checks;
-      int which;
+      MESH_PARENT = 0x400000,              ///< Show the parent label
+      MESH_LABEL_PARENT = 0x800000         ///< Show the parent or label
     };
-
-    QList<ProcessReqs> reqs;
-    Process* process;
+  
+    /**
+     * Enumeration of the type of checks that can be performed
+     */
+    enum CheckType {
+      CHECK_STACK = 0,     ///< Check stack properties
+      CHECK_STORE = 1,     ///< Check store properties
+      CHECK_MESH = 2       ///< Check mesh properties
+    };
+  
+    enum CheckWhich {
+      CHECK_CURRENT = -1     ///< Constant marking the element to check is the current one
+    };
+  
+    /**
+     * \class CheckState
+     *
+     * Class that construct a state check on the current process.
+     */
+    class MGX_EXPORT CheckState {
+  public:
+      CheckState(const CheckState& copy);
+      CheckState(Process* process);
+  
+      /**
+       * Add a check for a store
+       */
+      CheckState& store(int checks = STORE_ANY, int which = CHECK_CURRENT);
+      /**
+       * Add a check for a stack
+       */
+      CheckState& stack(int checks = STACK_ANY, int which = CHECK_CURRENT);
+      /**
+       * Add a check for a mesh
+       */
+      CheckState& mesh(int checks = MESH_ANY, int which = CHECK_CURRENT);
+  
+      /**
+       * A CheckState object converts to true if the checks hold on the current process
+       */
+      operator bool();
+  
+  protected:
+      void setError();
+  
+      struct ProcessReqs {
+        int type;
+        int checks;
+        int which;
+      };
+  
+      QList<ProcessReqs> reqs;
+      Process* process;
+    };
+  
+    friend class Process::CheckState;
+  
+    /**
+     * Call this function and convert the result to a boolean. If the checks hold, it will return true. If not, it
+     * will return false and set the error message to a standard, fully descriptive description of what conditions
+     * should be met to use this process.
+     *
+     * Syntax:
+     *
+     * checkState().TYPE(CONSTRAINTS).TYPE(CONSTRAINTS)...;
+     *
+     * Example:
+     *
+     * if(!checkState().store(STORE_MAIN | STORE_NON_EMPTY)
+     *                 .store(STORE_WORK | STORE_LABEL))
+     *   return false;
+     *
+     */
+    CheckState checkState();
+    //@}
+  
+    PrivateProcess* p;
+  
+  protected:
+    //@{
+    ///\name Internal methods
+  
+    /**
+     * Method that can be used to launch a system command. The process programmer should not use this directly but use
+     * one of the public convenience method instead.
+     */
+    bool systemCommand(SystemCommand cmd, const QStringList& parms);
+    /**
+     * Check stack properties
+     */
+    bool stackCheck(int checks, int which);
+    /**
+     * Check store properties
+     */
+    bool storeCheck(int checks, int which);
+    /**
+     * Check mesh properties
+     */
+    bool meshCheck(int checks, int which);
+  
+    /**
+     * Generate a standardised string describing how the stack should be to not generate an error
+     */
+    QString stackError(int checks, int which);
+    /**
+     * Generate a standardised string describing how the store should be to not generate an error
+     */
+    QString storeError(int checks, int which);
+    /**
+     * Generate a standardised string describing how the mesh should be to not generate an error
+     */
+    QString meshError(int checks, int which);
+    //@}
   };
-
-  friend class Process::CheckState;
-
+  
   /**
-   * Call this function and convert the result to a boolean. If the checks hold, it will return true. If not, it
-   * will return false and set the error message to a standard, fully descriptive description of what conditions
-   * should be met to use this process.
+   * \class StackProcess Process.hpp <Process.hpp>
    *
-   * Syntax:
+   * Stack processes have non-mutable access to meshes and mutable access to stacks.
    *
-   * checkState().TYPE(CONSTRAINTS).TYPE(CONSTRAINTS)...;
-   *
-   * Example:
-   *
-   * if(!checkState().store(STORE_MAIN | STORE_NON_EMPTY)
-   *                 .store(STORE_WORK | STORE_LABEL))
-   *   return false;
-   *
+   * As such, they can only create other stack processes.
+   * \ingroup ProcessUtils
    */
-  CheckState checkState();
-  //@}
-
-  PrivateProcess* p;
-
-protected:
-  //@{
-  ///\name Internal methods
-
+  class MGX_EXPORT StackProcess : public virtual Process {
+    friend class SetupProcess;
+    friend class GlobalProcess;
+    StackProcess() {
+    }
+  
+  public:
+    /**
+     * Copy constructor.
+     *
+     * This is the only way to create a stack process. It cannot be created without a pre-existing context.
+     */
+    StackProcess(const StackProcess& copy) : Process(copy) {}
+  
+    virtual QString type() const {
+      return "Stack";
+    }
+    const Mesh* mesh(int i) {
+      return Process::mesh(i);
+    }
+    const Mesh* currentMesh() {
+      return Process::currentMesh();
+    }
+    std::pair<const_mesh_iterator, const_mesh_iterator> meshes() const {
+      return Process::meshes();
+    }
+  };
+  
   /**
-   * Method that can be used to launch a system command. The process programmer should not use this directly but use
-   * one of the public convenience method instead.
-   */
-  bool systemCommand(SystemCommand cmd, const QStringList& parms);
-  /**
-   * Check stack properties
-   */
-  bool stackCheck(int checks, int which);
-  /**
-   * Check store properties
-   */
-  bool storeCheck(int checks, int which);
-  /**
-   * Check mesh properties
-   */
-  bool meshCheck(int checks, int which);
-
-  /**
-   * Generate a standardised string describing how the stack should be to not generate an error
-   */
-  QString stackError(int checks, int which);
-  /**
-   * Generate a standardised string describing how the store should be to not generate an error
-   */
-  QString storeError(int checks, int which);
-  /**
-   * Generate a standardised string describing how the mesh should be to not generate an error
-   */
-  QString meshError(int checks, int which);
-  //@}
-};
-
-/**
- * \class StackProcess Process.hpp <Process.hpp>
- *
- * Stack processes have non-mutable access to meshes and mutable access to stacks.
- *
- * As such, they can only create other stack processes.
- * \ingroup ProcessUtils
- */
-class MGX_EXPORT StackProcess : public virtual Process {
-  friend class SetupProcess;
-  friend class GlobalProcess;
-  StackProcess() {
-  }
-
-public:
-  /**
-   * Copy constructor.
+   * \class MeshProcess Process.hpp <Process.hpp>
    *
-   * This is the only way to create a stack process. It cannot be created without a pre-existing context.
-   */
-  StackProcess(const StackProcess& copy)
-    : Process(copy)
-  {
-  }
-
-  virtual QString type() const {
-    return "Stack";
-  }
-  const Mesh* mesh(int i) {
-    return Process::mesh(i);
-  }
-  const Mesh* currentMesh() {
-    return Process::currentMesh();
-  }
-  std::pair<const_mesh_iterator, const_mesh_iterator> meshes() const {
-    return Process::meshes();
-  }
-};
-
-/**
- * \class MeshProcess Process.hpp <Process.hpp>
- *
- * Mesh processes have mutable access to meshes and non-mutable access to stacks
- *
- * As such, they can only create other mesh processes.
- * \ingroup ProcessUtils
- */
-class MGX_EXPORT MeshProcess : public virtual Process {
-  friend class SetupProcess;
-  friend class GlobalProcess;
-  MeshProcess() {
-  }
-
-public:
-  /**
-   * Copy constructor.
+   * Mesh processes have mutable access to meshes and non-mutable access to stacks
    *
-   * This is the only way to create a mesh process. It cannot be created without a pre-existing context.
+   * As such, they can only create other mesh processes.
+   * \ingroup ProcessUtils
    */
-  MeshProcess(const MeshProcess& copy)
-    : Process(copy)
-  {
-  }
-
-  virtual QString type() const {
-    return "Mesh";
-  }
-  const Stack* stack(int i) {
-    return Process::stack(i);
-  }
-  const Stack* currentStack() {
-    return Process::currentStack();
-  }
-  std::pair<const_stack_iterator, const_stack_iterator> stacks() const {
-    return Process::stacks();
-  }
-};
-
-/**
- * \class GlobalProcess Process.hpp <Process.hpp>
- *
- * Global processes have full mutable access to all properties of the process.
- *
- * As such, they can create any kind of process.
- * \ingroup ProcessUtils
- */
-class MGX_EXPORT GlobalProcess : public MeshProcess, public StackProcess {
-  friend class SetupProcess;
-  GlobalProcess() {
-  }
-
-public:
+  class MGX_EXPORT MeshProcess : public virtual Process {
+    friend class SetupProcess;
+    friend class GlobalProcess;
+    MeshProcess() {
+    }
+  
+  public:
+    /**
+     * Copy constructor.
+     *
+     * This is the only way to create a mesh process. It cannot be created without a pre-existing context.
+     */
+    MeshProcess(const MeshProcess& copy)
+      : Process(copy)
+    {
+    }
+  
+    virtual QString type() const {
+      return "Mesh";
+    }
+    const Stack* stack(int i) {
+      return Process::stack(i);
+    }
+    const Stack* currentStack() {
+      return Process::currentStack();
+    }
+    std::pair<const_stack_iterator, const_stack_iterator> stacks() const {
+      return Process::stacks();
+    }
+  };
+  
   /**
-   * Copy constructor.
+   * \class GlobalProcess Process.hpp <Process.hpp>
    *
-   * This is the only way to create a global process. It cannot be created without a pre-existing context.
+   * Global processes have full mutable access to all properties of the process.
+   *
+   * As such, they can create any kind of process.
+   * \ingroup ProcessUtils
    */
-  GlobalProcess(const GlobalProcess& copy)
-    : Process(copy)
-    , MeshProcess(copy)
-    , StackProcess(copy)
-  {
-  }
-
-  virtual QString type() const {
-    return "Global";
-  }
-  Mesh* mesh(int i) {
-    return Process::mesh(i);
-  }
-  Mesh* currentMesh() {
-    return Process::currentMesh();
-  }
-  Stack* stack(int i) {
-    return Process::stack(i);
-  }
-  Stack* currentStack() {
-    return Process::currentStack();
-  }
-  std::pair<stack_iterator, stack_iterator> stacks() {
-    return Process::stacks();
-  }
-  std::pair<const_stack_iterator, const_stack_iterator> stacks() const {
-    return Process::stacks();
-  }
-  std::pair<mesh_iterator, mesh_iterator> meshes() {
-    return Process::meshes();
-  }
-  std::pair<const_mesh_iterator, const_mesh_iterator> meshes() const {
-    return Process::meshes();
-  }
-
-  bool setCurrentStack(int id, bool is_main);
-
-  bool resetProject();
-
-  bool takeSnapshot(QString filename, float overSampling = 1.0f, int width = 0, int height = 0, int quality = 95,
-                    bool expand_frustum = false);
-
-  using Process::systemCommand;   //(SystemCommand cmd, const QStringList& parms);
-};
-
-#ifndef DOXYGEN
-
-template <typename P> struct ProcessFactory {
-  typedef P ProcessType;
-
-  ProcessFactory()
-    : cnt(0)
-  {
-  }
-  ProcessFactory(const ProcessFactory&)
-    : cnt(0)
-  {
-  }
-  virtual ~ProcessFactory() {
-  }
-
-  virtual ProcessType* operator()(const ProcessType& process) const = 0;
-
-  int cnt;
-};
-
-#  ifdef WIN32
-template struct MGX_EXPORT ProcessFactory<StackProcess>;
-template struct MGX_EXPORT ProcessFactory<MeshProcess>;
-template struct MGX_EXPORT ProcessFactory<GlobalProcess>;
-#  endif
-
-template <typename P, typename Process> struct ClassProcessFactory : public ProcessFactory<P> {
-  ClassProcessFactory()
-    : ProcessFactory<P>()
-  {
-  }
-  ClassProcessFactory(const ClassProcessFactory& copy)
-    : ProcessFactory<P>(copy)
-  {
-  }
-
-  typedef P ProcessType;
-  virtual ProcessType* operator()(const ProcessType& process) const {
-    return new Process(process);
-  }
-};
-
-template <typename X> struct FactoryPointer {
-  typedef X ProcessType;
-  typedef ProcessFactory<X> value;
-  typedef ProcessFactory<X>* pointer;
-  typedef ProcessFactory<X>& reference;
-  typedef const ProcessFactory<X>* const_pointer;
-  typedef const ProcessFactory<X>& const_reference;
-
-  FactoryPointer()
-    : p(0)
-  {
-  }
-
-  FactoryPointer(pointer ptr)
-    : p(ptr)
-  {
-    acquire();
-  }
-
-  template <typename T>
-  FactoryPointer(T* ptr)
-    : p(ptr)
-  {
-    acquire();
-  }
-
-  FactoryPointer(const FactoryPointer& other)
-    : p(other.p)
-  {
-    acquire();
-  }
-
-  template <typename T>
-  FactoryPointer(const FactoryPointer<T>& other)
-    : p(other.p)
-  {
-    acquire();
-  }
-
-  ~FactoryPointer() {
-    release();
-  }
-
-  operator bool() const { return bool(p); }
-
-  ProcessType* operator()(const ProcessType& process) const {
-    return (*p)(process);
-  }
-
-  template <typename T> FactoryPointer& operator=(const T* other)
-  {
-    if(p != other) {
-      release();
-      p = other;
+  class MGX_EXPORT GlobalProcess : public MeshProcess, public StackProcess {
+    friend class SetupProcess;
+    GlobalProcess() {}
+  
+  public:
+    /**
+     * Copy constructor.
+     *
+     * This is the only way to create a global process. It cannot be created without a pre-existing context.
+     */
+    GlobalProcess(const GlobalProcess& copy)
+      : Process(copy) , MeshProcess(copy) , StackProcess(copy) {}
+  
+    virtual QString type() const {
+      return "Global";
+    }
+    Mesh* mesh(int i) {
+      return Process::mesh(i);
+    }
+    Mesh* currentMesh() {
+      return Process::currentMesh();
+    }
+    Stack* stack(int i) {
+      return Process::stack(i);
+    }
+    Stack* currentStack() {
+      return Process::currentStack();
+    }
+    std::pair<stack_iterator, stack_iterator> stacks() {
+      return Process::stacks();
+    }
+    std::pair<const_stack_iterator, const_stack_iterator> stacks() const {
+      return Process::stacks();
+    }
+    std::pair<mesh_iterator, mesh_iterator> meshes() {
+      return Process::meshes();
+    }
+    std::pair<const_mesh_iterator, const_mesh_iterator> meshes() const {
+      return Process::meshes();
+    }
+  
+    bool setCurrentStack(int id, bool is_main);
+  
+    bool resetProject();
+  
+    bool takeSnapshot(QString filename, float overSampling = 1.0f, int width = 0, int height = 0, int quality = 95,
+                      bool expand_frustum = false);
+  
+    using Process::systemCommand;   //(SystemCommand cmd, const QStringList& parms);
+  };
+  
+  #ifndef DOXYGEN
+  
+  template <typename P> struct ProcessFactory {
+    typedef P ProcessType;
+  
+    ProcessFactory() : cnt(0) {}
+    ProcessFactory(const ProcessFactory&) : cnt(0) {}
+    virtual ~ProcessFactory() {}
+  
+    virtual ProcessType* operator()(const ProcessType& process) const = 0;
+  
+    int cnt;
+  };
+  
+  #  ifdef WIN32
+  template struct MGX_EXPORT ProcessFactory<StackProcess>;
+  template struct MGX_EXPORT ProcessFactory<MeshProcess>;
+  template struct MGX_EXPORT ProcessFactory<GlobalProcess>;
+  #  endif
+  
+  template <typename P, typename Process> struct ClassProcessFactory : public ProcessFactory<P> {
+    ClassProcessFactory() : ProcessFactory<P>() {}
+    ClassProcessFactory(const ClassProcessFactory& copy) : ProcessFactory<P>(copy) {}
+  
+    typedef P ProcessType;
+    virtual ProcessType* operator()(const ProcessType& process) const {
+      return new Process(process);
+    }
+  };
+  
+  template <typename X> struct FactoryPointer {
+    typedef X ProcessType;
+    typedef ProcessFactory<X> value;
+    typedef ProcessFactory<X>* pointer;
+    typedef ProcessFactory<X>& reference;
+    typedef const ProcessFactory<X>* const_pointer;
+    typedef const ProcessFactory<X>& const_reference;
+  
+    FactoryPointer() : p(0) {}
+  
+    FactoryPointer(pointer ptr) : p(ptr)
+    {
       acquire();
     }
-    return *this;
-  }
-
-  FactoryPointer& operator=(const FactoryPointer& other)
-  {
-    if(p != other.p) {
-      release();
-      p = other.p;
+  
+    template <typename T>
+    FactoryPointer(T* ptr) : p(ptr)
+    {
       acquire();
     }
-    return *this;
-  }
-
-  template <typename T> FactoryPointer& operator=(const FactoryPointer<T>& other)
-  {
-    if(p != other.p) {
-      release();
-      p = other.p;
+  
+    FactoryPointer(const FactoryPointer& other) : p(other.p)
+    {
       acquire();
     }
-    return *this;
+  
+    template <typename T>
+    FactoryPointer(const FactoryPointer<T>& other) : p(other.p)
+    {
+      acquire();
+    }
+  
+    ~FactoryPointer() {
+      release();
+    }
+  
+    operator bool() const { return bool(p); }
+  
+    ProcessType* operator()(const ProcessType& process) const {
+      return (*p)(process);
+    }
+  
+    template <typename T> FactoryPointer& operator=(const T* other)
+    {
+      if(p != other) {
+        release();
+        p = other;
+        acquire();
+      }
+      return *this;
+    }
+  
+    FactoryPointer& operator=(const FactoryPointer& other)
+    {
+      if(p != other.p) {
+        release();
+        p = other.p;
+        acquire();
+      }
+      return *this;
+    }
+  
+    template <typename T> FactoryPointer& operator=(const FactoryPointer<T>& other)
+    {
+      if(p != other.p) {
+        release();
+        p = other.p;
+        acquire();
+      }
+      return *this;
+    }
+  
+    bool operator==(const FactoryPointer& other) const {
+      return p == other.p;
+    }
+  
+    bool operator!=(const FactoryPointer& other) const {
+      return p != other.p;
+    }
+  
+    reference operator*() {
+      return *p;
+    }
+    pointer operator->() {
+      return p;
+    }
+  
+    const_reference operator*() const {
+      return *p;
+    }
+    const_pointer operator->() const {
+      return p;
+    }
+  
+    uintptr_t id() const {
+      return (uintptr_t)p;
+    }
+  
+  private:
+    void release()
+    {
+      if(p) {
+        p->cnt--;
+        if(p->cnt == 0) {
+          if(DEBUG)
+            Information::out << "Deleting factory for " << util::qdemangle(typeid(*p).name())
+                             << " at address 0x" << QString::number(id(), 16) << endl;
+          delete p;
+        }
+        p = 0;
+      }
+    }
+  
+    void acquire()
+    {
+      if(p)
+        p->cnt++;
+    }
+  
+    pointer p;
+  };
+  
+  template <typename P> struct Registration {
+    typedef P ProcessType;
+    typedef FactoryPointer<P> processFactory;
+    typedef QList<processFactory> factoryList;
+  
+    Registration(processFactory f, const char* class_name, unsigned int compiledVersion);
+    ~Registration();
+    static factoryList& processFactories();
+  
+    processFactory factory;
+    const char* classname;
+  
+  private:
+    static factoryList factories;
+  };
+  
+  template <typename P>
+  Registration<P>::Registration(processFactory f, const char* class_name, unsigned int compiledVersion)
+    : factory(), classname(class_name)
+  {
+    if(DEBUG) {
+      Information::out << "Registration of process " << util::qdemangle(classname) << " at address 0x"
+                       << QString::number(f.id(), 16) << endl
+                       << "    Type of data: " << util::qdemangle(typeid(*f).name()) << endl;
+    }
+    if(Process::processVersion != compiledVersion) {
+      QTextStream err(stderr);
+      err << "Error registering factory " << util::qdemangle(class_name) << endl
+          << " It has been compiled against a different revision of MorphoGraphX:" << QString::number(compiledVersion)
+          << endl << " and MorphoGraphX is running process revision:" << QString::number(Process::processVersion)
+          << endl;
+    } else {
+      factory = f;
+      if(!factory and DEBUG)
+        Information::out << "Storing null factory!" << endl;
+      processFactories() << factory;
+    }
   }
-
-  bool operator==(const FactoryPointer& other) const {
-    return p == other.p;
-  }
-
-  bool operator!=(const FactoryPointer& other) const {
-    return p != other.p;
-  }
-
-  reference operator*() {
-    return *p;
-  }
-  pointer operator->() {
-    return p;
-  }
-
-  const_reference operator*() const {
-    return *p;
-  }
-  const_pointer operator->() const {
-    return p;
-  }
-
-  uintptr_t id() const {
-    return (uintptr_t)p;
-  }
-
-private:
-  void release()
+  
+  template <typename P> Registration<P>::~Registration()
   {
-    if(p) {
-      p->cnt--;
-      if(p->cnt == 0) {
-        if(DEBUG)
-          Information::out << "Deleting factory for " << util::qdemangle(typeid(*p).name())
-                           << " at address 0x" << QString::number(id(), 16) << endl;
-        delete p;
+    if(factory) {
+      if(DEBUG) {
+        Information::out << "Unregistration of process " << util::qdemangle(classname) << " at address 0x"
+                         << QString::number(factory.id(), 16) << endl
+                         << "    Type of data: " << util::qdemangle(typeid(*factory).name()) << endl;
       }
-      p = 0;
+      QList<processFactory>& list = processFactories();
+      int size_before = list.size();
+      for(int i = 0; i < list.size(); ++i) {
+        if(list[i] == factory) {
+          list.removeAt(i);
+          break;
+        }
+      }
+      if(DEBUG and list.size() == size_before) {
+        Information::out << "Error, could not find processFactory to remove" << endl;
+      }
     }
   }
-
-  void acquire()
+  
+  template <typename P> QList<typename Registration<P>::processFactory>& Registration<P>::processFactories()
   {
-    if(p)
-      p->cnt++;
+    return factories;
   }
-
-  pointer p;
-};
-
-template <typename P> struct Registration {
-  typedef P ProcessType;
-  typedef FactoryPointer<P> processFactory;
-  typedef QList<processFactory> factoryList;
-
-  Registration(processFactory f, const char* class_name, unsigned int compiledVersion);
-  ~Registration();
-  static factoryList& processFactories();
-
-  processFactory factory;
-  const char* classname;
-
-private:
-  static factoryList factories;
-};
-
-template <typename P>
-Registration<P>::Registration(processFactory f, const char* class_name, unsigned int compiledVersion)
-  : factory()
-  , classname(class_name)
-{
-  if(DEBUG) {
-    Information::out << "Registration of process " << util::qdemangle(classname) << " at address 0x"
-                     << QString::number(f.id(), 16) << endl
-                     << "    Type of data: " << util::qdemangle(typeid(*f).name()) << endl;
+  
+  #  ifdef WIN32
+  template struct MGX_EXPORT Registration<StackProcess>;
+  template struct MGX_EXPORT Registration<MeshProcess>;
+  template struct MGX_EXPORT Registration<GlobalProcess>;
+  #  else
+  template <typename P> typename Registration<P>::factoryList Registration<P>::factories;
+  #  endif
+  
+  typedef Registration<StackProcess> StackRegistration;
+  typedef Registration<MeshProcess> MeshRegistration;
+  typedef Registration<GlobalProcess> GlobalRegistration;
+  
+  typedef StackRegistration::processFactory stackProcessFactory;
+  typedef MeshRegistration::processFactory meshProcessFactory;
+  typedef GlobalRegistration::processFactory globalProcessFactory;
+  
+  inline QList<stackProcessFactory>& stackProcessFactories() {
+    return StackRegistration::processFactories();
   }
-  if(Process::processVersion != compiledVersion) {
-    QTextStream err(stderr);
-    err << "Error registering factory " << util::qdemangle(class_name) << endl
-        << " It has been compiled against a different version of MorphoGraphX:" << QString::number(compiledVersion)
-        << endl << " and MorphoGraphX is running processes version:" << QString::number(Process::processVersion)
-        << endl;
-  } else {
-    factory = f;
-    if(!factory and DEBUG)
-      Information::out << "Storing null factory!" << endl;
-    processFactories() << factory;
+  inline QList<meshProcessFactory>& meshProcessFactories() {
+    return MeshRegistration::processFactories();
   }
-}
-
-template <typename P> Registration<P>::~Registration()
-{
-  if(factory) {
-    if(DEBUG) {
-      Information::out << "Unregistration of process " << util::qdemangle(classname) << " at address 0x"
-                       << QString::number(factory.id(), 16) << endl
-                       << "    Type of data: " << util::qdemangle(typeid(*factory).name()) << endl;
-    }
-    QList<processFactory>& list = processFactories();
-    int size_before = list.size();
-    for(int i = 0; i < list.size(); ++i) {
-      if(list[i] == factory) {
-        list.removeAt(i);
-        break;
-      }
-    }
-    if(DEBUG and list.size() == size_before) {
-      Information::out << "Error, could not find processFactory to remove" << endl;
-    }
+  inline QList<globalProcessFactory>& globalProcessFactories() {
+    return GlobalRegistration::processFactories();
   }
-}
-
-template <typename P> QList<typename Registration<P>::processFactory>& Registration<P>::processFactories()
-{
-  return factories;
-}
-
-#  ifdef WIN32
-template struct MGX_EXPORT Registration<StackProcess>;
-template struct MGX_EXPORT Registration<MeshProcess>;
-template struct MGX_EXPORT Registration<GlobalProcess>;
-#  else
-template <typename P> typename Registration<P>::factoryList Registration<P>::factories;
-#  endif
-
-typedef Registration<StackProcess> StackRegistration;
-typedef Registration<MeshProcess> MeshRegistration;
-typedef Registration<GlobalProcess> GlobalRegistration;
-
-typedef StackRegistration::processFactory stackProcessFactory;
-typedef MeshRegistration::processFactory meshProcessFactory;
-typedef GlobalRegistration::processFactory globalProcessFactory;
-
-inline QList<stackProcessFactory>& stackProcessFactories() {
-  return StackRegistration::processFactories();
-}
-inline QList<meshProcessFactory>& meshProcessFactories() {
-  return MeshRegistration::processFactories();
-}
-inline QList<globalProcessFactory>& globalProcessFactories() {
-  return GlobalRegistration::processFactories();
-}
-#endif
-
-/**
- * \def REGISTER_STACK_PROCESS(ClassName)
- *
- * Register \c ClassName has a stack process. It must inherit StackProcess and have a constructor accepting a single
- * StackProcess.
- * \ingroup ProcessUtils
- */
-#define REGISTER_STACK_PROCESS(ClassName)                                                                       \
-  mgx::process::StackRegistration ClassName ## registration(new ClassProcessFactory<StackProcess, ClassName>(), \
-                                                            typeid(ClassName).name(), PROCESS_VERSION)
-
-/**
- * \def REGISTER_MESH_PROCESS(ClassName)
- *
- * Register \c ClassName has a mesh process. It must inherit MeshProcess and have a constructor accepting a single
- * MeshProcess.
- * \ingroup ProcessUtils
- */
-#define REGISTER_MESH_PROCESS(ClassName)                                                                      \
-  mgx::process::MeshRegistration ClassName ## registration(new ClassProcessFactory<MeshProcess, ClassName>(), \
-                                                           typeid(ClassName).name(), PROCESS_VERSION)
-
-/**
- * \def REGISTER_GLOBAL_PROCESS(ClassName)
- *
- * Register \c ClassName has a global process. It must inherit GlobalProcess and have a constructor accepting a single
- * GlobalProcess.
- * \ingroup ProcessUtils
- */
-#define REGISTER_GLOBAL_PROCESS(ClassName)                                                                        \
-  mgx::process::GlobalRegistration ClassName ## registration(new ClassProcessFactory<GlobalProcess, ClassName>(), \
+  #endif
+  
+  /**
+   * \def REGISTER_STACK_PROCESS(ClassName)
+   *
+   * Register \c ClassName has a stack process. It must inherit StackProcess and have a constructor accepting a single
+   * StackProcess.
+   * \ingroup ProcessUtils
+   */
+  #define REGISTER_STACK_PROCESS(ClassName)                                                                       \
+    mgx::process::StackRegistration ClassName ## registration(new ClassProcessFactory<StackProcess, ClassName>(), \
+                                                              typeid(ClassName).name(), PROCESS_VERSION)
+  
+  /**
+   * \def REGISTER_MESH_PROCESS(ClassName)
+   *
+   * Register \c ClassName has a mesh process. It must inherit MeshProcess and have a constructor accepting a single
+   * MeshProcess.
+   * \ingroup ProcessUtils
+   */
+  #define REGISTER_MESH_PROCESS(ClassName)                                                                      \
+    mgx::process::MeshRegistration ClassName ## registration(new ClassProcessFactory<MeshProcess, ClassName>(), \
                                                              typeid(ClassName).name(), PROCESS_VERSION)
-
-/**
- * \struct BaseProcessDefinition Process.hpp <Process.hpp>
- *
- * Definition of a process, without the process factory.
- * \ingroup ProcessUtils
- */
-struct MGX_EXPORT BaseProcessDefinition {
-  QString name;            ///< Name of the process
-  QString description;     ///< Description of the process
-  QStringList parmNames;   ///< List of named parameters of the process
-  QStringList parmDescs;   ///< List of descriptions of named parameters
-  QStringList parms;       ///< List of parameters/parameter defaults
-  QString folder;          ///< Folder in which to place the process
-  QIcon icon;              ///< Icon of the process
-  // uint nbNamedStrings;     ///< Number of named string parameters
-  // uint nbNamedValues;      ///< Number of named value parameters
-  ParmChoiceMap parmChoice;   ///< Map of choices for parameters
-};
-
-/**
- * \class ProcessDefinition Process.hpp <Process.hpp>
- *
- * Definition of a process, including the process factory.
- * \ingroup ProcessUtils
- */
-template <typename P> struct ProcessDefinition : public BaseProcessDefinition {
+  
   /**
-   * \typedef process_t
+   * \def REGISTER_GLOBAL_PROCESS(ClassName)
    *
-   * Type of the generated process.
+   * Register \c ClassName has a global process. It must inherit GlobalProcess and have a constructor accepting a single
+   * GlobalProcess.
+   * \ingroup ProcessUtils
    */
-  typedef P process_t;
+  #define REGISTER_GLOBAL_PROCESS(ClassName)                                                                        \
+    mgx::process::GlobalRegistration ClassName ## registration(new ClassProcessFactory<GlobalProcess, ClassName>(), \
+                                                               typeid(ClassName).name(), PROCESS_VERSION)
+  
   /**
-   * \typedef Type of the process factory
+   * \struct BaseProcessDefinition Process.hpp <Process.hpp>
+   *
+   * Definition of a process, without the process factory.
+   * \ingroup ProcessUtils
    */
-  typedef FactoryPointer<P> processFactory;
+  struct MGX_EXPORT BaseProcessDefinition {
+    QString name;            ///< Name of the process
+    QString description;     ///< Description of the process
+    QStringList parmNames;   ///< List of named parameters of the process
+    QStringList parmDescs;   ///< List of descriptions of named parameters
+    QStringList parms;       ///< List of parameters/parameter defaults
+    QString folder;          ///< Folder in which to place the process
+    QIcon icon;              ///< Icon of the process
+    // uint nbNamedStrings;     ///< Number of named string parameters
+    // uint nbNamedValues;      ///< Number of named value parameters
+    ParmChoiceMap parmChoice;   ///< Map of choices for parameters
+  };
+  
   /**
-   * Process factory
+   * \class ProcessDefinition Process.hpp <Process.hpp>
+   *
+   * Definition of a process, including the process factory.
+   * \ingroup ProcessUtils
    */
-  processFactory factory;
-};
-
-#ifndef DOXYGEN
-typedef QMap<QString, ProcessDefinition<StackProcess> > stackProcessesMap_t;
-typedef QMap<QString, ProcessDefinition<MeshProcess> > meshProcessesMap_t;
-typedef QMap<QString, ProcessDefinition<GlobalProcess> > globalProcessesMap_t;
-
-MGX_EXPORT extern stackProcessesMap_t stackProcesses;
-MGX_EXPORT extern meshProcessesMap_t meshProcesses;
-MGX_EXPORT extern globalProcessesMap_t globalProcesses;
+  template <typename P> struct ProcessDefinition : public BaseProcessDefinition {
+    /**
+     * \typedef process_t
+     *
+     * Type of the generated process.
+     */
+    typedef P process_t;
+    /**
+     * \typedef Type of the process factory
+     */
+    typedef FactoryPointer<P> processFactory;
+    /**
+     * Process factory
+     */
+    processFactory factory;
+  };
+  
+  #ifndef DOXYGEN
+    typedef QMap<QString, ProcessDefinition<StackProcess> > stackProcessesMap_t;
+    typedef QMap<QString, ProcessDefinition<MeshProcess> > meshProcessesMap_t;
+    typedef QMap<QString, ProcessDefinition<GlobalProcess> > globalProcessesMap_t;
+    
+    MGX_EXPORT extern stackProcessesMap_t stackProcesses;
+    MGX_EXPORT extern meshProcessesMap_t meshProcesses;
+    MGX_EXPORT extern globalProcessesMap_t globalProcesses;
+  #endif
+  
+  ///\addtogroup ProcessUtils
+  ///@{
+  /**
+   * Retrieves the process definition from the type and name of the process
+   */
+  MGX_EXPORT BaseProcessDefinition* getBaseProcessDefinition(const QString& processType, const QString& processName);
+  
+  /// Get the parameters for a given process
+  MGX_EXPORT bool getLastParms(const Process& proc, QStringList& parms);
+  /// Get the default parameters for a given process (i.e. the ones defined by the process)
+  MGX_EXPORT bool getDefaultParms(const Process& proc, QStringList& parms);
+  /// Save the default parameters in memory
+  MGX_EXPORT bool saveDefaultParms(const Process& proc, const QStringList& parms);
+  /// Check if the parameters have enough defaults
+  MGX_EXPORT bool checkProcessParms(const Process& proc, const QStringList& parms, size_t* nbParms = 0);
+  /// Get the parameters for a given process
+  MGX_EXPORT bool getLastParms(const QString& processType, const QString& processName, QStringList& parms);
+  /// Get the default parameters for a given process (i.e. the ones defined by the process)
+  MGX_EXPORT bool getDefaultParms(const QString& processType, const QString& processName, QStringList& parms);
+  /// Save the default parameters in memory
+  MGX_EXPORT bool saveDefaultParms(const QString& processType, const QString& processName, const QStringList& parms);
+  /// Check if the parameters have enough defaults
+  MGX_EXPORT bool checkProcessParms(const QString& processType, const QString& processName, const QStringList& parms,
+                                    size_t* nbParms = 0);
+  /// Get the definition of a process
+  MGX_EXPORT BaseProcessDefinition* getBaseProcessDefinition(const QString& processThread, const QString& processName);
+  
+  /**
+   * Returns the list of names of the processes of a given type
+   */
+  MGX_EXPORT QStringList listProcesses(const QString& processType);
+  
+  /**
+   * Check if \c processType is a valid type (i.e. it exists)
+   */
+  MGX_EXPORT bool validProcessType(const QString& processType);
+  /**
+   * Check if the \c processName exist in the list of \c processType.
+   */
+  MGX_EXPORT bool validProcessName(const QString& processType, const QString& processName);
+  
+  /// Helper function converting a string into a boolean.
+  MGX_EXPORT bool stringToBool(const QString& string);
+  /// Returns true if \c string correspond to the work store, false otherwise
+  MGX_EXPORT bool stringToWorkStore(const QString& string);
+  /// Returns true if \c string correspond to the main store, false otherwise
+  MGX_EXPORT bool stringToMainStore(const QString& string);
+  
+  /// Helper function converting a boolean into a string
+  inline QString boolToString(bool b) {
+    return (b ? "Yes" : "No");
+  }
+  
+  ///@}
+}}
 #endif
-
-///\addtogroup ProcessUtils
-///@{
-/**
- * Retrieves the process definition from the type and name of the process
- */
-MGX_EXPORT BaseProcessDefinition* getBaseProcessDefinition(const QString& processType, const QString& processName);
-
-/// Get the parameters for a given process
-MGX_EXPORT bool getLastParms(const Process& proc, QStringList& parms);
-/// Get the default parameters for a given process (i.e. the ones defined by the process)
-MGX_EXPORT bool getDefaultParms(const Process& proc, QStringList& parms);
-/// Save the default parameters in memory
-MGX_EXPORT bool saveDefaultParms(const Process& proc, const QStringList& parms);
-/// Check if the parameters have enough defaults
-MGX_EXPORT bool checkProcessParms(const Process& proc, const QStringList& parms, size_t* nbParms = 0);
-/// Get the parameters for a given process
-MGX_EXPORT bool getLastParms(const QString& processType, const QString& processName, QStringList& parms);
-/// Get the default parameters for a given process (i.e. the ones defined by the process)
-MGX_EXPORT bool getDefaultParms(const QString& processType, const QString& processName, QStringList& parms);
-/// Save the default parameters in memory
-MGX_EXPORT bool saveDefaultParms(const QString& processType, const QString& processName, const QStringList& parms);
-/// Check if the parameters have enough defaults
-MGX_EXPORT bool checkProcessParms(const QString& processType, const QString& processName, const QStringList& parms,
-                                  size_t* nbParms = 0);
-/// Get the definition of a process
-MGX_EXPORT BaseProcessDefinition* getBaseProcessDefinition(const QString& processThread, const QString& processName);
-
-/**
- * Returns the list of names of the processes of a given type
- */
-MGX_EXPORT QStringList listProcesses(const QString& processType);
-
-/**
- * Check if \c processType is a valid type (i.e. it exists)
- */
-MGX_EXPORT bool validProcessType(const QString& processType);
-/**
- * Check if the \c processName exist in the list of \c processType.
- */
-MGX_EXPORT bool validProcessName(const QString& processType, const QString& processName);
-
-/// Helper function converting a string into a boolean.
-MGX_EXPORT bool stringToBool(const QString& string);
-/// Returns true if \c string correspond to the work store, false otherwise
-MGX_EXPORT bool stringToWorkStore(const QString& string);
-/// Returns true if \c string correspond to the main store, false otherwise
-MGX_EXPORT bool stringToMainStore(const QString& string);
-
-/// Helper function converting a boolean into a string
-inline QString boolToString(bool b) {
-  return (b ? "Yes" : "No");
-}
-
-///@}
-} // namespace process
-} // namespace mgx
-#endif
Index: MeshProcessStructure.cpp
===================================================================
--- MeshProcessStructure.cpp	(revision 1255)
+++ MeshProcessStructure.cpp	(revision 1256)
@@ -5,707 +5,706 @@
 
 #include <QTextStream>
 
-namespace mgx {
-namespace process {
+namespace mgx { namespace process {
 
-bool TransformMesh::operator()(Mesh* mesh, Point3f translation, Point3f rotation, float angle, float scale)
-{
-  Point4f dir = homogeneous(rotation);
-  Matrix4f M = Matrix4f::rotation(dir, angle);
-  M(0, 3) = translation.x();
-  M(1, 3) = translation.y();
-  M(2, 3) = translation.z();
-  M(3, 3) = 1.f / scale;
-  const std::vector<vertex>& vs = mesh->activeVertices();
-  if(scale < 0 and vs.size() != mesh->graph().size())
-    return setErrorMessage(
-      "Error, the scaling can be negative only if all the vertices are transformed at the same time.");
-  forall(const vertex& v, vs) {
-    v->pos = cartesian(M * homogeneous(v->pos));
+  bool TransformMesh::operator()(Mesh* mesh, Point3f translation, Point3f rotation, float angle, float scale)
+  {
+    Point4f dir = homogeneous(rotation);
+    Matrix4f M = Matrix4f::rotation(dir, angle);
+    M(0, 3) = translation.x();
+    M(1, 3) = translation.y();
+    M(2, 3) = translation.z();
+    M(3, 3) = 1.f / scale;
+    const std::vector<vertex>& vs = mesh->activeVertices();
+    if(scale < 0 and vs.size() != mesh->graph().size())
+      return setErrorMessage(
+        "Error, the scaling can be negative only if all the vertices are transformed at the same time.");
+    forall(const vertex& v, vs) {
+      v->pos = cartesian(M * homogeneous(v->pos));
+    }
+    if(scale < 0) {
+      mesh->graph().reverse();
+      mesh->updateTriangles();
+    }
+    mesh->setNormals();
+    mesh->updatePositions();
+    return true;
   }
-  if(scale < 0) {
+  REGISTER_MESH_PROCESS(TransformMesh);
+  
+  bool ReverseMesh::operator()(Mesh* mesh)
+  {
+    if(mesh->activeVertices().size() != mesh->graph().size())
+      return setErrorMessage("All vertices must be reversed at the same.");
+  
     mesh->graph().reverse();
-    mesh->updateTriangles();
+    mesh->setNormals();
+    mesh->updateAll();
+    return true;
   }
-  mesh->setNormals();
-  mesh->updatePositions();
-  return true;
-}
-REGISTER_MESH_PROCESS(TransformMesh);
-
-bool ReverseMesh::operator()(Mesh* mesh)
-{
-  if(mesh->activeVertices().size() != mesh->graph().size())
-    return setErrorMessage("All vertices must be reversed at the same.");
-
-  mesh->graph().reverse();
-  mesh->setNormals();
-  mesh->updateAll();
-  return true;
-}
-REGISTER_MESH_PROCESS(ReverseMesh);
-
-bool SmoothMesh::operator()(Mesh* mesh, uint passes)
-{
-  const std::vector<vertex>& vs = mesh->activeVertices();
-  vvgraph& S = mesh->graph();
-  Progress progress(QString("Smoothing mesh %1").arg(mesh->userId()), passes);
-  for(uint i = 0; i < passes; ++i) {
-    if(!progress.advance(i))
-      userCancel();
-    // We'll use the normal as a temp position to save space in the vertex struct
-    forall(const vertex& v, vs) {
-      float wt = 0;
-      v->nrml = Point3f(0, 0, 0);
-      forall(const vertex& n, S.neighbors(v)) {
-        if(!v->margin) {
-          vertex m = S.nextTo(v, n);
-          float a = triangleArea(v->pos, n->pos, m->pos);
-          wt += a;
-          v->nrml += Point3f(a * (n->pos + m->pos) / 2.0);
-        } else if(n->margin) {
-          float a = (n->pos - v->pos).norm();
-          v->nrml += Point3f(a * n->pos);
-          wt += a;
+  REGISTER_MESH_PROCESS(ReverseMesh);
+  
+  bool SmoothMesh::operator()(Mesh* mesh, uint passes)
+  {
+    const std::vector<vertex>& vs = mesh->activeVertices();
+    vvgraph& S = mesh->graph();
+    Progress progress(QString("Smoothing mesh %1").arg(mesh->userId()), passes);
+    for(uint i = 0; i < passes; ++i) {
+      if(!progress.advance(i))
+        userCancel();
+      // We'll use the normal as a temp position to save space in the vertex struct
+      forall(const vertex& v, vs) {
+        float wt = 0;
+        v->nrml = Point3f(0, 0, 0);
+        forall(const vertex& n, S.neighbors(v)) {
+          if(!v->margin) {
+            vertex m = S.nextTo(v, n);
+            float a = triangleArea(v->pos, n->pos, m->pos);
+            wt += a;
+            v->nrml += Point3f(a * (n->pos + m->pos) / 2.0);
+          } else if(n->margin) {
+            float a = (n->pos - v->pos).norm();
+            v->nrml += Point3f(a * n->pos);
+            wt += a;
+          }
         }
+        if(wt > 0)
+          v->nrml /= wt;
+        else
+          v->nrml = v->pos;
       }
-      if(wt > 0)
-        v->nrml /= wt;
-      else
-        v->nrml = v->pos;
+      forall(const vertex& v, vs)
+        v->pos = v->pos * .5 + v->nrml * .5;
     }
+  
+    mesh->setNormals();
+    mesh->clearImgTex();
+    mesh->updateAll();
+    return true;
+  }
+  REGISTER_MESH_PROCESS(SmoothMesh);
+  
+  bool ShrinkMesh::operator()(Mesh* mesh, float distance)
+  {
+    const std::vector<vertex>& vs = mesh->activeVertices();
+  
     forall(const vertex& v, vs)
-      v->pos = v->pos * .5 + v->nrml * .5;
+      v->pos -= distance * v->nrml;
+  
+    mesh->setNormals();
+    mesh->clearImgTex();
+    mesh->updateAll();
+    return true;
   }
-
-  mesh->setNormals();
-  mesh->clearImgTex();
-  mesh->updateAll();
-  return true;
-}
-REGISTER_MESH_PROCESS(SmoothMesh);
-
-bool ShrinkMesh::operator()(Mesh* mesh, float distance)
-{
-  const std::vector<vertex>& vs = mesh->activeVertices();
-
-  forall(const vertex& v, vs)
-    v->pos -= distance * v->nrml;
-
-  mesh->setNormals();
-  mesh->clearImgTex();
-  mesh->updateAll();
-  return true;
-}
-REGISTER_MESH_PROCESS(ShrinkMesh);
-
-bool SubdivideMesh::operator()(Mesh* mesh)
-{
-  vvgraph& S = mesh->graph();
-  const std::vector<vertex>& vs = mesh->activeVertices();
-
-  bool selection = vs.size() != S.size();
-
-  Progress progress(QString("Subdividing mesh %1").arg(mesh->userId()), 0);
-  vvgraph SS = S.subgraph(vs);
-  vvgraph T, T1;
-  T = S;
-  util::Insert<vvgraph> insert;
-  std::vector<vertex> new_vertices;
-
-  int cnt = 0;
-
-  // Add vertex in middle of all existing edges
-  forall(const vertex& n, SS) {
-    if((++cnt % 1000 == 0) and progress.canceled()) {
-      S = T;
-      userCancel();
+  REGISTER_MESH_PROCESS(ShrinkMesh);
+  
+  bool SubdivideMesh::operator()(Mesh* mesh)
+  {
+    vvgraph& S = mesh->graph();
+    const std::vector<vertex>& vs = mesh->activeVertices();
+  
+    bool selection = vs.size() != S.size();
+  
+    Progress progress(QString("Subdividing mesh %1").arg(mesh->userId()), 0);
+    vvgraph SS = S.subgraph(vs);
+    vvgraph T, T1;
+    T = S;
+    util::Insert<vvgraph> insert;
+    std::vector<vertex> new_vertices;
+  
+    int cnt = 0;
+  
+    // Add vertex in middle of all existing edges
+    forall(const vertex& n, SS) {
+      if((++cnt % 1000 == 0) and progress.canceled()) {
+        S = T;
+        userCancel();
+      }
+      forall(const vertex& m, T.neighbors(n)) {
+        if(SS.contains(m) and m < n)
+          continue;
+        vertex v = insert(n, m, S);
+        new_vertices.push_back(v);
+        v->selected = selection;
+        v->margin = false;
+        v->signal = (m->signal + n->signal) / 2.0;
+        v->pos = (m->pos + n->pos) / 2.0;
+        v->txpos = (m->txpos + n->txpos) / 2.0;
+        if(m->label == n->label)
+          v->label = m->label;
+      }
     }
-    forall(const vertex& m, T.neighbors(n)) {
-      if(SS.contains(m) and m < n)
-        continue;
-      vertex v = insert(n, m, S);
-      new_vertices.push_back(v);
-      v->selected = selection;
-      v->margin = false;
-      v->signal = (m->signal + n->signal) / 2.0;
-      v->pos = (m->pos + n->pos) / 2.0;
-      v->txpos = (m->txpos + n->txpos) / 2.0;
-      if(m->label == n->label)
-        v->label = m->label;
-    }
-  }
-  progress.setMaximum(new_vertices.size() + 1);
-  T1 = S;
-  // Now add new edges
-  int i = 0;
-  forall(const vertex& v, new_vertices) {
-    ++i;
-    if((i % 1000 == 0)and !progress.advance(i)) {
-      S = T;
-      userCancel();
-    }
-    forall(const vertex& n, T1.neighbors(v)) {
-      vertex m = T1.nextTo(v, n);
-      vertex nv = T1.nextTo(n, v);
-      vertex mv = T1.prevTo(m, v);
-      vertex nm = T1.nextTo(nv, n);
-      vertex mn = T1.prevTo(mv, m);
-      if(nm != mn) {
-        if(mn == nv)         // it's a border!
-        {
-          if(norm(mv->pos - v->pos) < norm(m->pos - nv->pos)) {
-            S.spliceAfter(v, m, mv);
-            S.spliceBefore(mv, m, v);
-          } else {
-            S.spliceBefore(nv, mv, m);
-            S.spliceAfter(m, mv, nv);
+    progress.setMaximum(new_vertices.size() + 1);
+    T1 = S;
+    // Now add new edges
+    int i = 0;
+    forall(const vertex& v, new_vertices) {
+      ++i;
+      if((i % 1000 == 0)and !progress.advance(i)) {
+        S = T;
+        userCancel();
+      }
+      forall(const vertex& n, T1.neighbors(v)) {
+        vertex m = T1.nextTo(v, n);
+        vertex nv = T1.nextTo(n, v);
+        vertex mv = T1.prevTo(m, v);
+        vertex nm = T1.nextTo(nv, n);
+        vertex mn = T1.prevTo(mv, m);
+        if(nm != mn) {
+          if(mn == nv)         // it's a border!
+          {
+            if(norm(mv->pos - v->pos) < norm(m->pos - nv->pos)) {
+              S.spliceAfter(v, m, mv);
+              S.spliceBefore(mv, m, v);
+            } else {
+              S.spliceBefore(nv, mv, m);
+              S.spliceAfter(m, mv, nv);
+            }
           }
+          continue;
         }
-        continue;
+        S.spliceBefore(nv, nm, mv);
+        S.spliceAfter(mv, mn, nv);
       }
-      S.spliceBefore(nv, nm, mv);
-      S.spliceAfter(mv, mn, nv);
     }
+  
+    mesh->setCells(false);
+    SETSTATUS("Mesh " << mesh->userId() << " - Subdivide triangles, total vertices:" << S.size());
+    mesh->updateAll();
+    return true;
   }
-
-  mesh->setCells(false);
-  SETSTATUS("Mesh " << mesh->userId() << " - Subdivide triangles, total vertices:" << S.size());
-  mesh->updateAll();
-  return true;
-}
-
-REGISTER_MESH_PROCESS(SubdivideMesh);
-
-bool LoopSubdivisionMesh::operator()(Mesh* mesh)
-{
-  vvgraph& S = mesh->graph();
-  const std::vector<vertex>& vs = mesh->activeVertices();
-
-  bool selection = vs.size() != S.size();
-  vvgraph OldS;
-
-  if(selection)
-    OldS = S.subgraph(S);
-  else
-    OldS = S;
-
-  size_t ss = OldS.size();
-  size_t disp = ss / 50;
-
-  Progress progress(QString("Subdividing mesh %1").arg(mesh->userId()), 2 * ss);
-
-  util::Insert<vvgraph> insert;
-  std::vector<vertex> new_vertices;
-  std::vector<Point3f> old_pos;
-  std::map<vertex, size_t> vertex_index;
-  old_pos.reserve(OldS.size());
-
-  for(size_t i = 0; i < OldS.size(); ++i) {
-    vertex v = OldS[i];
-    vertex_index[v] = i;
-    old_pos[i] = v->pos;
-  }
-
-  // Add vertex in middle of all existing edges
-  for(size_t i = 0; i < OldS.size(); ++i) {
-    if((i % disp == 0)and not progress.advance(i))
-      userCancel();
-    bool surface_v = false;     // The vertex is on the border of the surface
-    const vertex& v = OldS[i];
-    size_t n = OldS.valence(v);
-    Point3f q;
-
-    float w = 0.375 + 0.25 * std::cos(2.0 * M_PI / float(n));
-    w *= w;
-    w = 0.625 - w;
-
-    forall(const vertex& u, OldS.neighbors(v)) {
-      size_t j = vertex_index[u];
-      bool boundary = true;
-      if((OldS.nextTo(u, v) == OldS.prevTo(v, u))and (OldS.prevTo(u, v) == OldS.nextTo(v, u)))
-        boundary = false;
-      else {
-        if(surface_v)
-          q = 0.0;
-        surface_v = true;
+  
+  REGISTER_MESH_PROCESS(SubdivideMesh);
+  
+  bool LoopSubdivisionMesh::operator()(Mesh* mesh)
+  {
+    vvgraph& S = mesh->graph();
+    const std::vector<vertex>& vs = mesh->activeVertices();
+  
+    bool selection = vs.size() != S.size();
+    vvgraph OldS;
+  
+    if(selection)
+      OldS = S.subgraph(S);
+    else
+      OldS = S;
+  
+    size_t ss = OldS.size();
+    size_t disp = ss / 50;
+  
+    Progress progress(QString("Subdividing mesh %1").arg(mesh->userId()), 2 * ss);
+  
+    util::Insert<vvgraph> insert;
+    std::vector<vertex> new_vertices;
+    std::vector<Point3f> old_pos;
+    std::map<vertex, size_t> vertex_index;
+    old_pos.reserve(OldS.size());
+  
+    for(size_t i = 0; i < OldS.size(); ++i) {
+      vertex v = OldS[i];
+      vertex_index[v] = i;
+      old_pos[i] = v->pos;
+    }
+  
+    // Add vertex in middle of all existing edges
+    for(size_t i = 0; i < OldS.size(); ++i) {
+      if((i % disp == 0)and not progress.advance(i))
+        userCancel();
+      bool surface_v = false;     // The vertex is on the border of the surface
+      const vertex& v = OldS[i];
+      size_t n = OldS.valence(v);
+      Point3f q;
+  
+      float w = 0.375 + 0.25 * std::cos(2.0 * M_PI / float(n));
+      w *= w;
+      w = 0.625 - w;
+  
+      forall(const vertex& u, OldS.neighbors(v)) {
+        size_t j = vertex_index[u];
+        bool boundary = true;
+        if((OldS.nextTo(u, v) == OldS.prevTo(v, u))and (OldS.prevTo(u, v) == OldS.nextTo(v, u)))
+          boundary = false;
+        else {
+          if(surface_v)
+            q = 0.0;
+          surface_v = true;
+        }
+        if((surface_v and boundary) or not surface_v)
+          q += old_pos[j];
+  
+        // Only sub-divide every undirected edge once
+        if(u < v)
+          continue;
+  
+        vertex x = insert(u, v, S);
+        new_vertices.push_back(x);
+  
+        // Set properties of the new vertex
+        x->selected = selection;
+        x->margin = boundary;
+        if(u->label == v->label)
+          x->label = u->label;
+        if(boundary) {
+          x->pos = (old_pos[i] + old_pos[j]) / 2.0;
+          x->txpos = (u->txpos + v->txpos) / 2.0;
+          x->signal = (u->signal + v->signal) / 2.0;
+        } else {
+          const vertex& nv = OldS.nextTo(v, u);
+          const vertex& pv = OldS.prevTo(v, u);
+          size_t kn = vertex_index[nv];
+          size_t kp = vertex_index[pv];
+          x->pos = (old_pos[i] * 3.0 + old_pos[j] * 3.0 + old_pos[kn] + old_pos[kp]) / 8.0;
+          x->txpos = (u->txpos * 3.0 + v->txpos * 3.0 + pv->txpos + nv->txpos) / 8.0;
+          x->signal = (u->signal * 3.0 + v->signal * 3.0 + pv->signal + nv->signal) / 8.0;
+        }
       }
-      if((surface_v and boundary) or not surface_v)
-        q += old_pos[j];
-
-      // Only sub-divide every undirected edge once
-      if(u < v)
-        continue;
-
-      vertex x = insert(u, v, S);
-      new_vertices.push_back(x);
-
-      // Set properties of the new vertex
-      x->selected = selection;
-      x->margin = boundary;
-      if(u->label == v->label)
-        x->label = u->label;
-      if(boundary) {
-        x->pos = (old_pos[i] + old_pos[j]) / 2.0;
-        x->txpos = (u->txpos + v->txpos) / 2.0;
-        x->signal = (u->signal + v->signal) / 2.0;
+      if(surface_v) {
+        v->pos = 0.75 * v->pos + 0.125 * q;
       } else {
-        const vertex& nv = OldS.nextTo(v, u);
-        const vertex& pv = OldS.prevTo(v, u);
-        size_t kn = vertex_index[nv];
-        size_t kp = vertex_index[pv];
-        x->pos = (old_pos[i] * 3.0 + old_pos[j] * 3.0 + old_pos[kn] + old_pos[kp]) / 8.0;
-        x->txpos = (u->txpos * 3.0 + v->txpos * 3.0 + pv->txpos + nv->txpos) / 8.0;
-        x->signal = (u->signal * 3.0 + v->signal * 3.0 + pv->signal + nv->signal) / 8.0;
+        v->pos = (1 - w) * v->pos + (w / n) * q;
       }
     }
-    if(surface_v) {
-      v->pos = 0.75 * v->pos + 0.125 * q;
-    } else {
-      v->pos = (1 - w) * v->pos + (w / n) * q;
+  
+    progress.setMaximum(ss + new_vertices.size());
+  
+    // Connect the inside triangles
+    size_t i = 0;
+    disp = new_vertices.size() / 50;
+    forall(const vertex& v, new_vertices) {
+      if((i % disp == 0)and not progress.advance(ss + i))
+        userCancel();
+      ++i;
+      const vertex& a = S.anyIn(v);
+      const vertex& b = S.nextTo(v, a);
+      if(OldS.prevTo(a, b) == OldS.nextTo(b, a)) {
+        S.spliceAfter(v, a, S.prevTo(a, v));
+        S.spliceBefore(v, b, S.nextTo(b, v));
+      }
+      if(OldS.nextTo(a, b) == OldS.prevTo(b, a)) {
+        S.spliceAfter(v, b, S.prevTo(b, v));
+        S.spliceBefore(v, a, S.nextTo(a, v));
+      }
     }
+  
+    mesh->setCells(false);
+    SETSTATUS("Mesh " << mesh->userId() << " - Subdivide triangles, total vertices:" << S.size());
+    mesh->updateAll();
+    return true;
   }
-
-  progress.setMaximum(ss + new_vertices.size());
-
-  // Connect the inside triangles
-  size_t i = 0;
-  disp = new_vertices.size() / 50;
-  forall(const vertex& v, new_vertices) {
-    if((i % disp == 0)and not progress.advance(ss + i))
-      userCancel();
-    ++i;
-    const vertex& a = S.anyIn(v);
-    const vertex& b = S.nextTo(v, a);
-    if(OldS.prevTo(a, b) == OldS.nextTo(b, a)) {
-      S.spliceAfter(v, a, S.prevTo(a, v));
-      S.spliceBefore(v, b, S.nextTo(b, v));
+  
+  REGISTER_MESH_PROCESS(LoopSubdivisionMesh);
+  
+  bool subdivideBisect(vvgraph& S, const vertex& v1, const vertex& v2, const vertex& v3, bool selected,
+                       std::vector<vertex>* vs)
+  {
+    // v1, v2, v3 must be in order
+    vertex a(0), b(0), c(0);
+  
+    // Find longest edge and divide
+    a = v1;
+    b = v2;
+    c = v3;
+    if((v2->pos - v3->pos).norm() > (a->pos - b->pos).norm()) {
+      a = v2;
+      b = v3;
+      c = v1;
+    } else if((v3->pos - v1->pos).norm() > (a->pos - b->pos).norm()) {
+      a = v3;
+      b = v1;
+      c = v2;
     }
-    if(OldS.nextTo(a, b) == OldS.prevTo(b, a)) {
-      S.spliceAfter(v, b, S.prevTo(b, v));
-      S.spliceBefore(v, a, S.nextTo(a, v));
+  
+    // Insert vertex in long edge if not already there
+    if(S.edge(a, b)) {
+      vertex d;
+      d->type = 'j';
+      d->selected = selected;
+      if(vs)
+        vs->push_back(d);
+      S.insert(d);
+      S.insertEdge(d, a);
+      S.insertEdge(d, b);
+      d->pos = (a->pos + b->pos) / 2.0;
+      d->signal = (a->signal + b->signal) / 2.0;
+      // d->txpos = clipTex((a->txpos + b->txpos)/2.0);
+      d->txpos = (a->txpos + b->txpos) / 2.0;
+      if(a->label == b->label)
+        d->label = a->label;
+      S.replace(a, b, d);
+      S.replace(b, a, d);
+    } else {
+      // Already there, must be the last triangle
+      const vertex& d = S.prevTo(a, c);
+      S.spliceAfter(c, a, d);
+      S.spliceBefore(d, a, c);
+      return true;
     }
+  
+    // Create dividing edge
+    vertex d(0);
+    if(S.edge(a, c)) {
+      d = S.prevTo(a, c);
+      S.spliceAfter(c, a, d);
+      S.spliceBefore(d, a, c);
+      const vertex& v = S.nextTo(c, d);
+      // If edge c,b split by v, connect d to v
+      if(v != b) {
+        S.spliceBefore(d, c, v);
+        S.spliceAfter(v, c, d);
+      }
+    } else if(S.edge(b, c)) {
+      d = S.nextTo(b, c);
+      S.spliceBefore(c, b, d);
+      S.spliceAfter(d, b, c);
+      const vertex& v = S.prevTo(c, d);
+      // If edge c,a split by v, connect d to v
+      if(v != a) {
+        S.spliceAfter(d, c, v);
+        S.spliceBefore(v, c, d);
+      }
+    } else {
+      SETSTATUS("subdivideBisect::Error:Both incoming short edges divided");
+      return false;
+    }
+  
+    // Find neighbor
+    vertex n(0);
+    if(S.prevTo(a, d) == S.nextTo(b, d)) {
+      n = S.prevTo(a, d);
+      // Neighbor already divided
+      if(S.edge(d, n))
+        return true;
+      return subdivideBisect(S, b, a, n, selected, vs);
+    }
+    return true;
   }
-
-  mesh->setCells(false);
-  SETSTATUS("Mesh " << mesh->userId() << " - Subdivide triangles, total vertices:" << S.size());
-  mesh->updateAll();
-  return true;
-}
-
-REGISTER_MESH_PROCESS(LoopSubdivisionMesh);
-
-bool subdivideBisect(vvgraph& S, const vertex& v1, const vertex& v2, const vertex& v3, bool selected,
-                     std::vector<vertex>* vs)
-{
-  // v1, v2, v3 must be in order
-  vertex a(0), b(0), c(0);
-
-  // Find longest edge and divide
-  a = v1;
-  b = v2;
-  c = v3;
-  if((v2->pos - v3->pos).norm() > (a->pos - b->pos).norm()) {
-    a = v2;
-    b = v3;
-    c = v1;
-  } else if((v3->pos - v1->pos).norm() > (a->pos - b->pos).norm()) {
-    a = v3;
-    b = v1;
-    c = v2;
-  }
-
-  // Insert vertex in long edge if not already there
-  if(S.edge(a, b)) {
-    vertex d;
-    d->type = 'j';
-    d->selected = selected;
-    if(vs)
-      vs->push_back(d);
-    S.insert(d);
-    S.insertEdge(d, a);
-    S.insertEdge(d, b);
-    d->pos = (a->pos + b->pos) / 2.0;
-    d->signal = (a->signal + b->signal) / 2.0;
-    // d->txpos = clipTex((a->txpos + b->txpos)/2.0);
-    d->txpos = (a->txpos + b->txpos) / 2.0;
-    if(a->label == b->label)
-      d->label = a->label;
-    S.replace(a, b, d);
-    S.replace(b, a, d);
-  } else {
-    // Already there, must be the last triangle
-    const vertex& d = S.prevTo(a, c);
-    S.spliceAfter(c, a, d);
-    S.spliceBefore(d, a, c);
+  
+  bool AdaptiveSubdivideBorderMesh::operator()(Mesh* mesh, float cellMaxArea, float borderDist)
+  {
+    vvgraph& S = mesh->graph();
+    const std::vector<vertex>& vs = mesh->activeVertices();
+    bool selected = vs.size() != S.size();
+  
+    // Find triangles on borders
+    mesh->markBorder(borderDist);
+  
+    // Copy to temp graph
+    vvgraph T = S;
+    forall(vertex v, vs)
+      forall(vertex n, T.neighbors(v)) {
+        vertex m = T.nextTo(v, n);
+        if(!mesh->uniqueTri(v, n, m))
+          continue;
+  
+        // Subdivide triangles on border and clear label
+        if(v->minb == 0 or m->minb == 0 or n->minb == 0)
+          continue;
+        v->label = n->label = m->label = 0;
+        float area = triangleArea(v->pos, n->pos, m->pos);
+        if(area < cellMaxArea)
+          continue;
+  
+        if(!subdivideBisect(S, v, n, m, selected)) {
+          setErrorMessage("Failed bisecting triangle");
+          return false;
+        }
+      }
+    SETSTATUS(S.size() << " total vertices");
+    mesh->updateAll();
+    mesh->setCells(false);
     return true;
   }
-
-  // Create dividing edge
-  vertex d(0);
-  if(S.edge(a, c)) {
-    d = S.prevTo(a, c);
-    S.spliceAfter(c, a, d);
-    S.spliceBefore(d, a, c);
-    const vertex& v = S.nextTo(c, d);
-    // If edge c,b split by v, connect d to v
-    if(v != b) {
-      S.spliceBefore(d, c, v);
-      S.spliceAfter(v, c, d);
+  
+  REGISTER_MESH_PROCESS(AdaptiveSubdivideBorderMesh);
+  
+  bool AdaptiveSubdivideSignalMesh::operator()(Mesh* mesh, float cellMaxAreaLow, float cellMaxAreaHigh)
+  {
+    vvgraph& S = mesh->graph();
+    const std::vector<vertex>& vs = mesh->activeVertices();
+  
+    bool selected = vs.size() != S.size();
+  
+    // Find max/min colors
+    float maxc = 0, minc = HUGE_VAL;
+    forall(const vertex& v, vs) {
+      if(v->signal > maxc)
+        maxc = v->signal;
+      if(v->signal < minc)
+        minc = v->signal;
     }
-  } else if(S.edge(b, c)) {
-    d = S.nextTo(b, c);
-    S.spliceBefore(c, b, d);
-    S.spliceAfter(d, b, c);
-    const vertex& v = S.prevTo(c, d);
-    // If edge c,a split by v, connect d to v
-    if(v != a) {
-      S.spliceAfter(d, c, v);
-      S.spliceBefore(v, c, d);
+    float rangec = maxc - minc;
+    // Return if no real signal difference
+    if(fabs(rangec) < 1e-5) {
+      setErrorMessage("subdivideTriangles::Error:No signal difference");
+      return false;
     }
-  } else {
-    SETSTATUS("subdivideBisect::Error:Both incoming short edges divided");
-    return false;
+    // Copy to temp graph
+    vvgraph T = S;
+    forall(vertex v, vs)
+      forall(vertex n, T.neighbors(v)) {
+        vertex m = T.nextTo(v, n);
+        if(!mesh->uniqueTri(v, n, m))
+          continue;
+  
+        // Find max signal on triangle
+        float maxcol = v->signal;
+        if(n->signal > maxcol)
+          maxcol = n->signal;
+        if(m->signal > maxcol)
+          maxcol = m->signal;
+  
+        float val = ((maxcol - minc) / rangec);
+        float area = triangleArea(v->pos, n->pos, m->pos);
+        if(area < interpolate(cellMaxAreaLow, cellMaxAreaHigh, val))
+          continue;
+  
+        if(!subdivideBisect(S, v, n, m, selected)) {
+          setErrorMessage("Failed bisecting triangle");
+          return false;
+        }
+      }
+    SETSTATUS(S.size() << " total vertices");
+    mesh->updateAll();
+    mesh->setCells(false);
+    return true;
   }
-
-  // Find neighbor
-  vertex n(0);
-  if(S.prevTo(a, d) == S.nextTo(b, d)) {
-    n = S.prevTo(a, d);
-    // Neighbor already divided
-    if(S.edge(d, n))
-      return true;
-    return subdivideBisect(S, b, a, n, selected, vs);
+  
+  REGISTER_MESH_PROCESS(AdaptiveSubdivideSignalMesh);
+  
+  bool SubdivideBisectMesh::operator()(Mesh* mesh, float cellMaxArea)
+  {
+    vvgraph& S = mesh->graph();
+    const std::vector<vertex>& vs = mesh->activeVertices();
+  
+    bool selected = vs.size() != S.size();
+  
+    // Copy to temp graph
+    vvgraph T = S;
+    forall(vertex v, vs)
+      forall(vertex n, T.neighbors(v)) {
+        vertex m = T.nextTo(v, n);
+        if(!mesh->uniqueTri(v, n, m))
+          continue;
+  
+        float area = triangleArea(v->pos, n->pos, m->pos);
+        if(area < cellMaxArea)
+          continue;
+  
+        if(!subdivideBisect(S, v, n, m, selected)) {
+          setErrorMessage("Failed bisecting triangle");
+          return false;
+        }
+      }
+    SETSTATUS(S.size() << " total vertices");
+    mesh->updateAll();
+    mesh->setCells(false);
+    return true;
   }
-  return true;
-}
-
-bool AdaptiveSubdivideBorderMesh::operator()(Mesh* mesh, float cellMaxArea, float borderDist)
-{
-  vvgraph& S = mesh->graph();
-  const std::vector<vertex>& vs = mesh->activeVertices();
-  bool selected = vs.size() != S.size();
-
-  // Find triangles on borders
-  mesh->markBorder(borderDist);
-
-  // Copy to temp graph
-  vvgraph T = S;
-  forall(vertex v, vs)
-    forall(vertex n, T.neighbors(v)) {
-      vertex m = T.nextTo(v, n);
-      if(!mesh->uniqueTri(v, n, m))
-        continue;
-
-      // Subdivide triangles on border and clear label
-      if(v->minb == 0 or m->minb == 0 or n->minb == 0)
-        continue;
-      v->label = n->label = m->label = 0;
-      float area = triangleArea(v->pos, n->pos, m->pos);
-      if(area < cellMaxArea)
-        continue;
-
-      if(!subdivideBisect(S, v, n, m, selected)) {
-        setErrorMessage("Failed bisecting triangle");
-        return false;
-      }
+  REGISTER_MESH_PROCESS(SubdivideBisectMesh);
+  
+  bool ScaleMesh::operator()(Mesh* mesh, float scaleX, float scaleY, float scaleZ)
+  {
+    vvgraph& S = mesh->graph();
+    const std::vector<vertex>& vs = mesh->activeVertices();
+  
+    if(scaleX * scaleY * scaleZ < 0) {
+      if(vs.size() != S.size())
+        return setErrorMessage(
+          "Error, symmetries have to be applied globally. Make sure the product of the scalings are positive.");
+      S.reverse();
     }
-  SETSTATUS(S.size() << " total vertices");
-  mesh->updateAll();
-  mesh->setCells(false);
-  return true;
-}
-
-REGISTER_MESH_PROCESS(AdaptiveSubdivideBorderMesh);
-
-bool AdaptiveSubdivideSignalMesh::operator()(Mesh* mesh, float cellMaxAreaLow, float cellMaxAreaHigh)
-{
-  vvgraph& S = mesh->graph();
-  const std::vector<vertex>& vs = mesh->activeVertices();
-
-  bool selected = vs.size() != S.size();
-
-  // Find max/min colors
-  float maxc = 0, minc = HUGE_VAL;
-  forall(const vertex& v, vs) {
-    if(v->signal > maxc)
-      maxc = v->signal;
-    if(v->signal < minc)
-      minc = v->signal;
+  
+    // Copy to temp graph
+    forall(vertex v, vs) {
+      if(scaleX != 1.0)
+        v->pos.x() *= scaleX;
+      if(scaleY != 1.0)
+        v->pos.y() *= scaleY;
+      if(scaleZ != 1.0)
+        v->pos.z() *= scaleZ;
+    }
+    mesh->updateAll();
+    return true;
   }
-  float rangec = maxc - minc;
-  // Return if no real signal difference
-  if(fabs(rangec) < 1e-5) {
-    setErrorMessage("subdivideTriangles::Error:No signal difference");
-    return false;
-  }
-  // Copy to temp graph
-  vvgraph T = S;
-  forall(vertex v, vs)
-    forall(vertex n, T.neighbors(v)) {
-      vertex m = T.nextTo(v, n);
-      if(!mesh->uniqueTri(v, n, m))
+  REGISTER_MESH_PROCESS(ScaleMesh);
+  
+  void markMargin(vvgraph& M, vvgraph& S, bool remborders)
+  {
+    if(M.empty() or S.empty())
+      return;
+  
+    // Mark margin and borders
+    forall(const vertex& v, M) {
+      v->margin = false;
+      // All vertices with valence <= 2 are border and margin
+      if(S.valence(v) <= 2) {
+        v->margin = true;
+        v->label = -1;
         continue;
-
-      // Find max signal on triangle
-      float maxcol = v->signal;
-      if(n->signal > maxcol)
-        maxcol = n->signal;
-      if(m->signal > maxcol)
-        maxcol = m->signal;
-
-      float val = ((maxcol - minc) / rangec);
-      float area = triangleArea(v->pos, n->pos, m->pos);
-      if(area < interpolate(cellMaxAreaLow, cellMaxAreaHigh, val))
-        continue;
-
-      if(!subdivideBisect(S, v, n, m, selected)) {
-        setErrorMessage("Failed bisecting triangle");
-        return false;
       }
-    }
-  SETSTATUS(S.size() << " total vertices");
-  mesh->updateAll();
-  mesh->setCells(false);
-  return true;
-}
-
-REGISTER_MESH_PROCESS(AdaptiveSubdivideSignalMesh);
-
-bool SubdivideBisectMesh::operator()(Mesh* mesh, float cellMaxArea)
-{
-  vvgraph& S = mesh->graph();
-  const std::vector<vertex>& vs = mesh->activeVertices();
-
-  bool selected = vs.size() != S.size();
-
-  // Copy to temp graph
-  vvgraph T = S;
-  forall(vertex v, vs)
-    forall(vertex n, T.neighbors(v)) {
-      vertex m = T.nextTo(v, n);
-      if(!mesh->uniqueTri(v, n, m))
+  
+      int label = 0, labcount = 0, zcount = 0;
+      forall(const vertex& n, S.neighbors(v)) {
+        // If there is no edge between a pair of vertices next to each other
+        // in a neighborhood, they muct be on the margin
+        vertex m = S.nextTo(v, n);
+        if(!S.edge(n, m)) {
+          v->margin = true;
+          v->label = -1;
+          break;
+        }
+        if(n->label == 0)
+          zcount++;
+        else if(n->label > 0 and n->label != label) {
+          labcount++;
+          label = n->label;
+        }
+      }
+      // Margin vertices always have border label
+      if(v->margin)
         continue;
-
-      float area = triangleArea(v->pos, n->pos, m->pos);
-      if(area < cellMaxArea)
-        continue;
-
-      if(!subdivideBisect(S, v, n, m, selected)) {
-        setErrorMessage("Failed bisecting triangle");
-        return false;
+      // Adjacent to more than one label means a cell boundary
+      if(labcount > 1)
+        v->label = -1;
+      // Clear hanging border lines,
+      if(v->label == -1 and remborders) {
+        // On zero labeled area, only clear if remborders set (so we can draw)
+        if(labcount == 0)
+          v->label = 0;
+        else if(labcount == 1 and zcount == 0)
+          v->label = label;
       }
     }
-  SETSTATUS(S.size() << " total vertices");
-  mesh->updateAll();
-  mesh->setCells(false);
-  return true;
-}
-REGISTER_MESH_PROCESS(SubdivideBisectMesh);
-
-bool ScaleMesh::operator()(Mesh* mesh, float scaleX, float scaleY, float scaleZ)
-{
-  vvgraph& S = mesh->graph();
-  const std::vector<vertex>& vs = mesh->activeVertices();
-
-  if(scaleX * scaleY * scaleZ < 0) {
-    if(vs.size() != S.size())
-      return setErrorMessage(
-        "Error, symmetries have to be applied globally. Make sure the product of the scalings are positive.");
-    S.reverse();
   }
-
-  // Copy to temp graph
-  forall(vertex v, vs) {
-    if(scaleX != 1.0)
-      v->pos.x() *= scaleX;
-    if(scaleY != 1.0)
-      v->pos.y() *= scaleY;
-    if(scaleZ != 1.0)
-      v->pos.z() *= scaleZ;
+  
+  bool MeshDeleteValence::operator()(Mesh* mesh, int startValence, int endValence)
+  {
+    if(startValence < 0 or endValence < 0)
+      return setErrorMessage("Start and end valence must be >= 0.");
+    vvgraph& S = mesh->graph();
+    std::vector<vertex> D;
+    forall(const vertex& v, S)
+      if(S.valence(v) >= (size_t)startValence and S.valence(v) <= (size_t)endValence)
+        D.push_back(v);
+    forall(const vertex& v, D)
+      S.erase(v);
+  
+    SETSTATUS(D.size() << " vertex(es) deleted, total vertices:" << S.size());
+    mesh->updateAll();
+    mesh->setCells(false);
+    return true;
   }
-  mesh->updateAll();
-  return true;
-}
-REGISTER_MESH_PROCESS(ScaleMesh);
-
-void markMargin(vvgraph& M, vvgraph& S, bool remborders)
-{
-  if(M.empty() or S.empty())
-    return;
-
-  // Mark margin and borders
-  forall(const vertex& v, M) {
-    v->margin = false;
-    // All vertices with valence <= 2 are border and margin
-    if(S.valence(v) <= 2) {
-      v->margin = true;
-      v->label = -1;
-      continue;
-    }
-
-    int label = 0, labcount = 0, zcount = 0;
-    forall(const vertex& n, S.neighbors(v)) {
-      // If there is no edge between a pair of vertices next to each other
-      // in a neighborhood, they muct be on the margin
-      vertex m = S.nextTo(v, n);
-      if(!S.edge(n, m)) {
-        v->margin = true;
-        v->label = -1;
-        break;
+  REGISTER_MESH_PROCESS(MeshDeleteValence);
+  
+  bool spliceNhbs(vvgraph& S, vertex& a, vertex& b)
+  {
+    vertex n = S.nextTo(b, a);
+    vertex m = S.prevTo(b, a);
+    vertex pv = n;
+  
+    while(n != m) {
+      if(!S.edge(a, n)) {
+        S.spliceAfter(a, pv, n);
+        S.spliceAfter(n, b, a);
       }
-      if(n->label == 0)
-        zcount++;
-      else if(n->label > 0 and n->label != label) {
-        labcount++;
-        label = n->label;
-      }
+      pv = n;
+      n = S.nextTo(b, n);
     }
-    // Margin vertices always have border label
-    if(v->margin)
-      continue;
-    // Adjacent to more than one label means a cell boundary
-    if(labcount > 1)
-      v->label = -1;
-    // Clear hanging border lines,
-    if(v->label == -1 and remborders) {
-      // On zero labeled area, only clear if remborders set (so we can draw)
-      if(labcount == 0)
-        v->label = 0;
-      else if(labcount == 1 and zcount == 0)
-        v->label = label;
-    }
+    return true;
   }
-}
-
-bool MeshDeleteValence::operator()(Mesh* mesh, int startValence, int endValence)
-{
-  if(startValence < 0 or endValence < 0)
-    return setErrorMessage("Start and end valence must be >= 0.");
-  vvgraph& S = mesh->graph();
-  std::vector<vertex> D;
-  forall(const vertex& v, S)
-    if(S.valence(v) >= (size_t)startValence and S.valence(v) <= (size_t)endValence)
-      D.push_back(v);
-  forall(const vertex& v, D)
-    S.erase(v);
-
-  SETSTATUS(D.size() << " vertex(es) deleted, total vertices:" << S.size());
-  mesh->updateAll();
-  mesh->setCells(false);
-  return true;
-}
-REGISTER_MESH_PROCESS(MeshDeleteValence);
-
-bool spliceNhbs(vvgraph& S, vertex& a, vertex& b)
-{
-  vertex n = S.nextTo(b, a);
-  vertex m = S.prevTo(b, a);
-  vertex pv = n;
-
-  while(n != m) {
-    if(!S.edge(a, n)) {
-      S.spliceAfter(a, pv, n);
-      S.spliceAfter(n, b, a);
+  
+  bool MergeVertices::operator()(Mesh* mesh)
+  {
+    typedef std::map<vertex, int> VtxIntMap;
+  
+    vvgraph& S = mesh->graph();
+    vvgraph vs = mesh->activeVertices();
+    if(vs.size() < 2)
+      throw QString("Error, Must select at least two connected vertices.");
+  
+    VtxIntMap weight;
+    int count = 0;
+    bool vertexDeleted;
+    do {
+      vertexDeleted = false;
+      forall(vertex a, vs) {
+        forall(vertex b, S.neighbors(a))
+          if(vs.contains(b) and spliceNhbs(S, a, b)) {
+            if(weight.count(a) == 0)
+              weight[a] = 1;
+            if(weight.count(b) == 0)
+              weight[b] = 1;
+            a->pos = (a->pos * weight[a] + b->pos * weight[b]) / float(weight[a] + weight[b]);
+            weight[a] += weight[b];
+            S.erase(b);
+            count++;
+            vertexDeleted = true;
+            break;
+          }
+        if(vertexDeleted)
+          break;
+      }
+    } while(vertexDeleted);
+  
+    if(count > 0)
+      mesh->updateAll();
+  
+    Information::out << count << " vertices deleted from mesh" << endl;
+    return true;
+  }
+  REGISTER_MESH_PROCESS(MergeVertices);
+  
+  bool DeleteEdge::operator()(Mesh* mesh)
+  {
+    vvgraph& S = mesh->graph();
+    vvgraph vs = mesh->activeVertices();
+    if(vs.size() != 2)
+      throw QString("Error, Must have exactly two vertices selected.");
+  
+    vertex v1 = *(vs.begin()), v2 = *(vs.begin() + 1);
+    if(!S.edge(v1, v2))
+      throw QString("Error, Vertices have no edge between them.");
+  
+    S.eraseEdge(v1, v2);
+    S.eraseEdge(v2, v1);
+  
+    mesh->updateAll();
+  
+    Information::out << "Edge deleted from mesh" << endl;
+    return true;
+  }
+  REGISTER_MESH_PROCESS(DeleteEdge);
+  
+  bool MeshDeleteSelection::operator()(Mesh* m)
+  {
+    m->correctSelection(false);
+    vvgraph& S = m->graph();
+  
+    size_t n = S.size();
+    for(size_t i = 0; i < n; ++i) {
+      size_t j = n - i - 1;
+      if((*(S.begin() + j))->selected)
+        S.erase(S.begin() + j);
     }
-    pv = n;
-    n = S.nextTo(b, n);
+  
+    m->updateAll();
+    return true;
   }
-  return true;
-}
-
-bool MergeVertices::operator()(Mesh* mesh)
-{
-  typedef std::map<vertex, int> VtxIntMap;
-
-  vvgraph& S = mesh->graph();
-  vvgraph vs = mesh->activeVertices();
-  if(vs.size() < 2)
-    throw QString("Error, Must select at least two connected vertices.");
-
-  VtxIntMap weight;
-  int count = 0;
-  bool vertexDeleted;
-  do {
-    vertexDeleted = false;
-    forall(vertex a, vs) {
-      forall(vertex b, S.neighbors(a))
-        if(vs.contains(b) and spliceNhbs(S, a, b)) {
-          if(weight.count(a) == 0)
-            weight[a] = 1;
-          if(weight.count(b) == 0)
-            weight[b] = 1;
-          a->pos = (a->pos * weight[a] + b->pos * weight[b]) / float(weight[a] + weight[b]);
-          weight[a] += weight[b];
-          S.erase(b);
-          count++;
-          vertexDeleted = true;
-          break;
-        }
-      if(vertexDeleted)
-        break;
-    }
-  } while(vertexDeleted);
-
-  if(count > 0)
+  REGISTER_MESH_PROCESS(MeshDeleteSelection);
+  
+  bool MeshKeepVertices::operator()(Mesh* mesh, bool keep)
+  {
+    const std::vector<vertex>& vs = mesh->activeVertices();
+  
+    forall(const vertex& v, vs)
+      if(keep)
+        v->type = 'l';
+      else if(v->type == 'l')
+        v->type = 'j';
+  
     mesh->updateAll();
-
-  Information::out << count << " vertices deleted from mesh" << endl;
-  return true;
-}
-REGISTER_MESH_PROCESS(MergeVertices);
-
-bool DeleteEdge::operator()(Mesh* mesh)
-{
-  vvgraph& S = mesh->graph();
-  vvgraph vs = mesh->activeVertices();
-  if(vs.size() != 2)
-    throw QString("Error, Must have exactly two vertices selected.");
-
-  vertex v1 = *(vs.begin()), v2 = *(vs.begin() + 1);
-  if(!S.edge(v1, v2))
-    throw QString("Error, Vertices have no edge between them.");
-
-  S.eraseEdge(v1, v2);
-  S.eraseEdge(v2, v1);
-
-  mesh->updateAll();
-
-  Information::out << "Edge deleted from mesh" << endl;
-  return true;
-}
-REGISTER_MESH_PROCESS(DeleteEdge);
-
-bool MeshDeleteSelection::operator()(Mesh* m)
-{
-  m->correctSelection(false);
-  vvgraph& S = m->graph();
-
-  size_t n = S.size();
-  for(size_t i = 0; i < n; ++i) {
-    size_t j = n - i - 1;
-    if(S[j]->selected)
-      S.erase(S.begin() + j);
+    return true;
   }
+  REGISTER_MESH_PROCESS(MeshKeepVertices);
 
-  m->updateAll();
-  return true;
-}
-REGISTER_MESH_PROCESS(MeshDeleteSelection);
-
-bool MeshKeepVertices::operator()(Mesh* mesh, bool keep)
-{
-  const std::vector<vertex>& vs = mesh->activeVertices();
-
-  forall(const vertex& v, vs)
-    if(keep)
-      v->type = 'l';
-    else if(v->type == 'l')
-      v->type = 'j';
-
-  mesh->updateAll();
-  return true;
-}
-REGISTER_MESH_PROCESS(MeshKeepVertices);
-} // namespace process
-} // namespace mgx
+}}
Index: SystemProcessLoad.cpp
===================================================================
--- SystemProcessLoad.cpp	(revision 1255)
+++ SystemProcessLoad.cpp	(revision 1256)
@@ -1,4 +1,5 @@
 #include "SystemProcessLoad.hpp"
+#include "MeshProcessLineage.hpp"
 
 #include "Dir.hpp"
 #include "Forall.hpp"
@@ -42,2445 +43,2598 @@
 
 static QTextStream err(stderr);
 
-namespace mgx {
-namespace process {
+namespace mgx { namespace process {
 
-typedef std::tr1::unordered_map<int, vertex> vertex_map;
-
-typedef CImg<ushort> CImgUS;
-
-struct SwapBytes {
-  ushort operator()(const ushort& us)
+  typedef std::tr1::unordered_map<int, vertex> vertex_map;
+  
+  typedef CImg<ushort> CImgUS;
+  
+  struct SwapBytes {
+    ushort operator()(const ushort& us)
+    {
+      // Uncomment the following lines to test speed
+      // ushort t = us;
+      // for(int i = 0 ; i < 19 ; ++i)
+      // t = ((t & 0x00ff) << 8) + ((t & 0xff00) >> 8);
+      // return t;
+  
+      return ((us & 0x00ff) << 8) + ((us & 0xff00) >> 8);
+    }
+  };
+  
+  bool StackSwapBytes::operator()(const Store* input, Store* output)
   {
-    // Uncomment the following lines to test speed
-    // ushort t = us;
-    // for(int i = 0 ; i < 19 ; ++i)
-    // t = ((t & 0x00ff) << 8) + ((t & 0xff00) >> 8);
-    // return t;
-
-    return ((us & 0x00ff) << 8) + ((us & 0xff00) >> 8);
+    thrust::transform(THRUST_RETAG(input->data().begin()), THRUST_RETAG(input->data().end()),
+                      THRUST_RETAG(output->data().begin()), SwapBytes());
+    output->copyMetaData(input);
+    output->changed();
+    return true;
   }
-};
-
-bool StackSwapBytes::operator()(const Store* input, Store* output)
-{
-  thrust::transform(THRUST_RETAG(input->data().begin()), THRUST_RETAG(input->data().end()),
-                    THRUST_RETAG(output->data().begin()), SwapBytes());
-  output->copyMetaData(input);
-  output->changed();
-  return true;
-}
-
-struct StackHdr {
-  uint hdrsz;
-  uint xsz, ysz, zsz;
-  float xum, yum, zum;
-  uint datasz;
-
-  StackHdr()
-    : hdrsz(1024)
+  
+  struct StackHdr {
+    uint hdrsz;
+    uint xsz, ysz, zsz;
+    float xum, yum, zum;
+    uint datasz;
+  
+    StackHdr()
+      : hdrsz(1024)
+    {
+    }
+  };
+  
+  bool StackImport::initialize(QStringList& parms, QWidget* parent)
   {
+    int stackId = parms[0].toInt();
+    QString storeName = parms[1];
+    Point3f step(parms[2].toFloat(), parms[3].toFloat(), parms[4].toFloat());
+    float brightness(parms[5].toFloat());
+    QString filename(parms[6]);
+  
+    // Get stack and store
+    Stack* stk = currentStack();
+    if(stackId != -1)
+      stk = stack(parms[0].toInt());
+    if(!checkState().stack(STACK_ANY, stackId))
+      return false;
+  
+    Store* store = stk->currentStore();
+    if(storeName == "Main")
+      store = stk->main();
+    else if(storeName == "Work")
+      store = stk->work();
+  
+    // Set up dialog
+    QDialog dlg(parent);
+    this->dlg = &dlg;
+    Ui_LoadStackDialog ui;
+    this->ui = &ui;
+    ui.setupUi(&dlg);
+    bool res = false;
+  
+    QObject::connect(ui.AddFiles, SIGNAL(clicked()), this, SLOT(AddFilesSlot()));
+    QObject::connect(ui.RemoveFiles, SIGNAL(clicked()), this, SLOT(RemoveFilesSlot()));
+    QObject::connect(ui.LoadProfile, SIGNAL(clicked()), this, SLOT(LoadProfile()));
+    QObject::connect(ui.SaveProfile, SIGNAL(clicked()), this, SLOT(SaveProfile()));
+    QObject::connect(ui.FilterFiles, SIGNAL(clicked()), this, SLOT(FilterFilesSlot()));
+    QObject::connect(ui.SortAscending, SIGNAL(clicked()), this, SLOT(SortAscendingSlot()));
+    QObject::connect(ui.SortDescending, SIGNAL(clicked()), this, SLOT(SortDescendingSlot()));
+    QObject::connect(ui.ImageFiles, SIGNAL(filesDropped(const QStringList &)), this,
+                     SLOT(AddFilesSlot(const QStringList &)));
+  
+    setImageSize(512, 512, 0);
+    ui.StepX->setValue(step.x());
+    ui.StepY->setValue(step.y());
+    ui.StepZ->setValue(step.z());
+    ui.Brightness->setValue(brightness);
+    ui.ImageFiles->clear();
+  
+    QString currentFile(store->file());
+  
+    if(currentFile.endsWith(".txt", Qt::CaseInsensitive)) {
+      // If current stack file is a .txt file, load it as a profile
+      LoadProfile(currentFile);
+      loadedFile = currentFile;
+    } else if(filename.endsWith(".txt", Qt::CaseInsensitive)) {
+      // If file list contains one
+      LoadProfile(filename);
+      loadedFile = filename;
+    }
+  
+    if(dlg.exec() == QDialog::Accepted) {
+      // Change parms
+      parms[2] = QString::number(ui.StepX->value());
+      parms[3] = QString::number(ui.StepY->value());
+      parms[4] = QString::number(ui.StepZ->value());
+      parms[5] = QString::number(ui.Brightness->value());
+      parms[6] = loadedFile;
+  
+      // Save image files
+      for(int i = 0; i < ui.ImageFiles->count(); ++i)
+        imageFiles << ui.ImageFiles->item(i)->text();
+  
+      res = true;
+    }
+  
+    this->dlg = 0;
+    this->ui = 0;
+    return res;
   }
-};
-
-bool StackImport::initialize(QStringList& parms, QWidget* parent)
-{
-  int stackId = parms[0].toInt();
-  QString storeName = parms[1];
-  Point3f step(parms[2].toFloat(), parms[3].toFloat(), parms[4].toFloat());
-  float brightness(parms[5].toFloat());
-  QString filename(parms[6]);
-
-  // Get stack and store
-  Stack* stk = currentStack();
-  if(stackId != -1)
-    stk = stack(parms[0].toInt());
-  if(!checkState().stack(STACK_ANY, stackId))
+  
+  bool StackImport::LoadProfile(QString filename, Point3u& size, Point3f& step, float& brightness, QStringList& files)
+  {
+    if(QFile::exists(filename)) {
+      util::Parms parms(filename);
+  
+      bool ok = true;
+      ok &= parms("Stack", "SizeX", size.x());
+      ok &= parms("Stack", "SizeY", size.y());
+      // New version: StepX and StepY and separate
+      if(parms("Stack", "StepX", step.x())) {
+        parms("Stack", "StepY", step.y());
+        parms("Stack", "StepZ", step.z());
+      } else {
+        // This is for backward compatibility
+        if(!parms("Stack", "StepXY", step.x()) or !parms("Stack", "StepZ", step.z())) {
+          float zScale;
+          if(parms("Stack", "ZScale", zScale)) {
+            step.z() = .5;
+            step.x() = step.z() / zScale;
+          } else
+            ok = false;
+        }
+        step.y() = step.x();
+      }
+      ok &= parms("Stack", "Brightness", brightness);
+      if(!ok) {
+        SETSTATUS("loadStack::Error:Cannot read parameter file:" << filename);
+        return false;
+      }
+      parms.all("Stack", "ImageFile", files);
+      size.z() = files.size();
+      txtFile = filename;
+      return true;
+    }
     return false;
-
-  Store* store = stk->currentStore();
-  if(storeName == "Main")
-    store = stk->main();
-  else if(storeName == "Work")
-    store = stk->work();
-
-  // Set up dialog
-  QDialog dlg(parent);
-  this->dlg = &dlg;
-  Ui_LoadStackDialog ui;
-  this->ui = &ui;
-  ui.setupUi(&dlg);
-  bool res = false;
-
-  QObject::connect(ui.AddFiles, SIGNAL(clicked()), this, SLOT(AddFilesSlot()));
-  QObject::connect(ui.RemoveFiles, SIGNAL(clicked()), this, SLOT(RemoveFilesSlot()));
-  QObject::connect(ui.LoadProfile, SIGNAL(clicked()), this, SLOT(LoadProfile()));
-  QObject::connect(ui.SaveProfile, SIGNAL(clicked()), this, SLOT(SaveProfile()));
-  QObject::connect(ui.FilterFiles, SIGNAL(clicked()), this, SLOT(FilterFilesSlot()));
-  QObject::connect(ui.SortAscending, SIGNAL(clicked()), this, SLOT(SortAscendingSlot()));
-  QObject::connect(ui.SortDescending, SIGNAL(clicked()), this, SLOT(SortDescendingSlot()));
-  QObject::connect(ui.ImageFiles, SIGNAL(filesDropped(const QStringList &)), this,
-                   SLOT(AddFilesSlot(const QStringList &)));
-
-  setImageSize(512, 512, 0);
-  ui.StepX->setValue(step.x());
-  ui.StepY->setValue(step.y());
-  ui.StepZ->setValue(step.z());
-  ui.Brightness->setValue(brightness);
-  ui.ImageFiles->clear();
-
-  QString currentFile(store->file());
-
-  if(currentFile.endsWith(".txt", Qt::CaseInsensitive)) {
-    // If current stack file is a .txt file, load it as a profile
-    LoadProfile(currentFile);
-    loadedFile = currentFile;
-  } else if(filename.endsWith(".txt", Qt::CaseInsensitive)) {
-    // If file list contains one
-    LoadProfile(filename);
-    loadedFile = filename;
   }
-
-  if(dlg.exec() == QDialog::Accepted) {
-    // Change parms
-    parms[2] = QString::number(ui.StepX->value());
-    parms[3] = QString::number(ui.StepY->value());
-    parms[4] = QString::number(ui.StepZ->value());
-    parms[5] = QString::number(ui.Brightness->value());
-    parms[6] = loadedFile;
-
-    // Save image files
-    for(int i = 0; i < ui.ImageFiles->count(); ++i)
-      imageFiles << ui.ImageFiles->item(i)->text();
-
-    res = true;
+  
+  void StackImport::LoadProfile(QString filename)
+  {
+    if(filename.isEmpty()) {
+      filename = QFileDialog::getOpenFileName(dlg, QString("Select profile file to open"), filename,
+                                              QString("Text files (*.txt)"), 0, FileDialogOptions);
+      if(filename.isEmpty())
+        return;
+    }
+  
+    QStringList ImageFiles;
+    Point3u size;
+    Point3f step;
+    float brightness;
+    if(LoadProfile(filename, size, step, brightness, imageFiles)) {
+      setImageSize(size.x(), size.y(), size.z());
+      ui->StepX->setValue(step.x());
+      ui->StepY->setValue(step.y());
+      ui->StepZ->setValue(step.z());
+      ui->Brightness->setValue(brightness);
+      QListWidget* lst = ui->ImageFiles;
+      lst->clear();
+      forall(const QString& s, imageFiles)
+        lst->addItem(s);
+  
+      loadedFile = filename;
+    }
   }
-
-  this->dlg = 0;
-  this->ui = 0;
-  return res;
-}
-
-bool StackImport::LoadProfile(QString filename, Point3u& size, Point3f& step, float& brightness, QStringList& files)
-{
-  if(QFile::exists(filename)) {
-    util::Parms parms(filename);
-
-    bool ok = true;
-    ok &= parms("Stack", "SizeX", size.x());
-    ok &= parms("Stack", "SizeY", size.y());
-    // New version: StepX and StepY and separate
-    if(parms("Stack", "StepX", step.x())) {
-      parms("Stack", "StepY", step.y());
-      parms("Stack", "StepZ", step.z());
-    } else {
-      // This is for backward compatibility
-      if(!parms("Stack", "StepXY", step.x()) or !parms("Stack", "StepZ", step.z())) {
-        float zScale;
-        if(parms("Stack", "ZScale", zScale)) {
-          step.z() = .5;
-          step.x() = step.z() / zScale;
-        } else
-          ok = false;
-      }
-      step.y() = step.x();
+  
+  void StackImport::SaveProfile()
+  {
+    // Write to file
+    QString filename = QFileDialog::getSaveFileName(dlg, QString("Select file to save profile for "), loadedFile,
+                                                    QString("Text files (*.txt)"), 0, FileDialogOptions);
+    if(filename.isEmpty())
+      return;
+  
+    // Check ending, add suffix if required
+    if(filename.right(4) != ".txt")
+      filename.append(".txt");
+  
+    QFile file(filename);
+    if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
+      SETSTATUS("loadStackSaveProfile::Error:Cannot open output file:" << filename);
+      return;
     }
-    ok &= parms("Stack", "Brightness", brightness);
-    if(!ok) {
-      SETSTATUS("loadStack::Error:Cannot read parameter file:" << filename);
-      return false;
+    QString StackFile = util::stripCurrentDir(filename);
+    actingFile(filename);
+  
+    QTextStream out(&file);
+    out << "[Stack]" << endl;
+    out << "SizeX: " << imageSize.x() << endl;
+    out << "SizeY: " << imageSize.y() << endl;
+    out << "StepX: " << ui->StepX->value() << endl;
+    out << "StepY: " << ui->StepY->value() << endl;
+    out << "StepZ: " << ui->StepZ->value() << endl;
+    out << "Brightness: " << ui->Brightness->value() << endl;
+    QListWidget* lst = ui->ImageFiles;
+    for(int i = 0; i < lst->count(); i++) {
+      QListWidgetItem* item = lst->item(i);
+      out << "ImageFile: " << util::stripCurrentDir(item->text()) << endl;
     }
-    parms.all("Stack", "ImageFile", files);
-    size.z() = files.size();
+    file.close();
+    loadedFile = filename;
+    SETSTATUS("Saving profile, file:" << filename);
     txtFile = filename;
-    return true;
   }
-  return false;
-}
-
-void StackImport::LoadProfile(QString filename)
-{
-  if(filename.isEmpty()) {
-    filename = QFileDialog::getOpenFileName(dlg, QString("Select profile file to open"), filename,
-                                            QString("Text files (*.txt)"), 0, FileDialogOptions);
-    if(filename.isEmpty())
+  
+  void StackImport::AddFilesSlot()
+  {
+    // RSS How to get a complete list from CImg? (there are over 100)
+    QStringList files = QFileDialog::getOpenFileNames(dlg, QString("Select stack image files "), util::currentPath(),
+                                                      QString("Any files (*.*)"), 0);
+    if(files.empty())
       return;
+  
+    AddFilesSlot(files);
   }
-
-  QStringList ImageFiles;
-  Point3u size;
-  Point3f step;
-  float brightness;
-  if(LoadProfile(filename, size, step, brightness, imageFiles)) {
-    setImageSize(size.x(), size.y(), size.z());
+  
+  void StackImport::AddFilesSlot(const QStringList& files)
+  {
+    QListWidget* lst = ui->ImageFiles;
+    if(lst->count() == 0) {
+      QString first = files[0];
+      Image3D image;
+      image.step = imageResolution();
+      if(!loadImage(first, image)) {
+        QMessageBox::critical(dlg, "Error reading image", QString("Error, cannot read image from '%1'").arg(first));
+        return;
+      }
+      SETSTATUS(QString("Loaded first image: size = %1x%2").arg(image.size.x()).arg(image.size.y()));
+      // CImgUS image(qPrintable(first));
+      setImageSize(image.size.x(), image.size.y(), 0);
+      setImageResolution(image.step);
+    }
+    lst->addItems(files);
+    setImageSize(imageSize.x(), imageSize.y(), lst->count());
+  }
+  
+  Point3f StackImport::imageResolution() {
+    return Point3f(ui->StepX->value(), ui->StepY->value(), ui->StepZ->value());
+  }
+  
+  void StackImport::setImageResolution(Point3f step)
+  {
     ui->StepX->setValue(step.x());
     ui->StepY->setValue(step.y());
     ui->StepZ->setValue(step.z());
-    ui->Brightness->setValue(brightness);
-    QListWidget* lst = ui->ImageFiles;
-    lst->clear();
-    forall(const QString& s, imageFiles)
-      lst->addItem(s);
-
-    loadedFile = filename;
   }
-}
-
-void StackImport::SaveProfile()
-{
-  // Write to file
-  QString filename = QFileDialog::getSaveFileName(dlg, QString("Select file to save profile for "), loadedFile,
-                                                  QString("Text files (*.txt)"), 0, FileDialogOptions);
-  if(filename.isEmpty())
-    return;
-
-  // Check ending, add suffix if required
-  if(filename.right(4) != ".txt")
-    filename.append(".txt");
-
-  QFile file(filename);
-  if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
-    SETSTATUS("loadStackSaveProfile::Error:Cannot open output file:" << filename);
-    return;
+  
+  void StackImport::setImageSize(Point3u size)
+  {
+    imageSize = size;
+    ui->SizeXY->setText(QString("(%1,%2,%3)").arg(imageSize.x()).arg(imageSize.y()).arg(imageSize.z()));
   }
-  QString StackFile = util::stripCurrentDir(filename);
-  actingFile(filename);
-
-  QTextStream out(&file);
-  out << "[Stack]" << endl;
-  out << "SizeX: " << imageSize.x() << endl;
-  out << "SizeY: " << imageSize.y() << endl;
-  out << "StepX: " << ui->StepX->value() << endl;
-  out << "StepY: " << ui->StepY->value() << endl;
-  out << "StepZ: " << ui->StepZ->value() << endl;
-  out << "Brightness: " << ui->Brightness->value() << endl;
-  QListWidget* lst = ui->ImageFiles;
-  for(int i = 0; i < lst->count(); i++) {
-    QListWidgetItem* item = lst->item(i);
-    out << "ImageFile: " << util::stripCurrentDir(item->text()) << endl;
+  
+  void StackImport::RemoveFilesSlot()
+  {
+    QListWidget* lst = ui->ImageFiles;
+    QList<QListWidgetItem*> items = lst->selectedItems();
+    for(QList<QListWidgetItem*>::iterator i = items.begin(); i != items.end(); i++) {
+      QListWidgetItem* item = lst->takeItem(lst->row(*i));
+      delete item;
+    }
+    setImageSize(imageSize.x(), imageSize.y(), lst->count());
   }
-  file.close();
-  loadedFile = filename;
-  SETSTATUS("Saving profile, file:" << filename);
-  txtFile = filename;
-}
-
-void StackImport::AddFilesSlot()
-{
-  // RSS How to get a complete list from CImg? (there are over 100)
-  QStringList files = QFileDialog::getOpenFileNames(dlg, QString("Select stack image files "), util::currentPath(),
-                                                    QString("Any files (*.*)"), 0);
-  if(files.empty())
-    return;
-
-  AddFilesSlot(files);
-}
-
-void StackImport::AddFilesSlot(const QStringList& files)
-{
-  QListWidget* lst = ui->ImageFiles;
-  if(lst->count() == 0) {
-    QString first = files[0];
-    Image3D image;
-    image.step = imageResolution();
-    if(!loadImage(first, image)) {
-      QMessageBox::critical(dlg, "Error reading image", QString("Error, cannot read image from '%1'").arg(first));
-      return;
+  
+  void StackImport::FilterFilesSlot()
+  {
+    QListWidget* lst = ui->ImageFiles;
+    QString text = ui->FilterText->text();
+  
+    QList<QListWidgetItem*> items = lst->findItems(".*", Qt::MatchRegExp);
+    for(QList<QListWidgetItem*>::iterator i = items.begin(); i != items.end(); i++) {
+      QString itemtext = (*i)->text();
+      if(itemtext.indexOf(text) < 0) {
+        QListWidgetItem* item = lst->takeItem(lst->row(*i));
+        delete item;
+      }
     }
-    SETSTATUS(QString("Loaded first image: size = %1x%2").arg(image.size.x()).arg(image.size.y()));
-    // CImgUS image(qPrintable(first));
-    setImageSize(image.size.x(), image.size.y(), 0);
-    setImageResolution(image.step);
   }
-  lst->addItems(files);
-  setImageSize(imageSize.x(), imageSize.y(), lst->count());
-}
-
-Point3f StackImport::imageResolution() {
-  return Point3f(ui->StepX->value(), ui->StepY->value(), ui->StepZ->value());
-}
-
-void StackImport::setImageResolution(Point3f step)
-{
-  ui->StepX->setValue(step.x());
-  ui->StepY->setValue(step.y());
-  ui->StepZ->setValue(step.z());
-}
-
-void StackImport::setImageSize(Point3u size)
-{
-  imageSize = size;
-  ui->SizeXY->setText(QString("(%1,%2,%3)").arg(imageSize.x()).arg(imageSize.y()).arg(imageSize.z()));
-}
-
-void StackImport::RemoveFilesSlot()
-{
-  QListWidget* lst = ui->ImageFiles;
-  QList<QListWidgetItem*> items = lst->selectedItems();
-  for(QList<QListWidgetItem*>::iterator i = items.begin(); i != items.end(); i++) {
-    QListWidgetItem* item = lst->takeItem(lst->row(*i));
-    delete item;
+  
+  void StackImport::SortAscendingSlot(bool val)
+  {
+    QListWidget* lst = ui->ImageFiles;
+    lst->sortItems((val ? Qt::AscendingOrder : Qt::DescendingOrder));
   }
-  setImageSize(imageSize.x(), imageSize.y(), lst->count());
-}
-
-void StackImport::FilterFilesSlot()
-{
-  QListWidget* lst = ui->ImageFiles;
-  QString text = ui->FilterText->text();
-
-  QList<QListWidgetItem*> items = lst->findItems(".*", Qt::MatchRegExp);
-  for(QList<QListWidgetItem*>::iterator i = items.begin(); i != items.end(); i++) {
-    QString itemtext = (*i)->text();
-    if(itemtext.indexOf(text) < 0) {
-      QListWidgetItem* item = lst->takeItem(lst->row(*i));
-      delete item;
+  
+  void StackImport::SortDescendingSlot() {
+    SortAscendingSlot(false);
+  }
+  
+  bool StackImport::operator()(Stack* stack, Store* store, Point3f step, float brightness, QString filename)
+  {
+    Point3u size;
+    if(filename.size() > 0) {
+      LoadProfile(filename, size, step, brightness, imageFiles);
+      actingFile(filename);
     }
+  
+    HVecUS& data = store->data();
+    {
+      CImgUS first_image(qPrintable(imageFiles.at(0)));
+      size = Point3u(first_image.width(), first_image.height(), imageFiles.size());
+    }
+    stack->setSize(size);
+    stack->setStep(step);
+    size_t SizeXYZ = size_t(size.x()) * size.y() * size.z();
+    store->setFile(filename);
+    uint filecount = 0;
+    SETSTATUS("Loading " << ((store == stack->main()) ? "main" : "work") << " stack " << stack->userId());
+    Progress progress(
+      QString("Loading %1 Stack %2").arg((store == stack->main()) ? "main" : "work").arg(stack->userId()), size.z());
+    memset(&data[0], 0, SizeXYZ * sizeof(ushort));
+  
+    Image3D image(data, size, step);
+    image.brightness = brightness;
+    image.minc = 65535;
+    image.maxc = 0;
+    for(uint z = 0; z < size.z(); z++) {
+      image.plane = filecount++;
+      if(!loadImage(imageFiles.at(z), image)) {
+        setErrorMessage(QString("Cannot read image from file '%1'").arg(imageFiles.at(z)));
+        return false;
+      }
+      SETSTATUS("Read File:" << imageFiles.at(z));
+      if(!progress.advance(z + 1))
+        userCancel();
+    }
+    if(image.maxc > 0xFFFF)
+      SETSTATUS("WARNING: max intensity:" << image.maxc << ", clipped at:" << 0xFFFF);
+    else
+      SETSTATUS(filecount << " of " << size.z() << " files,read intensity range:" << image.minc << "-" << image.maxc);
+    stack->center();
+    store->changed();
+    return true;
   }
-}
-
-void StackImport::SortAscendingSlot(bool val)
-{
-  QListWidget* lst = ui->ImageFiles;
-  lst->sortItems((val ? Qt::AscendingOrder : Qt::DescendingOrder));
-}
-
-void StackImport::SortDescendingSlot() {
-  SortAscendingSlot(false);
-}
-
-bool StackImport::operator()(Stack* stack, Store* store, Point3f step, float brightness, QString filename)
-{
-  Point3u size;
-  if(filename.size() > 0) {
-    LoadProfile(filename, size, step, brightness, imageFiles);
-    actingFile(filename);
+  
+  bool StackOpen::initialize(QStringList& parms, QWidget* parent)
+  {
+    bool is_work_store = stringToWorkStore(parms[1]);
+    int stackId = parms[2].toInt();
+    if(!checkState().store((is_work_store ? STORE_WORK : STORE_MAIN), stackId))
+      return false;
+    QString allFilters("All Stack files (*.mgxs *.inr *.tif *.tiff)");
+    QString mgxsFilter("MorphoGraphX Stack files (*.mgxs)"), inrFilter("Inria Stack files (*.inr)"),
+    tifFilter("TIFF Image Directory (*.tif *.tiff)"), filter;
+    QString filename = parms[0];
+  
+    QString currentFile;
+    if(is_work_store)
+      currentFile = stack(stackId)->work()->file();
+    else
+      currentFile = stack(stackId)->main()->file();
+    if(!currentFile.isEmpty())
+      filename = currentFile;
+  
+    // If we loaded a list of images before, strip of the ending and default type
+    if(filename.right(4) == ".txt") {
+      filename = filename.left(filename.length() - 4);
+      filename += ".mgxs";
+    }
+  
+    if(filename.right(4) == ".inr")
+      filter = inrFilter;
+    else if(filename.endsWith(".tif", Qt::CaseInsensitive) or filename.endsWith(".tiff", Qt::CaseInsensitive))
+      filter = tifFilter;
+    else if(filename.endsWith(".mgx", Qt::CaseInsensitive))
+      filter = mgxsFilter;
+    else
+      filter = allFilters;
+  
+    // Get the file name
+    filename = QFileDialog::getOpenFileName(
+        parent, QString("Select stack file"), filename,
+        QString(allFilters + ";;" + mgxsFilter + ";;" + inrFilter + ";;" + tifFilter), &filter, FileDialogOptions);
+    if(filename.isEmpty())
+      return false;
+  
+    parms[0] = filename;
+    return true;
   }
-
-  HVecUS& data = store->data();
+  
+  bool StackOpen::operator()(const QStringList& parms)
   {
-    CImgUS first_image(qPrintable(imageFiles.at(0)));
-    size = Point3u(first_image.width(), first_image.height(), imageFiles.size());
-  }
-  stack->setSize(size);
-  stack->setStep(step);
-  size_t SizeXYZ = size_t(size.x()) * size.y() * size.z();
-  store->setFile(filename);
-  uint filecount = 0;
-  SETSTATUS("Loading " << ((store == stack->main()) ? "main" : "work") << " stack " << stack->userId());
-  Progress progress(
-    QString("Loading %1 Stack %2").arg((store == stack->main()) ? "main" : "work").arg(stack->userId()), size.z());
-  memset(&data[0], 0, SizeXYZ * sizeof(ushort));
-
-  Image3D image(data, size, step);
-  image.brightness = brightness;
-  image.minc = 65535;
-  image.maxc = 0;
-  for(uint z = 0; z < size.z(); z++) {
-    image.plane = filecount++;
-    if(!loadImage(imageFiles.at(z), image)) {
-      setErrorMessage(QString("Cannot read image from file '%1'").arg(imageFiles.at(z)));
+    int stackId = parms[2].toInt();
+    if(!checkState().stack(STACK_ANY, stackId))
       return false;
+    Stack* stack = this->stack(stackId);
+    Store* store = (stringToWorkStore(parms[1]) ? stack->work() : stack->main());
+    bool res = (*this)(stack, store, parms[0]);
+    if(res) {
+      store->show();
     }
-    SETSTATUS("Read File:" << imageFiles.at(z));
-    if(!progress.advance(z + 1))
-      userCancel();
+    return res;
   }
-  if(image.maxc > 0xFFFF)
-    SETSTATUS("WARNING: max intensity:" << image.maxc << ", clipped at:" << 0xFFFF);
-  else
-    SETSTATUS(filecount << " of " << size.z() << " files,read intensity range:" << image.minc << "-" << image.maxc);
-  stack->center();
-  store->changed();
-  return true;
-}
-
-// REGISTER_STACK_PROCESS(StackImport);
-
-bool StackOpen::initialize(QStringList& parms, QWidget* parent)
-{
-  bool is_work_store = stringToWorkStore(parms[1]);
-  int stackId = parms[2].toInt();
-  if(!checkState().store((is_work_store ? STORE_WORK : STORE_MAIN), stackId))
-    return false;
-  QString allFilters("All Stack files (*.mgxs *.inr *.tif *.tiff)");
-  QString mgxsFilter("MorphoGraphX Stack files (*.mgxs)"), inrFilter("Inria Stack files (*.inr)"),
-  tifFilter("TIFF Image Directory (*.tif *.tiff)"), filter;
-  QString filename = parms[0];
-
-  QString currentFile;
-  if(is_work_store)
-    currentFile = stack(stackId)->work()->file();
-  else
-    currentFile = stack(stackId)->main()->file();
-  if(!currentFile.isEmpty())
-    filename = currentFile;
-
-  // If we loaded a list of images before, strip of the ending and default type
-  if(filename.right(4) == ".txt") {
-    filename = filename.left(filename.length() - 4);
-    filename += ".mgxs";
+  
+  bool StackOpen::loadMGXS_0(QIODevice& file, Stack* stack, Store* store)
+  {
+    HVecUS& data = store->data();
+    QByteArray stkdata = file.readAll();
+    file.close();
+    stkdata = qUncompress(stkdata);
+  
+    struct StackHdr stkhdr;
+    memcpy(&stkhdr, stkdata.constData(), sizeof(stkhdr));
+    Point3u size(stkhdr.xsz, stkhdr.ysz, stkhdr.zsz);
+    Point3f step(stkhdr.xum, stkhdr.yum, stkhdr.zum);
+    stack->setSize(size);
+    stack->setStep(step);
+    if(stkhdr.datasz / 2 != stack->storeSize())
+      throw QString("Datasize does not match dimensions in .mgxs file");
+    memcpy(data.data(), stkdata.constData() + stkhdr.hdrsz, stkhdr.datasz);
+    return true;
   }
-
-  if(filename.right(4) == ".inr")
-    filter = inrFilter;
-  else if(filename.endsWith(".tif", Qt::CaseInsensitive) or filename.endsWith(".tiff", Qt::CaseInsensitive))
-    filter = tifFilter;
-  else if(filename.endsWith(".mgx", Qt::CaseInsensitive))
-    filter = mgxsFilter;
-  else
-    filter = allFilters;
-
-  // Get the file name
-  filename = QFileDialog::getOpenFileName(
-      parent, QString("Select stack file"), filename,
-      QString(allFilters + ";;" + mgxsFilter + ";;" + inrFilter + ";;" + tifFilter), &filter, FileDialogOptions);
-  if(filename.isEmpty())
-    return false;
-
-  parms[0] = filename;
-  return true;
-}
-
-bool StackOpen::operator()(const QStringList& parms)
-{
-  int stackId = parms[2].toInt();
-  if(!checkState().stack(STACK_ANY, stackId))
-    return false;
-  Stack* stack = this->stack(stackId);
-  Store* store = (stringToWorkStore(parms[1]) ? stack->work() : stack->main());
-  bool res = (*this)(stack, store, parms[0]);
-  if(res) {
-    store->show();
+  
+  bool StackOpen::loadMGXS_1_3(QIODevice& file, Stack* stack, Store* store)
+  {
+    bool isLabel;
+    float sxum, syum, szum;
+    file.read((char*)&isLabel, sizeof(bool));
+    file.read((char*)&sxum, sizeof(float));
+    file.read((char*)&syum, sizeof(float));
+    file.read((char*)&szum, sizeof(float));
+    bool result = loadMGXS_1_0(file, stack, store);
+    if(result) {
+      store->setLabels(isLabel);
+      stack->setOrigin(Point3f(sxum, syum, szum));
+      SETSTATUS("Set stack step to " << stack->origin());
+    }
+    return result;
   }
-  return res;
-}
-
-bool StackOpen::loadMGXS_0(QIODevice& file, Stack* stack, Store* store)
-{
-  HVecUS& data = store->data();
-  QByteArray stkdata = file.readAll();
-  file.close();
-  stkdata = qUncompress(stkdata);
-
-  struct StackHdr stkhdr;
-  memcpy(&stkhdr, stkdata.constData(), sizeof(stkhdr));
-  Point3u size(stkhdr.xsz, stkhdr.ysz, stkhdr.zsz);
-  Point3f step(stkhdr.xum, stkhdr.yum, stkhdr.zum);
-  stack->setSize(size);
-  stack->setStep(step);
-  if(stkhdr.datasz / 2 != stack->storeSize())
-    throw QString("Datasize does not match dimensions in .mgxs file");
-  memcpy(data.data(), stkdata.constData() + stkhdr.hdrsz, stkhdr.datasz);
-  return true;
-}
-
-bool StackOpen::loadMGXS_1_3(QIODevice& file, Stack* stack, Store* store)
-{
-  bool isLabel;
-  float sxum, syum, szum;
-  file.read((char*)&isLabel, sizeof(bool));
-  file.read((char*)&sxum, sizeof(float));
-  file.read((char*)&syum, sizeof(float));
-  file.read((char*)&szum, sizeof(float));
-  bool result = loadMGXS_1_0(file, stack, store);
-  if(result) {
-    store->setLabels(isLabel);
-    stack->setOrigin(Point3f(sxum, syum, szum));
-    SETSTATUS("Set stack step to " << stack->origin());
-  }
-  return result;
-}
-
-bool StackOpen::loadMGXS_1_2(QIODevice& file, Stack* stack, Store* store)
-{
-  bool result = loadMGXS_1_3(file, stack, store);
-  if(result and store->labels()) {
-    StackSwapBytes swap(*this);
-    return swap(store, store);
-  }
-  return result;
-}
-
-bool StackOpen::loadMGXS_1_1(QIODevice& file, Stack* stack, Store* store)
-{
-  bool isLabel;
-  file.read((char*)&isLabel, sizeof(bool));
-  bool result = loadMGXS_1_0(file, stack, store);
-  if(result) {
-    store->setLabels(isLabel);
-    if(store->labels()) {
+  
+  bool StackOpen::loadMGXS_1_2(QIODevice& file, Stack* stack, Store* store)
+  {
+    bool result = loadMGXS_1_3(file, stack, store);
+    if(result and store->labels()) {
       StackSwapBytes swap(*this);
       return swap(store, store);
     }
+    return result;
   }
-  return result;
-}
-
-bool StackOpen::loadMGXS_1_0(QIODevice& file, Stack* stack, Store* store)
-{
-  HVecUS& data = store->data();
-  quint32 xsz;
-  quint32 ysz;
-  quint32 zsz;
-  float xum;
-  float yum;
-  float zum;
-  quint64 datasz;
-  quint8 cl;
-  file.read((char*)&xsz, sizeof(quint32));
-  file.read((char*)&ysz, sizeof(quint32));
-  file.read((char*)&zsz, sizeof(quint32));
-  Information::out << "Size: " << xsz << " " << ysz << " " << zsz << endl;
-  file.read((char*)&xum, sizeof(float));
-  file.read((char*)&yum, sizeof(float));
-  file.read((char*)&zum, sizeof(float));
-  file.read((char*)&datasz, sizeof(quint64));
-  file.read((char*)&cl, sizeof(quint8));
-  quint64 expected_size = 2ul * (quint64(xsz) * quint64(ysz) * quint64(zsz));
-  if(datasz != expected_size)
-    throw QString("Datasize does not match dimensions in MGXS file (size = %1, expected from dimension = %2)")
-          .arg(datasz)
-          .arg(expected_size);
-  Point3u size(xsz, ysz, zsz);
-  Point3f step(xum, yum, zum);
-  stack->setSize(size);
-  stack->setStep(step);
-  if(cl > 0) {
-    Progress progress(QString("Loading stack %1").arg(stack->id()), expected_size);
-    quint64 cur_size = 0;
-    char* d = (char*)data.data();
-    while(cur_size < 2 * data.size()) {
+  
+  bool StackOpen::loadMGXS_1_1(QIODevice& file, Stack* stack, Store* store)
+  {
+    bool isLabel;
+    file.read((char*)&isLabel, sizeof(bool));
+    bool result = loadMGXS_1_0(file, stack, store);
+    if(result) {
+      store->setLabels(isLabel);
+      if(store->labels()) {
+        StackSwapBytes swap(*this);
+        return swap(store, store);
+      }
+    }
+    return result;
+  }
+  
+  bool StackOpen::loadMGXS_1_0(QIODevice& file, Stack* stack, Store* store)
+  {
+    HVecUS& data = store->data();
+    quint32 xsz;
+    quint32 ysz;
+    quint32 zsz;
+    float xum;
+    float yum;
+    float zum;
+    quint64 datasz;
+    quint8 cl;
+    file.read((char*)&xsz, sizeof(quint32));
+    file.read((char*)&ysz, sizeof(quint32));
+    file.read((char*)&zsz, sizeof(quint32));
+    Information::out << "Size: " << xsz << " " << ysz << " " << zsz << endl;
+    file.read((char*)&xum, sizeof(float));
+    file.read((char*)&yum, sizeof(float));
+    file.read((char*)&zum, sizeof(float));
+    file.read((char*)&datasz, sizeof(quint64));
+    file.read((char*)&cl, sizeof(quint8));
+    quint64 expected_size = 2ul * (quint64(xsz) * quint64(ysz) * quint64(zsz));
+    if(datasz != expected_size)
+      throw QString("Datasize does not match dimensions in MGXS file (size = %1, expected from dimension = %2)")
+            .arg(datasz)
+            .arg(expected_size);
+    Point3u size(xsz, ysz, zsz);
+    Point3f step(xum, yum, zum);
+    stack->setSize(size);
+    stack->setStep(step);
+    if(cl > 0) {
+      Progress progress(QString("Loading stack %1").arg(stack->id()), expected_size);
+      quint64 cur_size = 0;
+      char* d = (char*)data.data();
+      while(cur_size < 2 * data.size()) {
+        if(!progress.advance(cur_size))
+          userCancel();
+        // Information::out << "advance to " << cur_size << endl;
+        quint32 sz;
+        qint64 qty = file.read((char*)&sz, sizeof(quint32));
+        if(qty != sizeof(quint32)) {
+          throw QString("Could not read enough data from MGXS file (read = %1, expected = %2)").arg(qty).arg(
+                  sizeof(quint32));
+        }
+        QByteArray stkdata = file.read(sz);
+        if(quint32(stkdata.size()) != sz) {
+          throw QString("Could not read enough data from MGXS file (read = %1, expected = %2)")
+                .arg(stkdata.size())
+                .arg(sz);
+        }
+        stkdata = qUncompress(stkdata);
+        if(stkdata.isEmpty()) {
+          throw QString("Compressed data in MGXS file is corrupted");
+        }
+        memcpy(d, stkdata.data(), stkdata.size());
+        d += stkdata.size();
+        cur_size += stkdata.size();
+      }
       if(!progress.advance(cur_size))
         userCancel();
-      // Information::out << "advance to " << cur_size << endl;
-      quint32 sz;
-      qint64 qty = file.read((char*)&sz, sizeof(quint32));
-      if(qty != sizeof(quint32)) {
-        throw QString("Could not read enough data from MGXS file (read = %1, expected = %2)").arg(qty).arg(
-                sizeof(quint32));
+    } else {
+      // Ok, if greater than 64MB, read in bits
+      quint64 nb_slices = expected_size >> 26;
+      quint64 slice_size = 1ul << 26;
+      Progress progress(QString("Loading stack %1").arg(stack->id()), nb_slices);
+      Information::out << "Nb of slices = " << nb_slices << endl;
+      for(quint64 i = 0; i < nb_slices; ++i) {
+        qint64 qty = file.read((char*)data.data() + i * slice_size, slice_size);
+        if(qty != (int)slice_size) {
+          throw QString("Could not read enough data from MGXS file (read = %1, expected = %2)").arg(qty).arg(
+                  slice_size);
+        }
+        if(!progress.advance(i))
+          userCancel();
+        // Information::out << "advance to " << i << endl;
       }
-      QByteArray stkdata = file.read(sz);
-      if(quint32(stkdata.size()) != sz) {
-        throw QString("Could not read enough data from MGXS file (read = %1, expected = %2)")
-              .arg(stkdata.size())
-              .arg(sz);
-      }
-      stkdata = qUncompress(stkdata);
-      if(stkdata.isEmpty()) {
-        throw QString("Compressed data in MGXS file is corrupted");
-      }
-      memcpy(d, stkdata.data(), stkdata.size());
-      d += stkdata.size();
-      cur_size += stkdata.size();
-    }
-    if(!progress.advance(cur_size))
-      userCancel();
-  } else {
-    // Ok, if greater than 64MB, read in bits
-    quint64 nb_slices = expected_size >> 26;
-    quint64 slice_size = 1ul << 26;
-    Progress progress(QString("Loading stack %1").arg(stack->id()), nb_slices);
-    Information::out << "Nb of slices = " << nb_slices << endl;
-    for(quint64 i = 0; i < nb_slices; ++i) {
-      qint64 qty = file.read((char*)data.data() + i * slice_size, slice_size);
-      if(qty != (int)slice_size) {
+      quint64 left_size = expected_size - (nb_slices << 26);
+      qint64 qty = file.read((char*)data.data() + (nb_slices << 26), left_size);
+      if(qty != (int)left_size) {
         throw QString("Could not read enough data from MGXS file (read = %1, expected = %2)").arg(qty).arg(
-                slice_size);
+                left_size);
       }
-      if(!progress.advance(i))
+      if(!progress.advance(nb_slices))
         userCancel();
-      // Information::out << "advance to " << i << endl;
     }
-    quint64 left_size = expected_size - (nb_slices << 26);
-    qint64 qty = file.read((char*)data.data() + (nb_slices << 26), left_size);
-    if(qty != (int)left_size) {
-      throw QString("Could not read enough data from MGXS file (read = %1, expected = %2)").arg(qty).arg(
-              left_size);
-    }
-    if(!progress.advance(nb_slices))
-      userCancel();
+    return true;
   }
-  return true;
-}
-
-QList<int> extractVersion(QIODevice& file)
-{
-  QByteArray version;
-  version.reserve(10);
-  do {
-    char c;
-    qint64 qty = file.read(&c, 1);
-    if(qty == 0) {
-      throw QString("extractVersion:Could not read enough data from file (read = %1, expected = %2)")
-            .arg(version.size())
-            .arg(version.size() + 1);
+  
+  QList<int> extractVersion(QIODevice& file)
+  {
+    QByteArray version;
+    version.reserve(10);
+    do {
+      char c;
+      qint64 qty = file.read(&c, 1);
+      if(qty == 0) {
+        throw QString("extractVersion:Could not read enough data from file (read = %1, expected = %2)")
+              .arg(version.size())
+              .arg(version.size() + 1);
+      }
+      version.push_back(c);
+    } while(version[version.size() - 1] != ' ');
+    version.chop(1);
+    QList<QByteArray> values = version.split('.');
+    QList<int> result;
+    foreach(const QByteArray &a, values) {
+      bool ok;
+      result << a.toInt(&ok);
+      if(!ok)
+        throw QString("extractVersion:Version number must contain only integers (read = '%1')").arg(QString(a));
     }
-    version.push_back(c);
-  } while(version[version.size() - 1] != ' ');
-  version.chop(1);
-  QList<QByteArray> values = version.split('.');
-  QList<int> result;
-  foreach(const QByteArray &a, values) {
-    bool ok;
-    result << a.toInt(&ok);
-    if(!ok)
-      throw QString("extractVersion:Version number must contain only integers (read = '%1')").arg(QString(a));
+    return result;
   }
-  return result;
-}
-
-bool StackOpen::operator()(Stack* stack, Store* store, QString filename)
-{
-  if(filename.isEmpty())
-    throw QString("StackOpen::Error:Error, trying to load a stack from an empty filename.");
-
-  actingFile(filename);
-  store->setFile(filename);
-  QFile file(filename);
-  if(!file.open(QIODevice::ReadOnly))
-    throw QString("StackOpen::Error:Cannot open input file - '%1'").arg(filename);
-
-  Progress progress(QString("Loading %1 Stack %2 from File '%3'")
-                    .arg((store == stack->main()) ? "main" : "work")
-                    .arg(stack->userId())
-                    .arg(filename),
-                    0, false);
-  // Progress progress(QString("Reading stack file %1").arg(filename), 0, false);
-  if(filename.endsWith(".mgxs", Qt::CaseInsensitive)) {
-    static const char version[] = "MGXS ";
-    static const int size_version = sizeof(version) - 1;
-    char header_version[size_version];
-    file.read(header_version, size_version);
-    if(memcmp(header_version, version, size_version) == 0) {
-      QList<int> version = extractVersion(file);
-      if(version.size() != 2) {
-        QStringList str;
-        foreach(int i, version)
-        str << QString::number(i);
-        throw QString("StackOpen::Error:Invalid file version format (%1), expected: MAJOR.MINOR")
-              .arg(str.join("."));
-      }
-      bool success = false;
-      switch(version[0]) {
-      case 1:
-        switch(version[1]) {
-        case 0:
-          success = loadMGXS_1_0(file, stack, store);
-          stack->center();
-          break;
+  
+  bool StackOpen::operator()(Stack* stack, Store* store, QString filename)
+  {
+    if(filename.isEmpty())
+      throw QString("StackOpen::Error:Error, trying to load a stack from an empty filename.");
+  
+    actingFile(filename);
+    store->setFile(filename);
+    QFile file(filename);
+    if(!file.open(QIODevice::ReadOnly))
+      throw QString("StackOpen::Error:Cannot open input file - '%1'").arg(filename);
+  
+    Progress progress(QString("Loading %1 Stack %2 from File '%3'")
+                      .arg((store == stack->main()) ? "main" : "work")
+                      .arg(stack->userId())
+                      .arg(filename),
+                      0, false);
+    // Progress progress(QString("Reading stack file %1").arg(filename), 0, false);
+    if(filename.endsWith(".mgxs", Qt::CaseInsensitive)) {
+      static const char version[] = "MGXS ";
+      static const int size_version = sizeof(version) - 1;
+      char header_version[size_version];
+      file.read(header_version, size_version);
+      if(memcmp(header_version, version, size_version) == 0) {
+        QList<int> version = extractVersion(file);
+        if(version.size() != 2) {
+          QStringList str;
+          foreach(int i, version)
+          str << QString::number(i);
+          throw QString("StackOpen::Error:Invalid file version format (%1), expected: MAJOR.MINOR")
+                .arg(str.join("."));
+        }
+        bool success = false;
+        switch(version[0]) {
         case 1:
-          success = loadMGXS_1_1(file, stack, store);
-          stack->center();
+          switch(version[1]) {
+          case 0:
+            success = loadMGXS_1_0(file, stack, store);
+            stack->center();
+            break;
+          case 1:
+            success = loadMGXS_1_1(file, stack, store);
+            stack->center();
+            break;
+          case 2:
+            success = loadMGXS_1_2(file, stack, store);
+            break;
+          case 3:
+            success = loadMGXS_1_3(file, stack, store);
+            break;
+          default:
+            throw QString(
+                    "StackOpen::Error:Unknown file version %1.%2, this software recognizes up to version 1.1")
+                  .arg(version[0])
+                  .arg(version[1]);
+          }
           break;
-        case 2:
-          success = loadMGXS_1_2(file, stack, store);
-          break;
-        case 3:
-          success = loadMGXS_1_3(file, stack, store);
-          break;
         default:
-          throw QString(
-                  "StackOpen::Error:Unknown file version %1.%2, this software recognizes up to version 1.1")
+          throw QString("StackOpen::Error:Unknown file version %1.%2, this software recognizes up to version 1.0")
                 .arg(version[0])
                 .arg(version[1]);
         }
-        break;
-      default:
-        throw QString("StackOpen::Error:Unknown file version %1.%2, this software recognizes up to version 1.0")
-              .arg(version[0])
-              .arg(version[1]);
+        if(!success)
+          return false;
+      } else {
+        file.seek(0);
+        if(!loadMGXS_0(file, stack, store))
+          return false;
+        stack->center();
       }
-      if(!success)
+    } else if(filename.endsWith(".inr", Qt::CaseInsensitive)) {
+      HVecUS& data = store->data();
+      QByteArray stkdata = file.readAll();
+      file.close();
+      CImgUS image;
+      Point3f voxelsz;
+      image.load_inr(filename.toLocal8Bit(), voxelsz.data());
+      Point3u size(image.width(), image.height(), image.depth());
+      Point3f step(voxelsz.x(), voxelsz.y(), voxelsz.z());
+      stack->setSize(size);
+      stack->setStep(step);
+      memcpy(data.data(), image.data(), stack->storeSize() * 2);
+      stack->center();
+    } else if(filename.endsWith(".tif", Qt::CaseInsensitive) or filename.endsWith(".tiff", Qt::CaseInsensitive)) {
+      Image3D data(store->data(), stack->size(), stack->step());
+      if(!loadTIFFImage(filename, data, true, &progress)) {
+        stack->setSize(Point3u(0, 0, 0));
+        stack->main()->changed();
+        stack->work()->changed();
+        setErrorMessage(
+          QString("Error, cannot load TIFF file %1. Check standard output for exact error.").arg(filename));
         return false;
-    } else {
-      file.seek(0);
-      if(!loadMGXS_0(file, stack, store))
-        return false;
+      }
+      stack->setSize(data.size);
+      stack->setStep(data.step);
       stack->center();
+    } else
+      throw QString("StackOpen::Error:Invalid file type - %1").arg(filename);
+  
+    if(store->labels()) {
+      ushort max_label = 0;
+      const HVecUS& data = store->data();
+      forall(const ushort& u, data) {
+        ushort label = u;
+        if(label > max_label)
+          max_label = label;
+      }
+      stack->setLabel(max_label);
     }
-  } else if(filename.endsWith(".inr", Qt::CaseInsensitive)) {
-    HVecUS& data = store->data();
-    QByteArray stkdata = file.readAll();
-    file.close();
-    CImgUS image;
-    Point3f voxelsz;
-    image.load_inr(filename.toLocal8Bit(), voxelsz.data());
-    Point3u size(image.width(), image.height(), image.depth());
-    Point3f step(voxelsz.x(), voxelsz.y(), voxelsz.z());
-    stack->setSize(size);
-    stack->setStep(step);
-    memcpy(data.data(), image.data(), stack->storeSize() * 2);
-    stack->center();
-  } else if(filename.endsWith(".tif", Qt::CaseInsensitive) or filename.endsWith(".tiff", Qt::CaseInsensitive)) {
-    Image3D data(store->data(), stack->size(), stack->step());
-    if(!loadTIFFImage(filename, data, true, &progress)) {
-      stack->setSize(Point3u(0, 0, 0));
-      stack->main()->changed();
-      stack->work()->changed();
-      setErrorMessage(
-        QString("Error, cannot load TIFF file %1. Check standard output for exact error.").arg(filename));
+  
+    store->setFile(filename);
+    store->changed();
+    SETSTATUS("Loaded stack " << stack->userId() << ", file:" << store->file() << " size: " << stack->size());
+    return true;
+  }
+  
+  bool MeshImport::initialize(QStringList& parms, QWidget* parent)
+  {
+    int meshId = parms[5].toInt();
+    if(!checkState().mesh(MESH_ANY, int(meshId)))
       return false;
+  
+    QDialog dlg(parent);
+    Ui_ImportMeshDialog ui;
+    ui.setupUi(&dlg);
+  
+    this->ui = &ui;
+    this->dlg = &dlg;
+  
+    QObject::connect(ui.SelectMeshFile, SIGNAL(clicked()), this, SLOT(selectMeshFile()));
+    QObject::connect(ui.MeshType, SIGNAL(currentIndexChanged(const QString &)), this,
+                     SLOT(selectMeshType(const QString &)));
+  
+    Mesh* mesh = this->mesh(meshId);
+    QString filename = mesh->file();
+    if(filename.isEmpty())
+      filename = parms[0];
+  
+    setMeshFile(properFile(filename, parms[1]), parms[1]);
+    ui.ScaleUm->setChecked(stringToBool(parms[2]));
+    ui.Transform->setChecked(stringToBool(parms[3]));
+    ui.Add->setChecked(stringToBool(parms[4]));
+  
+    bool res = false;
+    if(dlg.exec() == QDialog::Accepted) {
+      parms[0] = ui.MeshFile->text();
+      parms[1] = ui.MeshType->currentText();
+      parms[2] = (ui.ScaleUm->isChecked() ? "yes" : "no");
+      parms[3] = (ui.Transform->isChecked() ? "yes" : "no");
+      parms[4] = (ui.Add->isChecked() ? "yes" : "no");
+      res = true;
     }
-    stack->setSize(data.size);
-    stack->setStep(data.step);
-    stack->center();
-  } else
-    throw QString("StackOpen::Error:Invalid file type - %1").arg(filename);
-
-  if(store->labels()) {
-    ushort max_label = 0;
-    const HVecUS& data = store->data();
-    forall(const ushort& u, data) {
-      ushort label = u;
-      if(label > max_label)
-        max_label = label;
+    this->ui = 0;
+    this->dlg = 0;
+    return res;
+  }
+  
+  bool MeshImport::operator()(const QStringList& parms)
+  {
+    int meshId = parms[5].toInt();
+    if(!checkState().mesh(MESH_ANY, meshId))
+      return false;
+    Mesh* mesh = this->mesh(meshId);
+    QString type = parms[1];
+    bool scale = stringToBool(parms[2]);
+    bool transform = stringToBool(parms[3]);
+    bool add = stringToBool(parms[4]);
+    bool res = (*this)(mesh, parms[0], type, scale, transform, add);
+    if(res) {
+      // Show mesh if nothing visible
+      if(!(mesh->isMeshVisible() or mesh->isSurfaceVisible())) {
+        mesh->showSurface();
+        mesh->showMesh();
+      }
+      if(mesh->hasImgTex())
+        mesh->showImage();
+      else
+        mesh->showSignal();
+      mesh->setNormals();
     }
-    stack->setLabel(max_label);
+    return res;
   }
-
-  store->setFile(filename);
-  store->changed();
-  SETSTATUS("Loaded stack " << stack->userId() << ", file:" << store->file() << " size: " << stack->size());
-  return true;
-}
-
-// REGISTER_STACK_PROCESS(StackOpen);
-
-bool MeshImport::initialize(QStringList& parms, QWidget* parent)
-{
-  int meshId = parms[5].toInt();
-  if(!checkState().mesh(MESH_ANY, int(meshId)))
-    return false;
-
-  QDialog dlg(parent);
-  Ui_ImportMeshDialog ui;
-  ui.setupUi(&dlg);
-
-  this->ui = &ui;
-  this->dlg = &dlg;
-
-  QObject::connect(ui.SelectMeshFile, SIGNAL(clicked()), this, SLOT(selectMeshFile()));
-  QObject::connect(ui.MeshType, SIGNAL(currentIndexChanged(const QString &)), this,
-                   SLOT(selectMeshType(const QString &)));
-
-  Mesh* mesh = this->mesh(meshId);
-  QString filename = mesh->file();
-  if(filename.isEmpty())
-    filename = parms[0];
-
-  setMeshFile(properFile(filename, parms[1]), parms[1]);
-  ui.ScaleUm->setChecked(stringToBool(parms[2]));
-  ui.Transform->setChecked(stringToBool(parms[3]));
-  ui.Add->setChecked(stringToBool(parms[4]));
-
-  bool res = false;
-  if(dlg.exec() == QDialog::Accepted) {
-    parms[0] = ui.MeshFile->text();
-    parms[1] = ui.MeshType->currentText();
-    parms[2] = (ui.ScaleUm->isChecked() ? "yes" : "no");
-    parms[3] = (ui.Transform->isChecked() ? "yes" : "no");
-    parms[4] = (ui.Add->isChecked() ? "yes" : "no");
-    res = true;
-  }
-  this->ui = 0;
-  this->dlg = 0;
-  return res;
-}
-
-bool MeshImport::operator()(const QStringList& parms)
-{
-  int meshId = parms[5].toInt();
-  if(!checkState().mesh(MESH_ANY, meshId))
-    return false;
-  Mesh* mesh = this->mesh(meshId);
-  QString type = parms[1];
-  bool scale = stringToBool(parms[2]);
-  bool transform = stringToBool(parms[3]);
-  bool add = stringToBool(parms[4]);
-  bool res = (*this)(mesh, parms[0], type, scale, transform, add);
-  if(res) {
-    // Show mesh if nothing visible
-    if(!(mesh->isMeshVisible() or mesh->isSurfaceVisible())) {
-      mesh->showSurface();
-      mesh->showMesh();
+  
+  bool MeshImport::operator()(Mesh* mesh, QString filename, QString type, bool scale, bool transform, bool add)
+  {
+    Progress progress(QString("Loading Mesh %1 from File '%2'").arg(mesh->userId()).arg(filename), 0, false);
+    // Progress progress(QString("Loading Mesh File - %1").arg(filename), 0, false);
+    actingFile(filename);
+    QFileInfo fi(filename);
+    QString suf = fi.suffix();
+    bool success = false;
+    if(type.isEmpty()) {
+      QString low_fn = filename.toLower();
+      if(low_fn.endsWith(".ply", Qt::CaseInsensitive))
+        type = "PLY Mesh";
+      else if(low_fn.endsWith(".vtu", Qt::CaseInsensitive))
+        type = "VTK Mesh";
+      else if(low_fn.endsWith(".txt", Qt::CaseInsensitive))
+        type = "Text";
+      else if(low_fn.endsWith(".jpg", Qt::CaseInsensitive) or low_fn.endsWith(".jpeg", Qt::CaseInsensitive))
+        type = "Keyence";
+      else if(low_fn.endsWith(".mesh", Qt::CaseInsensitive))
+        type = "MeshEdit";
+      else if(low_fn.endsWith(".obj", Qt::CaseInsensitive))
+        type = "OBJ";
+      else {
+        setErrorMessage(QString("Cannot find the type of the file '%1'").arg(filename));
+        return false;
+      }
     }
-    if(mesh->hasImgTex())
-      mesh->showImage();
-    else
-      mesh->showSignal();
-    mesh->setNormals();
-  }
-  return res;
-}
-
-bool MeshImport::operator()(Mesh* mesh, QString filename, QString type, bool scale, bool transform, bool add)
-{
-  Progress progress(QString("Loading Mesh %1 from File '%2'").arg(mesh->userId()).arg(filename), 0, false);
-  // Progress progress(QString("Loading Mesh File - %1").arg(filename), 0, false);
-  actingFile(filename);
-  QFileInfo fi(filename);
-  QString suf = fi.suffix();
-  bool success = false;
-  if(type.isEmpty()) {
-    QString low_fn = filename.toLower();
-    if(low_fn.endsWith(".ply", Qt::CaseInsensitive))
-      type = "PLY Mesh";
-    else if(low_fn.endsWith(".vtu", Qt::CaseInsensitive))
-      type = "VTK Mesh";
-    else if(low_fn.endsWith(".txt", Qt::CaseInsensitive))
-      type = "Text";
-    else if(low_fn.endsWith(".jpg", Qt::CaseInsensitive) or low_fn.endsWith(".jpeg", Qt::CaseInsensitive))
-      type = "Keyence";
-    else if(low_fn.endsWith(".mesh", Qt::CaseInsensitive))
-      type = "MeshEdit";
-    else if(low_fn.endsWith(".obj", Qt::CaseInsensitive))
-      type = "OBJ";
+    if(type == "PLY")
+      success = loadMeshPLY(mesh, filename, scale, transform, add);
+    else if(type == "VTK Mesh")
+      success = loadMeshVTK(mesh, filename, scale, transform, add);
+    else if(type == "Text")
+      success = loadText(mesh, filename, scale, transform, add);
+    else if(type == "Cells")
+      success = loadCells(mesh, filename, scale, transform, add);
+    else if(type == "Keyence")
+      success = loadKeyence(mesh, filename, scale, transform, add);
+    else if(type == "MeshEdit")
+      success = loadMeshEdit(mesh, filename, scale, transform, add);
+    else if(type == "OBJ")
+      success = loadMeshOBJ(mesh, filename, scale, transform, add);
     else {
-      setErrorMessage(QString("Cannot find the type of the file '%1'").arg(filename));
+      setErrorMessage(QString("Unknown file type '%1'").arg(type));
       return false;
     }
+    if(success) {
+      mesh->setFile(properFile(filename, "Mesh"));
+      if(mesh->stack()->empty())
+        mesh->setScaled(scale);
+      else
+        mesh->setScaled(true);
+      mesh->setTransformed(transform);
+      mesh->updateAll();
+    }
+    return success;
   }
-  if(type == "PLY")
-    success = loadMeshPLY(mesh, filename, scale, transform, add);
-  else if(type == "VTK Mesh")
-    success = loadMeshVTK(mesh, filename, scale, transform, add);
-  else if(type == "Text")
-    success = loadText(mesh, filename, scale, transform, add);
-  else if(type == "Cells")
-    success = loadCells(mesh, filename, scale, transform, add);
-  else if(type == "Keyence")
-    success = loadKeyence(mesh, filename, scale, transform, add);
-  else if(type == "MeshEdit")
-    success = loadMeshEdit(mesh, filename, scale, transform, add);
-  else if(type == "OBJ")
-    success = loadMeshOBJ(mesh, filename, scale, transform, add);
-  else {
-    setErrorMessage(QString("Unknown file type '%1'").arg(type));
-    return false;
+  
+  static Point3f realPos(Point3f pos, bool scale, bool transform, const Mesh* mesh)
+  {
+    if(!scale)
+      pos = mesh->stack()->abstractToWorld(pos);
+    if(transform)
+      pos = Point3f(mesh->stack()->frame().coordinatesOf(Vec(pos)));
+    return pos;
   }
-  if(success) {
-    mesh->setFile(properFile(filename, "Mesh"));
-    if(mesh->stack()->empty())
-      mesh->setScaled(scale);
-    else
-      mesh->setScaled(true);
-    mesh->setTransformed(transform);
-    mesh->updateAll();
-  }
-  return success;
-}
-
-static Point3f realPos(Point3f pos, bool scale, bool transform, const Mesh* mesh)
-{
-  if(!scale)
-    pos = mesh->stack()->abstractToWorld(pos);
-  if(transform)
-    pos = Point3f(mesh->stack()->frame().coordinatesOf(Vec(pos)));
-  return pos;
-}
-
-bool MeshImport::loadText(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add)
-{
-  QFile file(filename);
-  if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
-    setErrorMessage(QString("loadText::Error:Cannot open input file: %1").arg(filename));
-    return false;
-  }
-
-  vvgraph& S = mesh->graph();
-
-  if(!S.empty() and !add)
-    mesh->reset();
-
-  vertex_map vmap;
-
-  QTextStream in(&file);
-  int vCnt;
-  in >> vCnt;
-  Progress progress(QString("Loading Mesh %1 from File '%2'").arg(mesh->userId()).arg(mesh->file()), vCnt * 2);
-  // Progress progress(QString("Loading Mesh-%1 - %2").arg(mesh->userId()).arg(mesh->file()), vCnt*2);
-  int interval = vCnt / 100;
-  if(interval < 1)
-    interval = 1;
-  S.reserve(vCnt);
-  for(int i = 0; i < vCnt; i++) {
-    if(in.atEnd())
-      throw QString("Premature end of file reading vertices");
-    vertex v;
-    S.insert(v);
-    in >> v->saveId >> v->pos >> v->label;
-    v->pos = realPos(v->pos, scale, transform, mesh);
-    vmap[v->saveId] = v;
-    if(v->label > mesh->viewLabel())
-      mesh->setLabel(v->label);
-    if((i % interval == 0)and !progress.advance(i))
+  
+  bool MeshImport::loadText(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add)
+  {
+    QFile file(filename);
+    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+      setErrorMessage(QString("loadText::Error:Cannot open input file: %1").arg(filename));
+      return false;
+    }
+  
+    vvgraph& S = mesh->graph();
+  
+    if(!S.empty() and !add)
+      mesh->reset();
+  
+    vertex_map vmap;
+  
+    QTextStream in(&file);
+    int vCnt;
+    in >> vCnt;
+    Progress progress(QString("Loading Mesh %1 from File '%2'").arg(mesh->userId()).arg(mesh->file()), vCnt * 2);
+    // Progress progress(QString("Loading Mesh-%1 - %2").arg(mesh->userId()).arg(mesh->file()), vCnt*2);
+    int interval = vCnt / 100;
+    if(interval < 1)
+      interval = 1;
+    S.reserve(vCnt);
+    for(int i = 0; i < vCnt; i++) {
+      if(in.atEnd())
+        throw QString("Premature end of file reading vertices");
+      vertex v;
+      S.insert(v);
+      in >> v->saveId >> v->pos >> v->label;
+      v->pos = realPos(v->pos, scale, transform, mesh);
+      vmap[v->saveId] = v;
+      if(v->label > mesh->viewLabel())
+        mesh->setLabel(v->label);
+      if((i % interval == 0)and !progress.advance(i))
+        userCancel();
+    }
+    for(int i = 0; i < vCnt; i++) {
+      if(in.atEnd())
+        throw QString("Premature end of file reading neighborhoods");
+      uint vId, nCnt;
+      in >> vId >> nCnt;
+      vertex_map::const_iterator vit = vmap.find(vId);
+      if(vit == vmap.end())
+        throw QString("Invalid vertex id: %1").arg(vId);
+      vertex v = vit->second;
+      vertex pn(0);
+      for(uint j = 0; j < nCnt; j++) {
+        uint nId;
+        in >> nId;
+        vertex_map::const_iterator nit = vmap.find(nId);
+        if(nit == vmap.end())
+          throw QString("Invalid vertex id: %1").arg(nId);
+        vertex n = nit->second;
+        if(S.valence(v) == 0)
+          S.insertEdge(v, n);
+        else
+          S.spliceAfter(v, pn, n);
+        pn = n;
+      }
+      if((i % interval == 0)and !progress.advance(vCnt + i))
+        userCancel();
+    }
+    if(!progress.advance(2 * vCnt))
       userCancel();
+    file.close();
+    mesh->setCells(false);
+    mesh->clearImgTex();
+    mesh->setNormals();
+    SETSTATUS("Loaded mesh, file:" << mesh->file() << ", vertices:" << S.size());
+    return true;
   }
-  for(int i = 0; i < vCnt; i++) {
-    if(in.atEnd())
-      throw QString("Premature end of file reading neighborhoods");
-    uint vId, nCnt;
-    in >> vId >> nCnt;
-    vertex_map::const_iterator vit = vmap.find(vId);
-    if(vit == vmap.end())
-      throw QString("Invalid vertex id: %1").arg(vId);
-    vertex v = vit->second;
-    vertex pn(0);
-    for(uint j = 0; j < nCnt; j++) {
-      uint nId;
-      in >> nId;
-      vertex_map::const_iterator nit = vmap.find(nId);
-      if(nit == vmap.end())
-        throw QString("Invalid vertex id: %1").arg(nId);
-      vertex n = nit->second;
-      if(S.valence(v) == 0)
-        S.insertEdge(v, n);
-      else
-        S.spliceAfter(v, pn, n);
-      pn = n;
+  
+  using util::PlyFile;
+  
+  void showHeader(PlyFile& ply)
+  {
+    Information::out << "PLY file content";
+    Information::out << "format = " << PlyFile::formatNames[ply.format()] << endl;
+    Information::out << "version = " << ply.version() << endl;
+    Information::out << "content position = " << ply.contentPosition() << endl;
+    Information::out << endl;
+    Information::out << "# elements = " << ply.nbElements() << endl;
+    for(size_t i = 0; i < ply.nbElements(); ++i) {
+      const PlyFile::Element& element = *ply.element(i);
+      Information::out << "Element '" << element.name() << "' - " << element.size()
+                       << " # properties = " << element.nbProperties() << endl;
+      for(size_t j = 0; j < element.nbProperties(); ++j) {
+        const PlyFile::Property& prop = *element.property(j);
+        Information::out << "Property '" << prop.name() << "'";
+        if(prop.kind() == PlyFile::Property::LIST)
+          Information::out << " list " << PlyFile::typeNames[prop.sizeType()];
+        Information::out << " " << PlyFile::typeNames[prop.fileType()] << " / "
+                         << PlyFile::typeNames[prop.memType()] << endl;
+      }
     }
-    if((i % interval == 0)and !progress.advance(vCnt + i))
-      userCancel();
   }
-  if(!progress.advance(2 * vCnt))
-    userCancel();
-  file.close();
-  mesh->setCells(false);
-  mesh->clearImgTex();
-  mesh->setNormals();
-  SETSTATUS("Loaded mesh, file:" << mesh->file() << ", vertices:" << S.size());
-  return true;
-}
-
-using util::PlyFile;
-
-void showHeader(PlyFile& ply)
-{
-  Information::out << "PLY file content";
-  Information::out << "format = " << PlyFile::formatNames[ply.format()] << endl;
-  Information::out << "version = " << ply.version() << endl;
-  Information::out << "content position = " << ply.contentPosition() << endl;
-  Information::out << endl;
-  Information::out << "# elements = " << ply.nbElements() << endl;
-  for(size_t i = 0; i < ply.nbElements(); ++i) {
-    const PlyFile::Element& element = *ply.element(i);
-    Information::out << "Element '" << element.name() << "' - " << element.size()
-                     << " # properties = " << element.nbProperties() << endl;
-    for(size_t j = 0; j < element.nbProperties(); ++j) {
-      const PlyFile::Property& prop = *element.property(j);
-      Information::out << "Property '" << prop.name() << "'";
-      if(prop.kind() == PlyFile::Property::LIST)
-        Information::out << " list " << PlyFile::typeNames[prop.sizeType()];
-      Information::out << " " << PlyFile::typeNames[prop.fileType()] << " / "
-                       << PlyFile::typeNames[prop.memType()] << endl;
+  
+  bool MeshImport::loadMeshPLY(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add)
+  {
+    vvgraph& S = mesh->graph();
+  
+    Progress progress(QString("Loading PLY Mesh %1 from File '%2'").arg(mesh->userId()).arg(filename), 0);
+  
+    if(!S.empty() and !add)
+      mesh->reset();
+  
+    // Define the reader and read header
+    PlyFile ply;
+    if(!ply.parseHeader(filename))
+      throw(QString("Cannot parse PLY file header"));
+  
+    // Get vertices and properties
+    PlyFile::Element* vtx = ply.element("vertex");
+    if(!vtx)
+      throw(QString("No vertex element in PLY file"));
+  
+    PlyFile::Property* vx = vtx->property("x");   // vertex positions
+    PlyFile::Property* vy = vtx->property("y");
+    PlyFile::Property* vz = vtx->property("z");
+    if(!vx or !vy or !vz)
+      throw(QString("x, y or z missing from vertex element in PLY file"));
+  
+    vx->setMemType(PlyFile::FLOAT);
+    vy->setMemType(PlyFile::FLOAT);
+    vz->setMemType(PlyFile::FLOAT);
+  
+    PlyFile::Property* vlabel = vtx->property("label");   // vertex labels
+    if(vlabel)
+      vlabel->setMemType(PlyFile::INT);
+  
+    // Vertex color
+    bool hasRGB = false;
+    PlyFile::Property* vRed = vtx->property("red");
+    PlyFile::Property* vGreen = vtx->property("green");
+    PlyFile::Property* vBlue = vtx->property("blue");
+    if(vRed and vGreen and vBlue)
+      hasRGB = true;
+    if(hasRGB) {
+      vRed->setMemType(PlyFile::UCHAR);
+      vGreen->setMemType(PlyFile::UCHAR);
+      vBlue->setMemType(PlyFile::UCHAR);
     }
-  }
-}
-
-bool MeshImport::loadMeshPLY(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add)
-{
-  vvgraph& S = mesh->graph();
-
-  Progress progress(QString("Loading PLY Mesh %1 from File '%2'").arg(mesh->userId()).arg(filename), 0);
-
-  if(!S.empty() and !add)
-    mesh->reset();
-
-  // Define the reader and read header
-  PlyFile ply;
-  if(!ply.parseHeader(filename))
-    throw(QString("Cannot parse PLY file header"));
-
-  // Get vertices and properties
-  PlyFile::Element* vtx = ply.element("vertex");
-  if(!vtx)
-    throw(QString("No vertex element in PLY file"));
-
-  PlyFile::Property* vx = vtx->property("x");   // vertex positions
-  PlyFile::Property* vy = vtx->property("y");
-  PlyFile::Property* vz = vtx->property("z");
-  if(!vx or !vy or !vz)
-    throw(QString("x, y or z missing from vertex element in PLY file"));
-
-  vx->setMemType(PlyFile::FLOAT);
-  vy->setMemType(PlyFile::FLOAT);
-  vz->setMemType(PlyFile::FLOAT);
-
-  PlyFile::Property* vlabel = vtx->property("label");   // vertex labels
-  if(vlabel)
-    vlabel->setMemType(PlyFile::INT);
-
-  // Vertex color
-  bool hasRGB = false;
-  PlyFile::Property* vRed = vtx->property("red");
-  PlyFile::Property* vGreen = vtx->property("green");
-  PlyFile::Property* vBlue = vtx->property("blue");
-  if(vRed and vGreen and vBlue)
-    hasRGB = true;
-  if(hasRGB) {
-    vRed->setMemType(PlyFile::UCHAR);
-    vGreen->setMemType(PlyFile::UCHAR);
-    vBlue->setMemType(PlyFile::UCHAR);
-  }
-
-  // Get faces and properties
-  PlyFile::Element* faces = ply.element("face");   // faces
-  if(!faces)
-    throw(QString("No face element in PLY file"));
-
-  PlyFile::Property* vi = faces->property("vertex_index");
-  if(!vi) {
-    vi = faces->property("vertex_indices");
-    if(!vi)
-      throw(QString("Neither vertex_index or vertex_indices are present in face element"));
-  }
-  vi->setMemType(PlyFile::INT);
-
-  PlyFile::Property* flabel = faces->property("label");   // face labels
-  if(flabel)
-    flabel->setMemType(PlyFile::INT);
-
-  // Parse file
-  if(!ply.parseContent())
-    throw(QString("Unable to parse contents of PLY file"));
-
-  // Get vertex data
-  std::vector<vertex> vertices(vtx->size(), vertex(0));   // vertex positions
-  const std::vector<float>& px = *vx->value<float>();
-  const std::vector<float>& py = *vy->value<float>();
-  const std::vector<float>& pz = *vz->value<float>();
-
-  std::vector<int>* vlabelp = 0;   // vertex labels
-  if(vlabel)
-    vlabelp = vlabel->value<int>();
-
-  std::vector<uchar>* vRedp = 0;   // vertex colors
-  std::vector<uchar>* vGreenp = 0;
-  std::vector<uchar>* vBluep = 0;
-  if(hasRGB) {
-    Information::out << "Has RGB information" << endl;
-    vRedp = vRed->value<uchar>();
-    vGreenp = vGreen->value<uchar>();
-    vBluep = vBlue->value<uchar>();
-  }
-
-  // Get face data
-  std::vector<Point3i> triangles;   // faces
-  const std::vector<std::vector<int32_t> >& vertex_index = *vi->list<int32_t>();
-
-  std::vector<int>* flabelp = 0;   // face labels
-  if(flabel)
-    flabelp = flabel->value<int>();
-
-  // See if cellular mesh
-  bool cells = false;
-  for(size_t i = 0; i < faces->size(); ++i)
-    if(vertex_index[i].size() > 3)
-      cells = true;
-
-  // Process vertices
-  for(uint i = 0; i < vtx->size(); ++i) {
-    vertex v;
-    v->pos = Point3f(px[i], py[i], pz[i]);
-    v->pos = realPos(v->pos, scale, transform, mesh);
-    v->saveId = i;
-    v->type = 'j';
-    vertices[i] = v;
-    S.insert(v);
+  
+    // Get faces and properties
+    PlyFile::Element* faces = ply.element("face");   // faces
+    if(!faces)
+      throw(QString("No face element in PLY file"));
+  
+    PlyFile::Property* vi = faces->property("vertex_index");
+    if(!vi) {
+      vi = faces->property("vertex_indices");
+      if(!vi)
+        throw(QString("Neither vertex_index or vertex_indices are present in face element"));
+    }
+    vi->setMemType(PlyFile::INT);
+  
+    PlyFile::Property* flabel = faces->property("label");   // face labels
+    if(flabel)
+      flabel->setMemType(PlyFile::INT);
+  
+    // Parse file
+    if(!ply.parseContent())
+      throw(QString("Unable to parse contents of PLY file"));
+  
+    // Get vertex data
+    std::vector<vertex> vertices(vtx->size(), vertex(0));   // vertex positions
+    const std::vector<float>& px = *vx->value<float>();
+    const std::vector<float>& py = *vy->value<float>();
+    const std::vector<float>& pz = *vz->value<float>();
+  
+    std::vector<int>* vlabelp = 0;   // vertex labels
+    if(vlabel)
+      vlabelp = vlabel->value<int>();
+  
+    std::vector<uchar>* vRedp = 0;   // vertex colors
+    std::vector<uchar>* vGreenp = 0;
+    std::vector<uchar>* vBluep = 0;
+    if(hasRGB) {
+      Information::out << "Has RGB information" << endl;
+      vRedp = vRed->value<uchar>();
+      vGreenp = vGreen->value<uchar>();
+      vBluep = vBlue->value<uchar>();
+    }
+  
+    // Get face data
+    std::vector<Point3i> triangles;   // faces
+    const std::vector<std::vector<int32_t> >& vertex_index = *vi->list<int32_t>();
+  
+    std::vector<int>* flabelp = 0;   // face labels
+    if(flabel)
+      flabelp = flabel->value<int>();
+  
+    // See if cellular mesh
+    bool cells = false;
+    for(size_t i = 0; i < faces->size(); ++i)
+      if(vertex_index[i].size() > 3)
+        cells = true;
+  
+    // Process vertices
+    for(uint i = 0; i < vtx->size(); ++i) {
+      vertex v;
+      v->pos = Point3f(px[i], py[i], pz[i]);
+      v->pos = realPos(v->pos, scale, transform, mesh);
+      v->saveId = i;
+      v->type = 'j';
+      vertices[i] = v;
+      S.insert(v);
+      if(cells)
+        v->label = -1;
+      else if(vlabel)
+        v->label = (*vlabelp)[i];
+  
+      if(hasRGB)
+        v->signal = (0.21 * (*vRedp)[i] + 0.71 * (*vGreenp)[i] + 0.07 * (*vBluep)[i]) / 256.0;
+  
+      if(v->label > mesh->viewLabel())
+        mesh->setLabel(v->label);
+    }
+  
+    // Process faces
+    int nextLabel = mesh->viewLabel();
+    for(size_t i = 0; i < faces->size(); ++i) {
+      if(cells) {
+        // If a cellular mesh, make a triangle fan.
+        vertex c;
+  
+        // Find center vertex position
+        c->pos = Point3f(0, 0, 0);
+        forall(int j, vertex_index[i])
+          c->pos += vertices[j]->pos;
+        c->pos /= vertex_index[i].size();
+        c->type = 'c';
+  
+        // Put label on center vertex
+        if(flabel)
+          c->label = (*flabelp)[i];
+        else
+          c->label = ++nextLabel;
+  
+        int centerv = vertices.size();
+        for(size_t j = 0; j < vertex_index[i].size(); ++j) {
+          size_t prev = j - 1;
+          if(j == 0)
+            prev = vertex_index[i].size() - 1;
+  
+          triangles.push_back(Point3i(centerv, vertex_index[i][prev], vertex_index[i][j]));
+        }
+        vertices.push_back(c);
+  
+        if(c->label > mesh->viewLabel())
+          mesh->setLabel(c->label);
+      } else     // For simple triangle mesh, just add the triangle
+        triangles.push_back(Point3i(vertex_index[i][0], vertex_index[i][1], vertex_index[i][2]));
+    }
+  
+    // Create connectivity from triangle list
+    if(!meshFromTriangles(S, vertices, triangles))
+      throw(QString("Cannot add all the triangles"));
+  
+    mesh->setCells(cells);
+    mesh->clearImgTex();
+    mesh->setNormals();
     if(cells)
-      v->label = -1;
-    else if(vlabel)
-      v->label = (*vlabelp)[i];
-
-    if(hasRGB)
-      v->signal = (0.21 * (*vRedp)[i] + 0.71 * (*vGreenp)[i] + 0.07 * (*vBluep)[i]) / 256.0;
-
-    if(v->label > mesh->viewLabel())
-      mesh->setLabel(v->label);
+      SETSTATUS("Loaded cellular mesh, file:" << mesh->file() << ", vertices:" << S.size());
+    else
+      SETSTATUS("Loaded triangle mesh, file:" << mesh->file() << ", vertices:" << S.size());
+    return true;
   }
-
-  // Process faces
-  int nextLabel = mesh->viewLabel();
-  for(size_t i = 0; i < faces->size(); ++i) {
-    if(cells) {
-      // If a cellular mesh, make a triangle fan.
-      vertex c;
-
-      // Find center vertex position
-      c->pos = Point3f(0, 0, 0);
-      forall(int j, vertex_index[i])
-        c->pos += vertices[j]->pos;
-      c->pos /= vertex_index[i].size();
-      c->type = 'c';
-
-      // Put label on center vertex
-      if(flabel)
-        c->label = (*flabelp)[i];
-      else
-        c->label = ++nextLabel;
-
-      int centerv = vertices.size();
-      for(size_t j = 0; j < vertex_index[i].size(); ++j) {
-        size_t prev = j - 1;
-        if(j == 0)
-          prev = vertex_index[i].size() - 1;
-
-        triangles.push_back(Point3i(centerv, vertex_index[i][prev], vertex_index[i][j]));
-      }
-      vertices.push_back(c);
-
-      if(c->label > mesh->viewLabel())
-        mesh->setLabel(c->label);
-    } else     // For simple triangle mesh, just add the triangle
-      triangles.push_back(Point3i(vertex_index[i][0], vertex_index[i][1], vertex_index[i][2]));
-  }
-
-  // Create connectivity from triangle list
-  if(!meshFromTriangles(S, vertices, triangles))
-    throw(QString("Cannot add all the triangles"));
-
-  mesh->setCells(cells);
-  mesh->clearImgTex();
-  mesh->setNormals();
-  if(cells)
-    SETSTATUS("Loaded cellular mesh, file:" << mesh->file() << ", vertices:" << S.size());
-  else
-    SETSTATUS("Loaded triangle mesh, file:" << mesh->file() << ", vertices:" << S.size());
-  return true;
-}
-
-bool MeshImport::loadCells(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add)
-{
-  QFile file(filename);
-  if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
-    setErrorMessage(QString("loadMesh::Error:Cannot open input file: %1").arg(filename));
-    return false;
-  }
-
-  vvgraph& S = mesh->graph();
-
-  if(!S.empty() and !add)
-    mesh->reset();
-
-  vertex_map vmap;
-
-  QTextStream in(&file);
-  int vCnt;
-  in >> vCnt;
-  Progress progress(QString("Loading Cellular Mesh %1 from File '%2'").arg(mesh->userId()).arg(mesh->file()),
-                    vCnt * 2);
-  int interval = vCnt / 100;
-  if(interval < 1)
-    interval = 1;
-  S.reserve(vCnt);
-  for(int i = 0; i < vCnt; i++) {
-    if(in.atEnd())
-      throw QString("Premature end of file reading vertices");
-    vertex v;
-    S.insert(v);
-    char tchar;
-    in >> v->saveId >> v->pos >> v->label >> tchar >> v->type;
-    v->pos = realPos(v->pos, scale, transform, mesh);
-    vmap[v->saveId] = v;
-    if(v->label > mesh->viewLabel())
-      mesh->setLabel(v->label);
-    if((i % interval == 0)and !progress.advance(i))
-      userCancel();
-  }
-  for(int i = 0; i < vCnt; i++) {
-    if(in.atEnd())
-      throw QString("Premature end of file reading neighborhoods");
-    uint vId, nCnt;
-    in >> vId >> nCnt;
-    vertex_map::const_iterator vit = vmap.find(vId);
-    if(vit == vmap.end())
-      throw QString("Invalid vertex id: %1").arg(vId);
-    vertex v = vit->second;
-    vertex pn(0);
-    for(uint j = 0; j < nCnt; j++) {
-      uint nId;
-      in >> nId;
-      vertex_map::const_iterator nit = vmap.find(nId);
-      if(nit == vmap.end())
-        throw QString("Invalid vertex id: %1").arg(nId);
-      vertex n = nit->second;
-      if(S.valence(v) == 0)
-        S.insertEdge(v, n);
-      else
-        S.spliceAfter(v, pn, n);
-      pn = n;
+  
+  bool MeshImport::loadCells(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add)
+  {
+    QFile file(filename);
+    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+      setErrorMessage(QString("loadMesh::Error:Cannot open input file: %1").arg(filename));
+      return false;
     }
-    if((i % interval == 0)and !progress.advance(vCnt + i))
-      userCancel();
-  }
-  if(!progress.advance(2 * vCnt))
-    userCancel();
-  file.close();
-  mesh->setCells(true);
-  mesh->clearImgTex();
-  mesh->setNormals();
-  SETSTATUS("Loaded cell mesh, file:" << mesh->file() << ", vertices:" << S.size());
-  return true;
-}
-
-bool MeshImport::loadKeyence(Mesh* mesh, const QString& filename, bool scale, bool transform, bool /*add*/)
-{
-  QFile file(filename);
-  if(!file.open(QIODevice::ReadOnly)) {
-    setErrorMessage(QString("loadMesh::Error:Cannot open input file: %1").arg(filename));
-    return false;
-  }
-
-  vvgraph& S = mesh->graph();
-
-  mesh->reset();
-
-  // First read in the entire file
-  QByteArray buff = file.readAll();
-  if(buff.size() != file.size())
-    throw QString("Could not read the whole file");
-  file.close();
-  // Grab the image size
-  int xsize = *(short*)(buff.data() + 47);
-  int ysize = *(short*)(buff.data() + 49);
-  // Height map uses every 4th pixel
-  int xsz = xsize / 4;
-  int ysz = ysize / 4;
-  Progress progress(QString("Loading Height Map %1 from File '%2'").arg(mesh->userId()).arg(mesh->file()), ysz);
-
-  // Find second image file
-  int imgpos = buff.indexOf(QByteArray("JFIF"), 16);
-  if(imgpos < 0)
-    throw QString("Can't find color image");
-  imgpos -= 6;
-  QTemporaryFile imgfile;
-
-  // Write to temp file
-  imgfile.open();
-  imgfile.write(buff.data() + imgpos, buff.size() - imgpos - xsz * ysz * 4);
-  imgfile.close();
-
-  // Load surface texture image
-  QImage image(imgfile.fileName());
-  // image.invertPixels();
-  if(xsize != image.width() or ysize != image.height())
-    throw QString("Invalid image size");
-  mesh->setImgTex(image);
-
-  // Find max/min z values to center image in z
-  float maxz = -1e10, minz = 1e10;
-  float* htp = (float*)(buff.data() + buff.size() - xsz * ysz * 4);
-  S.reserve(xsz * ysz);
-  for(int i = 0; i < xsz * ysz; i++) {
-    float z = *htp++;
-    if(z > maxz)
-      maxz = z;
-    if(z < minz)
-      minz = z;
-  }
-  float zshift = (minz + maxz) / 2.0;
-
-  // Save the vertex ids for connecting
-  // vertex vtx[xsz][ysz];
-  std::vector<std::vector<vertex> > vtx(xsz, std::vector<vertex>(ysz, vertex(0)));
-
-  // Create the vertices and fill in height and texture coords
-  htp = (float*)(buff.data() + buff.size() - xsz * ysz * 4);
-  for(int y = ysz - 1; y >= 0; y--) {
-    for(int x = xsz - 1; x >= 0; x--) {
-      float z = *htp++;
+  
+    vvgraph& S = mesh->graph();
+  
+    if(!S.empty() and !add)
+      mesh->reset();
+  
+    vertex_map vmap;
+  
+    QTextStream in(&file);
+    int vCnt;
+    in >> vCnt;
+    Progress progress(QString("Loading Cellular Mesh %1 from File '%2'").arg(mesh->userId()).arg(mesh->file()),
+                      vCnt * 2);
+    int interval = vCnt / 100;
+    if(interval < 1)
+      interval = 1;
+    S.reserve(vCnt);
+    for(int i = 0; i < vCnt; i++) {
+      if(in.atEnd())
+        throw QString("Premature end of file reading vertices");
       vertex v;
       S.insert(v);
-      vtx[x][y] = v;
-      v->pos.x() = (double(x) / double(xsz) - .5) * 4 / 3;
-      v->pos.y() = double(y) / double(ysz) - .5;
-      v->pos.z() = (z - zshift) * .03;
+      char tchar;
+      in >> v->saveId >> v->pos >> v->label >> tchar >> v->type;
       v->pos = realPos(v->pos, scale, transform, mesh);
-      v->txpos.x() = (float(x * 4) / float(xsize));
-      v->txpos.y() = (float(y * 4) / float(ysize));
+      vmap[v->saveId] = v;
+      if(v->label > mesh->viewLabel())
+        mesh->setLabel(v->label);
+      if((i % interval == 0)and !progress.advance(i))
+        userCancel();
     }
-  }
-
-  // Connect neighborhoods
-  for(int y = 0; y < ysz; y++) {
-    if(!progress.advance(y + 1))
-      throw(QString("Keyence load cancelled"));
-    for(int x = 0; x < xsz; x++) {
-      std::vector<vertex> nhbs;
-      nhbs.push_back(vtx[x][y]);
-      if(x == 0 and y == ysz - 1) {       // top left corner;
-        nhbs.push_back(vtx[x][y - 1]);
-        nhbs.push_back(vtx[x + 1][y - 1]);
-        nhbs.push_back(vtx[x + 1][y]);
-      } else if(x == 0 and y == 0) {       // bottom left corner
-        nhbs.push_back(vtx[x + 1][y]);
-        nhbs.push_back(vtx[x][y + 1]);
-      } else if(x == xsz - 1 and y == 0) {       // bottom right corner
-        nhbs.push_back(vtx[x][y + 1]);
-        nhbs.push_back(vtx[x - 1][y + 1]);
-        nhbs.push_back(vtx[x - 1][y]);
-      } else if(x == xsz - 1 and y == ysz - 1) {       // top right corner
-        nhbs.push_back(vtx[x - 1][y]);
-        nhbs.push_back(vtx[x][y - 1]);
-      } else if(y == ysz - 1) {       // top edge
-        nhbs.push_back(vtx[x - 1][y]);
-        nhbs.push_back(vtx[x][y - 1]);
-        nhbs.push_back(vtx[x + 1][y - 1]);
-        nhbs.push_back(vtx[x + 1][y]);
-      } else if(x == 0) {       // left edge
-        nhbs.push_back(vtx[x][y - 1]);
-        nhbs.push_back(vtx[x + 1][y - 1]);
-        nhbs.push_back(vtx[x + 1][y]);
-        nhbs.push_back(vtx[x][y + 1]);
-      } else if(y == 0) {       // bottom edge
-        nhbs.push_back(vtx[x + 1][y]);
-        nhbs.push_back(vtx[x][y + 1]);
-        nhbs.push_back(vtx[x - 1][y + 1]);
-        nhbs.push_back(vtx[x - 1][y]);
-      } else if(x == xsz - 1) {       // right edge
-        nhbs.push_back(vtx[x][y - 1]);
-        nhbs.push_back(vtx[x - 1][y + 1]);
-        nhbs.push_back(vtx[x - 1][y]);
-        nhbs.push_back(vtx[x][y + 1]);
-      } else {       // Interior vertex
-        nhbs.push_back(vtx[x + 1][y - 1]);
-        nhbs.push_back(vtx[x + 1][y]);
-        nhbs.push_back(vtx[x][y + 1]);
-        nhbs.push_back(vtx[x - 1][y + 1]);
-        nhbs.push_back(vtx[x - 1][y]);
-        nhbs.push_back(vtx[x][y - 1]);
-      }
-      vertex v = nhbs[0];
+    for(int i = 0; i < vCnt; i++) {
+      if(in.atEnd())
+        throw QString("Premature end of file reading neighborhoods");
+      uint vId, nCnt;
+      in >> vId >> nCnt;
+      vertex_map::const_iterator vit = vmap.find(vId);
+      if(vit == vmap.end())
+        throw QString("Invalid vertex id: %1").arg(vId);
+      vertex v = vit->second;
       vertex pn(0);
-      for(uint i = 1; i < nhbs.size(); i++) {
-        vertex n = nhbs[i];
-        if(i == 1)
+      for(uint j = 0; j < nCnt; j++) {
+        uint nId;
+        in >> nId;
+        vertex_map::const_iterator nit = vmap.find(nId);
+        if(nit == vmap.end())
+          throw QString("Invalid vertex id: %1").arg(nId);
+        vertex n = nit->second;
+        if(S.valence(v) == 0)
           S.insertEdge(v, n);
         else
           S.spliceAfter(v, pn, n);
         pn = n;
       }
+      if((i % interval == 0)and !progress.advance(vCnt + i))
+        userCancel();
     }
+    if(!progress.advance(2 * vCnt))
+      userCancel();
+    file.close();
+    mesh->setCells(true);
+    mesh->clearImgTex();
+    mesh->setNormals();
+    SETSTATUS("Loaded cell mesh, file:" << mesh->file() << ", vertices:" << S.size());
+    return true;
   }
-  mesh->setCells(false);
-  mesh->setNormals();
-  SETSTATUS("Loaded Keyence mesh, file:" << mesh->file() << ", vertices:" << S.size());
-  return true;
-}
-
-static bool addTriangle(vvgraph& S, std::vector<vertex>& vertices, Point3i tri)
-{
-  vertex x = vertices[tri.x()];
-  vertex y = vertices[tri.y()];
-  vertex z = vertices[tri.z()];
-  if(S.valence(x) == 0) {
-    S.insertEdge(x, y);
-    S.spliceAfter(x, y, z);
-  } else {
-    bool yinx = S.edge(x, y);
-    bool zinx = S.edge(x, z);
-
-    if(yinx and zinx) {     // Triangle already there
-      if(S.nextTo(x, y) != z)
-        SETSTATUS("addTriangle::Error:Error in nhbd");
-      return true;
-    } else if(yinx) {
+  
+  bool MeshImport::loadKeyence(Mesh* mesh, const QString& filename, bool scale, bool transform, bool /*add*/)
+  {
+    QFile file(filename);
+    if(!file.open(QIODevice::ReadOnly)) {
+      setErrorMessage(QString("loadMesh::Error:Cannot open input file: %1").arg(filename));
+      return false;
+    }
+  
+    vvgraph& S = mesh->graph();
+  
+    mesh->reset();
+  
+    // First read in the entire file
+    QByteArray buff = file.readAll();
+    if(buff.size() != file.size())
+      throw QString("Could not read the whole file");
+    file.close();
+    // Grab the image size
+    int xsize = *(short*)(buff.data() + 47);
+    int ysize = *(short*)(buff.data() + 49);
+    // Height map uses every 4th pixel
+    int xsz = xsize / 4;
+    int ysz = ysize / 4;
+    Progress progress(QString("Loading Height Map %1 from File '%2'").arg(mesh->userId()).arg(mesh->file()), ysz);
+  
+    // Find second image file
+    int imgpos = buff.indexOf(QByteArray("JFIF"), 16);
+    if(imgpos < 0)
+      throw QString("Can't find color image");
+    imgpos -= 6;
+    QTemporaryFile imgfile;
+  
+    // Write to temp file
+    imgfile.open();
+    imgfile.write(buff.data() + imgpos, buff.size() - imgpos - xsz * ysz * 4);
+    imgfile.close();
+  
+    // Load surface texture image
+    QImage image(imgfile.fileName());
+    // image.invertPixels();
+    if(xsize != image.width() or ysize != image.height())
+      throw QString("Invalid image size");
+    mesh->setImgTex(image);
+  
+    // Find max/min z values to center image in z
+    float maxz = -1e10, minz = 1e10;
+    float* htp = (float*)(buff.data() + buff.size() - xsz * ysz * 4);
+    S.reserve(xsz * ysz);
+    for(int i = 0; i < xsz * ysz; i++) {
+      float z = *htp++;
+      if(z > maxz)
+        maxz = z;
+      if(z < minz)
+        minz = z;
+    }
+    float zshift = (minz + maxz) / 2.0;
+  
+    // Save the vertex ids for connecting
+    // vertex vtx[xsz][ysz];
+    std::vector<std::vector<vertex> > vtx(xsz, std::vector<vertex>(ysz, vertex(0)));
+  
+    // Create the vertices and fill in height and texture coords
+    htp = (float*)(buff.data() + buff.size() - xsz * ysz * 4);
+    for(int y = ysz - 1; y >= 0; y--) {
+      for(int x = xsz - 1; x >= 0; x--) {
+        float z = *htp++;
+        vertex v;
+        S.insert(v);
+        vtx[x][y] = v;
+        v->pos.x() = (double(x) / double(xsz) - .5) * 4 / 3;
+        v->pos.y() = double(y) / double(ysz) - .5;
+        v->pos.z() = (z - zshift) * .03;
+        v->pos = realPos(v->pos, scale, transform, mesh);
+        v->txpos.x() = (float(x * 4) / float(xsize));
+        v->txpos.y() = (float(y * 4) / float(ysize));
+      }
+    }
+  
+    // Connect neighborhoods
+    for(int y = 0; y < ysz; y++) {
+      if(!progress.advance(y + 1))
+        throw(QString("Keyence load cancelled"));
+      for(int x = 0; x < xsz; x++) {
+        std::vector<vertex> nhbs;
+        nhbs.push_back(vtx[x][y]);
+        if(x == 0 and y == ysz - 1) {       // top left corner;
+          nhbs.push_back(vtx[x][y - 1]);
+          nhbs.push_back(vtx[x + 1][y - 1]);
+          nhbs.push_back(vtx[x + 1][y]);
+        } else if(x == 0 and y == 0) {       // bottom left corner
+          nhbs.push_back(vtx[x + 1][y]);
+          nhbs.push_back(vtx[x][y + 1]);
+        } else if(x == xsz - 1 and y == 0) {       // bottom right corner
+          nhbs.push_back(vtx[x][y + 1]);
+          nhbs.push_back(vtx[x - 1][y + 1]);
+          nhbs.push_back(vtx[x - 1][y]);
+        } else if(x == xsz - 1 and y == ysz - 1) {       // top right corner
+          nhbs.push_back(vtx[x - 1][y]);
+          nhbs.push_back(vtx[x][y - 1]);
+        } else if(y == ysz - 1) {       // top edge
+          nhbs.push_back(vtx[x - 1][y]);
+          nhbs.push_back(vtx[x][y - 1]);
+          nhbs.push_back(vtx[x + 1][y - 1]);
+          nhbs.push_back(vtx[x + 1][y]);
+        } else if(x == 0) {       // left edge
+          nhbs.push_back(vtx[x][y - 1]);
+          nhbs.push_back(vtx[x + 1][y - 1]);
+          nhbs.push_back(vtx[x + 1][y]);
+          nhbs.push_back(vtx[x][y + 1]);
+        } else if(y == 0) {       // bottom edge
+          nhbs.push_back(vtx[x + 1][y]);
+          nhbs.push_back(vtx[x][y + 1]);
+          nhbs.push_back(vtx[x - 1][y + 1]);
+          nhbs.push_back(vtx[x - 1][y]);
+        } else if(x == xsz - 1) {       // right edge
+          nhbs.push_back(vtx[x][y - 1]);
+          nhbs.push_back(vtx[x - 1][y + 1]);
+          nhbs.push_back(vtx[x - 1][y]);
+          nhbs.push_back(vtx[x][y + 1]);
+        } else {       // Interior vertex
+          nhbs.push_back(vtx[x + 1][y - 1]);
+          nhbs.push_back(vtx[x + 1][y]);
+          nhbs.push_back(vtx[x][y + 1]);
+          nhbs.push_back(vtx[x - 1][y + 1]);
+          nhbs.push_back(vtx[x - 1][y]);
+          nhbs.push_back(vtx[x][y - 1]);
+        }
+        vertex v = nhbs[0];
+        vertex pn(0);
+        for(uint i = 1; i < nhbs.size(); i++) {
+          vertex n = nhbs[i];
+          if(i == 1)
+            S.insertEdge(v, n);
+          else
+            S.spliceAfter(v, pn, n);
+          pn = n;
+        }
+      }
+    }
+    mesh->setCells(false);
+    mesh->setNormals();
+    SETSTATUS("Loaded Keyence mesh, file:" << mesh->file() << ", vertices:" << S.size());
+    return true;
+  }
+  
+  static bool addTriangle(vvgraph& S, std::vector<vertex>& vertices, Point3i tri)
+  {
+    vertex x = vertices[tri.x()];
+    vertex y = vertices[tri.y()];
+    vertex z = vertices[tri.z()];
+    if(S.valence(x) == 0) {
+      S.insertEdge(x, y);
       S.spliceAfter(x, y, z);
-      return true;
-    } else if(zinx) {
-      S.spliceBefore(x, z, y);
-      return true;
+    } else {
+      bool yinx = S.edge(x, y);
+      bool zinx = S.edge(x, z);
+  
+      if(yinx and zinx) {     // Triangle already there
+        if(S.nextTo(x, y) != z)
+          SETSTATUS("addTriangle::Error:Error in nhbd");
+        return true;
+      } else if(yinx) {
+        S.spliceAfter(x, y, z);
+        return true;
+      } else if(zinx) {
+        S.spliceBefore(x, z, y);
+        return true;
+      }
     }
+    return false;   // Did not insert triangle
   }
-  return false;   // Did not insert triangle
-}
-
-bool meshFromTriangles(vvgraph& S, std::vector<vertex>& vertices, std::vector<Point3i>& triangles)
-{
-  // Insert vertices into mesh
-  forall(const vertex& v, vertices)
-    S.insert(v);
-
-  // Make triangle list with all orientations.
-  std::vector<Point3i> tris;
-  tris.reserve(3 * triangles.size());
-  forall(const Point3i tri, triangles) {
-    tris.push_back(tri);
-    tris.push_back(Point3i(tri.y(), tri.z(), tri.x()));
-    tris.push_back(Point3i(tri.z(), tri.x(), tri.y()));
+  
+  bool meshFromTriangles(vvgraph& S, std::vector<vertex>& vertices, std::vector<Point3i>& triangles)
+  {
+    // Insert vertices into mesh
+    forall(const vertex& v, vertices)
+      S.insert(v);
+  
+    // Make triangle list with all orientations.
+    std::vector<Point3i> tris;
+    tris.reserve(3 * triangles.size());
+    forall(const Point3i tri, triangles) {
+      tris.push_back(tri);
+      tris.push_back(Point3i(tri.y(), tri.z(), tri.x()));
+      tris.push_back(Point3i(tri.z(), tri.x(), tri.y()));
+    }
+  
+    // Extract neighborhood from triangles,  make multiple passes until list empty
+    while(!tris.empty()) {
+      std::vector<Point3i> new_tris;
+      new_tris.reserve(tris.size() / 4);
+      bool success = false;
+      for(size_t i = 0; i < tris.size(); i++) {
+        if(!addTriangle(S, vertices, tris[i]))
+          new_tris.push_back(tris[i]);
+        else
+          success = true;
+      }
+      if(!success)
+        return false;       // Failed to add any triangle on this turn ... won't help again
+      swap(tris, new_tris);
+    }
+    return true;
   }
-
-  // Extract neighborhood from triangles,  make multiple passes until list empty
-  while(!tris.empty()) {
-    std::vector<Point3i> new_tris;
-    new_tris.reserve(tris.size() / 4);
-    bool success = false;
-    for(size_t i = 0; i < tris.size(); i++) {
-      if(!addTriangle(S, vertices, tris[i]))
-        new_tris.push_back(tris[i]);
-      else
-        success = true;
+  
+  bool MeshImport::loadMeshOBJ(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add)
+  {
+    QFile file(filename);
+    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+      setErrorMessage(QString("loadMesh::Error:Cannot open input file: %1").arg(filename));
+      return false;
     }
-    if(!success)
-      return false;       // Failed to add any triangle on this turn ... won't help again
-    swap(tris, new_tris);
-  }
-  return true;
-}
-
-bool MeshImport::loadMeshOBJ(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add)
-{
-  QFile file(filename);
-  if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
-    setErrorMessage(QString("loadMesh::Error:Cannot open input file: %1").arg(filename));
-    return false;
-  }
-
-  std::vector<Point3f> points;
-  std::vector<float> signal;
-  std::vector<int> labels;
-  IntFloatMap& label_heat = mesh->labelHeat();
-  label_heat.clear();
-  std::vector<Point3i> triangles;
-  float minSignal = FLT_MAX, maxSignal = -FLT_MAX;
-  float minHeat = FLT_MAX, maxHeat = -FLT_MAX;
-
-  QTextStream ts(&file);
-  int line_count = 0;
-  bool fixedBound = false;
-
-  Information::out << "Reading the file" << endl;
-  QString signalDescription;
-  QString heatDescription;
-
-  while(!ts.atEnd()) {
-    ++line_count;
-    QString line = ts.readLine().trimmed();
-    int idx = line.indexOf('#');
-    if(idx != -1)
-      line = line.left(idx).trimmed();
-    if(!line.isEmpty()) {
-      QStringList fields = line.split(QRegExp("[ \t]"), QString::SkipEmptyParts);
-      if(fields[0] == "v") {
-        if(fields.size() != 4 and fields.size() != 5) {
-          setErrorMessage(
-            QString("Error reading file '%1' on line %2: vertex needs 3 or 4 values (x y z [w]), got %3")
-            .arg(filename)
-            .arg(line_count)
-            .arg(fields.size() - 1));
-          return false;
-        }
-        Point3f pos;
-        bool ok;
-        pos.x() = fields[1].toFloat(&ok);
-        if(!ok) {
-          setErrorMessage(QString("Error reading file '%1' on line %2: invalid value for vertex x: '%3'")
-                          .arg(filename)
-                          .arg(line_count)
-                          .arg(fields[1]));
-          return false;
-        }
-        pos.y() = fields[2].toFloat(&ok);
-        if(!ok) {
-          setErrorMessage(QString("Error reading file '%1' on line %2: invalid value for vertex y: '%3'")
-                          .arg(filename)
-                          .arg(line_count)
-                          .arg(fields[2]));
-          return false;
-        }
-        pos.z() = fields[3].toFloat(&ok);
-        if(!ok) {
-          setErrorMessage(QString("Error reading file '%1' on line %2: invalid value for vertex z: '%3'")
-                          .arg(filename)
-                          .arg(line_count)
-                          .arg(fields[3]));
-          return false;
-        }
-        points.push_back(pos);
-
-        // If there is a 5th field, this is w, so we need to normalize the position with this
-        if(fields.size() == 5) {
-          float w = fields[4].toFloat(&ok);
+  
+    std::vector<Point3f> points;
+    std::vector<float> signal;
+    std::vector<int> labels;
+    IntFloatMap& label_heat = mesh->labelHeat();
+    label_heat.clear();
+    std::vector<Point3i> triangles;
+    float minSignal = FLT_MAX, maxSignal = -FLT_MAX;
+    float minHeat = FLT_MAX, maxHeat = -FLT_MAX;
+  
+    QTextStream ts(&file);
+    int line_count = 0;
+    bool fixedBound = false;
+  
+    Information::out << "Reading the file" << endl;
+    QString signalDescription;
+    QString heatDescription;
+  
+    while(!ts.atEnd()) {
+      ++line_count;
+      QString line = ts.readLine().trimmed();
+      int idx = line.indexOf('#');
+      if(idx != -1)
+        line = line.left(idx).trimmed();
+      if(!line.isEmpty()) {
+        QStringList fields = line.split(QRegExp("[ \t]"), QString::SkipEmptyParts);
+        if(fields[0] == "v") {
+          if(fields.size() != 4 and fields.size() != 5) {
+            setErrorMessage(
+              QString("Error reading file '%1' on line %2: vertex needs 3 or 4 values (x y z [w]), got %3")
+              .arg(filename)
+              .arg(line_count)
+              .arg(fields.size() - 1));
+            return false;
+          }
+          Point3f pos;
+          bool ok;
+          pos.x() = fields[1].toFloat(&ok);
           if(!ok) {
-            setErrorMessage(QString("Error reading file '%1' on line %2: invalid value for vertex w: '%3'")
+            setErrorMessage(QString("Error reading file '%1' on line %2: invalid value for vertex x: '%3'")
                             .arg(filename)
                             .arg(line_count)
-                            .arg(fields[4]));
+                            .arg(fields[1]));
             return false;
           }
-          if(w != 0)
-            pos /= w;
-          else {
+          pos.y() = fields[2].toFloat(&ok);
+          if(!ok) {
+            setErrorMessage(QString("Error reading file '%1' on line %2: invalid value for vertex y: '%3'")
+                            .arg(filename)
+                            .arg(line_count)
+                            .arg(fields[2]));
+            return false;
+          }
+          pos.z() = fields[3].toFloat(&ok);
+          if(!ok) {
+            setErrorMessage(QString("Error reading file '%1' on line %2: invalid value for vertex z: '%3'")
+                            .arg(filename)
+                            .arg(line_count)
+                            .arg(fields[3]));
+            return false;
+          }
+          points.push_back(pos);
+  
+          // If there is a 5th field, this is w, so we need to normalize the position with this
+          if(fields.size() == 5) {
+            float w = fields[4].toFloat(&ok);
+            if(!ok) {
+              setErrorMessage(QString("Error reading file '%1' on line %2: invalid value for vertex w: '%3'")
+                              .arg(filename)
+                              .arg(line_count)
+                              .arg(fields[4]));
+              return false;
+            }
+            if(w != 0)
+              pos /= w;
+            else {
+              setErrorMessage(
+                QString("Error reading file '%1' on line %2: MorphoGraphX cannot interpret a vertex w of 0")
+                .arg(filename)
+                .arg(line_count));
+              return false;
+            }
+          }
+        } else if(fields[0] == "f") {
+          std::vector<int> poly(fields.size() - 1);
+          bool ok;
+          int psz = points.size();
+          for(int i = 0; i < fields.size() - 1; ++i) {
+            poly[i] = fields[i + 1].toInt(&ok) - 1;
+            if(!ok or poly[i] < 0 or poly[i] >= psz) {
+              setErrorMessage(
+                QString("Error reading file '%1' on line %2: the first vertex id is not valid: '%3'")
+                .arg(filename)
+                .arg(line_count)
+                .arg(fields[i + 1]));
+              return false;
+            }
+          }
+          // If a triangle, just add it
+          if(poly.size() == 3)
+            triangles.push_back(Point3i(poly[0], poly[1], poly[2]));
+          else {         // Otherwise make a triangle fan
+                         // Find center
+            Point3f c(0, 0, 0);
+            for(size_t i = 0; i < poly.size(); ++i)
+              c += points[poly[i]];
+            c /= poly.size();
+            points.push_back(c);
+  
+            // Add tris
+            for(size_t i = 0; i < poly.size(); ++i)
+              if(i == poly.size() - 1)
+                triangles.push_back(Point3i(psz, poly[i], poly[0]));
+              else
+                triangles.push_back(Point3i(psz, poly[i], poly[i + 1]));
+          }
+        } else if(fields[0] == "label") {
+          if(fields.size() != 2) {
             setErrorMessage(
-              QString("Error reading file '%1' on line %2: MorphoGraphX cannot interpret a vertex w of 0")
+              QString("Error reading file '%1' on line %2: the label field must have 1 value, got %3")
               .arg(filename)
-              .arg(line_count));
+              .arg(line_count)
+              .arg(fields.size() - 1));
             return false;
           }
-        }
-      } else if(fields[0] == "f") {
-        std::vector<int> poly(fields.size() - 1);
-        bool ok;
-        int psz = points.size();
-        for(int i = 0; i < fields.size() - 1; ++i) {
-          poly[i] = fields[i + 1].toInt(&ok) - 1;
-          if(!ok or poly[i] < 0 or poly[i] >= psz) {
+          int lab;
+          bool ok;
+          lab = fields[1].toInt(&ok);
+          if(!ok) {
             setErrorMessage(
-              QString("Error reading file '%1' on line %2: the first vertex id is not valid: '%3'")
+              QString("Error reading file '%1' on line %2: the vertex label has invalid value: '%3'")
               .arg(filename)
               .arg(line_count)
-              .arg(fields[i + 1]));
+              .arg(fields[1]));
             return false;
           }
+          labels.push_back(lab);
+        } else if(fields[0] == "vv") {
+          if(fields.size() != 2) {
+            setErrorMessage(
+              QString("Error reading file '%1' on line %2: the vv field must have 1 value, got %3")
+              .arg(filename)
+              .arg(line_count)
+              .arg(fields.size() - 1));
+            return false;
+          }
+          float value;
+          bool ok;
+          value = fields[1].toFloat(&ok);
+          if(!ok) {
+            setErrorMessage(
+              QString("Error reading file '%1' on line %2: the vertex value has invalid value: '%3'")
+              .arg(filename)
+              .arg(line_count)
+              .arg(fields[1]));
+            return false;
+          }
+          signal.push_back(value);
+          if(!fixedBound) {
+            if(value > maxSignal)
+              maxSignal = value;
+            if(value < minSignal)
+              minSignal = value;
+          }
+        } else if(fields[0] == "vv_desc") {
+          fields.pop_front();
+          signalDescription = fields.join(" ");
+        } else if(fields[0] == "vv_range") {
+          if(fields.size() != 3) {
+            return setErrorMessage(
+              QString("Error reading file '%1' on line %2: the vv_range needs 2 values, not %3")
+              .arg(filename)
+              .arg(line_count)
+              .arg(fields.size() - 1));
+          }
+          float vmin, vmax;
+          bool ok;
+          vmin = fields[1].toFloat(&ok);
+          if(!ok) {
+            return setErrorMessage(
+              QString("Error reading file '%1' on line %2: min value for vv_range is not a value float: %3")
+              .arg(filename)
+              .arg(line_count)
+              .arg(fields[1]));
+          }
+          vmax = fields[2].toFloat(&ok);
+          if(!ok) {
+            return setErrorMessage(
+              QString("Error reading file '%1' on line %2: max value for vv_range is not a value float: %3")
+              .arg(filename)
+              .arg(line_count)
+              .arg(fields[2]));
+          }
+          minSignal = vmin;
+          maxSignal = vmax;
+          Information::out << "vv_range = " << minSignal << " - " << maxSignal << endl;
+          fixedBound = true;
+        } else if(fields[0] == "heat") {
+          if(fields.size() != 3) {
+            setErrorMessage(
+              QString("Error reading file '%1' on line %2: the vv field must have 2 value, got %3")
+              .arg(filename)
+              .arg(line_count)
+              .arg(fields.size() - 1));
+            return false;
+          }
+          int lab;
+          float value;
+          bool ok;
+          lab = fields[1].toInt(&ok);
+          if(!ok) {
+            setErrorMessage(
+              QString("Error reading file '%1' on line %2: the heat label has invalid value: '%3'")
+              .arg(filename)
+              .arg(line_count)
+              .arg(fields[1]));
+            return false;
+          }
+          value = fields[2].toFloat(&ok);
+          if(!ok) {
+            setErrorMessage(
+              QString("Error reading file '%1' on line %2: the heat value has invalid value: '%3'")
+              .arg(filename)
+              .arg(line_count)
+              .arg(fields[2]));
+            return false;
+          }
+          label_heat[lab] = value;
+          if(value < minHeat)
+            minHeat = value;
+          if(value > maxHeat)
+            maxHeat = value;
+        } else if(fields[0] == "heat_desc") {
+          fields.pop_front();
+          heatDescription = fields.join(" ");
         }
-        // If a triangle, just add it
-        if(poly.size() == 3)
-          triangles.push_back(Point3i(poly[0], poly[1], poly[2]));
-        else {         // Otherwise make a triangle fan
-                       // Find center
-          Point3f c(0, 0, 0);
-          for(size_t i = 0; i < poly.size(); ++i)
-            c += points[poly[i]];
-          c /= poly.size();
-          points.push_back(c);
-
-          // Add tris
-          for(size_t i = 0; i < poly.size(); ++i)
-            if(i == poly.size() - 1)
-              triangles.push_back(Point3i(psz, poly[i], poly[0]));
-            else
-              triangles.push_back(Point3i(psz, poly[i], poly[i + 1]));
-        }
-      } else if(fields[0] == "label") {
-        if(fields.size() != 2) {
-          setErrorMessage(
-            QString("Error reading file '%1' on line %2: the label field must have 1 value, got %3")
-            .arg(filename)
-            .arg(line_count)
-            .arg(fields.size() - 1));
-          return false;
-        }
-        int lab;
-        bool ok;
-        lab = fields[1].toInt(&ok);
-        if(!ok) {
-          setErrorMessage(
-            QString("Error reading file '%1' on line %2: the vertex label has invalid value: '%3'")
-            .arg(filename)
-            .arg(line_count)
-            .arg(fields[1]));
-          return false;
-        }
-        labels.push_back(lab);
-      } else if(fields[0] == "vv") {
-        if(fields.size() != 2) {
-          setErrorMessage(
-            QString("Error reading file '%1' on line %2: the vv field must have 1 value, got %3")
-            .arg(filename)
-            .arg(line_count)
-            .arg(fields.size() - 1));
-          return false;
-        }
-        float value;
-        bool ok;
-        value = fields[1].toFloat(&ok);
-        if(!ok) {
-          setErrorMessage(
-            QString("Error reading file '%1' on line %2: the vertex value has invalid value: '%3'")
-            .arg(filename)
-            .arg(line_count)
-            .arg(fields[1]));
-          return false;
-        }
-        signal.push_back(value);
-        if(!fixedBound) {
-          if(value > maxSignal)
-            maxSignal = value;
-          if(value < minSignal)
-            minSignal = value;
-        }
-      } else if(fields[0] == "vv_desc") {
-        fields.pop_front();
-        signalDescription = fields.join(" ");
-      } else if(fields[0] == "vv_range") {
-        if(fields.size() != 3) {
-          return setErrorMessage(
-            QString("Error reading file '%1' on line %2: the vv_range needs 2 values, not %3")
-            .arg(filename)
-            .arg(line_count)
-            .arg(fields.size() - 1));
-        }
-        float vmin, vmax;
-        bool ok;
-        vmin = fields[1].toFloat(&ok);
-        if(!ok) {
-          return setErrorMessage(
-            QString("Error reading file '%1' on line %2: min value for vv_range is not a value float: %3")
-            .arg(filename)
-            .arg(line_count)
-            .arg(fields[1]));
-        }
-        vmax = fields[2].toFloat(&ok);
-        if(!ok) {
-          return setErrorMessage(
-            QString("Error reading file '%1' on line %2: max value for vv_range is not a value float: %3")
-            .arg(filename)
-            .arg(line_count)
-            .arg(fields[2]));
-        }
-        minSignal = vmin;
-        maxSignal = vmax;
-        Information::out << "vv_range = " << minSignal << " - " << maxSignal << endl;
-        fixedBound = true;
-      } else if(fields[0] == "heat") {
-        if(fields.size() != 3) {
-          setErrorMessage(
-            QString("Error reading file '%1' on line %2: the vv field must have 2 value, got %3")
-            .arg(filename)
-            .arg(line_count)
-            .arg(fields.size() - 1));
-          return false;
-        }
-        int lab;
-        float value;
-        bool ok;
-        lab = fields[1].toInt(&ok);
-        if(!ok) {
-          setErrorMessage(
-            QString("Error reading file '%1' on line %2: the heat label has invalid value: '%3'")
-            .arg(filename)
-            .arg(line_count)
-            .arg(fields[1]));
-          return false;
-        }
-        value = fields[2].toFloat(&ok);
-        if(!ok) {
-          setErrorMessage(
-            QString("Error reading file '%1' on line %2: the heat value has invalid value: '%3'")
-            .arg(filename)
-            .arg(line_count)
-            .arg(fields[2]));
-          return false;
-        }
-        label_heat[lab] = value;
-        if(value < minHeat)
-          minHeat = value;
-        if(value > maxHeat)
-          maxHeat = value;
-      } else if(fields[0] == "heat_desc") {
-        fields.pop_front();
-        heatDescription = fields.join(" ");
+        // Ignore anything else
       }
-      // Ignore anything else
     }
+  
+    if(!signal.empty() and signal.size() != points.size()) {
+      setErrorMessage(
+        QString(
+          "Error reading file '%1', signal array size mismatch. Current file has %2 vs fields and %3 vertices")
+        .arg(filename)
+        .arg(signal.size())
+        .arg(points.size()));
+      return false;
+    }
+    if(!labels.empty() and labels.size() != points.size()) {
+      setErrorMessage(QString("Error reading file '%1', labels array size mismatch. Current file has %2 labels "
+                              "fields and %3 vertices")
+                      .arg(filename)
+                      .arg(labels.size())
+                      .arg(points.size()));
+      return false;
+    }
+  
+    Information::out << "Extracted " << points.size() << " points and " << triangles.size() << " triangles" << endl;
+  
+    vvgraph& S = mesh->graph();
+  
+    if(!add)
+      mesh->reset();
+    else
+      forall(const vertex& v, S)
+        v->saveId = -1;
+  
+    if(signal.empty() and not fixedBound) {
+      minSignal = 0.0;
+      maxSignal = 1.0;
+    } else if(maxSignal == minSignal)
+      minSignal -= 1.0f;
+  
+    // First add vertices
+    std::vector<vertex> vtx(points.size(), vertex(0));
+    for(size_t i = 0; i < points.size(); ++i) {
+      vertex v;
+      v->pos = realPos(points[i], scale, transform, mesh);
+      vtx[i] = v;
+      if(signal.empty())
+        v->signal = 1.0;
+      else {
+        v->signal = signal[i];
+      }
+      if(!labels.empty())
+        v->label = labels[i];
+      // Check for NaN
+      v->signal = v->signal == v->signal ? v->signal : 0;
+    }
+  
+    if(!meshFromTriangles(S, vtx, triangles)) {
+      setErrorMessage("Error, cannot add all the triangles");
+      return false;
+    }
+  
+    std::cout << "MinSignal:" << minSignal << ", MaxSignal:" << maxSignal << std::endl;
+  
+    if(!label_heat.empty()) {
+      if(minHeat >= maxHeat)
+        maxHeat += 1;
+      mesh->heatMapBounds() = Point2f(minHeat, maxHeat);
+      Information::out << "heatMapBounds = " << mesh->heatMapBounds() << endl;
+      mesh->showHeat();
+    }
+    if(!heatDescription.isEmpty())
+      mesh->heatMapUnit() = heatDescription;
+  
+    mesh->signalBounds() = Point2f(minSignal, maxSignal);
+    mesh->signalUnit() = signalDescription;
+    mesh->setCells(false);
+    mesh->clearImgTex();
+    mesh->setNormals();
+    mesh->updateBBox();
+    mesh->setCulling(false);
+    mesh->updateAll();
+  
+    return true;
   }
-
-  if(!signal.empty() and signal.size() != points.size()) {
-    setErrorMessage(
-      QString(
-        "Error reading file '%1', signal array size mismatch. Current file has %2 vs fields and %3 vertices")
-      .arg(filename)
-      .arg(signal.size())
-      .arg(points.size()));
-    return false;
-  }
-  if(!labels.empty() and labels.size() != points.size()) {
-    setErrorMessage(QString("Error reading file '%1', labels array size mismatch. Current file has %2 labels "
-                            "fields and %3 vertices")
-                    .arg(filename)
-                    .arg(labels.size())
-                    .arg(points.size()));
-    return false;
-  }
-
-  Information::out << "Extracted " << points.size() << " points and " << triangles.size() << " triangles" << endl;
-
-  vvgraph& S = mesh->graph();
-
-  if(!add)
-    mesh->reset();
-  else
-    forall(const vertex& v, S)
-      v->saveId = -1;
-
-  if(signal.empty() and not fixedBound) {
-    minSignal = 0.0;
-    maxSignal = 1.0;
-  } else if(maxSignal == minSignal)
-    minSignal -= 1.0f;
-
-  // First add vertices
-  std::vector<vertex> vtx(points.size(), vertex(0));
-  for(size_t i = 0; i < points.size(); ++i) {
-    vertex v;
-    v->pos = realPos(points[i], scale, transform, mesh);
-    vtx[i] = v;
-    if(signal.empty())
-      v->signal = 1.0;
-    else {
-      v->signal = signal[i];
+  
+  bool MeshImport::loadMeshEdit(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add)
+  {
+    QFile file(filename);
+    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+      setErrorMessage(QString("loadMesh::Error:Cannot open input file: %1").arg(filename));
+      return false;
     }
-    if(!labels.empty())
-      v->label = labels[i];
-    // Check for NaN
-    v->signal = v->signal == v->signal ? v->signal : 0;
+  
+    vvgraph& S = mesh->graph();
+  
+    if(!add)
+      mesh->reset();
+    else
+      forall(const vertex& v, S)
+        v->saveId = -1;
+  
+    std::vector<vertex> vertices;
+    std::vector<Point3i> triangles;
+  
+    QTextStream in(&file);
+    QString tmp;
+    tmp = in.readLine();
+    tmp = in.readLine();
+    tmp = in.readLine();
+    int vCnt;
+    in >> vCnt;
+    Progress progress(QString("Loading Triangle Mesh Vertices %1 from File '%2'").arg(mesh->userId()).arg(mesh->file()),
+                      vCnt);
+    int prog = 1;
+    uint saveId = 0;
+    S.reserve(vCnt);
+    for(int i = 0; i < vCnt; i++) {
+      if(in.atEnd())
+        throw(QString("Premature end of file reading vertices"));
+      vertex v;
+      S.insert(v);
+      in >> v->pos >> v->label;
+      v->pos = realPos(v->pos, scale, transform, mesh);
+      v->saveId = saveId++;
+      vertices.push_back(v);
+      if(v->label > mesh->viewLabel())
+        mesh->setLabel(v->label);
+      if(!progress.advance(prog++))
+        userCancel();
+    }
+    tmp = in.readLine();
+    tmp = in.readLine();
+    int tCnt, t;
+  
+    in >> tCnt;
+    progress.restart(QString("Loading triangles-%1 - %2").arg(mesh->userId()).arg(mesh->file()), tCnt);
+    for(int i = 0; i < tCnt; i++) {
+      if(in.atEnd())
+        throw QString("Premature end of file reading triangles");
+      Point3i tri;
+      in >> tri.x() >> tri.y() >> tri.z() >> t;
+      tri -= Point3i(1, 1, 1);
+      triangles.push_back(tri);
+      if(!progress.advance(prog++))
+        userCancel();
+    }
+    file.close();
+  
+    if(!meshFromTriangles(S, vertices, triangles)) {
+      setErrorMessage("Error, cannot add all the triangles");
+      return false;
+    }
+    mesh->setCells(false);
+    mesh->clearImgTex();
+    mesh->setNormals();
+    SETSTATUS("Loaded mesh, file:" << mesh->file() << ", vertices:" << S.size());
+    return true;
   }
-
-  if(!meshFromTriangles(S, vtx, triangles)) {
-    setErrorMessage("Error, cannot add all the triangles");
-    return false;
-  }
-
-  std::cout << "MinSignal:" << minSignal << ", MaxSignal:" << maxSignal << std::endl;
-
-  if(!label_heat.empty()) {
-    if(minHeat >= maxHeat)
-      maxHeat += 1;
-    mesh->heatMapBounds() = Point2f(minHeat, maxHeat);
-    Information::out << "heatMapBounds = " << mesh->heatMapBounds() << endl;
-    mesh->showHeat();
-  }
-  if(!heatDescription.isEmpty())
-    mesh->heatMapUnit() = heatDescription;
-
-  mesh->signalBounds() = Point2f(minSignal, maxSignal);
-  mesh->signalUnit() = signalDescription;
-  mesh->setCells(false);
-  mesh->clearImgTex();
-  mesh->setNormals();
-  mesh->updateBBox();
-  mesh->setCulling(false);
-  mesh->updateAll();
-
-  return true;
-}
-
-bool MeshImport::loadMeshEdit(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add)
-{
-  QFile file(filename);
-  if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
-    setErrorMessage(QString("loadMesh::Error:Cannot open input file: %1").arg(filename));
-    return false;
-  }
-
-  vvgraph& S = mesh->graph();
-
-  if(!add)
-    mesh->reset();
-  else
-    forall(const vertex& v, S)
-      v->saveId = -1;
-
-  std::vector<vertex> vertices;
-  std::vector<Point3i> triangles;
-
-  QTextStream in(&file);
-  QString tmp;
-  tmp = in.readLine();
-  tmp = in.readLine();
-  tmp = in.readLine();
-  int vCnt;
-  in >> vCnt;
-  Progress progress(QString("Loading Triangle Mesh Vertices %1 from File '%2'").arg(mesh->userId()).arg(mesh->file()),
-                    vCnt);
-  int prog = 1;
-  uint saveId = 0;
-  S.reserve(vCnt);
-  for(int i = 0; i < vCnt; i++) {
-    if(in.atEnd())
-      throw(QString("Premature end of file reading vertices"));
-    vertex v;
-    S.insert(v);
-    in >> v->pos >> v->label;
-    v->pos = realPos(v->pos, scale, transform, mesh);
-    v->saveId = saveId++;
-    vertices.push_back(v);
-    if(v->label > mesh->viewLabel())
-      mesh->setLabel(v->label);
-    if(!progress.advance(prog++))
-      userCancel();
-  }
-  tmp = in.readLine();
-  tmp = in.readLine();
-  int tCnt, t;
-
-  in >> tCnt;
-  progress.restart(QString("Loading triangles-%1 - %2").arg(mesh->userId()).arg(mesh->file()), tCnt);
-  for(int i = 0; i < tCnt; i++) {
-    if(in.atEnd())
-      throw QString("Premature end of file reading triangles");
-    Point3i tri;
-    in >> tri.x() >> tri.y() >> tri.z() >> t;
-    tri -= Point3i(1, 1, 1);
-    triangles.push_back(tri);
-    if(!progress.advance(prog++))
-      userCancel();
-  }
-  file.close();
-
-  if(!meshFromTriangles(S, vertices, triangles)) {
-    setErrorMessage("Error, cannot add all the triangles");
-    return false;
-  }
-  mesh->setCells(false);
-  mesh->clearImgTex();
-  mesh->setNormals();
-  SETSTATUS("Loaded mesh, file:" << mesh->file() << ", vertices:" << S.size());
-  return true;
-}
-
-void MeshImport::selectMeshType(const QString& type)
-{
-  QString filename = ui->MeshFile->text();
-  if(filename.isEmpty())
-    return;
-  QFileInfo fi(filename);
-  QString suf = fi.suffix();
-  if(!suf.isEmpty())
-    filename = filename.left(filename.size() - suf.size() - 1);
-  if(type == "Mesh")
-    filename += ".mgxm";
-  else if(type == "PLY")
-    filename += ".ply";
-  else if(type == "Text" or type == "Cells")
-    filename += ".txt";
-  else if(type == "Keyence")
-    filename += ".jpg";
-  else if(type == "MeshEdit")
-    filename += ".mesh";
-  else if(type == "OBJ")
-    filename += ".obj";
-  ui->MeshFile->setText(filename);
-}
-
-void MeshImport::selectMeshFile()
-{
-  QString filename = ui->MeshFile->text();
-  QStringList filters;
-  filters << "Stanford Polygon files (*.ply)"
-          << "VTK Mesh files (*.vtu)"
-          << "Text or cell files (*.txt)"
-          << "Keyence files (*.jpg)"
-          << "MeshEdit files (*.mesh)"
-          << "OBJ files (*.obj)"
-          << "All Mesh Files (*.ply *.vtu *.txt *.jpg *.mesh *.obj)";
-  QString filter;
+  
+  void MeshImport::selectMeshType(const QString& type)
   {
+    QString filename = ui->MeshFile->text();
+    if(filename.isEmpty())
+      return;
     QFileInfo fi(filename);
     QString suf = fi.suffix();
-    if(suf == "vtu")
-      filter = filters[0];
-    else if(suf == "vtu")
-      filter = filters[1];
-    else if(suf == "txt")
-      filter = filters[2];
-    else if(suf == "jpg")
-      filter = filters[3];
-    else if(suf == "mesh")
-      filter = filters[4];
-    else if(suf == "obj")
-      filter = filters[5];
-    else
-      filter = filters[6];
+    if(!suf.isEmpty())
+      filename = filename.left(filename.size() - suf.size() - 1);
+    if(type == "Mesh")
+      filename += ".mgxm";
+    else if(type == "PLY")
+      filename += ".ply";
+    else if(type == "Text" or type == "Cells")
+      filename += ".txt";
+    else if(type == "Keyence")
+      filename += ".jpg";
+    else if(type == "MeshEdit")
+      filename += ".mesh";
+    else if(type == "OBJ")
+      filename += ".obj";
+    ui->MeshFile->setText(filename);
   }
-  filename = QFileDialog::getOpenFileName(dlg, QString("Select mesh file"), filename, filters.join(";;"), &filter,
-                                          FileDialogOptions);
-  if(!filename.isEmpty()) {
-    if(!QFile::exists(filename)) {
-      QMessageBox::information(dlg, "Error selecting file",
-                               "You must select an existing file. Your selection is ignored.");
-      return;
+  
+  void MeshImport::selectMeshFile()
+  {
+    QString filename = ui->MeshFile->text();
+    QStringList filters;
+    filters << "Stanford Polygon files (*.ply)"
+            << "VTK Mesh files (*.vtu)"
+            << "Text or cell files (*.txt)"
+            << "Keyence files (*.jpg)"
+            << "MeshEdit files (*.mesh)"
+            << "OBJ files (*.obj)"
+            << "All Mesh Files (*.ply *.vtu *.txt *.jpg *.mesh *.obj)";
+    QString filter;
+    {
+      QFileInfo fi(filename);
+      QString suf = fi.suffix();
+      if(suf == "vtu")
+        filter = filters[0];
+      else if(suf == "vtu")
+        filter = filters[1];
+      else if(suf == "txt")
+        filter = filters[2];
+      else if(suf == "jpg")
+        filter = filters[3];
+      else if(suf == "mesh")
+        filter = filters[4];
+      else if(suf == "obj")
+        filter = filters[5];
+      else
+        filter = filters[6];
     }
-    setMeshFile(filename);
+    filename = QFileDialog::getOpenFileName(dlg, QString("Select mesh file"), filename, filters.join(";;"), &filter,
+                                            FileDialogOptions);
+    if(!filename.isEmpty()) {
+      if(!QFile::exists(filename)) {
+        QMessageBox::information(dlg, "Error selecting file",
+                                 "You must select an existing file. Your selection is ignored.");
+        return;
+      }
+      setMeshFile(filename);
+    }
   }
-}
-
-QString MeshImport::properFile(QString filename, const QString& type) const
-{
-  QFileInfo fi(filename);
-  QString suf = fi.suffix();
-  if(!suf.isEmpty())
-    filename = filename.left(filename.size() - suf.size() - 1);
-  if(type == "PLY Mesh")
-    filename += ".ply";
-  else if(type == "VTK Mesh")
-    filename += ".vtu";
-  else if(type == "Text" or type == "Cells")
-    filename += ".txt";
-  else if(type == "MeshEdit")
-    filename += ".mesh";
-  else if(type == "Keyence")
-    filename += ".jpg";
-  else if(type == "OBJ")
-    filename += ".obj";
-  return filename;
-}
-
-void MeshImport::setMeshFile(const QString& filename, const QString& type)
-{
-  QFileInfo fi(filename);
-  int tid = 0;
-  // Note: these ids need to match those in importmesh.ui
-  if(type.isEmpty()) {
+  
+  QString MeshImport::properFile(QString filename, const QString& type) const
+  {
+    QFileInfo fi(filename);
     QString suf = fi.suffix();
-    if(suf == "ply")
-      tid = 0;
-    else if(suf == "vtu")
-      tid = 1;
-    else if(suf == "txt")
-      tid = 2;
-    else if(suf == "jpg")
-      tid = 4;
-    else if(suf == "mesh")
-      tid = 5;
-    else if(suf == "obj")
-      tid = 6;
-    ui->MeshFile->setText(filename);
-  } else {
-    if(type == "PLY")
-      tid = 0;
+    if(!suf.isEmpty())
+      filename = filename.left(filename.size() - suf.size() - 1);
+    if(type == "PLY Mesh")
+      filename += ".ply";
     else if(type == "VTK Mesh")
-      tid = 1;
-    else if(type == "Text")
-      tid = 2;
-    else if(type == "Cells")
-      tid = 3;
+      filename += ".vtu";
+    else if(type == "Text" or type == "Cells")
+      filename += ".txt";
+    else if(type == "MeshEdit")
+      filename += ".mesh";
     else if(type == "Keyence")
-      tid = 4;
-    else if(type == "MeshEdit")
-      tid = 5;
+      filename += ".jpg";
     else if(type == "OBJ")
-      tid = 6;
-    ui->MeshFile->setText(properFile(filename, type));
+      filename += ".obj";
+    return filename;
   }
-  ui->MeshType->setCurrentIndex(tid);
-}
-
-// REGISTER_MESH_PROCESS(MeshImport);
-
-bool MeshLoad::initialize(QStringList& parms, QWidget* parent)
-{
-  int meshId = parms[3].toInt();
-  if(!checkState().mesh(MESH_ANY, meshId))
-    return false;
-
-  QDialog dlg(parent);
-  Ui_LoadMeshDialog ui;
-  ui.setupUi(&dlg);
-
-  this->ui = &ui;
-  this->dlg = &dlg;
-
-  QObject::connect(ui.SelectMeshFile, SIGNAL(clicked()), this, SLOT(selectMeshFile()));
-
-  Mesh* mesh = this->mesh(meshId);
-  QString filename = mesh->file();
-  if(filename.isEmpty())
-    filename = parms[0];
-
-  setMeshFile(filename);
-  ui.Transform->setChecked(stringToBool(parms[1]));
-  ui.Add->setChecked(stringToBool(parms[2]));
-
-  bool res = false;
-  if(dlg.exec() == QDialog::Accepted) {
-    parms[0] = ui.MeshFile->text();
-    parms[1] = (ui.Transform->isChecked() ? "yes" : "no");
-    parms[2] = (ui.Add->isChecked() ? "yes" : "no");
-    res = true;
+  
+  void MeshImport::setMeshFile(const QString& filename, const QString& type)
+  {
+    QFileInfo fi(filename);
+    int tid = 0;
+    // Note: these ids need to match those in importmesh.ui
+    if(type.isEmpty()) {
+      QString suf = fi.suffix();
+      if(suf == "ply")
+        tid = 0;
+      else if(suf == "vtu")
+        tid = 1;
+      else if(suf == "txt")
+        tid = 2;
+      else if(suf == "jpg")
+        tid = 4;
+      else if(suf == "mesh")
+        tid = 5;
+      else if(suf == "obj")
+        tid = 6;
+      ui->MeshFile->setText(filename);
+    } else {
+      if(type == "PLY")
+        tid = 0;
+      else if(type == "VTK Mesh")
+        tid = 1;
+      else if(type == "Text")
+        tid = 2;
+      else if(type == "Cells")
+        tid = 3;
+      else if(type == "Keyence")
+        tid = 4;
+      else if(type == "MeshEdit")
+        tid = 5;
+      else if(type == "OBJ")
+        tid = 6;
+      ui->MeshFile->setText(properFile(filename, type));
+    }
+    ui->MeshType->setCurrentIndex(tid);
   }
-  this->ui = 0;
-  this->dlg = 0;
-  return res;
-}
-
-void MeshLoad::selectMeshFile()
-{
-  QString filename = ui->MeshFile->text();
-  filename = QFileDialog::getOpenFileName(dlg, QString("Select mesh file"), filename,
-                                          "Mesh files (*.mgxm);;All files (*.*)", 0, FileDialogOptions);
-  if(!filename.isEmpty()) {
-    if(!QFile::exists(filename)) {
-      QMessageBox::information(dlg, "Error selecting file",
-                               "You must select an existing file. Your selection is ignored.");
-      return;
+  
+  bool MeshLoad::initialize(QStringList& parms, QWidget* parent)
+  {
+    int meshId = parms[3].toInt();
+    if(!checkState().mesh(MESH_ANY, meshId))
+      return false;
+  
+    QDialog dlg(parent);
+    Ui_LoadMeshDialog ui;
+    ui.setupUi(&dlg);
+  
+    this->ui = &ui;
+    this->dlg = &dlg;
+  
+    QObject::connect(ui.SelectMeshFile, SIGNAL(clicked()), this, SLOT(selectMeshFile()));
+  
+    Mesh* mesh = this->mesh(meshId);
+    QString filename = mesh->file();
+    if(filename.isEmpty())
+      filename = parms[0];
+  
+    setMeshFile(filename);
+    ui.Transform->setChecked(stringToBool(parms[1]));
+    ui.Add->setChecked(stringToBool(parms[2]));
+  
+    bool res = false;
+    if(dlg.exec() == QDialog::Accepted) {
+      parms[0] = ui.MeshFile->text();
+      parms[1] = (ui.Transform->isChecked() ? "yes" : "no");
+      parms[2] = (ui.Add->isChecked() ? "yes" : "no");
+      res = true;
     }
-    setMeshFile(filename);
+    this->ui = 0;
+    this->dlg = 0;
+    return res;
   }
-}
-
-void MeshLoad::setMeshFile(const QString& filename) {
-  ui->MeshFile->setText(filename);
-}
-
-bool MeshLoad::operator()(const QStringList& parms)
-{
-  int meshId = parms[3].toInt();
-  if(!checkState().mesh(MESH_ANY, meshId))
-    return false;
-  Mesh* mesh = this->mesh(meshId);
-  bool transform = stringToBool(parms[1]);
-  bool add = stringToBool(parms[2]);
-  bool res = (*this)(mesh, parms[0], transform, add);
-  if(res) {
-    // Show mesh if nothing visible
-    if(!(mesh->isMeshVisible() or mesh->isSurfaceVisible())) {
-      mesh->showSurface();
-      mesh->showMesh();
+  
+  void MeshLoad::selectMeshFile()
+  {
+    QString filename = ui->MeshFile->text();
+    filename = QFileDialog::getOpenFileName(dlg, QString("Select mesh file"), filename,
+                                            "Mesh files (*.mgxm);;All files (*.*)", 0, FileDialogOptions);
+    if(!filename.isEmpty()) {
+      if(!QFile::exists(filename)) {
+        QMessageBox::information(dlg, "Error selecting file",
+                                 "You must select an existing file. Your selection is ignored.");
+        return;
+      }
+      setMeshFile(filename);
     }
-    if(mesh->hasImgTex())
-      mesh->showImage();
-    else
-      mesh->showSignal();
-    mesh->setNormals();
   }
-  return res;
-}
-
-bool MeshLoad::loadMGXM_1_3(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add)
-{
-  return loadMGXM_1_2(file, mesh, scale, transform, add, false);
-}
-
-bool MeshLoad::loadMGXM_1_2(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add, bool has_color)
-{
-  bool is_cells;
-  file.read((char*)&is_cells, sizeof(bool));
-  mesh->setCells(is_cells);
-  return loadMGXM_1_1(file, mesh, scale, transform, add, has_color);
-}
-
-bool MeshLoad::loadMGXM_1_1(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add, bool has_color)
-{
-  file.read((char*)&scale, sizeof(bool));
-  file.read((char*)&transform, sizeof(bool));
-  Point2f signalBounds;
-  file.read((char*)&signalBounds[0], sizeof(float));
-  file.read((char*)&signalBounds[1], sizeof(float));
-  if(signalBounds[0] == signalBounds[1]) {
-    signalBounds[0] = 0;
-    signalBounds[1] = 65535;
+  
+  void MeshLoad::setMeshFile(const QString& filename) {
+    ui->MeshFile->setText(filename);
   }
-  mesh->signalBounds() = signalBounds;
-  uint stringSize;
-  file.read((char*)&stringSize, sizeof(uint));
-  QByteArray string(stringSize, 0);
-  file.read(string.data(), stringSize);
-  mesh->signalUnit() = QString::fromUtf8(string);
-  bool res = loadMGXM_0(file, mesh, scale, transform, add, has_color);
-  if(res and has_color) {
-    float deltaSignal = signalBounds[1] - signalBounds[0];
-    forall(const vertex& v, mesh->graph())
-      v->signal = signalBounds[0] + v->signal * deltaSignal;
+  
+  bool MeshLoad::operator()(const QStringList& parms)
+  {
+    int meshId = parms[3].toInt();
+    if(!checkState().mesh(MESH_ANY, meshId))
+      return false;
+    Mesh* mesh = this->mesh(meshId);
+    bool transform = stringToBool(parms[1]);
+    bool add = stringToBool(parms[2]);
+    bool res = (*this)(mesh, parms[0], transform, add);
+    if(res) {
+      // Show mesh if nothing visible
+      if(!(mesh->isMeshVisible() or mesh->isSurfaceVisible())) {
+        mesh->showSurface();
+        mesh->showMesh();
+      }
+      if(mesh->hasImgTex())
+        mesh->showImage();
+      else
+        mesh->showSignal();
+      mesh->setNormals();
+    }
+    return res;
   }
-  return res;
-}
-
-bool MeshLoad::loadMGXM_1_0(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add, bool )
-{
-  file.read((char*)&scale, sizeof(bool));
-  file.read((char*)&transform, sizeof(bool));
-  return loadMGXM_0(file, mesh, scale, transform, add);
-}
-
-bool MeshLoad::loadMGXM_0(QIODevice& file, Mesh* mesh, bool scale, bool transform, bool add, bool has_color)
-{
-  vvgraph& S = mesh->graph();
-  vertex_map vmap;
-
-  if(!S.empty() and !add)
-    mesh->reset();
-
-  uint hSz, vCnt, vSz, eSz;
-  file.read((char*)&hSz, 4);
-  file.read((char*)&vCnt, 4);
-  file.read((char*)&vSz, 4);
-  file.read((char*)&eSz, 4);
-  bool has_label = vSz >= 4;
-  if(has_label)
-    vSz -= 4;
-  if(has_color) {
-    has_color = vSz >= 4;
-    if(has_color)
-      vSz -= 4;
+  
+  bool MeshLoad::loadMGXM_1_3(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add)
+  {
+    return loadMGXM_1_2(file, mesh, scale, transform, add, false);
   }
-  bool has_signal = vSz >= 4;
-  if(has_signal)
-    vSz -= 4;
-  bool has_type = vSz >= 1;
-  if(has_type)
-    vSz -= 1;
-  bool has_selected = vSz >= 1;
-  if(has_selected)
-    vSz -= 1;
-
-  if(hSz > 0) {
-    std::vector<char> t(hSz);
-    file.read(&t[0], hSz);
+  
+  bool MeshLoad::loadMGXM_1_2(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add, bool has_color)
+  {
+    bool is_cells;
+    file.read((char*)&is_cells, sizeof(bool));
+    mesh->setCells(is_cells);
+    return loadMGXM_1_1(file, mesh, scale, transform, add, has_color);
   }
-  float tmp;
-
-  Progress progress(QString("Loading Mesh %1 from File '%2'").arg(mesh->userId()).arg(mesh->file()), vCnt * 2);
-  // Progress progress(QString("Loading Mesh-%1 - %2").arg(mesh->userId()).arg(mesh->file()), vCnt * 2);
-  int interval = vCnt / 100;
-  if(interval < 1)
-    interval = 1;
-  S.reserve(vCnt);
-  for(uint i = 0; i < vCnt; i++) {
-    if(file.atEnd())
-      throw(QString("Premature end of file reading vertices"));
-    vertex v;
-    S.insert(v);
-    file.read((char*)&v->saveId, 4);
-    file.read((char*)&v->pos, 12);
-    v->pos = realPos(v->pos, scale, transform, mesh);
+  
+  bool MeshLoad::loadMGXM_1_1(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add, bool has_color)
+  {
+    file.read((char*)&scale, sizeof(bool));
+    file.read((char*)&transform, sizeof(bool));
+    Point2f signalBounds;
+    file.read((char*)&signalBounds[0], sizeof(float));
+    file.read((char*)&signalBounds[1], sizeof(float));
+    if(signalBounds[0] == signalBounds[1]) {
+      signalBounds[0] = 0;
+      signalBounds[1] = 65535;
+    }
+    mesh->signalBounds() = signalBounds;
+    uint stringSize;
+    file.read((char*)&stringSize, sizeof(uint));
+    QByteArray string(stringSize, 0);
+    file.read(string.data(), stringSize);
+    mesh->signalUnit() = QString::fromUtf8(string);
+    bool res = loadMGXM_0(file, mesh, scale, transform, add, has_color);
+    if(res and has_color) {
+      float deltaSignal = signalBounds[1] - signalBounds[0];
+      forall(const vertex& v, mesh->graph())
+        v->signal = signalBounds[0] + v->signal * deltaSignal;
+    }
+    return res;
+  }
+  
+  bool MeshLoad::loadMGXM_1_0(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add, bool )
+  {
+    file.read((char*)&scale, sizeof(bool));
+    file.read((char*)&transform, sizeof(bool));
+    return loadMGXM_0(file, mesh, scale, transform, add);
+  }
+  
+  bool MeshLoad::loadMGXM_0(QIODevice& file, Mesh* mesh, bool scale, bool transform, bool add, bool has_color)
+  {
+    vvgraph& S = mesh->graph();
+    vertex_map vmap;
+  
+    if(!S.empty() and !add)
+      mesh->reset();
+  
+    uint hSz, vCnt, vSz, eSz;
+    file.read((char*)&hSz, 4);
+    file.read((char*)&vCnt, 4);
+    file.read((char*)&vSz, 4);
+    file.read((char*)&eSz, 4);
+    bool has_label = vSz >= 4;
     if(has_label)
-      file.read((char*)&v->label, 4);
-    if(has_color or has_signal)
-      file.read((char*)&v->signal, 4);
-    if(has_color and has_signal)
-      file.read((char*)&tmp, 4);
+      vSz -= 4;
+    if(has_color) {
+      has_color = vSz >= 4;
+      if(has_color)
+        vSz -= 4;
+    }
+    bool has_signal = vSz >= 4;
+    if(has_signal)
+      vSz -= 4;
+    bool has_type = vSz >= 1;
     if(has_type)
-      file.read((char*)&v->type, 1);
+      vSz -= 1;
+    bool has_selected = vSz >= 1;
     if(has_selected)
-      file.read((char*)&v->selected, 1);
-    if(vSz > 0) {
-      std::vector<char> t(vSz);
-      file.read(&t[0], vSz);
+      vSz -= 1;
+  
+    if(hSz > 0) {
+      std::vector<char> t(hSz);
+      file.read(&t[0], hSz);
     }
-    vmap[v->saveId] = v;
-    if(v->label > mesh->viewLabel())
-      mesh->setLabel(v->label);
-    if((i % interval == 0)and !progress.advance(i))
-      userCancel();
-  }
-  for(uint i = 0; i < vCnt; i++) {
-    if(file.atEnd())
-      throw(QString("Premature end of file reading neighborhoods"));
-    uint vId, nCnt;
-    file.read((char*)&vId, 4);
-    file.read((char*)&nCnt, 4);
-    if(eSz > 0) {
-      std::vector<char> t(eSz);
-      file.read(&t[0], eSz);
+    float tmp;
+  
+    Progress progress(QString("Loading Mesh %1 from File '%2'").arg(mesh->userId()).arg(mesh->file()), vCnt * 2);
+    // Progress progress(QString("Loading Mesh-%1 - %2").arg(mesh->userId()).arg(mesh->file()), vCnt * 2);
+    int interval = vCnt / 100;
+    if(interval < 1)
+      interval = 1;
+    S.reserve(vCnt);
+    for(uint i = 0; i < vCnt; i++) {
+      if(file.atEnd())
+        throw(QString("Premature end of file reading vertices"));
+      vertex v;
+      S.insert(v);
+      file.read((char*)&v->saveId, 4);
+      file.read((char*)&v->pos, 12);
+      v->pos = realPos(v->pos, scale, transform, mesh);
+      if(has_label)
+        file.read((char*)&v->label, 4);
+      if(has_color or has_signal)
+        file.read((char*)&v->signal, 4);
+      if(has_color and has_signal)
+        file.read((char*)&tmp, 4);
+      if(has_type)
+        file.read((char*)&v->type, 1);
+      if(has_selected)
+        file.read((char*)&v->selected, 1);
+      if(vSz > 0) {
+        std::vector<char> t(vSz);
+        file.read(&t[0], vSz);
+      }
+      vmap[v->saveId] = v;
+      if(v->label > mesh->viewLabel())
+        mesh->setLabel(v->label);
+      if((i % interval == 0)and !progress.advance(i))
+        userCancel();
     }
-    vertex_map::const_iterator vit = vmap.find(vId);
-    if(vit == vmap.end())
-      throw QString("Invalid vertex id: %1").arg(vId);
-    vertex v = vit->second;
-    vertex pn(0);
-    for(uint j = 0; j < nCnt; j++) {
-      uint nId;
-      file.read((char*)&nId, 4);
-      vertex_map::const_iterator nit = vmap.find(nId);
+    for(uint i = 0; i < vCnt; i++) {
+      if(file.atEnd())
+        throw(QString("Premature end of file reading neighborhoods"));
+      uint vId, nCnt;
+      file.read((char*)&vId, 4);
+      file.read((char*)&nCnt, 4);
+      if(eSz > 0) {
+        std::vector<char> t(eSz);
+        file.read(&t[0], eSz);
+      }
+      vertex_map::const_iterator vit = vmap.find(vId);
       if(vit == vmap.end())
-        throw QString("Invalid vertex id: %1").arg(nId);
-      vertex n = nit->second;
-      if(S.valence(v) == 0)
-        S.insertEdge(v, n);
-      else
-        S.spliceAfter(v, pn, n);
-      pn = n;
+        throw QString("Invalid vertex id: %1").arg(vId);
+      vertex v = vit->second;
+      vertex pn(0);
+      for(uint j = 0; j < nCnt; j++) {
+        uint nId;
+        file.read((char*)&nId, 4);
+        vertex_map::const_iterator nit = vmap.find(nId);
+        if(vit == vmap.end())
+          throw QString("Invalid vertex id: %1").arg(nId);
+        vertex n = nit->second;
+        if(S.valence(v) == 0)
+          S.insertEdge(v, n);
+        else
+          S.spliceAfter(v, pn, n);
+        pn = n;
+      }
+      if((i % interval) == 0 and !progress.advance(vCnt + i))
+        userCancel();
     }
-    if((i % interval) == 0 and !progress.advance(vCnt + i))
+    if(!progress.advance(2 * vCnt))
       userCancel();
+    return true;
   }
-  if(!progress.advance(2 * vCnt))
-    userCancel();
-  return true;
-}
-
-namespace {
-// Returns true if the mesh is a cell mesh
-bool checkCells(Mesh* mesh)
-{
-  const vvgraph& S = mesh->graph();
-  forall(const vertex& v, S) {
-    if(v->type == 'j') {
-      char prev = S.prevTo(v, S.anyIn(v))->type;
-      bool has_cell = false;
-      forall(const vertex& n, S.neighbors(v)) {
-        if(n->type == 'c') {
-          if(prev == 'c')
+  
+  namespace {
+  // Returns true if the mesh is a cell mesh
+  bool checkCells(Mesh* mesh)
+  {
+    const vvgraph& S = mesh->graph();
+    forall(const vertex& v, S) {
+      if(v->type == 'j') {
+        char prev = S.prevTo(v, S.anyIn(v))->type;
+        bool has_cell = false;
+        forall(const vertex& n, S.neighbors(v)) {
+          if(n->type == 'c') {
+            if(prev == 'c')
+              return false;
+            has_cell = true;
+          }
+          prev = n->type;
+        }
+        if(not has_cell)
+          return false;
+      } else if(v->type == 'c') {
+        forall(const vertex& n, S.neighbors(v))
+          if(n->type != 'j')
             return false;
-          has_cell = true;
-        }
-        prev = n->type;
-      }
-      if(not has_cell)
+      } else
         return false;
-    } else if(v->type == 'c') {
-      forall(const vertex& n, S.neighbors(v))
-        if(n->type != 'j')
-          return false;
-    } else
-      return false;
+    }
+    return true;
   }
-  return true;
-}
-} // namespace
-
-void MeshLoad::findSignalBounds(Mesh* mesh)
-{
-  vvgraph& S = mesh->graph();
-  float minSignal = FLT_MAX, maxSignal = -FLT_MAX;
-  forall(const vertex& v, S) {
-    float s = v->signal;
-    if(s > maxSignal)
-      maxSignal = s;
-    if(s < minSignal)
-      minSignal = s;
+  } // namespace
+  
+  void MeshLoad::findSignalBounds(Mesh* mesh)
+  {
+    vvgraph& S = mesh->graph();
+    float minSignal = FLT_MAX, maxSignal = -FLT_MAX;
+    forall(const vertex& v, S) {
+      float s = v->signal;
+      if(s > maxSignal)
+        maxSignal = s;
+      if(s < minSignal)
+        minSignal = s;
+    }
+    if(minSignal == maxSignal)
+      minSignal -= 1;
+    mesh->signalBounds() = Point2f(minSignal, maxSignal);
   }
-  if(minSignal == maxSignal)
-    minSignal -= 1;
-  mesh->signalBounds() = Point2f(minSignal, maxSignal);
-}
-
-bool MeshLoad::operator()(Mesh* mesh, QString filename, bool transform, bool add)
-{
-  QFile file(filename);
-  if(!file.open(QIODevice::ReadOnly)) {
-    setErrorMessage(QString("loadMesh::Error:Cannot open input file: %1").arg(filename));
-    return false;
-  }
-
-  char magic[9];
-  char magic_check[9] = "MGX MESH";
-  file.read(magic, 8);
-  magic[8] = 0;
-  bool scale;
-  if(strcmp(magic, magic_check) == 0) {
-    scale = false;
-    if(!loadMGXM_0(file, mesh, scale, transform, add))
+  
+  bool MeshLoad::operator()(Mesh* mesh, QString filename, bool transform, bool add)
+  {
+    QFile file(filename);
+    if(!file.open(QIODevice::ReadOnly)) {
+      setErrorMessage(QString("loadMesh::Error:Cannot open input file: %1").arg(filename));
       return false;
-    findSignalBounds(mesh);
-  } else {
-    file.seek(0);
-    file.read(magic, 5);
-    if(magic[4] == ' ')
-      magic[4] = 0;
-    if(strcmp(magic, "MGXM") == 0) {
-      QList<int> version = extractVersion(file);
-      if(version.size() != 2) {
-        QStringList str;
-        foreach(int i, version)
-        str << QString::number(i);
-        throw QString("MeshLoad::Error:Invalid file version format (%1), expected: MAJOR.MINOR")
-              .arg(str.join("."));
-      }
-      bool success = false;
-      switch(version[0]) {
-      case 1:
-        switch(version[1]) {
-        case 0:
-          success = loadMGXM_1_0(file, mesh, scale, transform, add);
-          mesh->setCells(checkCells(mesh));
-          findSignalBounds(mesh);
-          break;
+    }
+    char magic[9];
+    char magic_check[9] = "MGX MESH";
+    file.read(magic, 8);
+    magic[8] = 0;
+    bool scale;
+    if(strcmp(magic, magic_check) == 0) {
+      scale = false;
+      if(!loadMGXM_0(file, mesh, scale, transform, add))
+        return false;
+      findSignalBounds(mesh);
+    } else {
+      file.seek(0);
+      file.read(magic, 5);
+      if(magic[4] == ' ')
+        magic[4] = 0;
+      if(strcmp(magic, "MGXM") == 0) {
+        QList<int> version = extractVersion(file);
+        if(version.size() != 2) {
+          QStringList str;
+          foreach(int i, version)
+          str << QString::number(i);
+          throw QString("MeshLoad::Error:Invalid file version format (%1), expected: MAJOR.MINOR")
+                .arg(str.join("."));
+        }
+        bool success = false;
+        switch(version[0]) {
         case 1:
-          success = loadMGXM_1_1(file, mesh, scale, transform, add);
-          mesh->setCells(checkCells(mesh));
+          switch(version[1]) {
+          case 0:
+            success = loadMGXM_1_0(file, mesh, scale, transform, add);
+            mesh->setCells(checkCells(mesh));
+            findSignalBounds(mesh);
+            break;
+          case 1:
+            success = loadMGXM_1_1(file, mesh, scale, transform, add);
+            mesh->setCells(checkCells(mesh));
+            break;
+          case 2:
+            success = loadMGXM_1_2(file, mesh, scale, transform, add);
+            break;
+          case 3:
+            success = loadMGXM_1_3(file, mesh, scale, transform, add);
+            break;
+          default:
+            throw QString(
+                    "MeshLoad::Error:Unknown file version %1.%2, this software recognises up to version 1.0")
+                  .arg(version[0])
+                  .arg(version[1]);
+          }
           break;
-        case 2:
-          success = loadMGXM_1_2(file, mesh, scale, transform, add);
-          break;
-        case 3:
-          success = loadMGXM_1_3(file, mesh, scale, transform, add);
-          break;
         default:
-          throw QString(
-                  "MeshLoad::Error:Unknown file version %1.%2, this software recognises up to version 1.0")
+          throw QString("MeshLoad::Error:Unknown file version %1.%2, this software recognises up to version 1.0")
                 .arg(version[0])
                 .arg(version[1]);
         }
-        break;
-      default:
-        throw QString("MeshLoad::Error:Unknown file version %1.%2, this software recognises up to version 1.0")
-              .arg(version[0])
-              .arg(version[1]);
+        if(!success)
+          return false;
+      } else {
+        setErrorMessage(QString("The file '%1' is not a mgx mesh file").arg(filename));
+        return false;
       }
-      if(!success)
-        return false;
-    } else {
-      setErrorMessage(QString("The file '%1' is not a mgx mesh file").arg(filename));
-      return false;
     }
+    file.close();
+    actingFile(filename);
+    mesh->setFile(filename);
+    mesh->clearImgTex();
+    if(mesh->stack()->empty())
+      mesh->setScaled(scale);
+    else
+      mesh->setScaled(true);
+    mesh->setTransformed(transform);
+    mesh->updateAll();
+    SETSTATUS("Loaded mesh, file:" << mesh->file() << ", vertices:" << mesh->graph().size());
+    return true;
   }
-  file.close();
-  actingFile(filename);
-  mesh->setFile(filename);
-  mesh->clearImgTex();
-  if(mesh->stack()->empty())
-    mesh->setScaled(scale);
-  else
-    mesh->setScaled(true);
-  mesh->setTransformed(transform);
-  mesh->updateAll();
-  SETSTATUS("Loaded mesh, file:" << mesh->file() << ", vertices:" << mesh->graph().size());
-  return true;
-}
-
-// REGISTER_MESH_PROCESS(MeshLoad);
-
-bool LoadAllData::operator()(const QStringList&)
-{
-  if(!(*this)())
-    return false;
-  for(int i = 0; i < stackCount(); ++i) {
-    Stack* s = stack(i);
-    if(s->empty()) {
-      s->main()->hide();
-      s->work()->hide();
+  
+  bool LoadAllData::operator()(const QStringList&)
+  {
+    if(!(*this)())
+      return false;
+    for(int i = 0; i < stackCount(); ++i) {
+      Stack* s = stack(i);
+      if(s->empty()) {
+        s->main()->hide();
+        s->work()->hide();
+      }
     }
-  }
-  for(int i = 0; i < meshCount(); ++i) {
-    Mesh* m = mesh(i);
-    if(m->graph().empty()) {
-      m->hideSurface();
-      m->hideMesh();
-    } else {
-      if(m->toShow() == Mesh::HEAT)
-        m->showNormal();
+    for(int i = 0; i < meshCount(); ++i) {
+      Mesh* m = mesh(i);
+      if(m->graph().empty()) {
+        m->hideSurface();
+        m->hideMesh();
+      } else {
+        if(m->toShow() == Mesh::HEAT)
+          m->showNormal();
+      }
     }
+    return true;
   }
-  return true;
-}
-
-bool LoadAllData::loadStore(Stack* stack, Store* store, QStringList& errors)
-{
-  if(!store->file().isEmpty()) {
-    if(store->file().endsWith(".txt", Qt::CaseInsensitive)) {
-      StackImport importStack(*this);
-      Point3f step;
-      float brightness = 1.f;
-      if(!importStack(stack, store, step, brightness, store->file())) {
-        errors << importStack.errorMessage();
-        return false;
+  
+  bool LoadAllData::loadStore(Stack* stack, Store* store, QStringList& errors)
+  {
+    if(!store->file().isEmpty()) {
+      if(store->file().endsWith(".txt", Qt::CaseInsensitive)) {
+        StackImport importStack(*this);
+        Point3f step;
+        float brightness = 1.f;
+        if(!importStack(stack, store, step, brightness, store->file())) {
+          errors << importStack.errorMessage();
+          return false;
+        }
+      } else {
+        StackOpen openStack(*this);
+        if(!openStack(stack, store, store->file())) {
+          errors << openStack.errorMessage();
+          return false;
+        }
       }
-    } else {
-      StackOpen openStack(*this);
-      if(!openStack(stack, store, store->file())) {
-        errors << openStack.errorMessage();
-        return false;
+    } else
+      store->reset();
+    return true;
+  }
+  
+  bool LoadAllData::operator()()
+  {
+    QStringList errors;
+    for(int i = 0; i < stackCount(); ++i) {
+      Stack* s = stack(i);
+      Store* main = s->main();
+      QString mainFilename = main->file();
+      Store* work = s->work();
+      QString workFilename = work->file();
+      try {
+        main->setFile(mainFilename);
+        if(!loadStore(s, main, errors))
+          main->reset();
       }
-    }
-  } else
-    store->reset();
-  return true;
-}
-
-bool LoadAllData::operator()()
-{
-  QStringList errors;
-  for(int i = 0; i < stackCount(); ++i) {
-    Stack* s = stack(i);
-    Store* main = s->main();
-    QString mainFilename = main->file();
-    Store* work = s->work();
-    QString workFilename = work->file();
-    try {
-      main->setFile(mainFilename);
-      if(!loadStore(s, main, errors))
+      catch(UserCancelException&) {
         main->reset();
-    }
-    catch(UserCancelException&) {
-      main->reset();
-      return true;
-    }
-    try {
-      work->setFile(workFilename);
-      if(!loadStore(s, work, errors))
+        return true;
+      }
+      try {
+        work->setFile(workFilename);
+        if(!loadStore(s, work, errors))
+          work->reset();
+      }
+      catch(UserCancelException&) {
         work->reset();
+        return true;
+      }
+      if(main->file().isEmpty() and work->file().isEmpty()) {
+        s->setSize(Point3u(0, 0, 0));
+        main->reset();
+        work->reset();
+      }
     }
-    catch(UserCancelException&) {
-      work->reset();
-      return true;
-    }
-    if(main->file().isEmpty() and work->file().isEmpty()) {
-      s->setSize(Point3u(0, 0, 0));
-      main->reset();
-      work->reset();
-    }
-  }
-  MeshLoad loadMesh(*this);
-  MeshImport importMesh(*this);
-  for(int i = 0; i < meshCount(); ++i) {
-    Mesh* m = mesh(i);
-    if(!m->file().isEmpty()) {
-      try {
-        QString low_fn = m->file().toLower();
-        if(low_fn.endsWith(".mgxm", Qt::CaseInsensitive)) {
-          if(!loadMesh(m, m->file(), m->transformed(), false)) {
+    MeshLoad loadMesh(*this);
+    MeshImport importMesh(*this);
+    LoadParents loadParents(*this);
+    ResetParents resetParents(*this);
+    for(int i = 0; i < meshCount(); ++i) {
+      Mesh* m = mesh(i);
+      if(!m->file().isEmpty()) {
+        try {
+          QString low_fn = m->file().toLower();
+          if(low_fn.endsWith(".mgxm", Qt::CaseInsensitive)) {
+            if(!loadMesh(m, m->file(), m->transformed(), false)) {
+              m->reset();
+              errors << loadMesh.errorMessage();
+            }
+          } else if(!importMesh(m, m->file(), "", m->scaled(), m->transformed(), false)) {
             m->reset();
-            errors << loadMesh.errorMessage();
+            errors << importMesh.errorMessage();
           }
-        } else if(!importMesh(m, m->file(), "", m->scaled(), m->transformed(), false)) {
-          m->reset();
-          errors << importMesh.errorMessage();
         }
+        catch(UserCancelException&) {
+          m->graph().clear();
+          return true;
+        }
       }
-      catch(UserCancelException&) {
-        m->graph().clear();
-        return true;
+      if(!m->parentFile().isEmpty()) {
+        try {
+          if(!loadParents(m, m->parentFile())) {
+            errors << loadParents.errorMessage();
+            if(!resetParents(m))
+              errors << resetParents.errorMessage();
+          }
+        }
+        catch(UserCancelException&) {
+          // Is this OK in exception handler? It should not fail.
+          if(!resetParents(m))
+            errors << resetParents.errorMessage();
+          return true;
+        }
       }
+
     }
+    if(!errors.empty())
+      setWarningMessage(QString("Warnings:\n  *%1").arg(errors.join("\n  *")));
+    return true;
   }
-  if(!errors.empty())
-    setWarningMessage(QString("Warnings:\n  *%1").arg(errors.join("\n  *")));
-  return true;
-}
+  
+  bool LoadViewFile::operator()(const QStringList& parms) {
+    return (*this)(parms[0]);
+  }
+  
+  bool LoadViewFile::operator()(QString filename)
+  {
+    actingFile(filename, true);
+    bool res = systemCommand(LOAD_VIEW, QStringList() << filename);
+    if(!res) {
+      setErrorMessage("Error while loading view file.");
+      return false;
+    }
+    LoadAllData loaddata(*this);
+    res = loaddata();
+    if(!res)
+      setErrorMessage(loaddata.errorMessage());
+    return res;
+  }
+  
+  bool LoadViewFile::initialize(QStringList& parms, QWidget* parent)
+  {
+    QString filename = parms[0];
+  
+    // Get the file name
+    filename = QFileDialog::getOpenFileName(parent, QString("Select view file"), filename,
+                                            "MorphoGraphX View files (*.mgxv);;All files (*.*)", 0, FileDialogOptions);
+  
+    if(filename.isEmpty())
+      return false;
+  
+    parms[0] = filename;
+    return true;
+  }
+  
+  bool ResetMeshProcess::operator()(const QStringList& parms)
+  {
+    int meshId = parms[0].toInt();
+    if(!checkState().mesh(MESH_ANY, meshId))
+      return false;
+    return operator()(this->mesh(meshId));
+  }
+  
+  bool ResetMeshProcess::operator()(Mesh* m)
+  {
+    m->reset();
+    return true;
+  }
 
-// REGISTER_GLOBAL_PROCESS(LoadAllData);
-
-bool LoadViewFile::operator()(const QStringList& parms) {
-  return (*this)(parms[0]);
-}
-
-bool LoadViewFile::operator()(QString filename)
-{
-  actingFile(filename, true);
-  bool res = systemCommand(LOAD_VIEW, QStringList() << filename);
-  if(!res) {
-    setErrorMessage("Error while loading view file.");
-    return false;
+  bool SaveParents::initialize(QStringList& parms, QWidget* parent)
+  {
+    QString filename
+      = QFileDialog::getSaveFileName(parent, "Select file to save labels in", parms[0], "CSV files (*.csv)");
+    // check filename
+    if(filename.isEmpty())
+      return false;
+    // check ending, add suffix if required
+    QString suffix = ".csv";
+    if(filename.right(suffix.size()) != suffix)
+      filename.append(suffix);
+  
+    parms[0] = filename;
+    return true;
   }
-  LoadAllData loaddata(*this);
-  res = loaddata();
-  if(!res)
-    setErrorMessage(loaddata.errorMessage());
-  return res;
-}
+  
+  bool SaveParents::operator()(Mesh* mesh, const QString& filename)
+  {
+    const IntIntMap& parentLabel = mesh->parentLabelMap();
+    if(parentLabel.size() == 0) {
+      setErrorMessage(QString("There are no parent labels").arg(filename));
+      return false;
+    }
+  
+    // Open output file
+    QFile file(filename);
+    if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
+      setErrorMessage(QString("File '%1' cannot be opened for writing").arg(filename));
+      return false;
+    }
+    QTextStream out(&file);
+    // Write header
+    out << "Label, Parent Label" << endl;
+  
+    // Write data
+    forall(const IntIntPair& p, parentLabel) {
+      int label = p.first;
+      int parent = p.second;
+      out << label << "," << parent << endl;
+    }
+    file.close();
 
-bool LoadViewFile::initialize(QStringList& parms, QWidget* parent)
-{
-  QString filename = parms[0];
+    mesh->setParentFile(filename);
 
-  // Get the file name
-  filename = QFileDialog::getOpenFileName(parent, QString("Select view file"), filename,
-                                          "MorphoGraphX View files (*.mgxv);;All files (*.*)", 0, FileDialogOptions);
+    SETSTATUS("Storing " << parentLabel.size() << " parent labels to file " << filename);
 
-  if(filename.isEmpty())
-    return false;
+    return true;
+  }
+  
+  bool LoadParents::initialize(QStringList& parms, QWidget* parent)
+  {
+    QString filename
+      = QFileDialog::getOpenFileName(parent, "Choose parent label file to load", parms[0], "CSV files (*.csv)");
+  
+    // check file
+    if(filename.isEmpty())
+      return false;
+  
+    QFile file(filename);
+    if(!file.open(QIODevice::ReadOnly)) {
+      QMessageBox::critical(parent, "Error opening file",
+                            QString("File '%1' cannot be opened for reading").arg(filename));
+      return false;
+    }
+    QTextStream ss(&file);
+    QString line = ss.readLine();
+    QStringList fields = line.split(",");
+    if(fields.size() != 2) {
+      QMessageBox::critical(parent, "Error reading file",
+                            QString("File '%1' should be a CSV file with 2 columns").arg(filename));
+      return false;
+    }
+  
+    parms[0] = filename;
+    return true;
+  }
+  
+  bool LoadParents::operator()(Mesh* mesh, const QString& filename)
+  {
+    QFile file(filename);
+    if(!file.open(QIODevice::ReadOnly)) {
+      setErrorMessage(QString("File '%1' cannot be opened for reading").arg(filename));
+      return false;
+    }
+    QTextStream ss(&file);
+    QString line = ss.readLine();
+    QStringList fields = line.split(",");
+    if(fields.size() != 2) {
+      setErrorMessage(QString("File '%1' should be a CSV file with 2 columns").arg(filename));
+      return false;
+    }
+  
+    // read file
+    IntIntMap parentLabel;
+    IntFloatMap labelHeat;
+    int line_nb = 1;
+    while(ss.status() == QTextStream::Ok) {
+      ++line_nb;
+      fields = ss.readLine().split(",");
+      if(fields.size() != 2)
+        break;
+      bool ok;
+      int label = fields[0].toInt(&ok);
+      if(!ok) {
+        setErrorMessage(QString("Error line %1: the first column is not an integer number but '%2'")
+                        .arg(line_nb).arg(fields[0].trimmed()));
+        return false;
+      }
+      int parent = fields[1].toInt(&ok);
+      if(!ok) {
+        setErrorMessage(QString("Error line %1: the second column is not an integer number but '%2'")
+                        .arg(line_nb).arg(fields[1].trimmed()));
+        return false;
+      }
+      parentLabel[label] = parent;
+      labelHeat[label] = 1;
+    }
+  
+    // clear tables related to parents
+    mesh->parentCenter().clear();
+    mesh->parentCenterVis().clear();
+    mesh->parentNormal().clear();
+    mesh->parentNormalVis().clear();
+  
+    // update the parent map
+    mesh->parentLabelMap() = parentLabel;
+    mesh->labelHeat() = labelHeat;
+    mesh->heatMapUnit() = "ON/OFF";
+    mesh->heatMapBounds() = Point2f(0, 1);
+    mesh->setParentFile(filename);
+    mesh->updateTriangles();
 
-  parms[0] = filename;
-  return true;
-}
+    SETSTATUS(parentLabel.size() << " parent labels loaded from file " << filename);
+    return true;
+  }
+  
+  bool ResetParents::operator()(Mesh* mesh)
+  {
+    mesh->parentLabelMap().clear();
+    mesh->parentCenter().clear();
+    mesh->parentCenterVis().clear();
+    mesh->parentNormal().clear();
+    mesh->parentNormalVis().clear();
+    mesh->labelHeat().clear();
+    mesh->setParentFile();
+    mesh->updateTriangles();
+    return true;
+  }
 
-// REGISTER_GLOBAL_PROCESS(LoadViewFile);
-
-bool ResetMeshProcess::operator()(const QStringList& parms)
-{
-  int meshId = parms[0].toInt();
-  if(!checkState().mesh(MESH_ANY, meshId))
-    return false;
-  return operator()(this->mesh(meshId));
-}
-
-bool ResetMeshProcess::operator()(Mesh* m)
-{
-  m->reset();
-  return true;
-}
-} // namespace process
-} // namespace mgx
+}}
Index: PythonProcess.hpp
===================================================================
--- PythonProcess.hpp	(revision 1255)
+++ PythonProcess.hpp	(revision 1256)
@@ -9,97 +9,76 @@
 #include <Python.h>
 #include <string>
 
-namespace mgx {
-namespace process {
+namespace mgx { namespace process 
+{
+  class PythonProcess;
+  
+  struct MGX_EXPORT mgx_Factory {
+    QString type;
+    PythonProcess* process;
+  };
+  
+  struct MGX_EXPORT mgx_Factory_Python {
+    PyObject_HEAD;
+    mgx_Factory intern;
+    PyObject* fact_dict;
+  };
+  
+  struct MGX_EXPORT mgx_Process {
+    QString type;
+    QString name;
+    int numParms;
+    PythonProcess* process;
+  };
+  
+  struct MGX_EXPORT mgx_Process_Python {
+    PyObject_HEAD;
+    PyObject* descr;
+    mgx_Process intern;
+  };
+  
+  extern MGX_EXPORT PyTypeObject factory_type;
+  extern MGX_EXPORT PyTypeObject process_type;
+  
+  /**
+   * \class PythonProcess PythonProcess.hpp <PythonProcess.hpp>
+   *
+   * This process evaluate a Python script from which other processes can be called.
+   *
+   * \ingroup GlobalProcess
+   */
+  class MGX_EXPORT PythonProcess : public GlobalProcess {
+  public:
+    PythonProcess(const GlobalProcess& process) : Process(process), GlobalProcess(process) {}
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    bool operator()(const QStringList& parms) 
+    { 
+      return (*this)(parms[0]); 
+    }
 
-class PythonProcess;
+    bool operator()(QString filename); 
 
-struct MGX_EXPORT mgx_Factory {
-  QString type;
-  PythonProcess* process;
-};
+    QString name() const { return "Python Script"; }
+    QString folder() const { return "Python"; }
+    QString description() const { return "Run python script"; }
+    QStringList parmNames() const { return QStringList() << "Script"; }
+    QStringList parmDescs() const { return QStringList() << "Script"; }
+    QStringList parmDefaults() const { return QStringList() << ""; }
+    QIcon icon() const { return QIcon(":/images/Python.png"); }
+  
+    mgx_Process_Python* createProcess(const QString& type, const QString& name);
+  
+  protected:
+    bool initPython(const QString& filename);
+    bool finalizePython();
+    bool addFactory(char* name);
+    bool removeFactory(char* name);
+    QString getTraceBack(PyObject* tb, int limit);
+  
+    PyObject* module, *main, *main_dict;
+  };
 
-struct MGX_EXPORT mgx_Factory_Python {
-  PyObject_HEAD;
-  mgx_Factory intern;
-  PyObject* fact_dict;
-};
-
-struct MGX_EXPORT mgx_Process {
-  QString type;
-  QString name;
-  int numParms;
-  // int nbNamedStrings;
-  // int nbNamedValues;
-  PythonProcess* process;
-};
-
-struct MGX_EXPORT mgx_Process_Python {
-  PyObject_HEAD;
-  PyObject* descr;
-  mgx_Process intern;
-};
-
-extern MGX_EXPORT PyTypeObject factory_type;
-extern MGX_EXPORT PyTypeObject process_type;
-
-/**
- * \class PythonProcess PythonProcess.hpp <PythonProcess.hpp>
- *
- * This process evaluate a Python script from which other processes can be called.
- *
- * \ingroup GlobalProcess
- */
-class MGX_EXPORT PythonProcess : public GlobalProcess {
-public:
-  PythonProcess(const GlobalProcess& process)
-    : Process(process)
-    , GlobalProcess(process)
-  {
-  }
-
-  bool initialize(QStringList& parms, QWidget* parent);
-
-  bool operator()(const QStringList& parms) {
-    return (*this)(parms[0]);
-  }
-
-  bool operator()(QString filename);
-
-  QString name() const {
-    return "Python Script";
-  }
-  QString folder() const {
-    return "Python";
-  }
-  QString description() const {
-    return "Run python script";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Script";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Script";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/Python.png");
-  }
-
-  mgx_Process_Python* createProcess(const QString& type, const QString& name);
-
-protected:
-  bool initPython(const QString& filename);
-  bool finalizePython();
-  bool addFactory(char* name);
-  bool removeFactory(char* name);
-  QString getTraceBack(PyObject* tb, int limit);
-
-  PyObject* module, *main, *main_dict;
-};
-} // namespace process
-} // namespace mgx
-
-#endif // PYTHONPROCESS_HPP
+}}
+#endif
Index: MorphoViewer.hpp
===================================================================
--- MorphoViewer.hpp	(revision 1255)
+++ MorphoViewer.hpp	(revision 1256)
@@ -11,6 +11,7 @@
 #include <MGXViewer/qglviewer.h>
 #include <Shader.hpp>
 #include <VertexData.hpp>
+#include <Geometry.hpp>
 
 #include <QtGui>
 
@@ -33,10 +34,13 @@
 
   void wheelEvent(QWheelEvent* const event, qglviewer::Camera* const camera);
 
-  float zoom() const {
+  float zoom() const 
+  {
     return _zoom;
   }
-  void setZoom(float z) {
+
+  void setZoom(float z) 
+  {
     _zoom = z;
   }
 
@@ -44,7 +48,8 @@
   float _zoom;
 };
 
-class MGXCamera : public qglviewer::Camera {
+class MGXCamera : public qglviewer::Camera 
+{
 public:
   MGXCamera();
 
@@ -64,17 +69,23 @@
 
   virtual void drawAllPaths();
 
-  float zoom() const {
+  float zoom() const 
+  {
     return _frame->zoom();
   }
-  void setZoom(float z) {
+
+  void setZoom(float z) 
+  {
     _frame->setZoom(z);
   }
 
-  MGXCameraFrame* frame() {
+  MGXCameraFrame* frame() 
+  {
     return _frame;
   }
-  const MGXCameraFrame* frame() const {
+
+  const MGXCameraFrame* frame() const 
+  {
     return _frame;
   }
 
@@ -82,7 +93,8 @@
   MGXCameraFrame* _frame;
 };
 
-class MorphoViewer : public QGLViewer {
+class MorphoViewer : public QGLViewer 
+{
   Q_OBJECT
 public:
   enum FrameIdentity {
@@ -174,6 +186,7 @@
   float Spinning;
   float ZoomFactor() const;
   void setZoomFactor(float f);
+  mgx::Matrix4d CameraFrame;
   MGXCamera* _camera;
 
   MorphoGraphX* mainWindow();
Index: ColorBar.cpp
===================================================================
--- ColorBar.cpp	(revision 1255)
+++ ColorBar.cpp	(revision 1256)
@@ -11,982 +11,883 @@
 #include <QStringList>
 #include <QTextStream>
 
-#ifdef _MSC_VER
-double round(double d) {
-  return floor(d + 0.5);
-}
-#else
 using std::isnan;
-#endif
 
 namespace mgx {
 
-using Information::err;
-
-Point2d toPoint2d(const QPoint& p) {
-  return Point2d(p.x(), p.y());
-}
-
-Point2d toPoint2d(const QPointF& p) {
-  return Point2d(p.x(), p.y());
-}
-
-Colorbar::Colorbar(Position pos)
-  : font()   //"Monospace")
-  , prev_width(-1)
-  , prev_height(-1)
-{
-  // font.setStyleHint(QFont::TypeWriter);
-  font.setStyleStrategy(QFont::OpenGLCompatible);
-  font.setStyleStrategy(QFont::PreferAntialias);
-  position = pos;
-  vmin = 0;
-  vmax = 1;
-
-  scale_length = 0.3;
-  width = 20;
-  distance_to_border = 5;
-  text_to_bar = 5;
-  tick_size = 2;
-  exp_size = 0.7;
-  epsilon = 1e-9;
-  line_width = 2;
-  globalScaling = 1.0;
-}
-
-void limit_rect(QRectF& rect, const QSize& size, double lim_width, double lim_height)
-{
-  if(rect.left() < lim_width) {
-    rect.moveLeft(lim_width);
-    if(size.width() - rect.right() < lim_width)
-      rect.setRight(size.width() - lim_width);
-  } else if(size.width() - rect.right() < lim_width) {
-    rect.moveRight(size.width() - lim_width);
-    if(rect.left() < lim_width)
-      rect.setLeft(lim_width);
+  using Information::err;
+  
+  Point2d toPoint2d(const QPoint& p) {
+    return Point2d(p.x(), p.y());
   }
-  if(rect.top() < lim_height) {
-    rect.moveTop(lim_height);
-    if(size.height() - rect.bottom() < lim_height)
-      rect.setBottom(size.height() - lim_height);
-  } else if(size.height() - rect.bottom() < lim_height) {
-    rect.moveBottom(size.height() - lim_height);
-    if(rect.top() < lim_height)
-      rect.setTop(lim_height);
+  
+  Point2d toPoint2d(const QPointF& p) {
+    return Point2d(p.x(), p.y());
   }
-}
-
-/*
-   #define ISENABLED(attr) if(glIsEnabled(attr)) DEBUG_OUT << #attr << endl
-
-   static void checkOpenGLState()
-   {
-   ISENABLED(GL_ALPHA_TEST);
-   ISENABLED(GL_AUTO_NORMAL);
-   ISENABLED(GL_BLEND);
-   ISENABLED(GL_CLIP_PLANE0);
-   ISENABLED(GL_CLIP_PLANE1);
-   ISENABLED(GL_CLIP_PLANE2);
-   ISENABLED(GL_CLIP_PLANE3);
-   ISENABLED(GL_CLIP_PLANE4);
-   ISENABLED(GL_CLIP_PLANE5);
-   ISENABLED(GL_COLOR_ARRAY);
-   ISENABLED(GL_COLOR_LOGIC_OP);
-   ISENABLED(GL_COLOR_MATERIAL);
-   ISENABLED(GL_COLOR_SUM);
-   ISENABLED(GL_COLOR_TABLE);
-   ISENABLED(GL_CONVOLUTION_1D);
-   ISENABLED(GL_CONVOLUTION_2D);
-   ISENABLED(GL_CULL_FACE);
-   ISENABLED(GL_DEPTH_TEST);
-   ISENABLED(GL_DITHER);
-   ISENABLED(GL_EDGE_FLAG_ARRAY);
-   ISENABLED(GL_FOG);
-   ISENABLED(GL_HISTOGRAM);
-   ISENABLED(GL_INDEX_ARRAY);
-   ISENABLED(GL_INDEX_LOGIC_OP);
-   ISENABLED(GL_LIGHTING);
-   ISENABLED(GL_LIGHT0);
-   ISENABLED(GL_LIGHT1);
-   ISENABLED(GL_LIGHT2);
-   ISENABLED(GL_LIGHT3);
-   ISENABLED(GL_LIGHT4);
-   ISENABLED(GL_LIGHT5);
-   ISENABLED(GL_LIGHT6);
-   ISENABLED(GL_LINE_SMOOTH);
-   ISENABLED(GL_LINE_STIPPLE);
-   ISENABLED(GL_MAP1_COLOR_4);
-   ISENABLED(GL_MAP1_INDEX);
-   ISENABLED(GL_MAP1_NORMAL);
-   ISENABLED(GL_MAP1_TEXTURE_COORD_1);
-   ISENABLED(GL_MAP1_TEXTURE_COORD_2);
-   ISENABLED(GL_MAP1_TEXTURE_COORD_3);
-   ISENABLED(GL_MAP1_TEXTURE_COORD_4);
-   ISENABLED(GL_MAP2_COLOR_4);
-   ISENABLED(GL_MAP2_INDEX);
-   ISENABLED(GL_MAP2_NORMAL);
-   ISENABLED(GL_MAP2_TEXTURE_COORD_1);
-   ISENABLED(GL_MAP2_TEXTURE_COORD_2);
-   ISENABLED(GL_MAP2_TEXTURE_COORD_3);
-   ISENABLED(GL_MAP2_TEXTURE_COORD_4);
-   ISENABLED(GL_MAP2_VERTEX_3);
-   ISENABLED(GL_MAP2_VERTEX_4);
-   ISENABLED(GL_MINMAX);
-   ISENABLED(GL_MULTISAMPLE);
-   ISENABLED(GL_NORMAL_ARRAY);
-   ISENABLED(GL_NORMALIZE);
-   ISENABLED(GL_POINT_SMOOTH);
-   ISENABLED(GL_POINT_SPRITE);
-   ISENABLED(GL_POLYGON_SMOOTH);
-   ISENABLED(GL_POLYGON_OFFSET_FILL);
-   ISENABLED(GL_POLYGON_OFFSET_LINE);
-   ISENABLED(GL_POLYGON_OFFSET_POINT);
-   ISENABLED(GL_POLYGON_SMOOTH);
-   ISENABLED(GL_POLYGON_STIPPLE);
-   ISENABLED(GL_POST_COLOR_MATRIX_COLOR_TABLE);
-   ISENABLED(GL_POST_CONVOLUTION_COLOR_TABLE);
-   ISENABLED(GL_RESCALE_NORMAL);
-   ISENABLED(GL_SAMPLE_ALPHA_TO_COVERAGE);
-   ISENABLED(GL_SAMPLE_ALPHA_TO_ONE);
-   ISENABLED(GL_SAMPLE_COVERAGE);
-   ISENABLED(GL_SCISSOR_TEST);
-   ISENABLED(GL_SEPARABLE_2D);
-   ISENABLED(GL_STENCIL_TEST);
-   ISENABLED(GL_TEXTURE_1D);
-   ISENABLED(GL_TEXTURE_2D);
-   ISENABLED(GL_TEXTURE_3D);
-   ISENABLED(GL_TEXTURE_CUBE_MAP);
-   ISENABLED(GL_TEXTURE_COORD_ARRAY);
-   ISENABLED(GL_TEXTURE_GEN_Q);
-   ISENABLED(GL_TEXTURE_GEN_R);
-   ISENABLED(GL_TEXTURE_GEN_S);
-   ISENABLED(GL_TEXTURE_GEN_T);
-   ISENABLED(GL_VERTEX_ARRAY);
-   ISENABLED(GL_VERTEX_PROGRAM_POINT_SIZE);
-   ISENABLED(GL_VERTEX_PROGRAM_TWO_SIDE);
-   }
- */
-
-void Colorbar::draw(QGLViewer* viewer, GLuint texId, QPaintDevice* device) const
-{
-  if(device == 0)
-    device = viewer;
-  if(vmin == vmax)
-    return;
-  if(fabs(vmin - vmax) / (fabs(vmin) + fabs(vmax)) < epsilon)
-    return;
-  if(!finite(vmin) or !finite(vmax))
-    return;
-  glPushAttrib(GL_ALL_ATTRIB_BITS);
-  glDisable(GL_LIGHTING);
-  glDisable(GL_LIGHT0);
-  glDisable(GL_LIGHT1);
-  glDisable(GL_LIGHT2);
-  glDisable(GL_LIGHT3);
-  glDisable(GL_DITHER);
-  glDisable(GL_DEPTH_TEST);
-  glDisable(GL_CULL_FACE);
-  glDisable(GL_POLYGON_OFFSET_FILL);
-  glDisable(GL_POLYGON_OFFSET_POINT);
-  glDisable(GL_POLYGON_OFFSET_LINE);
-  glDisable(GL_AUTO_NORMAL);
-
-  glColor3f(1, 1, 1);
-
-  startScreenCoordinatesSystem(device);
-  do {
-    DEBUG_OUTPUT("***** START Colorbar::draw ******" << endl);
-    double w = device->width() / globalScaling;
-    double h = device->height() / globalScaling;
-
-    if(w == 0 or h == 0) {
-      DEBUG_OUTPUT("Zero-sized device" << endl);
-      break;
+  
+  Colorbar::Colorbar(Position pos) : font(), prev_width(-1), prev_height(-1)
+  {
+    // font.setStyleHint(QFont::TypeWriter);
+    font.setStyleStrategy(QFont::OpenGLCompatible);
+    font.setStyleStrategy(QFont::PreferAntialias);
+    position = pos;
+    vmin = 0;
+    vmax = 1;
+  
+    scale_length = 0.3;
+    width = 20;
+    distance_to_border = 5;
+    text_to_bar = 5;
+    tick_size = 2;
+    exp_size = 0.7;
+    epsilon = 1e-9;
+    line_width = 2;
+    globalScaling = 1.0;
+  }
+  
+  void limit_rect(QRectF& rect, const QSize& size, double lim_width, double lim_height)
+  {
+    if(rect.left() < lim_width) {
+      rect.moveLeft(lim_width);
+      if(size.width() - rect.right() < lim_width)
+        rect.setRight(size.width() - lim_width);
+    } else if(size.width() - rect.right() < lim_width) {
+      rect.moveRight(size.width() - lim_width);
+      if(rect.left() < lim_width)
+        rect.setLeft(lim_width);
     }
-
-    // First, find the position of the scale bar
-    QFontMetricsF metric(font, device);
-    QStringList font_test;
-    double lim_width = 0;
-    for(int i = 0; i < 10; ++i) {
-      QString s = QString::number(i);
-      font_test << s + s + s + s + s;
+    if(rect.top() < lim_height) {
+      rect.moveTop(lim_height);
+      if(size.height() - rect.bottom() < lim_height)
+        rect.setBottom(size.height() - lim_height);
+    } else if(size.height() - rect.bottom() < lim_height) {
+      rect.moveBottom(size.height() - lim_height);
+      if(rect.top() < lim_height)
+        rect.setTop(lim_height);
     }
-
-    forall(QString t, font_test) {
-      lim_width = std::max(lim_width, metric.width(t));
-    }
-    double lim_height = 3 * metric.height();
-    double shift_length;
-    switch(position) {
-    case TOP:
-    case BOTTOM:
-      shift_length = w * (1 - scale_length) / 2;
-      break;
-    case LEFT:
-    case RIGHT:
-      shift_length = h * (1 - scale_length) / 2;
-      break;
-    default:
-      shift_length = distance_to_border;
-    }
-
-    double delta_value = vmax - vmin;
-    double shift_width = distance_to_border;
-
-    QSize size(w, h);
-
-    Point2d start_pos, end_pos, next_side;
-    QRectF scale_rect;
-
-    switch(position) {
-    case TOP: {
-      scale_rect = QRectF(shift_length, shift_width, scale_length * w, width);
-      limit_rect(scale_rect, size, lim_width, lim_height);
-      start_pos = toPoint2d(scale_rect.bottomLeft());
-      end_pos = toPoint2d(scale_rect.bottomRight());
-      next_side = toPoint2d(scale_rect.topRight() - scale_rect.bottomRight());
-    } break;
-    case RIGHT: {
-      scale_rect = QRectF(w - shift_width - width, shift_length, width, scale_length * h);
-      limit_rect(scale_rect, size, lim_width, lim_height);
-      start_pos = toPoint2d(scale_rect.bottomLeft());
-      end_pos = toPoint2d(scale_rect.topLeft());
-      next_side = toPoint2d(scale_rect.bottomRight() - scale_rect.bottomLeft());
-    } break;
-    case BOTTOM: {
-      scale_rect = QRectF(shift_length, h - shift_width - width, scale_length * w, width);
-      limit_rect(scale_rect, size, lim_width, lim_height);
-      start_pos = toPoint2d(scale_rect.topLeft());
-      end_pos = toPoint2d(scale_rect.topRight());
-      next_side = toPoint2d(scale_rect.bottomRight() - scale_rect.topRight());
-    } break;
-    case LEFT: {
-      scale_rect = QRectF(shift_width, shift_length, width, scale_length * h);
-      limit_rect(scale_rect, size, lim_width, lim_height);
-      start_pos = toPoint2d(scale_rect.bottomRight());
-      end_pos = toPoint2d(scale_rect.topRight());
-      next_side = toPoint2d(scale_rect.bottomLeft() - scale_rect.bottomRight());
-    } break;
-    case TOP_LEFT: {
-      if(orientation == HORIZONTAL) {
+  }
+  
+  void Colorbar::draw(QGLViewer* viewer, GLuint texId, QPaintDevice* device) const
+  {
+    if(device == 0)
+      device = viewer;
+    if(vmin == vmax)
+      return;
+    if(fabs(vmin - vmax) / (fabs(vmin) + fabs(vmax)) < epsilon)
+      return;
+    if(!finite(vmin) or !finite(vmax))
+      return;
+    glPushAttrib(GL_ALL_ATTRIB_BITS);
+    glDisable(GL_LIGHTING);
+    glDisable(GL_LIGHT0);
+    glDisable(GL_LIGHT1);
+    glDisable(GL_LIGHT2);
+    glDisable(GL_LIGHT3);
+    glDisable(GL_DITHER);
+    glDisable(GL_DEPTH_TEST);
+    glDisable(GL_CULL_FACE);
+    glDisable(GL_POLYGON_OFFSET_FILL);
+    glDisable(GL_POLYGON_OFFSET_POINT);
+    glDisable(GL_POLYGON_OFFSET_LINE);
+    glDisable(GL_AUTO_NORMAL);
+  
+    glColor3f(1, 1, 1);
+  
+    startScreenCoordinatesSystem(device);
+    do {
+      DEBUG_OUTPUT("***** START Colorbar::draw ******" << endl);
+      double w = device->width() / globalScaling;
+      double h = device->height() / globalScaling;
+  
+      if(w == 0 or h == 0) {
+        DEBUG_OUTPUT("Zero-sized device" << endl);
+        break;
+      }
+  
+      // First, find the position of the scale bar
+      QFontMetricsF metric(font, device);
+      QStringList font_test;
+      double lim_width = 0;
+      for(int i = 0; i < 10; ++i) {
+        QString s = QString::number(i);
+        font_test << s + s + s + s + s;
+      }
+  
+      forall(QString t, font_test) {
+        lim_width = std::max(lim_width, metric.width(t));
+      }
+      double lim_height = 3 * metric.height();
+      double shift_length;
+      switch(position) {
+      case TOP:
+      case BOTTOM:
+        shift_length = w * (1 - scale_length) / 2;
+        break;
+      case LEFT:
+      case RIGHT:
+        shift_length = h * (1 - scale_length) / 2;
+        break;
+      default:
+        shift_length = distance_to_border;
+      }
+  
+      double delta_value = vmax - vmin;
+      double shift_width = distance_to_border;
+  
+      QSize size(w, h);
+  
+      Point2d start_pos, end_pos, next_side;
+      QRectF scale_rect;
+  
+      switch(position) {
+      case TOP: {
         scale_rect = QRectF(shift_length, shift_width, scale_length * w, width);
         limit_rect(scale_rect, size, lim_width, lim_height);
         start_pos = toPoint2d(scale_rect.bottomLeft());
         end_pos = toPoint2d(scale_rect.bottomRight());
         next_side = toPoint2d(scale_rect.topRight() - scale_rect.bottomRight());
-      } else {
-        scale_rect = QRectF(shift_width, shift_length, width, scale_length * h);
-        limit_rect(scale_rect, size, lim_width, lim_height);
-        start_pos = toPoint2d(scale_rect.bottomRight());
-        end_pos = toPoint2d(scale_rect.topRight());
-        next_side = toPoint2d(scale_rect.bottomLeft() - scale_rect.bottomRight());
-      }
-    } break;
-    case TOP_RIGHT: {
-      if(orientation == HORIZONTAL) {
-        scale_rect = QRectF(w * (1 - scale_length) - shift_length, shift_width, scale_length * w, width);
-        limit_rect(scale_rect, size, lim_width, lim_height);
-        start_pos = toPoint2d(scale_rect.bottomLeft());
-        end_pos = toPoint2d(scale_rect.bottomRight());
-        next_side = toPoint2d(scale_rect.topRight() - scale_rect.bottomRight());
-      } else {
+      } break;
+      case RIGHT: {
         scale_rect = QRectF(w - shift_width - width, shift_length, width, scale_length * h);
         limit_rect(scale_rect, size, lim_width, lim_height);
         start_pos = toPoint2d(scale_rect.bottomLeft());
         end_pos = toPoint2d(scale_rect.topLeft());
         next_side = toPoint2d(scale_rect.bottomRight() - scale_rect.bottomLeft());
-      }
-    } break;
-    case BOTTOM_LEFT: {
-      if(orientation == HORIZONTAL) {
+      } break;
+      case BOTTOM: {
         scale_rect = QRectF(shift_length, h - shift_width - width, scale_length * w, width);
         limit_rect(scale_rect, size, lim_width, lim_height);
         start_pos = toPoint2d(scale_rect.topLeft());
         end_pos = toPoint2d(scale_rect.topRight());
         next_side = toPoint2d(scale_rect.bottomRight() - scale_rect.topRight());
-      } else {
-        scale_rect = QRectF(shift_width, h * (1 - scale_length) - shift_length, width, scale_length * h);
+      } break;
+      case LEFT: {
+        scale_rect = QRectF(shift_width, shift_length, width, scale_length * h);
         limit_rect(scale_rect, size, lim_width, lim_height);
         start_pos = toPoint2d(scale_rect.bottomRight());
         end_pos = toPoint2d(scale_rect.topRight());
         next_side = toPoint2d(scale_rect.bottomLeft() - scale_rect.bottomRight());
-      }
-    } break;
-    case BOTTOM_RIGHT: {
-      if(orientation == HORIZONTAL) {
-        scale_rect
-          = QRectF(w * (1 - scale_length) - shift_length, h - width - shift_width, scale_length * w, width);
-        limit_rect(scale_rect, size, lim_width, lim_height);
-        start_pos = toPoint2d(scale_rect.topLeft());
-        end_pos = toPoint2d(scale_rect.topRight());
-        next_side = toPoint2d(scale_rect.bottomRight() - scale_rect.topRight());
-      } else {
-        scale_rect
-          = QRectF(w - shift_width - width, h * (1 - scale_length) - shift_length, width, scale_length * h);
-        limit_rect(scale_rect, size, lim_width, lim_height);
-        start_pos = toPoint2d(scale_rect.bottomLeft());
-        end_pos = toPoint2d(scale_rect.topLeft());
-        next_side = toPoint2d(scale_rect.bottomRight() - scale_rect.bottomLeft());
-      }
-    } break;
-    default:
-      break;
-    }
-    if(scale_rect.width() == 0 or scale_rect.height() == 0) {
-      DEBUG_OUTPUT("Zero-size colorbar" << endl);
-      break;
-    }
-    Point2d shift_pos = (end_pos - start_pos) / delta_value;
-    double length;
-    if(orientation == VERTICAL)
-      length = scale_rect.height();
-    else
-      length = scale_rect.width();
-
-    DEBUG_OUTPUT("Scale bar rect = " << scale_rect.width() << "x" << scale_rect.height() << "+" << scale_rect.height()
-                                     << "+" << scale_rect.width() << endl);
-
-    // Get the ticks
-    array ticks = selectValues(length, orientation == VERTICAL, &metric);
-    if(ticks.size() == 0)
-      break;
-    if(DEBUG) {
-      DEBUG_OUT << "List of ticks = ";
-      for(size_t i = 0; i < ticks.size(); ++i) {
-        DEBUG_OUT << ticks[i] << " ";
-      }
-      DEBUG_OUT << endl;
-    }
-    QString ticks_extra;
-    QStringList ticks_str = _tick2str(ticks, &ticks_extra);
-
-    DEBUG_OUTPUT("Ticks strings = " << ticks_str.join(", ") << endl);
-
-    // Now, draw the gradient
-    DEBUG_OUTPUT("Draw gradient" << endl);
-
-    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-    glEnable(GL_TEXTURE_1D);
-    glBindTexture(GL_TEXTURE_1D, texId);
-    glBegin(GL_QUADS);
-    glTexCoord1f(0);
-    glVertex2dv(start_pos.c_data());
-    glVertex2dv((start_pos + next_side).c_data());
-    glTexCoord1f(1);
-    glVertex2dv((end_pos + next_side).c_data());
-    glVertex2dv(end_pos.c_data());
-    glEnd();
-    glDisable(GL_TEXTURE_1D);
-
-    // Draw text
-    DEBUG_OUTPUT("Draw text" << endl);
-
-    // Compute the shifts
-    double max_width = 0;
-    double max_height = metric.height();
-    forall(QString tick, ticks_str) {
-      double w = metric.width(tick);
-      if(max_width < w)
-        max_width = w;
-      DEBUG_OUTPUT(QString("Width of '%1' = %2").arg(tick).arg(w) << endl);
-    }
-    double shift = 0;
-    if(orientation == VERTICAL) {
-      switch(position) {
-      case LEFT:
-      case TOP_LEFT:
-      case BOTTOM_LEFT:
-        shift = text_to_bar + line_width;
-        break;
-      case RIGHT:
-      case TOP_RIGHT:
-      case BOTTOM_RIGHT:
-        shift = -text_to_bar - max_width - line_width;
-        break;
+      } break;
+      case TOP_LEFT: {
+        if(orientation == HORIZONTAL) {
+          scale_rect = QRectF(shift_length, shift_width, scale_length * w, width);
+          limit_rect(scale_rect, size, lim_width, lim_height);
+          start_pos = toPoint2d(scale_rect.bottomLeft());
+          end_pos = toPoint2d(scale_rect.bottomRight());
+          next_side = toPoint2d(scale_rect.topRight() - scale_rect.bottomRight());
+        } else {
+          scale_rect = QRectF(shift_width, shift_length, width, scale_length * h);
+          limit_rect(scale_rect, size, lim_width, lim_height);
+          start_pos = toPoint2d(scale_rect.bottomRight());
+          end_pos = toPoint2d(scale_rect.topRight());
+          next_side = toPoint2d(scale_rect.bottomLeft() - scale_rect.bottomRight());
+        }
+      } break;
+      case TOP_RIGHT: {
+        if(orientation == HORIZONTAL) {
+          scale_rect = QRectF(w * (1 - scale_length) - shift_length, shift_width, scale_length * w, width);
+          limit_rect(scale_rect, size, lim_width, lim_height);
+          start_pos = toPoint2d(scale_rect.bottomLeft());
+          end_pos = toPoint2d(scale_rect.bottomRight());
+          next_side = toPoint2d(scale_rect.topRight() - scale_rect.bottomRight());
+        } else {
+          scale_rect = QRectF(w - shift_width - width, shift_length, width, scale_length * h);
+          limit_rect(scale_rect, size, lim_width, lim_height);
+          start_pos = toPoint2d(scale_rect.bottomLeft());
+          end_pos = toPoint2d(scale_rect.topLeft());
+          next_side = toPoint2d(scale_rect.bottomRight() - scale_rect.bottomLeft());
+        }
+      } break;
+      case BOTTOM_LEFT: {
+        if(orientation == HORIZONTAL) {
+          scale_rect = QRectF(shift_length, h - shift_width - width, scale_length * w, width);
+          limit_rect(scale_rect, size, lim_width, lim_height);
+          start_pos = toPoint2d(scale_rect.topLeft());
+          end_pos = toPoint2d(scale_rect.topRight());
+          next_side = toPoint2d(scale_rect.bottomRight() - scale_rect.topRight());
+        } else {
+          scale_rect = QRectF(shift_width, h * (1 - scale_length) - shift_length, width, scale_length * h);
+          limit_rect(scale_rect, size, lim_width, lim_height);
+          start_pos = toPoint2d(scale_rect.bottomRight());
+          end_pos = toPoint2d(scale_rect.topRight());
+          next_side = toPoint2d(scale_rect.bottomLeft() - scale_rect.bottomRight());
+        }
+      } break;
+      case BOTTOM_RIGHT: {
+        if(orientation == HORIZONTAL) {
+          scale_rect
+            = QRectF(w * (1 - scale_length) - shift_length, h - width - shift_width, scale_length * w, width);
+          limit_rect(scale_rect, size, lim_width, lim_height);
+          start_pos = toPoint2d(scale_rect.topLeft());
+          end_pos = toPoint2d(scale_rect.topRight());
+          next_side = toPoint2d(scale_rect.bottomRight() - scale_rect.topRight());
+        } else {
+          scale_rect
+            = QRectF(w - shift_width - width, h * (1 - scale_length) - shift_length, width, scale_length * h);
+          limit_rect(scale_rect, size, lim_width, lim_height);
+          start_pos = toPoint2d(scale_rect.bottomLeft());
+          end_pos = toPoint2d(scale_rect.topLeft());
+          next_side = toPoint2d(scale_rect.bottomRight() - scale_rect.bottomLeft());
+        }
+      } break;
       default:
         break;
       }
-    } else {
-      switch(position) {
-      case TOP:
-      case TOP_LEFT:
-      case TOP_RIGHT:
-        shift = text_to_bar + line_width;
+      if(scale_rect.width() == 0 or scale_rect.height() == 0) {
+        DEBUG_OUTPUT("Zero-size colorbar" << endl);
         break;
-      case BOTTOM:
-      case BOTTOM_LEFT:
-      case BOTTOM_RIGHT:
-        shift = -text_to_bar - max_height - line_width;
+      }
+      Point2d shift_pos = (end_pos - start_pos) / delta_value;
+      double length;
+      if(orientation == VERTICAL)
+        length = scale_rect.height();
+      else
+        length = scale_rect.width();
+  
+      DEBUG_OUTPUT("Scale bar rect = " << scale_rect.width() << "x" << scale_rect.height() << "+" << scale_rect.height()
+                                       << "+" << scale_rect.width() << endl);
+  
+      // Get the ticks
+      array ticks = selectValues(length, orientation == VERTICAL, &metric);
+      if(ticks.size() == 0)
         break;
-      default:
-        break;
+      if(DEBUG) {
+        Information::out << "List of ticks = ";
+        for(size_t i = 0; i < ticks.size(); ++i) {
+          Information::out << ticks[i] << " ";
+        }
+        Information::out << endl;
       }
-    }
-
-    DEBUG_OUTPUT("Shift = " << shift << endl);
-
-    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
-    Colorf col = Colors::getColor(Colors::LegendColor);
-    glColor3fv(col.c_data());
-
-    {
-      QPainter paint(device);
-      paint.scale(globalScaling, globalScaling);
-      paint.setFont(font);
-      paint.setPen(Colors::getQColor(Colors::LegendColor));
-
-      for(size_t i = 0; i < ticks.size(); ++i) {
-        QString ts = ticks_str[i];
-        double t = ticks[i];
-        double h = metric.height();
-        double w = metric.width(ts);
-        DEBUG_OUTPUT(QString("Width of '%1' = %2").arg(ts).arg(w) << endl);
-        Point2d pos = start_pos + shift_pos * (t - vmin);
-        if(orientation == VERTICAL) {
-          pos.x() += shift + max_width - w;
-          pos.y() -= h / 2;
-        } else {
-          pos.x() -= w / 3;
-          pos.y() += shift;
+      QString ticks_extra;
+      QStringList ticks_str = _tick2str(ticks, &ticks_extra);
+  
+      DEBUG_OUTPUT("Ticks strings = " << ticks_str.join(", ") << endl);
+  
+      // Now, draw the gradient
+      DEBUG_OUTPUT("Draw gradient" << endl);
+  
+      glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+      glEnable(GL_TEXTURE_1D);
+      glBindTexture(GL_TEXTURE_1D, texId);
+      glBegin(GL_QUADS);
+      glTexCoord1f(0);
+      glVertex2dv(start_pos.c_data());
+      glVertex2dv((start_pos + next_side).c_data());
+      glTexCoord1f(1);
+      glVertex2dv((end_pos + next_side).c_data());
+      glVertex2dv(end_pos.c_data());
+      glEnd();
+      glDisable(GL_TEXTURE_1D);
+  
+      // Draw text
+      DEBUG_OUTPUT("Draw text" << endl);
+  
+      // Compute the shifts
+      double max_width = 0;
+      double max_height = metric.height();
+      forall(QString tick, ticks_str) {
+        double w = metric.width(tick);
+        if(max_width < w)
+          max_width = w;
+        DEBUG_OUTPUT(QString("Width of '%1' = %2").arg(tick).arg(w) << endl);
+      }
+      double shift = 0;
+      if(orientation == VERTICAL) {
+        switch(position) {
+        case LEFT:
+        case TOP_LEFT:
+        case BOTTOM_LEFT:
+          shift = text_to_bar + line_width;
+          break;
+        case RIGHT:
+        case TOP_RIGHT:
+        case BOTTOM_RIGHT:
+          shift = -text_to_bar - max_width - line_width;
+          break;
+        default:
+          break;
         }
-        pos.y() += h;
-        paint.drawText(pos.x(), pos.y(), ts);
+      } else {
+        switch(position) {
+        case TOP:
+        case TOP_LEFT:
+        case TOP_RIGHT:
+          shift = text_to_bar + line_width;
+          break;
+        case BOTTOM:
+        case BOTTOM_LEFT:
+        case BOTTOM_RIGHT:
+          shift = -text_to_bar - max_height - line_width;
+          break;
+        default:
+          break;
+        }
       }
-
-      if(!ticks_extra.isEmpty() or !label.isEmpty()) {
-        DEBUG_OUTPUT("Add extra text: '" << ticks_extra << "'" << endl);
-        QString exp_txt = QString::fromUtf8("×10");
-        DEBUG_OUTPUT(QString("exp_txt = '%1'").arg(exp_txt) << endl);
-        double width = metric.width(exp_txt);
-        QFont exp_font = QFont(font);
-        if(exp_font.pixelSize() != -1)
-          exp_font.setPixelSize(exp_size * exp_font.pixelSize());
-        else
-          exp_font.setPointSizeF(exp_size * exp_font.pointSizeF());
-        QFontMetricsF exp_metric(exp_font, device);
-        double exp_width = exp_metric.boundingRect(ticks_extra).width();
-        double exp_height = exp_metric.boundingRect(ticks_extra).height();
-        double total_height = std::max(metric.ascent(), metric.ascent() / 2 + exp_metric.ascent());
-        double label_width;
-        if(!label.isEmpty())
-          label_width = metric.boundingRect(label).width();
-        else
-          label_width = 0;
-        double space_width = metric.width(" ");
-        Point2d pos = toPoint2d(scale_rect.topRight());
-        if(ticks_extra.isEmpty()) {
-          exp_width = width = space_width = 0;
-          exp_txt = "";
+  
+      DEBUG_OUTPUT("Shift = " << shift << endl);
+  
+      glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
+      Colorf col = Colors::getColor(Colors::LegendColor);
+      glColor3fv(col.c_data());
+  
+      {
+        QPainter paint(device);
+        paint.scale(globalScaling, globalScaling);
+        paint.setFont(font);
+        paint.setPen(Colors::getQColor(Colors::LegendColor));
+  
+        for(size_t i = 0; i < ticks.size(); ++i) {
+          QString ts = ticks_str[i];
+          double t = ticks[i];
+          double h = metric.height();
+          double w = metric.width(ts);
+          DEBUG_OUTPUT(QString("Width of '%1' = %2").arg(ts).arg(w) << endl);
+          Point2d pos = start_pos + shift_pos * (t - vmin);
+          if(orientation == VERTICAL) {
+            pos.x() += shift + max_width - w;
+            pos.y() -= h / 2;
+          } else {
+            pos.x() -= w / 3;
+            pos.y() += shift;
+          }
+          pos.y() += h;
+          paint.drawText(pos.x(), pos.y(), ts);
         }
-        double total_width = width + exp_width + label_width + space_width;
-        if(orientation == VERTICAL) {
-          pos.x() -= (scale_rect.width() + total_width) / 2;
-          if(pos.x() < 0) {
-            pos.x() = text_to_bar;
-          } else if(pos.x() + total_width + text_to_bar > w) {
-            pos.x() = w - total_width - text_to_bar;
+  
+        if(!ticks_extra.isEmpty() or !label.isEmpty()) {
+          DEBUG_OUTPUT("Add extra text: '" << ticks_extra << "'" << endl);
+          QString exp_txt = QString::fromUtf8("×10");
+          DEBUG_OUTPUT(QString("exp_txt = '%1'").arg(exp_txt) << endl);
+          double width = metric.width(exp_txt);
+          QFont exp_font = QFont(font);
+          if(exp_font.pixelSize() != -1)
+            exp_font.setPixelSize(exp_size * exp_font.pixelSize());
+          else
+            exp_font.setPointSizeF(exp_size * exp_font.pointSizeF());
+          QFontMetricsF exp_metric(exp_font, device);
+          double exp_width = exp_metric.boundingRect(ticks_extra).width();
+          double exp_height = exp_metric.boundingRect(ticks_extra).height();
+          double total_height = std::max(metric.ascent(), metric.ascent() / 2 + exp_metric.ascent());
+          double label_width;
+          if(!label.isEmpty())
+            label_width = metric.boundingRect(label).width();
+          else
+            label_width = 0;
+          double space_width = metric.width(" ");
+          Point2d pos = toPoint2d(scale_rect.topRight());
+          if(ticks_extra.isEmpty()) {
+            exp_width = width = space_width = 0;
+            exp_txt = "";
           }
-          pos.y() -= text_to_bar + total_height / 2;
-        } else {
-          switch(position) {
-          case BOTTOM:
-          case BOTTOM_LEFT:
-          case BOTTOM_RIGHT:
-            pos.y() += scale_rect.height() + text_to_bar + total_height;
-            pos.x() -= total_width;
-            break;
-          case TOP:
-          case TOP_LEFT:
-          case TOP_RIGHT:
-            pos.y() -= text_to_bar;
-            pos.x() -= total_width;
-            break;
-          default:
-            break;
+          double total_width = width + exp_width + label_width + space_width;
+          if(orientation == VERTICAL) {
+            pos.x() -= (scale_rect.width() + total_width) / 2;
+            if(pos.x() < 0) {
+              pos.x() = text_to_bar;
+            } else if(pos.x() + total_width + text_to_bar > w) {
+              pos.x() = w - total_width - text_to_bar;
+            }
+            pos.y() -= text_to_bar + total_height / 2;
+          } else {
+            switch(position) {
+            case BOTTOM:
+            case BOTTOM_LEFT:
+            case BOTTOM_RIGHT:
+              pos.y() += scale_rect.height() + text_to_bar + total_height;
+              pos.x() -= total_width;
+              break;
+            case TOP:
+            case TOP_LEFT:
+            case TOP_RIGHT:
+              pos.y() -= text_to_bar;
+              pos.x() -= total_width;
+              break;
+            default:
+              break;
+            }
           }
+  
+          DEBUG_OUTPUT("Rendering exp text" << endl);
+  
+          paint.drawText(pos.x(), pos.y(), exp_txt);
+  
+          Point2d label_pos = pos;
+  
+          label_pos.x() += width + exp_width + space_width;
+          paint.drawText(label_pos.x(), label_pos.y(), label);
+  
+          DEBUG_OUTPUT("Rendering exponent" << endl);
+          pos.x() += width;
+          pos.y() -= metric.ascent() * 0.5;
+          paint.setFont(exp_font);
+          paint.drawText(pos.x(), pos.y() - exp_height, exp_width, exp_height,
+                         Qt::AlignBottom | Qt::AlignLeft | Qt::TextDontClip, ticks_extra);
+          paint.setFont(font);
         }
-
-        DEBUG_OUTPUT("Rendering exp text" << endl);
-
-        paint.drawText(pos.x(), pos.y(), exp_txt);
-
-        Point2d label_pos = pos;
-
-        label_pos.x() += width + exp_width + space_width;
-        paint.drawText(label_pos.x(), label_pos.y(), label);
-
-        DEBUG_OUTPUT("Rendering exponent" << endl);
-        pos.x() += width;
-        pos.y() -= metric.ascent() * 0.5;
-        paint.setFont(exp_font);
-        paint.drawText(pos.x(), pos.y() - exp_height, exp_width, exp_height,
-                       Qt::AlignBottom | Qt::AlignLeft | Qt::TextDontClip, ticks_extra);
-        paint.setFont(font);
       }
+  
+      // Draw the box
+      DEBUG_OUTPUT("Draw box" << endl);
+      double lw = line_width * globalScaling;
+      glLineWidth(lw);
+      col = Colors::getColor(Colors::LegendColor);
+      glColor3fv(col.c_data());
+      double correct = (line_width > 0) ? (line_width / 2) : 0;
+  
+      Point2d p1 = start_pos;
+      Point2d p2 = start_pos + next_side;
+      Point2d p3 = end_pos + next_side;
+      Point2d p4 = end_pos;
+  
+      Point2d d12 = correct * normalized(p2 - p1);
+      Point2d d23 = correct * normalized(p3 - p2);
+      Point2d d34 = correct * normalized(p4 - p3);
+      Point2d d41 = correct * normalized(p1 - p4);
+  
+      glBegin(GL_LINES);
+      glVertex2dv((p1 - d12).c_data());
+      glVertex2dv((p2 + d12).c_data());
+      glVertex2dv((p2 - d23).c_data());
+      glVertex2dv((p3 + d23).c_data());
+      glVertex2dv((p3 - d34).c_data());
+      glVertex2dv((p4 + d34).c_data());
+      glVertex2dv((p4 - d41).c_data());
+      glVertex2dv((p1 + d41).c_data());
+      glEnd();
+  
+      // At last, draw the ticks
+      DEBUG_OUTPUT("Draw ticks" << endl);
+      glBegin(GL_LINES);
+      for(size_t i = 0; i < ticks.size(); ++i) {
+        double t = ticks[i];
+        Point2d pos1 = start_pos + shift_pos * (t - vmin);
+        Point2d pos2 = pos1;
+        if(orientation == VERTICAL) {
+          pos1.x() = scale_rect.left();
+          pos2.x() = pos1.x() + tick_size;
+          glVertex2dv(pos1.c_data());
+          glVertex2dv(pos2.c_data());
+  
+          pos1.x() = scale_rect.right();
+          pos2.x() = pos1.x() - tick_size;
+          glVertex2dv(pos1.c_data());
+          glVertex2dv(pos2.c_data());
+        } else {
+          pos1.y() = scale_rect.top();
+          pos2.y() = pos1.y() + tick_size;
+          glVertex2dv(pos1.c_data());
+          glVertex2dv(pos2.c_data());
+  
+          pos1.y() = scale_rect.bottom();
+          pos2.y() = pos1.y() - tick_size;
+          glVertex2dv(pos1.c_data());
+          glVertex2dv(pos2.c_data());
+        }
+      }
+      glEnd();
+  
+      DEBUG_OUTPUT("Done" << endl);
+    } while(false);
+  
+    stopScreenCoordinatesSystem();
+    glPopAttrib();
+  }
+  
+  void Colorbar::getValues(double start, double end, double delta, array& result) const
+  {
+    double new_start = floor(start / delta) * delta;
+    if((start < epsilon and fabs(new_start - start) > epsilon)
+       or (start >= epsilon and fabs((new_start - start) / start) > epsilon))
+      new_start += delta;
+    int nb_values = floor((end + delta / 100 - new_start) / delta) + 1;
+    DEBUG_OUTPUT("Values from " << start << " to " << end << " by " << delta << endl);
+    DEBUG_OUTPUT("  Nb values = " << nb_values << endl);
+    result.resize(nb_values);
+    int i = 0;
+    for(double value = new_start; value < end + delta / 100; value += delta) {
+      result[i++] = value;
     }
-
-    // Draw the box
-    DEBUG_OUTPUT("Draw box" << endl);
-    double lw = line_width * globalScaling;
-    glLineWidth(lw);
-    col = Colors::getColor(Colors::LegendColor);
-    glColor3fv(col.c_data());
-    double correct = (line_width > 0) ? (line_width / 2) : 0;
-
-    Point2d p1 = start_pos;
-    Point2d p2 = start_pos + next_side;
-    Point2d p3 = end_pos + next_side;
-    Point2d p4 = end_pos;
-
-    Point2d d12 = correct * normalized(p2 - p1);
-    Point2d d23 = correct * normalized(p3 - p2);
-    Point2d d34 = correct * normalized(p4 - p3);
-    Point2d d41 = correct * normalized(p1 - p4);
-
-    glBegin(GL_LINES);
-    glVertex2dv((p1 - d12).c_data());
-    glVertex2dv((p2 + d12).c_data());
-    glVertex2dv((p2 - d23).c_data());
-    glVertex2dv((p3 + d23).c_data());
-    glVertex2dv((p3 - d34).c_data());
-    glVertex2dv((p4 + d34).c_data());
-    glVertex2dv((p4 - d41).c_data());
-    glVertex2dv((p1 + d41).c_data());
-    glEnd();
-
-    // At last, draw the ticks
-    DEBUG_OUTPUT("Draw ticks" << endl);
-    glBegin(GL_LINES);
-    for(size_t i = 0; i < ticks.size(); ++i) {
-      double t = ticks[i];
-      Point2d pos1 = start_pos + shift_pos * (t - vmin);
-      Point2d pos2 = pos1;
-      if(orientation == VERTICAL) {
-        pos1.x() = scale_rect.left();
-        pos2.x() = pos1.x() + tick_size;
-        glVertex2dv(pos1.c_data());
-        glVertex2dv(pos2.c_data());
-
-        pos1.x() = scale_rect.right();
-        pos2.x() = pos1.x() - tick_size;
-        glVertex2dv(pos1.c_data());
-        glVertex2dv(pos2.c_data());
-      } else {
-        pos1.y() = scale_rect.top();
-        pos2.y() = pos1.y() + tick_size;
-        glVertex2dv(pos1.c_data());
-        glVertex2dv(pos2.c_data());
-
-        pos1.y() = scale_rect.bottom();
-        pos2.y() = pos1.y() - tick_size;
-        glVertex2dv(pos1.c_data());
-        glVertex2dv(pos2.c_data());
+    if(DEBUG) {
+      Information::out << "  value = ";
+      for(size_t i = 0; i < result.size(); ++i) {
+        Information::out << result[i] << " ";
       }
     }
-    glEnd();
-
-    DEBUG_OUTPUT("Done" << endl);
-  } while(false);
-
-  stopScreenCoordinatesSystem();
-  glPopAttrib();
-}
-
-void Colorbar::_getValues(double start, double end, double delta, array& result) const
-{
-  double new_start = floor(start / delta) * delta;
-  if((start < epsilon and fabs(new_start - start) > epsilon)
-     or (start >= epsilon and fabs((new_start - start) / start) > epsilon))
-    new_start += delta;
-  int nb_values = floor((end + delta / 100 - new_start) / delta) + 1;
-  DEBUG_OUTPUT("Values from " << start << " to " << end << " by " << delta << endl);
-  DEBUG_OUTPUT("  Nb values = " << nb_values << endl);
-  result.resize(nb_values);
-  int i = 0;
-  for(double value = new_start; value < end + delta / 100; value += delta) {
-    result[i++] = value;
   }
-  if(DEBUG) {
-    DEBUG_OUT << "  value = ";
-    for(size_t i = 0; i < result.size(); ++i) {
-      DEBUG_OUT << result[i] << " ";
+  
+  Colorbar::array Colorbar::selectValues(double length, bool is_vertical, const QFontMetricsF* arg_metric) const
+  {
+    const QFontMetricsF* metric = arg_metric ? arg_metric : new QFontMetricsF(font);
+    double min_dist = 1;
+    if(!is_vertical)   // Find the maximum size of 2 figures
+    {
+      for(int i = 0; i < 10; ++i) {
+        QString t = QString::number(i) + QString::number(i);
+        double w = metric->boundingRect(t).width();
+        if(min_dist < w)
+          min_dist = w;
+      }
     }
+    DEBUG_OUTPUT("Min_dist between values = " << min_dist << endl);
+    array result = selectValuesDirect(length, is_vertical, *metric, min_dist);
+    if(arg_metric == 0)
+      delete metric;
+    return result;
   }
-}
-
-Colorbar::array Colorbar::selectValues(double length, bool is_vertical, const QFontMetricsF* arg_metric) const
-{
-  const QFontMetricsF* metric = arg_metric ? arg_metric : new QFontMetricsF(font);
-  double min_dist = 1;
-  if(!is_vertical)   // Find the maximum size of 2 figures
+  
+  Colorbar::array Colorbar::selectValuesDirect(double length, bool is_vertical, const QFontMetricsF& metric,
+                                                 double min_dist) const
   {
-    for(int i = 0; i < 10; ++i) {
-      QString t = QString::number(i) + QString::number(i);
-      double w = metric->boundingRect(t).width();
-      if(min_dist < w)
-        min_dist = w;
+    double start = vmin;
+    double end = vmax;
+    double real_delta, exp;
+    util::tie(real_delta, exp) = significantDigits(start, end);
+    array ticks;
+    getValues(start, end, real_delta * exp, ticks);
+    while(!canRenderTicks(ticks, length, min_dist, is_vertical, metric)) {
+      DEBUG_OUTPUT("Error, can't render ticks" << endl);
+      if(real_delta == 1)
+        real_delta = 2;
+      else if(real_delta == 2)
+        real_delta = 5;
+      else if(real_delta == 5) {
+        exp *= 10;
+        real_delta = 1;
+      } else {
+        exp *= 10;
+        real_delta = 2;
+      }
+      getValues(start, end, real_delta * exp, ticks);
+      if(ticks.size() < 2)
+        return array();
+      else
+        DEBUG_OUTPUT("New number of values = " << ticks.size() << endl);
     }
+    return ticks;
   }
-  DEBUG_OUTPUT("Min_dist between values = " << min_dist << endl);
-  array result = _selectValues_direct(length, is_vertical, *metric, min_dist);
-  if(arg_metric == 0)
-    delete metric;
-  return result;
-}
-
-Colorbar::array Colorbar::_selectValues_direct(double length, bool is_vertical, const QFontMetricsF& metric,
-                                               double min_dist) const
-{
-  double start = vmin;
-  double end = vmax;
-  double real_delta, exp;
-  util::tie(real_delta, exp) = _significant_digits(start, end);
-  array ticks;
-  _getValues(start, end, real_delta * exp, ticks);
-  while(!_canRenderTicks(ticks, length, min_dist, is_vertical, metric)) {
-    DEBUG_OUTPUT("Error, can't render ticks" << endl);
-    if(real_delta == 1)
-      real_delta = 2;
-    else if(real_delta == 2)
+  
+  std::pair<double, double> Colorbar::significantDigits(double start, double end) const
+  {
+    double delta = (end - start) / 10;
+    double first_num = floor(log10(delta));
+    double exp = pow(10.0, first_num);
+    double real_delta = ceil(delta / exp);
+    if(real_delta > 6)
+      real_delta = 10;
+    else if(real_delta > 2)
       real_delta = 5;
-    else if(real_delta == 5) {
-      exp *= 10;
-      real_delta = 1;
+    return std::make_pair(real_delta, exp);
+  }
+  
+  QStringList Colorbar::_tick2str(const array& ticks, QString* extra) const
+  {
+    if(DEBUG) {
+      Information::out << "_tick2str" << endl;
+      Information::out << "Representation of the ticks (";
+      for(size_t i = 0; i < ticks.size(); ++i) {
+        Information::out << ticks[i];
+        if(i < ticks.size() - 1)
+          Information::out << ',';
+      }
+      Information::out << ")" << endl;
+    }
+    double m = abs(ticks).max();
+    double exp;
+    array new_ticks = ticks;
+    double factor = 1;
+    array absticks = abs(ticks);
+    array absolute_numbers = absticks[ticks != 0.0];
+  
+    if(DEBUG) {
+      Information::out << "Working on numbers (";
+      for(size_t i = 0; i < absolute_numbers.size(); ++i) {
+        Information::out << absolute_numbers[i];
+        if(i < absolute_numbers.size() - 1)
+          Information::out << ',';
+      }
+      Information::out << ")" << endl;
+    }
+    if(m <= 0.01) {
+      DEBUG_OUTPUT("Small numbers" << endl);
+      exp = log10(absolute_numbers).max();
+      exp = floor(exp);
+      factor = pow(10.0, exp);
+      new_ticks /= factor;
+      array t = abs(new_ticks.apply(round) - new_ticks);
+      t[new_ticks != 0.0] /= new_ticks[new_ticks != 0.0];
+      if((t > epsilon).sum()) {
+        exp = floor(log10(m));
+        factor = pow(10.0, exp);
+        new_ticks = ticks / factor;
+      }
+    } else if(m >= 20000) {
+      DEBUG_OUTPUT("Big numbers" << endl);
+      exp = round(log10(absolute_numbers).min());
+      factor = pow(10.0, exp);
+      new_ticks /= factor;
+      DEBUG_OUTPUT("Last number = " << ticks[ticks.size() - 1] / factor << endl);
+      DEBUG_OUTPUT("Last number = " << new_ticks[ticks.size() - 1] << endl);
+      array t = abs(new_ticks.apply(round) - new_ticks);
+      t[new_ticks != 0.0] /= new_ticks[new_ticks != 0.0];
+      if((t > epsilon).sum()) {
+        exp = floor(log10(m));
+        factor = pow(10.0, exp);
+        new_ticks = ticks / factor;
+      }
     } else {
-      exp *= 10;
-      real_delta = 2;
+      DEBUG_OUTPUT("Regular numbers" << endl);
+  #ifdef _MSC_VER
+      unsigned long nan[2] = { 0xffffffff, 0x7fffffff };
+      exp = *(double*)nan;
+  // exp = std::numeric_limits<double>::quiet_NaN();
+  #else
+      exp = nan("");
+  #endif
     }
-    _getValues(start, end, real_delta * exp, ticks);
-    if(ticks.size() < 2)
-      return array();
-    else
-      DEBUG_OUTPUT("New number of values = " << ticks.size() << endl);
+    new_ticks[abs((new_ticks * factor) / abs(ticks).max()) < epsilon] = 0;
+    QStringList ticks_str;
+    if(DEBUG) {
+      Information::out << "new_ticks = (";
+      for(size_t i = 0; i < new_ticks.size(); ++i) {
+        Information::out << new_ticks[i];
+        if(i < new_ticks.size() - 1)
+          Information::out << ',';
+      }
+      Information::out << ")" << endl;
+    }
+    for(size_t i = 0; i < new_ticks.size(); ++i) {
+      ticks_str << QString::number(new_ticks[i]);
+    }
+    if(extra) {
+      if(isnan(exp))
+        *extra = QString();
+      else
+        *extra = QString::number(int(round(exp)));
+    }
+    if(DEBUG) {
+      Information::out << "  max tick = " << ticks.max() << endl << "  exp = " << exp << endl 
+                       << "  factor = " << factor << endl;
+      if(extra)
+        Information::out << "  extra = " << *extra << endl;
+    }
+    return ticks_str;
   }
-  return ticks;
-}
-
-std::pair<double, double> Colorbar::_significant_digits(double start, double end) const
-{
-  double delta = (end - start) / 10;
-  double first_num = floor(log10(delta));
-  double exp = pow(10.0, first_num);
-  double real_delta = ceil(delta / exp);
-  if(real_delta > 6)
-    real_delta = 10;
-  else if(real_delta > 2)
-    real_delta = 5;
-  return std::make_pair(real_delta, exp);
-}
-
-QStringList Colorbar::_tick2str(const array& ticks, QString* extra) const
-{
-  if(DEBUG) {
-    DEBUG_OUT << "_tick2str" << endl;
-    DEBUG_OUT << "Representation of the ticks (";
-    for(size_t i = 0; i < ticks.size(); ++i) {
-      DEBUG_OUT << ticks[i];
-      if(i < ticks.size() - 1)
-        DEBUG_OUT << ',';
+  
+  bool Colorbar::canRenderTicks(const array& ticks, double length, double min_dist, bool is_vertical,
+                                 const QFontMetricsF& font_metric) const
+  {
+    double b = vmin;
+    double e = vmax;
+    double dl = length / (e - b);
+    array pos = dl * (ticks - b);
+    double cur_pos = -length;
+    QStringList ticks_str = _tick2str(ticks);
+    for(size_t i = 0; i < pos.size(); ++i) {
+      QString t = ticks_str[i];
+      double p = pos[i];
+      QRectF r = font_metric.boundingRect(t);
+      double w;
+      if(is_vertical)
+        w = r.height() / 2;
+      else
+        w = r.width() / 2;
+      double left = p - w;
+      if(left < cur_pos)
+        return false;
+      cur_pos = p + w + min_dist;
     }
-    DEBUG_OUT << ")" << endl;
+    return true;
   }
-  double m = abs(ticks).max();
-  double exp;
-  array new_ticks = ticks;
-  double factor = 1;
-  array absticks = abs(ticks);
-  array absolute_numbers = absticks[ticks != 0.0];
-
-  if(DEBUG) {
-    DEBUG_OUT << "Working on numbers (";
-    for(size_t i = 0; i < absolute_numbers.size(); ++i) {
-      DEBUG_OUT << absolute_numbers[i];
-      if(i < absolute_numbers.size() - 1)
-        DEBUG_OUT << ',';
+  
+  template <typename stream> void writepos(stream& s, const Colorbar::Position& pos)
+  {
+    switch(pos) {
+    case Colorbar::LEFT:
+      s << "Left";
+      break;
+    case Colorbar::RIGHT:
+      s << "Right";
+      break;
+    case Colorbar::TOP:
+      s << "Top";
+      break;
+    case Colorbar::BOTTOM:
+      s << "Bottom";
+      break;
+    case Colorbar::TOP_LEFT:
+      s << "TopLeft";
+      break;
+    case Colorbar::TOP_RIGHT:
+      s << "TopRight";
+      break;
+    case Colorbar::BOTTOM_LEFT:
+      s << "BottomLeft";
+      break;
+    case Colorbar::BOTTOM_RIGHT:
+      s << "BottomRight";
+      break;
     }
-    DEBUG_OUT << ")" << endl;
   }
-  if(m <= 0.01) {
-    DEBUG_OUTPUT("Small numbers" << endl);
-    exp = log10(absolute_numbers).max();
-    exp = floor(exp);
-    factor = pow(10.0, exp);
-    new_ticks /= factor;
-    array t = abs(new_ticks.apply(round) - new_ticks);
-    t[new_ticks != 0.0] /= new_ticks[new_ticks != 0.0];
-    if((t > epsilon).sum()) {
-      exp = floor(log10(m));
-      factor = pow(10.0, exp);
-      new_ticks = ticks / factor;
+  
+  template <typename str> bool readpos(const str& s, Colorbar::Position& pos)
+  {
+    if(s == "Left")
+      pos = Colorbar::LEFT;
+    else if(s == "Right")
+      pos = Colorbar::RIGHT;
+    else if(s == "Top")
+      pos = Colorbar::TOP;
+    else if(s == "Bottom")
+      pos = Colorbar::BOTTOM;
+    else if(s == "TopLeft")
+      pos = Colorbar::TOP_LEFT;
+    else if(s == "TopRight")
+      pos = Colorbar::TOP_RIGHT;
+    else if(s == "BottomLeft")
+      pos = Colorbar::BOTTOM_LEFT;
+    else if(s == "BottomRight")
+      pos = Colorbar::BOTTOM_RIGHT;
+    else {
+      pos = Colorbar::TOP_LEFT;
+      return false;
     }
-  } else if(m >= 20000) {
-    DEBUG_OUTPUT("Big numbers" << endl);
-    exp = round(log10(absolute_numbers).min());
-    factor = pow(10.0, exp);
-    new_ticks /= factor;
-    DEBUG_OUTPUT("Last number = " << ticks[ticks.size() - 1] / factor << endl);
-    DEBUG_OUTPUT("Last number = " << new_ticks[ticks.size() - 1] << endl);
-    array t = abs(new_ticks.apply(round) - new_ticks);
-    t[new_ticks != 0.0] /= new_ticks[new_ticks != 0.0];
-    if((t > epsilon).sum()) {
-      exp = floor(log10(m));
-      factor = pow(10.0, exp);
-      new_ticks = ticks / factor;
-    }
-  } else {
-    DEBUG_OUTPUT("Regular numbers" << endl);
-#ifdef _MSC_VER
-    unsigned long nan[2] = { 0xffffffff, 0x7fffffff };
-    exp = *(double*)nan;
-// exp = std::numeric_limits<double>::quiet_NaN();
-#else
-    exp = nan("");
-#endif
+    return true;
   }
-  new_ticks[abs((new_ticks * factor) / abs(ticks).max()) < epsilon] = 0;
-  QStringList ticks_str;
-  if(DEBUG) {
-    DEBUG_OUT << "new_ticks = (";
-    for(size_t i = 0; i < new_ticks.size(); ++i) {
-      DEBUG_OUT << new_ticks[i];
-      if(i < new_ticks.size() - 1)
-        DEBUG_OUT << ',';
+  
+  std::ostream& operator<<(std::ostream& s, const Colorbar::Position& pos)
+  {
+    writepos(s, pos);
+    return s;
+  }
+  
+  std::istream& operator>>(std::istream& s, Colorbar::Position& pos)
+  {
+    std::string str;
+    s >> str;
+    if(!readpos(str, pos)) {
+      std::cerr << "Error, cannot interpret the position '" << str << "', position will default to Left" << std::endl;
     }
-    DEBUG_OUT << ")" << endl;
+    return s;
   }
-  for(size_t i = 0; i < new_ticks.size(); ++i) {
-    ticks_str << QString::number(new_ticks[i]);
+  
+  QTextStream& operator<<(QTextStream& s, const Colorbar::Position& pos)
+  {
+    writepos(s, pos);
+    return s;
   }
-  if(extra) {
-    if(isnan(exp))
-      *extra = QString();
-    else
-      *extra = QString::number(int(round(exp)));
+  
+  QTextStream& operator>>(QTextStream& s, Colorbar::Position& pos)
+  {
+    QString str;
+    s >> str;
+    if(!readpos(str, pos)) {
+      err << "Error, cannot interpret the position '" << str << "', position will default to Right" << endl;
+    }
+    return s;
   }
-  if(DEBUG) {
-    DEBUG_OUT << "  max tick = " << ticks.max() << endl << "  exp = " << exp << endl << "  factor = " << factor << endl;
-    if(extra)
-      DEBUG_OUT << "  extra = " << *extra << endl;
+  
+  QDataStream& operator<<(QDataStream& s, const Colorbar::Position& pos)
+  {
+    s << (unsigned int)pos;
+    return s;
   }
-  return ticks_str;
-}
-
-bool Colorbar::_canRenderTicks(const array& ticks, double length, double min_dist, bool is_vertical,
-                               const QFontMetricsF& font_metric) const
-{
-  double b = vmin;
-  double e = vmax;
-  double dl = length / (e - b);
-  array pos = dl * (ticks - b);
-  double cur_pos = -length;
-  QStringList ticks_str = _tick2str(ticks);
-  for(size_t i = 0; i < pos.size(); ++i) {
-    QString t = ticks_str[i];
-    double p = pos[i];
-    QRectF r = font_metric.boundingRect(t);
-    double w;
-    if(is_vertical)
-      w = r.height() / 2;
-    else
-      w = r.width() / 2;
-    double left = p - w;
-    if(left < cur_pos)
-      return false;
-    cur_pos = p + w + min_dist;
+  
+  QDataStream& operator>>(QDataStream& s, Colorbar::Position& pos)
+  {
+    unsigned int i;
+    s >> i;
+    if(i < 4) {
+      pos = (Colorbar::Position)i;
+    } else {
+      std::cerr << "Error, integer value " << i << " doesn't correspond to a valid position, using Right as default"
+                << std::endl;
+      pos = Colorbar::RIGHT;
+    }
+    return s;
   }
-  return true;
-}
-
-template <typename stream> void writepos(stream& s, const Colorbar::Position& pos)
-{
-  switch(pos) {
-  case Colorbar::LEFT:
-    s << "Left";
-    break;
-  case Colorbar::RIGHT:
-    s << "Right";
-    break;
-  case Colorbar::TOP:
-    s << "Top";
-    break;
-  case Colorbar::BOTTOM:
-    s << "Bottom";
-    break;
-  case Colorbar::TOP_LEFT:
-    s << "TopLeft";
-    break;
-  case Colorbar::TOP_RIGHT:
-    s << "TopRight";
-    break;
-  case Colorbar::BOTTOM_LEFT:
-    s << "BottomLeft";
-    break;
-  case Colorbar::BOTTOM_RIGHT:
-    s << "BottomRight";
-    break;
+  
+  void Colorbar::readParms(util::Parms& parms, QString section)
+  {
+    parms(section, "ScaleLength", scale_length, 0.3);
+    parms(section, "Width", width, 20.0);
+    parms(section, "DistanceToBorder", distance_to_border, 5.0);
+    parms(section, "TextToBar", text_to_bar, 5.0);
+    parms(section, "TickSize", tick_size, 2.0);
+    parms(section, "ExpSize", exp_size, 0.7);
+    parms(section, "Epsilon", epsilon, 1e-9);
+    parms(section, "LineWidth", line_width, 2.0);
+    int ps;
+    parms(section, "FontSize", ps, 10);
+    font.setPointSize(ps);
+    QString ori;
+    parms(section, "Orientation", ori, QString("Vertical"));
+    if(ori == "Horizontal")
+      orientation = HORIZONTAL;
+    else if(ori == "Vertical")
+      orientation = VERTICAL;
+    else {
+      err << "Error, invalid orientation: " << ori << endl;
+      orientation = VERTICAL;
+    }
+  
+    parms(section, "Position", position, TOP_LEFT);
+    if(position == TOP or position == BOTTOM)
+      orientation = HORIZONTAL;
+    else if(position == LEFT or position == RIGHT)
+      orientation = VERTICAL;
   }
-}
-
-template <typename str> bool readpos(const str& s, Colorbar::Position& pos)
-{
-  if(s == "Left")
-    pos = Colorbar::LEFT;
-  else if(s == "Right")
-    pos = Colorbar::RIGHT;
-  else if(s == "Top")
-    pos = Colorbar::TOP;
-  else if(s == "Bottom")
-    pos = Colorbar::BOTTOM;
-  else if(s == "TopLeft")
-    pos = Colorbar::TOP_LEFT;
-  else if(s == "TopRight")
-    pos = Colorbar::TOP_RIGHT;
-  else if(s == "BottomLeft")
-    pos = Colorbar::BOTTOM_LEFT;
-  else if(s == "BottomRight")
-    pos = Colorbar::BOTTOM_RIGHT;
-  else {
-    pos = Colorbar::TOP_LEFT;
-    return false;
+  
+  void Colorbar::writeParms(QTextStream& pout, QString section)
+  {
+    pout << endl;
+    pout << "[" << section << "]" << endl;
+    pout << "ScaleLength: " << scale_length << endl;
+    pout << "Width: " << width << endl;
+    pout << "DistanceToBorder: " << distance_to_border << endl;
+    pout << "TextToBar: " << text_to_bar << endl;
+    pout << "TickSize: " << tick_size << endl;
+    pout << "ExpSize: " << exp_size << endl;
+    pout << "Epsilon: " << epsilon << endl;
+    pout << "LineWidth: " << line_width << endl;
+    pout << "Position: " << position << endl;
+    pout << "FontSize: " << font.pointSize() << endl;
+    pout << "Orientation: ";
+    switch(orientation) {
+    case HORIZONTAL:
+      pout << "Horizontal" << endl;
+      break;
+    case VERTICAL:
+      pout << "Vertical" << endl;
+      break;
+    }
   }
-  return true;
-}
-
-std::ostream& operator<<(std::ostream& s, const Colorbar::Position& pos)
-{
-  writepos(s, pos);
-  return s;
-}
-
-std::istream& operator>>(std::istream& s, Colorbar::Position& pos)
-{
-  std::string str;
-  s >> str;
-  if(!readpos(str, pos)) {
-    std::cerr << "Error, cannot interpret the position '" << str << "', position will default to Left" << std::endl;
+  
+  void Colorbar::startScreenCoordinatesSystem(QPaintDevice* device) const
+  {
+    glMatrixMode(GL_PROJECTION);
+    glPushMatrix();
+    glLoadIdentity();
+    glOrtho(0, device->width() / globalScaling, device->height() / globalScaling, 0, 0.0, -1.0);
+  
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glLoadIdentity();
   }
-  return s;
-}
-
-QTextStream& operator<<(QTextStream& s, const Colorbar::Position& pos)
-{
-  writepos(s, pos);
-  return s;
-}
-
-QTextStream& operator>>(QTextStream& s, Colorbar::Position& pos)
-{
-  QString str;
-  s >> str;
-  if(!readpos(str, pos)) {
-    err << "Error, cannot interpret the position '" << str << "', position will default to Right" << endl;
+  
+  void Colorbar::scaleDrawing(double scale) {
+    globalScaling = scale;
   }
-  return s;
-}
-
-QDataStream& operator<<(QDataStream& s, const Colorbar::Position& pos)
-{
-  s << (unsigned int)pos;
-  return s;
-}
-
-QDataStream& operator>>(QDataStream& s, Colorbar::Position& pos)
-{
-  unsigned int i;
-  s >> i;
-  if(i < 4) {
-    pos = (Colorbar::Position)i;
-  } else {
-    std::cerr << "Error, integer value " << i << " doesn't correspond to a valid position, using Right as default"
-              << std::endl;
-    pos = Colorbar::RIGHT;
+  
+  void Colorbar::restoreScale() {
+    globalScaling = 1.0;
   }
-  return s;
-}
-
-void Colorbar::readParms(util::Parms& parms, QString section)
-{
-  parms(section, "ScaleLength", scale_length, 0.3);
-  parms(section, "Width", width, 20.0);
-  parms(section, "DistanceToBorder", distance_to_border, 5.0);
-  parms(section, "TextToBar", text_to_bar, 5.0);
-  parms(section, "TickSize", tick_size, 2.0);
-  parms(section, "ExpSize", exp_size, 0.7);
-  parms(section, "Epsilon", epsilon, 1e-9);
-  parms(section, "LineWidth", line_width, 2.0);
-  int ps;
-  parms(section, "FontSize", ps, 10);
-  font.setPointSize(ps);
-  QString ori;
-  parms(section, "Orientation", ori, QString("Vertical"));
-  if(ori == "Horizontal")
-    orientation = HORIZONTAL;
-  else if(ori == "Vertical")
-    orientation = VERTICAL;
-  else {
-    err << "Error, invalid orientation: " << ori << endl;
-    orientation = VERTICAL;
+  
+  void Colorbar::stopScreenCoordinatesSystem() const
+  {
+    glMatrixMode(GL_PROJECTION);
+    glPopMatrix();
+  
+    glMatrixMode(GL_MODELVIEW);
+    glPopMatrix();
   }
-
-  parms(section, "Position", position, TOP_LEFT);
-  if(position == TOP or position == BOTTOM)
-    orientation = HORIZONTAL;
-  else if(position == LEFT or position == RIGHT)
-    orientation = VERTICAL;
-}
-
-void Colorbar::writeParms(QTextStream& pout, QString section)
-{
-  pout << endl;
-  pout << "[" << section << "]" << endl;
-  pout << "ScaleLength: " << scale_length << endl;
-  pout << "Width: " << width << endl;
-  pout << "DistanceToBorder: " << distance_to_border << endl;
-  pout << "TextToBar: " << text_to_bar << endl;
-  pout << "TickSize: " << tick_size << endl;
-  pout << "ExpSize: " << exp_size << endl;
-  pout << "Epsilon: " << epsilon << endl;
-  pout << "LineWidth: " << line_width << endl;
-  pout << "Position: " << position << endl;
-  pout << "FontSize: " << font.pointSize() << endl;
-  pout << "Orientation: ";
-  switch(orientation) {
-  case HORIZONTAL:
-    pout << "Horizontal" << endl;
-    break;
-  case VERTICAL:
-    pout << "Vertical" << endl;
-    break;
-  }
-}
-
-void Colorbar::startScreenCoordinatesSystem(QPaintDevice* device) const
-{
-  glMatrixMode(GL_PROJECTION);
-  glPushMatrix();
-  glLoadIdentity();
-  glOrtho(0, device->width() / globalScaling, device->height() / globalScaling, 0, 0.0, -1.0);
-
-  glMatrixMode(GL_MODELVIEW);
-  glPushMatrix();
-  glLoadIdentity();
-}
-
-void Colorbar::scaleDrawing(double scale) {
-  globalScaling = scale;
-}
-
-void Colorbar::restoreScale() {
-  globalScaling = 1.0;
-}
-
-void Colorbar::stopScreenCoordinatesSystem() const
-{
-  glMatrixMode(GL_PROJECTION);
-  glPopMatrix();
-
-  glMatrixMode(GL_MODELVIEW);
-  glPopMatrix();
-}
 } // namespace mgx
Index: ImageData.hpp
===================================================================
--- ImageData.hpp	(revision 1255)
+++ ImageData.hpp	(revision 1256)
@@ -24,782 +24,780 @@
 #include <string.h>
 
 namespace mgx {
-
-class CutSurf;
-
-typedef util::Vector<4, vertex> Point4v;
-typedef util::Vector<3, GLubyte> Point3GLub;
-
-struct UpdateImgDataEvent : public QEvent {
-  UpdateImgDataEvent()
-    : QEvent(QEvent::User)
+  
+  class CutSurf;
+  
+  typedef util::Vector<4, vertex> Point4v;
+  typedef util::Vector<3, GLubyte> Point3GLub;
+  
+  struct UpdateImgDataEvent : public QEvent {
+    UpdateImgDataEvent() : QEvent(QEvent::User) {}
+  };
+  
+  class MGX_EXPORT ImgData : public QObject //, public ImplicitFunction
   {
-  }
-};
-
-class MGX_EXPORT ImgData : public QObject //, public ImplicitFunction
-{
-  Q_OBJECT
-public:
-  typedef Mesh::MeshView MeshViewModeEnum;
-
-  static const uint RELOAD_NONE = 0x0;
-  static const uint RELOAD_MAIN = 0x1;
-  static const uint RELOAD_WORK = 0x2;
-  static const uint RELOAD_TRIS = 0x4;
-  static const uint RELOAD_LINES = 0x8;
-  static const uint RELOAD_POS = 0x10;
-  static const uint RELOAD_VBO = 0x20;
-  static const uint UPDATE_SELECTION = 0x40;
-
-  int StackId;
-
-  Stack* stack;
-  Mesh* mesh;
-
-  // Main and stack paramters
-  bool Main16Bit, Work16Bit;
-
-  // General
-  bool needUpdateLines;
-  bool needUpdateTris;
-
-  gui::TransferFunctionDlg* workTransferDlg, *mainTransferDlg, *surfTransferDlg, *heatTransferDlg;
-  // Function defining the color of the pixels
-  std::vector<TransferFunction::Colorf> MainColorMap;   // Color map for the main data
-  std::vector<TransferFunction::Colorf> WorkColorMap;   // Color map for the work data
-  std::vector<TransferFunction::Colorf> SurfColorMap;   // Color map for the surface
-  std::vector<TransferFunction::Colorf> HeatColorMap;   // Color map for the heatmap
-  // If true, a new texture need to be sent for the colormap
-  bool newMainColorMap, newWorkColorMap, newSurfColorMap, newHeatColorMap;
-  std::vector<double> MainHist;   // Histogram of the main data
-  std::vector<double> WorkHist;   // Histogram of the working data
-  std::vector<double> SurfHist;   // Histogram of the surface data
-  std::vector<double> HeatHist;   // Histogram of the surface data
-  std::pair<double, double> mainBounds;
-  std::pair<double, double> workBounds;
-
-  GLuint mainDataTexId;              // 3D texture Id for main stack
-  GLuint workDataTexId;              // 3D texture Id for work stack
-  GLuint dataTexColor;               // 3D texture color
-  GLuint surfTexId;                  // 1D texture map for surface colors.
-  GLuint heatTexId;                  // 1D texture map for heatmap colors.
-  GLuint imgTexId;                   // 2D texture map for surface from an image
-  GLuint mcmapTexId, wcmapTexId;     // 1D texture map for volume colors.
-  GLuint labelTexId;                 // 1D texture map to color indexed texture for labels
-  graph::vertex_identity_t lineId;   // Last id when drawing lines
-  std::set<uint> selectV;            // List of selected vertices
-
-  Colors::ColorType MeshColor;
-  Colors::ColorType MeshBorderColor;
-  // Colors::ColorType MeshPointColor;
-  Colors::ColorType MeshSelectColor;
-
-  int TCount;   // Triangle count
-  int LCount;   // Line count
-  int VCount;   // Vertex count
-
-  // Helper arrays for vertex buffer obejects
-  std::vector<vertex> idVA;                // Vertex ids, used to find selection in triangle mode (!MeshSelect)
-  std::vector<vertex> pidVA;               // Point vtx ids, used to find selection in point mode (MeshSelect)
-  std::unordered_map<vertex, uint> vMap;   // Pointer into idVA by vertex
-
-  // VBO arrays
-  std::vector<Point3f> posVA;      // Vertex positions
-  std::vector<Point3f> nrmlVA;     // Vertex normals
-  std::vector<Point3GLub> selVA;   // Unique colors for triangle selection
-  std::vector<Point3f> texVA;      // Mesh labels, signal, and heat
-  std::vector<Point2f> imgVA;      // Image texture coordinates
-
-  std::vector<uint> lineVA;    // Indices for drawing lines
-  std::vector<uint> lbrdVA;    // Indices for drawing border lines
-  std::vector<uint> lcellVA;   // Indices for drawing cell border lines
-  std::vector<uint> lselVA;    // Indices for drawing selected lines
-
-  std::vector<uint> pbrdVA;            // Indices for drawing border points
-  std::vector<uint> pcellVA;           // Indices for drawing cell border points
-  std::vector<uint> pselVA;            // Indices for drawing selected points
-  std::vector<Point3f> pntsVA;         // Vertices for drawing points
-  std::vector<Point3GLub> pcolVA;      // Colors for points
-  std::vector<Point3GLub> pselcolVA;   // Selection colors for points
-
-  GLuint posVAid;   // VBO object ids
-  GLuint nrmlVAid;
-  GLuint selVAid;
-  GLuint texVAid;
-  GLuint imgVAid;
-
-  GLuint pntsVAid;
-  GLuint pcolVAid;
-  GLuint pselVAid;
-
-  GLubyte* texMap;   // Texture map to memory
-
-  // Parameters from stack file
-  QString Section;
-  std::vector<QString> ImageFiles;
-
-  QWidget* parent;   // Parent widget
-  float min, max;
-
-  // Vectors to make heat maps
-  float labelWallBordMin;
-  float labelWallBordMax;
-  QString sigStr;          // Description of heat map
-  IntPoint3fMap LabC;      // Label Centers
-  Point3u clipDo;          // Which clipping planes are selected
-  Point4f pn[6];           // Clip planes tranformed into frame coordinates
-  HVec4F Hpn;              // Host vector for planes for cuda
-  Matrix4d frm;            // Frame matrix
-  Matrix4d clm[3];         // Clip plane matrices
-  float pixelRadius;       // Radius in frame coordinates of pixel edit tool
-  BoundingBox3f bBox;      // Bounding box
-  BoundingBox3i bBoxTex;   // Bounding box for texture update
-  int marchLabel;          // Label for maching cubes on segmented stack
-
-  bool LoadMeshAdd;
-  float meshShift;   // Shift for the mesh, relative to the scene radius
-
-  // Variables to marching cubes (for eval)
-  HVecUS* marchData;
-
-  bool EnableRotate;
-
-  bool readOnce;   // Used for parameter loading
-
-  // Parameters shared by all instances
-  static int ClearColor;
-  static uint Slices;
-  static uint TileCount;
-  static Point3u MaxTexSize;
-  static float ZOffset;
-
-  static float DrawNormals;
-  static float DrawOffset;
-  static float DrawZeroLabels;
-  static float DrawNhbds;
-  static bool DeleteBadVertex;
-  static bool FillWorkData;
-  static bool SeedStack;
-  static int PixelEditRadius;
-  static int PixelEditMaxPix;
-  static std::vector<Colorf> LabelColors;
-  bool LabelColorsChanged;
-
-  static bool MeshSelect;
-  static ScaleBar scaleBar;
-  static Colorbar colorBar;
-
-  static float MeshPointSize;
-  static float MeshLineWidth;
-
-  bool changed;         // Has the stack (mesh) changed
-  bool pixelsChanged;   // Changed flag for pixel editing
-
-public:
-  ImgData(int id, QWidget* _parent = 0);
-
-  ~ImgData();
-
-  void init(Stack* s, Mesh* m);
-
-  // Set the internal format of the data
-  void setWork16Bit(bool val);
-  void setMain16Bit(bool val);
-
-  // Set parameters for function
-  void readParms(util::Parms& parms, QString section);
-
-  // Set parameters for function
-  void writeParms(QTextStream& pout, QString section);
-
-  // Get the frame with or without additional transform
-  qglviewer::ManipulatedFrame& getFrame() {
-    return stack->getFrame();
-  }
-
-  // Get the main frame
-  qglviewer::ManipulatedFrame& getMainFrame() {
-    return stack->frame();
-  }
-
-  // Get the transform frame
-  qglviewer::ManipulatedFrame& getTransFrame() {
-    return stack->trans();
-  }
-
-  // Marching cubes evaluation function
-  int eval(Point3f p);
-
-  // Draw stack data
-  void drawStack(Shader* shader);
-
-  // Set the file containing the current color map
-  void setColorMap(const QString& pth, bool work);
-
-  // Update heat histogram
-  void updateHeatHistogram();
-  // Update surface histogram
-  void updateSurfHistogram();
-  // Update work histogram
-  void updateWorkHistogram();
-  // Update main histogram
-  void updateMainHistogram();
-
-  // Edit the transfer function
-  void editMainTransferFunction(QWidget* parent = 0);
-  void editWorkTransferFunction(QWidget* parent = 0);
-  void editSurfTransferFunction(QWidget* parent = 0);
-  void editHeatTransferFunction(QWidget* parent = 0);
-
-  // Update the color map texture
-  void updateSurfColorMap() {
-    updateColorMap(newSurfColorMap, SurfColorMap, mesh->surfFct());
-  }
-  void updateHeatColorMap() {
-    updateColorMap(newHeatColorMap, HeatColorMap, mesh->heatFct());
-  }
-  void updateWorkColorMap() {
-    updateColorMap(newWorkColorMap, WorkColorMap, stack->work()->transferFct());
-  }
-  void updateMainColorMap() {
-    updateColorMap(newMainColorMap, MainColorMap, stack->main()->transferFct());
-  }
-  void updateColorMap(bool& newColorMap, std::vector<TransferFunction::Colorf>& ColorMap,
-                      const TransferFunction& transferFct);
-
-  // Setup color map to use in draw
-  void setupSurfColorMap() {
-    setupColorMap(newSurfColorMap, surfTexId, SurfColorMap, Shader::AT_SURF_TEX);
-  }
-  void setupHeatColorMap() {
-    setupColorMap(newHeatColorMap, heatTexId, HeatColorMap, Shader::AT_HEAT_TEX);
-  }
-  void setupMainColorMap() {
-    setupColorMap(newMainColorMap, mcmapTexId, MainColorMap, Shader::AT_CMAP_TEX);
-  }
-  void setupMainColorMap2() {
-    setupColorMap(newMainColorMap, mcmapTexId, MainColorMap, Shader::AT_SECOND_CMAP_TEX);
-  }
-  void setupWorkColorMap() {
-    setupColorMap(newWorkColorMap, wcmapTexId, WorkColorMap, Shader::AT_CMAP_TEX);
-  }
-  void setupWorkColorMap2() {
-    setupColorMap(newWorkColorMap, wcmapTexId, WorkColorMap, Shader::AT_SECOND_CMAP_TEX);
-  }
-  void setupLabelColorMap()
-  {
-    std::vector<TransferFunction::Colorf> empty;
-    bool nonew = false;
-    setupColorMap(nonew, labelTexId, empty, Shader::AT_LABEL_TEX);
-  }
-  void setupColorMap(bool& newColorMap, GLuint& cmapTexId, const std::vector<TransferFunction::Colorf>& ColorMap,
-                     Shader::ActiveTextures activeTex);
-
-  // Draw mesh wireframe, select renders point only in AUX buffer
-  void drawMesh(bool select);
-
-  // Draw lines joining corresponding vertices
-  void drawVertexVertexLine(ImgData* stack);   // added by ALR
-
-  // Draw cell axis
-  void drawCellAxis();   // added by ALR
-
-  // Draw Bounding Box around the stack
-  void drawBBox();
-
-  // Setup the uniforms and textures to render 3D data
-  void setup3DRenderingData(Shader* shader);
-
-  // Draw mesh shaded, select renders unique colors in AUX buffer
-  void drawSurf(bool select, Shader* texture_shader = 0, Shader* label_shader = 0, Shader* volume_shader = 0);
-
-  bool showOpaqueSurface() {
-    return mesh->isSurfaceVisible() and !mesh->blending();
-  }
-
-  bool showTransparentSurface() {
-    return mesh->isSurfaceVisible() && mesh->blending() && (mesh->opacity() > 0.0);
-  }
-
-  void setupVolumeShader(Shader& shader, int pos);
-
-  // Mark margin vertices and border labels
-  void markMargin(std::set<vertex>& M, bool remborders);
-
-  // Check if the graph has matching in-out edges
-  void chkGraph();
-
-  // Subdivide bisect, recursively divide to prevent degenerate triangles
-  void subdivideBisect(vertex v1, vertex v2, vertex v3);
-
-  // Get all vertices close to a set of border vertices
-  void markBorder(float borderSize);
-
-  // Get signal and areas by label
-  void getLabelMaps(float borderSize);
-
-  // Test if border triangle
-  bool isBordTriangle(int label, vertex v, vertex n, vertex m, IntIntPair& rp);
-
-  // Setup data for clipping test
-  void getClipTestData(ClipRegion& clip1, ClipRegion& clip2, ClipRegion& clip3);
-
-  // Test if a point (in image coordinates) is inside clipping planes
-  bool clipTest(const Point3i& ip);
-
-  // Routine to connect neighborhoods when loading keyence data
-  void makeNhbd(std::vector<vertex>& vtxs);
-  void makeNhbd(vvgraph& S, vertex v, vertex n1, vertex n2, vertex n3, vertex n4);
-  void makeNhbd(vvgraph& S, vertex v, vertex n1, vertex n2, vertex n3, vertex n4, vertex n5, vertex n6);
-
-  // Save surface for ICP
-  int getPointsICP(std::vector<Point3f>& pts, qglviewer::Frame& frame);
-
-  // Reset stack data
-  void resetStack();
-
-  // Reset mesh data
-  void resetMesh();
-
-  // Initialize controls
-  void initControls(QWidget* viewer);
-
-  // Determine if triangle is labeled, all vertices labelled and the same (or -1 = boundary)
-  int getLabel(vertex v1, vertex v2, vertex v3, bool useParentLabel = true) const;
-
-  // Texture management
-  void unloadTex();
-  void loadTex();
-  void reloadLabelTex();
-  void reloadMainTex(const BoundingBox3i& bbox = BoundingBox3i());
-  void reloadWorkTex(const BoundingBox3i& bbox = BoundingBox3i());
-  void reloadTex(GLuint texId);
-  void updateTex(GLuint texId, BoundingBox3i bBox);
-  void initTex();
-  void bind3DTex(GLuint texId, Shader::ActiveTextures atexId = Shader::AT_TEX3D);
-  void bind2DTex(GLuint texId);
-  void unbind3DTex();
-  void unbind2DTex();
-  void loadImgTex(const QImage& image);
-
-  // Fill selected color with current label (bucket icon)
-  void fillLabel(int label, int currlabel);
-
-  // Set parent label
-  void setParent(int label, int parentLabel);
-
-  // Select the vertices for given label
-  void selectLabel(int label, int repeat = 0);
-
-  // Unselect the vertices for given label
-  void unselectLabel(int label);
-
-  // Select the vertices for given parent
-  void selectParent(int label, int repeat = 0);
-
-  // Unselect the vertices for given parent
-  void unselectParent(int label);
-
-  // Select connected vertices
-  void selectConnected(std::vector<uint>& vlist, bool unselect);
-
-  // Put label on a list of vertices (a triangle)
-  void addSeed(int label, std::vector<uint>& vlist);
-
-  // Fill selection with current
-  void fillSelect(int label);
-
-  // Delete selected vertices
-  void deleteLabel(int label);
-
-  // void markLine(const vertex &s, const vertex &d);
-
-  // Set margins and normals and count triangles for VBOs
-  void marginNormalsVBOs();
-
-  // Update triangle texture coords
-  void updateTris();
-  void updateTris(vvgraph& T);
-
-  // Update points and lines
-  void updateLines();
-
-  // Update positions
-  void updatePos();
-
-  // Fill the vertex array
-  void fillVBOs();
-
-  // Correct the selection
-  void correctSelection(bool inclusive);
-
-  // Update the selection array
-  void updateSelection();
-
-  // Update Color and texture vertex array
-  void updColorVBOs();
-
-  // Update VBO texture coordinate values
-  // RSS: Is this used?
-  // void updTexCoord();
-
-  // Update a list of vertex positions in the VBO
-  void updPos(std::set<uint>& vlist, bool points);
-
-  // Find selected triangle in triangle select mode (!MeshSelect)
-  void findSelectTriangle(uint x, uint y, std::vector<uint>& vlist, int& label, bool useParentLabel = true);
-
-  // Find selected point in mesh select mode (MeshSelect)
-  int findSelectPoint(uint x, uint y);
-
-  // Average a list of vertices to find select point
-  bool findSeedPoint(uint x, uint y, CutSurf& cutSurf, Point3f& p);
-
-  // Clear mesh selection
-  void clearMeshSelect();
-
-  // Add point to selection
-  void addSelect(const std::vector<uint>& vlist);
-
-  // Remove points from selection
-  void removeSelect(const std::vector<uint>& vlist);
-
-  // Update selection colors
-  void updColor(const std::vector<uint>& vlist);
-
-  // Apply a single clip plane to the bounding box
-  void bBoxClip(BoundingBox3f& bBox, Point3f p, Point3f n);
-
-  // Make a bounding box from the clipping planes
-  void bBoxFromClip();
-
-  // Start pixel editing
-  void pixelEditStart(ClipRegion& clip1, ClipRegion& clip2, ClipRegion& clip3);
-
-  // Pixel editing operations
-  // p, px, py and pz should be in world coordinates
-  void pixelEdit(float pixelRadius, const Point3f& p, const Point3f& px, const Point3f& py, const Point3f& pz,
-                 bool doCut, int currentLabel);
-
-  // Stop pixel editing
-  void pixelEditStop();
-
-  bool isMainVisible() const {
-    return stack->main()->isVisible() and mainDataTexId;
-  }
-  bool isWorkVisible() const {
-    return stack->work()->isVisible() and workDataTexId;
-  }
-  bool isVisible() const {
-    return isMainVisible() or isWorkVisible();
-  }
-
-  HVecUS& currentData()
-  {
-    if(stack->work()->isVisible())
-      return stack->work()->data();
-    return stack->main()->data();
-  }
-  const HVecUS& currentData() const
-  {
-    if(stack->work()->isVisible())
-      return stack->work()->data();
-    return stack->main()->data();
-  }
-  Point3f imageGradientW(Point3d worldpos);
-  Point3f imageGradientI(Point3i ipos);
-  uint imageLevel(Point3d worldpos);
-  Point2i imageMinMax();
-
-  GLenum interpolation(GLuint texId)
-  {
-    if(texId == workDataTexId)
-      return stack->work()->labels() ? GL_NEAREST : GL_LINEAR;
-    else
-      return stack->main()->labels() ? GL_NEAREST : GL_LINEAR;
-  }
-
-  GLenum internalFormat(GLuint texId)
-  {
-    if(texId == workDataTexId)
-      return Work16Bit ? GL_ALPHA16 : GL_ALPHA8;
-    else
-      return Main16Bit ? GL_ALPHA16 : GL_ALPHA8;
-  }
-
-  GLenum swapTextureBytes(GLuint texId)
-  {
-    if(texId == workDataTexId)
-      return stack->work()->labels();
-    else
-      return stack->main()->labels();
-  }
-
-  // Set stack sizes
-  void updateStackSize();
-
-  // Change the texture scale of the stack
-  void setTexScale(float s);
-
-  bool valid() const {
-    return stack->storeSize() > 0 and (mainDataTexId or workDataTexId);
-  }
-
-protected:
-  // Update a list of vertex labels
-  void updLabel(int label, std::vector<uint>& vlist);
-
-  // Add a triangle to the VV mesh when converting from unoriented mesh (triangles must be oriented)
-  bool addTriangle(std::vector<vertex>& vertices, Point3i tri);
-
-  // Create mesh from triangle and vertex lists
-  void meshFromTriangles(std::vector<vertex>& vertices, std::vector<Point3i>& triangles);
-
-  // Project signal onto mesh vertices
-  void projSignal(HVecUS& data, vertex v, float mindist, float maxdist);
-
-  // Load 3D texture data, possibly downsampling.
-  void load3DTexData(const GLuint texId, const Point3u size, const ushort* data);
-
-  // Get step for texture decimation
-  Point3u getTexStep();
-
-public:
-  // Clip texture coordinates
-  float trimTex(const float val) {
-    return (trim(val, 0.0f, 1.0f));
-  }
-
-  Point2f trimTex(const Point2f& val) {
-    return (Point2f(trimTex(val.x()), trimTex(val.y())));
-  }
-
-protected:
-  // Return unique triangles
-  static bool uniqueTri(const vvgraph& S, const vertex& v, const vertex& n, const vertex& m)
-  {
-    if(v.id() <= n.id() or v.id() <= m.id() or n.id() == m.id() or !S.edge(v, n) or !S.edge(v, m) or !S.edge(n, m))
-      return false;
-    else
-      return true;
-  }
-
-  // Return unique lines
-  static bool uniqueLine(const vvgraph& S, const vertex& v, const vertex& n)
-  {
-    if(v.id() <= n.id() or !S.edge(v, n))
-      return false;
-    else
-      return true;
-  }
-
-  // Test if quad out of bounds, used for clipping 3D data
-  bool testQuad(float a, float b, float c, float d, float x)
-  {
-    if(a > x and b > x and c > x and d > x)
-      return (true);
-    if(a < -x and b < -x and c < -x and d < -x)
-      return (true);
-    return (false);
-  }
-
-  // See if point should be drawn
-  //  bool pDraw(const vertex &v)
-  //  {
-  //    // Choose which vertices to draw
-  //    if(MeshBorder and !v->margin)
-  //      return false;
-  //    if(MeshCell and v->label != -1)
-  //      return false;
-  //    return true;
-  //  }
-
-  // Get point color
-  Point3GLub pColor(const vertex& v)
-  {
-    // Get the color
-    Color3f c;
-    if(v->selected)
-      c = Colors::getColor(MeshSelectColor);
-    else if(v->minb != 0 or v->label < 0)
-      c = Colors::getColor(MeshBorderColor);
-    else
-      c = Colors::getColor(MeshColor);
-
-    return (Point3GLub(255 * c.x(), 255 * c.y(), 255 * c.z()));
-  }
-
-  // Get line color, and if it should be drawn
-  bool lDraw(const vertex& a, const vertex& b)
-  {
-    // Choose which line to draw
-    if((mesh->meshView() == Mesh::BORDER_MESH)and !(a->margin and b->margin))
-      return false;
-    if((mesh->meshView() == Mesh::CELL_MESH)and !(a->label == -1 and b->label == -1))
-      return false;
-    return true;
-  }
-
-  // Compute offset for image data including border
-  size_t offset(uint x, uint y, uint z) {
-    return stack->offset(x, y, z);
-  }
-
-  size_t offset(Point3i ipos) {
-    return stack->offset(ipos);
-  }
-
-  // Check if in bounds
-  bool boundsOK(int x, int y, int z)
-  {
-    if(x < 0 or y < 0 or z < 0 or x >= int(stack->size().x()) or y >= int(stack->size().y())
-       or z >= int(stack->size().z()))
+    Q_OBJECT
+  public:
+    typedef Mesh::MeshView MeshViewModeEnum;
+  
+    static const uint RELOAD_NONE = 0x0;
+    static const uint RELOAD_MAIN = 0x1;
+    static const uint RELOAD_WORK = 0x2;
+    static const uint RELOAD_TRIS = 0x4;
+    static const uint RELOAD_LINES = 0x8;
+    static const uint RELOAD_POS = 0x10;
+    static const uint RELOAD_VBO = 0x20;
+    static const uint UPDATE_SELECTION = 0x40;
+  
+    int StackId;
+  
+    Stack* stack;
+    Mesh* mesh;
+  
+    // Main and stack paramters
+    bool Main16Bit, Work16Bit;
+  
+    // General
+    bool needUpdateLines;
+    bool needUpdateTris;
+  
+    gui::TransferFunctionDlg* workTransferDlg, *mainTransferDlg, *surfTransferDlg, *heatTransferDlg;
+    // Function defining the color of the pixels
+    std::vector<TransferFunction::Colorf> MainColorMap;   // Color map for the main data
+    std::vector<TransferFunction::Colorf> WorkColorMap;   // Color map for the work data
+    std::vector<TransferFunction::Colorf> SurfColorMap;   // Color map for the surface
+    std::vector<TransferFunction::Colorf> HeatColorMap;   // Color map for the heatmap
+    // If true, a new texture need to be sent for the colormap
+    bool newMainColorMap, newWorkColorMap, newSurfColorMap, newHeatColorMap;
+    std::vector<double> MainHist;   // Histogram of the main data
+    std::vector<double> WorkHist;   // Histogram of the working data
+    std::vector<double> SurfHist;   // Histogram of the surface data
+    std::vector<double> HeatHist;   // Histogram of the surface data
+    std::pair<double, double> mainBounds;
+    std::pair<double, double> workBounds;
+  
+    GLuint mainDataTexId;              // 3D texture Id for main stack
+    GLuint workDataTexId;              // 3D texture Id for work stack
+    GLuint dataTexColor;               // 3D texture color
+    GLuint surfTexId;                  // 1D texture map for surface colors.
+    GLuint heatTexId;                  // 1D texture map for heatmap colors.
+    GLuint imgTexId;                   // 2D texture map for surface from an image
+    GLuint mcmapTexId, wcmapTexId;     // 1D texture map for volume colors.
+    GLuint labelTexId;                 // 1D texture map to color indexed texture for labels
+    graph::vertex_identity_t lineId;   // Last id when drawing lines
+    std::set<uint> selectV;            // List of selected vertices
+  
+    Colors::ColorType MeshColor;
+    Colors::ColorType MeshBorderColor;
+    // Colors::ColorType MeshPointColor;
+    Colors::ColorType MeshSelectColor;
+  
+    int TCount;   // Triangle count
+    int LCount;   // Line count
+    int VCount;   // Vertex count
+  
+    // Helper arrays for vertex buffer obejects
+    std::vector<vertex> idVA;                // Vertex ids, used to find selection in triangle mode (!MeshSelect)
+    std::vector<vertex> pidVA;               // Point vtx ids, used to find selection in point mode (MeshSelect)
+    std::unordered_map<vertex, uint> vMap;   // Pointer into idVA by vertex
+  
+    // VBO arrays
+    std::vector<Point3f> posVA;      // Vertex positions
+    std::vector<Point3f> nrmlVA;     // Vertex normals
+    std::vector<Point3GLub> selVA;   // Unique colors for triangle selection
+    std::vector<Point3f> texVA;      // Mesh labels, signal, and heat
+    std::vector<Point2f> imgVA;      // Image texture coordinates
+  
+    std::vector<uint> lineVA;    // Indices for drawing lines
+    std::vector<uint> lbrdVA;    // Indices for drawing border lines
+    std::vector<uint> lcellVA;   // Indices for drawing cell border lines
+    std::vector<uint> lselVA;    // Indices for drawing selected lines
+  
+    std::vector<uint> pbrdVA;            // Indices for drawing border points
+    std::vector<uint> pcellVA;           // Indices for drawing cell border points
+    std::vector<uint> pselVA;            // Indices for drawing selected points
+    std::vector<Point3f> pntsVA;         // Vertices for drawing points
+    std::vector<Point3GLub> pcolVA;      // Colors for points
+    std::vector<Point3GLub> pselcolVA;   // Selection colors for points
+  
+    GLuint posVAid;   // VBO object ids
+    GLuint nrmlVAid;
+    GLuint selVAid;
+    GLuint texVAid;
+    GLuint imgVAid;
+  
+    GLuint pntsVAid;
+    GLuint pcolVAid;
+    GLuint pselVAid;
+  
+    GLubyte* texMap;   // Texture map to memory
+  
+    // Parameters from stack file
+    QString Section;
+    std::vector<QString> ImageFiles;
+  
+    QWidget* parent;   // Parent widget
+    float min, max;
+  
+    // Vectors to make heat maps
+    float labelWallBordMin;
+    float labelWallBordMax;
+    QString sigStr;          // Description of heat map
+    IntPoint3fMap LabC;      // Label Centers
+    Point3u clipDo;          // Which clipping planes are selected
+    Point4f pn[6];           // Clip planes tranformed into frame coordinates
+    HVec4F Hpn;              // Host vector for planes for cuda
+    Matrix4d frm;            // Frame matrix
+    Matrix4d clm[3];         // Clip plane matrices
+    float pixelRadius;       // Radius in frame coordinates of pixel edit tool
+    BoundingBox3f bBox;      // Bounding box
+    BoundingBox3i bBoxTex;   // Bounding box for texture update
+    int marchLabel;          // Label for maching cubes on segmented stack
+  
+    bool LoadMeshAdd;
+    float meshShift;   // Shift for the mesh, relative to the scene radius
+  
+    // Variables to marching cubes (for eval)
+    HVecUS* marchData;
+  
+    bool EnableRotate;
+  
+    bool readOnce;   // Used for parameter loading
+  
+    // Parameters shared by all instances
+    static int ClearColor;
+    static uint Slices;
+    static uint TileCount;
+    static Point3u MaxTexSize;
+    static float ZOffset;
+  
+    static float DrawNormals;
+    static float DrawOffset;
+    static float DrawZeroLabels;
+    static float DrawNhbds;
+    static bool DeleteBadVertex;
+    static bool FillWorkData;
+    static bool SeedStack;
+    static int PixelEditRadius;
+    static int PixelEditMaxPix;
+    static std::vector<Colorf> LabelColors;
+    bool LabelColorsChanged;
+  
+    static bool MeshSelect;
+    static ScaleBar scaleBar;
+    static Colorbar colorBar;
+  
+    static float MeshPointSize;
+    static float MeshLineWidth;
+  
+    bool changed;         // Has the stack (mesh) changed
+    bool pixelsChanged;   // Changed flag for pixel editing
+  
+  public:
+    ImgData(int id, QWidget* _parent = 0);
+  
+    ~ImgData();
+  
+    void init(Stack* s, Mesh* m);
+  
+    // Set the internal format of the data
+    void setWork16Bit(bool val);
+    void setMain16Bit(bool val);
+  
+    // Set parameters for function
+    void readParms(util::Parms& parms, QString section);
+  
+    // Set parameters for function
+    void writeParms(QTextStream& pout, QString section);
+  
+    // Get the frame with or without additional transform
+    qglviewer::ManipulatedFrame& getFrame() {
+      return stack->getFrame();
+    }
+  
+    // Get the main frame
+    qglviewer::ManipulatedFrame& getMainFrame() {
+      return stack->frame();
+    }
+  
+    // Get the transform frame
+    qglviewer::ManipulatedFrame& getTransFrame() {
+      return stack->trans();
+    }
+  
+    // Marching cubes evaluation function
+    int eval(Point3f p);
+  
+    // Draw stack data
+    void drawStack(Shader* shader);
+  
+    // Set the file containing the current color map
+    void setColorMap(const QString& pth, bool work);
+  
+    // Update heat histogram
+    void updateHeatHistogram();
+    // Update surface histogram
+    void updateSurfHistogram();
+    // Update work histogram
+    void updateWorkHistogram();
+    // Update main histogram
+    void updateMainHistogram();
+  
+    // Edit the transfer function
+    void editMainTransferFunction(QWidget* parent = 0);
+    void editWorkTransferFunction(QWidget* parent = 0);
+    void editSurfTransferFunction(QWidget* parent = 0);
+    void editHeatTransferFunction(QWidget* parent = 0);
+  
+    // Update the color map texture
+    void updateSurfColorMap() {
+      updateColorMap(newSurfColorMap, SurfColorMap, mesh->surfFct());
+    }
+    void updateHeatColorMap() {
+      updateColorMap(newHeatColorMap, HeatColorMap, mesh->heatFct());
+    }
+    void updateWorkColorMap() {
+      updateColorMap(newWorkColorMap, WorkColorMap, stack->work()->transferFct());
+    }
+    void updateMainColorMap() {
+      updateColorMap(newMainColorMap, MainColorMap, stack->main()->transferFct());
+    }
+    void updateColorMap(bool& newColorMap, std::vector<TransferFunction::Colorf>& ColorMap,
+                        const TransferFunction& transferFct);
+  
+    // Setup color map to use in draw
+    void setupSurfColorMap() {
+      setupColorMap(newSurfColorMap, surfTexId, SurfColorMap, Shader::AT_SURF_TEX);
+    }
+    void setupHeatColorMap() {
+      setupColorMap(newHeatColorMap, heatTexId, HeatColorMap, Shader::AT_HEAT_TEX);
+    }
+    void setupMainColorMap() {
+      setupColorMap(newMainColorMap, mcmapTexId, MainColorMap, Shader::AT_CMAP_TEX);
+    }
+    void setupMainColorMap2() {
+      setupColorMap(newMainColorMap, mcmapTexId, MainColorMap, Shader::AT_SECOND_CMAP_TEX);
+    }
+    void setupWorkColorMap() {
+      setupColorMap(newWorkColorMap, wcmapTexId, WorkColorMap, Shader::AT_CMAP_TEX);
+    }
+    void setupWorkColorMap2() {
+      setupColorMap(newWorkColorMap, wcmapTexId, WorkColorMap, Shader::AT_SECOND_CMAP_TEX);
+    }
+    void setupLabelColorMap()
+    {
+      std::vector<TransferFunction::Colorf> empty;
+      bool nonew = false;
+      setupColorMap(nonew, labelTexId, empty, Shader::AT_LABEL_TEX);
+    }
+    void setupColorMap(bool& newColorMap, GLuint& cmapTexId, const std::vector<TransferFunction::Colorf>& ColorMap,
+                       Shader::ActiveTextures activeTex);
+  
+    // Draw mesh wireframe, select renders point only in AUX buffer
+    void drawMesh(bool select);
+  
+    // Draw lines joining corresponding vertices
+    void drawVertexVertexLine(ImgData* stack);   // added by ALR
+  
+    // Draw cell axis
+    void drawCellAxis();   // added by ALR
+  
+    // Draw Bounding Box around the stack
+    void drawBBox();
+  
+    // Setup the uniforms and textures to render 3D data
+    void setup3DRenderingData(Shader* shader);
+  
+    // Draw mesh shaded, select renders unique colors in AUX buffer
+    void drawSurf(bool select, Shader* texture_shader = 0, Shader* label_shader = 0, Shader* volume_shader = 0);
+  
+    bool showOpaqueSurface() {
+      return mesh->isSurfaceVisible() and !mesh->blending();
+    }
+  
+    bool showTransparentSurface() {
+      return mesh->isSurfaceVisible() && mesh->blending() && (mesh->opacity() > 0.0);
+    }
+  
+    void setupVolumeShader(Shader& shader, int pos);
+  
+    // Mark margin vertices and border labels
+    void markMargin(std::set<vertex>& M, bool remborders);
+  
+    // Check if the graph has matching in-out edges
+    void chkGraph();
+  
+    // Subdivide bisect, recursively divide to prevent degenerate triangles
+    void subdivideBisect(vertex v1, vertex v2, vertex v3);
+  
+    // Get all vertices close to a set of border vertices
+    void markBorder(float borderSize);
+  
+    // Get signal and areas by label
+    void getLabelMaps(float borderSize);
+  
+    // Test if border triangle
+    bool isBordTriangle(int label, vertex v, vertex n, vertex m, IntIntPair& rp);
+  
+    // Setup data for clipping test
+    void getClipTestData(ClipRegion& clip1, ClipRegion& clip2, ClipRegion& clip3);
+  
+    // Test if a point (in image coordinates) is inside clipping planes
+    bool clipTest(const Point3i& ip);
+  
+    // Routine to connect neighborhoods when loading keyence data
+    void makeNhbd(std::vector<vertex>& vtxs);
+    void makeNhbd(vvgraph& S, vertex v, vertex n1, vertex n2, vertex n3, vertex n4);
+    void makeNhbd(vvgraph& S, vertex v, vertex n1, vertex n2, vertex n3, vertex n4, vertex n5, vertex n6);
+  
+    // Save surface for ICP
+    int getPointsICP(std::vector<Point3f>& pts, qglviewer::Frame& frame);
+  
+    // Reset stack data
+    void resetStack();
+  
+    // Reset mesh data
+    void resetMesh();
+  
+    // Initialize controls
+    void initControls(QWidget* viewer);
+  
+    // Determine if triangle is labeled, all vertices labelled and the same (or -1 = boundary)
+    int getLabel(vertex v1, vertex v2, vertex v3, bool useParentLabel = true) const;
+  
+    // Texture management
+    void unloadTex();
+    void loadTex();
+    void reloadLabelTex();
+    void reloadMainTex(const BoundingBox3i& bbox = BoundingBox3i());
+    void reloadWorkTex(const BoundingBox3i& bbox = BoundingBox3i());
+    void reloadTex(GLuint texId);
+    void updateTex(GLuint texId, BoundingBox3i bBox);
+    void initTex();
+    void bind3DTex(GLuint texId, Shader::ActiveTextures atexId = Shader::AT_TEX3D);
+    void bind2DTex(GLuint texId);
+    void unbind3DTex();
+    void unbind2DTex();
+    void loadImgTex(const QImage& image);
+  
+    // Fill selected color with current label (bucket icon)
+    void fillLabel(int label, int currlabel);
+  
+    // Set parent label
+    void setParent(int label, int parentLabel);
+  
+    // Select the vertices for given label
+    void selectLabel(int label, int repeat = 0);
+  
+    // Unselect the vertices for given label
+    void unselectLabel(int label);
+  
+    // Select the vertices for given parent
+    void selectParent(int label, int repeat = 0);
+  
+    // Unselect the vertices for given parent
+    void unselectParent(int label);
+  
+    // Select connected vertices
+    void selectConnected(std::vector<uint>& vlist, bool unselect);
+  
+    // Put label on a list of vertices (a triangle)
+    void addSeed(int label, std::vector<uint>& vlist);
+  
+    // Fill selection with current
+    void fillSelect(int label);
+  
+    // Delete selected vertices
+    void deleteLabel(int label);
+  
+    // void markLine(const vertex &s, const vertex &d);
+  
+    // Set margins and normals and count triangles for VBOs
+    void marginNormalsVBOs();
+  
+    // Update triangle texture coords
+    void updateTris();
+    void updateTris(vvgraph& T);
+  
+    // Update points and lines
+    void updateLines();
+  
+    // Update positions
+    void updatePos();
+  
+    // Fill the vertex array
+    void fillVBOs();
+  
+    // Correct the selection
+    void correctSelection(bool inclusive);
+  
+    // Update the selection array
+    void updateSelection();
+  
+    // Update Color and texture vertex array
+    void updColorVBOs();
+  
+    // Update VBO texture coordinate values
+    // RSS: Is this used?
+    // void updTexCoord();
+  
+    // Update a list of vertex positions in the VBO
+    void updPos(std::set<uint>& vlist, bool points);
+  
+    // Find selected triangle in triangle select mode (!MeshSelect)
+    void findSelectTriangle(uint x, uint y, std::vector<uint>& vlist, int& label, bool useParentLabel = true);
+  
+    // Find selected point in mesh select mode (MeshSelect)
+    int findSelectPoint(uint x, uint y);
+  
+    // Average a list of vertices to find select point
+    bool findSeedPoint(uint x, uint y, CutSurf& cutSurf, Point3f& p);
+  
+    // Clear mesh selection
+    void clearMeshSelect();
+  
+    // Add point to selection
+    void addSelect(const std::vector<uint>& vlist);
+  
+    // Remove points from selection
+    void removeSelect(const std::vector<uint>& vlist);
+  
+    // Update selection colors
+    void updColor(const std::vector<uint>& vlist);
+  
+    // Apply a single clip plane to the bounding box
+    void bBoxClip(BoundingBox3f& bBox, Point3f p, Point3f n);
+  
+    // Make a bounding box from the clipping planes
+    void bBoxFromClip();
+  
+    // Start pixel editing
+    void pixelEditStart(ClipRegion& clip1, ClipRegion& clip2, ClipRegion& clip3);
+  
+    // Pixel editing operations
+    // p, px, py and pz should be in world coordinates
+    void pixelEdit(float pixelRadius, const Point3f& p, const Point3f& px, const Point3f& py, const Point3f& pz,
+                   bool doCut, int currentLabel);
+  
+    // Stop pixel editing
+    void pixelEditStop();
+  
+    bool isMainVisible() const {
+      return stack->main()->isVisible() and mainDataTexId;
+    }
+    bool isWorkVisible() const {
+      return stack->work()->isVisible() and workDataTexId;
+    }
+    bool isVisible() const {
+      return isMainVisible() or isWorkVisible();
+    }
+  
+    HVecUS& currentData()
+    {
+      if(stack->work()->isVisible())
+        return stack->work()->data();
+      return stack->main()->data();
+    }
+    const HVecUS& currentData() const
+    {
+      if(stack->work()->isVisible())
+        return stack->work()->data();
+      return stack->main()->data();
+    }
+    Point3f imageGradientW(Point3d worldpos);
+    Point3f imageGradientI(Point3i ipos);
+    uint imageLevel(Point3d worldpos);
+    Point2i imageMinMax();
+  
+    GLenum interpolation(GLuint texId)
+    {
+      if(texId == workDataTexId)
+        return stack->work()->labels() ? GL_NEAREST : GL_LINEAR;
+      else
+        return stack->main()->labels() ? GL_NEAREST : GL_LINEAR;
+    }
+  
+    GLenum internalFormat(GLuint texId)
+    {
+      if(texId == workDataTexId)
+        return Work16Bit ? GL_ALPHA16 : GL_ALPHA8;
+      else
+        return Main16Bit ? GL_ALPHA16 : GL_ALPHA8;
+    }
+  
+    GLenum swapTextureBytes(GLuint texId)
+    {
+      if(texId == workDataTexId)
+        return stack->work()->labels();
+      else
+        return stack->main()->labels();
+    }
+  
+    // Set stack sizes
+    void updateStackSize();
+  
+    // Change the texture scale of the stack
+    void setTexScale(float s);
+  
+    bool valid() const {
+      return stack->storeSize() > 0 and (mainDataTexId or workDataTexId);
+    }
+  
+  protected:
+    // Update a list of vertex labels
+    void updLabel(int label, std::vector<uint>& vlist);
+  
+    // Add a triangle to the VV mesh when converting from unoriented mesh (triangles must be oriented)
+    bool addTriangle(std::vector<vertex>& vertices, Point3i tri);
+  
+    // Create mesh from triangle and vertex lists
+    void meshFromTriangles(std::vector<vertex>& vertices, std::vector<Point3i>& triangles);
+  
+    // Project signal onto mesh vertices
+    void projSignal(HVecUS& data, vertex v, float mindist, float maxdist);
+  
+    // Load 3D texture data, possibly downsampling.
+    void load3DTexData(const GLuint texId, const Point3u size, const ushort* data);
+  
+    // Get step for texture decimation
+    Point3u getTexStep();
+  
+  public:
+    // Clip texture coordinates
+    float trimTex(const float val) {
+      return (trim(val, 0.0f, 1.0f));
+    }
+  
+    Point2f trimTex(const Point2f& val) {
+      return (Point2f(trimTex(val.x()), trimTex(val.y())));
+    }
+  
+  protected:
+    // Return unique triangles
+    static bool uniqueTri(const vvgraph& S, const vertex& v, const vertex& n, const vertex& m)
+    {
+      if(v.id() <= n.id() or v.id() <= m.id() or n.id() == m.id() or !S.edge(v, n) or !S.edge(v, m) or !S.edge(n, m))
+        return false;
+      else
+        return true;
+    }
+  
+    // Return unique lines
+    static bool uniqueLine(const vvgraph& S, const vertex& v, const vertex& n)
+    {
+      if(v.id() <= n.id() or !S.edge(v, n))
+        return false;
+      else
+        return true;
+    }
+  
+    // Test if quad out of bounds, used for clipping 3D data
+    bool testQuad(float a, float b, float c, float d, float x)
+    {
+      if(a > x and b > x and c > x and d > x)
+        return (true);
+      if(a < -x and b < -x and c < -x and d < -x)
+        return (true);
       return (false);
-    else
-      return (true);
-  }
-
-public:
-  /// Go from image coordinates to world coordinates
-  template <typename T> Point3f imageToWorld(const util::Vector<3, T>& img) const
-  {
-    return stack->imageToWorld<T>(img);
-  }
-
-  /// Go from world coordinates to image coordinates
-  template <typename T> util::Vector<3, T> worldToImage(Point3f wrld) const {
-    return stack->worldToImage<T>(wrld);
-  }
-
-  Point3f worldToImagef(const Point3f& a) const {
-    return worldToImage<float>(a);
-  }
-  Point3i worldToImagei(const Point3f& a) const {
-    return worldToImage<int>(a);
-  }
-  Point3u worldToImageu(const Point3f& a) const {
-    return worldToImage<uint>(a);
-  }
-
-  // Map scale slider values
-  int toSliderScale(float s);
-  float fromSliderScale(int i);
-
-protected:
-  void updateHistogram(std::vector<double>& hist, const HVecUS& data, std::pair<double, double>& minMaxValues,
-                       int max_data = 1 << 16, int size = 512);
-  void invalidateHistogram(std::vector<double>& hist) {
-    hist.clear();
-  }
-
-  // Clear 3D stack texture
-  void clearData(HVecUS& data)
-  {
-    data.resize(stack->storeSize());
-    memset(&data[0], 0, data.size() * sizeof(ushort));
-  }
-
-  // Return texture info for a vertex (this version used to update color when drawing on mesh)
-  Point3f texCoord(int label, vertex v);
-
-  // Return texture info for a vertex (this version used to fill VBOs and respects wall heatmap)
-  Point3f texCoord(int label, vertex v, vertex a, vertex b, vertex c);
-
-  // Set label on triangle
-  bool setLabel(vertex v1, vertex v2, vertex v3, int label)
-  {
-    bool ok = true;
-    if(v1->label > 0 and v1->label != label)
-      ok = false;
-    if(v2->label > 0 and v2->label != label)
-      ok = false;
-    if(v3->label > 0 and v3->label != label)
-      ok = false;
-
-    if(ok) {
-      if(v1->label == 0)
-        v1->label = label;
-      if(v2->label == 0)
-        v2->label = label;
-      if(v3->label == 0)
-        v3->label = label;
     }
-    return (ok);
-  }
+  
+    // See if point should be drawn
+    //  bool pDraw(const vertex &v)
+    //  {
+    //    // Choose which vertices to draw
+    //    if(MeshBorder and !v->margin)
+    //      return false;
+    //    if(MeshCell and v->label != -1)
+    //      return false;
+    //    return true;
+    //  }
+  
+    // Get point color
+    Point3GLub pColor(const vertex& v)
+    {
+      // Get the color
+      Color3f c;
+      if(v->selected)
+        c = Colors::getColor(MeshSelectColor);
+      else if(v->minb != 0 or v->label < 0)
+        c = Colors::getColor(MeshBorderColor);
+      else
+        c = Colors::getColor(MeshColor);
+  
+      return (Point3GLub(255 * c.x(), 255 * c.y(), 255 * c.z()));
+    }
+  
+    // Get line color, and if it should be drawn
+    bool lDraw(const vertex& a, const vertex& b)
+    {
+      // Choose which line to draw
+      if((mesh->meshView() == Mesh::BORDER_MESH)and !(a->margin and b->margin))
+        return false;
+      if((mesh->meshView() == Mesh::CELL_MESH)and !(a->label == -1 and b->label == -1))
+        return false;
+      return true;
+    }
+  
+    // Compute offset for image data including border
+    size_t offset(uint x, uint y, uint z) {
+      return stack->offset(x, y, z);
+    }
+  
+    size_t offset(Point3i ipos) {
+      return stack->offset(ipos);
+    }
+  
+    // Check if in bounds
+    bool boundsOK(int x, int y, int z)
+    {
+      if(x < 0 or y < 0 or z < 0 or x >= int(stack->size().x()) or y >= int(stack->size().y())
+         or z >= int(stack->size().z()))
+        return (false);
+      else
+        return (true);
+    }
+  
+  public:
+    /// Go from image coordinates to world coordinates
+    template <typename T> Point3f imageToWorld(const util::Vector<3, T>& img) const
+    {
+      return stack->imageToWorld<T>(img);
+    }
+  
+    /// Go from world coordinates to image coordinates
+    template <typename T> util::Vector<3, T> worldToImage(Point3f wrld) const {
+      return stack->worldToImage<T>(wrld);
+    }
+  
+    Point3f worldToImagef(const Point3f& a) const {
+      return worldToImage<float>(a);
+    }
+    Point3i worldToImagei(const Point3f& a) const {
+      return worldToImage<int>(a);
+    }
+    Point3u worldToImageu(const Point3f& a) const {
+      return worldToImage<uint>(a);
+    }
+  
+    // Map scale slider values
+    int toSliderScale(float s);
+    float fromSliderScale(int i);
+  
+  protected:
+    void updateHistogram(std::vector<double>& hist, const HVecUS& data, std::pair<double, double>& minMaxValues,
+                         int max_data = 1 << 16, int size = 512);
+    void invalidateHistogram(std::vector<double>& hist) {
+      hist.clear();
+    }
+  
+    // Clear 3D stack texture
+    void clearData(HVecUS& data)
+    {
+      data.resize(stack->storeSize());
+      memset(&data[0], 0, data.size() * sizeof(ushort));
+    }
+  
+    // Return texture info for a vertex (this version used to update color when drawing on mesh)
+    Point3f texCoord(int label, vertex v);
+  
+    // Return texture info for a vertex (this version used to fill VBOs and respects wall heatmap)
+    Point3f texCoord(int label, vertex v, vertex a, vertex b, vertex c);
+  
+    // Set label on triangle
+    bool setLabel(vertex v1, vertex v2, vertex v3, int label)
+    {
+      bool ok = true;
+      if(v1->label > 0 and v1->label != label)
+        ok = false;
+      if(v2->label > 0 and v2->label != label)
+        ok = false;
+      if(v3->label > 0 and v3->label != label)
+        ok = false;
+  
+      if(ok) {
+        if(v1->label == 0)
+          v1->label = label;
+        if(v2->label == 0)
+          v2->label = label;
+        if(v3->label == 0)
+          v3->label = label;
+      }
+      return (ok);
+    }
+  
+  signals:
+    void changedInterface();
+    // void changeSize(uint x, uint y, uint z, float xstep, float ystep, float zstep);
+    void changeSize(const Point3u& size, const Point3f& step, const Point3f& origin);
+    void stackUnloaded();
+  
+  public slots:
+    // Update the colors of all points in the mesh
+    void updColor();
+  
+    // Slots for controls
+    void MainShowSlot(bool val);
+    void MainBrightSlot(int val);
+    void MainOpacitySlot(int val);
+    void MainLabelsSlot(bool val);
+    void Main16BitSlot(bool val);
+  
+    void WorkShowSlot(bool val);
+    void WorkBrightSlot(int val);
+    void WorkOpacitySlot(int val);
+    void WorkLabelsSlot(bool val);
+    void Work16BitSlot(bool val);
+  
+    void SurfShowSlot(bool val);
+    void SurfBrightSlot(int val);
+    void SurfOpacitySlot(int val);
+    void SurfBlendSlot(bool val);
+    void SurfCullSlot(bool val);
+  
+    void SurfNormalSlot(bool val);
+    void SurfLabelSlot(bool val);
+    void SurfHeatSlot(bool val);
+    void SurfParentSlot(bool val);
+  
+    void SurfSignalSlot(bool val);
+    void SurfTextureSlot(bool val);
+    void SurfImageSlot(bool val);
+  
+    void MeshShowSlot(bool val);
+    void ChangeMeshViewModeSlot(int mode);
+    void MeshLinesSlot(bool val);
+    void MeshPointsSlot(bool val);
+  
+    void CellMapSlot(bool val);
+    void ShowTransSlot(bool val);
+    void ShowScaleSlot(bool val);
+    void ShowBBoxSlot(bool val);
+    void TieScalesSlot(bool val);   // ALR
+    void ScaleSlotX(int val);
+    void ScaleSlotY(int val);
+    void ScaleSlotZ(int val);
+  
+    // Slots to change transfer functions
+    void setSurfColorMap(const TransferFunction& fct);
+    void setHeatColorMap(const TransferFunction& fct);
+    void setWorkColorMap(const TransferFunction& fct);
+    void setMainColorMap(const TransferFunction& fct);
+  
+    // Slots to detect changes in transfer fct dialog boxes
+    void updateSurfColorMap(const TransferFunction& fct);
+    void updateHeatColorMap(const TransferFunction& fct);
+    void updateWorkColorMap(const TransferFunction& fct);
+    void updateMainColorMap(const TransferFunction& fct);
+  
+    // Update lines or tris
+    void updateImgData();
+    void postUpdateImgData(bool lines, bool tris);
+  
+  signals:
+    void viewerUpdate();
+    void updateSliderScale();
+    void forceSurfHeat();
+  };
 
-signals:
-  void changedInterface();
-  // void changeSize(uint x, uint y, uint z, float xstep, float ystep, float zstep);
-  void changeSize(const Point3u& size, const Point3f& step, const Point3f& origin);
-  void stackUnloaded();
-
-public slots:
-  // Update the colors of all points in the mesh
-  void updColor();
-
-  // Slots for controls
-  void MainShowSlot(bool val);
-  void MainBrightSlot(int val);
-  void MainOpacitySlot(int val);
-  void MainLabelsSlot(bool val);
-  void Main16BitSlot(bool val);
-
-  void WorkShowSlot(bool val);
-  void WorkBrightSlot(int val);
-  void WorkOpacitySlot(int val);
-  void WorkLabelsSlot(bool val);
-  void Work16BitSlot(bool val);
-
-  void SurfShowSlot(bool val);
-  void SurfBrightSlot(int val);
-  void SurfOpacitySlot(int val);
-  void SurfBlendSlot(bool val);
-  void SurfCullSlot(bool val);
-
-  void SurfNormalSlot(bool val);
-  void SurfLabelSlot(bool val);
-  void SurfHeatSlot(bool val);
-  void SurfParentSlot(bool val);
-
-  void SurfSignalSlot(bool val);
-  void SurfTextureSlot(bool val);
-  void SurfImageSlot(bool val);
-
-  void MeshShowSlot(bool val);
-  void ChangeMeshViewModeSlot(int mode);
-  void MeshLinesSlot(bool val);
-  void MeshPointsSlot(bool val);
-
-  void CellMapSlot(bool val);
-  void ShowTransSlot(bool val);
-  void ShowScaleSlot(bool val);
-  void ShowBBoxSlot(bool val);
-  void TieScalesSlot(bool val);   // ALR
-  void ScaleSlotX(int val);
-  void ScaleSlotY(int val);
-  void ScaleSlotZ(int val);
-
-  // Slots to change transfer functions
-  void setSurfColorMap(const TransferFunction& fct);
-  void setHeatColorMap(const TransferFunction& fct);
-  void setWorkColorMap(const TransferFunction& fct);
-  void setMainColorMap(const TransferFunction& fct);
-
-  // Slots to detect changes in transfer fct dialog boxes
-  void updateSurfColorMap(const TransferFunction& fct);
-  void updateHeatColorMap(const TransferFunction& fct);
-  void updateWorkColorMap(const TransferFunction& fct);
-  void updateMainColorMap(const TransferFunction& fct);
-
-  // Update lines or tris
-  void updateImgData();
-  void postUpdateImgData(bool lines, bool tris);
-
-signals:
-  void viewerUpdate();
-  void updateSliderScale();
-  void forceSurfHeat();
-};
-} // namespace mgx
-#endif /*IMAGE_DATA_H*/
+}
+#endif
Index: MorphoGraphX.hpp
===================================================================
--- MorphoGraphX.hpp	(revision 1255)
+++ MorphoGraphX.hpp	(revision 1256)
@@ -145,8 +145,8 @@
   void ImportMesh(int stack);
   void ExportMesh(int stack);
   void ResetMesh(int mesh);
-  void LoadMesh(int stack);
-  void SaveMesh(int stack);
+  void LoadMesh(int mesh);
+  void SaveMesh(int mesh);
   void ImportStack(int stack, bool main);
   void ImportStackSeries(int stack, bool main);
   void OpenStack(int stack, bool main);
@@ -191,13 +191,10 @@
   void LoadView(const QString& filename);
   void SaveView(const QString& filename);
 
-  void FileSaveAllSlot();
-  void FileReloadAllSlot();
   void FileEditPathsSlot();
   void FileOpenSlot();
   void FileSaveSlot();
   void FileSaveAsSlot();
-  void FileResetAllSlot();
   void ExitSlot();
 
   void GlobalContrastSlot();
Index: SystemProcess.cpp
===================================================================
--- SystemProcess.cpp	(revision 1255)
+++ SystemProcess.cpp	(revision 1256)
@@ -3,52 +3,49 @@
 #include "SystemProcessSave.hpp"
 #include "Information.hpp"
 
-namespace mgx {
-namespace process {
+namespace mgx { namespace process {
 
-#define INIT_PROCESS(varName, ClassName, ProcessClass) \
-  varName(new ClassProcessFactory<ProcessClass, ClassName>(), typeid(ClassName).name(), PROCESS_VERSION)
-
-struct SystemRegistration {
-  SystemRegistration()
-    : INIT_PROCESS(stackImport, StackImport, StackProcess)
-    , INIT_PROCESS(stackOpen, StackOpen, StackProcess)
-    , INIT_PROCESS(stackExport, StackExport, StackProcess)
-    , INIT_PROCESS(stackSave, StackSave, StackProcess)
-    , INIT_PROCESS(meshImport, MeshImport, MeshProcess)
-    , INIT_PROCESS(meshLoad, MeshLoad, MeshProcess)
-    , INIT_PROCESS(meshExport, MeshExport, MeshProcess)
-    , INIT_PROCESS(meshSave, MeshSave, MeshProcess)
-    , INIT_PROCESS(meshReset, ResetMeshProcess, MeshProcess)
-    , INIT_PROCESS(loadAllData, LoadAllData, GlobalProcess)
-    , INIT_PROCESS(loadViewFile, LoadViewFile, GlobalProcess)
-    , INIT_PROCESS(saveViewFile, SaveViewFile, GlobalProcess)
-    , INIT_PROCESS(saveAll, SaveAll, GlobalProcess)
-    , INIT_PROCESS(resetAll, ResetAll, GlobalProcess)
-    , INIT_PROCESS(takeSnapshot, TakeSnapshot, GlobalProcess)
+  #define INIT_PROCESS(varName, ClassName, ProcessClass) \
+    varName(new ClassProcessFactory<ProcessClass, ClassName>(), typeid(ClassName).name(), PROCESS_VERSION)
+  
+  struct SystemRegistration {
+    SystemRegistration()
+      : INIT_PROCESS(stackImport, StackImport, StackProcess),
+        INIT_PROCESS(stackOpen, StackOpen, StackProcess),
+        INIT_PROCESS(stackExport, StackExport, StackProcess),
+        INIT_PROCESS(stackSave, StackSave, StackProcess),
+        INIT_PROCESS(meshImport, MeshImport, MeshProcess),
+        INIT_PROCESS(meshLoad, MeshLoad, MeshProcess),
+        INIT_PROCESS(meshExport, MeshExport, MeshProcess),
+        INIT_PROCESS(meshSave, MeshSave, MeshProcess),
+        INIT_PROCESS(meshReset, ResetMeshProcess, MeshProcess),
+        INIT_PROCESS(loadParents, LoadParents, MeshProcess),
+        INIT_PROCESS(saveParents, SaveParents, MeshProcess),
+        INIT_PROCESS(resetParents, ResetParents, MeshProcess),
+        INIT_PROCESS(loadViewFile, LoadViewFile, GlobalProcess),
+        INIT_PROCESS(saveViewFile, SaveViewFile, GlobalProcess),
+        INIT_PROCESS(takeSnapshot, TakeSnapshot, GlobalProcess) {}
+  
+    StackRegistration stackImport, stackOpen, stackExport, stackSave;
+    MeshRegistration meshImport, meshLoad, meshExport, meshSave, meshReset, loadParents, saveParents, resetParents;
+    GlobalRegistration loadViewFile, saveViewFile, takeSnapshot;
+  };
+  
+  static SystemRegistration* systemRegistration = 0;
+  
+  void registerSystemProcesses()
   {
+    if(systemRegistration == 0)
+      systemRegistration = new SystemRegistration();
   }
+  
+  void unregisterSystemProcesses()
+  {
+    if(mgx::DEBUG)
+      Information::out << "Trying to unregister system processes" << endl;
+    if(systemRegistration)
+      delete systemRegistration;
+    systemRegistration = 0;
+  }
 
-  StackRegistration stackImport, stackOpen, stackExport, stackSave;
-  MeshRegistration meshImport, meshLoad, meshExport, meshSave, meshReset;
-  GlobalRegistration loadAllData, loadViewFile, saveViewFile, saveAll, resetAll, takeSnapshot;
-};
-
-static SystemRegistration* systemRegistration = 0;
-
-void registerSystemProcesses()
-{
-  if(systemRegistration == 0)
-    systemRegistration = new SystemRegistration();
-}
-
-void unregisterSystemProcesses()
-{
-  if(mgx::DEBUG)
-    Information::out << "Trying to unregister system processes" << endl;
-  if(systemRegistration)
-    delete systemRegistration;
-  systemRegistration = 0;
-}
-} // namespace process
-} // namespace mgx
+}}
Index: MeshProcessLineage.hpp
===================================================================
--- MeshProcessLineage.hpp	(revision 1255)
+++ MeshProcessLineage.hpp	(revision 1256)
@@ -3,311 +3,117 @@
 
 #include <Process.hpp>
 
-namespace mgx {
-namespace process {
-///\addtogroup MeshProcess
-///@{
-/**
- * \class SaveParents MeshProcessLineage.hpp <MeshProcessLineage.hpp>
- *
- * Save mapping from labels to parents
- */
-class MGX_EXPORT SaveParents : public MeshProcess {
-public:
-  SaveParents(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
+namespace mgx { namespace process {
 
-  bool initialize(QStringList& parms, QWidget* parent);
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_ANY))
-      return false;
-    Mesh* m = currentMesh();
-    return (*this)(m, parms[0]);
-  }
-
-  bool operator()(Mesh* mesh, const QString& filename);
-
-  QString folder() const {
-    return "Lineage Tracking";
-  }
-  QString name() const {
-    return "Save Parents";
-  }
-  QString description() const {
-    return "Save map of labels to parents labels to a file";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Filename";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Path to spreadsheet file.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/ParentsSave.png");
-  }
-};
-
-/**
- * \class LoadParents MeshProcessLineage.hpp <MeshProcessLineage.hpp>
- *
- * Load mapping from labels to parents
- */
-class MGX_EXPORT LoadParents : public MeshProcess {
-public:
-  LoadParents(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool initialize(QStringList& parms, QWidget* parent);
-
-  bool operator()(const QStringList& parms)
-  {
-    if(!checkState().mesh(MESH_ANY))
-      return false;
-    Mesh* m = currentMesh();
-    bool res = (*this)(m, parms[0]);
-    if(res)
-      m->showParent();
-    return res;
-  }
-
-  bool operator()(Mesh* mesh, const QString& filename);
-
-  QString folder() const {
-    return "Lineage Tracking";
-  }
-  QString name() const {
-    return "Load Parents";
-  }
-  QString description() const {
-    return "Load map of labels to parents from a file";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Filename";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Path to spreadsheet file.";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/ParentsOpen.png");
-  }
-};
-
-/**
- * \class ClearParents MeshProcessLineage.hpp <MeshProcessLineage.hpp>
- *
- * Clear label to parent mapping
- */
-class MGX_EXPORT ClearParents : public MeshProcess {
-public:
-  ClearParents(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& )
-  {
-    if(!checkState().mesh(MESH_ANY))
-      return false;
-    Mesh* m = currentMesh();
-    return (*this)(m);
-  }
-
-  bool operator()(Mesh* mesh);
-
-  QString folder() const {
-    return "Lineage Tracking";
-  }
-  QString name() const {
-    return "Clear Parents";
-  }
-  QString description() const {
-    return "Clear mapping from parents to labels";
-  }
-  QStringList parmNames() const {
-    return QStringList();
-  }
-  QStringList parmDescs() const {
-    return QStringList();
-  }
-  QIcon icon() const {
-    return QIcon(":/images/ParentsClear.png");
-  }
-};
-
-/**
- * \class CorrectParents MeshProcessLineage.hpp <MeshProcessLineage.hpp>
- *
- * Take out non-existing labels from parent map.
- */
-class MGX_EXPORT CorrectParents : public MeshProcess {
-public:
-  CorrectParents(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& )
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY, 0).mesh(MESH_NON_EMPTY, 1))
-      return false;
-    Mesh* mesh1, *mesh2;
-    if(currentMesh() == mesh(0)) {
-      mesh2 = mesh(0);
-      mesh1 = mesh(1);
-    } else if(currentMesh() == mesh(1)) {
-      mesh2 = mesh(1);
-      mesh1 = mesh(0);
-    } else
-      return false;
-
-    bool res = (*this)(mesh1, mesh2);
-    return res;
-  }
-
-  bool operator()(Mesh* mesh1, Mesh* mesh2);
-
-  QString folder() const {
-    return "Lineage Tracking";
-  }
-  QString name() const {
-    return "Correct Parents";
-  }
-  QString description() const {
-    return "Take out non-existing labels from parent map.";
-  }
-  QStringList parmNames() const {
-    return QStringList();
-  }
-  QStringList parmDescs() const {
-    return QStringList();
-  }
-  QIcon icon() const {
-    return QIcon(":/images/ParentsCheck.png");
-  }
-};
-
-/**
- * \class HeatMapDaughterCells MeshProcessLineage.hpp <MeshProcessLineage.hpp>
- *
- * Compute the heap map that shows how many daughter cells a parent cell has.
- */
-class HeatMapDaughterCells : public MeshProcess {
-public:
-  HeatMapDaughterCells(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& )
-  {
-    if(!checkState().mesh(MESH_NON_EMPTY) or currentMesh()->toShow() != Mesh::PARENT) {
-      setErrorMessage("The current mesh must have show parents selected.");
-      return false;
+  ///\addtogroup MeshProcess
+  ///@{
+  /**
+   * \class CorrectParents MeshProcessLineage.hpp <MeshProcessLineage.hpp>
+   *
+   * Take out non-existing labels from parent map.
+   */
+  class MGX_EXPORT CorrectParents : public MeshProcess {
+  public:
+    CorrectParents(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& )
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY, 0).mesh(MESH_NON_EMPTY, 1))
+        return false;
+      Mesh* mesh1, *mesh2;
+      if(currentMesh() == mesh(0)) {
+        mesh2 = mesh(0);
+        mesh1 = mesh(1);
+      } else if(currentMesh() == mesh(1)) {
+        mesh2 = mesh(1);
+        mesh1 = mesh(0);
+      } else
+        return false;
+  
+      bool res = (*this)(mesh1, mesh2);
+      return res;
     }
-    Mesh* m = currentMesh();
-
-    bool res = (*this)(m);
-    if(res)
-      m->showHeat();
-    return res;
-  }
-
-  bool operator()(Mesh* m);
-
-  QString folder() const {
-    return "Lineage Tracking";
-  }
-  QString name() const {
-    return "Heat Map Daughter Cells";
-  }
-  QString description() const {
-    return "Compute the heat map that shows how may daughter cells a parent cell has.";
-  }
-  QStringList parmNames() const {
-    return QStringList();
-  }
-  QStringList parmDescs() const {
-    return QStringList();
-  }
-  QStringList parmDefaults() const {
-    return QStringList();
-  }
-  QIcon icon() const {
-    return QIcon(":/images/HeatMapDaughterCells.png");
-  }
-};
-
-/**
- * \class CopyParentsToLabels MeshProcessLineage.hpp <MeshProcessLineage.hpp>
- *
- * Copy parents to labels, and clear parent table.
- */
-class CopyParentsToLabels : public MeshProcess {
-public:
-  CopyParentsToLabels(const MeshProcess& process)
-    : Process(process)
-    , MeshProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList& )
-  {
-
-    if(!checkState().mesh(MESH_NON_EMPTY) or currentMesh()->toShow() != Mesh::PARENT) {
-      setErrorMessage("The current mesh must have show parents selected.");
-      return false;
+  
+    bool operator()(Mesh* mesh1, Mesh* mesh2);
+  
+    QString folder() const { return "Lineage Tracking"; }
+    QString name() const { return "Correct Parents"; }
+    QString description() const { return "Take out non-existing labels from parent map."; }
+    QStringList parmNames() const { return QStringList(); }
+    QStringList parmDescs() const { return QStringList(); }
+    QIcon icon() const { return QIcon(":/images/ParentsCheck.png"); }
+  };
+  
+  /**
+   * \class HeatMapDaughterCells MeshProcessLineage.hpp <MeshProcessLineage.hpp>
+   *
+   * Compute the heap map that shows how many daughter cells a parent cell has.
+   */
+  class HeatMapDaughterCells : public MeshProcess {
+  public:
+    HeatMapDaughterCells(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& )
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY | MESH_PARENT)) {
+        setErrorMessage("The current mesh must have show parents selected.");
+        return false;
+      }
+      Mesh* m = currentMesh();
+  
+      bool res = (*this)(m);
+      if(res)
+        m->showHeat();
+      return res;
     }
-    Mesh* m = currentMesh();
+  
+    bool operator()(Mesh* m);
+  
+    QString folder() const { return "Lineage Tracking"; }
+    QString name() const { return "Heat Map Daughter Cells"; }
+    QString description() const { return 
+      "Compute the heat map that shows how may daughter cells a parent cell has."; }
+    QStringList parmNames() const { return QStringList(); }
+    QStringList parmDescs() const { return QStringList(); }
+    QStringList parmDefaults() const { return QStringList(); }
+    QIcon icon() const { return QIcon(":/images/HeatMapDaughterCells.png"); }
+  };
+  
+  /**
+   * \class CopyParentsToLabels MeshProcessLineage.hpp <MeshProcessLineage.hpp>
+   *
+   * Copy parents to labels, and clear parent table.
+   */
+  class CopyParentsToLabels : public MeshProcess {
+  public:
+    CopyParentsToLabels(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& )
+    {
+      if(!checkState().mesh(MESH_NON_EMPTY | MESH_PARENT)) {
+        setErrorMessage("The current mesh must have show parents selected.");
+        return false;
+      }
+      Mesh* m = currentMesh();
+  
+      bool res = (*this)(m);
+      if(res)
+        m->showLabel();
+      return res;
+    }
+  
+    bool operator()(Mesh* m);
+  
+    QString folder() const { return "Lineage Tracking"; }
+    QString name() const { return "Copy Parents to Labels"; }
+    QString description() const { return "Copy parents to labels, and clear parent table."; }
+    QStringList parmNames() const { return QStringList(); }
+    QStringList parmDescs() const { return QStringList(); }
+    QStringList parmDefaults() const { return QStringList(); }
+    QIcon icon() const { return QIcon(":/images/ParentsCopyToLabel.png"); }
+  };
+  ///@}
+ 
+}}
 
-    bool res = (*this)(m);
-    if(res)
-      m->showLabel();
-    return res;
-  }
-
-  bool operator()(Mesh* m);
-
-  QString folder() const {
-    return "Lineage Tracking";
-  }
-  QString name() const {
-    return "Copy Parents to Labels";
-  }
-  QString description() const {
-    return "Copy parents to labels, and clear parent table.";
-  }
-  QStringList parmNames() const {
-    return QStringList();
-  }
-  QStringList parmDescs() const {
-    return QStringList();
-  }
-  QStringList parmDefaults() const {
-    return QStringList();
-  }
-  QIcon icon() const {
-    return QIcon(":/images/ParentsCopyToLabel.png");
-  }
-};
-///@}
-} // namespace process
-} // namespace mgx
-
 #endif
Index: Information.cpp
===================================================================
--- Information.cpp	(revision 1255)
+++ Information.cpp	(revision 1256)
@@ -13,38 +13,46 @@
 
 namespace mgx {
 
-bool DEBUG = false;
+  bool DEBUG = false;
 
-namespace Information {
-QTextStream out(stdout);
-QTextStream err(stderr);
+  namespace Information {
 
-static QStatusBar* status = 0;
-static QMainWindow* mainWnd = 0;
+    QTextStream out(stdout);
+    QTextStream err(stderr);
+    
+    static QStatusBar* status = 0;
+    static QMainWindow* mainWnd = 0;
+    
+    void setMainWindow(QMainWindow* wnd)
+    {
+      mainWnd = wnd;
+      status = wnd->statusBar();
+      out.setCodec("UTF-8");
+      err.setCodec("UTF-8");
+    }
+    
+    void setStatus(const QString& text)
+    {
+      // If not in GUI thread
+      if(status and status->thread() != QThread::currentThread()) {
+        QCoreApplication::postEvent(mainWnd, new Event(text));
+        return;
+      }
+      if(status != 0)
+        status->showMessage(text);
+    }
+    
+    void print(const QString& text)
+    {
+      // RSS: Is it safe to write to QTextStream in different threads?
+      out << text << endl;
+      setStatus(text);
+    }
 
-void setMainWindow(QMainWindow* wnd)
-{
-  mainWnd = wnd;
-  status = wnd->statusBar();
-  out.setCodec("UTF-8");
-  err.setCodec("UTF-8");
-}
+    void print(const string text)
+    {
+      print(QString::fromStdString(text));
+    }
 
-void Print(const QString& _text)
-{
-  if(status and status->thread() != QThread::currentThread()) {
-    QCoreApplication::postEvent(mainWnd, new Event(_text));
-    return;
   }
-  out << _text << endl;
-  if(status != 0)
-    status->showMessage(_text);
 }
-
-void Print(const string _text)
-{
-  QString txt = QString::fromStdString(_text);
-  Print(txt);
-}
-} // namespace Information
-} // namespace mgx
Index: MeshProcessHeatMap.cpp
===================================================================
--- MeshProcessHeatMap.cpp	(revision 1255)
+++ MeshProcessHeatMap.cpp	(revision 1256)
@@ -6,1317 +6,1331 @@
 #include "ui_LoadHeatMap.h"
 #include <cmath>
 
-namespace mgx {
-namespace process {
-bool ComputeHeatMap::initialize(QStringList& parms, QWidget* parent)
-{
-  dlg = new QDialog(parent);
-  Ui_HeatMapDialog ui;
-  ui.setupUi(dlg);
-
-  connect(ui.HeatMapType, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(changeMapType(const QString &)));
-  connect(ui.SelectSpreadsheetFile, SIGNAL(clicked()), this, SLOT(selectSpreadsheetFile()));
-
-  for(int i = 0; i < ui.HeatMapType->count(); ++i) {
-    if(ui.HeatMapType->itemText(i) == parms[0]) {
-      ui.HeatMapType->setCurrentIndex(i);
-      break;
+namespace mgx { namespace process {
+  bool ComputeHeatMap::initialize(QStringList& parms, QWidget* parent)
+  {
+    dlg = new QDialog(parent);
+    Ui_HeatMapDialog ui;
+    ui.setupUi(dlg);
+  
+    connect(ui.HeatMapType, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(changeMapType(const QString &)));
+    connect(ui.SelectSpreadsheetFile, SIGNAL(clicked()), this, SLOT(selectSpreadsheetFile()));
+  
+    for(int i = 0; i < ui.HeatMapType->count(); ++i) {
+      if(ui.HeatMapType->itemText(i) == parms[0]) {
+        ui.HeatMapType->setCurrentIndex(i);
+        break;
+      }
     }
-  }
-  for(int i = 0; i < ui.HeatMapSignal->count(); ++i) {
-    if(ui.HeatMapSignal->itemText(i) == parms[1]) {
-      ui.HeatMapSignal->setCurrentIndex(i);
-      break;
-    }
-  }
-  ui.SpreadsheetFile->setText(parms[2]);
-  if(parms[3].isEmpty()) {
-    ui.CreateSpreadsheet->setChecked(false);
-  } else {
-    QStringList spread = parms[3].split(",");
-    ui.HeatMapRepGeom->setChecked(spread.contains("Geometry"));
-    ui.HeatMapRepSig->setChecked(spread.contains("Signal"));
-    ui.HeatMapRepBord->setChecked(spread.contains("Border"));
-  }
-  ui.HeatMapRange->setChecked(stringToBool(parms[4]));
-  ui.RangeMin->setValue(parms[5].toFloat());
-  ui.RangeMax->setValue(parms[6].toFloat());
-  ui.HeatMapAvg->setChecked(stringToBool(parms[7]));
-  ui.GlobalCoordinates->setChecked(stringToBool(parms[8]));
-  ui.HeatMapPolarity->setChecked(parms[9] != "None");
-  if(ui.HeatMapPolarity->isChecked()) {
-    for(int i = 0; i < ui.HeatMapPolarityType->count(); ++i) {
-      if(ui.HeatMapPolarityType->itemText(i) == parms[9]) {
-        ui.HeatMapPolarityType->setCurrentIndex(i);
+    for(int i = 0; i < ui.HeatMapSignal->count(); ++i) {
+      if(ui.HeatMapSignal->itemText(i) == parms[1]) {
+        ui.HeatMapSignal->setCurrentIndex(i);
         break;
       }
     }
-  }
-
-  ui.HeatMapChange->setChecked(stringToBool(parms[10]));
-  if(parms[11] == "Increasing")
-    ui.HeatMapIncr->setCurrentIndex(0);
-  else
-    ui.HeatMapIncr->setCurrentIndex(1);
-  if(parms[12] == "Ratio")
-    ui.HeatMapDiffType->setCurrentIndex(0);
-  else if(parms[12] == "Difference")
-    ui.HeatMapDiffType->setCurrentIndex(1);
-  else if(parms[12] == "Growth")
-    ui.HeatMapDiffType->setCurrentIndex(2);
-
-  ui.HeatMapGrowthTime->setValue(parms[13].toFloat());
-  borderSize = parms[14].toFloat();
-
-  bool go = dlg->exec() == QDialog::Accepted;
-  if(go) {
-    parms.clear();
-    QStringList spread;
-    if(ui.CreateSpreadsheet->isChecked()) {
-      if(ui.HeatMapRepGeom->isChecked())
-        spread << "Geometry";
-      if(ui.HeatMapRepSig->isChecked())
-        spread << "Signal";
-      if(ui.HeatMapRepBord->isChecked())
-        spread << "Border";
+    ui.SpreadsheetFile->setText(parms[2]);
+    if(parms[3].isEmpty()) {
+      ui.CreateSpreadsheet->setChecked(false);
+    } else {
+      QStringList spread = parms[3].split(",");
+      ui.HeatMapRepGeom->setChecked(spread.contains("Geometry"));
+      ui.HeatMapRepSig->setChecked(spread.contains("Signal"));
+      ui.HeatMapRepBord->setChecked(spread.contains("Border"));
     }
-    parms << ui.HeatMapType->currentText() << ui.HeatMapSignal->currentText() << ui.SpreadsheetFile->text()
-          << spread.join(",") << (ui.HeatMapRange->isChecked() ? "Yes" : "No")
-          << QString::number(ui.RangeMin->value()) << QString::number(ui.RangeMax->value())
-          << (ui.HeatMapAvg->isChecked() ? "Yes" : "No") << (ui.GlobalCoordinates->isChecked() ? "Yes" : "No")
-          << (ui.HeatMapPolarity->isChecked() ? ui.HeatMapPolarityType->currentText() : QString("None"))
-          << (ui.HeatMapChange->isChecked() ? "Yes" : "No") << ui.HeatMapIncr->currentText()
-          << ui.HeatMapDiffType->currentText() << QString::number(ui.HeatMapGrowthTime->value())
-          << QString::number(borderSize);
+    ui.HeatMapRange->setChecked(stringToBool(parms[4]));
+    ui.RangeMin->setValue(parms[5].toFloat());
+    ui.RangeMax->setValue(parms[6].toFloat());
+    ui.HeatMapAvg->setChecked(stringToBool(parms[7]));
+    ui.GlobalCoordinates->setChecked(stringToBool(parms[8]));
+    ui.HeatMapPolarity->setChecked(parms[9] != "None");
+    if(ui.HeatMapPolarity->isChecked()) {
+      for(int i = 0; i < ui.HeatMapPolarityType->count(); ++i) {
+        if(ui.HeatMapPolarityType->itemText(i) == parms[9]) {
+          ui.HeatMapPolarityType->setCurrentIndex(i);
+          break;
+        }
+      }
+    }
+  
+    ui.HeatMapChange->setChecked(stringToBool(parms[10]));
+    if(parms[11] == "Increasing")
+      ui.HeatMapIncr->setCurrentIndex(0);
+    else
+      ui.HeatMapIncr->setCurrentIndex(1);
+    if(parms[12] == "Ratio")
+      ui.HeatMapDiffType->setCurrentIndex(0);
+    else if(parms[12] == "Difference")
+      ui.HeatMapDiffType->setCurrentIndex(1);
+    else if(parms[12] == "Growth")
+      ui.HeatMapDiffType->setCurrentIndex(2);
+  
+    ui.HeatMapGrowthTime->setValue(parms[13].toFloat());
+    borderSize = parms[14].toFloat();
+  
+    bool go = dlg->exec() == QDialog::Accepted;
+    if(go) {
+      parms.clear();
+      QStringList spread;
+      if(ui.CreateSpreadsheet->isChecked()) {
+        if(ui.HeatMapRepGeom->isChecked())
+          spread << "Geometry";
+        if(ui.HeatMapRepSig->isChecked())
+          spread << "Signal";
+        if(ui.HeatMapRepBord->isChecked())
+          spread << "Border";
+      }
+      parms << ui.HeatMapType->currentText() << ui.HeatMapSignal->currentText() << ui.SpreadsheetFile->text()
+            << spread.join(",") << (ui.HeatMapRange->isChecked() ? "Yes" : "No")
+            << QString::number(ui.RangeMin->value()) << QString::number(ui.RangeMax->value())
+            << (ui.HeatMapAvg->isChecked() ? "Yes" : "No") << (ui.GlobalCoordinates->isChecked() ? "Yes" : "No")
+            << (ui.HeatMapPolarity->isChecked() ? ui.HeatMapPolarityType->currentText() : QString("None"))
+            << (ui.HeatMapChange->isChecked() ? "Yes" : "No") << ui.HeatMapIncr->currentText()
+            << ui.HeatMapDiffType->currentText() << QString::number(ui.HeatMapGrowthTime->value())
+            << QString::number(borderSize);
+    }
+    delete dlg;
+    dlg = 0;
+    return go;
   }
-  delete dlg;
-  dlg = 0;
-  return go;
-}
-
-bool ComputeHeatMap::operator()(const QStringList& parms)
-{
-  MapType map;
-  if(parms[0] == "Area")
-    map = AREA;
-  else if(parms[0] == "Volume")
-    map = VOLUME;
-  else if(parms[0] == "Walls")
-    map = WALL;
-  else {
-    setErrorMessage("Error, first string must be one of 'Area', 'Volume' or 'Walls'");
-    return false;
-  }
-  SignalType signal;
-  if(parms[1] == "Geometry")
-    signal = GEOMETRY;
-  else if(parms[1] == "Border signal")
-    signal = BORDER;
-  else if(parms[1] == "Interior signal")
-    signal = INTERIOR;
-  else if(parms[1] == "Border/total")
-    signal = BORDER_TOTAL;
-  else if(parms[1] == "Interior/total")
-    signal = INTERIOR_TOTAL;
-  else if(parms[1] == "Total signal")
-    signal = TOTAL;
-  else {
-    setErrorMessage("Error, second string must be one of 'Geometry', 'Border signal',"
-                    " 'Interior signal', 'Border/total', 'Interior/total' or 'Total signal'");
-    return false;
-  }
-  QString reportFile = parms[2];
-  if(!reportFile.isEmpty() and !reportFile.endsWith(".csv", Qt::CaseInsensitive))
-    reportFile += ".csv";
-  QStringList spread = parms[3].split(",");
-  int report = 0;
-  if(spread.contains("Geometry"))
-    report |= GEOMETRY;
-  if(spread.contains("Signal"))
-    report |= TOTAL;
-  if(spread.contains("Border"))
-    report |= BORDER;
-  bool manualRange = stringToBool(parms[4]);
-  float rangeMin = parms[5].toFloat();
-  float rangeMax = parms[6].toFloat();
-  if(manualRange and rangeMin >= rangeMax) {
-    setErrorMessage("If range is manual, then rangeMin (2nd value) must be less than rangeMax (3rd value)");
-    return false;
-  }
-  bool signalAverage = stringToBool(parms[7]);
-  bool globalCoordinates = stringToBool(parms[8]);
-  PolarityType polarity = NONE;
-  if(parms[9] == "None")
-    polarity = NONE;
-  else if(parms[9] == "Cell Average")
-    polarity = CELL_AVERAGE;
-  else if(parms[9] == "Wall/Min")
-    polarity = WALL_MIN;
-  else {
-    setErrorMessage("Error, 9th string must be one of 'None', 'Cell Average or 'Wall/Min'");
-    return false;
-  }
-
-  MultiMapType multiMapType;
-  float growthTime = parms[13].toFloat();
-  bool hasChange = stringToBool(parms[10]);
-  if(!hasChange)
-    multiMapType = SINGLE;
-  else {
-    bool incr = parms[11] == "Increasing";
-    bool ratio = parms[12] == "Ratio";
-    bool diff = parms[12] == "Difference";
-    bool growth = parms[12] == "Growth";
-    if(growth and growthTime <= 0) {
-      setErrorMessage("Time for growth rate cannot be <= 0)");
+  
+  bool ComputeHeatMap::operator()(const QStringList& parms)
+  {
+    MapType map;
+    if(parms[0] == "Area")
+      map = AREA;
+    else if(parms[0] == "Volume")
+      map = VOLUME;
+    else if(parms[0] == "Walls")
+      map = WALL;
+    else {
+      setErrorMessage("Error, first string must be one of 'Area', 'Volume' or 'Walls'");
       return false;
     }
-    if(incr) {
-      if(ratio)
-        multiMapType = INCREASING_RATIO;
-      else if(diff)
-        multiMapType = INCREASING_DIFF;
-      else
-        multiMapType = INCREASING_GROWTH;
-    } else {
-      if(ratio)
-        multiMapType = DECREASING_RATIO;
-      else if(diff)
-        multiMapType = DECREASING_DIFF;
-      else
-        multiMapType = DECREASING_GROWTH;
+    SignalType signal;
+    if(parms[1] == "Geometry")
+      signal = GEOMETRY;
+    else if(parms[1] == "Border signal")
+      signal = BORDER;
+    else if(parms[1] == "Interior signal")
+      signal = INTERIOR;
+    else if(parms[1] == "Border/total")
+      signal = BORDER_TOTAL;
+    else if(parms[1] == "Interior/total")
+      signal = INTERIOR_TOTAL;
+    else if(parms[1] == "Total signal")
+      signal = TOTAL;
+    else {
+      setErrorMessage("Error, second string must be one of 'Geometry', 'Border signal',"
+                      " 'Interior signal', 'Border/total', 'Interior/total' or 'Total signal'");
+      return false;
     }
-  }
-  float borderSize = parms[14].toFloat();
-
-  Mesh* mesh1 = 0, *mesh2 = 0;
-  if(multiMapType == SINGLE) {
-    if(!checkState().mesh(MESH_NON_EMPTY))
+    QString reportFile = parms[2];
+    if(!reportFile.isEmpty() and !reportFile.endsWith(".csv", Qt::CaseInsensitive))
+      reportFile += ".csv";
+    QStringList spread = parms[3].split(",");
+    int report = 0;
+    if(spread.contains("Geometry"))
+      report |= GEOMETRY;
+    if(spread.contains("Signal"))
+      report |= TOTAL;
+    if(spread.contains("Border"))
+      report |= BORDER;
+    bool manualRange = stringToBool(parms[4]);
+    float rangeMin = parms[5].toFloat();
+    float rangeMax = parms[6].toFloat();
+    if(manualRange and rangeMin >= rangeMax) {
+      setErrorMessage("If range is manual, then rangeMin (2nd value) must be less than rangeMax (3rd value)");
       return false;
-    mesh1 = currentMesh();
-  } else {
-    if(!checkState().mesh(MESH_NON_EMPTY, 0).mesh(MESH_NON_EMPTY, 1))
+    }
+    bool signalAverage = stringToBool(parms[7]);
+    bool globalCoordinates = stringToBool(parms[8]);
+    PolarityType polarity = NONE;
+    if(parms[9] == "None")
+      polarity = NONE;
+    else if(parms[9] == "Cell Average")
+      polarity = CELL_AVERAGE;
+    else if(parms[9] == "Wall/Min")
+      polarity = WALL_MIN;
+    else {
+      setErrorMessage("Error, 9th string must be one of 'None', 'Cell Average or 'Wall/Min'");
       return false;
-    if(currentMesh() == mesh(0)) {
-      mesh1 = mesh(0);
-      mesh2 = mesh(1);
-    } else if(currentMesh() == mesh(1)) {
-      mesh2 = mesh(0);
-      mesh1 = mesh(1);
-    } else
+    }
+  
+    MultiMapType multiMapType;
+    float growthTime = parms[13].toFloat();
+    bool hasChange = stringToBool(parms[10]);
+    if(!hasChange)
+      multiMapType = SINGLE;
+    else {
+      bool incr = parms[11] == "Increasing";
+      bool ratio = parms[12] == "Ratio";
+      bool diff = parms[12] == "Difference";
+      bool growth = parms[12] == "Growth";
+      if(growth and growthTime <= 0) {
+        setErrorMessage("Time for growth rate cannot be <= 0)");
+        return false;
+      }
+      if(incr) {
+        if(ratio)
+          multiMapType = INCREASING_RATIO;
+        else if(diff)
+          multiMapType = INCREASING_DIFF;
+        else
+          multiMapType = INCREASING_GROWTH;
+      } else {
+        if(ratio)
+          multiMapType = DECREASING_RATIO;
+        else if(diff)
+          multiMapType = DECREASING_DIFF;
+        else
+          multiMapType = DECREASING_GROWTH;
+      }
+    }
+    float borderSize = parms[14].toFloat();
+  
+    // Check the mesh state
+    Mesh* mesh1 = currentMesh(), *mesh2 = 0;
+    if(!checkState().mesh(MESH_NON_EMPTY | MESH_LABEL_PARENT, mesh1->id())) {
+      setErrorMessage("Show labels or parents must be selected on current mesh");
       return false;
-  }
+    }
+    if(multiMapType != SINGLE) {
+      if(currentMesh() == mesh(0))
+        mesh2 = mesh(1);
+      else if(currentMesh() == mesh(1))
+        mesh2 = mesh(0);
+      else
+        return false;
 
-  bool res = (*this)(mesh1, mesh2, map, signal, reportFile, report, manualRange, rangeMin, rangeMax, signalAverage,
-                     globalCoordinates, polarity, multiMapType, growthTime, borderSize);
-
-  if(res)
-    currentMesh()->showHeat();
-
-  return res;
-}
-
-bool ComputeHeatMap::operator()(Mesh* mesh1, Mesh* mesh2, MapType _map, SignalType _signal, const QString& reportFile,
-                                int _report, bool _manualRange, float _rangeMin, float _rangeMax, bool _signalAverage,
-                                bool _globalCoordinates, PolarityType _polarity, MultiMapType _multiMapType,
-                                float _growthTime, float _borderSize)
-{
-  mapType = _map;
-  signal = _signal;
-  report = _report;
-  manualRange = _manualRange;
-  rangeMin = _rangeMin;
-  rangeMax = _rangeMax;
-  signalAverage = _signalAverage;
-  globalCoordinates = _globalCoordinates;
-  polarity = _polarity;
-  multiMapType = _multiMapType;
-  growthTime = _growthTime;
-  borderSize = _borderSize;
-
-  bool multiMap = multiMapType != SINGLE;
-  if(multiMap and (!mesh2 or mesh2->graph().empty())) {
-    setErrorMessage("Error, to compute a heat map based on two maps, you must specify two meshes");
-    return false;
-  }
-
-  // Check if the report/signal can actually be computed
-
-  if(mapType == VOLUME) {
-    int anysignal = (BORDER | INTERIOR | TOTAL | BORDER_TOTAL | INTERIOR_TOTAL);
-    if((mesh1 and (mesh1->stack()->empty() or mesh1->stack()->currentStore()->labels()))
-       or (mesh2 and (mesh2->stack()->empty() or mesh2->stack()->currentStore()->labels()))) {
-      if((signal & anysignal)or (report & anysignal))
-        return setErrorMessage("Error, trying to measure 3D signal without a stack being loaded");
+      if(!checkState().mesh(MESH_NON_EMPTY | MESH_LABEL_PARENT, mesh2->id())) {
+        setErrorMessage("Show labels or parents must be selected on second mesh");
+        return false;
+      }
     }
+  
+    bool res = (*this)(mesh1, mesh2, map, signal, reportFile, report, manualRange, rangeMin, rangeMax, signalAverage,
+                       globalCoordinates, polarity, multiMapType, growthTime, borderSize);
+  
+    if(res)
+      currentMesh()->showHeat();
+  
+    return res;
   }
-
-  QString sigStr = "";
-  if(signalAverage and signal != GEOMETRY)
-    sigStr += "Average ";
-
-  // Heat map signal type
-  switch(signal) {
-  case GEOMETRY:
-    switch(mapType) {
-    case AREA:
-      sigStr += "Area";
-      break;
-    case VOLUME:
-      sigStr += "Volume";
-      break;
-    case WALL:
-      sigStr += "Wall";
+  
+  bool ComputeHeatMap::operator()(Mesh* mesh1, Mesh* mesh2, MapType _map, SignalType _signal, const QString& reportFile,
+                                  int _report, bool _manualRange, float _rangeMin, float _rangeMax, bool _signalAverage,
+                                  bool _globalCoordinates, PolarityType _polarity, MultiMapType _multiMapType,
+                                  float _growthTime, float _borderSize)
+  {
+    mapType = _map;
+    signal = _signal;
+    report = _report;
+    manualRange = _manualRange;
+    rangeMin = _rangeMin;
+    rangeMax = _rangeMax;
+    signalAverage = _signalAverage;
+    globalCoordinates = _globalCoordinates;
+    polarity = _polarity;
+    multiMapType = _multiMapType;
+    growthTime = _growthTime;
+    borderSize = _borderSize;
+  
+    bool multiMap = multiMapType != SINGLE;
+    if(multiMap and (!mesh2 or mesh2->graph().empty())) {
+      setErrorMessage("Error, to compute a heat map based on two maps, you must specify two meshes");
+      return false;
     }
-    break;
-  case BORDER:
-    sigStr += "Border Signal";
-    break;
-  case INTERIOR:
-    sigStr += "Interior Signal";
-    break;
-  case BORDER_TOTAL:
-    sigStr += "Border/Total Signal";
-    break;
-  case INTERIOR_TOTAL:
-    sigStr += "Interior/Total Signal";
-    break;
-  case TOTAL:
-    sigStr += "Total Signal";
-  }
-
-  ImageHeatMaps map1, map2;
-  if(!getLabelMaps(map1, mesh1))
-    return false;
-
-  IntFloatMap& LabelHeat = mesh1->labelHeat();
-  IntIntFloatMap& WallHeat = mesh1->wallHeat();
-
-  // If we are doing a change map, get it from the other mesh and take the ratio as the signal
-  // Otherwise just copy the info
-  LabelHeat.clear();
-  WallHeat.clear();
-  if(!multiMap) {
-    if(mapType == AREA or mapType == VOLUME)
-      LabelHeat = map1.LabelHeatAmt;
-    else if(mapType == WALL)
-      WallHeat = map1.WallHeatAmt;
-  } else {
-    switch(multiMapType) {
-    case INCREASING_RATIO:
-      sigStr += " increase ratio";
+  
+    // Check if the report/signal can actually be computed
+  
+    if(mapType == VOLUME) {
+      int anysignal = (BORDER | INTERIOR | TOTAL | BORDER_TOTAL | INTERIOR_TOTAL);
+      if((mesh1 and (mesh1->stack()->empty() or mesh1->stack()->currentStore()->labels()))
+         or (mesh2 and (mesh2->stack()->empty() or mesh2->stack()->currentStore()->labels()))) {
+        if((signal & anysignal)or (report & anysignal))
+          return setErrorMessage("Error, trying to measure 3D signal without a stack being loaded");
+      }
+    }
+  
+    QString sigStr = "";
+    if(signalAverage and signal != GEOMETRY)
+      sigStr += "Average ";
+  
+    // Heat map signal type
+    switch(signal) {
+    case GEOMETRY:
+      switch(mapType) {
+      case AREA:
+        sigStr += "Area";
+        break;
+      case VOLUME:
+        sigStr += "Volume";
+        break;
+      case WALL:
+        sigStr += "Wall";
+      }
       break;
-    case INCREASING_DIFF:
-      sigStr += " increase difference";
+    case BORDER:
+      sigStr += "Border Signal";
       break;
-    case INCREASING_GROWTH:
-      sigStr += QString(" increase growth(%1)").arg(growthTime);
+    case INTERIOR:
+      sigStr += "Interior Signal";
       break;
-    case DECREASING_RATIO:
-      sigStr += " decrease ratio";
+    case BORDER_TOTAL:
+      sigStr += "Border/Total Signal";
       break;
-    case DECREASING_DIFF:
-      sigStr += " decrease difference";
+    case INTERIOR_TOTAL:
+      sigStr += "Interior/Total Signal";
       break;
-    case DECREASING_GROWTH:
-      sigStr += QString(" decrease growth(%1)").arg(growthTime);
-      break;
-    case SINGLE:
-      break;
+    case TOTAL:
+      sigStr += "Total Signal";
     }
-
-    // Get values from other mesh
-    if(!getLabelMaps(map2, mesh2))
+  
+    ImageHeatMaps map1, map2;
+    if(!getLabelMaps(map1, mesh1))
       return false;
-
-    // Change map for area and volume
-    switch(mapType) {
-    case AREA:
-    case VOLUME: {
-      std::vector<int> LabelDel;
-      forall(const IntFloatPair& p, map1.LabelHeatAmt) {
-        int i = p.first;
-        // Calculate change
-        if(map2.LabelHeatAmt.find(i) != map2.LabelHeatAmt.end()) {
-          switch(multiMapType) {
-          case INCREASING_RATIO:
-            LabelHeat[i] = (map1.LabelHeatAmt[i] == 0 ? 0 : map2.LabelHeatAmt[i] / map1.LabelHeatAmt[i]);
-            break;
-          case DECREASING_RATIO:
-            LabelHeat[i] = (map2.LabelHeatAmt[i] == 0 ? 0 : map1.LabelHeatAmt[i] / map2.LabelHeatAmt[i]);
-            break;
-          case INCREASING_DIFF:
-            LabelHeat[i] = map2.LabelHeatAmt[i] - map1.LabelHeatAmt[i];
-            break;
-          case DECREASING_DIFF:
-            LabelHeat[i] = map1.LabelHeatAmt[i] - map2.LabelHeatAmt[i];
-            break;
-          case INCREASING_GROWTH:
-            if(growthTime == 0 or map1.LabelHeatAmt[i] == 0)
-              LabelHeat[i] = 0;
-            else
-              LabelHeat[i] = (map2.LabelHeatAmt[i] / map1.LabelHeatAmt[i] - 1) / growthTime;
-            break;
-          case DECREASING_GROWTH:
-            if(growthTime == 0 or map2.LabelHeatAmt[i] == 0)
-              LabelHeat[i] = 0;
-            else
-              LabelHeat[i] = (map1.LabelHeatAmt[i] / map2.LabelHeatAmt[i] - 1) / growthTime;
-            break;
-          case SINGLE:
-            break;
-          }
-        } else
-          LabelDel.push_back(i);
+  
+    IntFloatMap& LabelHeat = mesh1->labelHeat();
+    IntIntFloatMap& WallHeat = mesh1->wallHeat();
+  
+    // If we are doing a change map, get it from the other mesh and take the ratio as the signal
+    // Otherwise just copy the info
+    LabelHeat.clear();
+    WallHeat.clear();
+    if(!multiMap) {
+      if(mapType == AREA or mapType == VOLUME)
+        LabelHeat = map1.LabelHeatAmt;
+      else if(mapType == WALL)
+        WallHeat = map1.WallHeatAmt;
+    } else {
+      switch(multiMapType) {
+      case INCREASING_RATIO:
+        sigStr += " increase ratio";
+        break;
+      case INCREASING_DIFF:
+        sigStr += " increase difference";
+        break;
+      case INCREASING_GROWTH:
+        sigStr += QString(" increase growth(%1)").arg(growthTime);
+        break;
+      case DECREASING_RATIO:
+        sigStr += " decrease ratio";
+        break;
+      case DECREASING_DIFF:
+        sigStr += " decrease difference";
+        break;
+      case DECREASING_GROWTH:
+        sigStr += QString(" decrease growth(%1)").arg(growthTime);
+        break;
+      case SINGLE:
+        break;
       }
-      // Delete labels not in both meshes
-      forall(int i, LabelDel) {
-        LabelHeat.erase(i);
-        SETSTATUS("MakeHeatMap Warning mesh " << mesh1->userId() << " erasing label " << i);
-      }
-    } break;
-    case WALL: {     // Calculate wall change map
-      std::vector<IntIntPair> WallDel;
-      forall(const IntIntFloatPair& p, map1.WallHeatAmt) {
-        IntIntPair i = p.first;
-        // Calculate change
-        if(map2.WallHeatAmt.find(i) != map2.WallHeatAmt.end()) {
-          switch(multiMapType) {
-          case INCREASING_RATIO:
-            WallHeat[i] = (map1.WallHeatAmt[i] == 0 ? 0 : map2.WallHeatAmt[i] / map1.WallHeatAmt[i]);
-            break;
-          case DECREASING_RATIO:
-            WallHeat[i] = (map2.WallHeatAmt[i] == 0 ? 0 : map1.WallHeatAmt[i] / map2.WallHeatAmt[i]);
-            break;
-          case INCREASING_DIFF:
-            WallHeat[i] = map2.WallHeatAmt[i] - map1.WallHeatAmt[i];
-            break;
-          case DECREASING_DIFF:
-            WallHeat[i] = map1.WallHeatAmt[i] - map2.WallHeatAmt[i];
-          case INCREASING_GROWTH:
-            if(growthTime == 0 or map1.WallHeatAmt[i] == 0)
-              WallHeat[i] = 0;
-            else
-              WallHeat[i] = (map2.WallHeatAmt[i] / map1.WallHeatAmt[i] - 1) / growthTime;
-            break;
-          case DECREASING_GROWTH:
-            if(growthTime == 0 or map2.WallHeatAmt[i] == 0)
-              WallHeat[i] = 0;
-            else
-              WallHeat[i] = (map1.WallHeatAmt[i] / map2.WallHeatAmt[i] - 1) / growthTime;
-            break;
-          case SINGLE:
-            break;
+  
+      // Get values from other mesh
+      if(!getLabelMaps(map2, mesh2))
+        return false;
+  
+      // Change map for area and volume
+      switch(mapType) {
+        case AREA:
+        case VOLUME: {
+          std::vector<int> LabelDel;
+          forall(const IntFloatPair& p, map1.LabelHeatAmt) {
+            int i = p.first;
+            // Calculate change
+            if(map2.LabelHeatAmt.find(i) != map2.LabelHeatAmt.end()) {
+              switch(multiMapType) {
+              case INCREASING_RATIO:
+                LabelHeat[i] = (map1.LabelHeatAmt[i] == 0 ? 0 : map2.LabelHeatAmt[i] / map1.LabelHeatAmt[i]);
+                break;
+              case DECREASING_RATIO:
+                LabelHeat[i] = (map2.LabelHeatAmt[i] == 0 ? 0 : map1.LabelHeatAmt[i] / map2.LabelHeatAmt[i]);
+                break;
+              case INCREASING_DIFF:
+                LabelHeat[i] = map2.LabelHeatAmt[i] - map1.LabelHeatAmt[i];
+                break;
+              case DECREASING_DIFF:
+                LabelHeat[i] = map1.LabelHeatAmt[i] - map2.LabelHeatAmt[i];
+                break;
+              case INCREASING_GROWTH:
+                if(growthTime == 0 or map1.LabelHeatAmt[i] == 0)
+                  LabelHeat[i] = 0;
+                else
+                  LabelHeat[i] = (map2.LabelHeatAmt[i] / map1.LabelHeatAmt[i] - 1) / growthTime;
+                break;
+              case DECREASING_GROWTH:
+                if(growthTime == 0 or map2.LabelHeatAmt[i] == 0)
+                  LabelHeat[i] = 0;
+                else
+                  LabelHeat[i] = (map1.LabelHeatAmt[i] / map2.LabelHeatAmt[i] - 1) / growthTime;
+                break;
+              case SINGLE:
+                break;
+              }
+            } else
+              LabelDel.push_back(i);
           }
-        } else
-          WallDel.push_back(i);
+          // Delete labels not in both meshes
+          forall(int i, LabelDel) {
+            LabelHeat.erase(i);
+            SETSTATUS("MakeHeatMap Warning mesh " << mesh1->userId() << " erasing label " << i);
+          }
+        } break;
+        case WALL: {     // Calculate wall change map
+          std::vector<IntIntPair> WallDel;
+          forall(const IntIntFloatPair& p, map1.WallHeatAmt) {
+            IntIntPair i = p.first;
+            // Calculate change
+            if(map2.WallHeatAmt.find(i) != map2.WallHeatAmt.end()) {
+              switch(multiMapType) {
+              case INCREASING_RATIO:
+                WallHeat[i] = (map1.WallHeatAmt[i] == 0 ? 0 : map2.WallHeatAmt[i] / map1.WallHeatAmt[i]);
+                break;
+              case DECREASING_RATIO:
+                WallHeat[i] = (map2.WallHeatAmt[i] == 0 ? 0 : map1.WallHeatAmt[i] / map2.WallHeatAmt[i]);
+                break;
+              case INCREASING_DIFF:
+                WallHeat[i] = map2.WallHeatAmt[i] - map1.WallHeatAmt[i];
+                break;
+              case DECREASING_DIFF:
+                WallHeat[i] = map1.WallHeatAmt[i] - map2.WallHeatAmt[i];
+              case INCREASING_GROWTH:
+                if(growthTime == 0 or map1.WallHeatAmt[i] == 0)
+                  WallHeat[i] = 0;
+                else
+                  WallHeat[i] = (map2.WallHeatAmt[i] / map1.WallHeatAmt[i] - 1) / growthTime;
+                break;
+              case DECREASING_GROWTH:
+                if(growthTime == 0 or map2.WallHeatAmt[i] == 0)
+                  WallHeat[i] = 0;
+                else
+                  WallHeat[i] = (map1.WallHeatAmt[i] / map2.WallHeatAmt[i] - 1) / growthTime;
+                break;
+              case SINGLE:
+                break;
+              }
+            } else
+              WallDel.push_back(i);
+          }
+          // Delete labels not in both meshes
+          forall(IntIntPair i, WallDel) {
+            WallHeat.erase(i);
+            SETSTATUS("MakeHeatMap::Warning:Mesh" << mesh1->userId() << " erasing wall " << i.first << "->"
+                                                  << i.second);
+          }
+        }
       }
-      // Delete labels not in both meshes
-      forall(IntIntPair i, WallDel) {
-        WallHeat.erase(i);
-        SETSTATUS("MakeHeatMap::Warning:Mesh" << mesh1->userId() << " erasing wall " << i.first << "->"
-                                              << i.second);
-      }
     }
+  
+    // Adjust heat map if run on parents
+    if(mesh1->toShow() == Mesh::PARENT) {
+      IntFloatMap OldHeat = LabelHeat;
+      LabelHeat.clear();
+      IntIntMap& parentMap = mesh1->parentLabelMap();
+      forall(const IntIntPair& p, parentMap)
+        if(p.second > 0 and OldHeat.count(p.second) > 0)
+          LabelHeat[p.first] = OldHeat[p.second];
     }
-  }
-
-  // Adjust heat map if run on parents
-  if(mesh1->toShow() == Mesh::PARENT) {
-    Information::out << "Heat map table" << endl;
-    forall(const IntFloatPair& p, LabelHeat)
-      Information::out << p.first << " " << p.second << endl;
-    IntFloatMap OldHeat = LabelHeat;
-    LabelHeat.clear();
-    IntIntMap& parentMap = mesh1->parentLabelMap();
-    forall(const IntIntPair& p, parentMap) {
-      if(p.second > 0)
-        LabelHeat[p.first] = OldHeat[p.second];
-      Information::out << "cell " << p.first << " has label " << p.second << " old heat:" << OldHeat[p.second]
-                       << endl;
+  
+    // Calculate ranges if not using user defined range
+    float heatMinAmt = rangeMin;
+    float heatMaxAmt = rangeMax;
+    if(!manualRange) {
+      heatMinAmt = HUGE_VAL, heatMaxAmt = -HUGE_VAL;
+  
+      // Find max and min
+      switch(mapType) {
+      case AREA:
+      case VOLUME:
+        forall(const IntFloatPair& p, LabelHeat) {
+          float amt = LabelHeat[p.first];
+          if(amt < heatMinAmt)
+            heatMinAmt = amt;
+          if(amt > heatMaxAmt)
+            heatMaxAmt = amt;
+        }
+        break;
+      case WALL:
+        forall(const IntIntFloatPair& p, WallHeat) {
+          float amt = WallHeat[p.first];
+          if(amt < heatMinAmt)
+            heatMinAmt = amt;
+          if(amt > heatMaxAmt)
+            heatMaxAmt = amt;
+        }
+      }
     }
-  }
-
-  // Calculate ranges if not using user defined range
-  float heatMinAmt = rangeMin;
-  float heatMaxAmt = rangeMax;
-  if(!manualRange) {
-    heatMinAmt = HUGE_VAL, heatMaxAmt = -HUGE_VAL;
-
-    // Find max and min
+    mesh1->heatMapBounds() = Point2f(heatMinAmt, heatMaxAmt);
+  
+    // Find units
+    QString gunits(""), hunits("");
     switch(mapType) {
+    case WALL:
+      gunits = UM;
+      break;
     case AREA:
+      gunits = UM2;
+      break;
     case VOLUME:
-      forall(const IntFloatPair& p, LabelHeat) {
-        float amt = LabelHeat[p.first];
-        if(amt < heatMinAmt)
-          heatMinAmt = amt;
-        if(amt > heatMaxAmt)
-          heatMaxAmt = amt;
-      }
+      gunits = UM3;
       break;
-    case WALL:
-      forall(const IntIntFloatPair& p, WallHeat) {
-        float amt = WallHeat[p.first];
-        if(amt < heatMinAmt)
-          heatMinAmt = amt;
-        if(amt > heatMaxAmt)
-          heatMaxAmt = amt;
-      }
     }
-  }
-  mesh1->heatMapBounds() = Point2f(heatMinAmt, heatMaxAmt);
-
-  // Find units
-  QString gunits(""), hunits("");
-  switch(mapType) {
-  case WALL:
-    gunits = UM;
-    break;
-  case AREA:
-    gunits = UM2;
-    break;
-  case VOLUME:
-    gunits = UM3;
-    break;
-  }
-  if(!multiMap and signal == GEOMETRY)
-    hunits = gunits;
-
-  mesh1->heatMapUnit() = hunits;
-
-  // Write to file
-  if(report != 0) {
-    QFile file(reportFile);
-    if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
-      SETSTATUS("makeHeatMap::Error:Cannot open output file:" << reportFile);
-    } else {
-      QTextStream out(&file);
-
-      // Area heat map
-      switch(mapType) {
-      case AREA:
-      case VOLUME: {
-        // Write header
-        out << "Label,Value";
-        if(mapType == AREA) {
-          out << QString(",Area (%1)").arg(UM2);
-          if(report & BORDER) {
-            out << QString(",Border Area (%1),Interior Area (%1)").arg(UM2);
+    if(!multiMap and signal == GEOMETRY)
+      hunits = gunits;
+  
+    mesh1->heatMapUnit() = hunits;
+  
+    // Write to file
+    if(report != 0) {
+      QFile file(reportFile);
+      if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
+        SETSTATUS("makeHeatMap::Error:Cannot open output file:" << reportFile);
+      } else {
+        QTextStream out(&file);
+  
+        // Area heat map
+        switch(mapType) {
+        case AREA:
+        case VOLUME: {
+          // Write header
+          out << "Label,Value";
+          if(mapType == AREA) {
+            out << QString(",Area (%1)").arg(UM2);
+            if(report & BORDER) {
+              out << QString(",Border Area (%1),Interior Area (%1)").arg(UM2);
+            }
+          } else {
+            out << QString(",Volume (%1)").arg(UM3);
+            if(report & BORDER) {
+              out << QString(",Border Volume (%1),Interior Volume (%1)").arg(UM3);
+            }
           }
-        } else {
-          out << QString(",Volume (%1)").arg(UM3);
-          if(report & BORDER) {
-            out << QString(",Border Volume (%1),Interior Volume (%1)").arg(UM3);
+          if((report & BORDER)or (report & TOTAL)) {
+            out << ",Total Signal";
+            if(report & BORDER) {
+              out << ",Border Signal,Interior Signal";
+            }
           }
-        }
-        if((report & BORDER)or (report & TOTAL)) {
-          out << ",Total Signal";
-          if(report & BORDER) {
-            out << ",Border Signal,Interior Signal";
-          }
-        }
-        out << ",Center_X,Center_Y,Center_Z";
-        out << endl;
-
-        // Write data
-        IntPoint3fMap& LabelCenter = mesh1->labelCenter();
-        const qglviewer::Frame& frame = mesh1->stack()->getFrame();
-        forall(const IntFloatPair& p, LabelHeat) {
-          int label = p.first;
-          out << label << "," << LabelHeat[label];
-          out << "," << map1.LabelGeom[label];
-          if(report & BORDER) {
-            out << "," << map1.LabelBordGeom[label];
-            out << "," << map1.LabelIntGeom[label];
-          }
-          if((report & SINGLE)or (report & TOTAL)) {
-            out << "," << map1.LabelTotalSig[label];
+          out << ",Center_X,Center_Y,Center_Z";
+          out << endl;
+  
+          // Write data
+          IntPoint3fMap& LabelCenter = mesh1->labelCenter();
+          const qglviewer::Frame& frame = mesh1->stack()->getFrame();
+          forall(const IntFloatPair& p, LabelHeat) {
+            int label = p.first;
+            out << label << "," << LabelHeat[label];
+            out << "," << map1.LabelGeom[label];
             if(report & BORDER) {
-              out << "," << map1.LabelBordSig[label];
-              out << "," << map1.LabelIntSig[label];
+              out << "," << map1.LabelBordGeom[label];
+              out << "," << map1.LabelIntGeom[label];
             }
+            if((report & SINGLE)or (report & TOTAL)) {
+              out << "," << map1.LabelTotalSig[label];
+              if(report & BORDER) {
+                out << "," << map1.LabelBordSig[label];
+                out << "," << map1.LabelIntSig[label];
+              }
+            }
+            // Write cell centers
+            if(globalCoordinates) {
+              Point3f tr = Point3f(frame.inverseCoordinatesOf(qglviewer::Vec(LabelCenter[label])));
+              out << "," << tr.x();
+              out << "," << tr.y();
+              out << "," << tr.z();
+            } else {
+              out << "," << LabelCenter[label].x();
+              out << "," << LabelCenter[label].y();
+              out << "," << LabelCenter[label].z();
+            }
+  
+            out << endl;
           }
-          // Write cell centers
-          if(globalCoordinates) {
-            Point3f tr = Point3f(frame.inverseCoordinatesOf(qglviewer::Vec(LabelCenter[label])));
-            out << "," << tr.x();
-            out << "," << tr.y();
-            out << "," << tr.z();
-          } else {
-            out << "," << LabelCenter[label].x();
-            out << "," << LabelCenter[label].y();
-            out << "," << LabelCenter[label].z();
-          }
-
-          out << endl;
-        }
-      } break;
-      case WALL: {
-        IntIntFloatMap& WallGeom = mesh1->wallGeom();
-        // Write header
-        out << QString("Label,Neighbor,Value,Wall Length (%1)").arg(UM);
-        if(signal == TOTAL or (report & TOTAL))
-          out << QString(",Wall Border Area (%1),Wall Signal").arg(UM2);
-        out << endl;
-
-        // Write data
-        forall(const IntIntFloatPair& p, WallHeat) {
-          IntIntPair wall = p.first;
-          out << wall.first << "," << wall.second << ",";
-          out << WallHeat[wall] << "," << WallGeom[wall];
+        } break;
+        case WALL: {
+          IntIntFloatMap& WallGeom = mesh1->wallGeom();
+          // Write header
+          out << QString("Label,Neighbor,Value,Wall Length (%1)").arg(UM);
           if(signal == TOTAL or (report & TOTAL))
-            out << "," << map1.WallBordGeom[wall] << "," << map1.WallBordSig[wall];
+            out << QString(",Wall Border Area (%1),Wall Signal").arg(UM2);
           out << endl;
+  
+          // Write data
+          forall(const IntIntFloatPair& p, WallHeat) {
+            IntIntPair wall = p.first;
+            out << wall.first << "," << wall.second << ",";
+            out << WallHeat[wall] << "," << WallGeom[wall];
+            if(signal == TOTAL or (report & TOTAL))
+              out << "," << map1.WallBordGeom[wall] << "," << map1.WallBordSig[wall];
+            out << endl;
+          }
         }
+        }
+        // Footer same for all heat maps
+        QString msg = QString("%1 HeatMap results for mesh %2").arg(sigStr).arg(mesh1->userId());
+        out << endl << endl << qPrintable(msg) << endl;
+  
+        out << "Signal range: " << heatMinAmt << "-" << heatMaxAmt << " " << hunits << endl;
+        file.close();
       }
+    }
+  
+    // Print out stats
+    int ncells = map1.LabelGeom.size();
+    int acells = map1.LabelTotalSig.size();
+    double totageom = 0, totgeom = 0;
+    if(mapType == AREA or mapType == VOLUME) {
+      forall(const IntFloatPair& p, map1.LabelGeom) {
+        totgeom += map1.LabelGeom[p.first];
+        if(map1.LabelTotalSig.find(p.first) != map1.LabelTotalSig.end())
+          totageom += map1.LabelGeom[p.first];
       }
-      // Footer same for all heat maps
-      QString msg = QString("%1 HeatMap results for mesh %2").arg(sigStr).arg(mesh1->userId());
-      out << endl << endl << qPrintable(msg) << endl;
-
-      out << "Signal range: " << heatMinAmt << "-" << heatMaxAmt << " " << hunits << endl;
-      file.close();
+      SETSTATUS("Mesh " << mesh1->userId() << " " << sigStr << " analysis, Cells: " << acells << "/" << ncells << ", "
+                        << totageom << "/" << totgeom << " " << gunits);
     }
+    Information::out << "Range min: " << heatMinAmt << " max: " << heatMaxAmt << " " << hunits << endl;
+  
+    mesh1->updateTriangles();
+    return true;
   }
-
-  // Print out stats
-  int ncells = map1.LabelGeom.size();
-  int acells = map1.LabelTotalSig.size();
-  double totageom = 0, totgeom = 0;
-  if(mapType == AREA or mapType == VOLUME) {
-    forall(const IntFloatPair& p, map1.LabelGeom) {
-      totgeom += map1.LabelGeom[p.first];
-      if(map1.LabelTotalSig.find(p.first) != map1.LabelTotalSig.end())
-        totageom += map1.LabelGeom[p.first];
-    }
-    SETSTATUS("Mesh " << mesh1->userId() << " " << sigStr << " analysis, Cells: " << acells << "/" << ncells << ", "
-                      << totageom << "/" << totgeom << " " << gunits);
+  
+  void ComputeHeatMap::selectSpreadsheetFile()
+  {
+    QLineEdit* edit = dlg->findChild<QLineEdit*>("SpreadsheetFile");
+    if(edit) {
+      QString filename = edit->text();
+      if(filename.isEmpty())
+        filename = "spreadsheet.csv";
+      filename = QFileDialog::getSaveFileName(dlg, "Select file to save report in", filename, "CSV files (*.csv)");
+      if(!filename.isEmpty()) {
+        if(!filename.endsWith(".csv", Qt::CaseInsensitive))
+          filename += ".csv";
+        edit->setText(filename);
+      }
+    } else
+      SETSTATUS("SpreadsheetFile not found ...");
   }
-  SETSTATUS("Range min: " << heatMinAmt << " max: " << heatMaxAmt << " " << hunits);
-
-  mesh1->updateTriangles();
-  return true;
-}
-
-void ComputeHeatMap::selectSpreadsheetFile()
-{
-  QLineEdit* edit = dlg->findChild<QLineEdit*>("SpreadsheetFile");
-  if(edit) {
-    QString filename = edit->text();
-    if(filename.isEmpty())
-      filename = "spreadsheet.csv";
-    filename = QFileDialog::getSaveFileName(dlg, "Select file to save report in", filename, "CSV files (*.csv)");
-    if(!filename.isEmpty()) {
-      if(!filename.endsWith(".csv", Qt::CaseInsensitive))
-        filename += ".csv";
-      edit->setText(filename);
-    }
-  } else
-    SETSTATUS("SpreadsheetFile not found ...");
-}
-
-void ComputeHeatMap::changeMapType(const QString& type)
-{
-  QCheckBox* pol = dlg->findChild<QCheckBox*>("HeatMapPolarity");
-  if(pol)
-    pol->setEnabled(type == "Walls");
-  else
-    SETSTATUS("HeatMapPolarity not found");
-  QComboBox* signal = dlg->findChild<QComboBox*>("HeatMapSignal");
-  if(signal) {
-    QString curtext = signal->currentText();
-    signal->clear();
-    if(type == "Area") {
-      signal->addItem("Geometry");
-      signal->addItem("Border signal");
-      signal->addItem("Interior signal");
-      signal->addItem("Border/total");
-      signal->addItem("Interior/total");
-      signal->addItem("Total signal");
-    } else if(type == "Volume") {
-      signal->addItem("Geometry");
-      signal->addItem("Border signal");
-      signal->addItem("Interior signal");
-      signal->addItem("Border/total");
-      signal->addItem("Interior/total");
-      signal->addItem("Total signal");
-    } else {
-      signal->addItem("Geometry");
-      signal->addItem("Total signal");
-    }
-    for(int i = 0; i < signal->count(); ++i) {
-      if(signal->itemText(i) == curtext) {
-        signal->setCurrentIndex(i);
-        break;
+  
+  void ComputeHeatMap::changeMapType(const QString& type)
+  {
+    QCheckBox* pol = dlg->findChild<QCheckBox*>("HeatMapPolarity");
+    if(pol)
+      pol->setEnabled(type == "Walls");
+    else
+      SETSTATUS("HeatMapPolarity not found");
+    QComboBox* signal = dlg->findChild<QComboBox*>("HeatMapSignal");
+    if(signal) {
+      QString curtext = signal->currentText();
+      signal->clear();
+      if(type == "Area") {
+        signal->addItem("Geometry");
+        signal->addItem("Border signal");
+        signal->addItem("Interior signal");
+        signal->addItem("Border/total");
+        signal->addItem("Interior/total");
+        signal->addItem("Total signal");
+      } else if(type == "Volume") {
+        signal->addItem("Geometry");
+        signal->addItem("Border signal");
+        signal->addItem("Interior signal");
+        signal->addItem("Border/total");
+        signal->addItem("Interior/total");
+        signal->addItem("Total signal");
+      } else {
+        signal->addItem("Geometry");
+        signal->addItem("Total signal");
       }
+      for(int i = 0; i < signal->count(); ++i) {
+        if(signal->itemText(i) == curtext) {
+          signal->setCurrentIndex(i);
+          break;
+        }
+      }
+    } else
+      SETSTATUS("HeatMapSignal not found");
+    QCheckBox* border = dlg->findChild<QCheckBox*>("HeatMapRepBord");
+    if(border)
+      border->setEnabled(type == "Area" || type == "Volume");
+    else
+      SETSTATUS("HeatMapRepBord not found");
+  }
+  
+  void getBBox(const HVec3F& pts, Point3f* bBox)
+  {
+    bBox[0] = Point3f(1e10, 1e10, 1e10);
+    bBox[1] = -bBox[0];
+    forall(const Point3f& pt, pts)
+      for(int i = 0; i < 3; i++) {
+        if(pt[i] < bBox[0][i])
+          bBox[0][i] = pt[i];
+        if(pt[i] > bBox[1][i])
+          bBox[1][i] = pt[i];
+      }
+  }
+  
+  bool ComputeHeatMap::getLabelMaps(ImageHeatMaps& map, Mesh* mesh)
+  {
+    const Stack* stack = mesh->stack();
+    int label;
+  
+    IntFloatMap& LabelGeom = map.LabelGeom;
+    IntFloatMap& LabelBordGeom = map.LabelBordGeom;
+    IntFloatMap& LabelIntGeom = map.LabelIntGeom;
+    IntFloatMap& LabelTotalSig = map.LabelTotalSig;
+    IntFloatMap& LabelBordSig = map.LabelBordSig;
+    IntFloatMap& LabelIntSig = map.LabelIntSig;
+    IntFloatMap& LabelHeatAmt = map.LabelHeatAmt;
+    IntHVec3uMap& LabelTris = map.LabelTris;
+    IntVIdSetMap& LabelPts = map.LabelPts;
+  
+    IntIntFloatMap& WallBordGeom = map.WallBordGeom;
+    IntIntFloatMap& WallBordSig = map.WallBordSig;
+    IntIntFloatMap& WallHeatAmt = map.WallHeatAmt;
+  
+    IntPoint3fMap& LabelCenter = mesh->labelCenter();
+  
+    LabelGeom.clear();
+    LabelBordGeom.clear();
+    LabelIntGeom.clear();
+    LabelTotalSig.clear();
+    LabelBordSig.clear();
+    LabelIntSig.clear();
+    LabelTris.clear();
+    LabelPts.clear();
+    LabelHeatAmt.clear();
+    LabelCenter.clear();
+  
+    WallBordGeom.clear();
+    WallBordSig.clear();
+    WallHeatAmt.clear();
+  
+    // Get the graph
+    vvgraph& S = mesh->graph();
+  
+    // Find selected labels
+    std::set<int> SelectedLabels;
+    std::vector<vertex> av = mesh->activeVertices();
+    bool DoSelected = false;
+    if(av.size() != S.size()) {
+      DoSelected = true;
+      forall(const vertex v, av)
+        forall(const vertex& n, S.neighbors(v)) {
+          vertex m = S.nextTo(v, n);
+          if(!mesh->uniqueTri(v, n, m))
+             continue;
+          int label = mesh->getLabel(v, n, m);
+          if(v->label > 0)
+            SelectedLabels.insert(v->label);
+        }
+      SETSTATUS("Notice: Computing heatmap only for " << SelectedLabels.size() << " selected labels.");
     }
-  } else
-    SETSTATUS("HeatMapSignal not found");
-  QCheckBox* border = dlg->findChild<QCheckBox*>("HeatMapRepBord");
-  if(border)
-    border->setEnabled(type == "Area" || type == "Volume");
-  else
-    SETSTATUS("HeatMapRepBord not found");
-}
-
-void getBBox(const HVec3F& pts, Point3f* bBox)
-{
-  bBox[0] = Point3f(1e10, 1e10, 1e10);
-  bBox[1] = -bBox[0];
-  forall(const Point3f& pt, pts)
-    for(int i = 0; i < 3; i++) {
-      if(pt[i] < bBox[0][i])
-        bBox[0][i] = pt[i];
-      if(pt[i] > bBox[1][i])
-        bBox[1][i] = pt[i];
-    }
-}
-
-bool ComputeHeatMap::getLabelMaps(ImageHeatMaps& map, Mesh* mesh)
-{
-  const Stack* stack = mesh->stack();
-  int label;
-
-  IntFloatMap& LabelGeom = map.LabelGeom;
-  IntFloatMap& LabelBordGeom = map.LabelBordGeom;
-  IntFloatMap& LabelIntGeom = map.LabelIntGeom;
-  IntFloatMap& LabelTotalSig = map.LabelTotalSig;
-  IntFloatMap& LabelBordSig = map.LabelBordSig;
-  IntFloatMap& LabelIntSig = map.LabelIntSig;
-  IntFloatMap& LabelHeatAmt = map.LabelHeatAmt;
-  IntHVec3uMap& LabelTris = map.LabelTris;
-  IntVIdSetMap& LabelPts = map.LabelPts;
-
-  IntIntFloatMap& WallBordGeom = map.WallBordGeom;
-  IntIntFloatMap& WallBordSig = map.WallBordSig;
-  IntIntFloatMap& WallHeatAmt = map.WallHeatAmt;
-
-  IntPoint3fMap& LabelCenter = mesh->labelCenter();
-
-  LabelGeom.clear();
-  LabelBordGeom.clear();
-  LabelIntGeom.clear();
-  LabelTotalSig.clear();
-  LabelBordSig.clear();
-  LabelIntSig.clear();
-  LabelTris.clear();
-  LabelPts.clear();
-  LabelHeatAmt.clear();
-  LabelCenter.clear();
-
-  WallBordGeom.clear();
-  WallBordSig.clear();
-  WallHeatAmt.clear();
-
-  vvgraph& S = mesh->graph();
-
-  // Find border vertices for wall maps or area maps that require it
-  bool doborder = false;
-  QList<SignalType> needBorder = QList<SignalType>() << BORDER << BORDER_TOTAL << INTERIOR << INTERIOR_TOTAL;
-  if((mapType == AREA or mapType == VOLUME)and ((report & BORDER) or needBorder.contains(signal)))
-    doborder = true;
-
-  // Find all vertices within a limited distance from the walls
-  if(doborder or mapType == WALL)
-    mesh->updateWallGeometry(borderSize);
-
-  if(mapType == AREA or mapType == VOLUME) {
-    // For volumes, delete labels with open meshes
-    std::set<int> LabelDel;
-
-    // Loop over triangles
-    forall(const vertex& v, S) {
-      forall(const vertex& n, S.neighbors(v)) {
-        vertex m = S.nextTo(v, n);
-        if(!mesh->uniqueTri(v, n, m))
-          continue;
-        label = mesh->getLabel(v, n, m);
-        if(label <= 0)
-          continue;
-
-        if(mapType == AREA) {
-          // Total area, signal, and label center
-          float area = triangleArea(v->pos, n->pos, m->pos);
-          LabelGeom[label] += area;
-          LabelCenter[label] += area * Point3f(v->pos + n->pos + m->pos) / 3.0;
-          LabelTotalSig[label] += area * (v->signal + n->signal + m->signal) / 3.0;
-
-          // Calculate how much of triangle is in border area
-          if(doborder) {
-            int border = 0;
-            if(v->minb != 0)
-              border++;
-            if(n->minb != 0)
-              border++;
-            if(m->minb != 0)
-              border++;
-            // Border area and signal
-            float bamt = float(border) / 3.0;
-            LabelBordSig[label] += area * bamt * (v->signal + n->signal + m->signal) / 3.0;
-            LabelBordGeom[label] += area * bamt;
-
-            // Interior area and signal
-            float iamt = float(3 - border) / 3.0;
-            LabelIntSig[label] += area * iamt * (v->signal + n->signal + m->signal) / 3.0;
-            LabelIntGeom[label] += area * iamt;
+  
+    // Find border vertices for wall maps or area maps that require it
+    bool doborder = false;
+    QList<SignalType> needBorder = QList<SignalType>() << BORDER << BORDER_TOTAL << INTERIOR << INTERIOR_TOTAL;
+    if((mapType == AREA or mapType == VOLUME)and ((report & BORDER) or needBorder.contains(signal)))
+      doborder = true;
+  
+    // Find all vertices within a limited distance from the walls
+    if(doborder or mapType == WALL)
+      mesh->updateWallGeometry(borderSize);
+  
+    if(mapType == AREA or mapType == VOLUME) {
+      // For volumes, delete labels with open meshes
+      std::set<int> LabelDel;
+  
+      // Loop over triangles
+      forall(const vertex& v, S) {
+        forall(const vertex& n, S.neighbors(v)) {
+          vertex m = S.nextTo(v, n);
+          if(!mesh->uniqueTri(v, n, m))
+            continue;
+          label = mesh->getLabel(v, n, m);
+          if(label <= 0)
+            continue;
+          if(DoSelected and SelectedLabels.count(label) == 0)
+            continue;
+  
+          if(mapType == AREA) {
+            // Total area, signal, and label center
+            float area = triangleArea(v->pos, n->pos, m->pos);
+            LabelGeom[label] += area;
+            LabelCenter[label] += area * Point3f(v->pos + n->pos + m->pos) / 3.0;
+            LabelTotalSig[label] += area * (v->signal + n->signal + m->signal) / 3.0;
+  
+            // Calculate how much of triangle is in border area
+            if(doborder) {
+              int border = 0;
+              if(v->minb != 0)
+                border++;
+              if(n->minb != 0)
+                border++;
+              if(m->minb != 0)
+                border++;
+              // Border area and signal
+              float bamt = float(border) / 3.0;
+              LabelBordSig[label] += area * bamt * (v->signal + n->signal + m->signal) / 3.0;
+              LabelBordGeom[label] += area * bamt;
+  
+              // Interior area and signal
+              float iamt = float(3 - border) / 3.0;
+              LabelIntSig[label] += area * iamt * (v->signal + n->signal + m->signal) / 3.0;
+              LabelIntGeom[label] += area * iamt;
+            }
+          } else if(mapType == VOLUME) {
+            // For volume just grab the triangle list
+            // If any vertices of triangle are not the same as the label, then the label
+            // does not define a closed volume, add it to deletion list
+            // RSS: Fix this for parents
+            if(v->label != label or n->label != label or m->label != label)
+              LabelDel.insert(label);
+  
+            // Calculate volume enclosed by mesh and save triangles
+            float volume = signedTetraVolume(v->pos, n->pos, m->pos);
+            LabelGeom[label] += volume;
+            LabelCenter[label] += volume * Point3f(v->pos + n->pos + m->pos) / 4.0;
+  
+            // Save triangles and points if processing volume signal
+            if(signal != GEOMETRY or (report & TOTAL) or (report & BORDER)) {
+              LabelTris[label].push_back(Point3ul(v.id(), n.id(), m.id()));
+              LabelPts[label].insert(v.id());
+              LabelPts[label].insert(n.id());
+              LabelPts[label].insert(m.id());
+            }
           }
-        } else if(mapType == VOLUME) {
-          // For volume just grab the triangle list
-          // If any vertices of triangle are not the same as the label, then the label
-          // does not define a closed volume, add it to deletion list
-          // RSS: Fix this for parents
-          if(v->label != label or n->label != label or m->label != label)
-            LabelDel.insert(label);
-
-          // Calculate volume enclosed by mesh and save triangles
-          float volume = signedTetraVolume(v->pos, n->pos, m->pos);
-          LabelGeom[label] += volume;
-          LabelCenter[label] += volume * Point3f(v->pos + n->pos + m->pos) / 4.0;
-
-          // Save triangles and points if processing volume signal
-          if(signal != GEOMETRY or (report & TOTAL) or (report & BORDER)) {
-            LabelTris[label].push_back(Point3ul(v.id(), n.id(), m.id()));
-            LabelPts[label].insert(v.id());
-            LabelPts[label].insert(n.id());
-            LabelPts[label].insert(m.id());
-          }
         }
       }
-    }
-
-    // Do the volume heat map signal calculation
-    if(mapType == VOLUME) {
-      // Remove labels which define volume calculations on open meshes
-      forall(int i, LabelDel) {
-        LabelTotalSig.erase(i);
-        SETSTATUS("MakeHeatMap::Warning: Mesh " << mesh->userId() << " open mesh for Vol calc, erasing label "
-                                                << i);
-      }
-
-      // Get mesh volume fluorescence
-      if(signal != GEOMETRY or (report & TOTAL) or (report & BORDER)) {
-        // Get current store
-        const Store* store = mesh->stack()->currentStore();
-        if(!store) {
-          setErrorMessage("Volume signal calculation requires associated store");
-          return false;
+  
+      // Do the volume heat map signal calculation
+      if(mapType == VOLUME) {
+        // Remove labels which define volume calculations on open meshes
+        forall(int i, LabelDel) {
+          LabelTotalSig.erase(i);
+          SETSTATUS("MakeHeatMap::Warning: Mesh " << mesh->userId() << " open mesh for Vol calc, erasing label "
+                                                  << i);
         }
-        const HVecUS& data = store->data();
-
-        // Clear previous geometries and use pixel based volumes, keep the centers
-        LabelGeom.clear();
-        LabelBordGeom.clear();
-        LabelIntGeom.clear();
-
-        // Loop over labels
-        uint step = 0;
-        Progress progress(QString("Finding signal inside mesh %1").arg(mesh->userId()), LabelGeom.size());
-
-        forall(const IntPoint3fPair& p, LabelCenter) {
-          int label = p.first;
-
-          // Process triangle and point lists
-          IntIntMap vmap;
-          HVec3F pts(LabelPts[label].size());
-          int idx = 0;
-          forall(const ulong u, LabelPts[label]) {
-            vertex v(u);
-            pts[idx] = v->pos;
-            vmap[u] = idx++;
+  
+        // Get mesh volume fluorescence
+        if(signal != GEOMETRY or (report & TOTAL) or (report & BORDER)) {
+          // Get current store
+          const Store* store = mesh->stack()->currentStore();
+          if(!store) {
+            setErrorMessage("Volume signal calculation requires associated store");
+            return false;
           }
-          // Calculate triangle normals.
-          idx = 0;
-          HVec3F nrmls(LabelTris[label].size());
-          // Convert triangle index list to new vertex list
-          forall(Point3u& tri, LabelTris[label]) {
-            tri = Point3u(vmap[tri.x()], vmap[tri.y()], vmap[tri.z()]);
-            if(tri.x() > pts.size() or tri.y() > pts.size() or tri.z() > pts.size()) {
-              setErrorMessage("Error, bad triangle index");
-              return false;
+          const HVecUS& data = store->data();
+  
+          // Clear previous geometries and use pixel based volumes, keep the centers
+          LabelGeom.clear();
+          LabelBordGeom.clear();
+          LabelIntGeom.clear();
+  
+          // Loop over labels
+          uint step = 0;
+          Progress progress(QString("Finding signal inside mesh %1").arg(mesh->userId()), LabelGeom.size());
+  
+          forall(const IntPoint3fPair& p, LabelCenter) {
+            int label = p.first;
+  
+            // Process triangle and point lists
+            IntIntMap vmap;
+            HVec3F pts(LabelPts[label].size());
+            int idx = 0;
+            forall(const ulong u, LabelPts[label]) {
+              vertex v(u);
+              pts[idx] = v->pos;
+              vmap[u] = idx++;
             }
-            Point3f a = pts[tri.x()], b = pts[tri.y()], c = pts[tri.z()];
-            nrmls[idx++] = ((b - a) ^ (c - a)).normalize();
-          }
-
-          // Get bounding box
-          Point3f bBoxW[2];
-          getBBox(pts, bBoxW);
-          BoundingBox3i bBoxI(stack->worldToImagei(bBoxW[0]),
-                              stack->worldToImagei(bBoxW[1]) + Point3i(1, 1, 1));
-          Point3i imgSize = stack->size();
-          bBoxI &= BoundingBox3i(Point3i(0, 0, 0), imgSize);
-          Point3i size = bBoxI.size();
-
-          // call cuda
-          if(!progress.advance(step++))
-            userCancel();
-          HVecUS totMask(size_t(size.x()) * size.y() * size.z(), 0),
-          bordMask(size.x() * size.y() * size.z(), 0);
-          if(insideMeshGPU(bBoxI[0], size, stack->step(), stack->origin(), pts, LabelTris[label], nrmls,
-                           totMask))
-            return false;
-          if(!progress.advance(0))
-            userCancel();
-
-          if(doborder) {
-            if(nearMeshGPU(bBoxI[0], size, stack->step(), stack->origin(), pts, nrmls, 0, borderSize,
-                           bordMask))
+            // Calculate triangle normals.
+            idx = 0;
+            HVec3F nrmls(LabelTris[label].size());
+            // Convert triangle index list to new vertex list
+            forall(Point3u& tri, LabelTris[label]) {
+              tri = Point3u(vmap[tri.x()], vmap[tri.y()], vmap[tri.z()]);
+              if(tri.x() > pts.size() or tri.y() > pts.size() or tri.z() > pts.size()) {
+                setErrorMessage("Error, bad triangle index");
+                return false;
+              }
+              Point3f a = pts[tri.x()], b = pts[tri.y()], c = pts[tri.z()];
+              nrmls[idx++] = ((b - a) ^ (c - a)).normalize();
+            }
+  
+            // Get bounding box
+            Point3f bBoxW[2];
+            getBBox(pts, bBoxW);
+            BoundingBox3i bBoxI(stack->worldToImagei(bBoxW[0]),
+                                stack->worldToImagei(bBoxW[1]) + Point3i(1, 1, 1));
+            Point3i imgSize = stack->size();
+            bBoxI &= BoundingBox3i(Point3i(0, 0, 0), imgSize);
+            Point3i size = bBoxI.size();
+  
+            // call cuda
+            if(!progress.advance(step++))
+              userCancel();
+            HVecUS totMask(size_t(size.x()) * size.y() * size.z(), 0),
+            bordMask(size.x() * size.y() * size.z(), 0);
+            if(insideMeshGPU(bBoxI[0], size, stack->step(), stack->origin(), pts, LabelTris[label], nrmls,
+                             totMask))
               return false;
             if(!progress.advance(0))
               userCancel();
-          }
-
-          // Count interior, border, and total pixels
-          uint borderPix = 0, interiorPix = 0, totalPix = 0;
-
-          // sum results
-          for(int z = bBoxI[0].z(); z < bBoxI[1].z(); ++z)
-            for(int y = bBoxI[0].y(); y < bBoxI[1].y(); ++y) {
-              int xIdx = stack->offset(bBoxI[0].x(), y, z);
-              for(int x = bBoxI[0].x(); x < bBoxI[1].x(); ++x, ++xIdx) {
-                size_t mIdx = ((size_t(z) - bBoxI[0].z()) * size.y() + y - bBoxI[0].y()) * size.x() + x
-                  - bBoxI[0].x();
-                if(totMask[mIdx]) {
-                  LabelTotalSig[label] += data[xIdx];
-                  totalPix++;
-                  if(doborder and bordMask[mIdx]) {
-                    borderPix++;
-                    LabelBordSig[label] += data[xIdx];
-                  } else {
-                    interiorPix++;
-                    LabelIntSig[label] += data[xIdx];
+  
+            if(doborder) {
+              if(nearMeshGPU(bBoxI[0], size, stack->step(), stack->origin(), pts, nrmls, 0, borderSize,
+                             bordMask))
+                return false;
+              if(!progress.advance(0))
+                userCancel();
+            }
+  
+            // Count interior, border, and total pixels
+            uint borderPix = 0, interiorPix = 0, totalPix = 0;
+  
+            // sum results
+            for(int z = bBoxI[0].z(); z < bBoxI[1].z(); ++z)
+              for(int y = bBoxI[0].y(); y < bBoxI[1].y(); ++y) {
+                int xIdx = stack->offset(bBoxI[0].x(), y, z);
+                for(int x = bBoxI[0].x(); x < bBoxI[1].x(); ++x, ++xIdx) {
+                  size_t mIdx = ((size_t(z) - bBoxI[0].z()) * size.y() + y - bBoxI[0].y()) * size.x() + x
+                    - bBoxI[0].x();
+                  if(totMask[mIdx]) {
+                    LabelTotalSig[label] += data[xIdx];
+                    totalPix++;
+                    if(doborder and bordMask[mIdx]) {
+                      borderPix++;
+                      LabelBordSig[label] += data[xIdx];
+                    } else {
+                      interiorPix++;
+                      LabelIntSig[label] += data[xIdx];
+                    }
                   }
                 }
               }
-            }
-
-          // Calculate volume and average signal per label
-          float pixVolume = stack->step().x() * stack->step().y() * stack->step().z();
-
-          LabelGeom[label] = totalPix * pixVolume;
-          LabelBordGeom[label] = borderPix * pixVolume;
-          LabelIntGeom[label] = interiorPix * pixVolume;
-
-          LabelTotalSig[label] *= pixVolume;
-          LabelBordSig[label] *= pixVolume;
-          LabelIntSig[label] *= pixVolume;
+  
+            // Calculate volume and average signal per label
+            float pixVolume = stack->step().x() * stack->step().y() * stack->step().z();
+  
+            LabelGeom[label] = totalPix * pixVolume;
+            LabelBordGeom[label] = borderPix * pixVolume;
+            LabelIntGeom[label] = interiorPix * pixVolume;
+  
+            LabelTotalSig[label] *= pixVolume;
+            LabelBordSig[label] *= pixVolume;
+            LabelIntSig[label] *= pixVolume;
+          }
         }
       }
-    }
-
-    // Fill in heatmap color
-    forall(const IntFloatPair& p, LabelGeom) {
-      int label = p.first;
-
-      // Calculate label center
-      LabelCenter[label] = (LabelGeom[label] == 0 ? Point3f(0, 0, 0) : LabelCenter[label] / LabelGeom[label]);
-
-      float totalSignal, bordSignal = 0, intSignal = 0;
-
-      // Set signal amounts, average over area if required
-      totalSignal = LabelTotalSig[label];
-      if(doborder) {
-        bordSignal = LabelBordSig[label];
-        intSignal = LabelIntSig[label];
-      }
-      if(signalAverage) {
-        totalSignal = (LabelGeom[label] == 0 ? 0 : totalSignal / LabelGeom[label]);
+  
+      // Fill in heatmap color
+      forall(const IntFloatPair& p, LabelGeom) {
+        int label = p.first;
+  
+        // Calculate label center
+        LabelCenter[label] = (LabelGeom[label] == 0 ? Point3f(0, 0, 0) : LabelCenter[label] / LabelGeom[label]);
+  
+        float totalSignal, bordSignal = 0, intSignal = 0;
+  
+        // Set signal amounts, average over area if required
+        totalSignal = LabelTotalSig[label];
         if(doborder) {
-          bordSignal = (LabelBordGeom[label] == 0 ? 0 : bordSignal / LabelBordGeom[label]);
-          intSignal = (LabelIntGeom[label] == 0 ? 0 : intSignal / LabelIntGeom[label]);
+          bordSignal = LabelBordSig[label];
+          intSignal = LabelIntSig[label];
         }
+        if(signalAverage) {
+          totalSignal = (LabelGeom[label] == 0 ? 0 : totalSignal / LabelGeom[label]);
+          if(doborder) {
+            bordSignal = (LabelBordGeom[label] == 0 ? 0 : bordSignal / LabelBordGeom[label]);
+            intSignal = (LabelIntGeom[label] == 0 ? 0 : intSignal / LabelIntGeom[label]);
+          }
+        }
+  
+        // Fill in heat depending on user choice
+        switch(signal) {
+        case GEOMETRY:
+          LabelHeatAmt[label] = LabelGeom[label];
+          break;
+        case BORDER:
+          LabelHeatAmt[label] = bordSignal;
+          break;
+        case BORDER_TOTAL:
+          LabelHeatAmt[label] = (totalSignal == 0 ? 0 : bordSignal / totalSignal);
+          break;
+        case INTERIOR:
+          LabelHeatAmt[label] = intSignal;
+          break;
+        case INTERIOR_TOTAL:
+          LabelHeatAmt[label] = (totalSignal == 0 ? 0 : intSignal / totalSignal);
+          break;
+        case TOTAL:
+          LabelHeatAmt[label] = totalSignal;
+          break;
+        }
       }
-
-      // Fill in heat depending on user choice
-      switch(signal) {
-      case GEOMETRY:
-        LabelHeatAmt[label] = LabelGeom[label];
-        break;
-      case BORDER:
-        LabelHeatAmt[label] = bordSignal;
-        break;
-      case BORDER_TOTAL:
-        LabelHeatAmt[label] = (totalSignal == 0 ? 0 : bordSignal / totalSignal);
-        break;
-      case INTERIOR:
-        LabelHeatAmt[label] = intSignal;
-        break;
-      case INTERIOR_TOTAL:
-        LabelHeatAmt[label] = (totalSignal == 0 ? 0 : intSignal / totalSignal);
-        break;
-      case TOTAL:
-        LabelHeatAmt[label] = totalSignal;
-        break;
-      }
-    }
-  } else if(mapType == WALL) {   // Do Wall heatmap
-    IntIntFloatMap& WallGeom = mesh->wallGeom();
-
-    forall(const IntIntFloatPair& wall, WallGeom) {
-      LabelGeom[wall.first.first] += wall.second;
-    }
-
-    // Find area, and signal on each wall
-    if(signal == TOTAL or (report & TOTAL)) {
-      forall(const vertex& v, S) {
-        forall(const vertex& n, S.neighbors(v)) {
-          vertex m = S.nextTo(v, n);
-          if(!mesh->uniqueTri(v, n, m))
-            continue;
-
-          // Sum signal and area
-          IntIntPair wall;
-          int label = mesh->getLabel(v, n, m);
-          if(mesh->isBordTriangle(label, v, n, m, wall)) {
-            float area = triangleArea(v->pos, n->pos, m->pos);
-            WallBordGeom[wall] += area;
-            WallBordSig[wall] += (v->signal + n->signal + m->signal) / 3.0 * area;
-            if(polarity != NONE) {
-              LabelBordGeom[wall.first] += area;
-              LabelBordSig[wall.first] += (v->signal + n->signal + m->signal) / 3.0 * area;
+    } else if(mapType == WALL) {   // Do Wall heatmap
+      IntIntFloatMap& WallGeom = mesh->wallGeom();
+  
+      forall(const IntIntFloatPair& wall, WallGeom)
+        LabelGeom[wall.first.first] += wall.second;
+  
+      // Find area, and signal on each wall
+      if(signal == TOTAL or (report & TOTAL)) {
+        forall(const vertex& v, S) {
+          forall(const vertex& n, S.neighbors(v)) {
+            vertex m = S.nextTo(v, n);
+            if(!mesh->uniqueTri(v, n, m))
+              continue;
+  
+            // Sum signal and area
+            IntIntPair wall;
+            int label = mesh->getLabel(v, n, m);
+            if(mesh->isBordTriangle(label, v, n, m, wall)) {
+              float area = triangleArea(v->pos, n->pos, m->pos);
+              WallBordGeom[wall] += area;
+              WallBordSig[wall] += (v->signal + n->signal + m->signal) / 3.0 * area;
+              if(polarity != NONE) {
+                LabelBordGeom[wall.first] += area;
+                LabelBordSig[wall.first] += (v->signal + n->signal + m->signal) / 3.0 * area;
+              }
             }
           }
         }
       }
-    }
-
-    forall(const IntIntFloatPair& wall, WallGeom) {
-      // Fill in heat depending on user choice
-      switch(signal) {
-      case GEOMETRY:
-        // Heat based on wall length
-        if(polarity == CELL_AVERAGE)
-          WallHeatAmt[wall.first]
-            = (LabelGeom[wall.first.first] == 0 ? 0 : WallGeom[wall.first] / LabelGeom[wall.first.first]);
-        else
-          WallHeatAmt[wall.first] = WallGeom[wall.first];
-        break;
-      case TOTAL:
-        // Heat based on wall signal
-        WallHeatAmt[wall.first] = WallBordSig[wall.first];
-        // Divide by area if required
-        if(signalAverage)
-          WallHeatAmt[wall.first]
-            = (WallBordGeom[wall.first] == 0 ? 0 : WallHeatAmt[wall.first] / WallBordGeom[wall.first]);
-        // Do relative to cell average
-        if(polarity == CELL_AVERAGE) {
-          if(signalAverage)
+  
+      forall(const IntIntFloatPair& wall, WallGeom) {
+        // Fill in heat depending on user choice
+        switch(signal) {
+        case GEOMETRY:
+          // Heat based on wall length
+          if(polarity == CELL_AVERAGE)
             WallHeatAmt[wall.first]
-              = (LabelBordSig[wall.first.first] == 0 or LabelBordGeom[wall.first.first] == 0
-                 ? 0
-                 : WallHeatAmt[wall.first]
-                 / (LabelBordSig[wall.first.first] / LabelBordGeom[wall.first.first]));
+              = (LabelGeom[wall.first.first] == 0 ? 0 : WallGeom[wall.first] / LabelGeom[wall.first.first]);
           else
+            WallHeatAmt[wall.first] = WallGeom[wall.first];
+          break;
+        case TOTAL:
+          // Heat based on wall signal
+          WallHeatAmt[wall.first] = WallBordSig[wall.first];
+          // Divide by area if required
+          if(signalAverage)
             WallHeatAmt[wall.first]
-              = (LabelBordSig[wall.first.first] == 0 ? 0 : WallHeatAmt[wall.first]
-                 / LabelBordSig[wall.first.first]);
+              = (WallBordGeom[wall.first] == 0 ? 0 : WallHeatAmt[wall.first] / WallBordGeom[wall.first]);
+          // Do relative to cell average
+          if(polarity == CELL_AVERAGE) {
+            if(signalAverage)
+              WallHeatAmt[wall.first]
+                = (LabelBordSig[wall.first.first] == 0 or LabelBordGeom[wall.first.first] == 0
+                   ? 0
+                   : WallHeatAmt[wall.first]
+                   / (LabelBordSig[wall.first.first] / LabelBordGeom[wall.first.first]));
+            else
+              WallHeatAmt[wall.first]
+                = (LabelBordSig[wall.first.first] == 0 ? 0 : WallHeatAmt[wall.first]
+                   / LabelBordSig[wall.first.first]);
+          }
+          break;
+        case BORDER:
+        case INTERIOR:
+        case BORDER_TOTAL:
+        case INTERIOR_TOTAL:
+          break;
         }
-        break;
-      case BORDER:
-      case INTERIOR:
-      case BORDER_TOTAL:
-      case INTERIOR_TOTAL:
-        break;
       }
+  
+      // Maps for polarity calc relative to minimum wall
+      if(polarity == WALL_MIN) {
+        IntFloatMap LabelMin;
+        // Find min heat per cell
+        forall(const IntIntFloatPair& wall, WallHeatAmt)
+          if(LabelMin.find(wall.first.first) == LabelMin.end())
+            LabelMin[wall.first.first] = wall.second;
+          else if(LabelMin[wall.first.first] > wall.second)
+            LabelMin[wall.first.first] = wall.second;
+        // Divide heat amounts
+        forall(const IntIntFloatPair& wall, WallHeatAmt)
+          WallHeatAmt[wall.first]
+            = (LabelMin[wall.first.first] == 0 ? 0 : WallHeatAmt[wall.first] / LabelMin[wall.first.first]);
+      }
     }
-
-    // Maps for polarity calc relative to minimum wall
-    if(polarity == WALL_MIN) {
-      IntFloatMap LabelMin;
-      // Find min heat per cell
-      forall(const IntIntFloatPair& wall, WallHeatAmt)
-        if(LabelMin.find(wall.first.first) == LabelMin.end())
-          LabelMin[wall.first.first] = wall.second;
-        else if(LabelMin[wall.first.first] > wall.second)
-          LabelMin[wall.first.first] = wall.second;
-      // Divide heat amounts
-      forall(const IntIntFloatPair& wall, WallHeatAmt)
-        WallHeatAmt[wall.first]
-          = (LabelMin[wall.first.first] == 0 ? 0 : WallHeatAmt[wall.first] / LabelMin[wall.first.first]);
-    }
-  }
-  return true;
-}
-REGISTER_MESH_PROCESS(ComputeHeatMap);
-
-bool DeleteHeatRangeLabels::operator()(Mesh* mesh, bool rescale, bool deleteCells, float min, float max)
-{
-  using std::isnan;
-  Point2f& heatMapBounds = mesh->heatMapBounds();
-  if(isnan(min))
-    min = heatMapBounds[0];
-  if(isnan(max))
-    max = heatMapBounds[1];
-  if(min >= max) {
-    setErrorMessage("Error, the minimum must be strictly less than the maximum");
-    return false;
-  }
-  IntFloatMap& labelHeat = mesh->labelHeat();
-  if(labelHeat.empty())
     return true;
-  vvgraph& S = mesh->graph();
-  std::vector<vertex> T;
-
-  float vmin = 1, vmax = 0;
-
-  IntSet deleteLabel;
-  for(IntFloatMap::iterator it = labelHeat.begin(); it != labelHeat.end(); ++it) {
-    float v = it->second;
-    if(v >= min and v <= max)
-      deleteLabel.insert(it->first);
-    else if(rescale) {
-      if(v < vmin)
-        vmin = v;
-      if(v > vmax)
-        vmax = v;
-    }
   }
-  if(deleteLabel.empty())
-    return true;
-
-  if(rescale and vmin < vmax)
-    heatMapBounds = Point2f(vmin, vmax);
-
-  forall(const vertex& v, S) {
-    if(deleteLabel.count(v->label)) {
-      if(deleteCells)
-        T.push_back(v);
+  REGISTER_MESH_PROCESS(ComputeHeatMap);
+  
+  bool DeleteHeatRangeLabels::operator()(Mesh* mesh, bool rescale, bool deleteCells, float min, float max)
+  {
+    using std::isnan;
+    Point2f& heatMapBounds = mesh->heatMapBounds();
+    if(isnan(min))
+      min = heatMapBounds[0];
+    if(isnan(max))
+      max = heatMapBounds[1];
+    if(min >= max) {
+      setErrorMessage("Error, the minimum must be strictly less than the maximum");
+      return false;
     }
-  }
-  forall(const vertex& v, T)
-    S.erase(v);
-  forall(int label, deleteLabel)
-    labelHeat.erase(label);
-
-  if(deleteCells) {
-    // At last, erase all vertices not part of a triangle
-    do {
-      T.clear();
-      forall(const vertex& v, S) {
-        if(S.valence(v) < 2)
+    IntFloatMap& labelHeat = mesh->labelHeat();
+    if(labelHeat.empty())
+      return true;
+    vvgraph& S = mesh->graph();
+    std::vector<vertex> T;
+  
+    float vmin = 1, vmax = 0;
+  
+    IntSet deleteLabel;
+    for(IntFloatMap::iterator it = labelHeat.begin(); it != labelHeat.end(); ++it) {
+      float v = it->second;
+      if(v >= min and v <= max)
+        deleteLabel.insert(it->first);
+      else if(rescale) {
+        if(v < vmin)
+          vmin = v;
+        if(v > vmax)
+          vmax = v;
+      }
+    }
+    if(deleteLabel.empty())
+      return true;
+  
+    if(rescale and vmin < vmax)
+      heatMapBounds = Point2f(vmin, vmax);
+  
+    forall(const vertex& v, S) {
+      if(deleteLabel.count(v->label)) {
+        if(deleteCells)
           T.push_back(v);
-        else if(S.valence(v) == 2) {
-          const vertex& n = S.anyIn(v);
-          const vertex& m = S.nextTo(v, n);
-          if(!S.edge(n, m))
+      }
+    }
+    forall(const vertex& v, T)
+      S.erase(v);
+    forall(int label, deleteLabel)
+      labelHeat.erase(label);
+  
+    if(deleteCells) {
+      // At last, erase all vertices not part of a triangle
+      do {
+        T.clear();
+        forall(const vertex& v, S) {
+          if(S.valence(v) < 2)
             T.push_back(v);
+          else if(S.valence(v) == 2) {
+            const vertex& n = S.anyIn(v);
+            const vertex& m = S.nextTo(v, n);
+            if(!S.edge(n, m))
+              T.push_back(v);
+          }
         }
-      }
-      forall(const vertex& v, T)
-        S.erase(v);
-    } while(!T.empty());
-    mesh->updateLines();
+        forall(const vertex& v, T)
+          S.erase(v);
+      } while(!T.empty());
+      mesh->updateLines();
+    }
+    mesh->updateAll();
+    return true;
   }
-  mesh->updateAll();
-  return true;
-}
-REGISTER_MESH_PROCESS(DeleteHeatRangeLabels);
-
-bool RescaleHeatMap::operator()(Mesh* m, float minValue, float maxValue)
-{
-  using std::isnan;
-
-  if(isnan(minValue))
-    minValue = m->heatMapBounds()[0];
-  if(isnan(maxValue))
-    maxValue = m->heatMapBounds()[1];
-
-  if(maxValue <= minValue)
-    maxValue = minValue + 1;
-
-  m->heatMapBounds() = Point2f(minValue, maxValue);
-
-  return true;
-}
-REGISTER_MESH_PROCESS(RescaleHeatMap);
-
-bool SaveHeatMap::initialize(QStringList& parms, QWidget* parent)
-{
-  QString& filename = parms[0];
-  if(filename.isEmpty())
-    filename = QFileDialog::getSaveFileName(parent, "Choose spreadsheet file to save", QDir::currentPath(),
-                                            "CSV files (*.csv)");
-  if(filename.isEmpty())
-    return false;
-  if(!filename.endsWith(".csv", Qt::CaseInsensitive))
-    filename += ".csv";
-  parms[0] = filename;
-  return true;
-}
-
-bool SaveHeatMap::operator()(Mesh* mesh, const QString& filename)
-{
-  QFile file(filename);
-  if(!file.open(QIODevice::WriteOnly)) {
-    setErrorMessage(QString("File '%1' cannot be opened for writing").arg(filename));
-    return false;
+  REGISTER_MESH_PROCESS(DeleteHeatRangeLabels);
+  
+  bool RescaleHeatMap::operator()(Mesh* m, float minValue, float maxValue)
+  {
+    using std::isnan;
+  
+    if(isnan(minValue))
+      minValue = m->heatMapBounds()[0];
+    if(isnan(maxValue))
+      maxValue = m->heatMapBounds()[1];
+  
+    if(maxValue <= minValue)
+      maxValue = minValue + 1;
+  
+    m->heatMapBounds() = Point2f(minValue, maxValue);
+  
+    return true;
   }
-  QTextStream out(&file);
-
-  out << "Label,Value" << endl;
-  forall(const IntFloatPair& p, mesh->labelHeat())
-    out << p.first << "," << p.second << endl;
-
-  SETSTATUS(QString("Wrote heat map file with %1 labels").arg(mesh->labelHeat().size()));
-  return true;
-}
-REGISTER_MESH_PROCESS(SaveHeatMap);
-
-bool LoadHeatMap::initialize(QStringList& parms, QWidget* parent)
-{
-  Ui_LoadHeatMap ui;
-  dlg = new QDialog(parent);
-  ui.setupUi(dlg);
-  connect(ui.SelectHeatMapFile, SIGNAL(clicked()), this, SLOT(selectFile()));
-  connect(ui.HeatMapColumn, SIGNAL(currentIndexChanged(int)), this, SLOT(selectColumn(int)));
-  this->ui = &ui;
-  ui.HeatMapColumn->setSizeAdjustPolicy(QComboBox::AdjustToContents);
-  if(!parms[0].isEmpty())
-    selectFile(parms[0]);
-  if(dlg->exec() == QDialog::Accepted) {
-    parms[0] = ui.HeatMapFile->text();
-    parms[1] = QString::number(ui.HeatMapColumn->currentIndex());
+  REGISTER_MESH_PROCESS(RescaleHeatMap);
+  
+  bool SaveHeatMap::initialize(QStringList& parms, QWidget* parent)
+  {
+    QString& filename = parms[0];
+    if(filename.isEmpty())
+      filename = QFileDialog::getSaveFileName(parent, "Choose spreadsheet file to save", QDir::currentPath(),
+                                              "CSV files (*.csv)");
+    if(filename.isEmpty())
+      return false;
+    if(!filename.endsWith(".csv", Qt::CaseInsensitive))
+      filename += ".csv";
+    parms[0] = filename;
     return true;
   }
-  return false;
-}
-
-void LoadHeatMap::selectFile(const QString& filename)
-{
-  QFile file(filename);
-  if(!file.open(QIODevice::ReadOnly)) {
-    QMessageBox::critical(dlg, "Error opening file",
-                          QString("File '%1' cannot be opened for reading").arg(filename));
-    return;
+  
+  bool SaveHeatMap::operator()(Mesh* mesh, const QString& filename)
+  {
+    QFile file(filename);
+    if(!file.open(QIODevice::WriteOnly)) {
+      setErrorMessage(QString("File '%1' cannot be opened for writing").arg(filename));
+      return false;
+    }
+    QTextStream out(&file);
+  
+    out << "Label,Value" << endl;
+    forall(const IntFloatPair& p, mesh->labelHeat())
+      out << p.first << "," << p.second << endl;
+  
+    SETSTATUS(QString("Wrote heat map file with %1 labels").arg(mesh->labelHeat().size()));
+    return true;
   }
-  QTextStream ss(&file);
-  QString line = ss.readLine();
-  QStringList fields = line.split(",");
-  if(fields.size() < 2) {
-    QMessageBox::critical(dlg, "Error reading file",
-                          QString("File '%1' should be a CSV file with at least 3 columns").arg(filename));
-    return;
+  REGISTER_MESH_PROCESS(SaveHeatMap);
+  
+  bool LoadHeatMap::initialize(QStringList& parms, QWidget* parent)
+  {
+    Ui_LoadHeatMap ui;
+    dlg = new QDialog(parent);
+    ui.setupUi(dlg);
+    connect(ui.SelectHeatMapFile, SIGNAL(clicked()), this, SLOT(selectFile()));
+    connect(ui.HeatMapColumn, SIGNAL(currentIndexChanged(int)), this, SLOT(selectColumn(int)));
+    this->ui = &ui;
+    ui.HeatMapColumn->setSizeAdjustPolicy(QComboBox::AdjustToContents);
+    if(!parms[0].isEmpty())
+      selectFile(parms[0]);
+    if(dlg->exec() == QDialog::Accepted) {
+      parms[0] = ui.HeatMapFile->text();
+      parms[1] = QString::number(ui.HeatMapColumn->currentIndex());
+      return true;
+    }
+    return false;
   }
-  QRegExp unit(".*\\((.*)\\)\\s*");
-  ui->HeatMapColumn->clear();
-  column_unit.clear();
-  for(int i = 0; i < fields.size(); ++i) {
-    QString txt = fields[i].trimmed();
-    if(txt[0] == '"' and txt[txt.size() - 1] == '"')
-      txt = txt.mid(1, txt.size() - 2).trimmed();
-    if(unit.indexIn(txt) == 0)
-      column_unit << unit.cap(1);
+  
+  void LoadHeatMap::selectFile(const QString& filename)
+  {
+    QFile file(filename);
+    if(!file.open(QIODevice::ReadOnly)) {
+      QMessageBox::critical(dlg, "Error opening file",
+                            QString("File '%1' cannot be opened for reading").arg(filename));
+      return;
+    }
+    QTextStream ss(&file);
+    QString line = ss.readLine();
+    QStringList fields = line.split(",");
+    if(fields.size() < 2) {
+      QMessageBox::critical(dlg, "Error reading file",
+                            QString("File '%1' should be a CSV file with at least 3 columns").arg(filename));
+      return;
+    }
+    QRegExp unit(".*\\((.*)\\)\\s*");
+    ui->HeatMapColumn->clear();
+    column_unit.clear();
+    for(int i = 0; i < fields.size(); ++i) {
+      QString txt = fields[i].trimmed();
+      if(txt[0] == '"' and txt[txt.size() - 1] == '"')
+        txt = txt.mid(1, txt.size() - 2).trimmed();
+      if(unit.indexIn(txt) == 0)
+        column_unit << unit.cap(1);
+      else
+        column_unit << "";
+      ui->HeatMapColumn->addItem(txt);
+    }
+    if(fields[1].trimmed() == "Neighbor")
+      ui->HeatMapColumn->setCurrentIndex(3);
     else
-      column_unit << "";
-    ui->HeatMapColumn->addItem(txt);
+      ui->HeatMapColumn->setCurrentIndex(2);
+    ui->HeatMapFile->setText(filename);
   }
-  if(fields[1].trimmed() == "Neighbor")
-    ui->HeatMapColumn->setCurrentIndex(3);
-  else
-    ui->HeatMapColumn->setCurrentIndex(2);
-  ui->HeatMapFile->setText(filename);
-}
-
-void LoadHeatMap::selectFile()
-{
-  QString filename = QFileDialog::getOpenFileName(dlg, "Choose spreadsheet to load", ui->HeatMapFile->text(),
-                                                  "CSV files (*.csv);;All files (*.*)");
-  if(!filename.isEmpty())
-    selectFile(filename);
-}
-
-void LoadHeatMap::selectColumn(int i)
-{
-  if(i >= 0 and i < column_unit.size())
-    ui->unitLabel->setText(column_unit[i]);
-}
-
-bool LoadHeatMap::operator()(Mesh* mesh, const QString& filename, int column, float border_size)
-{
-  if(column < 0) {
-    setErrorMessage(QString("Invalid column '%1'").arg(column));
-    return false;
+  
+  void LoadHeatMap::selectFile()
+  {
+    QString filename = QFileDialog::getOpenFileName(dlg, "Choose spreadsheet to load", ui->HeatMapFile->text(),
+                                                    "CSV files (*.csv);;All files (*.*)");
+    if(!filename.isEmpty())
+      selectFile(filename);
   }
-
-  QFile file(filename);
-  if(!file.open(QIODevice::ReadOnly)) {
-    setErrorMessage(QString("File '%1' cannot be opened for reading").arg(filename));
-    return false;
+  
+  void LoadHeatMap::selectColumn(int i)
+  {
+    if(i >= 0 and i < column_unit.size())
+      ui->unitLabel->setText(column_unit[i]);
   }
-  QTextStream ss(&file);
-  QString line = ss.readLine();
-  QStringList fields = line.split(",");
-  if(fields.size() < column + 1) {
-    setErrorMessage(
-      QString("File '%1' should be a CSV file with at least %2 columns").arg(filename).arg(column + 1));
-    return false;
-  }
-  QRegExp re_unit(".*\\((.*)\\)\\s*");
-  QString unit;
-  QString txt = fields[column].trimmed();
-  int nb_fields = fields.size();
-  if(re_unit.indexIn(txt) == 0)
-    unit = re_unit.cap(1);
-  QString col2 = fields[1];
-  if(col2[0] == '"' and col2[col2.size() - 1] == '"')
-    col2 = col2.mid(1, col2.size() - 2).trimmed();
-  bool is_wall = col2.trimmed() == "Neighbor";
-  if(is_wall)
-    mesh->updateWallGeometry(border_size);
-  float minValue = HUGE_VAL, maxValue = -HUGE_VAL;
-  int line_nb = 1;
-  IntFloatMap& labelMap = mesh->labelHeat();
-  IntIntFloatMap& wallMap = mesh->wallHeat();
-  while(ss.status() == QTextStream::Ok) {
-    ++line_nb;
-    fields = ss.readLine().split(",");
-    if(fields.size() != nb_fields or fields[0].isEmpty())
-      break;
-    bool ok;
-    int neighbor = 0;
-    int label = fields[0].toInt(&ok);
-    if(!ok) {
-      setErrorMessage(QString("Error line %1: the first column is not an integer number but '%2'")
-                      .arg(line_nb)
-                      .arg(fields[0].trimmed()));
+  
+  bool LoadHeatMap::operator()(Mesh* mesh, const QString& filename, int column, float border_size)
+  {
+    if(column < 0) {
+      setErrorMessage(QString("Invalid column '%1'").arg(column));
       return false;
     }
-    if(is_wall) {
-      neighbor = fields[1].toInt(&ok);
+  
+    QFile file(filename);
+    if(!file.open(QIODevice::ReadOnly)) {
+      setErrorMessage(QString("File '%1' cannot be opened for reading").arg(filename));
+      return false;
+    }
+    QTextStream ss(&file);
+    QString line = ss.readLine();
+    QStringList fields = line.split(",");
+    if(fields.size() < column + 1) {
+      setErrorMessage(
+        QString("File '%1' should be a CSV file with at least %2 columns").arg(filename).arg(column + 1));
+      return false;
+    }
+    QRegExp re_unit(".*\\((.*)\\)\\s*");
+    QString unit;
+    QString txt = fields[column].trimmed();
+    int nb_fields = fields.size();
+    if(re_unit.indexIn(txt) == 0)
+      unit = re_unit.cap(1);
+    QString col2 = fields[1];
+    if(col2[0] == '"' and col2[col2.size() - 1] == '"')
+      col2 = col2.mid(1, col2.size() - 2).trimmed();
+    bool is_wall = col2.trimmed() == "Neighbor";
+    if(is_wall)
+      mesh->updateWallGeometry(border_size);
+    float minValue = HUGE_VAL, maxValue = -HUGE_VAL;
+    int line_nb = 1;
+    IntFloatMap& labelMap = mesh->labelHeat();
+    IntIntFloatMap& wallMap = mesh->wallHeat();
+    while(ss.status() == QTextStream::Ok) {
+      ++line_nb;
+      fields = ss.readLine().split(",");
+      if(fields.size() != nb_fields or fields[0].isEmpty())
+        break;
+      bool ok;
+      int neighbor = 0;
+      int label = fields[0].toInt(&ok);
       if(!ok) {
-        setErrorMessage(QString("Error line %1: the second column is not an integer number but '%2'")
+        setErrorMessage(QString("Error line %1: the first column is not an integer number but '%2'")
                         .arg(line_nb)
-                        .arg(fields[1].trimmed()));
+                        .arg(fields[0].trimmed()));
         return false;
       }
+      if(is_wall) {
+        neighbor = fields[1].toInt(&ok);
+        if(!ok) {
+          setErrorMessage(QString("Error line %1: the second column is not an integer number but '%2'")
+                          .arg(line_nb)
+                          .arg(fields[1].trimmed()));
+          return false;
+        }
+      }
+      float value = fields[column].toFloat(&ok);
+      if(!ok) {
+        setErrorMessage(QString("Error line %1: the column %2 is not an floating point number but '%3'")
+                        .arg(line_nb)
+                        .arg(column)
+                        .arg(fields[column].trimmed()));
+        return false;
+      }
+      if(is_wall)
+        wallMap[std::make_pair(label, neighbor)] = value;
+      else
+        labelMap[label] = value;
+      if(value < minValue)
+        minValue = value;
+      if(value > maxValue)
+        maxValue = value;
     }
-    float value = fields[column].toFloat(&ok);
-    if(!ok) {
-      setErrorMessage(QString("Error line %1: the column %2 is not an floating point number but '%3'")
-                      .arg(line_nb)
-                      .arg(column)
-                      .arg(fields[column].trimmed()));
-      return false;
-    }
-    if(is_wall)
-      wallMap[std::make_pair(label, neighbor)] = value;
-    else
-      labelMap[label] = value;
-    if(value < minValue)
-      minValue = value;
-    if(value > maxValue)
-      maxValue = value;
+    if(minValue >= maxValue)
+      return setErrorMessage("The file contains 0 or 1 value only. We cannot create a heat map from that.");
+    mesh->heatMapUnit() = unit;
+    mesh->heatMapBounds() = Point2f(minValue, maxValue);
+    mesh->updateTriangles();
+    mesh->showHeat();
+    SETSTATUS(QString("Loaded heat map with values ranging from %1%3 to %2%3").arg(minValue).arg(maxValue).arg(unit));
+    return true;
   }
-  if(minValue >= maxValue)
-    return setErrorMessage("The file contains 0 or 1 value only. We cannot create a heat map from that.");
-  mesh->heatMapUnit() = unit;
-  mesh->heatMapBounds() = Point2f(minValue, maxValue);
-  mesh->updateTriangles();
-  mesh->showHeat();
-  SETSTATUS(QString("Loaded heat map with values ranging from %1%3 to %2%3").arg(minValue).arg(maxValue).arg(unit));
-  return true;
-}
-REGISTER_MESH_PROCESS(LoadHeatMap);
-} // namespace process
-} // namespace mgx
+  REGISTER_MESH_PROCESS(LoadHeatMap);
+}}
Index: CMakeLists.txt
===================================================================
--- CMakeLists.txt	(revision 1255)
+++ CMakeLists.txt	(revision 1256)
@@ -81,7 +81,6 @@
   ExportMesh.ui
   TransferFunctionDlg.ui
   EditMarkersDlg.ui
-  SaveAll.ui
   ExportStack.ui
 )
 QT4_WRAP_UI(MorphoGraphX_SO_UIS_H ${MorphoGraphX_SO_UIS})
@@ -395,6 +394,6 @@
   ENDIF()
 ENDIF()
 
-INCLUDE(CPack)
+#INCLUDE(CPack)
 
 ################################################################
Index: Geometry.hpp
===================================================================
--- Geometry.hpp	(revision 1255)
+++ Geometry.hpp	(revision 1256)
@@ -19,262 +19,264 @@
 #include <math.h>
 
 namespace mgx {
-/**
- * Algorithmic %geometry
- *
- * This namespace contains different useful %geometry %algorithms, like
- * intersections, areas, ...
- */
-typedef unsigned char ubyte;
-typedef unsigned int uint;
-typedef unsigned short ushort;
-typedef unsigned long ulong;
 
-typedef util::Vector<2, float> Point2f;
-typedef util::Vector<3, float> Point3f;
-typedef util::Vector<4, float> Point4f;
-typedef util::Vector<5, float> Point5f;
-typedef util::Vector<6, float> Point6f;
-typedef util::Vector<12, float> Point12f;
-
-typedef util::Vector<2, double> Point2d;
-typedef util::Vector<3, double> Point3d;
-typedef util::Vector<4, double> Point4d;
-typedef util::Vector<5, double> Point5d;
-typedef util::Vector<6, double> Point6d;
-typedef util::Vector<16, double> Point16d;
-
-typedef util::Vector<2, int> Point2i;
-typedef util::Vector<3, int> Point3i;
-typedef util::Vector<4, int> Point4i;
-typedef util::Vector<5, int> Point5i;
-typedef util::Vector<6, int> Point6i;
-
-typedef util::Vector<2, uint> Point2u;
-typedef util::Vector<3, uint> Point3u;
-typedef util::Vector<4, uint> Point4u;
-typedef util::Vector<5, uint> Point5u;
-typedef util::Vector<6, uint> Point6u;
-
-typedef util::Vector<2, size_t> Point2s;
-typedef util::Vector<3, size_t> Point3s;
-typedef util::Vector<4, size_t> Point4s;
-typedef util::Vector<5, size_t> Point5s;
-typedef util::Vector<6, size_t> Point6s;
-
-typedef util::Vector<3, ushort> Point3us;
-
-typedef util::Matrix<2, 2, float> Matrix2f;
-typedef util::Matrix<3, 3, float> Matrix3f;
-typedef util::Matrix<4, 4, float> Matrix4f;
-
-typedef util::Matrix<2, 2, double> Matrix2d;
-typedef util::Matrix<3, 3, double> Matrix3d;
-typedef util::Matrix<4, 4, double> Matrix4d;
-
-typedef util::BoundingBox<3, uint> BoundingBox3u;
-typedef util::BoundingBox<3, int> BoundingBox3i;
-typedef util::BoundingBox<3, float> BoundingBox3f;
-
-// Min
-template <typename T> CU_HOST_DEVICE T min(const T a, const T b)
-{
-  if(a <= b)
-    return a;
-  return b;
-}
-
-// Max
-template <typename T> T CU_HOST_DEVICE max(const T a, const T b)
-{
-  if(a >= b)
-    return a;
-  return b;
-}
-
-// Trim to min/max
-template <typename T> CU_HOST_DEVICE T trim(const T x, const T minx, const T maxx) {
-  return max(minx, min(maxx, x));
-}
-
-CU_HOST_DEVICE
-Point3u toVoxelsCeil(const Point3f& p, const Point3f& step)
-{
-  Point3u r(0, 0, 0);
-  if(p.x() > 0 and step.x() > 0)
-    r.x() = uint(ceil(p.x() / step.x()));
-  if(p.y() > 0 and step.y() > 0)
-    r.y() = uint(ceil(p.y() / step.y()));
-  if(p.z() > 0 and step.z() > 0)
-    r.z() = uint(ceil(p.z() / step.z()));
-  return r;
-}
-
-// Multiple openGL 4D matrix by 3D point and return 3D point
-template <typename T>
-CU_HOST_DEVICE util::Vector<3, T> multMatrix4Point3(const util::Matrix<4, 4, T>& m, const util::Vector<3, T>& p)
-{
-  util::Vector<4, T> t(p.x(), p.y(), p.z(), T(1.0));
-  t = m * t;
-  util::Vector<3, T> res(t.x() / t.t(), t.y() / t.t(), t.z() / t.t());
-  return res;
-}
-
-template <typename T> T CU_HOST_DEVICE interpolate(const T a, const T b, const T s)
-{
-  T t = trim(s, (T)0.0, (T)1.0);
-  return ((1.0 - t) * a + t * b);
-}
-
-// CU_HOST_DEVICE
-// Point3f getEulerAngles(Matrix4d &m)
-//{
-//  Point3f r(0,0,0);
-//  if(fabs(m(1,0)) > .1)
-//    r.x() = atan2(m(0,2), m(2,2)) / M_PI * 180;
-//  else
-//    r.x() = atan2(-m(2,0), m(0,0)) / M_PI * 180;
-//  r.y() = atan2(-m(1,2), m(2,2)) / M_PI * 180;
-//  r.z() = asin(m(1,0)) / M_PI * 180;
-//  return(r);
-//}
-
-// Plane-Line Intersection, 0 <= s <= 1, on line, s >= 0 ray intersect
-CU_HOST_DEVICE
-bool planeLineIntersect(Point3f p, Point3f n, Point3f u1, Point3f u2, float& s, Point3f& u)
-{
-  n.normalize();
-  Point3f u1u2 = u2 - u1;
-  float t = n * u1u2;
-  // Check if parallel
-  if(t == 0)
-    return (false);
-  s = n * (p - u1) / t;
-  u = u1 + s * u1u2;
-  return (true);
-}
-
-// Triangle area
-CU_HOST_DEVICE
-float triangleArea(Point3f a, Point3f b, Point3f c) {
-  return ((a - b).cross(a - c).norm() / 2.0);
-}
-
-// Signed volume of a tetrahedron
-CU_HOST_DEVICE
-float signedTetraVolume(Point3f a, Point3f b, Point3f c)
-{
-  return ((-c.x() * b.y() * a.z() + b.x() * c.y() * a.z() + c.x() * a.y() * b.z() - a.x() * c.y() * b.z()
-           - b.x() * a.y() * c.z() + a.x() * b.y() * c.z()) / 6.0f);
-}
-
-// Get (a set of) basis vectors from a plane
-CU_HOST_DEVICE
-void getBasisFromPlane(const Point3f& nrml, Point3f& x, Point3f& y, Point3f& z)
-{
-  Point3f n = nrml;
-  n.normalize();
-  x = Point3f(1, 0, 0);
-  y = Point3f(0, 1, 0);
-  z = Point3f(0, 0, 1);
-  if(z.cross(n).norm() != 0) {
-    y = z.cross(n);
-    y.normalize();
-    x = y.cross(n);
-    x.normalize();
-  } else
-    x = n * z * x;
-  z = n;
-}
-
-// Intersect a ray with a 3D triangle
-//    Input:  ray r1,r2 triangle t0,t1,t2
-//    Output: intp = intersection point (when it exists)
-//    Return: -1 = triangle is degenerate (a segment or point)
-//             0 = disjoint (no intersect)
-//             1 = intersect in unique point I1
-//             2 = are in the same plane
-CU_HOST_DEVICE
-int rayTriangleIntersect(const Point3f& r0, const Point3f& r1, const Point3f& t0, const Point3f& t1, const Point3f& t2,
-                         Point3f& intp)
-{
-  // get triangle edge vectors and plane normal
-  Point3f u = t1 - t0;
-  Point3f v = t2 - t0;
-  Point3f n = u.cross(v);
-  if(n.x() == 0 && n.y() == 0 && n.z() == 0)   // triangle is degenerate
-    return -1;
-
-  Point3f dir = r1 - r0;   // ray direction vector
-  Point3f w0 = r0 - t0;
-  float a = -n * w0;
-  float b = n * dir;
-  if(b == 0) {     // ray is parallel to triangle plane
-    if(a == 0)     // ray lies in triangle plane
-      return 2;
-    else
-      return 0;       // ray disjoint from plane
+  /**
+   * Algorithmic %geometry
+   *
+   * This namespace contains different useful %geometry %algorithms, like
+   * intersections, areas, ...
+   */
+  typedef unsigned char ubyte;
+  typedef unsigned int uint;
+  typedef unsigned short ushort;
+  typedef unsigned long ulong;
+  
+  typedef util::Vector<2, float> Point2f;
+  typedef util::Vector<3, float> Point3f;
+  typedef util::Vector<4, float> Point4f;
+  typedef util::Vector<5, float> Point5f;
+  typedef util::Vector<6, float> Point6f;
+  typedef util::Vector<12, float> Point12f;
+  
+  typedef util::Vector<2, double> Point2d;
+  typedef util::Vector<3, double> Point3d;
+  typedef util::Vector<4, double> Point4d;
+  typedef util::Vector<5, double> Point5d;
+  typedef util::Vector<6, double> Point6d;
+  typedef util::Vector<16, double> Point16d;
+  
+  typedef util::Vector<2, int> Point2i;
+  typedef util::Vector<3, int> Point3i;
+  typedef util::Vector<4, int> Point4i;
+  typedef util::Vector<5, int> Point5i;
+  typedef util::Vector<6, int> Point6i;
+  
+  typedef util::Vector<2, uint> Point2u;
+  typedef util::Vector<3, uint> Point3u;
+  typedef util::Vector<4, uint> Point4u;
+  typedef util::Vector<5, uint> Point5u;
+  typedef util::Vector<6, uint> Point6u;
+  
+  typedef util::Vector<2, size_t> Point2s;
+  typedef util::Vector<3, size_t> Point3s;
+  typedef util::Vector<4, size_t> Point4s;
+  typedef util::Vector<5, size_t> Point5s;
+  typedef util::Vector<6, size_t> Point6s;
+  
+  typedef util::Vector<3, ushort> Point3us;
+  
+  typedef util::Matrix<2, 2, float> Matrix2f;
+  typedef util::Matrix<3, 3, float> Matrix3f;
+  typedef util::Matrix<4, 4, float> Matrix4f;
+  
+  typedef util::Matrix<2, 2, double> Matrix2d;
+  typedef util::Matrix<3, 3, double> Matrix3d;
+  typedef util::Matrix<4, 4, double> Matrix4d;
+  
+  typedef util::BoundingBox<3, uint> BoundingBox3u;
+  typedef util::BoundingBox<3, int> BoundingBox3i;
+  typedef util::BoundingBox<3, float> BoundingBox3f;
+  
+  // Min
+  template <typename T> CU_HOST_DEVICE T min(const T a, const T b)
+  {
+    if(a <= b)
+      return a;
+    return b;
   }
-
-  // get intersect point of ray with triangle plane
-  float r = a / b;
-  if(r < 0.0f)    // ray goes away from triangle
-    return 0;     // => no intersect
-  // for a segment, also test if (r > 1.0) => no intersect
-
-  intp = r0 + r * dir;   // intersect point of ray and plane
-
-  // is intersect point inside the triangle?
-  float uu, uv, vv, wu, wv, d;
-  uu = u * u;
-  uv = u * v;
-  vv = v * v;
-  Point3f w = intp - t0;
-  wu = w * u;
-  wv = w * v;
-  d = uv * uv - uu * vv;
-
-  // get and test parametric coords
-  float s, t;
-  s = (uv * wv - vv * wu) / d;
-  if(s < 0.0f || s > 1.0f)   // outside
-    return 0;
-  t = (uv * wu - uu * wv) / d;
-  if(t < 0.0f || (s + t) > 1.0f)   // outside
-    return 0;
-
-  return 1;   // in
-}
-
-// Return distance from a point to a line (or segment)
-CU_HOST_DEVICE
-float distLinePoint(Point3f v1, Point3f v2, Point3f p, bool segment)
-{
-  v2 -= v1;
-  float n = norm(v2);
-  // Points are the same
-  if(n == 0)
-    return norm(p - v1);
-
-  Point3f vn = v2 / n;
-  p -= v1;
-  Point3f q = vn * (p * vn);
-  float dist = norm(p - q);
-  if(!segment)
+  
+  // Max
+  template <typename T> T CU_HOST_DEVICE max(const T a, const T b)
+  {
+    if(a >= b)
+      return a;
+    return b;
+  }
+  
+  // Trim to min/max
+  template <typename T> CU_HOST_DEVICE T trim(const T x, const T minx, const T maxx) {
+    return max(minx, min(maxx, x));
+  }
+  
+  CU_HOST_DEVICE
+  Point3u toVoxelsCeil(const Point3f& p, const Point3f& step)
+  {
+    Point3u r(0, 0, 0);
+    if(p.x() > 0 and step.x() > 0)
+      r.x() = uint(ceil(p.x() / step.x()));
+    if(p.y() > 0 and step.y() > 0)
+      r.y() = uint(ceil(p.y() / step.y()));
+    if(p.z() > 0 and step.z() > 0)
+      r.z() = uint(ceil(p.z() / step.z()));
+    return r;
+  }
+  
+  // Multiple openGL 4D matrix by 3D point and return 3D point
+  template <typename T>
+  CU_HOST_DEVICE util::Vector<3, T> multMatrix4Point3(const util::Matrix<4, 4, T>& m, const util::Vector<3, T>& p)
+  {
+    util::Vector<4, T> t(p.x(), p.y(), p.z(), T(1.0));
+    t = m * t;
+    util::Vector<3, T> res(t.x() / t.t(), t.y() / t.t(), t.z() / t.t());
+    return res;
+  }
+  
+  template <typename T> T CU_HOST_DEVICE interpolate(const T a, const T b, const T s)
+  {
+    T t = trim(s, (T)0.0, (T)1.0);
+    return ((1.0 - t) * a + t * b);
+  }
+  
+  // CU_HOST_DEVICE
+  // Point3f getEulerAngles(Matrix4d &m)
+  //{
+  //  Point3f r(0,0,0);
+  //  if(fabs(m(1,0)) > .1)
+  //    r.x() = atan2(m(0,2), m(2,2)) / M_PI * 180;
+  //  else
+  //    r.x() = atan2(-m(2,0), m(0,0)) / M_PI * 180;
+  //  r.y() = atan2(-m(1,2), m(2,2)) / M_PI * 180;
+  //  r.z() = asin(m(1,0)) / M_PI * 180;
+  //  return(r);
+  //}
+  
+  // Plane-Line Intersection, 0 <= s <= 1, on line, s >= 0 ray intersect
+  CU_HOST_DEVICE
+  bool planeLineIntersect(Point3f p, Point3f n, Point3f u1, Point3f u2, float& s, Point3f& u)
+  {
+    n.normalize();
+    Point3f u1u2 = u2 - u1;
+    float t = n * u1u2;
+    // Check if parallel
+    if(t == 0)
+      return (false);
+    s = n * (p - u1) / t;
+    u = u1 + s * u1u2;
+    return (true);
+  }
+  
+  // Triangle area
+  CU_HOST_DEVICE
+  float triangleArea(Point3f a, Point3f b, Point3f c) {
+    return ((a - b).cross(a - c).norm() / 2.0);
+  }
+  
+  // Signed volume of a tetrahedron
+  CU_HOST_DEVICE
+  float signedTetraVolume(Point3f a, Point3f b, Point3f c)
+  {
+    return ((-c.x() * b.y() * a.z() + b.x() * c.y() * a.z() + c.x() * a.y() * b.z() - a.x() * c.y() * b.z()
+             - b.x() * a.y() * c.z() + a.x() * b.y() * c.z()) / 6.0f);
+  }
+  
+  // Get (a set of) basis vectors from a plane
+  CU_HOST_DEVICE
+  void getBasisFromPlane(const Point3f& nrml, Point3f& x, Point3f& y, Point3f& z)
+  {
+    Point3f n = nrml;
+    n.normalize();
+    x = Point3f(1, 0, 0);
+    y = Point3f(0, 1, 0);
+    z = Point3f(0, 0, 1);
+    if(z.cross(n).norm() != 0) {
+      y = z.cross(n);
+      y.normalize();
+      x = y.cross(n);
+      x.normalize();
+    } else
+      x = n * z * x;
+    z = n;
+  }
+  
+  // Intersect a ray with a 3D triangle
+  //    Input:  ray r1,r2 triangle t0,t1,t2
+  //    Output: intp = intersection point (when it exists)
+  //    Return: -1 = triangle is degenerate (a segment or point)
+  //             0 = disjoint (no intersect)
+  //             1 = intersect in unique point I1
+  //             2 = are in the same plane
+  CU_HOST_DEVICE
+  int rayTriangleIntersect(const Point3f& r0, const Point3f& r1, const Point3f& t0, const Point3f& t1, const Point3f& t2,
+                           Point3f& intp)
+  {
+    // get triangle edge vectors and plane normal
+    Point3f u = t1 - t0;
+    Point3f v = t2 - t0;
+    Point3f n = u.cross(v);
+    if(n.x() == 0 && n.y() == 0 && n.z() == 0)   // triangle is degenerate
+      return -1;
+  
+    Point3f dir = r1 - r0;   // ray direction vector
+    Point3f w0 = r0 - t0;
+    float a = -n * w0;
+    float b = n * dir;
+    if(b == 0) {     // ray is parallel to triangle plane
+      if(a == 0)     // ray lies in triangle plane
+        return 2;
+      else
+        return 0;       // ray disjoint from plane
+    }
+  
+    // get intersect point of ray with triangle plane
+    float r = a / b;
+    if(r < 0.0f)    // ray goes away from triangle
+      return 0;     // => no intersect
+    // for a segment, also test if (r > 1.0) => no intersect
+  
+    intp = r0 + r * dir;   // intersect point of ray and plane
+  
+    // is intersect point inside the triangle?
+    float uu, uv, vv, wu, wv, d;
+    uu = u * u;
+    uv = u * v;
+    vv = v * v;
+    Point3f w = intp - t0;
+    wu = w * u;
+    wv = w * v;
+    d = uv * uv - uu * vv;
+  
+    // get and test parametric coords
+    float s, t;
+    s = (uv * wv - vv * wu) / d;
+    if(s < 0.0f || s > 1.0f)   // outside
+      return 0;
+    t = (uv * wu - uu * wv) / d;
+    if(t < 0.0f || (s + t) > 1.0f)   // outside
+      return 0;
+  
+    return 1;   // in
+  }
+  
+  // Return distance from a point to a line (or segment)
+  CU_HOST_DEVICE
+  float distLinePoint(Point3f v1, Point3f v2, Point3f p, bool segment)
+  {
+    v2 -= v1;
+    float n = norm(v2);
+    // Points are the same
+    if(n == 0)
+      return norm(p - v1);
+  
+    Point3f vn = v2 / n;
+    p -= v1;
+    Point3f q = vn * (p * vn);
+    float dist = norm(p - q);
+    if(!segment)
+      return dist;
+  
+    // Projected point on line segment
+    float qn = p * vn;
+    if(qn >= 0 and qn <= n)
+      return dist;
+  
+    // Otherwise pick closest endpoint
+    dist = norm(p);
+    float d = norm(p - v2);
+    if(d < dist)
+      dist = d;
+  
     return dist;
+  }
 
-  // Projected point on line segment
-  float qn = p * vn;
-  if(qn >= 0 and qn <= n)
-    return dist;
-
-  // Otherwise pick closest endpoint
-  dist = norm(p);
-  float d = norm(p - v2);
-  if(d < dist)
-    dist = d;
-
-  return dist;
 }
-} // namespace mgx
 #endif
Index: Vector.hpp
===================================================================
--- Vector.hpp	(revision 1255)
+++ Vector.hpp	(revision 1256)
@@ -173,7 +173,7 @@
   }
 
   /**
-   * Initialize a 6D vector
+   * Initialize a 7D vector
    */
   CU_HOST_DEVICE
   Vector(const T& x, const T& y, const T& z, const T& a, const T& b, const T& c, const T& d)
Index: SystemProcessLoad.hpp
===================================================================
--- SystemProcessLoad.hpp	(revision 1255)
+++ SystemProcessLoad.hpp	(revision 1256)
@@ -17,608 +17,505 @@
 class QFile;
 class QIODevice;
 
-namespace mgx {
-namespace process {
-/**
- * This function creates a graph from a triangle soup.
- *
- * \note The graph will not be cleared, the triangles will be added to the
- * graph.
- *
- * \param S Graph that will be updated.
- * \param vertices List of vertices to insert in S
- * \param triangles List of triplet of indices in \c vertices defining
- * triangles
- *
- * \returns true on success, false on failure
- *
- * \ingroup ProcessUtils
- */
-MGX_EXPORT bool meshFromTriangles(vvgraph& S, std::vector<vertex>& vertices,
-                                  std::vector<Point3i>& triangles);
-
-MGX_EXPORT QList<int> extractVersion(QIODevice& file);
-
-/**
- * \class StackSwapBytes SystemProcessLoad.hpp <SystemProcessLoad.hpp>
- *
- * Process that swap bytes
- *
- * \ingroup StackProcess
- */
-class MGX_EXPORT StackSwapBytes : public StackProcess {
-public:
-  StackSwapBytes(const StackProcess& process)
-    : Process(process)
-    , StackProcess(process)
-  {
-  }
-
-  bool operator()(const QStringList&)
-  {
-    if(!checkState().store(STORE_NON_EMPTY))
-      return false;
-    Store* input = currentStack()->currentStore();
-    Store* output = currentStack()->work();
-    bool res = (*this)(input, output);
-    if(res) {
-      input->hide();
-      output->show();
+namespace mgx { namespace process {
+  /**
+   * This function creates a graph from a triangle soup.
+   *
+   * \note The graph will not be cleared, the triangles will be added to the
+   * graph.
+   *
+   * \param S Graph that will be updated.
+   * \param vertices List of vertices to insert in S
+   * \param triangles List of triplet of indices in \c vertices defining
+   * triangles
+   *
+   * \returns true on success, false on failure
+   *
+   * \ingroup ProcessUtils
+   */
+  MGX_EXPORT bool meshFromTriangles(vvgraph& S, std::vector<vertex>& vertices,
+                                    std::vector<Point3i>& triangles);
+  
+  MGX_EXPORT QList<int> extractVersion(QIODevice& file);
+  
+  /**
+   * \class StackSwapBytes SystemProcessLoad.hpp <SystemProcessLoad.hpp>
+   *
+   * Process that swap bytes
+   *
+   * \ingroup StackProcess
+   */
+  class MGX_EXPORT StackSwapBytes : public StackProcess {
+  public:
+    StackSwapBytes(const StackProcess& process) : Process(process), StackProcess(process) {}
+  
+    bool operator()(const QStringList&)
+    {
+      if(!checkState().store(STORE_NON_EMPTY))
+        return false;
+      Store* input = currentStack()->currentStore();
+      Store* output = currentStack()->work();
+      bool res = (*this)(input, output);
+      if(res) {
+        input->hide();
+        output->show();
+      }
+      return res;
     }
-    return res;
-  }
-
-  bool operator()(const Store* input, Store* output);
-
-  QString name() const {
-    return "Swap Bytes";
-  }
-  QString description() const {
-    return "Swap the bytes of the values in the stack.";
-  }
-  QString folder() const {
-    return "Filters";
-  }
-  QStringList parmNames() const {
-    return QStringList();
-  }
-  QStringList parmDescs() const {
-    return QStringList();
-  }
-  QIcon icon() const {
-    return QIcon(":/images/SwapBytes.png");
-  }
-};
-
-/**
- * \class StackImport SystemProcessLoad.hpp <SystemProcessLoad.hpp>
- *
- * Import images forming a stack.
- *
- * \ingroup StackProcess
- */
-class MGX_EXPORT StackImport : public QObject, public StackProcess {
-  Q_OBJECT
-public:
-  StackImport(const StackProcess& proc)
-    : Process(proc)
-    , QObject()
-    , StackProcess(proc)
-  {
-  }
-
-  bool initialize(QStringList& parms, QWidget* parent);
-
-  bool operator()(const QStringList& parms)
-  {
-    int stackId = parms[0].toInt();
-    QString storeName = parms[1];
-    Point3f step(parms[2].toFloat(), parms[3].toFloat(), parms[4].toFloat());
-    float brightness(parms[5].toFloat());
-    QString filename(parms[6]);
-
-    // Get stack and store
-    Stack* stk = currentStack();
-    if(stackId != -1)
-      stk = stack(parms[0].toInt());
-    if(!checkState().stack(STACK_ANY, stackId))
-      return false;
-
-    Store* store = stk->currentStore();
-    if(storeName == "Main")
-      store = stk->main();
-    else if(storeName == "Work")
-      store = stk->work();
-
-    return (*this)(stk, store, step, brightness, filename);
-  }
+  
+    bool operator()(const Store* input, Store* output);
+  
+    QString name() const { return "Swap Bytes"; }
+    QString description() const { return "Swap the bytes of the values in the stack."; }
+    QString folder() const { return "Filters"; }
+    QStringList parmNames() const { return QStringList(); }
+    QStringList parmDescs() const { return QStringList(); }
+    QIcon icon() const { return QIcon(":/images/SwapBytes.png"); }
+  };
+  
   /**
-   * Import the stack
-   * \param stack Stack that will contain the image
-   * \param store Store that will contain the image
-   * \param filenames Either a single text file containing all the
-   * parameters, or a list of image files, one per z slice
-   * \param brightness Multiplication coefficient to convert less than 16
-   * bits images to 16 bits
-   * \param step Size of a voxel
+   * \class StackImport SystemProcessLoad.hpp <SystemProcessLoad.hpp>
+   *
+   * Import images forming a stack.
+   *
+   * \ingroup StackProcess
    */
-  bool operator()(Stack* stack, Store* store, Point3f step, float brightness, QString filename);
-
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Import";
-  }
-  QString description() const {
-    return "Import stack from a series of images";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Stack"
-                         << "Store"
-                         << "X Step"
-                         << "Y Step"
-                         << "Z Step"
-                         << "Brightness"
-                         << "Profile File";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Stack"
-                         << "Store"
-                         << "X Step"
-                         << "Y Step"
-                         << "Z Step"
-                         << "Brightness"
-                         << "Profile File";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << "-1"
-                         << "Current"
-                         << "1.0"
-                         << "1.0"
-                         << "1.0"
-                         << "1.0"
-                         << "";
-  }
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[1] << "Main"
-           << "Work"
-           << "Current";
-    return map;
-  }
-  QIcon icon() const {
-    return QIcon(":/images/open.png");
-  }
-
-protected slots:
-  void SaveProfile();
-  void LoadProfile(QString filename = QString());
-  void AddFilesSlot();
-  void AddFilesSlot(const QStringList& files);
-  void RemoveFilesSlot();
-  void FilterFilesSlot();
-  void SortAscendingSlot(bool val = true);
-  void SortDescendingSlot();
-
-protected:
-  bool LoadProfile(QString filename, Point3u& size, Point3f& step, float& brightness, QStringList& files);
-  void setImageSize(Point3u size);
-  void setImageSize(uint x, uint y, uint z) {
-    setImageSize(Point3u(x, y, z));
-  }
-  void setImageResolution(Point3f step);
-  void setImageResolution(float x, float y, float z) {
-    setImageResolution(Point3f(x, y, z));
-  }
-  Point3f imageResolution();
-
-  QString txtFile;
-  QDialog* dlg;
-  Ui_LoadStackDialog* ui;
-  QString loadedFile;
-  Point3u imageSize;
-  QStringList imageFiles;
-};
-
-/**
- * \class StackOpen SystemProcessLoad.hpp <SystemProcessLoad.hpp>
- *
- * Open a stack in either the MGXS or INRIA formats.
- *
- * \ingroup StackProcess
- */
-class MGX_EXPORT StackOpen : public StackProcess {
-public:
-  StackOpen(const StackProcess& proc)
-    : Process(proc)
-    , StackProcess(proc)
-  {
-  }
-
-  bool operator()(const QStringList& parms);
+  class MGX_EXPORT StackImport : public QObject, public StackProcess {
+    Q_OBJECT
+  public:
+    StackImport(const StackProcess& proc) : Process(proc), QObject(), StackProcess(proc) {}
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    bool operator()(const QStringList& parms)
+    {
+      int stackId = parms[0].toInt();
+      QString storeName = parms[1];
+      Point3f step(parms[2].toFloat(), parms[3].toFloat(), parms[4].toFloat());
+      float brightness(parms[5].toFloat());
+      QString filename(parms[6]);
+  
+      // Get stack and store
+      Stack* stk = currentStack();
+      if(stackId != -1)
+        stk = stack(parms[0].toInt());
+      if(!checkState().stack(STACK_ANY, stackId))
+        return false;
+  
+      Store* store = stk->currentStore();
+      if(storeName == "Main")
+        store = stk->main();
+      else if(storeName == "Work")
+        store = stk->work();
+  
+      return (*this)(stk, store, step, brightness, filename);
+    }
+    /**
+     * Import the stack
+     * \param stack Stack that will contain the image
+     * \param store Store that will contain the image
+     * \param filenames Either a single text file containing all the
+     * parameters, or a list of image files, one per z slice
+     * \param brightness Multiplication coefficient to convert less than 16
+     * bits images to 16 bits
+     * \param step Size of a voxel
+     */
+    bool operator()(Stack* stack, Store* store, Point3f step, float brightness, QString filename);
+  
+    QString folder() const { return "System"; }
+    QString name() const { return "Import"; }
+    QString description() const { return "Import stack from a series of images"; }
+    QStringList parmNames() const { return QStringList() 
+      << "Stack" << "Store" << "X Step" << "Y Step" << "Z Step" << "Brightness" << "Profile File"; }
+    QStringList parmDescs() const { return QStringList() 
+      << "Stack" << "Store" << "X Step" << "Y Step" << "Z Step" << "Brightness" << "Profile File"; }
+    QStringList parmDefaults() const { return QStringList() 
+      << "-1" << "Current" << "1.0" << "1.0" << "1.0" << "1.0" << ""; }
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[1] << "Main" << "Work" << "Current";
+      return map;
+    }
+    QIcon icon() const { return QIcon(":/images/open.png"); }
+  
+  protected slots:
+    void SaveProfile();
+    void LoadProfile(QString filename = QString());
+    void AddFilesSlot();
+    void AddFilesSlot(const QStringList& files);
+    void RemoveFilesSlot();
+    void FilterFilesSlot();
+    void SortAscendingSlot(bool val = true);
+    void SortDescendingSlot();
+  
+  protected:
+    bool LoadProfile(QString filename, Point3u& size, Point3f& step, float& brightness, QStringList& files);
+    void setImageSize(Point3u size);
+    void setImageSize(uint x, uint y, uint z) {
+      setImageSize(Point3u(x, y, z));
+    }
+    void setImageResolution(Point3f step);
+    void setImageResolution(float x, float y, float z) {
+      setImageResolution(Point3f(x, y, z));
+    }
+    Point3f imageResolution();
+  
+    QString txtFile;
+    QDialog* dlg;
+    Ui_LoadStackDialog* ui;
+    QString loadedFile;
+    Point3u imageSize;
+    QStringList imageFiles;
+  };
+  
   /**
-   * Open the image
-   * \param stack Stack that will contain the image
-   * \param store Store that will contain the image
-   * \param filename File containing the image.
+   * \class StackOpen SystemProcessLoad.hpp <SystemProcessLoad.hpp>
+   *
+   * Open a stack in either the MGXS or INRIA formats.
+   *
+   * \ingroup StackProcess
    */
-  bool operator()(Stack* stack, Store* store, QString filename);
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Open";
-  }
-  QString description() const {
-    return "Open a stack from a known 3D image format";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Filename"
-                         << "Store"
-                         << "Stack number";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Filename"
-                         << "Store"
-                         << "Stack number";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << ""
-                         << "Main"
-                         << "0";
-  }
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[1] = storeChoice();
-    return map;
-  }
-  bool initialize(QStringList& parms, QWidget* parent);
-  QIcon icon() const {
-    return QIcon(":/images/open.png");
-  }
-
-  bool loadMGXS_1_3(QIODevice& file, Stack* stack, Store* store);
-  bool loadMGXS_1_2(QIODevice& file, Stack* stack, Store* store);
-  bool loadMGXS_1_1(QIODevice& file, Stack* stack, Store* store);
-  bool loadMGXS_1_0(QIODevice& file, Stack* stack, Store* store);
-  bool loadMGXS_0(QIODevice& file, Stack* stack, Store* store);
-  void centerImage();
-};
-
-/**
- * \class MeshLoad SystemProcessLoad.hpp <SystemProcessLoad.hpp>
- *
- * Load a MGXM mesh file.
- *
- * \ingroup MeshProcess
- */
-class MGX_EXPORT MeshLoad : public QObject, public MeshProcess {
-  Q_OBJECT
-public:
-  MeshLoad(const MeshProcess& proc)
-    : Process(proc)
-    , QObject()
-    , MeshProcess(proc)
-  {
-  }
-
-  bool operator()(const QStringList& parms);
+  class MGX_EXPORT StackOpen : public StackProcess {
+  public:
+    StackOpen(const StackProcess& proc) : Process(proc), StackProcess(proc) {}
+  
+    bool operator()(const QStringList& parms);
+    /**
+     * Open the image
+     * \param stack Stack that will contain the image
+     * \param store Store that will contain the image
+     * \param filename File containing the image.
+     */
+    bool operator()(Stack* stack, Store* store, QString filename);
+    QString folder() const { return "System"; }
+    QString name() const { return "Open"; }
+    QString description() const { return "Open a stack from a known 3D image format"; }
+    QStringList parmNames() const { return QStringList() << "Filename" << "Store" << "Stack number"; }
+    QStringList parmDescs() const { return QStringList() << "Filename" << "Store" << "Stack number"; }
+    QStringList parmDefaults() const { return QStringList() << "" << "Main" << "0"; }
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[1] = storeChoice();
+      return map;
+    }
+    bool initialize(QStringList& parms, QWidget* parent);
+    QIcon icon() const { return QIcon(":/images/open.png"); }
+  
+    bool loadMGXS_1_3(QIODevice& file, Stack* stack, Store* store);
+    bool loadMGXS_1_2(QIODevice& file, Stack* stack, Store* store);
+    bool loadMGXS_1_1(QIODevice& file, Stack* stack, Store* store);
+    bool loadMGXS_1_0(QIODevice& file, Stack* stack, Store* store);
+    bool loadMGXS_0(QIODevice& file, Stack* stack, Store* store);
+    void centerImage();
+  };
+  
   /**
-   * Load a MGXM file
-   * \param mesh Mesh that will contain the data
-   * \param filename File containing the mesh.
-   * \param scale If true, the mesh will be scaled according to the current
-   * scale factor
-   * \param transform If true, the mesh will be transformed according to
-   * the current transformation frame
-   * \param add If true, the mesh will be added to the current one instead
-   * of replacing it.
+   * \class MeshLoad SystemProcessLoad.hpp <SystemProcessLoad.hpp>
+   *
+   * Load a MGXM mesh file.
+   *
+   * \ingroup MeshProcess
    */
-  bool operator()(Mesh* mesh, QString filename, bool transform, bool add);
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Load";
-  }
-  QString description() const {
-    return "Load a mesh from one of the known formats.";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Filename"
-                         << "Transform"
-                         << "Add"
-                         << "Stack number";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Filename"
-                         << "Transform"
-                         << "Add"
-                         << "Stack number";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << ""
-                         << "no"
-                         << "no"
-                         << "0";
-  }
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[1] = map[2] = booleanChoice();
-    return map;
-  }
-  bool initialize(QStringList& parms, QWidget* parent);
-  QIcon icon() const {
-    return QIcon(":/images/open.png");
-  }
+  class MGX_EXPORT MeshLoad : public QObject, public MeshProcess {
+    Q_OBJECT
+  public:
+    MeshLoad(const MeshProcess& proc) : Process(proc), QObject(), MeshProcess(proc) {}
+  
+    bool operator()(const QStringList& parms);
+    /**
+     * Load a MGXM file
+     * \param mesh Mesh that will contain the data
+     * \param filename File containing the mesh.
+     * \param scale If true, the mesh will be scaled according to the current
+     * scale factor
+     * \param transform If true, the mesh will be transformed according to
+     * the current transformation frame
+     * \param add If true, the mesh will be added to the current one instead
+     * of replacing it.
+     */
+    bool operator()(Mesh* mesh, QString filename, bool transform, bool add);
+    QString folder() const { return "System"; }
+    QString name() const { return "Load"; }
+    QString description() const { return "Load a mesh from one of the known formats."; }
+    QStringList parmNames() const { return QStringList() 
+      << "Filename" << "Transform" << "Add" << "Stack number"; }
+    QStringList parmDescs() const { return QStringList() 
+      << "Filename" << "Transform" << "Add" << "Stack number"; }
+    QStringList parmDefaults() const { return QStringList() 
+      << "" << "no" << "no" << "0"; }
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[1] = map[2] = booleanChoice();
+      return map;
+    }
+    bool initialize(QStringList& parms, QWidget* parent);
+    QIcon icon() const { return QIcon(":/images/open.png"); }
+  
+    bool loadMGXM_0(QIODevice& file, Mesh* mesh, bool scale, bool transform, bool add, bool has_color = true);
+    bool loadMGXM_1_0(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add, bool has_color = true);
+    bool loadMGXM_1_1(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add, bool has_color = true);
+    bool loadMGXM_1_2(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add, bool has_color = true);
+    bool loadMGXM_1_3(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add);
+  
+    void findSignalBounds(Mesh* mesh);
+  
+  protected slots:
+    void selectMeshFile();
+  
+  protected:
+    void setMeshFile(const QString& filename);
+  
+    QDialog* dlg;
+    Ui_LoadMeshDialog* ui;
+  };
+  
+  /**
+   * \class MeshImport SystemProcessLoad.hpp <SystemProcessLoad.hpp>
+   *
+   * Import a mesh from a file of another format
+   *
+   * \ingroup MeshProcess
+   */
+  class MGX_EXPORT MeshImport : public QObject, public MeshProcess {
+    Q_OBJECT
+  
+  public:
+    MeshImport(const MeshProcess& proc) : Process(proc), QObject(), MeshProcess(proc) {}
+  
+    bool operator()(const QStringList& parms);
+    /**
+     * Import a mesh
+     * \param mesh Mesh that will contain the data
+     * \param filename File describing the mesh
+     * \param type Type of the file. Must be one of 'Text', 'Cells', 'Keyence' or 'MeshEdit', or empty (i.e.
+     * auto-detect)
+     * \param scale If true, the mesh will be scaled
+     * \param transform If true, the mesh will be transformed
+     * \param add If true, the mesh won't be cleared before loading the file
+     *
+     * \sa MeshOpen
+     */
+    bool initialize(QStringList& parms, QWidget* parent);
 
-  bool loadMGXM_0(QIODevice& file, Mesh* mesh, bool scale, bool transform, bool add, bool has_color = true);
-  bool loadMGXM_1_0(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add, bool has_color = true);
-  bool loadMGXM_1_1(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add, bool has_color = true);
-  bool loadMGXM_1_2(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add, bool has_color = true);
-  bool loadMGXM_1_3(QIODevice& file, Mesh* mesh, bool& scale, bool& transform, bool add);
+    bool operator()(Mesh* mesh, QString filename, QString type, bool scale, bool transform, bool add);
 
-  void findSignalBounds(Mesh* mesh);
-
-protected slots:
-  void selectMeshFile();
-
-protected:
-  void setMeshFile(const QString& filename);
-
-  QDialog* dlg;
-  Ui_LoadMeshDialog* ui;
-};
-
-/**
- * \class MeshImport SystemProcessLoad.hpp <SystemProcessLoad.hpp>
- *
- * Import a mesh from a file of another format
- *
- * \ingroup MeshProcess
- */
-class MGX_EXPORT MeshImport : public QObject, public MeshProcess {
-  Q_OBJECT
-
-public:
-  MeshImport(const MeshProcess& proc)
-    : Process(proc)
-    , QObject()
-    , MeshProcess(proc)
-  {
-  }
-
-  bool operator()(const QStringList& parms);
+    QString folder() const { return "System"; }
+    QString name() const { return "Import"; }
+    QString description() const { return "Import a mesh from one of the known formats."; }
+    QStringList parmNames() const { return QStringList() 
+      << "Filename" << "Kind" << "Scale" << "Transform" << "Add" << "Stack number"; }
+    QStringList parmDescs() const { return QStringList() 
+      << "Filename" << "Kind" << "Scale" << "Transform" << "Add" << "Stack number"; }
+    QStringList parmDefaults() const { return QStringList() 
+      << "" << "PLY" << "yes" << "no" << "no" << "0"; }
+    ParmChoiceMap parmChoice() const
+    {
+      ParmChoiceMap map;
+      map[1] = QStringList() << "VTK Mesh" << "Text" << "Cells" << "Keyence" << "MeshEdit";
+      map[2] = map[3] = map[4] = booleanChoice();
+      return map;
+    }
+    QIcon icon() const { return QIcon(":/images/open.png"); }
+  
+  protected slots:
+    void selectMeshFile();
+    void selectMeshType(const QString& type);
+  
+  protected:
+    void setMeshFile(const QString& filename, const QString& type = QString());
+    QString properFile(QString filename, const QString& type) const;
+  
+    bool loadText(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add);
+    bool loadCells(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add);
+    bool loadKeyence(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add);
+    bool loadMeshEdit(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add);
+    bool loadMeshVTK(Mesh* mesh, const QString& filename, bool& scale, bool transform, bool add);
+    bool loadMeshOBJ(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add);
+    bool loadMeshPLY(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add);
+  
+    QDialog* dlg;
+    Ui_ImportMeshDialog* ui;
+  };
+  
   /**
-   * Import a mesh
-   * \param mesh Mesh that will contain the data
-   * \param filename File describing the mesh
-   * \param type Type of the file. Must be one of 'Text', 'Cells', 'Keyence' or 'MeshEdit', or empty (i.e.
-   * auto-detect)
-   * \param scale If true, the mesh will be scaled
-   * \param transform If true, the mesh will be transformed
-   * \param add If true, the mesh won't be cleared before loading the file
+   * \class LoadAllData SystemProcessLoad.hpp <SystemProcessLoad.hpp>
    *
-   * \sa MeshOpen
+   * Load all the files as specified in the various objects (filenames).
+   *
+   * Note that currently, it will load only the main store of the stacks as
+   * only they can have any data.
+   *
+   * \ingroup GlobalProcess
    */
-  bool operator()(Mesh* mesh, QString filename, QString type, bool scale, bool transform, bool add);
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Import";
-  }
-  QString description() const {
-    return "Import a mesh from one of the known formats.";
-  }
-  QStringList parmNames() const
-  {
-    return QStringList() << "Filename"
-                         << "Kind"
-                         << "Scale"
-                         << "Transform"
-                         << "Add"
-                         << "Stack number";
-  }
-  QStringList parmDescs() const
-  {
-    return QStringList() << "Filename"
-                         << "Kind"
-                         << "Scale"
-                         << "Transform"
-                         << "Add"
-                         << "Stack number";
-  }
-  QStringList parmDefaults() const
-  {
-    return QStringList() << ""
-                         << "PLY"
-                         << "yes"
-                         << "no"
-                         << "no"
-                         << "0";
-  }
-  ParmChoiceMap parmChoice() const
-  {
-    ParmChoiceMap map;
-    map[1] = QStringList() << "VTK Mesh"
-                           << "Text"
-                           << "Cells"
-                           << "Keyence"
-                           << "MeshEdit";
-    map[2] = map[3] = map[4] = booleanChoice();
-    return map;
-  }
-  bool initialize(QStringList& parms, QWidget* parent);
-  QIcon icon() const {
-    return QIcon(":/images/open.png");
-  }
+  class MGX_EXPORT LoadAllData : public GlobalProcess {
+  public:
+    LoadAllData(const GlobalProcess& proc) : Process(proc), GlobalProcess(proc) {}
+  
+    bool operator()(const QStringList&);
+    bool operator()();
+  
+    QString folder() const { return "System"; }
+    QString name() const { return "Load All"; }
+    QString description() const { return 
+      "Load the data for all existing objects, using the filename and properties set in them."; }
+    QStringList parmNames() const { return QStringList(); }
+    QStringList parmDescs() const { return QStringList(); }
+    QIcon icon() const { return QIcon(":/images/open.png"); }
+  
+  protected:
+    bool loadStore(Stack* stack, Store* store, QStringList& errors);
+  };
+  
+  /**
+   * \class LoadViewFile SystemProcessLoad.hpp <SystemProcessLoad.hpp>
+   * Load a view file and all the associated files.
+   *
+   * \ingroup GlobalProcess
+   */
+  class MGX_EXPORT LoadViewFile : public GlobalProcess {
+  public:
+    LoadViewFile(const GlobalProcess& proc) : Process(proc), GlobalProcess(proc) {}
+  
+    bool operator()(const QStringList& parms);
+    /**
+     * Load the file \c filename
+     */
+    bool operator()(QString filename);
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    QString folder() const { return "System"; }
+    QString name() const { return "Load View"; }
+    QString description() const { return 
+      "Load a view file and set all the fields and interface. Does not load the data though."; }
+    QStringList parmNames() const { return QStringList() << "Filename"; }
+    QStringList parmDescs() const { return QStringList() << "Filename"; }
+    QStringList parmDefaults() const { return QStringList() << ""; }
+    QIcon icon() const { return QIcon(":/images/open.png"); }
+  };
+  
+  /**
+   * \class ResetMeshProcess SystemProcessLoad.hpp <SystemProcessLoad.hpp>
+   *
+   * Reset a mesh
+   *
+   * \ingroup MeshProcess
+   */
+  class MGX_EXPORT ResetMeshProcess : public MeshProcess {
+  public:
+    ResetMeshProcess(const MeshProcess& proc) : Process(proc), MeshProcess(proc) {}
+  
+    bool operator()(const QStringList& parms);
+    bool operator()(Mesh* m);
+  
+    QString folder() const { return "System"; }
+    QString name() const { return "Reset"; }
+    QString description() const { return "Reset a mesh, -1 for current."; }
+    QStringList parmNames() const { return QStringList() << "Mesh"; }
+    QStringList parmDescs() const { return QStringList() << "Mesh"; }
+    QStringList parmDefaults() const { return QStringList() << "-1"; }
+    QIcon icon() const { return QIcon(":/images/ClearStack.png"); }
+  };
 
-protected slots:
-  void selectMeshFile();
-  void selectMeshType(const QString& type);
-
-protected:
-  void setMeshFile(const QString& filename, const QString& type = QString());
-  QString properFile(QString filename, const QString& type) const;
-
-  bool loadText(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add);
-  bool loadCells(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add);
-  bool loadKeyence(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add);
-  bool loadMeshEdit(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add);
-  bool loadMeshVTK(Mesh* mesh, const QString& filename, bool& scale, bool transform, bool add);
-  bool loadMeshOBJ(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add);
-  bool loadMeshPLY(Mesh* mesh, const QString& filename, bool scale, bool transform, bool add);
-
-  QDialog* dlg;
-  Ui_ImportMeshDialog* ui;
-};
-
-/**
- * \class LoadAllData SystemProcessLoad.hpp <SystemProcessLoad.hpp>
- *
- * Load all the files as specified in the various objects (filenames).
- *
- * Note that currently, it will load only the main store of the stacks as
- * only they can have any data.
- *
- * \ingroup GlobalProcess
- */
-class MGX_EXPORT LoadAllData : public GlobalProcess {
-public:
-  LoadAllData(const GlobalProcess& proc)
-    : Process(proc)
-    , GlobalProcess(proc)
-  {
-  }
-
-  bool operator()(const QStringList&);
-  bool operator()();
-
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Load All";
-  }
-  QString description() const
-  {
-    return "Load the data for all existing objects, using the filename and properties set in them.";
-  }
-  QStringList parmNames() const {
-    return QStringList();
-  }
-  QStringList parmDescs() const {
-    return QStringList();
-  }
-  QIcon icon() const {
-    return QIcon(":/images/open.png");
-  }
-
-protected:
-  bool loadStore(Stack* stack, Store* store, QStringList& errors);
-};
-
-/**
- * \class LoadViewFile SystemProcessLoad.hpp <SystemProcessLoad.hpp>
- * Load a view file and all the associated files.
- *
- * \ingroup GlobalProcess
- */
-class MGX_EXPORT LoadViewFile : public GlobalProcess {
-public:
-  LoadViewFile(const GlobalProcess& proc)
-    : Process(proc)
-    , GlobalProcess(proc)
-  {
-  }
-
-  bool operator()(const QStringList& parms);
   /**
-   * Load the file \c filename
+   * \class SaveParents MeshProcessLineage.hpp <MeshProcessLineage.hpp>
+   *
+   * Save mapping from labels to parents
+   *
+   * \ingroup MeshProcess
    */
-  bool operator()(QString filename);
+  class MGX_EXPORT SaveParents : public MeshProcess {
+  public:
+    SaveParents(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_ANY))
+        return false;
+      Mesh* m = currentMesh();
+      return (*this)(m, parms[0]);
+    }
+  
+    bool operator()(Mesh* mesh, const QString& filename);
+  
+    QString folder() const { return "Lineage Tracking"; }
+    QString name() const { return "Save Parents"; }
+    QString description() const { return "Save map of labels to parents labels to a file"; }
+    QStringList parmNames() const { return QStringList() << "Filename"; }
+    QStringList parmDescs() const { return QStringList() << "Path to spreadsheet file."; }
+    QStringList parmDefaults() const { return QStringList() << ""; }
+    QIcon icon() const { return QIcon(":/images/ParentsSave.png"); }
+  };
+  
+  /**
+   * \class LoadParents MeshProcessLineage.hpp <MeshProcessLineage.hpp>
+   *
+   * Load mapping from labels to parents
+   *
+   * \ingroup MeshProcess
+   */
+  class MGX_EXPORT LoadParents : public MeshProcess {
+  public:
+    LoadParents(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool initialize(QStringList& parms, QWidget* parent);
+  
+    bool operator()(const QStringList& parms)
+    {
+      if(!checkState().mesh(MESH_ANY))
+        return false;
+      Mesh* m = currentMesh();
+      bool res = (*this)(m, parms[0]);
+      if(res)
+        m->showParent();
+      return res;
+    }
+  
+    bool operator()(Mesh* mesh, const QString& filename);
+  
+    QString folder() const { return "Lineage Tracking"; }
+    QString name() const { return "Load Parents"; }
+    QString description() const { return "Load map of labels to parents from a file"; }
+    QStringList parmNames() const { return QStringList() << "Filename"; }
+    QStringList parmDescs() const { return QStringList() << "Path to spreadsheet file."; }
+    QStringList parmDefaults() const { return QStringList() << ""; }
+    QIcon icon() const { return QIcon(":/images/ParentsOpen.png"); }
+  };
+  
+  /**
+   * \class ResetParents MeshProcessLineage.hpp <MeshProcessLineage.hpp>
+   *
+   * Clear label to parent mapping
+   *
+   * \ingroup MeshProcess
+   */
+  class MGX_EXPORT ResetParents : public MeshProcess {
+  public:
+    ResetParents(const MeshProcess& process) : Process(process), MeshProcess(process) {}
+  
+    bool operator()(const QStringList& )
+    {
+      if(!checkState().mesh(MESH_ANY))
+        return false;
+      Mesh* m = currentMesh();
+      return (*this)(m);
+    }
+  
+    bool operator()(Mesh* mesh);
+  
+    QString folder() const { return "Lineage Tracking"; }
+    QString name() const { return "Reset Parents"; }
+    QString description() const { return "Clear mapping from parents to labels"; }
+    QStringList parmNames() const { return QStringList(); }
+    QStringList parmDescs() const { return QStringList(); }
+    QIcon icon() const { return QIcon(":/images/ParentsClear.png"); }
+  };
 
-  bool initialize(QStringList& parms, QWidget* parent);
+}}
 
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Load View";
-  }
-  QString description() const
-  {
-    return "Load a view file and set all the fields and interface. Does not load the data though.";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Filename";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Filename";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/open.png");
-  }
-};
-
-/**
- * \class ResetMeshProcess SystemProcessLoad.hpp <SystemProcessLoad.hpp>
- *
- * Reset a mesh
- *
- * \ingroup MeshProcess
- */
-class MGX_EXPORT ResetMeshProcess : public MeshProcess {
-public:
-  ResetMeshProcess(const MeshProcess& proc)
-    : Process(proc)
-    , MeshProcess(proc)
-  {
-  }
-
-  bool operator()(const QStringList& parms);
-  bool operator()(Mesh* m);
-
-  QString folder() const {
-    return "System";
-  }
-  QString name() const {
-    return "Reset";
-  }
-  QString description() const {
-    return "Reset a mesh, -1 for current.";
-  }
-  QStringList parmNames() const {
-    return QStringList() << "Mesh";
-  }
-  QStringList parmDescs() const {
-    return QStringList() << "Mesh";
-  }
-  QStringList parmDefaults() const {
-    return QStringList() << "-1";
-  }
-  QIcon icon() const {
-    return QIcon(":/images/ClearStack.png");
-  }
-};
-} // namespace process
-} // namespace mgx
-
 #endif
Index: Mesh.cpp
===================================================================
--- Mesh.cpp	(revision 1255)
+++ Mesh.cpp	(revision 1256)
@@ -10,677 +10,689 @@
 #include "Dir.hpp"
 
 namespace mgx {
-
-Mesh::Mesh(const Stack* stack)
-  : _id(-1)
-  , _stack(stack)
-{
-  init();
-}
-
-Mesh::Mesh(int id, const Stack* stack)
-  : _id(id)
-  , _stack(stack)
-{
-  init();
-}
-
-void Mesh::setStack(const Stack* s) {
-  _stack = s;
-}
-
-void Mesh::init()
-{
-  changed_surf_function = false;
-  changed_heat_function = false;
-  changed_label = false;
-  _changed = 0;
-  _show = NORMAL;
-  _color = SIGNAL;
-  _culling = true;
-  _blending = true;
-  _isSurfaceVisible = false;
-  _isMeshVisible = false;
-  _currLabel = 0;
-  _opacity = 1.0f;
-  _brightness = 1.0f;
-  _meshView = SELECTED_MESH;
-  _showMeshLines = false;
-  _showMeshPoints = false;
-  _showMeshCellMap = false;
-  _cells = false;
-  _imgtex = false;
-  _scaled = false;
-  _transformed = false;
-  _showBBox = false;
-  _cellAxisOffset = 0;
-  _cellAxisWidth = 1;
-}
-
-Mesh::~Mesh() {
-}
-
-void Mesh::updateAll() {
-  _changed = ImgData::RELOAD_VBO;
-}
-
-void Mesh::updateTriangles() {
-  _changed |= ImgData::RELOAD_TRIS;
-}
-
-void Mesh::updateLines() {
-  _changed |= ImgData::RELOAD_LINES;
-}
-
-void Mesh::updatePositions() {
-  _changed |= ImgData::RELOAD_POS;
-}
-
-void Mesh::updateSelection() {
-  _changed |= ImgData::UPDATE_SELECTION;
-}
-
-void Mesh::updateWallGeometry(float borderSize)
-{
-  // First, mark the borders
-  markBorder(borderSize);
-
-  _labelNeighbors.clear();
-  _wallVId.clear();
-  _wallGeom.clear();
-
-  forall(const vertex& v, S) {
-    if(v->label != -1)
-      continue;
-    forall(const vertex& n, S.neighbors(v)) {
-      if(n->label != -1 or n > v)
+  
+  Mesh::Mesh(const Stack* stack) : _id(-1), _stack(stack)
+  {
+    init();
+  }
+  
+  Mesh::Mesh(int id, const Stack* stack) : _id(id), _stack(stack)
+  {
+    init();
+  }
+  
+  void Mesh::setStack(const Stack* s) {
+    _stack = s;
+  }
+  
+  void Mesh::init()
+  {
+    changed_surf_function = false;
+    changed_heat_function = false;
+    changed_label = false;
+    _changed = 0;
+    _show = NORMAL;
+    _color = SIGNAL;
+    _culling = true;
+    _blending = true;
+    _isSurfaceVisible = false;
+    _isMeshVisible = false;
+    _currLabel = 0;
+    _opacity = 1.0f;
+    _brightness = 1.0f;
+    _meshView = SELECTED_MESH;
+    _showMeshLines = false;
+    _showMeshPoints = false;
+    _showMeshCellMap = false;
+    _cells = false;
+    _imgtex = false;
+    _scaled = false;
+    _transformed = false;
+    _showBBox = false;
+    _cellAxisOffset = 0;
+    _cellAxisWidth = 1;
+  }
+  
+  Mesh::~Mesh() {}
+  
+  void Mesh::updateAll() 
+  {
+    _changed = ImgData::RELOAD_VBO;
+  }
+  
+  void Mesh::updateTriangles() 
+  {
+    _changed |= ImgData::RELOAD_TRIS;
+  }
+  
+  void Mesh::updateLines() 
+  {
+    _changed |= ImgData::RELOAD_LINES;
+  }
+  
+  void Mesh::updatePositions() 
+  {
+    _changed |= ImgData::RELOAD_POS;
+  }
+  
+  void Mesh::updateSelection() 
+  {
+    _changed |= ImgData::UPDATE_SELECTION;
+  }
+  
+  void Mesh::updateWallGeometry(float borderSize)
+  {
+    // First, mark the borders
+    markBorder(borderSize);
+  
+    _labelNeighbors.clear();
+    _wallVId.clear();
+    _wallGeom.clear();
+  
+    forall(const vertex& v, S) {
+      if(v->label != -1)
         continue;
-      IntSet Sv, Sn;
-      // Get list of neighbors for each vertex.
-      forall(const vertex& s, S.neighbors(v))
-        if(s->label != -1)
-          Sv.insert(s->label);
-      forall(const vertex& s, S.neighbors(n))
-        if(s->label != -1)
-          Sn.insert(s->label);
-      IntVec labelV;
-      forall(int lab, Sv)
-        if(Sn.find(lab) != Sn.end())
-          labelV.push_back(lab);
-      if(labelV.size() <= 1)
-        continue;
-      // Find wall length, add to neighbors array, and add vertices in wall to set
-      for(size_t i = 0; i < labelV.size() - 1; i++) {
-        IntIntPair wall;
-
-        wall = IntIntPair(labelV[i], labelV[i + 1]);
-        if(wall.first > 0) {
-          _wallGeom[wall] += (v->pos - n->pos).norm();
-          _labelNeighbors[wall.first].insert(wall.second);
-          _wallVId[wall].insert(v.id());
-          _wallVId[wall].insert(n.id());
+      forall(const vertex& n, S.neighbors(v)) {
+        if(n->label != -1 or n > v)
+          continue;
+        IntSet Sv, Sn;
+        // Get list of neighbors for each vertex.
+        forall(const vertex& s, S.neighbors(v))
+          if(s->label != -1)
+            Sv.insert(s->label);
+        forall(const vertex& s, S.neighbors(n))
+          if(s->label != -1)
+            Sn.insert(s->label);
+        IntVec labelV;
+        forall(int lab, Sv)
+          if(Sn.find(lab) != Sn.end())
+            labelV.push_back(lab);
+        if(labelV.size() <= 1)
+          continue;
+        // Find wall length, add to neighbors array, and add vertices in wall to set
+        for(size_t i = 0; i < labelV.size() - 1; i++) {
+          IntIntPair wall;
+  
+          wall = IntIntPair(labelV[i], labelV[i + 1]);
+          if(wall.first > 0) {
+            _wallGeom[wall] += (v->pos - n->pos).norm();
+            _labelNeighbors[wall.first].insert(wall.second);
+            _wallVId[wall].insert(v.id());
+            _wallVId[wall].insert(n.id());
+          }
+  
+          wall = IntIntPair(labelV[i + 1], labelV[i]);
+          if(wall.first > 0) {
+            _wallGeom[wall] += (v->pos - n->pos).norm();
+            _labelNeighbors[wall.first].insert(wall.second);
+            _wallVId[wall].insert(v.id());
+            _wallVId[wall].insert(n.id());
+          }
         }
-
-        wall = IntIntPair(labelV[i + 1], labelV[i]);
-        if(wall.first > 0) {
-          _wallGeom[wall] += (v->pos - n->pos).norm();
-          _labelNeighbors[wall.first].insert(wall.second);
-          _wallVId[wall].insert(v.id());
-          _wallVId[wall].insert(n.id());
-        }
       }
     }
   }
-}
-
-int Mesh::getLabel(vertex v1, vertex v2, vertex v3, bool useParentLabel) const
-{
-  if(!v1->label or !v2->label or !v3->label)
-    return 0;
-  if(v1->label < 0 and v2->label < 0 and v3->label < 0)
-    return -1;
-
-  int labcnt = 0, label = 0;
-  if(v1->label > 0) {
-    labcnt++;
-    label = v1->label;
-  }
-  if(v2->label > 0) {
-    if(v2->label != label) {
+  
+  int Mesh::getLabel(vertex v1, vertex v2, vertex v3, bool useParentLabel) const
+  {
+    if(!v1->label or !v2->label or !v3->label)
+      return 0;
+    if(v1->label < 0 and v2->label < 0 and v3->label < 0)
+      return -1;
+  
+    int labcnt = 0, label = 0;
+    if(v1->label > 0) {
       labcnt++;
-      label = v2->label;
+      label = v1->label;
     }
-  }
-  if(v3->label > 0) {
-    if(v3->label != label) {
-      labcnt++;
-      label = v3->label;
+    if(v2->label > 0) {
+      if(v2->label != label) {
+        labcnt++;
+        label = v2->label;
+      }
     }
-  }
-  if(labcnt != 1)
-    return 0;
-
-  if(useParentLabel and toShow() == Mesh::PARENT) {
-    IntIntMap::const_iterator i = parentLabelMap().find(label);
-    if(i == parentLabelMap().end())
+    if(v3->label > 0) {
+      if(v3->label != label) {
+        labcnt++;
+        label = v3->label;
+      }
+    }
+    if(labcnt != 1)
       return 0;
-    else
-      return i->second;
+  
+    if(useParentLabel and toShow() == Mesh::PARENT) {
+      IntIntMap::const_iterator i = parentLabelMap().find(label);
+      if(i == parentLabelMap().end())
+        return 0;
+      else
+        return i->second;
+    }
+    return label;
   }
-  return label;
-}
-
-bool Mesh::isBordTriangle(int label, vertex v, vertex n, vertex m, IntIntPair& wall) const
-{
-  if(_wallVId.empty() or v->minb == 0 or n->minb == 0 or m->minb == 0)
-    return (false);
-
-  // Search through neighbor list and sum signal and area
-  IntIntSetMap::const_iterator found = _labelNeighbors.find(label);
-  if(found == _labelNeighbors.end())
+  
+  bool Mesh::isBordTriangle(int label, vertex v, vertex n, vertex m, IntIntPair& wall) const
+  {
+    if(_wallVId.empty() or v->minb == 0 or n->minb == 0 or m->minb == 0)
+      return (false);
+  
+    // Search through neighbor list and sum signal and area
+    IntIntSetMap::const_iterator found = _labelNeighbors.find(label);
+    if(found == _labelNeighbors.end())
+      return false;
+    forall(int lab, found->second) {
+      IntIntPair p(label, lab);
+      IntIntVIdSetMap::const_iterator found = _wallVId.find(p);
+      if(found == _wallVId.end())
+        continue;
+  
+      const VIdSet& VtxSet = found->second;
+  
+      // If triangle belongs to this side of wall
+      int count = 0;
+      if(VtxSet.find(v->minb) != VtxSet.end())
+        count++;
+      if(VtxSet.find(n->minb) != VtxSet.end())
+        count++;
+      if(VtxSet.find(m->minb) != VtxSet.end())
+        count++;
+  
+      if(count >= 2) {
+        wall = p;
+        return true;
+      }
+    }
     return false;
-  forall(int lab, found->second) {
-    IntIntPair p(label, lab);
-    IntIntVIdSetMap::const_iterator found = _wallVId.find(p);
-    if(found == _wallVId.end())
-      continue;
-
-    const VIdSet& VtxSet = found->second;
-
-    // If triangle belongs to this side of wall
-    int count = 0;
-    if(VtxSet.find(v->minb) != VtxSet.end())
-      count++;
-    if(VtxSet.find(n->minb) != VtxSet.end())
-      count++;
-    if(VtxSet.find(m->minb) != VtxSet.end())
-      count++;
-
-    if(count >= 2) {
-      wall = p;
-      return true;
-    }
   }
-  return false;
-}
-
-void Mesh::markBorder(float borderSize)
-{
-  if(S.empty())
-    return;
-
-  // For cellular mesh we will mark all vertices
-  if(cells()) {
-    int bcount = 0;
-    forall(const vertex& v, S)
-      if(v->type == 'j') {
-        v->minb = v.id();
-        bcount++;
-      } else
-        v->minb = S.anyIn(v).id();
-  } else {
-    // Process non cellular mesh, first all border vertices in R
-    std::set<vertex> R;
-    forall(const vertex& v, S)
-      if(v->label == -1) {
-        R.insert(v);
-        v->minb = v.id();
-      } else
-        v->minb = 0;
-    // uint bsize = R.size();
-
-    // Start with border vertices and propogate
-    std::set<vertex> T = R;     // Temp list
-    std::set<vertex> D;         // delete list
-    std::set<vertex> I;         // insert list
-
-    uint rsize;
-    do {
-      rsize = R.size();
-      forall(const vertex& v, T) {
-        // If a vertex doesn't add any neighbors, we'll assume it is interior
-        bool del = true;
-        forall(const vertex& n, S.neighbors(v)) {
-          // If not in border front
-          if(R.find(n) == R.end()) {
-            vertex w = vertex(v->minb);
-            if(w.isNull()) {
-              SETSTATUS("markBorder::Error:Null vertex w");
-              continue;
-            }
-            vertex minb = w;
-            double min = (n->pos - w->pos).norm();
-            // forall(const vertex &m, S.neighbors(w))
-            forall(const vertex& m, S.neighbors(n)) {
-              if(m->minb != 0) {
-                vertex mb(m->minb);
-                if(mb.isNull()) {
-                  SETSTATUS("markBorder::Error:Null vertex mb");
-                  continue;
+  
+  void Mesh::markBorder(float borderSize)
+  {
+    if(S.empty())
+      return;
+  
+    // For cellular mesh we will mark all vertices
+    if(cells()) {
+      int bcount = 0;
+      forall(const vertex& v, S)
+        if(v->type == 'j') {
+          v->minb = v.id();
+          bcount++;
+        } else
+          v->minb = S.anyIn(v).id();
+    } else {
+      // Process non cellular mesh, first all border vertices in R
+      std::set<vertex> R;
+      forall(const vertex& v, S)
+        if(v->label == -1) {
+          R.insert(v);
+          v->minb = v.id();
+        } else
+          v->minb = 0;
+      // uint bsize = R.size();
+  
+      // Start with border vertices and propogate
+      std::set<vertex> T = R;     // Temp list
+      std::set<vertex> D;         // delete list
+      std::set<vertex> I;         // insert list
+  
+      uint rsize;
+      do {
+        rsize = R.size();
+        forall(const vertex& v, T) {
+          // If a vertex doesn't add any neighbors, we'll assume it is interior
+          bool del = true;
+          forall(const vertex& n, S.neighbors(v)) {
+            // If not in border front
+            if(R.find(n) == R.end()) {
+              vertex w = vertex(v->minb);
+              if(w.isNull()) {
+                SETSTATUS("markBorder::Error:Null vertex w");
+                continue;
+              }
+              vertex minb = w;
+              double min = (n->pos - w->pos).norm();
+              // forall(const vertex &m, S.neighbors(w))
+              forall(const vertex& m, S.neighbors(n)) {
+                if(m->minb != 0) {
+                  vertex mb(m->minb);
+                  if(mb.isNull()) {
+                    SETSTATUS("markBorder::Error:Null vertex mb");
+                    continue;
+                  }
+                  double dis = (n->pos - mb->pos).norm();
+                  if(dis < min) {
+                    min = dis;
+                    minb = mb;
+                  }
                 }
-                double dis = (n->pos - mb->pos).norm();
-                if(dis < min) {
-                  min = dis;
-                  minb = mb;
-                }
               }
+              if(min <= borderSize) {
+                n->minb = minb.id();
+                R.insert(n);
+                I.insert(n);
+              }
+              del = false;
             }
-            if(min <= borderSize) {
-              n->minb = minb.id();
-              R.insert(n);
-              I.insert(n);
-            }
-            del = false;
           }
+          if(del)
+            D.insert(v);
         }
-        if(del)
-          D.insert(v);
-      }
-      forall(const vertex& v, I)
-        T.insert(v);
-      forall(const vertex& v, D)
-        T.erase(v);
-      I.clear();
-      D.clear();
-    } while(rsize < R.size());     // Do till R stops growing
-  }
-}
-
-// Set normal
-bool Mesh::setNormal(vvgraph& S, vertex v)
-{
-  //  RSS: Changed to use the same algorithm as in ImageData.
-  //
-  v->nrml = Point3f(0, 0, 0);
-  forall(const vertex& n, S.neighbors(v)) {
-    vertex m = S.nextTo(v, n);
-    // add to normal
-    if(n != m and S.edge(n, m)) {
-      Point3f vn = n->pos - v->pos;
-      Point3f vm = m->pos - v->pos;
-      if(S.nextTo(n, m) != v)
-        v->nrml -= vn.cross(vm);
-      else
-        v->nrml += vn.cross(vm);
+        forall(const vertex& v, I)
+          T.insert(v);
+        forall(const vertex& v, D)
+          T.erase(v);
+        I.clear();
+        D.clear();
+      } while(rsize < R.size());     // Do till R stops growing
     }
   }
-  // Check for 0 normals
-  if(v->nrml.norm() == 0) {
+  
+  // Set normal
+  bool Mesh::setNormal(vvgraph& S, vertex v)
+  {
+    //  RSS: Changed to use the same algorithm as in ImageData.
+    //
     v->nrml = Point3f(0, 0, 0);
-    return false;
+    forall(const vertex& n, S.neighbors(v)) {
+      vertex m = S.nextTo(v, n);
+      // add to normal
+      if(n != m and S.edge(n, m)) {
+        Point3f vn = n->pos - v->pos;
+        Point3f vm = m->pos - v->pos;
+        if(S.nextTo(n, m) != v)
+          v->nrml -= vn.cross(vm);
+        else
+          v->nrml += vn.cross(vm);
+      }
+    }
+    // Check for 0 normals
+    if(v->nrml.norm() == 0) {
+      v->nrml = Point3f(0, 0, 0);
+      return false;
+    }
+    v->nrml.normalize();
+  
+    // Check for nan
+    if(fabs(1.0 - v->nrml.norm()) < 1e-4)
+      ;
+    else {
+      v->nrml = Point3f(0, 0, 0);
+      return false;
+    }
+    return true;
   }
-  v->nrml.normalize();
-
-  // Check for nan
-  if(fabs(1.0 - v->nrml.norm()) < 1e-4)
-    ;
-  else {
-    v->nrml = Point3f(0, 0, 0);
-    return false;
+  
+  // Set normals
+  bool Mesh::setNormals()
+  {
+    if(S.empty())
+      return true;
+  
+    size_t nb_invalid = 0;
+  
+    forall(const vertex& v, S)
+      if(!setNormal(S, v))
+        nb_invalid++;
+  
+    if(nb_invalid > 0)
+      SETSTATUS("Mesh::setNormals -- " << nb_invalid << " vertices with invalid normals");
+    return nb_invalid == 0;
   }
-  return true;
-}
-
-// Set normals
-bool Mesh::setNormals()
-{
-  if(S.empty())
-    return true;
-
-  size_t nb_invalid = 0;
-
-  forall(const vertex& v, S)
-    if(!setNormal(S, v))
-      nb_invalid++;
-
-  if(nb_invalid > 0)
-    SETSTATUS("Mesh::setNormals -- " << nb_invalid << " vertices with invalid normals");
-  return nb_invalid == 0;
-}
-
-void Mesh::reset()
-{
-  S.clear();
-  _cellAxis.clear();
-  _cellAxisScaled.clear();
-  _VVCorrespondance.clear();
-
-  _labelHeat.clear();
-  _wallHeat.clear();
-  _labelCenter.clear();
-  _labelCenterVis.clear();
-  _parentCenter.clear();
-  _parentCenterVis.clear();
-  _labelNormal.clear();
-  _labelNormalVis.clear();
-  _parentNormal.clear();
-  _parentNormalVis.clear();
-  _labelNeighbors.clear();
-  _wallVId.clear();
-  _wallGeom.clear();
-  _parentLabel.clear();
-
-  setFile();
-  clearImgTex();
-  setScaled(true);
-  setTransformed(false);
-  setCells(false);
-}
-
-void Mesh::setFile(const QString& file)
-{
-  if(file.isEmpty()) {
-    _file = file;
-  } else {
-    _file = util::absoluteFilePath(file);
+  
+  void Mesh::reset()
+  {
+    S.clear();
+    _cellAxis.clear();
+    _cellAxisScaled.clear();
+    _VVCorrespondance.clear();
+  
+    _labelHeat.clear();
+    _wallHeat.clear();
+    _labelCenter.clear();
+    _labelCenterVis.clear();
+    _parentCenter.clear();
+    _parentCenterVis.clear();
+    _labelNormal.clear();
+    _labelNormalVis.clear();
+    _parentNormal.clear();
+    _parentNormalVis.clear();
+    _labelNeighbors.clear();
+    _wallVId.clear();
+    _wallGeom.clear();
+    _parentLabel.clear();
+  
+    setFile();
+    clearImgTex();
+    setScaled(true);
+    setTransformed(false);
+    setCells(false);
   }
-}
-
-// Get set of vertices that are connected
-void Mesh::getConnectedVertices(const vvgraph& S, vvgraph& V) const
-{
-  vvgraph vNew(V);
-  do {
-    vvgraph N;
-    forall(const vertex& v, vNew)
-      forall(const vertex& n, S.neighbors(v))
-        if(not V.contains(n)) {
-          V.insert(n);
-          N.insert(n);
-        }
-    vNew = N;
-    N.clear();
-  } while(!vNew.empty());
-}
-
-// Get list of connected regions. Most often used to find 3D cells.
-// cellV is a vector of vvgraphs representing all the regions (cells)
-// vCell maps vertices to region (cell) index numbers
-int Mesh::getConnectedRegions(const vvgraph& S, VVGraphVec& cellV, VIntMap& vCell) const
-{
-  int number = 0;
-  VtxSet T(S.begin(), S.end());
-  while(!T.empty()) {
-    vvgraph V;
-    V.insert(*T.begin());
-    getConnectedVertices(S, V);
-    forall(const vertex& v, V) {
-      vCell[v] = number;
-      T.erase(v);
+  
+  // Set the mesh filename
+  void Mesh::setFile(const QString& file)
+  {
+    if(file.isEmpty()) {
+      _file = file;
+    } else {
+      _file = util::absoluteFilePath(file);
     }
-    cellV.push_back(V);
-    number++;
   }
-  // Return number of cells
-  return number;
-}
 
-// Get the neighborhood of a vertex, Euclidean distance, must be connected
-void Mesh::getNhbd(const vvgraph& S, const vertex& v, float radius, VtxSet& nhbd) // static
-{
-  VtxVec VLast, VNew;
-  nhbd.insert(v);
-  VLast.push_back(v);
-  Point3f pos = v->pos;
-  do {
-    forall(const vertex& w, VLast)
-      forall(const vertex& n, S.neighbors(w))
-        if(nhbd.find(n) == nhbd.end() and norm(n->pos - pos) < radius) {
-          VNew.push_back(n);
-          nhbd.insert(n);
-        }
+  // Set the parent label filename
+  void Mesh::setParentFile(const QString& file)
+  {
+    if(file.isEmpty()) {
+      _parentFile = file;
+    } else {
+      _parentFile = util::absoluteFilePath(file);
+    }
+  } 
 
-    std::swap(VLast, VNew);
-    VNew.clear();
-  } while(!VLast.empty());
-}
-
-std::vector<vertex> Mesh::selectedVertices() const
-{
-  std::vector<vertex> vs;
-  if(isMeshVisible() and (showMeshLines() or showMeshPoints())) {
-    forall(const vertex& v, S) {
-      if(v->selected)
-        vs.push_back(v);
-    }
+  // Get set of vertices that are connected
+  void Mesh::getConnectedVertices(const vvgraph& S, vvgraph& V) const
+  {
+    vvgraph vNew(V);
+    do {
+      vvgraph N;
+      forall(const vertex& v, vNew)
+        forall(const vertex& n, S.neighbors(v))
+          if(not V.contains(n)) {
+            V.insert(n);
+            N.insert(n);
+          }
+      vNew = N;
+      N.clear();
+    } while(!vNew.empty());
   }
-  return vs;
-}
-
-std::vector<vertex> Mesh::activeVertices() const
-{
-  std::vector<vertex> vs;
-  vs.reserve(S.size());
-  if(isMeshVisible() and (showMeshLines() or showMeshPoints())) {
-    forall(const vertex& v, S) {
-      if(v->selected)
-        vs.push_back(v);
+  
+  // Get list of connected regions. Most often used to find 3D cells.
+  // cellV is a vector of vvgraphs representing all the regions (cells)
+  // vCell maps vertices to region (cell) index numbers
+  int Mesh::getConnectedRegions(const vvgraph& S, VVGraphVec& cellV, VIntMap& vCell) const
+  {
+    int number = 0;
+    VtxSet T(S.begin(), S.end());
+    while(!T.empty()) {
+      vvgraph V;
+      V.insert(*T.begin());
+      getConnectedVertices(S, V);
+      forall(const vertex& v, V) {
+        vCell[v] = number;
+        T.erase(v);
+      }
+      cellV.push_back(V);
+      number++;
     }
+    // Return number of cells
+    return number;
   }
-  if(vs.empty())
-    std::copy(S.begin(), S.end(), std::back_inserter(vs));
-  return vs;
-}
-
-struct CorrectSelectionKernel {
-  CorrectSelectionKernel(bool inc, const vvgraph& SS, HVecUB& r)
-    : inclusive(inc)
-    , S(SS)
-    , result(r)
+  
+  // Get the neighborhood of a vertex, Euclidean distance, must be connected
+  void Mesh::getNhbd(const vvgraph& S, const vertex& v, float radius, VtxSet& nhbd) // static
   {
+    VtxVec VLast, VNew;
+    nhbd.insert(v);
+    VLast.push_back(v);
+    Point3f pos = v->pos;
+    do {
+      forall(const vertex& w, VLast)
+        forall(const vertex& n, S.neighbors(w))
+          if(nhbd.find(n) == nhbd.end() and norm(n->pos - pos) < radius) {
+            VNew.push_back(n);
+            nhbd.insert(n);
+          }
+  
+      std::swap(VLast, VNew);
+      VNew.clear();
+    } while(!VLast.empty());
   }
-
-  void operator()(size_t i)
+  
+  std::vector<vertex> Mesh::selectedVertices() const
   {
-    const vertex& v = S[i];
-    if(v->label < 0 and v->type != 'l') {
-      bool has_non_border = false;
-      bool has_nb_selected = false;
-      bool has_nb_non_selected = false;
-      bool has_border_selected = false;
-      bool has_nb_labeled = false;
-      forall(const vertex& n, S.neighbors(v)) {
-        if(n->label >= 0) {
-          has_non_border = true;
-          if(n->label > 0)
-            has_nb_labeled = true;
-          if(n->selected)
-            has_nb_selected = true;
-          else
-            has_nb_non_selected = true;
-        } else if(n->selected)
-          has_border_selected = true;
+    std::vector<vertex> vs;
+    if(isMeshVisible() and (showMeshLines() or showMeshPoints())) {
+      forall(const vertex& v, S) {
+        if(v->selected)
+          vs.push_back(v);
       }
-      if(inclusive and has_nb_selected)
-        result[i] = 1;
-      else if(has_non_border and not has_nb_non_selected)
-        result[i] = 1;
-      else if(!has_non_border and has_border_selected)
-        result[i] = 1;
-      else if(v->selected and !has_nb_labeled)
-        result[i] = 1;
-      else
-        result[i] = 0;
-    } else
-      result[i] = v->selected;
+    }
+    return vs;
   }
-
-  bool inclusive;
-  const vvgraph& S;
-  HVecUB& result;
-};
-
-struct CopyResultToSelection {
-  CopyResultToSelection(vvgraph& SS, const HVecUB& r)
-    : S(SS)
-    , result(r)
+  
+  std::vector<vertex> Mesh::activeVertices() const
   {
-  }
-
-  void operator()(size_t i) {
-    S[i]->selected = (result[i] != 0);
-  }
-
-  vvgraph& S;
-  const HVecUB& result;
-};
-
-void Mesh::correctSelection(bool inclusive)
-{
-  if(S.empty() or toShow() == NORMAL)
-    return;
-  thrust::counting_iterator<size_t> first_id(0);
-  thrust::counting_iterator<size_t> last_id = first_id + S.size();
-  HVecUB result(S.size());
-  thrust::for_each(THRUST_RETAG(first_id), THRUST_RETAG(last_id), CorrectSelectionKernel(inclusive, S, result));
-  thrust::for_each(THRUST_RETAG(first_id), THRUST_RETAG(last_id), CopyResultToSelection(S, result));
-}
-
-void Mesh::resetModified()
-{
-  changed_surf_function = false;
-  changed_heat_function = false;
-  changed_label = false;
-  _changed = 0;
-}
-
-void Mesh::updateBBox()
-{
-  _bbox = BoundingBox3f(Point3f(FLT_MAX, FLT_MAX, FLT_MAX), Point3f(-FLT_MAX, -FLT_MAX, -FLT_MAX));
-  forall(const vertex& v, S)
-    _bbox |= v->pos;
-}
-
-// Update the mesh labelCenter and labelNormal, to display the cell axis on mesh surface.
-// if parent labels are selected, the centers and normals are computed based on parents
-// if mesh is cellular, simply take the average positions and normals
-void Mesh::updateCentersNormals()
-{
-  vvgraph S = graph();
-
-  _labelCenter.clear();
-  _labelNormal.clear();
-  _labelCenterVis.clear();
-  _labelNormalVis.clear();
-
-  _parentCenter.clear();
-  _parentNormal.clear();
-  _parentCenterVis.clear();
-  _parentNormalVis.clear();
-
-  std::map<int, std::set<vertex> > vertices;
-
-  // Compute label centers and normals
-  //
-  // If the mesh is simplified, then the center is set to vertex of type 'c', whose normal
-  // and position should represent the one of the whole cell
-  if(_cells) {
-    forall(const vertex& v, S) {
-      if(v->type == 'c') {
-        int label = v->label;
-        _labelCenter[label] = v->pos;
-        _labelNormal[label] = v->nrml;
-        _labelCenterVis[label] = v->pos;
-        _labelNormalVis[label] = v->nrml;
+    std::vector<vertex> vs;
+    vs.reserve(S.size());
+    if(isMeshVisible() and (showMeshLines() or showMeshPoints())) {
+      forall(const vertex& v, S) {
+        if(v->selected)
+          vs.push_back(v);
       }
     }
-  } else   // Otherwise, we need to compute it
+    if(vs.empty())
+      std::copy(S.begin(), S.end(), std::back_inserter(vs));
+    return vs;
+  }
+  
+  struct CorrectSelectionKernel {
+    CorrectSelectionKernel(bool inc, const vvgraph& SS, HVecUB& r)
+      : inclusive(inc)
+      , S(SS)
+      , result(r)
+    {
+    }
+  
+    void operator()(size_t i)
+    {
+      const vertex& v = S[i];
+      if(v->label < 0 and v->type != 'l') {
+        bool has_non_border = false;
+        bool has_nb_selected = false;
+        bool has_nb_non_selected = false;
+        bool has_border_selected = false;
+        bool has_nb_labeled = false;
+        forall(const vertex& n, S.neighbors(v)) {
+          if(n->label >= 0) {
+            has_non_border = true;
+            if(n->label > 0)
+              has_nb_labeled = true;
+            if(n->selected)
+              has_nb_selected = true;
+            else
+              has_nb_non_selected = true;
+          } else if(n->selected)
+            has_border_selected = true;
+        }
+        if(inclusive and has_nb_selected)
+          result[i] = 1;
+        else if(has_non_border and not has_nb_non_selected)
+          result[i] = 1;
+        else if(!has_non_border and has_border_selected)
+          result[i] = 1;
+        else if(v->selected and !has_nb_labeled)
+          result[i] = 1;
+        else
+          result[i] = 0;
+      } else
+        result[i] = v->selected;
+    }
+  
+    bool inclusive;
+    const vvgraph& S;
+    HVecUB& result;
+  };
+  
+  struct CopyResultToSelection {
+    CopyResultToSelection(vvgraph& SS, const HVecUB& r)
+      : S(SS)
+      , result(r)
+    {
+    }
+  
+    void operator()(size_t i) {
+      S[i]->selected = (result[i] != 0);
+    }
+  
+    vvgraph& S;
+    const HVecUB& result;
+  };
+  
+  void Mesh::correctSelection(bool inclusive)
   {
-    IntFloatMap areas;
-    // Find cell centers, areas and normals.
-    forall(const vertex& v, S) {
-      forall(const vertex& n, S.neighbors(v)) {
-        const vertex& m = S.nextTo(v, n);
-        if(!uniqueTri(v, n, m))
-          continue;
-        int label = getLabel(v, n, m, false);
-        if(label == 0)
-          continue;
-        vertices[label].insert(v);
-        vertices[label].insert(n);
-        vertices[label].insert(m);
-        float area = triangleArea(v->pos, n->pos, m->pos);
-        areas[label] += area;
-        _labelCenter[label] += (v->pos + n->pos + m->pos) / 3.0 * area;
-        _labelNormal[label] += (v->nrml + n->nrml + m->nrml) / 3.0 * area;
+    if(S.empty() or toShow() == NORMAL)
+      return;
+    thrust::counting_iterator<size_t> first_id(0);
+    thrust::counting_iterator<size_t> last_id = first_id + S.size();
+    HVecUB result(S.size());
+    thrust::for_each(THRUST_RETAG(first_id), THRUST_RETAG(last_id), CorrectSelectionKernel(inclusive, S, result));
+    thrust::for_each(THRUST_RETAG(first_id), THRUST_RETAG(last_id), CopyResultToSelection(S, result));
+  }
+  
+  void Mesh::resetModified()
+  {
+    changed_surf_function = false;
+    changed_heat_function = false;
+    changed_label = false;
+    _changed = 0;
+  }
+  
+  void Mesh::updateBBox()
+  {
+    _bbox = BoundingBox3f(Point3f(FLT_MAX, FLT_MAX, FLT_MAX), Point3f(-FLT_MAX, -FLT_MAX, -FLT_MAX));
+    forall(const vertex& v, S)
+      _bbox |= v->pos;
+  }
+  
+  // Update the mesh labelCenter and labelNormal, to display the cell axis on mesh surface.
+  // if parent labels are selected, the centers and normals are computed based on parents
+  // if mesh is cellular, simply take the average positions and normals
+  void Mesh::updateCentersNormals()
+  {
+    vvgraph S = graph();
+  
+    _labelCenter.clear();
+    _labelNormal.clear();
+    _labelCenterVis.clear();
+    _labelNormalVis.clear();
+  
+    _parentCenter.clear();
+    _parentNormal.clear();
+    _parentCenterVis.clear();
+    _parentNormalVis.clear();
+  
+    std::map<int, std::set<vertex> > vertices;
+  
+    // Compute label centers and normals
+    //
+    // If the mesh is simplified, then the center is set to vertex of type 'c', whose normal
+    // and position should represent the one of the whole cell
+    if(_cells) {
+      forall(const vertex& v, S) {
+        if(v->type == 'c') {
+          int label = v->label;
+          _labelCenter[label] = v->pos;
+          _labelNormal[label] = v->nrml;
+          _labelCenterVis[label] = v->pos;
+          _labelNormalVis[label] = v->nrml;
+        }
       }
-    }
-
-    forall(const IntFloatPair& p, areas) {
-      int label = p.first;
-      float area = p.second;
-      if(area > 0) {
-        _labelCenter[label] /= area;
-        _labelNormal[label] /= area;
-        Point3f center = _labelCenter[label];
-        // find closest point on surface and set it to the center
-        vertex minv = *(vertices[label].begin());
-        float mindis = norm(minv->pos - center);
-        forall(const vertex& v, vertices[label]) {
-          float dis = norm(v->pos - center);
-          if(dis < mindis) {
-            mindis = dis;
-            minv = v;
+    } else   // Otherwise, we need to compute it
+    {
+      IntFloatMap areas;
+      // Find cell centers, areas and normals.
+      forall(const vertex& v, S) {
+        forall(const vertex& n, S.neighbors(v)) {
+          const vertex& m = S.nextTo(v, n);
+          if(!uniqueTri(v, n, m))
+            continue;
+          int label = getLabel(v, n, m, false);
+          if(label == 0)
+            continue;
+          vertices[label].insert(v);
+          vertices[label].insert(n);
+          vertices[label].insert(m);
+          float area = triangleArea(v->pos, n->pos, m->pos);
+          areas[label] += area;
+          _labelCenter[label] += (v->pos + n->pos + m->pos) / 3.0 * area;
+          _labelNormal[label] += (v->nrml + n->nrml + m->nrml) / 3.0 * area;
+        }
+      }
+  
+      forall(const IntFloatPair& p, areas) {
+        int label = p.first;
+        float area = p.second;
+        if(area > 0) {
+          _labelCenter[label] /= area;
+          _labelNormal[label] /= area;
+          Point3f center = _labelCenter[label];
+          // find closest point on surface and set it to the center
+          vertex minv = *(vertices[label].begin());
+          float mindis = norm(minv->pos - center);
+          forall(const vertex& v, vertices[label]) {
+            float dis = norm(v->pos - center);
+            if(dis < mindis) {
+              mindis = dis;
+              minv = v;
+            }
           }
+          _labelCenterVis[label] = minv->pos;
+          _labelNormalVis[label] = minv->nrml;
         }
-        _labelCenterVis[label] = minv->pos;
-        _labelNormalVis[label] = minv->nrml;
       }
     }
-  }
-
-  // If parent labels exist, compute parent centers and normals
-  if(!_parentLabel.empty()) {
-    IntIntUMap nDaughters;
-    std::map<int, std::set<vertex> > verticesParents;
-
-    for(IntIntMap::iterator it = _parentLabel.begin(); it != _parentLabel.end(); ++it) {
-      int lDaughter = it->first;
-      int lParent = it->second;
-      if(lParent == 0 or lDaughter == 0 or _labelCenter.count(lDaughter) == 0)
-        continue;
-
-      nDaughters[lParent]++;
-      _parentCenter[lParent] += _labelCenter[lDaughter];
-      _parentNormal[lParent] += _labelNormal[lDaughter];
-      if(!_cells) {
-        std::set<vertex> vDaughter = vertices[lDaughter];
-        verticesParents[lParent].insert(vDaughter.begin(), vDaughter.end());
+  
+    // If parent labels exist, compute parent centers and normals
+    if(!_parentLabel.empty()) {
+      IntIntUMap nDaughters;
+      std::map<int, std::set<vertex> > verticesParents;
+  
+      for(IntIntMap::iterator it = _parentLabel.begin(); it != _parentLabel.end(); ++it) {
+        int lDaughter = it->first;
+        int lParent = it->second;
+        if(lParent == 0 or lDaughter == 0 or _labelCenter.count(lDaughter) == 0)
+          continue;
+  
+        nDaughters[lParent]++;
+        _parentCenter[lParent] += _labelCenter[lDaughter];
+        _parentNormal[lParent] += _labelNormal[lDaughter];
+        if(!_cells) {
+          std::set<vertex> vDaughter = vertices[lDaughter];
+          verticesParents[lParent].insert(vDaughter.begin(), vDaughter.end());
+        }
       }
-    }
-
-    forall(const IntPoint3fPair& lc, _parentCenter) {
-      int labelP = lc.first;
-      _parentCenter[labelP] /= nDaughters[labelP];
-      _parentNormal[labelP] /= nDaughters[labelP];
-      Point3f center = _parentCenter[labelP];
-      if(!_cells) {
-        // find closest point on surface and set it to the center
-        float mindis = HUGE_VAL;
-        // vertex minv;
-        vertex minv = *(verticesParents[labelP].begin());
-        forall(const vertex& v, verticesParents[labelP]) {
-          float dis = norm(v->pos - center);
-          if(dis < mindis) {
-            mindis = dis;
-            minv = v;
+  
+      forall(const IntPoint3fPair& lc, _parentCenter) {
+        int labelP = lc.first;
+        _parentCenter[labelP] /= nDaughters[labelP];
+        _parentNormal[labelP] /= nDaughters[labelP];
+        Point3f center = _parentCenter[labelP];
+        if(!_cells) {
+          // find closest point on surface and set it to the center
+          float mindis = HUGE_VAL;
+          // vertex minv;
+          vertex minv = *(verticesParents[labelP].begin());
+          forall(const vertex& v, verticesParents[labelP]) {
+            float dis = norm(v->pos - center);
+            if(dis < mindis) {
+              mindis = dis;
+              minv = v;
+            }
           }
+          _parentCenterVis[labelP] = minv->pos;
+          _parentNormalVis[labelP] = minv->nrml;
+        } else {
+          _parentCenterVis[labelP] = _parentCenter[labelP];
+          _parentNormalVis[labelP] = _parentNormal[labelP];
         }
-        _parentCenterVis[labelP] = minv->pos;
-        _parentNormalVis[labelP] = minv->nrml;
-      } else {
-        _parentCenterVis[labelP] = _parentCenter[labelP];
-        _parentNormalVis[labelP] = _parentNormal[labelP];
       }
     }
   }
-}
+  
+  void Mesh::clearCellAxis()
+  {
+    _cellAxis.clear();
+    _cellAxisScaled.clear();
+    _cellAxisColor.clear();
+    _cellAxisType.clear();
+  }
 
-void Mesh::clearCellAxis()
-{
-  _cellAxis.clear();
-  _cellAxisScaled.clear();
-  _cellAxisColor.clear();
-  _cellAxisType.clear();
 }
-} // namespace mgx
