Index: sansview/perspectives/fitting/fit_thread.py
===================================================================
--- sansview/perspectives/fitting/fit_thread.py	(revision c138160dcc63309fdadb0528422eee7750eda56e)
+++ sansview/perspectives/fitting/fit_thread.py	(revision ed2ea6affd15bc8ac6492c7f3afba6be6f2a899f)
@@ -8,8 +8,4 @@
 DEFAULT_BEAM = 0.005
 import time
-
-import thread
-print "main",thread.get_ident()
-
  
 class ConsoleUpdate(FitHandler):
@@ -53,5 +49,5 @@
             
             wx.PostEvent(self.parent, StatusEvent(status=\
-             "%d%% complete ..."%(p)))
+             "%d%% complete ..."%(p),type="update"))
        
         # Update percent complete
@@ -61,25 +57,21 @@
         if dt > self.progress_delta:
             if 1 <= dp <= 2:
-                print "%d%% complete"%p
                 self.progress_percent = p
                 self.progress_time = t
                 wx.PostEvent(self.parent, StatusEvent(status=\
-                                                      "%d%% complete ..."%(p)))
+                                                      "%d%% complete ..."%(p),type="update"))
        
             elif 2 < dp <= 5:
                 if p//5 != self.progress_percent//5:
-                    print "%d%% complete"%(5*(p//5))
                     wx.PostEvent(self.parent, StatusEvent(status=\
-                       "%d%% complete ..."%(5*(p//5))))
+                       "%d%% complete ..."%(5*(p//5)),type="update"))
                     self.progress_percent = p
                     self.progress_time = t
             else:
                 if p//10 != self.progress_percent//10:
-                    print "%d%% complete"%(10*(p//10))
-                    
                     self.progress_percent = p
                     self.progress_time = t
                     wx.PostEvent(self.parent, StatusEvent(status=\
-                   "%d%% complete ..."%(10*(p//10))))
+                   "%d%% complete ..."%(10*(p//10)),type="update"))
         
     def improvement(self):
@@ -107,5 +99,5 @@
 
 class FitThread(CalcThread):
-    """Compute 2D data"""
+    """Thread performing the fit """
     
     def __init__(self,parent, fn,pars=None,cpage=None, qmin=None,qmax=None,ymin=None, ymax=None,
@@ -135,29 +127,35 @@
                        "Start the computation  ",curr_thread=self,type="start"))
     def isquit(self):
+        """
+             @raise KeyboardInterrupt: when the thread is interrupted
+        """
         try:
             CalcThread.isquit(self)
         except KeyboardInterrupt:
-            #printEVT("Calc %s interrupted" % self.model.name)
             wx.PostEvent(self.parent, StatusEvent(status=\
-                       "Calc %g interrupted" % time.time()))
-           
+                       "Calc %g interrupted"))
             raise KeyboardInterrupt
         
     def update(self):
-        print "updatting"
-        elapsed = time.time()-self.starttime
+        """
+            Is called when values of result are available
+        """
         wx.PostEvent(self.parent, StatusEvent(status="Computing \
         ... " ,curr_thread=self,type="update"))
             
     def compute(self):
+        """
+            Perform a fit 
+        """
         try: 
             self.starttime = time.time()
+            #Sending a progess message to the status bar
             wx.PostEvent(self.parent, StatusEvent(status=\
                        "Computing . ...",curr_thread=self,type="progress"))
+            #Handler used for park engine displayed message
             handler= ConsoleUpdate(parent= self.parent,improvement_delta=0.1)
+            #Result from the fit
             result = self.fitter.fit(handler= handler)
-            print "result", result
-           
-            print "in my compute function"
+        
             elapsed = time.time()-self.starttime
             self.complete(result= result,
@@ -174,5 +172,4 @@
             # Thread was interrupted, just proceed and re-raise.
             # Real code should not print, but this is an example...
-            print "Thread stopped. "
             raise
         except:
Index: sansview/perspectives/fitting/fitpage1D.py
===================================================================
--- sansview/perspectives/fitting/fitpage1D.py	(revision 169fb5fff17a84360ddddf4173e43ce256cde561)
+++ sansview/perspectives/fitting/fitpage1D.py	(revision ed2ea6affd15bc8ac6492c7f3afba6be6f2a899f)
@@ -41,5 +41,5 @@
         #panel interface
         self.vbox  = wx.BoxSizer(wx.VERTICAL)
-        #self.sizer10 = wx.GridBagSizer(5,5)
+    
         self.sizer9 = wx.GridBagSizer(5,5)
         self.sizer8 = wx.GridBagSizer(5,5)
@@ -253,20 +253,5 @@
         iy+=1 
         self.sizer9.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-        #----------sizer 10 draw------------------------------------------------------
-        """
-        id = wx.NewId()
-        self.btClose =wx.Button(self,id,'Close')
-        self.btClose.Bind(wx.EVT_BUTTON, self.onClose,id=id)
-        self.btClose.SetToolTipString("Close page.")
-        
-        ix= 3
-        iy= 1
-        self.sizer10.Add((20,20),(iy,ix),(1,1),wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
-        ix +=1
-        self.sizer10.Add( self.btClose,(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
-        ix =0
-        iy+=1
-        self.sizer10.Add((20,20),(iy,ix),(1,1),wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
-       """
+        
         # contains link between  model ,all its parameters, and panel organization
         self.parameters=[]
@@ -349,5 +334,5 @@
         
         flag=self.checkFitRange()
-        print "flag", flag
+        #print "flag", flag
         if flag== True:
             try:
Index: sansview/perspectives/fitting/fitpanel.py
===================================================================
--- sansview/perspectives/fitting/fitpanel.py	(revision 3199b5919bd1edc326db1180d59ac6aafd7bb0de)
+++ sansview/perspectives/fitting/fitpanel.py	(revision ed2ea6affd15bc8ac6492c7f3afba6be6f2a899f)
@@ -64,12 +64,4 @@
     def onClosePage(self, event):
         """
-        self.ToggleWindowStyle(wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB)
-        #print "went here",self.get_current_page(), self.GetPage(0)
-        #event.Skip()
-        if self.GetPageCount() <= 2:
-            #print "wente here"
-            
-            # Prevent last tab from being closed
-            self.ToggleWindowStyle(~wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB)
         """
         selected_page = self.GetPage(self.GetSelection())
@@ -93,5 +85,5 @@
                 
             if selected_page.name== self.draw_model_name:
-                print "went here"
+                #print "went here"
                 self.draw_model_name=None
                 self.model_page=None
@@ -234,5 +226,5 @@
              selected on that page. remove its reference into page_finder (fitting module)
         """
-        print "model page", page_number, page, self.draw_model_name
+        #print "model page", page_number, page, self.draw_model_name
         if page!=None and page_number!=None:
             i=self.DeletePage(page_number)
@@ -242,5 +234,5 @@
             self.model_page=None
             self.draw_model_name=None
-            print"self.draw_model_name",self.draw_model_name
+            #print"self.draw_model_name",self.draw_model_name
             return 
         try:
Index: sansview/perspectives/fitting/fitting.py
===================================================================
--- sansview/perspectives/fitting/fitting.py	(revision c98b1d58d2048813920ff9e05bd7f373ce61dbbc)
+++ sansview/perspectives/fitting/fitting.py	(revision ed2ea6affd15bc8ac6492c7f3afba6be6f2a899f)
@@ -4,23 +4,19 @@
 
 from copy import deepcopy 
-from danse.common.plottools.plottables import Data1D, Theory1D,Data2D
-from danse.common.plottools.PlotPanel import PlotPanel
+from danse.common.plottools.plottables import  Theory1D,Data2D
 from sans.guicomm.events import NewPlotEvent, StatusEvent  
-from sans.guicomm.events import EVT_SLICER_PANEL,EVT_MODEL2D_PANEL,ERR_DATA
-
-from sans.fit.AbstractFitEngine import Model,FitData1D,FitData2D#,Data,
+from sans.guicomm.events import EVT_SLICER_PANEL,ERR_DATA
+
+from sans.fit.AbstractFitEngine import Model
 from fitproblem import FitProblem
 from fitpanel import FitPanel
 from fit_thread import FitThread
-import models#,modelpage
+import models
 import fitpage1D
-#import park
+
 DEFAULT_BEAM = 0.005
 DEFAULT_QMIN = 0.0
 DEFAULT_QMAX = 0.1
 DEFAULT_NPTS = 50
-import time
-import thread
-print "main",thread.get_ident()
 
 class Plugin:
@@ -34,20 +30,21 @@
         ## Reference to the parent window
         self.parent = None
+        #Provide list of models existing in the application
         self.menu_mng = models.ModelManager()
         ## List of panels for the simulation perspective (names)
         self.perspective = []
+        #list of panel to send to guiframe
         self.mypanels=[]
+        # reference to the current running thread
         self.calc_thread = None
-        self.done = False
         # Start with a good default
         self.elapsed = 0.022
+        # the type of optimizer selected, park or scipy
         self.fitter  = None
-       
-        #Flag to let the plug-in know that it is running standalone
+        #Flag to let the plug-in know that it is running stand alone
         self.standalone=True
         ## Fit engine
         self._fit_engine = 'scipy'
-        self.enable_model2D=False
-        # list of selcted data
+        #List of selected data
         self.selected_data_list=[]
         # Log startup
@@ -55,8 +52,14 @@
         # model 2D view
         self.model2D_id=None
+        #keep reference of the simultaneous fit page
         self.sim_page=None
+        #dictionary containing data name and error on dy of that data 
         self.err_dy={}
         
     def _on_data_error(self, event):
+        """
+            receives and event from plotting plu-gins to store the data name and 
+            their errors of y coordinates for 1Data hide and show error
+        """
         self.err_dy= event.err_dy
         
@@ -68,5 +71,4 @@
             @ return : list of information to populate the main menu
         """
-        self.parent.Bind(EVT_MODEL2D_PANEL, self._on_model2D_show)
         #Menu for fitting
         self.menu1 = wx.Menu()
@@ -94,4 +96,6 @@
     
     def on_add_sim_page(self, event):
+        """
+        """
         self.sim_page= self.fit_panel.add_sim_page()
         self.sim_page.add_model(self.page_finder)
@@ -113,6 +117,4 @@
         
         
-        
-    
     def get_context_menu(self, graph=None):
         """
@@ -160,12 +162,10 @@
         self.mypanels.append(self.fit_panel)
         return self.mypanels
-    
-    
-    def _on_model2D_show(self, event ):
-        print "model2D get the id ", event.id
-        
+
         
     def _on_slicer_event(self, event):
-        print "fitting:slicer event ", event.panel
+        """
+        """
+        #print "fitting:slicer event ", event.panel
         if event.panel!=None:
             new_panel = event.panel
@@ -178,8 +178,11 @@
             new_panel
             self.mypanels.append(new_panel) 
-        return        
+        return    
+    
+        
     def _on_show_panel(self, event):
         print "_on_show_panel: fitting"
       
+      
     def get_perspective(self):
         """
@@ -205,5 +208,8 @@
         self.parent.set_perspective(self.perspective)
 
+
     def copy_data(self, item, dy):
+        """
+        """
         detector=None
         source=None
@@ -224,4 +230,5 @@
         data.source= source
         return data
+
 
     def _onSelect(self,event):
@@ -253,5 +260,5 @@
                  item.__class__.__name__ is "Data2D":
                 #find a name for the page created for notebook
-                print "fitting", self.panel
+                #print "fitting", self.panel
                 try:
                    
@@ -273,7 +280,8 @@
                         wx.PostEvent(self.parent, StatusEvent(status="Page was already Created"))
                 except:
-                    raise
-                    #wx.PostEvent(self.parent, StatusEvent(status="Creating Fit page: %s"\
-                    #%sys.exc_value))
+                    #raise
+                    wx.PostEvent(self.parent, StatusEvent(status="Creating Fit page: %s"\
+                    %sys.exc_value))
+                    return
                     
                     
@@ -311,5 +319,5 @@
                 list=value.get_model()
                 model=list[0]
-                print "fitting",model.name,modelname, values
+                #print "fitting",model.name,modelname, values
                 if model.name== modelname:
                     value.set_model_param(names,values)
@@ -360,7 +368,7 @@
                     model.setParam(name,result.pvec)
                 else:
-                    print "fitting result : chisqr",result.fitness
-                    print "fitting result : pvec",result.pvec
-                    print "fitting result : stderr",result.stderr
+                    #print "fitting result : chisqr",result.fitness
+                    #print "fitting result : pvec",result.pvec
+                    #print "fitting result : stderr",result.stderr
                     #model.setParam(name,result.pvec[i])
 #                   print "fitting: single fit", name, result.pvec[i]
@@ -374,7 +382,8 @@
                              xmin=xmin, xmax=xmax,title=None)
         except:
-            raise
-            #wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value))
-            #return
+            #raise
+            wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value))
+            return
+       
        
     def _simul_fit_completed(self,result,qmin,qmax, elapsed,pars=None,cpage=None,
@@ -394,5 +403,5 @@
             wx.PostEvent(self.parent, StatusEvent(status="Simultaneous fit \
             complete ", type="stop"))
-            print "result",cpage,str(result),result.parameters,result.fitness,result.stderr
+            #print "result",cpage,str(result),result.parameters,result.fitness,result.stderr
             
             try:
@@ -426,10 +435,16 @@
                 wx.PostEvent(self.parent, StatusEvent(status="Simultaneous Fitting error: %s" % sys.exc_value))
                 return
+            
+            
     def stop_fit(self):
+        """
+        """
         if self.calc_thread != None and self.calc_thread.isrunning():
             #self.calc_thread.interrupt()
             self.calc_thread.stop()
             wx.PostEvent(self.parent, StatusEvent(status="Fitting  \
-is cancelled" , type="stop"))
+                is cancelled" , type="stop"))
+            
+            
     def _on_single_fit(self,id=None,qmin=None, qmax=None,ymin=None, ymax=None,xmin=None,xmax=None):
         """ 
@@ -526,9 +541,5 @@
                 self.calc_thread.queue()
                 self.calc_thread.ready(2.5)
-                #while not self.done:
-                    #print "when here"
-                 #   time.sleep(1)
-                
-               
+             
             except:
                 wx.PostEvent(self.parent, StatusEvent(status="Single Fit error: %s" % sys.exc_value))
@@ -585,5 +596,5 @@
                         
                     self.fitter.set_model(new_model, self.fit_id, pars) 
-                    print "sim-->model",metadata,model,self.fit_id, pars
+                    #print "sim-->model",metadata,model,self.fit_id, pars
                     dy=[]
                     x=[]
@@ -603,5 +614,5 @@
                                 metadata.x=x
                     self.fitter.set_data(metadata,self.fit_id,qmin,qmax,ymin,ymax)
-                    print "sim---->value of problem",value.get_scheduled()
+                    #print "sim---->value of problem",value.get_scheduled()
                     self.fitter.select_problem_for_fit(Uid=self.fit_id,value=value.get_scheduled())
                     self.fit_id += 1 
@@ -646,5 +657,7 @@
         
     def _onset_engine(self,event):
-        """ set engine to scipy"""
+        """ 
+            set engine to scipy
+        """
         if self._fit_engine== 'park':
             self._on_change_engine('scipy')
@@ -670,5 +683,5 @@
         name = evt.name
         
-        print "name fitting", name
+        #print "name fitting", name
         #sim_page=self.fit_panel.GetPage(1)
         sim_page=self.sim_page
@@ -695,7 +708,10 @@
                 self.sim_page.add_model(self.page_finder)
         
-    def  set_smearer(self,smearer):     
-         current_pg=self.fit_panel.get_current_page()
-         self.page_finder[current_pg].set_smearer(smearer)
+    def  set_smearer(self,smearer):
+        """
+        
+        """   
+        current_pg=self.fit_panel.get_current_page()
+        self.page_finder[current_pg].set_smearer(smearer)
          
     def redraw_model(self,qmin= None,qmax= None):
@@ -725,18 +741,9 @@
                     model=list[0]
                     break 
-            print "model in fitting",model
+            #print "model in fitting",model
             if data!=None and data.__class__.__name__ != 'Data2D':
                 theory = Theory1D(x=[], y=[])
                 theory.name = model.name
                 theory.group_id = data.group_id
-                """
-                if hasattr(data, "id"):
-                    import string
-                    if string.find("Model",data.id )!=None:
-                        #allow plotting on the same panel 
-                        theory.id =str(data.id )+" "+str(self.index_theory)
-                        self.index_theory +=1
-                    else:
-                    """
                 theory.id = "Model"
                    
@@ -777,4 +784,5 @@
                     wx.PostEvent(self.parent, StatusEvent(status="fitting \
                         skipping point x %g %s" %(qmin, sys.exc_value)) )
+                    
                 wx.PostEvent(self.parent, NewPlotEvent(plot=theory,
                                                 title=str(data.name)))
@@ -841,5 +849,5 @@
         if hasattr(evt.model, "name"):
             name = evt.model.name
-        print "on model menu", name
+        #print "on model menu", name
         model=evt.model()
         description=model.description
@@ -869,4 +877,7 @@
     def _draw_model1D(self,model,name,description=None, enable1D=True,
                       qmin=DEFAULT_QMIN, qmax=DEFAULT_QMAX, qstep=DEFAULT_NPTS):
+        """
+        
+        """
         
         if enable1D:
@@ -894,4 +905,5 @@
                     wx.PostEvent(self.parent, StatusEvent(status="Draw model 1D error: %s" % sys.exc_value))
                     #raise
+                    return
             else:
                 for i in range(xlen):
@@ -899,5 +911,5 @@
                 try:
                     new_plot = Theory1D(x, y)
-                    print "draw model 1D", name
+                    #print "draw model 1D", name
                     new_plot.name = name
                     new_plot.xaxis("\\rm{Q}", 'A^{-1}')
@@ -914,9 +926,16 @@
                     #raise
                     wx.PostEvent(self.parent, StatusEvent(status="Draw model 1D error: %s" % sys.exc_value))
+                    return
+    
+    
+    
     def update(self, output,time):
+        """
+        """
         pass
     
     def complete(self, output, elapsed, model, qmin, qmax,qstep=DEFAULT_NPTS):
-       
+        """
+        """
         wx.PostEvent(self.parent, StatusEvent(status="Calc \
         complete !" , type="stop"))
@@ -1007,5 +1026,5 @@
             try:
                 from sans.guiframe.model_thread import Calc2D
-                print "in draw model 2d ",self.model
+               # print "in draw model 2d ",self.model
                 self.calc_thread = Calc2D(parent =self.parent,x=x,
                                            y=y,model= self.model, 
Index: sansview/perspectives/fitting/modelpage.py
===================================================================
--- sansview/perspectives/fitting/modelpage.py	(revision 7d680c728676cc89e2dd09571975ac68a3763f2f)
+++ sansview/perspectives/fitting/modelpage.py	(revision ed2ea6affd15bc8ac6492c7f3afba6be6f2a899f)
@@ -738,5 +738,5 @@
             angle= self.phi_cb.GetLabelText()
         n=0
-        print "hello1",self.model.runXY([0.01,0.01]) 
+        #print "hello1",self.model.runXY([0.01,0.01]) 
         self.disp_list=self.model.getDispParamList()
         name= "phi"
@@ -748,10 +748,10 @@
                     #self.model.dispersion[param]['npts'] = len(values)
                     n+=1
-            print "model dispers list",self.model.getDispParamList()
+            #print "model dispers list",self.model.getDispParamList()
             if n ==0:
               wx.PostEvent(self.parent.parent, StatusEvent(status=\
                             " Model contains no %s distribution"%name))  
             else:
-                print "hello2",self.model.runXY([0.01,0.01]) 
+                #print "hello2",self.model.runXY([0.01,0.01]) 
                 #self._draw_model()
                 qmin=self.qmin_x
@@ -775,5 +775,5 @@
                             value = self.model.runXY([x[i_x], y[i_y]])
                             output[i_x] [i_y]=value 
-                print"modelpage", output
+                #print"modelpage", output
                 self.manager.complete( output=output, elapsed=None, model=self.model, qmin=qmin, qmax=qmax,qstep=qstep)
                 #self._draw_model()
@@ -782,4 +782,6 @@
                       
     def set_panel_dispers(self, disp_list, type="GaussianModel" ):
+        """
+        """
         
         self.fittable_param=[]
@@ -958,4 +960,6 @@
         
     def set_model_parameter(self):
+        """
+        """
         if len(self.parameters) !=0 and self.model !=None:
             # Flag to register when a parameter has changed.
@@ -975,7 +979,9 @@
                          
                 except:
-                    raise
+                    #raise
                     wx.PostEvent(self.parent.parent, StatusEvent(status=\
                             "Model Drawing  Error:wrong value entered : %s"% sys.exc_value))
+                    return 
+                
                 
             for item in self.fixed_param:
@@ -1009,27 +1015,12 @@
                          self.model.setParam(name,value)
                          is_modified = True
-                     """
-                     #if self.checkFitValues(item[4], item[5]):
-                     #    if param_min.lstrip().rstrip()== "-inf":
-                             param_min=None
-                         else:
-                             param_min=float(param_min)
-                         if param_max.lstrip().rstrip() =="+inf":
-                             param_max=None
-                         else:
-                             param_max=float(param_max)
-                         if  param_min !=  self.model.details[name][1]:
-                             self.model.details[name][1]= param_min
-                             is_modified = True
-                         if  param_max !=  self.model.details[name][2]:
-                             self.model.details[name][2]= param_max
-                             is_modified = True
-                        """
+                   
                 except:
-                    #print item[4].GetValue(),item[5].GetValue()
-                    raise 
-                    #wx.PostEvent(self.parent.parent, StatusEvent(status=\
-                    #       "Model Drawing  Error:wrong value entered : %s"% sys.exc_value))
-            
+                    #raise 
+                    wx.PostEvent(self.parent.parent, StatusEvent(status=\
+                           "Model Drawing  Error:wrong value entered : %s"% sys.exc_value))
+                    return
+                
+                
             # Here we should check whether the boundaries have been modified.
             # If qmin and qmax have been modified, update qmin and qmax and 
@@ -1067,6 +1058,12 @@
        
     def select_param(self,event):
+        """
+        
+        """
         pass
     def select_all_param(self,event): 
+        """
+        
+        """
         pass
     def select_all_param_helper(self):
Index: sansview/perspectives/fitting/old_ modelpage.py
===================================================================
--- sansview/perspectives/fitting/old_ modelpage.py	(revision ed2ea6affd15bc8ac6492c7f3afba6be6f2a899f)
+++ sansview/perspectives/fitting/old_ modelpage.py	(revision ed2ea6affd15bc8ac6492c7f3afba6be6f2a899f)
@@ -0,0 +1,1031 @@
+import sys
+import wx
+import wx.lib
+import numpy
+import copy
+
+
+from sans.guicomm.events import StatusEvent   
+from sans.guiframe.utils import format_number
+(ModelEventbox, EVT_MODEL_BOX) = wx.lib.newevent.NewEvent()
+_BOX_WIDTH = 80
+
+
+
+
+class ModelPage(wx.ScrolledWindow):
+    """
+        FitPanel class contains fields allowing to display results when
+        fitting  a model and one data
+        @note: For Fit to be performed the user should check at least one parameter
+        on fit Panel window.
+  
+    """
+    ## Internal name for the AUI manager
+    window_name = "Fit page"
+    ## Title to appear on top of the window
+    window_caption = "Fit Page"
+    name=""
+    def __init__(self, parent,model,name, *args, **kwargs):
+        wx.ScrolledWindow.__init__(self, parent, *args, **kwargs)
+        """ 
+            Initialization of the Panel
+        """
+        # model on which the fit would be performed
+        self.model=model
+        self.back_up_model= model.clone()
+        #list of dispersion paramaters
+        self.disp_list=[]
+        try:
+            self.disp_list=self.model.getDispParamList()
+        except:
+            pass 
+        self.manager = None
+        self.parent  = parent
+        self.event_owner = None
+        # this panel does contain data .existing data allow a different drawing
+        #on set_model parameters
+        self.data=None
+        #panel interface
+        self.vbox  = wx.BoxSizer(wx.VERTICAL)
+        self.sizer11 = wx.BoxSizer(wx.HORIZONTAL)
+        self.sizer10 = wx.GridBagSizer(5,5)
+        self.sizer9 = wx.GridBagSizer(5,5)
+        self.sizer8 = wx.GridBagSizer(5,5)
+        self.sizer7 = wx.GridBagSizer(5,5)
+        self.sizer6 = wx.GridBagSizer(5,5)
+        self.sizer5 = wx.GridBagSizer(5,5)
+        self.sizer4 = wx.GridBagSizer(5,5)
+       
+        #model selection
+        self.vbox.Add(wx.StaticLine(self, -1), 0, wx.EXPAND, 0)
+        self.vbox.Add(self.sizer4)
+        #model description
+        self.vbox.Add(self.sizer11)
+        #model paramaters layer
+        self.vbox.Add(self.sizer5)
+        #polydispersion selected
+        self.vbox.Add(wx.StaticLine(self, -1), 0, wx.EXPAND, 0)
+        self.vbox.Add(self.sizer6)
+        #combox box for type of dispersion
+        self.vbox.Add(self.sizer7)
+        #dispersion parameters layer
+        self.vbox.Add(self.sizer8)
+        # plotting range
+        self.vbox.Add(self.sizer9)
+        #close layer
+        self.vbox.Add(wx.StaticLine(self, -1), 0, wx.EXPAND, 0)
+        self.vbox.Add(wx.StaticLine(self, -1), 0, wx.EXPAND, 0)
+        self.vbox.Add(self.sizer10)
+        
+      
+        #------------------ sizer 4  draw------------------------  
+       
+       
+        # define combox box
+        self.modelbox = wx.ComboBox(self, -1)
+         # preview selected model name
+        self.prevmodel_name=name
+        #print "model view prev_model",name
+        self.modelbox.SetValue(self.prevmodel_name)
+        #enable model 2D draw
+        self.enable2D= False
+        #filling sizer2
+        ix = 0
+        iy = 1
+        self.sizer4.Add(wx.StaticText(self,-1,'Model'),(iy,ix),(1,1)\
+                  , wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        ix += 1
+        self.sizer4.Add(self.modelbox,(iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        ix += 1
+        id = wx.NewId()
+        self.model_view =wx.Button(self,id,'View 2D')
+        self.model_view.Bind(wx.EVT_BUTTON, self.onModel2D,id=id)
+        self.model_view.SetToolTipString("View model in 2D")
+        
+        self.sizer4.Add(self.model_view,(iy,ix),(1,1),\
+                   wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        
+        self.model_view.Enable()
+        self.model_view.SetFocus()
+        
+        ix = 0
+        iy += 1
+        self.sizer4.Add((20,20),(iy,ix),(1,1),wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+
+        #----------sizer6-------------------------------------------------
+        self.disable_disp = wx.RadioButton(self, -1, 'No', (10, 10), style=wx.RB_GROUP)
+        self.enable_disp = wx.RadioButton(self, -1, 'Yes', (10, 30))
+        self.Bind(wx.EVT_RADIOBUTTON, self.Set_DipersParam, id=self.disable_disp.GetId())
+        self.Bind(wx.EVT_RADIOBUTTON, self.Set_DipersParam, id=self.enable_disp.GetId())
+        ix= 0
+        iy=1
+        self.sizer6.Add(wx.StaticText(self,-1,'Polydispersity: '),(iy,ix),(1,1)\
+                  , wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        ix += 1
+        self.sizer6.Add(self.enable_disp ,(iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        ix += 1
+        self.sizer6.Add(self.disable_disp ,(iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        ix =0
+        iy+=1
+        self.sizer6.Add((20,20),(iy,ix),(1,1),wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)  
+
+        
+        #---------sizer 9 draw----------------------------------------
+       
+         ## Q range
+        self.qmin_x= 0.001
+        self.qmax_x= 0.1
+        self.num_points= 100
+        
+        
+        self.qmin    = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
+        self.qmin.SetValue(format_number(self.qmin_x))
+        self.qmin.SetToolTipString("Minimun value of Q in linear scale.")
+        self.qmin.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
+        self.qmin.Bind(wx.EVT_TEXT_ENTER, self._onparamEnter)
+     
+        self.qmax    = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
+        self.qmax.SetValue(format_number(self.qmax_x))
+        self.qmax.SetToolTipString("Maximum value of Q in linear scale.")
+        self.qmax.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
+        self.qmax.Bind(wx.EVT_TEXT_ENTER, self._onparamEnter)
+     
+
+        self.npts    = wx.TextCtrl(self, -1,size=(_BOX_WIDTH,20))
+        self.npts.SetValue(format_number(self.num_points))
+        self.npts.SetToolTipString("Number of point to plot.")
+        self.npts.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
+        self.npts.Bind(wx.EVT_TEXT_ENTER, self._onparamEnter)
+       
+        ix = 0
+        iy = 1 
+        self.sizer9.Add(wx.StaticText(self, -1, 'Plotting Range'),(iy, ix),(1,1),\
+                            wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        ix += 1 
+        self.sizer9.Add(wx.StaticText(self, -1, 'Min'),(iy, ix),(1,1),\
+                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        ix += 1
+        self.sizer9.Add(wx.StaticText(self, -1, 'Max'),(iy, ix),(1,1),\
+                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        ix += 1
+        self.sizer9.Add(wx.StaticText(self, -1, 'Npts'),(iy, ix),(1,1),\
+                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        ix = 0
+        iy += 1
+        self.sizer9.Add(wx.StaticText(self, -1, 'Q range'),(iy, ix),(1,1),\
+                            wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        ix += 1
+        self.sizer9.Add(self.qmin,(iy, ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        ix += 1
+        self.sizer9.Add(self.qmax,(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        ix += 1
+        self.sizer9.Add(self.npts,(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        
+        ix =0
+        iy+=1 
+        self.sizer9.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        #----------sizer 10 draw------------------------------------------------------
+        id = wx.NewId()
+        self.btClose =wx.Button(self,id,'Close')
+        self.btClose.Bind(wx.EVT_BUTTON, self.onClose,id=id)
+        self.btClose.SetToolTipString("Close page.")
+        
+        ix= 3
+        iy= 1
+        self.sizer10.Add((20,20),(iy,ix),(1,1),wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        ix +=1
+        self.sizer10.Add( self.btClose,(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        ix =0
+        iy+=1
+        self.sizer10.Add((20,20),(iy,ix),(1,1),wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+       
+        # contains link between  model ,all its parameters, and panel organization
+        self.parameters=[]
+        self.fixed_param=[]
+        self.fittable_param=[]
+        self.polydisp= {}
+        #contains link between a model and selected parameters to fit 
+        self.param_toFit=[]
+        
+        #dictionary of model name and model class
+        self.model_list_box={}
+        #Draw initial panel
+         #-----sizer 11--------------------model description------
+        if self.model!=None:
+            self.set_panel(self.model)
+        self.theta_cb=None
+       
+       
+        self.vbox.Layout()
+        self.vbox.Fit(self) 
+        self.SetSizer(self.vbox)
+        self.SetScrollbars(20,20,55,40)
+        
+        self.Centre()
+        self.Layout()
+        self.parent.GetSizer().Layout()
+    def set_model_description(self, model):
+        
+        if model !=None and str(model.description)!=""and self.data==None:
+            self.sizer11.Clear(True)
+            self.box_description= wx.StaticBox(self, -1, 'Model Description')
+            boxsizer1 = wx.StaticBoxSizer(self.box_description, wx.VERTICAL)
+            boxsizer1.SetMinSize((320,20))
+            self.description = wx.StaticText(self,-1,str(model.description))
+            boxsizer1.Add(self.description, 0, wx.EXPAND)  
+            self.sizer11.Add(boxsizer1,1, wx.EXPAND | wx.ALL, 2)
+      
+        
+    def set_owner(self,owner):
+        """ 
+            set owner of fitpage
+            @param owner: the class responsible of plotting
+        """
+        self.event_owner=owner    
+   
+  
+    def set_manager(self, manager):
+        """
+             set panel manager
+             @param manager: instance of plugin fitting
+        """
+        self.manager = manager  
+        
+    def populate_box(self, dict):
+        """
+            Populate each combox box of each page
+            @param page: the page to populate
+        """
+        id=0
+        self.model_list_box=dict
+        list_name=[]
+        for item in  self.model_list_box.itervalues():
+            name = item.__name__
+            if hasattr(item, "name"):
+                name = item.name
+            list_name.append(name)
+        list_name.sort() 
+         
+        for name in list_name:
+            self.modelbox.Insert(name,int(id))
+            id+=1
+        wx.EVT_COMBOBOX(self.modelbox,-1, self._on_select_model) 
+        return 0
+    
+
+    def Set_DipersParam(self, event):
+        if self.enable_disp.GetValue():
+            if len(self.disp_list)==0:
+                ix=0
+                iy=1
+                self.fittable_param=[]
+                self.fixed_param=[]
+                self.sizer8.Clear(True)
+                model_disp = wx.StaticText(self, -1, 'No PolyDispersity for this model')
+                self.sizer7.Add(model_disp,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+                self.vbox.Layout()
+                self.SetScrollbars(20,20,55,40)
+                self.Layout()
+                self.parent.GetSizer().Layout()
+                return 
+            else:
+                if self.data !=None and self.model !=None: # allow to recognize data panel from model panel
+                    
+                
+                    self.cb1.SetValue(False)
+                    self.select_all_param_helper()
+                
+                self.populate_disp_box()
+                self.set_panel_dispers(self.disp_list)
+                
+        else:
+            if self.data !=None and self.model!=None:
+                if self.cb1.GetValue():
+                    self.select_all_param_helper()
+            try:
+                if self.back_up_model!=None:
+                    keys = self.back_up_model.getDispParamList()
+                    keys.sort()
+                    #disperse param into the initial state
+                    for item in keys:
+                        value= self.back_up_model.getParam(item)
+                        self.model.setParam(item, value)
+                    self._draw_model() 
+            except:
+                pass  
+                
+            self.fittable_param=[]        
+            self.fixed_param=[]
+            self.sizer7.Clear(True)
+            self.sizer8.Clear(True)
+            self.vbox.Layout()
+            self.SetScrollbars(20,20,55,40)
+            self.Layout()
+            self.parent.GetSizer().Layout()
+            
+    def populate_disp_box(self):
+        self.sizer7.Clear(True)
+        if len(self.disp_list)>0:
+            ix=0
+            iy=1
+            model_disp = wx.StaticText(self, -1, 'Model Disp')
+            self.sizer7.Add(model_disp,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+            ix += 1 
+            # set up the combox box
+            id = 0
+            import sans.models.dispersion_models 
+            self.polydisp= sans.models.dispersion_models.models
+            self.disp_box = wx.ComboBox(self, -1)
+            self.disp_box.SetValue("GaussianModel")
+            for k,v in self.polydisp.iteritems():
+                if str(v)=="MyModel":
+                    self.disp_box.Insert("Select customized Model",id)  
+                else:
+                    self.disp_box.Insert(str(v),id)  
+                id+=1
+            wx.EVT_COMBOBOX(self.disp_box,-1, self._on_select_Disp) 
+            self.sizer7.Add(self.disp_box,( iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+            self.vbox.Layout()
+            self.SetScrollbars(20,20,55,40)
+            self.Layout()
+            self.parent.GetSizer().Layout()  
+            
+            
+    def set_range(self, qmin_x, qmax_x, npts):
+        """
+            Set the range for the plotted models
+            @param qmin: minimum Q
+            @param qmax: maximum Q
+            @param npts: number of Q bins
+        """
+        # Set the data members
+        self.qmin_x = qmin_x
+        self.qmax_x = qmax_x
+        self.num_points = npts
+        
+        # Set the controls
+        self.qmin.SetValue(format_number(self.qmin_x))
+        self.qmax.SetValue(format_number(self.qmax_x))
+        self.npts.SetValue(format_number(self.num_points))
+    def checkFitRange(self):
+        """
+            Check the validity of fitting range
+            @note: qmin should always be less than qmax or else each control box
+            background is colored in pink.
+        """
+       
+        flag = True
+        valueMin = self.qmin.GetValue()
+        valueMax = self.qmax.GetValue()
+        # Check for possible values entered
+        #print "fitpage: checkfitrange:",valueMin,valueMax
+        try:
+            if (float(valueMax)> float(valueMin)):
+                self.qmax.SetBackgroundColour(wx.WHITE)
+                self.qmin.SetBackgroundColour(wx.WHITE)
+            else:
+                flag = False
+                self.qmin.SetBackgroundColour("pink")
+                self.qmax.SetBackgroundColour("pink")      
+        except:
+            flag = False
+            self.qmin.SetBackgroundColour("pink")
+            self.qmax.SetBackgroundColour("pink")
+            
+        self.qmin.Refresh()
+        self.qmax.Refresh()
+        return flag
+    
+
+        
+    def onClose(self,event):
+        """ close the page associated with this panel"""
+        self.parent.onClose()
+        
+  
+        
+    def onModel2D(self, event):
+        """
+         call manager to plot model in 2D
+        """
+        # If the 2D display is not currently enabled, plot the model in 2D 
+        # and set the enable2D flag.
+        if self.enable2D==False:
+            self.enable2D=True
+            self._draw_model()
+            self.model_view.Disable()
+            
+    
+    def select_model(self, model, name):
+        """
+            Select a new model
+            @param model: model object 
+        """
+        self.model = model
+        self.parent.model_page.name = name
+        self.parent.draw_model_name = name
+        
+        print "select_model", self.name,model.__class__
+        self.set_panel(model)
+        self._draw_model(name)
+        
+        # Select the model from the combo box
+        items = self.modelbox.GetItems()
+        for i in range(len(items)):
+            print "model name",items[i],model.name, model.__class__.__name__
+            if items[i]==name:
+                self.modelbox.SetSelection(i)
+                
+                
+    def _on_select_Disp(self,event):
+        """
+             allow selecting different dispersion
+             self.disp_list should change type later .now only gaussian
+        """
+        type =event.GetString()
+        self.set_panel_dispers( self.disp_list,type )
+                
+    def _on_select_model(self,event):
+        """
+            react when a model is selected from page's combo box
+            post an event to its owner to draw an appropriate theory
+        """
+        self.disable_disp.SetValue(True)
+        self.sizer8.Clear(True)
+        self.sizer7.Clear(True)       
+        self.vbox.Layout()
+        self.SetScrollbars(20,20,55,40)
+        self.Layout()
+        self.parent.GetSizer().Layout()
+        for item in self.model_list_box.itervalues():
+            name = item.__name__
+            if hasattr(item, "name"):
+                name = item.name
+            if name ==event.GetString():
+                model=item()
+                self.model= model
+                self.set_panel(model)
+                self.name= name
+                self.model_view.SetFocus()
+                self.parent.model_page.name=name
+                self.parent.draw_model_name=name
+                #self.manager.draw_model(model, name)
+                #self.enable2D=False
+                #self.model_view.Enable()
+                self._draw_model(name)
+            
+            
+    def get_model_box(self): 
+        """ return reference to combox box self.model"""
+        return self.modelbox
+
+    
+    def get_param_list(self):
+        """
+            @return self.param_toFit: list containing  references to TextCtrl
+            checked.Theses TextCtrl will allow reference to parameters to fit.
+            @raise: if return an empty list of parameter fit will nnote work 
+            properly so raise ValueError,"missing parameter to fit"
+        """
+        if self.param_toFit !=[]:
+            return self.param_toFit
+        else:
+            raise ValueError,"missing parameter to fit"
+        
+        
+    def set_panel(self,model):
+        """
+            Build the panel from the model content
+            @param model: the model selected in combo box for fitting purpose
+        """
+        print "set_panel", model
+        
+        self.sizer5.Clear(True)
+        self.parameters = []
+        self.param_toFit=[]
+        self.fixed_param=[]
+        self.model = model
+        
+        self.set_model_description( self.model) 
+        
+        keys = self.model.getParamList()
+        #list of dispersion paramaters
+        self.disp_list=self.model.getDispParamList()
+       
+        keys.sort()
+        ik=0
+        im=1
+        
+        iy = 1
+        ix = 0
+        self.cb1 = wx.CheckBox(self, -1,"Select all", (10, 10))
+        if self.data!=None:
+            wx.EVT_CHECKBOX(self, self.cb1.GetId(), self.select_all_param)
+            self.cb1.SetValue(False)
+        else:
+            self.cb1.Disable()
+            self.cb1.Hide()
+       
+        self.sizer5.Add(self.cb1,(iy, ix),(1,1),\
+                          wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        ix +=1
+        self.text2_2 = wx.StaticText(self, -1, 'Values')
+        self.sizer5.Add(self.text2_2,(iy, ix),(1,1),\
+                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
+        ix +=2
+        self.text2_3 = wx.StaticText(self, -1, 'Errors')
+        self.sizer5.Add(self.text2_3,(iy, ix),(1,1),\
+                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+        self.text2_3.Hide() 
+        ix +=1
+        self.text2_4 = wx.StaticText(self, -1, 'Units')
+        self.sizer5.Add(self.text2_4,(iy, ix),(1,1),\
+                            wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
+        self.text2_4.Hide()
+        disp_list=self.model.getDispParamList()
+        for item in keys:
+            if not item in disp_list:
+                iy += 1
+                ix = 0
+    
+                cb = wx.CheckBox(self, -1, item, (10, 10))
+                if self.data!=None:
+                    cb.SetValue(False)
+                    wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
+                else:
+                    cb.Disable()
+                self.sizer5.Add( cb,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+               
+                ix += 1
+                value= self.model.getParam(item)
+                ctl1 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER)
+                ctl1.SetValue(str (format_number(value)))
+                ctl1.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
+                ctl1.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
+                self.sizer5.Add(ctl1, (iy,ix),(1,1), wx.EXPAND)
+                
+                ix += 1
+                text2=wx.StaticText(self, -1, '+/-')
+                self.sizer5.Add(text2,(iy, ix),(1,1),\
+                                wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
+                text2.Hide()  
+                ix += 1
+                ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER)
+                self.sizer5.Add(ctl2, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+                ctl2.Hide()
+                ix +=1
+                # Units
+                try:
+                    units = wx.StaticText(self, -1, self.model.details[item][0], style=wx.ALIGN_LEFT)
+                except:
+                    units = wx.StaticText(self, -1, "", style=wx.ALIGN_LEFT)
+                self.sizer5.Add(units, (iy,ix),(1,1),  wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+           
+            self.parameters.append([cb,ctl1,text2,ctl2])
+                
+        iy+=1
+        self.sizer5.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+        
+        #Display units text on panel
+        for item in keys:   
+            if self.model.details[item][0]!='':
+                self.text2_4.Show()
+                break
+            else:
+                self.text2_4.Hide()
+        #Disable or enable fit button
+        """
+        if not (len(self.param_toFit ) >0):
+            self.qmin.Disable()
+            self.qmax.Disable()
+        else:
+            self.qmin.Enable()
+            self.qmax.Enable()
+        """  
+        self.vbox.Layout()
+        self.SetScrollbars(20,20,55,40)
+        self.Layout()
+        self.parent.GetSizer().Layout()
+    def _selectDlg(self):
+        import os
+        dlg = wx.FileDialog(self, "Choose a weight file", os.getcwd(), "", "*.*", wx.OPEN)
+        path = None
+        if dlg.ShowModal() == wx.ID_OK:
+            path = dlg.GetPath()
+        dlg.Destroy()
+        return path
+    def read_file(self, path):
+        try:
+            if path==None:
+                wx.PostEvent(self.parent.parent, StatusEvent(status=\
+                            " Selected Distribution was not loaded: %s"%path))
+                return None, None
+            input_f = open(path, 'r')
+            buff = input_f.read()
+            lines = buff.split('\n')
+            
+            angles = []
+            weights=[]
+            for line in lines:
+                toks = line.split()
+                if len(toks)==2:
+                    try:
+                        angle = float(toks[0])
+                        weight = float(toks[1])
+                    except:
+                        # Skip non-data lines
+                        pass
+                    angles.append(angle)
+                    weights.append(weight)
+            return numpy.array(angles), numpy.array(weights)
+        except:
+            raise 
+        
+    def _draw_disp_theta(self): 
+        path = self._selectDlg()
+        dispersion=None
+       
+        for key, value in self.polydisp.iteritems():
+            if value =="MyModel":
+                disp_ph = key()
+                disp_th = key()
+                break
+        values,weights = self.read_file(path)
+        if values ==None and weights==None:
+            return 
+        import math
+        disp_ph.set_weights( values, weights)
+        disp_th.set_weights( values, weights)
+        
+        if self.theta_cb !=None:
+            angle= self.theta_cb.GetLabelText()
+        n=0
+        self.disp_list=self.model.getDispParamList()
+        if angle.lower().count("theta")>0:   
+            for param in self.model.getParamList():
+                if  not param in self.disp_list and  param.lower().count("theta")>0: 
+                    self.model.set_dispersion(param, disp_th)
+                    self.model.dispersion[param]['npts'] = len(values)
+                    n+=1
+           
+            if n ==0:
+              wx.PostEvent(self.parent.parent, StatusEvent(status=\
+                            " Model contains no theta distribution"))  
+            else:
+                self._draw_model() 
+    def _draw_disp_Phi(self): 
+        path = self._selectDlg()
+        dispersion=None
+       
+        for key, value in self.polydisp.iteritems():
+            if value =="MyModel":
+                disp_ph = key()
+                disp_th = key()
+                break
+        values,weights = self.read_file(path)
+        if values ==None and weights==None:
+            return 
+        import math
+        disp_ph.set_weights( values, weights)
+        disp_th.set_weights( values, weights)
+        
+        if self.theta_cb !=None:
+            angle= self.theta_cb.GetLabelText()
+        n=0
+        self.disp_list=self.model.getDispParamList()
+        if angle.lower().count("theta")>0:   
+            for param in self.model.getParamList():
+                if  not param in self.disp_list and  param.lower().count("theta")>0: 
+                    self.model.set_dispersion(param, disp_th)
+                    self.model.dispersion[param]['npts'] = len(values)
+                    n+=1
+           
+            if n ==0:
+              wx.PostEvent(self.parent.parent, StatusEvent(status=\
+                            " Model contains no theta distribution"))  
+            else:
+                self._draw_model() 
+          
+          
+    def select_disp_angle(self, event): 
+        if not self.phi_cb.GetValue():
+            return
+        path = self._selectDlg()
+        dispersion=None
+       
+        for key, value in self.polydisp.iteritems():
+            if value =="MyModel":
+                disp_ph = key()
+                disp_th = key()
+               
+                break
+        try:
+            values,weights = self.read_file(path)
+        except:
+            raise
+        #print "values,weights",values,weights
+        if values ==None and weights==None:
+            return 
+        import math
+        wx.PostEvent(self.parent.parent, StatusEvent(status=\
+                            " Costumized Distribution: %s"% path))
+       
+        disp_ph.set_weights( values, weights)
+        disp_th.set_weights( values, weights)
+        
+       
+        
+        if self.theta_cb !=None:
+            angle= self.phi_cb.GetLabelText()
+        n=0
+        print "hello1",self.model.runXY([0.01,0.01]) 
+        self.disp_list=self.model.getDispParamList()
+        name= "phi"
+        if angle.lower().count(name)>0:   
+            for param in self.model.getParamList():
+                if  not param in self.disp_list and  param.lower().count(name)>0: 
+                    self.model.set_dispersion(param, disp_th)
+                    print "para, th",param, disp_th
+                    #self.model.dispersion[param]['npts'] = len(values)
+                    n+=1
+            print "model dispers list",self.model.getDispParamList()
+            if n ==0:
+              wx.PostEvent(self.parent.parent, StatusEvent(status=\
+                            " Model contains no %s distribution"%name))  
+            else:
+                print "hello2",self.model.runXY([0.01,0.01]) 
+                #self._draw_model()
+                qmin=self.qmin_x
+                qmax=self.qmax_x
+                qstep= self.num_points
+                x=  numpy.linspace(start= -1*qmax,
+                               stop= qmax,
+                               num= qstep,
+                               endpoint=True )  
+                y = numpy.linspace(start= -1*qmax,
+                               stop= qmax,
+                               num= qstep,
+                               endpoint=True )
+                output= numpy.zeros([len(x),len(y)])
+                for i_x in range(int(len(x))):
+                    for i_y in range(int(len(y))):
+                        if (x[i_x]*x[i_x]+y[i_y]*y[i_y]) \
+                        < qmin * qmin:
+                            output[i_x] [i_y]=0   
+                        else:
+                            value = self.model.runXY([x[i_x], y[i_y]])
+                            output[i_x] [i_y]=value 
+                print"modelpage", output
+                self.manager.complete( output=output, elapsed=None, model=self.model, qmin=qmin, qmax=qmax,qstep=qstep)
+                #self._draw_model()
+                      
+                      
+                      
+    def set_panel_dispers(self, disp_list, type="GaussianModel" ):
+        
+        self.fittable_param=[]
+        self.fixed_param=[]
+        
+        ix=0
+        iy=1
+                ### this will become a separate method
+        if type== "Select customized Model":
+            ix=0
+            iy=1
+            self.sizer8.Clear(True)        
+            disp1 = wx.StaticText(self, -1, 'Array Dispersion')
+            self.sizer8.Add(disp1,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+            
+            ix+=1 
+            self.theta_cb = wx.CheckBox(self, -1,"Theta ", (10, 10))
+            wx.EVT_CHECKBOX(self, self.theta_cb.GetId(), self.select_disp_angle)
+            self.sizer8.Add(self.theta_cb,(iy, ix),(1,1),\
+                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+            ix+=1
+            self.phi_cb = wx.CheckBox(self, -1,"Phi", (10, 10))
+            wx.EVT_CHECKBOX(self, self.phi_cb.GetId(), self.select_disp_angle)
+            self.sizer8.Add(self.phi_cb,(iy, ix),(1,1),\
+                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+            
+            ix =0
+            iy +=1 
+            self.sizer8.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)        
+            self.vbox.Layout()
+            self.SetScrollbars(20,20,55,40)
+            self.Layout()
+            self.parent.GetSizer().Layout()  
+           
+        if type== "GaussianModel" :
+
+            self.sizer8.Clear(True)
+            disp = wx.StaticText(self, -1, 'Dispersion')
+            self.sizer8.Add(disp,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+            ix += 1 
+            values = wx.StaticText(self, -1, 'Values')
+            self.sizer8.Add(values,( iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+            ix +=2
+            self.text2_3 = wx.StaticText(self, -1, 'Errors')
+            self.sizer8.Add(self.text2_3,(iy, ix),(1,1),\
+                            wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+            self.text2_3.Hide() 
+           
+            ix += 1 
+            npts = wx.StaticText(self, -1, 'Npts')
+            self.sizer8.Add(npts,( iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+            ix += 1 
+            nsigmas = wx.StaticText(self, -1, 'Nsigmas')
+            self.sizer8.Add(nsigmas,( iy, ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+            
+            disp_list.sort()
+            print disp_list,self.model.dispersion
+            for item in self.model.dispersion.keys():
+                name1=item+".width"
+                name2=item+".npts"
+                name3=item+".nsigmas"
+                iy += 1
+                for p in self.model.dispersion[item].keys():
+                    #print "name 1 2 3", name1, name2, name3
+                    if p=="width":
+                        ix = 0
+                        cb = wx.CheckBox(self, -1, name1, (10, 10))
+                        if self.data !=None:
+                            cb.SetValue(False)
+                            wx.EVT_CHECKBOX(self, cb.GetId(), self.select_param)
+                        else:
+                            cb.Disable()
+                        self.sizer8.Add( cb,( iy, ix),(1,1),  wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
+                        ix = 1
+                        value= self.model.getParam(name1)
+                        ctl1 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER)
+                        ctl1.SetValue(str (format_number(value)))
+                        ctl1.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
+                        ctl1.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
+                        self.sizer8.Add(ctl1, (iy,ix),(1,1), wx.EXPAND)
+                        
+                        ix = 2
+                        text2=wx.StaticText(self, -1, '+/-')
+                        self.sizer8.Add(text2,(iy, ix),(1,1),\
+                                        wx.EXPAND|wx.ADJUST_MINSIZE, 0) 
+                        text2.Hide()  
+                        ix = 3
+                        ctl2 = wx.TextCtrl(self, -1, size=(_BOX_WIDTH,20), style=wx.TE_PROCESS_ENTER)
+                        self.sizer8.Add(ctl2, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+                        ctl2.Hide()
+                        self.fittable_param.append([cb,ctl1,text2,ctl2])
+                       
+                        
+                    elif p=="npts":
+                            ix =4 
+                            value= self.model.getParam(name2)
+                            Tctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20), style=wx.TE_PROCESS_ENTER)
+                            Tctl.SetValue(str (format_number(value)))
+                            Tctl.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
+                            Tctl.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
+                            self.sizer8.Add(Tctl, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+                            self.fixed_param.append([name2, Tctl])
+                    elif p=="nsigmas":
+                            ix =5 
+                            value= self.model.getParam(name3)
+                            Tctl = wx.TextCtrl(self, -1, size=(_BOX_WIDTH/2,20), style=wx.TE_PROCESS_ENTER)
+                            Tctl.SetValue(str (format_number(value)))
+                            Tctl.Bind(wx.EVT_KILL_FOCUS, self._onparamEnter)
+                            Tctl.Bind(wx.EVT_TEXT_ENTER,self._onparamEnter)
+                            self.sizer8.Add(Tctl, (iy,ix),(1,1), wx.EXPAND|wx.ADJUST_MINSIZE, 0)
+                            self.fixed_param.append([name3, Tctl])
+                wx.PostEvent(self.parent.parent, StatusEvent(status=\
+                            " Selected Distribution: Gaussian"))   
+            ix =0
+            iy +=1 
+            self.sizer8.Add((20,20),(iy,ix),(1,1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)        
+            self.vbox.Layout()
+            self.SetScrollbars(20,20,55,40)
+            self.Layout()
+            self.parent.GetSizer().Layout()  
+          
+         
+           
+        
+    def _onparamEnter(self,event):
+        """ 
+            when enter value on panel redraw model according to changed
+        """
+        self.set_model_parameter()
+        
+    def set_model_parameter(self):
+        if len(self.parameters) !=0 and self.model !=None:
+            # Flag to register when a parameter has changed.
+            is_modified = False
+            for item in self.fittable_param:
+                try:
+                     name=str(item[0].GetLabelText())
+                     value= float(item[1].GetValue())
+                     #print "model para", name,value
+                     # If the value of the parameter has changed,
+                     # update the model and set the is_modified flag
+                     if value != self.model.getParam(name):
+                         #print "went hereee"
+                         self.model.setParam(name,value)
+                         
+                         is_modified = True
+                         
+                except:
+                    raise
+                    wx.PostEvent(self.parent.parent, StatusEvent(status=\
+                            "Model Drawing  Error:wrong value entered : %s"% sys.exc_value))
+                
+            for item in self.fixed_param:
+                try:
+                     name=str(item[0])
+                     value= float(item[1].GetValue())
+                     #print "model para", name,value,self.model.getParam(name)
+                     # If the value of the parameter has changed,
+                     # update the model and set the is_modified flag
+                     if value != self.model.getParam(name):
+                         #print "went hereee"
+                         self.model.setParam(name,value)
+                         is_modified = True
+                         
+                except:
+                    raise
+                    wx.PostEvent(self.parent.parent, StatusEvent(status=\
+                            "Model Drawing  Error:wrong value entered : %s"% sys.exc_value))
+                
+            for item in self.parameters:
+                try:
+                     name=str(item[0].GetLabelText())
+                     value= float(item[1].GetValue())
+                     #print " fittable model para", name,value
+                     # If the value of the parameter has changed,
+                     # update the model and set the is_modified flag
+                     if value != self.model.getParam(name):
+                         #print "went here", name,value
+                         self.model.setParam(name,value)
+                         is_modified = True
+                except:
+                     wx.PostEvent(self.parent.parent, StatusEvent(status=\
+                            "Model Drawing  Error:wrong value entered : %s"% sys.exc_value))
+            
+            # Here we should check whether the boundaries have been modified.
+            # If qmin and qmax have been modified, update qmin and qmax and 
+            # set the is_modified flag to True
+            if float(self.qmin.GetValue()) != self.qmin_x:
+                self.qmin_x = float(self.qmin.GetValue())
+                is_modified = True
+            if float(self.qmax.GetValue()) != self.qmax_x:
+                self.qmax_x = float(self.qmax.GetValue())
+                is_modified = True
+            
+            if float(self.npts.GetValue()) !=  self.num_points:
+                self.num_points = float(self.npts.GetValue())
+                is_modified = True
+          
+            if is_modified:
+                self._draw_model()            
+            
+    def _draw_model(self, name=None):
+        """
+            Method to draw or refresh a plotted model.
+            The method will use the data member from the model page
+            to build a call to the fitting perspective manager.
+            
+            [Note to coder: This way future changes will be done in only one place.] 
+        """
+        #print "_draw_model",self.model
+        if name==None:
+            name= self.model.name
+       
+        self.manager.draw_model(self.model, name, data=self.data,
+                                qmin=self.qmin_x, qmax=self.qmax_x,
+                                qstep= self.num_points,
+                                enable2D=self.enable2D)
+       
+    def select_param(self,event):
+        pass
+    def select_all_param(self,event): 
+        pass
+    def select_all_param_helper(self):
+        """
+             Allows selecting or delecting button
+        """
+        self.param_toFit=[]
+        if  self.parameters !=[]:
+            if  self.cb1.GetValue()==True:
+                for item in self.parameters:
+                    item[0].SetValue(True)
+                    list= [item[0],item[1],item[2],item[3]]
+                    self.param_toFit.append(list )
+                if len(self.fittable_param)>0:
+                    for item in self.fittable_param:
+                        item[0].SetValue(True)
+                        list= [item[0],item[1],item[2],item[3]]
+                        self.param_toFit.append(list )
+            else:
+                for item in self.parameters:
+                    item[0].SetValue(False)
+                for item in self.fittable_param:
+                    item[0].SetValue(False)
+                self.param_toFit=[]
+               
+                
+       
Index: sansview/perspectives/fitting/simfitpage.py
===================================================================
--- sansview/perspectives/fitting/simfitpage.py	(revision 51d47b5b86b892ab660da7cca3522ab438d9158d)
+++ sansview/perspectives/fitting/simfitpage.py	(revision ed2ea6affd15bc8ac6492c7f3afba6be6f2a899f)
@@ -265,9 +265,9 @@
         for item in mylist:
             if utils.look_for_tag( value,str(item))[0]:
-                print "went here"
+                #print "went here"
                 model_param = utils.split_text(str(item), value,1)
                 param_name = model_param[0]
                 param_value = model_param[1]
-                print "simpage",utils.look_for_tag(param_name,"\.")[0]
+                #print "simpage",utils.look_for_tag(param_name,"\.")[0]
                 if utils.look_for_tag(param_name,"\.")[0]:
                     param_names = utils.split_text("\.",param_name,1)
@@ -275,5 +275,5 @@
                     param_name = param_names[1]
                     ##### just added
-                    print "simfitpage: param name",model_name,param_name
+                    #print "simfitpage: param name",model_name,param_name
                 
                     param=[str(model_name),param_name,str(param_value),"="]
@@ -301,5 +301,5 @@
                 #raise ValueError,"Missing '=' in expression"
                 wx.PostEvent(self.parent.Parent, StatusEvent(status="Missing '=' in expression"))
-                
+               
             
         
@@ -334,5 +334,5 @@
             #raise ValueError,"Missing '=' in expression"
             wx.PostEvent(self.parent.Parent, StatusEvent(status="Missing '=' in expression"))
-        
+            
    
     
Index: sansview/perspectives/fitting/state.py
===================================================================
--- sansview/perspectives/fitting/state.py	(revision 2268d100cf4d0c2aa066591523a5c8846391f5d0)
+++ 	(revision )
@@ -1,258 +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,data=None, model=None, slicer=None, panel=None):
-        self.target = target
-        self.model  = model
-        self.data   = data
-        self.type_panel= None
-        self.disp_list = []
-        self.manager = None
-        self.parent  = parent
-        self.event_owner = None
-        self.modelbox = wx.ComboBox(self, -1)
-         # preview selected model name
-        self.prevmodel_name=name
-        #print "model view prev_model",name
-        self.modelbox.SetValue(self.prevmodel_name)
-        #enable model 2D draw
-        self.enable2D= False
-         ## Q range
-        self.qmin_x= 0.001
-        self.qmax_x= 0.1
-        self.num_points= 100
-        self.parameters=[]
-        self.fixed_param=[]
-        self.fittable_param=[]
-        #contains link between a model and selected parameters to fit 
-        self.param_toFit=[]
-        
-        #dictionary of model name and model class
-        self.model_list_box={}
-        #Draw initial panel
-        self.enable_disp= None
-        self.disable_disp=None    
-            
-        if panel !=None:
-            self.panel= panel
-            
-        
-        
-        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_panel(self):
-        obj          = State(self.target, self.model.clone(),self.panel)
-        obj.data = deepcopy(self.data)
-        
-        
-        
-        
-    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:
-            print
-            #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)))
-
-    
