Index: guiframe/data_loader.py
===================================================================
--- guiframe/data_loader.py	(revision 8bd764d24747a8a4ae90ca4c10c529656b5ac9cc)
+++ guiframe/data_loader.py	(revision 6d920cd2a2b96abc4845a5766911d8ef7fe5adc5)
@@ -1,3 +1,3 @@
-import os, sys
+import os, sys,numpy
 import wx
 from dataFitting import Data1D, Theory1D
@@ -28,5 +28,4 @@
         Load a 1D ascii file, with errors
     """
-    import numpy
     if path and os.path.isfile(path):
     
@@ -63,9 +62,12 @@
     return None, None, None
 
-def plot_data(parent, path, name="Loaded Data"):
+def plot_data(parent, path):
+    """
+        Use the DataLoader loader to created data to plot.
+        @param path: the path of the data to load
+    """
     from sans.guicomm.events import NewPlotEvent, StatusEvent
-   
     from DataLoader.loader import  Loader
-    import numpy
+    
     #Instantiate a loader 
     L = Loader()
@@ -98,7 +100,6 @@
             new_plot.x_bins=output.x_bins
             new_plot.y_bins=output.y_bins
-            #print "data_loader",output
         else:
-            #print "output.dx, output.dy",output.dx, output.dy
+           
             if output.dy ==None :
                 new_plot = Theory1D(output.x,output.y, dxl, dxw)
@@ -109,7 +110,7 @@
                 new_plot = Theory1D(output.x,output.y,output.dy, dxl, dxw)
             else:
-                    
                 new_plot = Data1D(x=output.x,y=output.y,dx=output.dx,dy=output.dy, dxl=dxl, dxw=dxw)
-       
+        if output.filename==None:
+            output.filename=str(filename)
         new_plot.source=output.source
         new_plot.name = output.filename
@@ -121,5 +122,4 @@
         if hasattr(output, "dxw"):
             new_plot.dxw = output.dxw
-        #print "loader output.detector",output.source
         new_plot.detector =output.detector
         
@@ -151,9 +151,6 @@
            
             new_plot.source=item.source
-            #new_plot.info=output
             new_plot.name = str(item.run[0])
             new_plot.interactive = True
-           
-            #print "loader output.detector",output.source
             new_plot.detector =item.detector
             # If the data file does not tell us what the axes are, just assume...
@@ -162,4 +159,6 @@
             new_plot.group_id = str(item.run[0])
             new_plot.id = str(item.run[0])
+            new_plot.info= item
+            
             if hasattr(item,"title"):
                 title= item.title
Index: guiframe/gui_manager.py
===================================================================
--- guiframe/gui_manager.py	(revision 700f9b484abb7a4e73e5c999b745a31e1f731c2b)
+++ guiframe/gui_manager.py	(revision 6d920cd2a2b96abc4845a5766911d8ef7fe5adc5)
@@ -35,5 +35,5 @@
     import config
     
-from sans.guicomm.events import EVT_STATUS,Model2DPanelEvent
+from sans.guicomm.events import EVT_STATUS
 from sans.guicomm.events import EVT_NEW_PLOT,EVT_SLICER_PARS_UPDATE
 import history
@@ -224,7 +224,4 @@
         self.defaultPanel    = DefaultPanel(self, -1, style=wx.RAISED_BORDER)
         
-        # History panel
-        #self.histPanel     = history.HistoryPanel(self, style=wx.RAISED_BORDER)
-        # self.build_gui()
        
         # Register the close event so it calls our own method
@@ -297,5 +294,5 @@
         """
         import imp
-        print "Looking for plug-ins in %s" % dir
+        #print "Looking for plug-ins in %s" % dir
         # List of plug-in objects
         
@@ -368,6 +365,4 @@
         # It also sets the size of the application windows
         self.panels["default"] = self.defaultPanel
-         # History panel
-        #self.panels["historyPanel"] = self.histPanel  
         
         self._mgr.AddPane(self.defaultPanel, wx.aui.AuiPaneInfo().
@@ -378,20 +373,5 @@
                               MinSize(wx.Size(self._window_width, self._window_height)).
                               Show())
-        """
-        self._mgr.AddPane(self.histPanel, wx.aui.AuiPaneInfo().
-                          Name("historyPanel").Caption("History").
-                          #Float().
-                          Bottom().
-                          Dock().
-                          TopDockable().
-                          BottomDockable().
-                          LeftDockable().
-                          RightDockable().
-                          MinimizeButton().
-                          Hide().
-                          #Show().
-                          BestSize(wx.Size(500,600)).
-                          MinSize(wx.Size(200,150)))
-        """
+     
 
         # Add the panels to the AUI manager
@@ -410,6 +390,4 @@
                                           BestSize(wx.Size(600,600)).
                                           MinSize(wx.Size(400,400)).
-                                          #BestSize(wx.Size(500,500)).
-                                          #MinSize(wx.Size(200,200)).
                                           Hide())
                 
@@ -418,6 +396,4 @@
                 self._mgr.AddPane(p, wx.aui.AuiPaneInfo().
                                   Name(p.window_name).Caption(p.window_caption).
-                                  #Floatable().
-                                  #Float().
                                   Right().
                                   Dock().
@@ -428,9 +404,7 @@
                                   MinimizeButton().
                                   Hide().
-                                  #Show().
                                   BestSize(wx.Size(600,600)).
                                   MinSize(wx.Size(500,500)))
-                                  #BestSize(wx.Size(400,400)).
-                                  #MinSize(wx.Size(300,300)))
+                               
 
                 
@@ -516,9 +490,5 @@
         filemenu.Append(id, '&Open', 'Open a file')
         wx.EVT_MENU(self, id, self._on_open)
-        
-        #id = wx.NewId()
-        #filemenu.Append(id, '&History', 'Register previous States')
-        #wx.EVT_MENU(self, id, self._onHistoryPanel)
-        
+    
         id = wx.NewId()
         filemenu.Append(id,'&Quit', 'Exit') 
@@ -652,12 +622,5 @@
                 
             self._mgr.Update()
-    """
-    def _onHistoryPanel(self, event):
-        print "on history"
-        if not self._mgr.GetPane("historyPanel").IsShown():
-            self._mgr.GetPane("historyPanel").Show()
-        self._mgr.Update()
-        return
-    """   
+   
     def _on_open(self, event):
    
