Index: sansview/perspectives/fitting/fit_thread.py
===================================================================
--- sansview/perspectives/fitting/fit_thread.py	(revision e9b4cc4bf7422dc2f8b9a3ad59600fae011de8f7)
+++ sansview/perspectives/fitting/fit_thread.py	(revision e9b4cc4bf7422dc2f8b9a3ad59600fae011de8f7)
@@ -0,0 +1,174 @@
+
+import sys, wx, logging
+import string, numpy, math
+from sans.guicomm.events import NewPlotEvent, StatusEvent  
+from calcthread import CalcThread
+import park
+from park.fitresult import FitHandler
+DEFAULT_BEAM = 0.005
+import time
+
+import thread
+print "main",thread.get_ident()
+
+ 
+class ConsoleUpdate(FitHandler):
+    """
+    Print progress to the console.
+    """
+    isbetter = False
+    """Record whether results improved since last update"""
+    progress_delta =  60
+    """Number of seconds between progress updates"""
+    improvement_delta = 5
+    """Number of seconds between improvement updates"""
+    def __init__(self,parent, quiet=False,progress_delta=60,improvement_delta=5):
+        """
+        If quiet is true, only print out final summary, not progress and
+        improvements.
+        """
+        self.parent= parent
+        self.progress_time = time.time()
+        self.progress_percent = 0
+        self.improvement_time = self.progress_time
+        self.isbetter = False
+        self.quiet = quiet
+        self.progress_delta = progress_delta
+        self.improvement_delta = improvement_delta
+
+    def progress(self, k, n):
+        """
+        Report on progress.
+        """
+        if self.quiet: return
+        t = time.time()
+        p = int((100*k)//n)
+        
+        # Show improvements if there are any
+        dt = t - self.improvement_time
+        if self.isbetter and dt > self.improvement_delta:
+            self.result.print_summary()
+            self.isbetter = False
+            self.improvement_time = t
+            
+            wx.PostEvent(self.parent, StatusEvent(status=\
+             "%d%% complete ..."%(p)))
+       
+        # Update percent complete
+        dp = p-self.progress_percent
+        if dp < 1: return
+        dt = t - self.progress_time
+        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)))
+       
+            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))))
+                    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))))
+        
+    def improvement(self):
+        """
+        Called when a result is observed which is better than previous
+        results from the fit.
+        """
+        self.isbetter = True
+    
+    def error(self, msg):
+        """
+        Model had an error; print traceback
+        """
+        if self.isbetter:
+            self.result.print_summary()
+        print msg
+
+    def finalize(self):
+        if self.isbetter:
+            self.result.print_summary()
+
+    def abort(self):
+        if self.isbetter:
+            self.result.print_summary()
+
+class FitThread(CalcThread):
+    """Compute 2D data"""
+    
+    def __init__(self,parent, fn,pars=None,cpage=None, qmin=None,qmax=None,ymin=None, ymax=None,
+                 completefn = None,
+                 updatefn   = None,
+                 yieldtime  = 0.01,
+                 worktime   = 0.01
+                 ):
+        CalcThread.__init__(self,completefn,
+                 updatefn,
+                 yieldtime,
+                 worktime)
+        self.parent = parent
+        self.fitter= fn
+        self.cpage= cpage
+        self.pars = pars
+        self.starttime = 0
+        self.qmin = qmin
+        self.qmax = qmax
+        self.ymin = ymin
+        self.ymax = ymax
+        self.done= False
+    def isquit(self):
+        try:
+            CalcThread.isquit(self)
+        except KeyboardInterrupt:
+            #printEVT("Calc %s interrupted" % self.model.name)
+            wx.PostEvent(self.parent, StatusEvent(status=\
+                       "Calc %g interrupted" % time.time()))
+           
+            raise KeyboardInterrupt
+        
+    def update(self):
+        print "updatting"
+        timen= time.time()
+        wx.PostEvent(self.parent, StatusEvent(status="Computing \
+        ... %g sec" % timen))
+            
+    def compute(self):
+        try: 
+            self.starttime = time.time()
+            wx.PostEvent(self.parent, StatusEvent(status=\
+                       "Start the computation %g " % self.starttime))
+            handler= ConsoleUpdate(parent= self.parent,improvement_delta=0.1)
+            result = self.fitter.fit(handler= handler)
+            print "result", result
+           
+            print "in my compute function"
+            elapsed = time.time()-self.starttime
+            self.complete(result= result,
+                          pars = self.pars,
+                          cpage= self.cpage,
+                          qmin = self.qmin,
+                          qmax = self.qmax,
+                          ymin = self.ymin,
+                          ymax = self.ymax, 
+                          elapsed=elapsed )
+        except KeyboardInterrupt:
+            # Thread was interrupted, just proceed and re-raise.
+            # Real code should not print, but this is an example...
+            print "Thread stopped. "
+            raise
+        except:
+            wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value))
+            return 
+    
Index: sansview/perspectives/fitting/fitpage1D.py
===================================================================
--- sansview/perspectives/fitting/fitpage1D.py	(revision d23544dc7fd696d91cd1cad277cfeaadecd7e55d)
+++ sansview/perspectives/fitting/fitpage1D.py	(revision e9b4cc4bf7422dc2f8b9a3ad59600fae011de8f7)
@@ -483,17 +483,10 @@
             when enter value on panel redraw model according to changed
         """
-        self.set_model_parameter()
+        self.set_model()
         self.compute_chisqr()
         
-     
-    def set_model_parameter(self):
-        """
-            this method redraws the model according to parameters values changes
-            and the reset model according to paramaters changes
-        """
-        print "went here",len(self.parameters) ,self.model
+    def set_model(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.parameters:
                 try:
@@ -502,14 +495,26 @@
                     item[3].Clear()
                     item[3].Hide()
-                    name=str(item[0].GetLabelText())
-                    value= float(item[1].GetValue())
-                    # If the value of the parameter has changed,
-                    # update the model and set the is_modified flag
-                    if value != self.model.getParam(name):
-                        self.model.setParam(name,value)
-                        is_modified = True 
                 except:
                      wx.PostEvent(self.parent.GrandParent, StatusEvent(status=\
                             "Drawing  Error:wrong value entered : %s"% sys.exc_value))
+        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.parameters:
+                try:
+                     name=str(item[0].GetLabelText())
+                     value= float(item[1].GetValue())
+                     # If the value of the parameter has changed,
+                     # update the model and set the is_modified flag
+                     if value != self.model.getParam(name):
+                         self.model.setParam(name,value)
+                         is_modified = True
+                except:
+                     wx.PostEvent(self.parent.GrandParent, 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 
Index: sansview/perspectives/fitting/fitpage2D.py
===================================================================
--- sansview/perspectives/fitting/fitpage2D.py	(revision d23544dc7fd696d91cd1cad277cfeaadecd7e55d)
+++ sansview/perspectives/fitting/fitpage2D.py	(revision e9b4cc4bf7422dc2f8b9a3ad59600fae011de8f7)
@@ -200,5 +200,4 @@
                         for j in range(len(self.data.y_bins)):
                             if self.data.y_bins[j]>= ymin and self.data.y_bins[j]<= ymax:
-                                print "data error ",self.data.err_data[j][i]
                                 res.append( (self.data.data[j][i]- self.model.runXY(\
                                  [self.data.x_bins[i],self.data.y_bins[j]]))\
@@ -209,5 +208,5 @@
                     if numpy.isfinite(item):
                         sum +=item
-                print "chisqr : sum 2D", xmin, xmax, ymin, ymax,sum
+                #print "chisqr : sum 2D", xmin, xmax, ymin, ymax,sum
                 #print res
                 self.tcChi.SetValue(format_number(math.fabs(sum)))
Index: sansview/perspectives/fitting/fitting.py
===================================================================
--- sansview/perspectives/fitting/fitting.py	(revision d23544dc7fd696d91cd1cad277cfeaadecd7e55d)
+++ sansview/perspectives/fitting/fitting.py	(revision e9b4cc4bf7422dc2f8b9a3ad59600fae011de8f7)
@@ -10,9 +10,13 @@
 from fitproblem import FitProblem
 from fitpanel import FitPanel
-
+from fit_thread import FitThread
 import models,modelpage
 import fitpage1D,fitpage2D
 import park
 DEFAULT_BEAM = 0.005
+import time
+import thread
+print "main",thread.get_ident()
+
 class Plugin:
     """
@@ -28,4 +32,7 @@
         ## List of panels for the simulation perspective (names)
         self.perspective = []
+        
+        self.calc_thread = None
+        self.done = False
         # Start with a good default
         self.elapsed = 0.022
@@ -222,6 +229,6 @@
             return model_name,param_name
         
-        
-    def _single_fit_completed(self,result,pars,cpage,qmin,qmax,ymin=None, ymax=None):
+   
+    def _single_fit_completed(self,result,pars,cpage,qmin,qmax,elapsed,ymin=None, ymax=None):
         """
             Display fit result on one page of the notebook.
@@ -233,4 +240,6 @@
           
         """
+        #self.done = True
+        #wx.PostEvent(self.parent, StatusEvent(status="Fitting Completed: %g" % elapsed))
         try:
             for page, value in self.page_finder.iteritems():
@@ -260,5 +269,5 @@
             
        
-    def _simul_fit_completed(self,result,qmin,qmax,ymin=None, ymax=None):
+    def _simul_fit_completed(self,result,qmin,qmax, elapsed,pars=None,cpage=None, ymin=None, ymax=None):
         """
             Parameter estimation completed, 
@@ -267,4 +276,5 @@
             @param elapsed: computation time
         """
+        wx.PostEvent(self.parent, StatusEvent(status="Fitting Completed: %g" % elapsed))
         try:
             for page, value in self.page_finder.iteritems():