Index: iframe/history.py
===================================================================
--- guiframe/history.py	(revision ca88b2eded93a483ace5848e87ba70d47c410949)
+++ 	(revision )
@@ -1,201 +1,0 @@
-"""
-    Panel class to show the model history
-"""
-#TODO: when a model change is followed by a parameter change,
-#      we end up with the same model twice in a row in the history
-#TODO: implement aging of history items
-
-import wx
-import wx.lib.newevent
-import config
-
-# History events
-(HistoryEvent, EVT_HISTORY) = wx.lib.newevent.NewEvent()
-
-# Maximum number of full history events in the buffer
-MAX_BUFF_LEN = 30
-
-isWindows = False
-import sys
-if sys.platform.count("win32")>0:
-    isWindows = True
-    
-if isWindows:
-    from ctypes import *
-    from ctypes.wintypes import DWORD
-
-    SIZE_T = c_ulong
-
-    class _MEMORYSTATUS(Structure):
-        _fields_ = [("dwLength", DWORD),
-                    ("dwMemoryLength", DWORD),
-                    ("dwTotalPhys", SIZE_T),
-                    ("dwAvailPhys", SIZE_T),
-                    ("dwTotalPageFile", SIZE_T),
-                    ("dwAvailPageFile", SIZE_T),
-                    ("dwTotalVirtual", SIZE_T),
-                    ("dwAvailVirtualPhys", SIZE_T)]
-        def show(self):
-            for field_name, field_type in self._fields_:
-                print field_name, getattr(self, field_name)
-    
-
-
-
-class HistoryPanel(wx.Panel):
-    """
-        Panel to show history items
-    """
-    #TODO: show units
-    #TODO: order parameters properly
-    ## Internal name for the AUI manager
-    window_name = "historyPanel"
-    ## Title to appear on top of the window
-    window_caption = "historyPanel"
-    
-    CENTER_PANE = False
-    def __init__(self, parent, *args, **kwargs):
-        wx.Panel.__init__(self, parent, *args, **kwargs)
-        self.parent = parent
-
-        # Listen to history events
-        self.parent.Bind(EVT_HISTORY, self.onEVT_HISTORY)
-
-        # Internal counter of history items
-        self.counter = 0
-        
-        # Buffer filled flag
-        self.buffer_filled = False
-        
-        # Set up the layout
-        self._set_layout()
-        
-        # Save current flag
-        self.current_saved = False
-        
-    def _set_layout(self):
-        """
-            Set up the layout of the panel
-        """
-        self.sizer = wx.GridBagSizer(0,5)
-        
-        title = wx.StaticText(self, -1, "History", style=wx.ALIGN_LEFT)         
-        self.sizer.Add(title, (0,0), flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL, border=15)
-
-        self.view_box = wx.ListBox(self, 101, wx.DefaultPosition, (295, 200), 
-                                   [], wx.LB_SINGLE | wx.LB_HSCROLL)
-        
-        self.sizer.Add(self.view_box, (1,0), flag=wx.TOP, border=0)
-        
-        self.SetSizer(self.sizer)
-        
-        self.Bind(wx.EVT_CONTEXT_MENU, self.onShowPopup, id=101)
-        self.Bind(wx.EVT_LISTBOX, self.onSelect, id=101)
-        
-    def onRemove(self, ev):
-        """
-            Remove an item
-        """
-        indices = self.view_box.GetSelections()
-        if len(indices)>0:
-            self.view_box.Delete(indices[0])
-        
-    def onRename(self, ev):
-        """
-            Rename an item
-        """
-        indices = self.view_box.GetSelections()
-        if len(indices)>0:
-            print "NOT YET IMPLMENTED"
-            print "renaming", self.view_box.GetString(indices[0])
-        
-    def onShowPopup(self, event):
-        """
-            Popup context menu event
-        """
-        # menu
-        popupmenu = wx.Menu()
-        id = wx.NewId()
-        popupmenu.Append(id, "&Remove Selected")
-        #popupmenu.Append(102, "&Rename Selected")
-        wx.EVT_MENU(self, id, self.onRemove)
-        #wx.EVT_MENU(self, 102, self.onRename)
-
-        pos = event.GetPosition()
-        pos = self.ScreenToClient(pos)
-        self.PopupMenu(popupmenu, pos)
-
-    def onSelect(self, event):
-        """
-            Process item selection events
-        """
-        index = event.GetSelection()
-        view_name = self.view_box.GetString(index)
-        view = event.GetClientData()
-
-        wx.PostEvent(self.parent, view)
-                
-    def onEVT_HISTORY(self, event):
-        """
-            Process EVT_HISTORY events
-            When a history event arrives, put it in the list
-            of history items
-            
-            @param event: EVT_HISTORY event
-        """
-        print "onEVT_HISTORY",event.name
-        #TODO: this will only work on Windows
-        import distutils.util
-        isWindows = False
-        if sys.platform.count("win32")>0:
-            isWindows = True
-            
-        if isWindows:
-            memstatus = _MEMORYSTATUS()
-            windll.kernel32.GlobalMemoryStatus(byref(memstatus))
-            size_0   = getattr(memstatus, 'dwAvailPhys')
-            size_obj = 1000.0
-            if not event.item.state._data_2D == None:
-                size_obj = len(event.item.state._data_2D)*len(event.item.state._data_2D)*32.0
-        
-        #print "HistoryPanel.EVT_HISTORY"
-        self.counter += 1
-        self.view_box.Insert("%d: %s" % (self.counter, event.name), 
-                             self.view_box.GetCount(), event.item)
-                
-        deleteOldItem = False
-        if isWindows:
-            # This break our scheme of the history panel not knowing
-            # about the events, but we need to protect against 
-            # filling up the memory. 
-            # TODO: fix this
-        
-            if size_0/size_obj < 10:
-                deleteOldItem = True
-                
-        else:
-        
-            # If the buffer is already full, write the earlier ones
-            # in a file.
-            if self.view_box.GetCount() > MAX_BUFF_LEN:
-                deleteOldItem = True
-            
-        if deleteOldItem:
-            #item_0 = self.view_box.GetString(0)
-            #import os
-            # Write it
-            #filename = "history_%i.dat" % os.getpid()
-            #fd = open(filename,'a')
-            #fd.write("test\n")    
-        
-            # For now, delete item from list 
-            if not self.buffer_filled:
-                evt = config.StatusBarEvent( \
-                    message = "Memory running low, oldest history events will be deleted")
-                    #message = "Maximum number of history events reached (%g)" % MAX_BUFF_LEN)
-                wx.PostEvent(self.parent, evt)
-                self.buffer_filled = True
-            
-            self.view_box.Delete(0)
-
-
Index: guiframe/local_perspectives/plotting/AnnulusSlicer.py
===================================================================
--- guiframe/local_perspectives/plotting/AnnulusSlicer.py	(revision 18eba35c7477f0694169ce9f4575ba08f17c4cc0)
+++ guiframe/local_perspectives/plotting/AnnulusSlicer.py	(revision 6d920cd2a2b96abc4845a5766911d8ef7fe5adc5)
@@ -122,5 +122,5 @@
         rmax = max(math.fabs(self.inner_circle.get_radius()),
                    math.fabs(self.outer_circle.get_radius()))
-        print "rmin, rmax", rmin, rmax
+        #print "rmin, rmax", rmin, rmax
         if nbins==None:
             nbins = 20
Index: guiframe/local_perspectives/plotting/Plotter1D.py
===================================================================
--- guiframe/local_perspectives/plotting/Plotter1D.py	(revision 8bd764d24747a8a4ae90ca4c10c529656b5ac9cc)
+++ guiframe/local_perspectives/plotting/Plotter1D.py	(revision 6d920cd2a2b96abc4845a5766911d8ef7fe5adc5)
@@ -263,14 +263,5 @@
         slicerpop.Append(id, '&Reset Graph')
         wx.EVT_MENU(self, id, self.onResetGraph)  
-        """
-        slicerpop.AppendSeparator() 
-        id = wx.NewId()
-        slicerpop.Append(id,'&Printer setup', 'Set image size')
-        wx.EVT_MENU(self, id, self.onPrinterSetup)
-        
-        id = wx.NewId()
-        slicerpop.Append(id,'&Printer Preview', 'Set image size')
-        wx.EVT_MENU(self, id, self.onPrinterPreview)
-        """
+       
         
 
Index: guiframe/local_perspectives/plotting/Plotter2D.py
===================================================================
--- guiframe/local_perspectives/plotting/Plotter2D.py	(revision 8bd764d24747a8a4ae90ca4c10c529656b5ac9cc)
+++ guiframe/local_perspectives/plotting/Plotter2D.py	(revision 6d920cd2a2b96abc4845a5766911d8ef7fe5adc5)
@@ -93,5 +93,5 @@
         
     def _onEVT_SLICER_PARS(self, event):
-        print "paramaters entered on slicer panel", event.type, event.params
+        #print "paramaters entered on slicer panel", event.type, event.params
         self.slicer.set_params(event.params)
         #from sans.guicomm.events import SlicerPanelEvent
@@ -247,12 +247,5 @@
         slicerpop.AppendSeparator() 
        
-        """
-        # Option to save the data displayed
-        id = wx.NewId()
-        slicerpop.Append(id,'&Printer setup', 'Set image size')
-        wx.EVT_MENU(self, id, self.onPrinterSetup)
-        
-       
-        """
+     
         id = wx.NewId()
         slicerpop.Append(id, '&Toggle Linear/Log scale')
@@ -265,5 +258,7 @@
    
     def _onEditDetector(self, event):
-        print "edit detortor param",self.zmin_2D, self.zmax_2D
+        """
+        """
+        #print "edit detortor param",self.zmin_2D, self.zmax_2D
         import detector_dialog
         dialog = detector_dialog.DetectorDialog(self, -1,base=self.parent)
@@ -286,5 +281,5 @@
        
         dialog.Destroy()
-        print "zmn ,zmax", self.zmin_2D, self.zmax_2D
+        #print "zmn ,zmax", self.zmin_2D, self.zmax_2D
         self.image(data= self.data2D.data,
                    xmin= self.data2D.xmin,
Index: guiframe/local_perspectives/plotting/boxSum.py
===================================================================
--- guiframe/local_perspectives/plotting/boxSum.py	(revision 18eba35c7477f0694169ce9f4575ba08f17c4cc0)
+++ guiframe/local_perspectives/plotting/boxSum.py	(revision 6d920cd2a2b96abc4845a5766911d8ef7fe5adc5)
@@ -74,9 +74,12 @@
         #print "box sum  self.base.parent",self.base.parent
         self.base.Bind(EVT_SLICER_PARS, self._onEVT_SLICER_PARS)
+        
     def set_panel_name(self, name):
         self.panel_name= name
+        
+        
     def _onEVT_SLICER_PARS(self, event):
         wx.PostEvent(self.base.parent, StatusEvent(status="Boxsum._onEVT_SLICER_PARS"))
-        print "receiving value ",event.params
+        #print "receiving value ",event.params
         event.Skip()
         if event.type == self.__class__.__name__:
@@ -157,8 +160,8 @@
         y_min= self.vertical_lines.y2
         y_max= self.vertical_lines.y1
-        print "xmin, xmax, ymin , ymax", x_min, x_max, y_min, y_max
+        #print "xmin, xmax, ymin , ymax", x_min, x_max, y_min, y_max
         box =  Boxavg (x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max)
         self.count, self.error = box(self.base.data2D)
-        print "box_sum output",box(self.base.data2D)
+        #print "box_sum output",box(self.base.data2D)
                           
     def moveend(self, ev):
Index: guiframe/local_perspectives/plotting/last_boxSlicer.py
===================================================================
--- guiframe/local_perspectives/plotting/last_boxSlicer.py	(revision 6d920cd2a2b96abc4845a5766911d8ef7fe5adc5)
+++ guiframe/local_perspectives/plotting/last_boxSlicer.py	(revision 6d920cd2a2b96abc4845a5766911d8ef7fe5adc5)
@@ -0,0 +1,613 @@
+#TODO: the line slicer should listen to all 2DREFRESH events, get the data and slice it
+#      before pushing a new 1D data update.
+
+#
+#TODO: NEED MAJOR REFACTOR
+#
+
+
+# Debug printout
+#from config import printEVT
+from BaseInteractor import _BaseInteractor
+from copy import deepcopy
+import math
+
+from sans.guicomm.events import NewPlotEvent, StatusEvent,SlicerParameterEvent,EVT_SLICER_PARS
+import SlicerParameters
+import wx
+
+
+class BoxInteractor(_BaseInteractor):
+    """
+         Select an annulus through a 2D plot
+    """
+    def __init__(self,base,axes,color='black', zorder=3,
+                  x_min=0.0025, x_max=0.0025, y_min=0.0025, y_max=0.0025):
+        
+        _BaseInteractor.__init__(self, base, axes, color=color)
+        self.markers = []
+        self.axes = axes
+        self.qmax = self.base.data2D.xmax
+        self.connect = self.base.connect
+        self.x= 0.5*min(math.fabs(self.base.data2D.xmax),math.fabs( self.base.data2D.xmin))
+        self.y= 0.5*min(math.fabs(self.base.data2D.xmax),math.fabs( self.base.data2D.xmin))        
+         
+        self.theta2= math.pi/3
+        ## Number of points on the plot
+        self.nbins = 30
+        self.count=0
+        self.error=0
+        self.averager=None
+        self.left_line = VerticalLine(self, self.base.subplot,color='blue', 
+                                      zorder=zorder,
+                                        ymin= -self.y , 
+                                        ymax= self.y ,
+                                        xmin= -self.x,
+                                        xmax= -self.x)
+        self.left_line.qmax = self.qmax
+        
+        self.right_line= VerticalLine(self, self.base.subplot,color='black', 
+                                      zorder=zorder,
+                                     ymin= -self.y , 
+                                     ymax= self.y,
+                                     xmin= self.x,
+                                     xmax= self.x)
+        self.right_line.qmax = self.qmax
+        
+        self.top_line= HorizontalLine(self, self.base.subplot,color='green', 
+                                      zorder=zorder,
+                                      xmin= -self.x,
+                                      xmax= self.x,
+                                      ymin= self.y,
+                                      ymax= self.y)
+        self.top_line.qmax= self.qmax
+        
+        self.bottom_line= HorizontalLine(self, self.base.subplot,color='gray', 
+                                      zorder=zorder,
+                                      xmin= -self.x,
+                                      xmax= self.x,
+                                      ymin= -self.y,
+                                      ymax= -self.y)
+        self.bottom_line.qmax= self.qmax
+        
+        self.update()
+        self._post_data()
+        
+        # Bind to slice parameter events
+        self.base.Bind(EVT_SLICER_PARS, self._onEVT_SLICER_PARS)
+
+
+    def _onEVT_SLICER_PARS(self, event):
+        wx.PostEvent(self.base, StatusEvent(status="BoxSlicer._onEVT_SLICER_PARS"))
+        event.Skip()
+        if event.type == self.__class__.__name__:
+            self.set_params(event.params)
+            self.base.update()
+
+    def update_and_post(self):
+        self.update()
+        self._post_data()
+
+    def save_data(self, path, image, x, y):
+        output = open(path, 'w')
+        
+        data_x, data_y = self.get_data(image, x, y)
+        
+        output.write("<phi>  <average>\n")
+        for i in range(len(data_x)):
+            output.write("%g  %g\n" % (data_x[i], data_y[i]))
+        output.close()
+
+    def set_layer(self, n):
+        self.layernum = n
+        self.update()
+        
+    def clear(self):
+        self.averager=None
+        self.clear_markers()
+        self.left_line.clear()
+        self.right_line.clear()
+        self.top_line.clear()
+        self.bottom_line.clear()
+        #self.base.connect.disconnect()
+        self.base.Unbind(EVT_SLICER_PARS)
+        
+    def update(self):
+        """
+        Respond to changes in the model by recalculating the profiles and
+        resetting the widgets.
+        """
+        
+        if self.top_line.has_move:
+            #print"top has moved"
+            self.top_line.update()
+            self.bottom_line.update(ymin= -self.top_line.y1,
+                                    ymax= -self.top_line.y2)
+            self.left_line.update(ymin= -self.top_line.y1,
+                                    ymax= -self.top_line.y2)
+            self.right_line.update(ymin= -self.top_line.y1,
+                                    ymax= -self.top_line.y2)
+           
+        if self.bottom_line.has_move:
+            #print "bottom has move"
+            self.bottom_line.update()
+            self.top_line.update(ymin= -self.bottom_line.y1,
+                                    ymax= -self.bottom_line.y2)
+            self.left_line.update(ymin= self.bottom_line.y1,
+                                    ymax= self.top_line.y1)
+            self.right_line.update(ymin= self.bottom_line.y1,
+                                    ymax=self.top_line.y1)
+           
+        if self.left_line.has_move:
+           
+            self.left_line.update()
+            self.right_line.update(xmin = - self.left_line.x1,
+                                   xmax = - self.left_line.x1)
+            self.bottom_line.update(xmin=  self.left_line.x1,
+                                     xmax= self.right_line.x1)
+            self.top_line.update(xmin= self.left_line.x1,
+                                    xmax= self.right_line.x1)
+           
+        if self.right_line.has_move:
+           
+            self.right_line.update()
+            self.left_line.update(xmin = -self.right_line.x1,
+                                   xmax = -self.right_line.x1)
+            
+            self.bottom_line.update(xmin= self.left_line.x1,
+                                 xmax= self.right_line.x1)
+            
+            self.top_line.update(xmin= self.left_line.x1,
+                                    xmax= self.right_line.x1)
+               
+            
+    def save(self, ev):
+        """
+        Remember the roughness for this layer and the next so that we
+        can restore on Esc.
+        """
+        self.base.freeze_axes()
+        self.left_line.save(ev)
+        self.right_line.save(ev)
+        self.top_line.save(ev)
+        self.bottom_line.save(ev)
+    def _post_data(self):
+        pass
+        
+    
+    def post_data(self,new_slab=None , nbins=None):
+        """ post data averaging in Q"""
+        x_min= min(self.left_line.x1, self.right_line.x1)
+        x_max= max(self.left_line.x1, self.right_line.x1)
+        
+        y_min= min(self.top_line.y1, self.bottom_line.y1)
+        y_max= max(self.top_line.y1, self.bottom_line.y1)  
+        
+        if nbins !=None:
+            self.nbins
+        if self.averager==None:
+            if new_slab ==None:
+                raise ValueError,"post data:cannot average , averager is empty"
+            self.averager= new_slab
+        bin_width= (x_max + math.fabs(x_min))/self.nbins
+        
+        box = self.averager( x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max,
+                         bin_width=bin_width)
+        
+        boxavg = box(self.base.data2D)
+        
+        from sans.guiframe.dataFitting import Data1D
+        if hasattr(boxavg,"dxl"):
+            dxl= boxavg.dxl
+        else:
+            dxl= None
+        if hasattr(boxavg,"dxw"):
+            dxw=boxavg.dxw
+        else:
+            dxw= None
+       
+        new_plot = Data1D(x=boxavg.x,y=boxavg.y,dy=boxavg.dy,dxl=dxl,dxw=dxw)
+        new_plot.name = str(self.averager.__name__) +"("+ self.base.data2D.name+")"
+        
+       
+
+        new_plot.source=self.base.data2D.source
+        new_plot.interactive = True
+        #print "loader output.detector",output.source
+        new_plot.detector =self.base.data2D.detector
+        # If the data file does not tell us what the axes are, just assume...
+        new_plot.xaxis("\\rm{Q}", 'rad')
+        new_plot.yaxis("\\rm{Intensity} ","cm^{-1}")
+        new_plot.group_id = str(self.averager.__name__)+self.base.data2D.name
+        new_plot.id = str(self.averager.__name__)
+        wx.PostEvent(self.base.parent, NewPlotEvent(plot=new_plot,
+                                                 title=str(self.averager.__name__) ))
+        
+        
+    def _post_data(self):
+        # Compute data
+        data = self.base.data2D
+        from DataLoader.manipulations import  Boxavg
+        radius = math.sqrt(math.pow(self.qmax,2)+math.pow(self.qmax,2))
+        self.x= math.fabs(self.right_line.x1)
+        self.y= math.fabs(self.top_line.y1 )
+       
+        box =  Boxavg (x_min=-self.x, x_max=self.x, y_min=-self.y, y_max=self.y)
+       
+        self.count, self.error= box(self.base.data2D)
+        
+        #print "post data"
+              
+                                       
+    def moveend(self, ev):
+        self.base.thaw_axes()
+        
+        # Post paramters
+        event = SlicerParameterEvent()
+        event.type = self.__class__.__name__
+        event.params = self.get_params()
+        wx.PostEvent(self.base.parent, event)
+
+        self._post_data()
+            
+    def restore(self):
+        """
+        Restore the roughness for this layer.
+        """
+        self.left_line.restore()
+        self.right_line.restore()
+        self.top_line.restore()
+        self.bottom_line.restore()
+
+    def move(self, x, y, ev):
+        """
+        Process move to a new position, making sure that the move is allowed.
+        """
+        pass
+        
+    def set_cursor(self, x, y):
+        pass
+        
+    def get_params(self):
+        params = {}
+        params["x_max"]= math.fabs(self.right_line.x1)
+        params["y_max"]= math.fabs(self.top_line.y1)
+        params["nbins"]= self.nbins
+        params["errors"] = self.error
+        params["count"]= self.count
+        return params
+    
+    def set_params(self, params):
+        
+        self.x = float(math.fabs(params["x_max"]))
+        self.y = float(math.fabs(params["y_max"] ))
+        self.nbins=params["nbins"]
+        self.left_line.update(xmin= -1*self.x,
+                              xmax = -1*self.x,
+                              ymin= -self.y,
+                              ymax=  self.y, 
+                              )
+        self.right_line.update(xmin= self.x,
+                              xmax = self.x,
+                              ymin= -self.y,
+                              ymax=  self.y, 
+                              )
+        self.top_line.update(xmin= -1*self.x,
+                             xmax= self.x,
+                             ymin= self.y,
+                             ymax= self.y)
+        self.bottom_line.update(xmin= -1*self.x,
+                                 xmax= self.x,
+                                 ymin= -1*self.y,
+                                 ymax= -1*self.y)
+       
+        self.post_data( nbins=None)
+    def freeze_axes(self):
+        self.base.freeze_axes()
+        
+    def thaw_axes(self):
+        self.base.thaw_axes()
+
+    def draw(self):
+        self.base.draw()
+
+class HorizontalLine(_BaseInteractor):
+    """
+         Select an annulus through a 2D plot
+    """
+    def __init__(self,base,axes,color='black', zorder=5,mline=None,ymin=None, ymax=None, y=0.5,
+                 xmin=0.0,xmax=0.5):
+        
+        _BaseInteractor.__init__(self, base, axes, color=color)
+        self.markers = []
+        self.axes = axes
+        self.x1= xmax
+        self.save_x1= xmax
+        
+        self.x2= xmin
+        self.save_x2= xmin
+        
+        self.y1= ymax
+        self.save_y1= ymax
+        
+        self.y2= ymin
+        self.save_y2= ymin
+        self.mline= mline
+        try:
+            # Inner circle marker
+            self.inner_marker = self.axes.plot([0],[self.y1], linestyle='',
+                                          marker='s', markersize=10,
+                                          color=self.color, alpha=0.6,
+                                          pickradius=5, label="pick", 
+                                          zorder=zorder, # Prefer this to other lines
+                                          visible=True)[0]
+        except:
+            self.inner_marker = self.axes.plot([0],[self.y1], linestyle='',
+                                          marker='s', markersize=10,
+                                          color=self.color, alpha=0.6,
+                                          label="pick", 
+                                          visible=True)[0]
+            message  = "\nTHIS PROTOTYPE NEEDS THE LATEST VERSION OF MATPLOTLIB\n"
+            message += "Get the SVN version that is at least as recent as June 1, 2007"
+            
+        self.line = self.axes.plot([self.x1,-self.x1],
+                                   [self.y1,self.y2],
+                                      linestyle='-', marker='',
+                                      color=self.color,
+                                      visible=True)[0]
+        
+        self.npts = 20
+        self.has_move=False
+        self.connect_markers([self.line, self.inner_marker])
+        self.update()
+
+    def set_layer(self, n):
+        self.layernum = n
+        self.update()
+        
+    def clear(self):
+        self.clear_markers()
+        try:
+            
+            self.line.remove()
+        except:
+            # Old version of matplotlib
+            for item in range(len(self.axes.lines)):
+                del self.axes.lines[0]
+   
+    def get_radius(self):
+        
+        return 0
+   
+    def update(self,xmin=None, xmax=None,ymin=None,ymax=None, mline=None,translation=False):
+        """
+        Draw the new roughness on the graph.
+        """
+        if xmin !=None:
+            self.x1 = xmin
+        if ymin !=None:
+            self.y1 = ymin
+        self.inner_marker.set(xdata=[0],ydata=[self.y1])
+        self.line.set(xdata=[self.x1,-self.x1],
+                       ydata=[self.y1,self.y1])
+    
+        
+        
+    def save(self, ev):
+        """
+        Remember the roughness for this layer and the next so that we
+        can restore on Esc.
+        """
+        self.save_x1= self.x1
+        self.save_x2= self.x2
+       
+        self.save_y1= self.y1
+        self.save_y2= self.y2
+    
+        
+        self.base.freeze_axes()
+
+    def moveend(self, ev):
+       
+        self.has_move=False
+        self.base.moveend(ev)
+            
+    def restore(self):
+        """
+        Restore the roughness for this layer.
+        """
+        self.x1 = self.save_x1
+        self.x2 = self.save_x2
+        self.y1 = self.save_y1
+        self.y2 = self.save_y2
+        
+
+    def move(self, x, y, ev):
+        """
+        Process move to a new position, making sure that the move is allowed.
+        """
+        #print "horizontal move x y "
+        self.y1= y
+        self.has_move=True
+        self.base.base.update()
+        
+    def set_cursor(self, x, y):
+        self.move(x, y, None)
+        self.update()
+        
+        
+    def get_params(self):
+        params = {}
+        params["radius"] = self.x1
+        #params["theta"] = self.xmax
+        return params
+    
+    def set_params(self, params):
+
+        x = params["radius"] 
+        self.set_cursor(x, self._inner_mouse_y)
+        
+
+
+
+class VerticalLine(_BaseInteractor):
+    """
+         Select an annulus through a 2D plot
+    """
+    def __init__(self,base,axes,color='black', zorder=5, mline=None, ymin=0.0, 
+                 ymax=0.5,xmin=-0.5,xmax=0.5
+                 ):
+        
+        _BaseInteractor.__init__(self, base, axes, color=color)
+        self.markers = []
+        self.axes = axes
+        
+        self.x1= xmax
+        self.x2= xmin
+        self.y1= ymax
+        self.y2= ymin
+        try:
+            # Inner circle marker
+            self.inner_marker = self.axes.plot([self.x1],[0], linestyle='',
+                                          marker='s', markersize=10,
+                                          color=self.color, alpha=0.6,
+                                          pickradius=5, label="pick", 
+                                          zorder=zorder, # Prefer this to other lines
+                                          visible=True)[0]
+        except:
+            self.inner_marker = self.axes.plot([self.x1],[0], linestyle='',
+                                          marker='s', markersize=10,
+                                          color=self.color, alpha=0.6,
+                                          label="pick", 
+                                          visible=True)[0]
+            message  = "\nTHIS PROTOTYPE NEEDS THE LATEST VERSION OF MATPLOTLIB\n"
+            message += "Get the SVN version that is at least as recent as June 1, 2007"
+            
+        self.line = self.axes.plot([self.x1,self.x2],[self.y1,self.y2],
+                                      linestyle='-', marker='',
+                                      color=self.color,
+                                      visible=True)[0]
+      
+        self.has_move=False
+        self.connect_markers([self.line, self.inner_marker])
+        self.update()
+
+    def set_layer(self, n):
+        self.layernum = n
+        self.update()
+        
+    def clear(self):
+        self.clear_markers()
+        try:
+            
+            self.line.remove()
+        except:
+            # Old version of matplotlib
+            for item in range(len(self.axes.lines)):
+                del self.axes.lines[0]
+   
+    
+    def get_radius(self):
+        return 0
+    
+    def update(self,xmin=None,xmax=None,ymin=None, ymax=None, opline=None,translation=False):
+        """
+        Draw the new roughness on the graph.
+        """
+
+   
+        if xmin!=None:
+            self.x1=xmin
+        if ymin!=None:
+            self.y1=ymin
+        self.inner_marker.set(xdata=[self.x1],ydata=[0]) 
+        self.line.set(xdata=[self.x1,self.x1],
+                       ydata=[self.y1,-self.y1]) 
+        
+    
+        
+    def save(self, ev):
+        """
+        Remember the roughness for this layer and the next so that we
+        can restore on Esc.
+        """
+        self.save_x1= self.x1
+        self.save_x2= self.x2
+        self.save_y1= self.y1
+        self.save_y2= self.y2
+        
+        self.base.freeze_axes()
+
+    def moveend(self, ev):
+        
+        self.has_move=False
+        self.base.moveend(ev)
+            
+    def restore(self):
+        """
+        Restore the roughness for this layer.
+        """
+        self.x1 = self.save_x1
+        self.x2 = self.save_x2
+        self.y1 = self.save_y1
+        self.y2= self.save_y2
+      
+        
+    def move(self, x, y, ev):
+        """
+        Process move to a new position, making sure that the move is allowed.
+        """
+        self.has_move=True
+        
+        # compute the b intercept of the vertical line
+        self.x1= x
+        
+        
+        self.base.base.update()
+        
+        
+    def set_cursor(self, x, y):
+        self.move(x, y, None)
+        self.update()
+        
+        
+    def get_params(self):
+        params = {}
+        params["x"] = self.xmin
+        params["ymin"] = self.ymin
+        params["ymax"] = self.ymax
+        return params
+    
+    def set_params(self, params):
+        """
+            Draw a vertical line given some value of params
+            @param params: a dictionary containing value for x, ymin , ymax to draw 
+            a vertical line
+        """
+        x = params["x"] 
+        ymin = params["ymin"] 
+        ymax = params["ymax"] 
+        #self.set_cursor(x, self._inner_mouse_y)
+        self.update(self,x =x,ymin =ymin, ymax =ymax)
+        
+
+class BoxInteractorX(BoxInteractor):
+    def __init__(self,base,axes,color='black', zorder=3):
+        BoxInteractor.__init__(self, base, axes, color=color)
+        self.base=base
+        self._post_data()
+    def _post_data(self):
+        from DataLoader.manipulations import SlabX
+        self.post_data(SlabX )   
+        
+
+class BoxInteractorY(BoxInteractor):
+    def __init__(self,base,axes,color='black', zorder=3):
+        BoxInteractor.__init__(self, base, axes, color=color)
+        self.base=base
+        self._post_data()
+    def _post_data(self):
+        from DataLoader.manipulations import SlabY
+        self.post_data(SlabY )   
+        
+        
Index: guiframe/local_perspectives/plotting/old_detector_dialog.py
===================================================================
--- guiframe/local_perspectives/plotting/old_detector_dialog.py	(revision 6d920cd2a2b96abc4845a5766911d8ef7fe5adc5)
+++ guiframe/local_perspectives/plotting/old_detector_dialog.py	(revision 6d920cd2a2b96abc4845a5766911d8ef7fe5adc5)
@@ -0,0 +1,207 @@
+#!/usr/bin/env python
+
+# version
+__id__ = "$Id: aboutdialog.py 1193 2007-05-03 17:29:59Z dmitriy $"
+__revision__ = "$Revision: 1193 $"
+
+import wx
+from sans.guiframe.utils import format_number
+from sans.guicomm.events import StatusEvent ,NewPlotEvent,SlicerEvent
+class DetectorDialog(wx.Dialog):
+    """
+        Dialog box to let the user edit detector settings
+    """
+    
+    def __init__(self,parent,id=1,base=None, *args, **kwds):
+
+        kwds["style"] = wx.DEFAULT_DIALOG_STYLE
+        wx.Dialog.__init__(self,parent,id=1, *args, **kwds)
+        self.parent=base
+        self.label_xnpts = wx.StaticText(self, -1, "Detector width in pixels")
+        self.label_ynpts = wx.StaticText(self, -1, "Detector Height in pixels")
+        self.label_qmax = wx.StaticText(self, -1, "Q max")
+        self.label_zmin = wx.StaticText(self, -1, "Min amplitude for color map (optional)")
+        self.label_zmax = wx.StaticText(self, -1, "Max amplitude for color map (optional)")
+        self.label_beam = wx.StaticText(self, -1, "Beam stop radius in units of q")
+        #self.label_sym  = wx.StaticText(self, -1, 'Use 4-fold symmetry')
+        
+        # Npts, q max
+        #self.npts_ctl = wx.TextCtrl(self, -1, size=(60,20))
+        #self.qmax_ctl = wx.TextCtrl(self, -1, size=(60,20))
+        #self.beam_ctl = wx.TextCtrl(self, -1, size=(60,20))
+        self.xnpts_ctl = wx.StaticText(self, -1, "")
+        self.ynpts_ctl = wx.StaticText(self, -1, "")
+        self.qmax_ctl = wx.StaticText(self, -1, "")
+        self.beam_ctl = wx.StaticText(self, -1, "")
+        
+        self.zmin_ctl = wx.TextCtrl(self, -1, size=(60,20))
+        self.zmax_ctl = wx.TextCtrl(self, -1, size=(60,20))
+        #self.chk_sym  = wx.CheckBox(self, -1, '')
+
+        self.static_line_3 = wx.StaticLine(self, -1)
+        
+        
+        self.button_OK = wx.Button(self, wx.ID_OK, "OK")
+        self.button_Cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
+        self.Bind(wx.EVT_BUTTON, self.checkValues, self.button_OK)
+
+        self.__set_properties()
+        self.__do_layout()
+
+        self.Fit()
+        
+    class Event:
+        xnpts = 0
+        ynpts = 0
+        qpax = 0
+        beam = 0
+        zmin = 0
+        zmax = 0
+        sym4 = False
+        
+    def checkValues(self, event):
+        flag = True
+        try:
+            value=self.zmin_ctl.GetValue()
+            if value and float( value)==0.0:
+                flag = False
+                wx.PostEvent(self.parent, StatusEvent(status="Enter number greater than zero"))
+                self.zmin_ctl.SetBackgroundColour("pink")
+                self.zmin_ctl.Refresh()
+            else:
+                self.zmin_ctl.SetBackgroundColour(wx.WHITE)
+                self.zmin_ctl.Refresh()
+        except:
+            flag = False
+            wx.PostEvent(self.parent, StatusEvent(status="Enter float value"))
+            self.zmin_ctl.SetBackgroundColour("pink")
+            self.zmin_ctl.Refresh()
+        try:
+            value=self.zmax_ctl.GetValue()
+            if value and int(value)==0.0:
+                flag = False
+                wx.PostEvent(self.parent, StatusEvent(status="Enter number greater than zero"))
+                self.zmax_ctl.SetBackgroundColour("pink")
+                self.zmax_ctl.Refresh()
+            else:
+                self.zmax_ctl.SetBackgroundColour(wx.WHITE)
+                self.zmax_ctl.Refresh()
+        except:
+            flag = False
+            wx.PostEvent(self.parent, StatusEvent(status="Enter Integer value"))
+            self.zmax_ctl.SetBackgroundColour("pink")
+            self.zmax_ctl.Refresh()
+        
+        if flag:
+            event.Skip(True)
+    
+    def setContent(self, xnpts,ynpts, qmax, beam,zmin=None,zmax=None, sym=False):
+        self.xnpts_ctl.SetLabel(str(format_number(xnpts)))
+        self.ynpts_ctl.SetLabel(str(format_number(ynpts)))
+        self.qmax_ctl.SetLabel(str(format_number(qmax)))
+        self.beam_ctl.SetLabel(str(format_number(beam)))
+        #self.chk_sym.SetValue(sym)
+        if zmin !=None:
+            self.zmin_ctl.SetValue(str(format_number(zmin)))
+        if zmax !=None:
+            self.zmax_ctl.SetValue(str(format_number(zmax)))
+
+    def getContent(self):
+        event = self.Event()
+        #event.npts = int(self.npts_ctl.GetValue())
+        #event.qmax = float(self.qmax_ctl.GetValue())
+        #event.beam = float(self.beam_ctl.GetValue())
+        #event.sym4 = self.chk_sym.GetValue()
+        
+        t_min = self.zmin_ctl.GetValue()
+        t_max = self.zmax_ctl.GetValue()
+        v_min = None
+        v_max = None
+        
+        if len(t_min.lstrip())>0:
+            try:
+                v_min = float(t_min)
+            except:
+                v_min = None
+        
+        if len(t_max.lstrip())>0:
+            try:
+                v_max = float(t_max)
+            except:
+                v_max = None
+        
+        event.zmin = v_min
+        event.zmax = v_max
+        
+        return event
+
+    def __set_properties(self):
+        self.SetTitle("Detector parameters")
+        self.SetSize((600, 595))
+
+    def __do_layout(self):
+        sizer_main = wx.BoxSizer(wx.VERTICAL)
+        sizer_button = wx.BoxSizer(wx.HORIZONTAL)
+        sizer_params = wx.GridBagSizer(5,5)
+
+        iy = 0
+        sizer_params.Add(self.label_xnpts, (iy,0), (1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        sizer_params.Add(self.xnpts_ctl,   (iy,1), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        iy += 1
+        sizer_params.Add(self.label_ynpts, (iy,0), (1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        sizer_params.Add(self.ynpts_ctl,   (iy,1), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        iy += 1
+        sizer_params.Add(self.label_qmax, (iy,0), (1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        sizer_params.Add(self.qmax_ctl,   (iy,1), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        iy += 1
+        sizer_params.Add(self.label_beam, (iy,0), (1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        sizer_params.Add(self.beam_ctl,   (iy,1), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        iy += 1
+        sizer_params.Add(self.label_zmin, (iy,0), (1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        sizer_params.Add(self.zmin_ctl,   (iy,1), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        iy += 1
+        sizer_params.Add(self.label_zmax, (iy,0), (1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        sizer_params.Add(self.zmax_ctl,   (iy,1), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        iy += 1
+        #sizer_params.Add(self.label_sym,  (iy,0), (1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        #sizer_params.Add(self.chk_sym,    (iy,1), (1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+
+        sizer_main.Add(sizer_params, 0, wx.EXPAND|wx.ALL, 10)
+        sizer_main.Add(self.static_line_3, 0, wx.EXPAND, 0)
+        
+        
+        sizer_button.Add((20, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        sizer_button.Add(self.button_OK, 0, wx.LEFT|wx.ADJUST_MINSIZE, 10)
+        sizer_button.Add(self.button_Cancel, 0, wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)
+        
+        
+        sizer_main.Add(sizer_button, 0, wx.EXPAND|wx.BOTTOM|wx.TOP, 10)
+        self.SetAutoLayout(True)
+        self.SetSizer(sizer_main)
+        self.Layout()
+        self.Centre()
+        # end wxGlade
+
+
+# end of class DialogAbout
+
+##### testing code ############################################################
+class MyApp(wx.App):
+    def OnInit(self):
+        wx.InitAllImageHandlers()
+        dialog = DetectorDialog(None, -1, "")
+        self.SetTopWindow(dialog)
+        dialog.setContent(128, 0.05)
+        print dialog.ShowModal()
+        evt = dialog.getContent()
+        print evt.npts, evt.qmax
+        dialog.Destroy()
+        return 1
+
+# end of class MyApp
+
+if __name__ == "__main__":
+    app = MyApp(0)
+    app.MainLoop()
+    
+##### end of testing code #####################################################    
Index: guiframe/local_perspectives/plotting/plotting.py
===================================================================
--- guiframe/local_perspectives/plotting/plotting.py	(revision 50cbacefffa06e9b3fc1977ff378587f5f0b9b7a)
+++ guiframe/local_perspectives/plotting/plotting.py	(revision 6d920cd2a2b96abc4845a5766911d8ef7fe5adc5)
@@ -108,8 +108,7 @@
                         is_available = True
                         
-                        
                         panel._onEVT_1DREPLOT(event)
                         self.parent.show_panel(panel.uid)
-                        print "went here for replottiing", event.plot.name
+                        #print "went here for replottiing", event.plot.name
                         
                 else:
@@ -125,5 +124,5 @@
                 from Plotter1D import ModelPanel1D
                 if hasattr(event.plot,"xtransform"):
-                    print "went here"
+                    #print "went here"
                     xtransform = event.plot.xtransform
                 else:
Index: guiframe/model_thread.py
===================================================================
--- guiframe/model_thread.py	(revision 700f9b484abb7a4e73e5c999b745a31e1f731c2b)
+++ guiframe/model_thread.py	(revision 6d920cd2a2b96abc4845a5766911d8ef7fe5adc5)
@@ -163,5 +163,5 @@
                        "Error computing %s at [%g,%g]" %(self.model.name, self.x[i_x],self.y[i_y])))
                      pass
-        print "model thread ouput",output       
+        #print "model thread ouput",output       
         elapsed = time.time()-self.starttime
         self.complete(
Index: iframe/state.py
===================================================================
--- guiframe/state.py	(revision ca88b2eded93a483ace5848e87ba70d47c410949)
+++ 	(revision )
@@ -1,217 +1,0 @@
-"""
-    Object to manage the state of the application
-"""
-
-#TODO: use both CPUs and break the calculations in two threads
-#TODO: stop threads before starting a new one
-
-import wx
-import wx.lib.newevent
-
-import ModelParameters
-import history
-import modelData
-from model_thread import Calc2D, Calc1D, Calc2D_4fold, Calc2D_all
-from copy import deepcopy
-
-#TODO: State should report back to StateManager instead
-#    of firing these events itself
-(Refresh2DEvent, EVT_2DREFRESH) = wx.lib.newevent.NewEvent()
-(Refresh1DEvent, EVT_1DREFRESH) = wx.lib.newevent.NewEvent()
-
-# Debug printout
-from config import printEVT
-
-
-
-class State:
-    
-    def __init__(self, target=None, model=None, slicer=None):
-        self.target = target
-        self.model  = model
-        self.slicer = slicer
-        self.model_par_memento = None
-        self.detector_memento = None
-        self.averager_memento = None
-        self.pars1D_memento   = None
-        
-        # Keep the latest data 
-        self._data_2D = None
-        self._data_1D = None
-        # The following should disappear
-        self.qmax = None
-        self.x_1D = None
-        
-        # Threads
-        self.active = True
-        self.calc_thread_2D = None
-        self.calc_thread_1D = None
-        
-        # Info for history
-        self.description = ''
-        
-    def clone(self):
-        obj          = State(self.target, self.model.clone(), self.slicer)
-        obj._data_1D = deepcopy(self._data_1D)
-        obj._data_2D = deepcopy(self._data_2D)
-        obj.qmax     = deepcopy(self.qmax)
-        obj.x_1D     = deepcopy(self.x_1D)
-        obj.model_par_memento = deepcopy(self.model_par_memento)
-        obj.detector_memento = deepcopy(self.detector_memento)
-        obj.averager_memento = deepcopy(self.averager_memento)
-        obj.description = self.description
-        return obj
-        
-    def clear_data(self):
-        self._data_1D = None
-        self._data_2D = None
-        
-    def stop(self):
-        self.active = False
-        if self.calc_thread_1D != None and self.calc_thread_1D.isrunning():
-            self.calc_thread_1D.stop()
-        if self.calc_thread_2D != None and self.calc_thread_2D.isrunning():
-            self.calc_thread_2D.stop()
-        
-    def setModelParMemento(self, memento):
-        self.model_par_memento = memento
-        
-    def setDetectorMemento(self, memento):
-        self.clear_data()
-        # Change description
-        self.description = '%s' % memento.toString(self.detector_memento)
-        self.detector_memento = memento
-        
-    def setPars1DMemento(self, memento):
-        self.clear_data()
-        # Change description
-        self.description = '%s' % memento.toString(self.pars1D_memento)
-        self.pars1D_memento = memento
-        
-    def setAveragerMemento(self, memento):
-        self.clear_data()
-        self.averager_memento = memento
-        
-    def setModel(self, model):
-        """
-            Set the model and send a history event
-        """
-        # Clean the data to invoke recalc
-        self._data_1D = None
-        self._data_2D = None
-        
-        # Set the model 
-        self.model = model
-        
-        self.description = ''
-        
-        return str(self.model.name)
-        
-    def setParams(self, params):
-        """
-            Update parameters and return a name
-            that represents the change (key)
-        """
-        # Clean the data to invoke recalc
-        self._data_1D = None
-        self._data_2D = None
-
-        # Compose string to summarize change        
-        name = self.model.name
-        
-        # Identify and perform changes
-        for item in params:
-            name += "/%s=%-5.5g" % (item, self.model.getParam(item))
-            self.model.setParam(item, params[item])
-        
-        return name
-
-    def setSlicer(self, slicer):
-        self.slicer = slicer
-        
-    def get_data_1d(self, x):
-        """
-            Calculate the data 
-            @param min: minimum q-value
-            @param max: maximum q-value
-        """
-        
-        printEVT("State.get_data_1d")
-        if not self.model:
-            return
-        
-        if self._data_1D == None:
-            self.x_1D = deepcopy(x)
-            if self.calc_thread_1D != None and self.calc_thread_1D.isrunning():
-                self.calc_thread_1D.stop()
-                
-            self.calc_thread_1D = Calc1D(x, self.model.clone(), 
-                                completefn=self.complete1D,
-                                updatefn=self.update1D)
-            self.calc_thread_1D.queue()
-            self.calc_thread_1D.ready(2.5)
-        else:
-            printEVT("Dispatch 1D non-recalc data") 
-            wx.PostEvent(self.target, Refresh1DEvent(name=self.model.name, x = self.x_1D,
-                                                     output=deepcopy(self._data_1D)))
-         
-    
-    def get_data_2d(self, max, x, y):
-        """ 
-            Calculate 2D data
-            @param max: maximum q-value
-        """
-        if not self.model:
-            return
-        
-        if self._data_2D == None:
-            self.qmax = max
-            if self.calc_thread_2D != None and self.calc_thread_2D.isrunning():
-                self.calc_thread_2D.stop()
-                
-            if self.detector_memento == None or self.detector_memento.sym4 == False:    
-                self.calc_thread_2D = Calc2D(x, y, self.model.clone(), 
-                                    completefn=self.complete2D,
-                                    updatefn=self.update2D,
-                                    yieldtime=0.0)
-            else:
-                self.calc_thread_2D = Calc2D_4fold(x, y, self.model.clone(), 
-                                    completefn=self.complete2D,
-                                    updatefn=self.update2D,
-                                    yieldtime=0.0)
-                
-            self.calc_thread_2D.queue()
-            self.calc_thread_2D.ready(2.5)
-        else:
-            printEVT("Dispatch 2D non-recalc data") 
-            wx.PostEvent(self.target, Refresh2DEvent(output=deepcopy(self._data_2D),
-                                                    qmax=self.qmax))
-            
-             
-    def update2D(self, output):
-        printEVT("State.updated2D")
-        if self.active:
-            #self._data_2D = output
-            self._data_2D = deepcopy(output)
-            wx.PostEvent(self.target, Refresh2DEvent(output=deepcopy(self._data_2D),
-                                                qmax=self.qmax))
-    
-    def complete2D(self, output, elapsed):
-        printEVT("%s: Calc 2D complete in %g sec" % (self.model.name, elapsed)) 
-        if self.active:
-            self._data_2D = deepcopy(output)
-            wx.PostEvent(self.target, Refresh2DEvent(output=deepcopy(self._data_2D),
-                                                qmax=self.qmax))
-        else:
-            printEVT("Active = False!")
-
-    def update1D(self, output):
-        pass
-    
-    def complete1D(self, output, elapsed):
-        printEVT("Calc 1D complete in %g sec" % elapsed) 
-        self._data_1D = deepcopy(output)
-        wx.PostEvent(self.target, Refresh1DEvent(name=self.model.name, x = self.x_1D,
-                                                 output=deepcopy(self._data_1D)))
-
-    
Index: iframe/stateManager.py
===================================================================
--- guiframe/stateManager.py	(revision ca88b2eded93a483ace5848e87ba70d47c410949)
+++ 	(revision )
@@ -1,323 +1,0 @@
-"""
-    Object to manage the state of the application
-"""
-
-import wx
-import wx.lib.newevent
-
-import ModelParameters
-import AveragerParameters
-import Averager2D
-import history
-import modelData
-from model_thread import Calc2D
-from copy import deepcopy
-from fitting import ChiUpdateEvent 
-
-(Refresh2DEvent, EVT_2DREFRESH) = wx.lib.newevent.NewEvent()
-
-# Debug printout
-from config import printEVT
-import config
-from state import State
-import Plotter1D
-import Plotter2D
-
-(StateEvent, EVT_STATE)   = wx.lib.newevent.NewEvent()
-
-class DetectorMemento:
-    def __init__(self, qmax=0.1, npts=10, beam=None, zmin=None, zmax=None, sym4=False):
-        self.qmax = qmax
-        self.npts = npts
-        self.zmin = zmin
-        self.zmax = zmax
-        self.beam = beam
-        self.sym4 = sym4
-        
-    def toString(self, memento):
-        """
-            Return a string that describes the difference
-            between the given memento and the current one
-            @param memento: memento to compare to
-            @return: string
-        """
-        if memento == None:
-            return "/Qmax = %g/Det npts = %g" % (self.qmax, self.npts)
-        else:
-            descr = ''
-            if not memento.qmax == self.qmax:
-                descr += "/Qmax = %g" % self.qmax
-            if not memento.npts == self.npts:
-                descr += "/Det npts = %g" % self.npts
-            if not self.zmin==None and not memento.zmin == self.zmin:
-                descr += "/Zmin = %g" % self.zmin
-            if self.zmax and not memento.zmax == self.zmax:
-                descr += "/Zmax = %g" % self.zmax
-            if not memento.beam == self.beam:
-                descr += "/beamstop = %g" % self.beam
-            return descr
-
-class StateManager:
-    
-    def __init__(self, target=None, model=None, slicer=None):
-        self.target = target
-        self.state  = State(target, model, slicer)
-        
-        # Listen to parameter changes to fire history events
-
-        self.target.Bind(ModelParameters.EVT_MODEL_PARS, self._onEVT_MODEL_PARS)
-        self.target.Bind(AveragerParameters.EVT_AVG_PARS, self._onEVT_AVG_PARS)
-        self.target.Bind(EVT_STATE, self._onEVT_STATE)
-        self.target.Bind(Plotter2D.EVT_DETECTOR, self._onEVT_DETECTOR)
-        self.target.Bind(Plotter1D.EVT_PLOT1D_PARS, self._onEVT_PLOT1D_PARS)
-                
-    def setModel(self, target, model, tag=''):
-        """
-            Set the model and send a history event
-        """
-        # Prepare the restore event
-        self._saveCurrent(tag)
-        
-        # Now change the model
-        self.state.setModel(model)
-        evt = ModelParameters.ModelEvent(model=model, data=self.state, new=True)
-        wx.PostEvent(target, evt)
-        # Posting averager state
-        wx.PostEvent(target, AveragerParameters.AveragerStateEvent(memento=AveragerParameters.AveragerParameterMemento()))
-        
-    def _saveCurrent(self, tag=''):
-        """
-            Send a history event to capture the current state
-        """
-        #TODO: need a way to find the difference between old and new model
-        if not self.state.model == None:
-            stored_event = StateEvent(state = self.state.clone())
-            
-            # Send the history event
-            evt = history.HistoryEvent(name = self.state.model.name+'%s/%s' % (self.state.description, tag),
-                                       item = stored_event)
-            wx.PostEvent(self.target, evt)
-        
-        
-    def setSlicer(self, slicer):
-        """
-            Set the slicer
-        """
-        printEVT("StateManager.setSlicer: Slicer not implmeted")
-        self.state.slicer = slicer
-        
-    def _onEVT_STATE(self, event):
-        """
-            Restor a stored state
-            @param event: state event
-        """
-        self.state.stop()
-        self.state = event.state.clone()
-        
-        # Posting detector parameter panel state event
-        if not self.state.detector_memento == None:
-            det_event = Plotter2D.createDetectorParsEvent(qmax=self.state.detector_memento.qmax,
-                                                          npts=self.state.detector_memento.npts,
-                                                          beam=self.state.detector_memento.beam,
-                                                          zmin=self.state.detector_memento.zmin,
-                                                          zmax=self.state.detector_memento.zmax,
-                                                          sym4=self.state.detector_memento.sym4,
-                                                          info_only=True)
-        else:
-            det_event = Plotter2D.createDetectorParsEvent(qmax=None,
-                                                          npts=None,
-                                                          info_only=True)
-        printEVT("StateManager: posting detector memento")
-        wx.PostEvent(self.target, det_event)
-        
-        # Posting 1D plot parameters
-        if not self.state.pars1D_memento == None:
-            pars1D_event = Plotter1D.createPlot1DParsEvent(qmax=self.state.pars1D_memento.qmax,
-                                                           npts=self.state.pars1D_memento.npts,
-                                                           qmin=self.state.pars1D_memento.qmin,
-                                                           info_only=True)
-        else:
-            pars1D_event = Plotter1D.createPlot1DParsEvent(qmin=None,
-                                                           qmax=None,
-                                                           npts=None,
-                                                           info_only=True)
-        printEVT("StateManager: posting 1D plot pars memento")
-        wx.PostEvent(self.target, pars1D_event)
-        
-        
-        # Posting averager state
-        wx.PostEvent(self.target, AveragerParameters.AveragerStateEvent(memento=event.state.averager_memento))
-        
-        # Posting model event
-        evt = ModelParameters.ModelEvent(model=self.state.model, data=self.state, new=True)
-        wx.PostEvent(self.target, evt)
-        
-        # Posting parameter panel state event
-        evt2 = ModelParameters.ModelParameterStateEvent(memento=event.state.model_par_memento)
-        wx.PostEvent(self.target, evt2)
-        
-        printEVT("State.onEVT_STATE: history item restored: %s" % self.state.model.name)
-        
-    def _onEVT_DETECTOR(self, event):
-        config.printEVT("StateManager._onEVT_DETECTOR")
-        if event.info_only:
-            config.printEVT("   skip EVT_DETECTOR")
-            return
-        
-        event.Skip()
-        self._saveCurrent()
-        
-        # Clear current data to invoke recalculation
-        #self.state.clear_data()
-        self.state.setDetectorMemento(DetectorMemento(event.qmax, event.npts,
-                                                      zmin = event.zmin, zmax = event.zmax,
-                                                      beam = event.beam, sym4 = event.sym4))
-        
-        # Send an update event to the plotters
-        evt = ModelParameters.ModelEvent(model=self.state.model, data=self.state, new=False)
-        wx.PostEvent(self.target, evt)
-
-    def _onEVT_PLOT1D_PARS(self, event):
-        config.printEVT("StateManager._onEVT_PLOT1D_PARS")
-        if event.info_only:
-            config.printEVT("   skip EVT_PLOT1D_PARS")
-            return
-        
-        event.Skip()
-        self._saveCurrent()
-        
-        # Update the state
-        self.state.setPars1DMemento(Plotter1D.Plot1DMemento(event.qmin, 
-                                                              event.qmax, 
-                                                              event.npts))
-        
-        # Send an update event to the plotters
-        evt = ModelParameters.ModelEvent(model=self.state.model, data=self.state, new=False)
-        wx.PostEvent(self.target, evt)
-
-        
-    def _onEVT_MODEL_PARS(self, event):
-        """
-            Modify the parameters of the model and
-            fire a history event
-            
-            @param event: parameter change event
-        """
-        printEVT("State.onEVT_MODEL_PARS")
-
-        # Save the state before changing it
-        stored_event = StateEvent(state = self.state.clone())
-
-        # Post message to status bar
-        wx.PostEvent(self.target, config.StatusBarEvent(message=event.status))
-        
-        # Dispersion?
-        disp_tag = ''
-        if event.disp_changed and len(event.disp)>0:
-            if not self.state.model.__class__.__name__ == "Averager2D":
-                config.printEVT("StateMng: setting up averager")
-                new_model = Averager2D.Averager2D()
-                flag = new_model.set_model(self.state.model.clone())
-                self.state.setModel(new_model)
-            else:
-                disp_list = deepcopy(self.state.model.get_dispersity())
-                for item in disp_list:
-                    disp_tag += '/Disp[%s]=%g [%g pts]' % (item[0], item[1], item[2])
-                
-            self.state.model.set_dispersity(event.disp)
-            
-        if not event.average and \
-            self.state.model.__class__.__name__ == "Averager2D":
-            disp_list = deepcopy(self.state.model.get_dispersity())
-            if self.state.model.set_dispersity([]):
-                for item in disp_list:
-                    disp_tag += '/Disp[%s]=%g [%g pts]' % (item[0], item[1], item[2])
-        
-        # Push parameters to model
-        name = self.state.setParams(event.params)
-        self.state.setModelParMemento(event.memento)
-
-        #print str(self.state.model)
-
-        # Send an update event to the plotters
-        evt = ModelParameters.ModelEvent(model=self.state.model, data=self.state, new=False)
-        wx.PostEvent(self.target, evt)
-
-        if len(event.params)>0 or len(event.disp)>0 or event.disp_changed:      
-            # Send the history event
-            evt = history.HistoryEvent(name = name+disp_tag,
-                                       item = stored_event)
-            wx.PostEvent(self.target, evt)
-            
-            # Post chi^2 recalculation event for fit panel
-            wx.PostEvent(self.target, ChiUpdateEvent())
-            
-    def _onEVT_AVG_PARS(self, event):
-        printEVT("State._onEVT_AVG_PARS")
-
-        # Save the state before changing it
-        stored_event = StateEvent(state = self.state.clone())
-        
-        # Inspect the change to give a proper title to the 
-        # history item
-        info = "Phi = OFF/THETA=ON (filename)"
-        
-        # Set averager memento to retreive the same state from history panel
-        self.state.setAveragerMemento(event.memento)
-        
-        # Flags for history event
-        phi_flag   = "OFF"
-        theta_flag = "OFF"
-                    
-        #theta_file = os.path.basename(self.theta_file_path)
-        
-        # Post message to status bar if needed
-        if not event.status == None:
-             wx.PostEvent(self.target, config.StatusBarEvent(message=event.status))
-            
-        # Check if we already have an Averager2D model
-        # When we reach this points, either we need an Averager2D 
-        # or we already have one.
-        if not self.state.model.__class__.__name__ == "Averager2D":
-            model = Averager2D.Averager2D()
-            flag = model.set_model(self.state.model.clone())
-            if flag:
-                self.state.setModel(model)                        
-            else:
-                message = "Current model doesn't have theta or phi: skipping"
-                wx.PostEvent(self.target, config.StatusBarEvent(message=message))
-                return
-        else:
-            if self.state.model.phi_on:
-                phi_flag = "ON"
-            if self.state.model.theta_on:
-                theta_flag = "ON"
-            
-        # Set phi info
-        if event.phi_on:
-            if not self.state.model.setPhiFile(event.phi_file):
-                message = "Current model doesn't have phi: skipping"
-                wx.PostEvent(self.target, config.StatusBarEvent(message=message))
-        else:
-            self.state.model.setPhiFile(None)
-        
-        # Set theta info
-        if event.theta_on:
-            if not self.state.model.setThetaFile(event.theta_file):
-                message = "Current model doesn't have phi: skipping"
-                wx.PostEvent(self.target, config.StatusBarEvent(message=message))                
-        else:
-            self.state.model.setThetaFile(None)
-        
-        # Send the history event
-        hist_evt = history.HistoryEvent(name = "%s/Phi %s/Theta %s" % \
-                                        (self.state.model.name, phi_flag, theta_flag),
-                                   item = stored_event)
-        wx.PostEvent(self.target, hist_evt)
-        
-        # Send an update event to the plotters
-        evt = ModelParameters.ModelEvent(model=self.state.model, data=self.state, new=False)
-        wx.PostEvent(self.target, evt)
-
-            
-            