@@ -291,5 +301,5 @@
              wx.PostEvent(self.parent, StatusEvent(status="Fitting error: %s" % sys.exc_value))
             
-    
+  
     def _on_single_fit(self,id=None,qmin=None,qmax=None,ymin=None,ymax=None):
         """ 
@@ -344,9 +354,25 @@
                 #of parameter names in the list      
         try:
-            result=self.fitter.fit()
-            #self._single_fit_completed(result,pars,current_pg,qmin,qmax)
-            #print "single_fit: result",result.fitness,result.pvec,result.stderr
-            #self._single_fit_completed(result,pars,page,qmin,qmax)
-            self._single_fit_completed(result,pars,page_fitted,qmin,qmax,ymin,ymax)
+            # If a thread is already started, stop it
+            if self.calc_thread != None and self.calc_thread.isrunning():
+                self.calc_thread.stop()
+                    
+            self.calc_thread =FitThread(parent =self.parent,
+                                        fn= self.fitter,
+                                        pars= pars,
+                                        cpage= page_fitted,
+                                       qmin=qmin,
+                                       qmax=qmax,
+                                       ymin= ymin,
+                                       ymax= ymax,
+                                       completefn=self._single_fit_completed,
+                                       updatefn=None)
+            self.calc_thread.queue()
+            self.calc_thread.ready(2.5)
+            #while not self.done:
+                #print "when here"
+             #   time.sleep(1)
+            
+           
         except:
             raise
@@ -412,6 +438,19 @@
         #Do the simultaneous fit
         try:
-            result=self.fitter.fit()
-            self._simul_fit_completed(result,qmin,qmax,ymin,ymax)
+            # If a thread is already started, stop it
+            if self.calc_thread != None and self.calc_thread.isrunning():
+                self.calc_thread.stop()
+                    
+            self.calc_thread =FitThread(parent =self.parent,
+                                        fn= self.fitter,
+                                       qmin=qmin,
+                                       qmax=qmax,
+                                       ymin= ymin,
+                                       ymax= ymax,
+                                       completefn= self._simul_fit_completed,
+                                       updatefn=None)
+            self.calc_thread.queue()
+            self.calc_thread.ready(2.5)
+            
         except:
             wx.PostEvent(self.parent, StatusEvent(status="Simultaneous Fitting error: %s" % sys.exc_value))
@@ -479,5 +518,5 @@
         self.plot_helper(currpage=page,qmin= qmin,qmax= qmax)
         
-    def plot_helper(self,currpage,qmin=None,qmax=None,ymin=None,ymax=None):
+    def plot_helper(self,currpage, fitModel=None, qmin=None,qmax=None,ymin=None,ymax=None):
         """
             Plot a theory given a model and data
@@ -654,11 +693,9 @@
                 except:
                     raise
-    def update(self, output,elapsed):
-        print "Got an update", elapsed
-        wx.PostEvent(self.parent, StatusEvent(status="Plot \
-        updating ... %g sec" % elapsed))
+    def update(self, output,time):
+        pass
     
     def complete(self, output, elapsed, model, qmin, qmax):
-        #printEVT("Calc complete in %g sec" % elapsed) 
+       
         wx.PostEvent(self.parent, StatusEvent(status="Calc \
         complete in %g sec" % elapsed))
@@ -723,5 +760,5 @@
                                        qmax=qmax,
                             completefn=self.complete,
-                            updatefn=self.update)
+                            updatefn=None)
             self.calc_thread.queue()
             self.calc_thread.ready(2.5)
Index: sansview/perspectives/fitting/model_thread.py
===================================================================
--- sansview/perspectives/fitting/model_thread.py	(revision d15c02022d76c57e7bc024e447f04fd9510dff8b)
+++ sansview/perspectives/fitting/model_thread.py	(revision e9b4cc4bf7422dc2f8b9a3ad59600fae011de8f7)
@@ -109,4 +109,5 @@
         self.model = model
         self.starttime = 0
+       
         
     def isquit(self):
@@ -120,4 +121,9 @@
             raise KeyboardInterrupt
         
+    def update(self, output=None, time=None):
+        
+        wx.PostEvent(self.parent, StatusEvent(status="Plot \
+        updating ... %g sec" % time))
+        
     def compute(self):
         import numpy
@@ -125,28 +131,16 @@
         y = self.y
         output = numpy.zeros((len(x),len(y)))
-        """
-        if self.qmin *self.qmax >=0:
-            print "same signe plotting"
-            if self.qmax==0:
-                center_x= self.qmin/2
-                center_y= self.qmin /2
-            else:
-                center_x= (self.qmax -self.qmin)/2
-                center_y= (self.qmax -self.qmin)/2
-        else:
-        """
+      
         center_x=0
         center_y=0
-        #print "center_x , center_y",center_x , center_y
-        #print "x ",len(x)
-        #print "y", y
-        #print "int(len(self.x)/2)",int(len(self.x)/2)
+       
         self.starttime = time.time()
+        wx.PostEvent(self.parent, StatusEvent(status=\
+                       "Start Drawing model %g " % self.starttime))
         lx = len(self.x)
        
         for i_x in range(len(self.x)):
-           
-            # Check whether we need to bail out
-            self.update(output=output)
+            # Check whether we need to bail out
+            self.update(output=output, time=time.time() )
             self.isquit()
             
@@ -154,14 +148,10 @@
                 try:
                     if (self.x[i_x]*self.x[i_x]+self.y[i_y]*self.y[i_y]) \
-                    < self.qmin * self.qmin:
-                        output[i_x] [i_y]=0
-                         
+                        < self.qmin * self.qmin:
+                        
+                        output[i_x] [i_y]=0   
                     else:
-                        value1 = self.model.runXY([self.x[i_x]-center_x, self.y[i_y]-center_y])
-                       
-                        
-                        output[i_x] [i_y]=value1 
-                       
-                    
+                        value = self.model.runXY([self.x[i_x]-center_x, self.y[i_y]-center_y])
+                        output[i_x] [i_y]=value   
                 except:
                      wx.PostEvent(self.parent, StatusEvent(status=\
Index: sansview/perspectives/fitting/modelpage.py
===================================================================
--- sansview/perspectives/fitting/modelpage.py	(revision d23544dc7fd696d91cd1cad277cfeaadecd7e55d)
+++ sansview/perspectives/fitting/modelpage.py	(revision e9b4cc4bf7422dc2f8b9a3ad59600fae011de8f7)
@@ -402,7 +402,9 @@
                 self.qmax = float(self.xmax.GetValue())
                 is_modified = True
-            if float(self.npts.GetValue()) !=  self.num_points:
-                self.qmax = float(self.npts.GetValue())
-                is_modified = True
+            
+                if float(self.npts.GetValue()) !=  self.num_points:
+                    self.qmax = float(self.npts.GetValue())
+                    is_modified = True
+          
             
             if is_modified:
