; $Id: ooechomagnetic__bin.pro,v 1.16 2008/03/22 00:32:34 kneller Exp $
;###############################################################################
;
;FILENAME:
;        ooEchoMagnetic::bin
;
;PURPOSE:
;   Provide binning with time average option for I/XYZ Up/Down values.
;
;CATEGORY:
;   Analysis software.
;
;METHODS IN FILE:
;   ooEchoMagnetic::report_timeaverage_state
;   ooEchoMagnetic::do_t_ave
;   ooEchoMagnetic::setExtensions
;   ooEchoMagnetic::report_DeepMask_State
;   ooEchoMagnetic::saveMask
;   ooEchoMagnetic::getDeepMask
;   ooEchoMagnetic::DeepRebin
;   ooEchoMagnetic::bin
;
;
; AUTHOR:
; Larry Kneller
; NIST Center for Neutron Research
; 100 Bureau Drive, Gaithersburg, MD 20899
; United States
; kneller@nist.gov  301-975-8839
; Feb 15 2006
;
; LICENSE:
; The software in this file is written by an employee of
; National Institute of Standards and Technology
; as part of the DAVE software project.
;
; The DAVE software package is not subject to copyright protection
; and is in the public domain. It should be considered as an
; experimental neutron scattering data reduction, visualization, and
; analysis system. As such, the authors assume no responsibility
; whatsoever for its use, and make no guarantees, expressed or
; implied, about its quality, reliability, or any other
; characteristic. The use of certain trade names or commercial
; products does not imply any endorsement of a particular product,
; nor does it imply that the named product is necessarily the best
; product for the stated purpose. We would appreciate acknowledgment
; if the DAVE software is used or if the code in this file is
; included in another product.
;
;###############################################################################


;function ooEcho::report_timeaverage_state
;;
;;NAME:
;;        ooEcho::report_timeaverage_state
;;
;;PURPOSE:
;;           Report the state of time averaging for this object
;;PARAMETERS:
;;           None.
;;KEYWORDS:
;;           None.
;
;
;
;    ;FIRST DO THE TIME AVERAGING OVER ALL TIMES IN FULL self.eorig
;    ;
;    ;GET THE CURRENT self.e
;    ;
;    ;COMPARE AT THE CURRENT INDEX.
;    ;
;    ;IF THEY ARE ALL EQUAL, THEN RETURN TRUE, ELSE FALSE.
;    ;
;
;
;    ;GET INDICES FOR THE SPECIFIC POINT COMPARISON
;    term = self->term()
;    xindex = self.x_dim/2
;    yindex = self.y_dim/2
;    index = xindex + yindex*self.x_dim
;
;
;    m_new = self->do_t_ave(1)
;
;    m_new = reform(m_new,self.x_dim_orig,self.y_dim_orig,$
;                         self.no_of_phases,self.no_of_fourier_times)
;;t0 = systime(/seconds)
;;print,systime(/seconds)-t0
;    mbin = larrebin(m_new,self.x_dim,self.y_dim,$
;            self.no_of_phases,self.no_of_fourier_times)
;;print,systime(/seconds)-t0
;
;
;    mbin = reform(mbin,self.x_dim*self.y_dim,$
;                       self.no_of_phases,$
;                       self.no_of_fourier_times)
;
;
;    tave_array = mbin[index,term,*]
;    test_array = (*(self.e))[index,term,*]
;
;    wh = where((tave_array eq test_array),count)
;
;    return,count eq self.no_of_fourier_times
;end;report_time_average_state
;
;
;function ooEcho::do_t_ave,timeaverage
;;
;;NAME:
;;        ooEcho::do_t_ave
;;
;;PURPOSE:
;;           Calculate a version of self.eorig with the XYZUp/Down or IUp/Down time-averaged.
;;PARAMETERS:
;;           Timeaverage FLAG TO DO (1) OR NOT DO (0) THEW TIME AVERAGING.
;;KEYWORDS:
;;           None.
;
;
;        m = (*self.eorig)[*,*,*]    ;[npix,nphs,nt]
;        m_new = m
;
;        ;IF TIME AVERAGING SET THEN DO IT, OTHERWISE JUST RETURN *self.eorig
;        if timeaverage eq 1 then begin
;            term = self->term()
;            msz = size(m)
;
;            mask1d = *self.mask1d   ;[nphs,nt]
;            t = lonarr(msz[1],msz[2])
;            t_ave = t
;
;            ;THIS AVERAGE SHOULD ACCOUNT FOR THE CURRENT 1d MASKING!!!!
;            tcount = intarr(msz[2])
;            tcount[0:term-1] = 1    ;SET THESE TO 1 SINCE THEY WILL NOT BE USED BELOW.
;
;            for i=term,msz[2]-1 do begin
;                for j=0,msz[3]-1 do begin
;                    if mask1d[i,j] eq 1 then begin ;mask1d eq 1 means unmasked
;                        tcount[i] = tcount[i] + 1
;                        t[*,i] = t[*,i] + m[*,i,j]
;                    endif
;                endfor;j
;            endfor;i
;            ;print,'tcount=',tcount
;
;            for i=term,msz[2]-1 do begin
;                t_ave[*,i] = t[*,i]/tcount[i]   ;THE eb CALCULATIONS SHOULD CHANGE BASED ON THE
;                                                ;T_AVE SWITCH (i.e. THEY SHOULD NOT SIMPLY BE SQUARE ROOTS!
;                                                ;THIS IS PROBABLY THE DIFFERENCE IN GEORG'S AND MY ERROR BARS.)
;            endfor;i
;            ;LOOK FOR INSTANCES WHERE THERE ARE NO VALUES IN THE SUM FOR THE AVERAGE CALCULATION
;            ;AND ZERO THESE OUT.
;            whtzero = where(tcount eq 0,tzerocount)
;            if tzerocount ne 0 then begin
;                t_ave[*,whtzero] = 0
;            endif
;
;
;            for j=0,msz[3]-1 do begin
;                for i=term,msz[2]-1 do begin
;                    m_new[*,i,j] = t_ave[*,i]
;                endfor;i
;            endfor;j
;        endif;timeaverage eq 1
;
;    return,m_new
;
;end;do_t_ave
;pro ooEcho::writeFitparmsToFile,filename=filename,nomasked=nomasked
;
;
;    ;print,'nomasked=',nomasked
;    if n_elements(nomasked) eq 0 then nomasked = 0
;    if n_elements(filename) eq 0 then begin
;        ;print,'TEST'
;        fn = dialog_pickfile(path = self.workdir,title='Select Fit Parameters File:', $
;                             /overwrite_prompt,/write)
;        if fn eq '' then begin
;            void = dialog_message('No output file selected.')
;            return
;        endif
;    endif else begin
;        fn = filename
;    endelse
;
;    openw,lun,fn,/get_lun
;
;    fitparms = *self.fitparms
;    times = (10.0^9)*(*self.fourierTime)
;
;
;    ;CHANGE FROM OMEGA TO PERIOD.
;    omega  = fitparms[4,*,*]
;    somega = fitparms[10,*,*]
;    fitparms[4,*,*]  = 360.0/omega
;    fitparms[10,*,*] = (somega/omega)*fitparms[4,*,*]
;
;    mask = *self.mask2d
;
;
;    theQVals = (*(self->getProperty(tag='QVals')))[*,0]
;
;
;;    help,fitparms
;;    print,12,self.x_dim*self.y_dim,self.no_of_fourier_times
;
;    format = '(i2,",",i2,",",g14.8,",",g14.8,",",' + $
;                            'g14.8,",",g14.8,",",' + $
;                            'g14.8,",",g14.8,",",' + $
;                            'g14.8,",",g14.8,",",' + $
;                            'g14.8,",",g14.8,",",' + $
;                            'g14.8,",",g14.8,",",' + $
;                            'g14.8,",",g14.8)'
;
;    printf,lun,self.filename
;    printf,lun,self.comment
;    printf,lun,'xpos,ypos,time, Av � dAv , A � dA , PH � dPH , W � dW , T � dT , PHoffset � dPHoffset'
;    for k=0,self.no_of_fourier_times-1 do begin
;        for i=0,self.x_dim-1 do begin
;            for j=0,self.y_dim-1 do begin
;                if nomasked eq 1 then begin
;                    if mask[self.x_dim*j+i,k] gt 0 then begin
;                        printf,lun,i,j,times[k],theQVals[self.x_dim*j+i],$
;                                    fitparms[0,self.x_dim*j+i,k],fitparms[6,self.x_dim*j+i,k],$
;                                    fitparms[1,self.x_dim*j+i,k],fitparms[7,self.x_dim*j+i,k],$
;                                    fitparms[2,self.x_dim*j+i,k],fitparms[8,self.x_dim*j+i,k],$
;                                    fitparms[3,self.x_dim*j+i,k],fitparms[9,self.x_dim*j+i,k],$
;                                    fitparms[4,self.x_dim*j+i,k],fitparms[10,self.x_dim*j+i,k],$
;                                    fitparms[5,self.x_dim*j+i,k],fitparms[11,self.x_dim*j+i,k],$
;                                    format=format
;                    endif
;                endif else begin
;
;                    printf,lun,i,j,times[k],theQVals[self.x_dim*j+i],$
;                                fitparms[0,self.x_dim*j+i,k],fitparms[6,self.x_dim*j+i,k],$
;                                fitparms[1,self.x_dim*j+i,k],fitparms[7,self.x_dim*j+i,k],$
;                                fitparms[2,self.x_dim*j+i,k],fitparms[8,self.x_dim*j+i,k],$
;                                fitparms[3,self.x_dim*j+i,k],fitparms[9,self.x_dim*j+i,k],$
;                                fitparms[4,self.x_dim*j+i,k],fitparms[10,self.x_dim*j+i,k],$
;                                fitparms[5,self.x_dim*j+i,k],fitparms[11,self.x_dim*j+i,k],$
;                                format=format
;                endelse
;            endfor;j
;        endfor;i
;    endfor;k
;
;    free_lun,lun
;
;
;end;writeFitParmsToFile
pro ooEchoMagnetic::checkAmpFlipper,amp,lims,phase,hydrogenated,_Extra=extra

    if amp le lims[0] or amp ge lims[1] then begin
        print,'ooEchoMagnetic::checkAmpFlipper   flipping; hydrogenated=',hydrogenated
        amp = -amp
        phase = phase - 180.0     ;USE THIS INITIALLY AND HOPE PHASE IS CAUGHT ELSEWHERE.
    endif

    ;return,amp

end;checkampflipper
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function ooEchoMagnetic::chirpFit,xind,yind,tauind,$
                            fixed=fixed,$
                            limited=limited,$
                            startparms=startparms,$
                            parmlims=parmlims,$
                            parinfo=parinfo,$
                            suppress=suppress,$
                            hydrogenated=hydrogenated,$
                            allownegamp = allownegamp,$
                            noborrow=noborrow,$
                            forcenegamp=forcenegamp,$
                            tavestate=tavestate,$
                            _Extra=extra
;
;NAME:
;        ooEchoMagnetic::chirpFit
;
;PURPOSE:
;           Fit a single echo and update the fitdisplaymask.
;PARAMETERS:
;           xind
;           yind
;           tauind
;KEYWORDS:
;           suppress    Flag to suppres treatment line.
;RETURN VALUE:
;       result  Fitparms
;       0       Failure

;print,'ooEchoMagnetic::chirpFit'
;THIS OVERRIDES ooEcho::chirpfit.

    if n_elements(noborrow) eq 0 then noborrow = 0
    if n_elements(suppress) eq 0 then suppress = 0
    if n_elements(allownegamp) eq 0 then allownegamp = 1
    if n_elements(forcenegamp) eq 0 then forcenegamp = 0
    if n_elements(tavestate) eq 0 then tavestate=self->report_timeaverage_state() 

    ;if suppress eq 0 then self->addTreatment,'ooEcho::chirpFit'


    ;FITTING FOR A SINGLE ECHO
    ;   KEYWORDS:
    ;   startparms IS A 6 ELEMENTS ARRAY OF THE INPUT STARTING PARAMETERS
    ;   fixed IS A 6 ELEMENTS ARRAY OF 1's AND 0's

;042005
;CHANGE THE NEXT LINE TO REFLECT THE USER MASKED MASK VALUE OF -1
;if ((*(self.mask2d))[yind*self.x_dim+xind,tauind] ne 0) then begin

if ((*(self.mask2d))[yind*self.x_dim+xind,tauind] gt 0) then begin


    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    ;CHANGE HERE TO USE MASKED 1D ARRAYS
    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;    x = self->chirpPhases(tauind)
;    y = self->chirp(xind,yind,tauind)
    x = self->chirpPhasesMasked(tauind)
    y = self->chirpMasked(xind,yind,tauind)
    sy= sqrt(double(y))

    ;THE FOLLOWING STEP WILL WEIGHT PIXELS WITH
    ;ZERO COUNTS WITH A 1 IN THE FIT!!!!!

    ;SET sy[] = 1 AT ZERO VALUES
    for ii = 0,n_elements(sy)-1 do begin
        if sy[ii] eq 0.0 then sy[ii] = 1.0
    endfor;ii
    dum_up = self->chirpIup(xind,yind,tauind,tavestate=tavestate)
    dum_down = self->chirpIdown(xind,yind,tauind,tavestate=tavestate)

    if dum_up gt dum_down then begin
        hydrogenated = 1
    endif else hydrogenated = 0

                                                ;041106
    if self.magnetic ne 0 then hydrogenated = 0 ;THIS IS AN OCCASIONAL PROBLEM IF MAGNETIC
                                                ;DATA HAVE POOR STATISTICS.
                                                ;SOMETIMES THE DATA WILL BE MIS-IDENTIFIED
                                                ;AS HYDROGENATED.
                                                ;IF THIS HAPPENS, THE PARM LIMITS WILL
                                                ;FLIP TO A NEGATIVE RANGE AND THE FITS
                                                ;WILL CRASH.  THIS CHECK PREVENTS THE
                                                ;FLIP
                                                ;THE USER MAY ALSO TIME AVERAGAE Iup/down
                                                ;TO PREVENT THE BAD CASES FROM HAPPENING.

;051305
;ALLOW SMALL NEGATIVE AMPLITUDES FOR SAMPLE/CELL AS IGOR DOES.
if self.type eq 2 or self.type eq 3 then begin

;THIS CHECK NEEDS TO BE FOLLOWED UP!!!!!!!!!!!!!!!!!!!!!!!
    ;081406
    if allownegamp eq 1 then begin
        minamp = -30.0d - mean(y)/30.0d
    endif else begin
        minamp = 0.001
    endelse

endif else begin
    minamp = 0.001;-30.0d - mean(y)/30.0d
endelse

    lims = [[0.01d,10000000.0d], [minamp,1000000000.0d], [-1999.0d,2000.0d],$
            [0.01d,1000.0d], [0.001d,200000.0d], [-1999.0d,2000.0d]]
;print,'hydrogenated=',hydrogenated

;083005
        if hydrogenated eq 1 then begin
            temp = -1.0*lims[0,1]
            lims[0,1] = -1.0*lims[1,1]
            lims[1,1] = temp
        endif

        ;help,lims
    if forcenegamp gt 0 then begin
        ;help,lims
        lims[*,1] = [-1000000000.0d,-0.0000001]
    endif


    ;PREVENT CRASH DUE TO BAD STATS
    if (min(sy) gt 0.0) then begin
        names = ['OFFSET','AMPLITUDE','CENTER','SIGMA','OMEGA','PHASE']

        if (n_elements(startparms) ne 6) then begin
            ;SELECT STARTING PARAMETERS BASED ON INFORMATION
            ;IN DATA.
            start = self->startParms(xind,yind,tauind,noborrow=noborrow,tavestate=tavestate)
            perror = 0.0*start
        endif else begin
            start = startparms
            perror = 0.0*start
        endelse

        ;I SHOULDN'T HAVE TO CREATE THIS EACH TIME!!!  IF I PASS
        ;IT IN AS AN ARGUMENT THEN I CAN AVOID THIS CALL EVERY TIME
        ;WITH AN IF STATEMENT
        if n_elements(parinfo) ne 6 then begin
            parinfo = replicate({value:0.0d,$
                                fixed:0,$
                                limited:[1,1], $
                                limits:[0.0d,0.0d],$
                                parname:'',tied:''},$
                                6)
        endif

;if allownegamp eq 0 and hydrogenated eq 1 then start[1] = -abs(start[1])


;110104
fixed = (*self.fixed)[*,xind+yind*self.x_dim,tauind]
        parinfo[*].value = start



        if (n_elements(fixed) ne 6) then begin
            parinfo[*].fixed = [0,0,0,1,1,1]
        endif else begin
            parinfo[*].fixed = fixed
        endelse

;111405
;NEED TO SAVE THE PHASE AND PERIOD IN CASE THEY ARE FIXED
;DURING THE FIT PROCESS.
savephase = parinfo[2].value
if fixed[2] eq 1 then savephase = parinfo[2].value
if fixed[4] eq 1 then saveperiod = parinfo[4].value

;110104
        ;(*self.fixed)[*,xind+yind*self.x_dim,tauind] = fixed
        nfree = 6 - total((*self.fixed)[*,xind+yind*self.x_dim,tauind])

;       parinfo[*].limited = [[1,1],[1,1],[0,0],[1,0],[1,1],[0,0]]
        ;parinfo[*].limited = [[1,1],[1,1],[1,1],[1,1],[1,1],[1,1]]
        if (n_elements(parmlims) ne 12) then begin
            parinfo[*].limits = lims
        endif else begin
            parinfo[*].limits = parmlims
        endelse

        parinfo[*].parname = names
        ;parinfo[5].tied = 'P[2]'   ;ACCORDING TO GEORG EHLERS WE MAY WANT
                                    ;P[2] AND P[5] TO BE INDEPENDENT

;       parinfo[0] =   {value:300.0,fixed:0,limited:[1,1],$
;                       limits:[200.0,350.0],parname:'OFFSET',$
;                       $;step:0, relstep:0, $
;                       $;mpside:-1,mpminstep:10.0,mpmaxstep:100.0,tied:2.0*p[1]$
;                       }


;101904 testing


        ;041405
        ;DON'T TRY TO FIT IF ALL PARMS ARE FIXED!!!

;        PRINT,parinfo.limits
;        print,parinfo.limited
;        print,start
;        print,parinfo.value
;print,hydrogenated



        if total(parinfo[*].fixed) ne 6 then begin

            parms = mpfitfun('chirpFun', x, y, sy, start, $
                                                parinfo = parinfo, $
                                                perror=perror, /QUIET)


;thenewamp   = parms[1]
;thenewphase = parms[2]
;
;self->checkAmpFlipper,thenewamp,parinfo[1].limits,thenewphase,hydrogenated
;
;parms[1] = thenewamp
;parms[2] = thenewphase


;print,parinfo[*].limits

        ;I THINK ORIGINALLY I CHOSE NOT TO ADD THIS TYPE OF
        ;THING TO THE chirpFit METHOD.  FOR NOW I WILL ADD
        ;IT TO ATTEMPT TO GET THE FITTING MORE RELIABLE.
        ;

            ;082304
            ;
            ;DO A SIMPLE PARAMETER CHECK HERE FOR THE MOST COMMON
            ;PEGGING VALUES OF THE FIT PARAMETERS

            ;FIRST CHECK, AMPLITUDE/PHASE
            ;if parms[1] eq minamp then begin ;0.1 or parms[1] eq -0.1 then begin

            whlim = where(parms[1] ge max(parinfo[1].limits),whmaxcount)
            if abs((parms[1]-parinfo[1].limits[0])/parinfo[1].limits[0]) lt 0.0001 then whmaxcount++
            whlim = where(parms[1] le min(parinfo[1].limits),whmincount)
            if abs((parms[1]-parinfo[1].limits[1])/parinfo[1].limits[1]) lt 0.0001 then whmincount++
            whlimcount = whmaxcount + whmincount
            if whlimcount ne 0 then begin
                start = parms
                start[0] = self->chirpMean(xind,yind,tauind)
                if hydrogenated eq 0 then begin
                    start[1] = self->chirpMean(xind,yind,tauind)
                endif else begin
                    start[1] = -1.0*self->chirpMean(xind,yind,tauind)
                endelse
                if forcenegamp gt 0 then begin
                    start[1] = max(y) - min(y)
                    start[1] = -abs(start[1])
                    parinfo[1].fixed = 1
                    print,'ooEchoMagnetic::chirpfit FLIP AND FIX!!!',xind,yind,tauind

                    ;GET THE OFFSET CORRECT THEN FIT THE AMPLITUDE.

                endif;forcenegamp

;thenewamp   = parms[1]
;thenewphase = parms[2]
;
;self->checkAmpFlipper,thenewamp,parinfo[1].limits,thenewphase,hydrogenated
;
;parms[1] = thenewamp
;parms[2] = thenewphase


                ;start[2] = phsstart
                if noborrow eq 0 then begin
                    dum = min(y,phaseStartIndex)
                    phaseStart = x[phaseStartIndex]
                endif else phaseStart = savephase

;111405
;NEED TO SAVE THE PHASE AND PERIOD IN CASE THEY ARE FIXED
;DURING THE FIT PROCESS.
if fixed[2] eq 1 then phaseStart = savephase
if fixed[4] eq 1 then parinfo[4].value = saveperiod

                start[2] = phaseStart
                ;print,'Start after changes:',xind,yind,tauind,start

                parinfo[0].value = start[0]
                parinfo[1].value = start[1]
                parinfo[2].value = start[2]
                ;savefixed = parinfo[2].fixed
                ;parinfo[2].fixed = 0

                parms = mpfitfun('chirpFun', x, y, sy, start, $
                                                    parinfo = parinfo, $
                                                    perror=perror, /QUIET)



                if forcenegamp gt 0 then begin
                    start = parms
                    start[1] = (max(y) - min(y))/2.0
                    start[1] = -abs(start[1])
                    parinfo[1].fixed = 0
                    print,'ooEchoMagnetic::chirpfit FLIP AND UNFIX!!!',xind,yind,tauind
                endif;forcenegamp

                parms = mpfitfun('chirpFun', x, y, sy, start, $
                                                    parinfo = parinfo, $
                                                    perror=perror, /QUIET)


;thenewamp   = parms[1]
;thenewphase = parms[2]
;
;self->checkAmpFlipper,thenewamp,parinfo[1].limits,thenewphase,hydrogenated
;
;parms[1] = thenewamp
;parms[2] = thenewphase

                ;parinfo[2].fixed = savefixed

;091205 CHANGES
;                if parms[1] eq -0.1 then begin
            whlim = where(parms[1] ge max(parinfo[1].limits),whmaxcount)
            if abs((parms[1]-parinfo[1].limits[0])/parinfo[1].limits[0]) lt 0.0001 then whmaxcount++
            whlim = where(parms[1] le min(parinfo[1].limits),whmincount)
            if abs((parms[1]-parinfo[1].limits[1])/parinfo[1].limits[1]) lt 0.0001 then whmincount++
            whlimcount = whmaxcount + whmincount
            if whlimcount ne 0 then begin

                    print,'ooEchoMagnetic::chirpfit STILL NOT RIGHT!!!!',xind,yind,tauind

                    start = parms
                    start[1] = (max(y) - min(y))/2.0
                    if forcenegamp gt 0 then begin
                        start[1] = -abs(start[1])
                        print,'ooEchoMagnetic::chirpfit FLIP AND UNFIX!!!',xind,yind,tauind
                    endif;forcenegamp
                    parinfo[1].fixed = 0


;                    print,xind,yind,tauind
;                    print,parms,perror
;                    print,startparms
;                    print,parinfo[*].value


;print,'ooEchoMagnetic::chirpFit    parms[1] = ',parms[1]

;111405
;NEED TO SAVE THE PHASE AND PERIOD IN CASE THEY ARE FIXED
;DURING THE FIT PROCESS.
if fixed[2] eq 1 then start[2] = savephase
if fixed[4] eq 1 then start[4] = saveperiod






                    parms = mpfitfun('chirpFun', x, y, sy, start, $
                                                        parinfo = parinfo, $
                                                        perror=perror, quiet = 1)

                endif;parms[1] eq -0.1





;print,'TEST'
;print,parms[4]
                ;041205
                if ((parms[4] gt 360.0/300.0) or (parms[4] lt 360.0/420.0)) and fixed[4] ne 1 then begin
                    if fixed[2] eq 1 then start[2] = savephase

                    ;FIT WITH PERIOD FIXED THEN FIT WITH PERIOD ALLOWED TO VARY
                    parinfo[*].value = start
                    parinfo[4].fixed = 1

                    parms = mpfitfun('chirpFun', x, y, sy, parinfo=parinfo, perror=perror,quiet=1);quiet)
                    parinfo[4].fixed = 0
                    parinfo[*].value = parms


                    if fixed[2] eq 1 then parinfo[2].value = savephase
                    parms = mpfitfun('chirpFun', x, y, sy, parinfo=parinfo, perror=perror,quiet=1);quiet)
                endif;PERIOD RANGES LIMITS
                ;041205

            endif;parms[1] eq 0.1


            whlim = where(parms[1] ge max(parinfo[1].limits),whmaxcount)
            if abs((parms[1]-parinfo[1].limits[0])/parinfo[1].limits[0]) lt 0.0001 then whmaxcount++
            whlim = where(parms[1] le min(parinfo[1].limits),whmincount)
            if abs((parms[1]-parinfo[1].limits[1])/parinfo[1].limits[1]) lt 0.0001 then whmincount++
            whlimcount = whmaxcount + whmincount
            if whlimcount ne 0 then begin
                    print,'ooEchoMagnetic::chirpfit SETTTING AMPLITUDE MANUALLY.',xind,yind,tauind
                    start[1] = (max(y) - min(y))/2.0
                    if forcenegamp gt 0 then begin
                        start[1] = -abs(start[1])
                        print,'ooEchoMagnetic::chirpfit FLIP AND UNFIX!!!',xind,yind,tauind
                    endif;forcenegamp
                    parinfo[1].fixed = 0
                    parms[1] = start[1]
            endif


;thenewamp   = parms[1]
;thenewphase = parms[2]
;
;self->checkAmpFlipper,thenewamp,parinfo[1].limits,thenewphase,hydrogenated
;
;parms[1] = thenewamp
;parms[2] = thenewphase

;;041106
;print,'TEST'
;print,parms[4]
;                if ((parms[4] gt 360.0/300.0) or (parms[4] lt 360.0/420.0)) and fixed[4] ne 1 then begin
;                    if fixed[2] eq 1 then start[2] = savephase
;print,'TEST'
;print,360/parms[4]
;
;                    ;FIT WITH PERIOD FIXED THEN FIT WITH PERIOD ALLOWED TO VARY
;                    parinfo[*].value = start
;                    parinfo[4].value = 1.0/360.0
;                    ;parinfo[4].fixed = 1
;
;                    parms = mpfitfun('chirpFun', x, y, sy, parinfo=parinfo, perror=perror,quiet=1);quiet)
;print,parms
;
;                    parinfo[4].fixed = 0
;                    parinfo[*].value = parms
;
;
;                    if fixed[2] eq 1 then parinfo[2].value = savephase
;                    parms = mpfitfun('chirpFun', x, y, sy, parinfo=parinfo, perror=perror,quiet=1);quiet)
;print,parms
;
;
;                endif

        endif else begin
            parms = start
        endelse

        result = [parms,perror]



        ;ASSIGN RESULTS OF INDIVIDUAL FITS TO fitparms
        ;ELEMENT AS FITS ARE DONE
        (*self.fitparms)[*,self.x_dim*yind+xind,tauind] = result




;ooEcho::checkAmp CHECKS THAT THE AMPLITUDE SATISFIES CERTAIN CRITERIA BUT IT
;                 PERFORMS NO FIT!!!
;

        dum = self->checkAmp(xind,yind,tauind,tavestate=tavestate)
        result[1] = dum


        ;SET VALUE OF CHI-SQUARED FOR THIS PIXEL,TAU
        (*self.chisq)[yind*self.x_dim + xind,tauind]$
                            = self->chisq(y,sy,tauind,parms,nfree)

        ;SET VALUE OF CHI-SQUARED FOR THIS PIXEL,TAU
        (*self.fitparms)[*,yind*self.x_dim + xind,tauind] $
                            = result

;if xind eq 11 and yind eq 6 then begin
;    ;;;;;(*self.fitparms)[*,self.x_dim*yind+xind,tauind] = result
;print,'HEY!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
;
;    print,'ooechoMagnetic::chirpFit in ooEchoMagnetic__bin      AFTER checkAmp:'
;    print,parms
;    print,'Chisq calculated=',self->chisq(y,sy,tauind,parms,nfree)
;    print,'Chisq[11,6] stored = ',(*self.chisq)[xind+yind*self.x_dim,tauind]
;    help,/traceback
;
;
;    ;IT APPEARS THAT THE RESULTS OF checkAmp ARE NOT SAVED IN fitParms!!!!!!!!
;    ; BUT THIS IS BECAUSE IT WAS RESET OUTSIDE THIS METHOD!!!!!
;endif


        self->setfitdisplaymask,xind,yind,tauind,value=1
        return,result

    endif else begin
        ;IN CASE OF POOR STATISTICS

        self->setfitdisplaymask,xind,yind,tauind,value=0
        return,0
    endelse
endif else begin;mask2d
        return,0
endelse
end;chirpFit


pro ooEchoMagnetic::setExtensions,deepMaskFile=deepMaskFile,deepMaskSwitch=deepMaskSwitch,_Extra=extra




    if ptr_valid(self.extensions) eq 0 then begin
        if n_elements(deepMaskFile) eq 0 then deepMaskFile = ''
        if n_elements(deepMaskSwitch) eq 0 then deepMaskSwitch = 0

        extensions = {deepMaskFile:deepMaskFile,$
                      deepMaskSwitch:0,$
                      parray:ptr_new(),$    Polarization array
                      farray:ptr_new(),$    Flipping ratio array
                      eff_bpwArrayPtr:ptr_new(),$   eff_bpw array
                      xyzupdownscaleArrayPtr:ptr_new(),$    xyzupdownscalearray
                      mask1dPixels:ptr_new() $              xdim X ydim X nphs X nt ARRAY MASK
                      }
        self.extensions = ptr_new(extensions)
    endif else begin
        if n_elements(deepMaskFile) eq 0 then deepMaskFile = (*self.extensions).deepMaskFile
        if n_elements(deepMaskSwitch) eq 0 then deepMaskSwitch = (*self.extensions).deepMaskSwitch
        (*self.extensions).deepMaskFile = deepMaskFile
        (*self.extensions).deepMaskSwitch = deepMaskSwitch
    endelse
end;setExtensions
function ooEchoMagnetic::report_Deepmask_state,_Extra=extra

    if ptr_valid(self.extensions) eq 0 then begin
        self->setExtensions
    endif

    return,(*self.extensions).deepMaskSwitch

end;setExtensions

function ooEcho::report_Deepmask_state,_Extra=extra

    ;FOR BACKWARD COMPATIBILITY FOR CASES WHERE DATA OBJECTS
    ;WERE SAVED AS ooEcho AND NOT ooEchoMagnetic AS IS CURRENTLY DONE.

    return,0

end;setExtensions

pro ooEchoMagnetic::saveMask,dir=dir,_Extra=extra

    if n_elements(dir) eq 0 then dir = self.workdir
    self.workdir = dir

    fn = dialog_pickfile(title='Select Mask File:',/overwrite_prompt,path=dir)
    if fn ne '' then begin
        mask = *self.mask2d
        openw,lun,fn,/get_lun
        printf,lun,mask
        free_lun,lun
        self.workdir = file_dirname(fn)
    endif else begin
        void = dialog_message('No file name entered.')
    endelse
    dir = self.workdir

    self->setExtensions,deepMaskFile=fn


end;saveMask
function ooEchoMagnetic::getDeepMask,d1,d2,d3,d4,filename=filename,$
                                    default=default,newfile=newfile,$
                                    _Extra=extra


;CHECK FOR ooEchoMagnetic2, IF NOT, THEN REQUEST FILE.

;THIS IS PLACE WHERE I HAVE TO CHECK THE OBJECT TYPE AND
;GET THE FILENAME IF NEEDED.


;help,/traceback

    if n_elements(filename) eq 0 then filename = ''
    if n_elements(default) eq 0 then default = 0
    if n_elements(newfile) eq 0 then newfile = 0

    if ptr_valid(self.extensions) then begin
        filename = (*self.extensions).deepMaskFile
    endif else begin
        filename = ''
    endelse

    echofilename = file_basename(self.filename)


    if ((filename eq '' or newfile eq 1) and default eq 0) then begin
    ;print,'ooEchoMagnetic::getDeepMask filename=',filename

        ;FOR THE ooEchoMagnetic VERSION:
        filename = dialog_pickfile(title='Select 32x32 mask file for '+echofilename+':',$
                             path = self.workdir)

        self->setExtensions,deepMaskFile=filename

    endif
    ;print,filename

    ;FOR THE ooEchoMagnetic2 VERSION:
    ;fn = self.deepMaskFile
    ;if fn eq '' then . . .

    no_file = 0
    if filename eq '' or default eq 1 then begin
        no_file = 1
        void = dialog_message('Using default 32x32 mask '+echofilename+'.')
    endif;filename


    mask = lonarr(d1,d2,d3,d4)
    tempmask = lonarr(d1*d2,d4) ;d3 IS THE NUMBER OF PHASES.

    if n_elements(filename) ne 0 and no_file eq 0 then begin

        CATCH, Error_status
        IF Error_status NE 0 THEN BEGIN
            help,/traceback
            void = dialog_message('Could not read mask file for '+echofilename+', using default mask.')
            for i=0,d3-1 do begin
                for j=0,d4-1 do begin
                    mask[*,*,i,j] = reform(self->defaultmask(),d1,d2)
                endfor;j
            endfor;i
            CATCH, /CANCEL
            return,mask
        ENDIF

        ;OPEN THE FILE AND GET THE MASK.

        openr,lun,filename,/get_lun
        readf,lun,tempmask
        free_lun,lun
        for i=0,d3-1 do begin
            for j=0,d4-1 do begin
                mask[*,*,i,j] = reform(tempmask[*,j],d1,d2)
            endfor;j
        endfor;i

    endif else begin
        for i=0,d3-1 do begin
            for j=0,d4-1 do begin
                mask[*,*,i,j] = reform(self->defaultmask(),d1,d2)
            endfor;j
        endfor;i

    endelse
    ;HERE IS WHERE THERE WILL BE AN OPTION TO READ FROM A FILE.
    wh_mask_le_0 = where(mask le 0,count)

;    print,'ooEchoMagnetic::getDeepMask'
;    print,'[----------------------------------------------------------]'
;
;    print,'count=',count
;    print,'min(mask)=',min(mask)
;    print,'max(mask)=',max(mask)
    if count gt 0 then begin
        mask(wh_mask_le_0) = 0
    endif
;    print,'min(mask)=',min(mask)
;    print,'max(mask)=',max(mask)

    return,mask

end;ooEchoMagnetic::getDeepMask

function ooEchoMagnetic::DeepRebin,arr,xnew,ynew,znew,wnew,filename=filename,$
                                    newfile=newfile,default=default,$
                                    _Extra=extra
;
;NAME:
;        ooEchoMagnetic::DeepRebin
;
;PURPOSE:
;           Rebinning method.  This will allow the user
;           to bin the data from the 32x32 array with that masking.
;           This will allow the removal of just the offending data and
;           no extra.
;
;
;PARAMETERS:
;           arr         The array to be rebinned.
;           xnew        The new size of the x dimension
;           ynew        The new size of the y dimension
;           znew        The new size of the z dimension
;           wnew        The new size of the 4th dimension
;KEYWORDS:
;           none
;RETURN VALUE:
;           newArr      The new array created by the binning operation.


    if n_elements(newfile) eq 0 then newfile = 0
    if n_elements(default) eq 0 then default = 0

    sz = size(arr)
    ;GET THE TYPE OF THE DATA ARRAY
    help,arr,output=s
    segs = strsplit(s,/extract)



deepmask = self->getdeepmask(sz[1],sz[2],sz[3],sz[4],newfile=newfile,default=default,filename=filename,_Extra=extra)
;print,'filename=',filename

;APPLY THE MASK TO THE ARRAY.
arr = deepmask*arr

    ;NOW INSERT THE 4D CASE (x,y,phase,tau)
    if sz[0] eq 4 then begin
        mod1 = sz[1] mod xnew
        mod2 = sz[2] mod ynew
        if mod1 eq 0 and mod2 eq 0 and $
            znew eq sz[3] and wnew eq sz[4] then begin

                ;GET BIN FACTORS
                binx = sz[1]/xnew
                biny = sz[2]/ynew

                ;INITIALIZE REBINNED ARRAY
                case segs[1] of
                'LONG':newArr = lonarr(xnew,ynew,znew,wnew)
                'INT': newArr = lonarr(xnew,ynew,znew,wnew)
                'DOUBLE':newArr = dblarr(xnew,ynew,znew,wnew)
                'FLOAT':newArr = dblarr(xnew,ynew,znew,wnew)
                else:return,0
                endcase;segs[1]


                for i=0,xnew - 1 do begin
                    for j=0,ynew - 1 do begin
                        for k=0,znew - 1 do begin
                            for l=0,wnew - 1 do begin
                                newArr[i,j,k,l] =                 $
                                    total(                      $
                                    arr[i*binx:(i+1)*binx-1,      $
                                        j*biny:(j+1)*biny-1,k,l])
                            endfor;l
                        endfor;k
                    endfor;j
                endfor;i
        endif;MULTIPLE OF 2 REBINNING
    endif else begin;4D

        newarr = 0
    endelse


    return,newArr

end;DeepRebin

pro ooEchoMagnetic::writeFitparmsToFile,filename=filename,nomasked=nomasked,_Extra=extra

    self->ooEcho::writeFitparmsToFile,filename=filename,nomasked=nomasked

end;writeFitParmsToFile

pro ooEchoMagnetic::bin,xfactor=xfactor,yfactor=yfactor,factor=factor,timeaverage=timeaverage,$
                        deepmasking=deepmasking,donotrebin=donotrebin,filename=filename,$
                        default=default,newfile=newfile,_Extra=extra
;
;NAME:
;        ooEchoMagnetic::bin
;
;PURPOSE:
;           Bin the echo data set.
;PARAMETERS:
;           None.
;KEYWORDS:
;           factor      Binning factor applied to both dimensions.  If present it overrides x,yfactor.
;           xfactor     Binning factors appplied specifically to each dimension.
;           yfactor
;           timeaverage Flag to time average Iup/down OR XYZUp/Down
;           deepbinning Flag to do deep binning.
;           donotrebin  Flag to not rebin (used when time averaging is desired for all sets, but not binning.)


    ;;
    ;THIS IS A BINNING METHOD.
    ;IT ALWAYS STARTS FROM INITIAL DETECTOR THAT
    ;IS READ IN FROM FILE.  ANOTHER REBIN METHOD MAY BE
    ;USEFUL SO THAT THE CURRENT STATE CAN BE REBINNED.
    ;
    ;;;

    ;TIME AVERAGING OVER THE up/down VALUES IS HANDLED HERE.


    ;;
    ;NOTE!!!!!! CURRENTLY bin REQUIRES x/y/factor TO DIVIDE EVENLY INTO
    ;           THE DIMENSIONS OF THE DATA ARRAY
    ;;;



    ;SET KEYWORD VALUES
    if (n_elements(xfactor) eq 0) then begin
        xfactor = 1
    endif
    if (n_elements(yfactor) eq 0) then begin
        yfactor = 1
    endif


    if n_elements(deepmasking) eq 0 then deepmasking = 0

;print,'timeaverage=',timeaverage
    if n_elements(timeaverage) eq 0 then timeaverage = 0
    if n_elements(donotrebin) eq 0 then donotrebin = 0
    if n_elements(filename) eq 0 then filename = ''
    if n_elements(default) eq 0 then default = 0
    if n_elements(newfile) eq 0 then newfile = 0


    ;IF THE FACTOR DOES NOT CHANGE THE CURRENT BINNING OF THE DATA
    ;OBJECT, THEN ONLY TIME AVERAGE.  GET CURRENT BIN FACTOR
    ;BEFORE ANY CHANGES ARE MADE.
    current_xfactor = self.x_dim_orig/self.x_dim
    current_yfactor = self.y_dim_orig/self.y_dim


    ;IF FACTOR IS PRESENT USE ONLY FACTOR
    if (n_elements(factor) ne 0) then begin
            xfactor = factor
            yfactor = factor
    endif else begin
            ;DEAFULT TO CURRENT BINNING
            xfactor = current_xfactor
            yfactor = current_xfactor
    endelse

    if donotrebin ne 0 then begin
        xfactor = current_xfactor
        yfactor = current_yfactor
    endif


    ;GET THE eorig MATRIX WITH EVERYTHING AFTER self->term()-1 TIME AVERAGED
    m_new = self->do_t_ave(timeaverage)

        m = reform(m_new[*,*,*],self.x_dim_orig,self.y_dim_orig,$
                self.no_of_phases,self.no_of_fourier_times)


        ;THE NEXT PART MUST BE DONE REGARDLESS OF WHETHER THE FACTOR CHANGES!!!

;        if xfactor eq current_xfactor and yfactor eq current_yfactor then begin
;            ;do nothing
;        endif else begin

            if (xfactor eq 1 and yfactor eq 1) then begin
        ;        print,'NOTE: LARGE DATA IMAGES WILL SLOW THIS PROCESS'

                if deepmasking eq 1 then begin

;
;                    help,m
;                    help,*self.mask2d
;                    help,self.x_dim
;                    help,self.y_dim
;                    help,self.no_of_phases
;                    help,self.no_of_fourier_times

                    deepmask = self->getdeepmask(self.x_dim,self.y_dim,self.no_of_phases,self.no_of_fourier_times,$
                                                 newfile=newfile,default=default,filename=filename,_Extra=extra)

;                    help,deepmask
                    mask2d = reform(deepmask[*,*,0,*],self.x_dim*self.y_dim,self.no_of_fourier_times)
                    if ptr_valid(self.mask2d) then ptr_free,self.mask2d
                    self.mask2d = ptr_new(mask2d)

                endif

                    rmbin = m;(*self.eorig)
                    rmbin = reform(m,self.x_dim_orig*self.y_dim_orig, $
                                     self.no_of_phases, $
                                     self.no_of_fourier_times)
                    self.x_dim = self.x_dim_orig
                    self.y_dim = self.y_dim_orig
                    self.x_cen = self.x_cen_orig
                    self.y_cen = self.y_cen_orig

            endif else begin
                ;REFORM 3-D MATRIX INTO 4-D FOR BINNING

                ;SET DIMENSIONS OF BINNED AREA DETECTOR
                self.x_dim = self.x_dim_orig/xfactor
                self.y_dim = self.y_dim_orig/yfactor
                self.x_cen = self.x_cen_orig/double(xfactor)
                self.y_cen = self.y_cen_orig/double(yfactor)
;print,factor
                if deepmasking ne 1 then begin
                    mbin = larrebin(m,self.x_dim,self.y_dim,$
                            self.no_of_phases,self.no_of_fourier_times)
                            self->setExtensions,deepMaskSwitch=0


                endif else begin
                    mbin = self->deeprebin(m,self.x_dim,self.y_dim,$
                            self.no_of_phases,self.no_of_fourier_times,$
                            newfile=newfile,default=default,$
                            filename=filename)
;print,'filename=',filename

                            self->setExtensions,deepMaskSwitch=1,deepMaskFile=filename
                endelse

                ;REFORM INTO 3-D MATRIX FOR FUTURE PROCESSING
                rmbin = reform(mbin,(self.x_dim)*(self.y_dim),$
                         self.no_of_phases,self.no_of_fourier_times)

            endelse;CHANGE BINNING


;    ;NOW BIN m_new BASED ON THE FACTORS.  SAVE THE MASKING IF THE BINNING IS UNCHANGED
;    current_mask = *self.mask2d

;        print,'xfactor=',xfactor
;        print,'yfactor=',yfactor
;        print,'current_xfactor=',current_xfactor
;        print,'current_yfactor=',current_yfactor

        if xfactor eq current_xfactor and $
            yfactor eq current_yfactor then begin


                ;THINGS TO DO WHEN THERE IS NO CHANGE IN BINNING

                    ptr_free,self.e
                    ptr_free,self.emask

                    ;SET NEW VALUE OF self.emask
                    self.e = ptr_new(rmbin)
                    self.emask = ptr_new(rmbin)                 ;APPLY MASK TO emask HERE


                    sz = size(*(self.e))
                    if ptr_valid(self.Iup) gt 0 then ptr_free,self.Iup
                    self.Iup = ptr_new(dblarr(sz[1],sz[3])+1.0)
                    if ptr_valid(self.Idown) gt 0 then ptr_free,self.Idown
                    self.Idown = ptr_new(dblarr(sz[1],sz[3])+1.0)
                    if ptr_valid(self.sIup) gt 0 then ptr_free,self.sIup
                    self.sIup = ptr_new(dblarr(sz[1],sz[3])+1.0)
                    if ptr_valid(self.sIdown) gt 0 then ptr_free,self.sIdown
                    self.sIdown = ptr_new(dblarr(sz[1],sz[3])+1.0)
                    if ptr_valid(self.S) gt 0 then ptr_free,self.S
                    self.S = ptr_new(dblarr(sz[1],sz[3])+1.0)
                    if ptr_valid(self.sS) gt 0 then ptr_free,self.sS
                    self.sS = ptr_new(dblarr(sz[1],sz[3])+1.0)



;CHECK HERE TO SEE IF TIME AVERAGING WAS CHANGED.
;
;IF YES THEN                     self.IupdownSwitch = 0  ;INDICATE THAT Iup,down ARE NOT CALCULATED



                    self.IupdownSwitch = 0  ;INDICATE THAT Iup,down ARE NOT CALCULATED


        endif else begin


                    ptr_free,self.e
                    ptr_free,self.emask

                    ;SET NEW VALUE OF self.emask
                    self.e = ptr_new(rmbin)
                    self.emask = ptr_new(rmbin)                 ;APPLY MASK TO emask HERE



                ;REBIN MASKS AND ASSUME THEY CANNOT BE RECOVERED AFTER A BIN OPERATION.
                    maskmbin = intarr(self.x_dim*self.y_dim,self.no_of_fourier_times)
                    maskmbinold = intarr(self.x_dim*self.y_dim,self.no_of_fourier_times)

                    fitdisplaymaskmbin = intarr(self.x_dim*self.y_dim,self.no_of_fourier_times)
                    fitdisplaymaskmbinold = intarr(self.x_dim*self.y_dim,self.no_of_fourier_times)

                    ;063004
                    ;
                    ;UPDATE maskmbin WITH THE DEFAULT MASK.
                    ;
                    ;THE IMPLEMENTATAION WILL BE A FOR LOOP:
                    for m = 0,self.no_of_fourier_times-1 do begin
                       maskmbin[*,m] = self->defaultMask(binfactor=factor,xfactor=xfactor,yfactor=yfactor)
                       maskmbinold[*,m] = self->defaultMask(binfactor=factor,xfactor=xfactor,yfactor=yfactor)
                    endfor;m


                    if ptr_valid(self.mask2d) gt 0 then ptr_free,self.mask2d
                    self.mask2d = ptr_new(maskmbin)
                    if ptr_valid(self.mask2dold) gt 0 then ptr_free,self.mask2dold
                    self.mask2dold = ptr_new(maskmbinold)

                    if ptr_valid(self.fitdisplaymask) gt 0 then ptr_free,self.fitdisplaymask
                    self.fitdisplaymask = ptr_new(fitdisplaymaskmbin)
                    if ptr_valid(self.fitdisplaymaskold) gt 0 then ptr_free,self.fitdisplaymaskold
                    self.fitdisplaymaskold = ptr_new(fitdisplaymaskmbinold)



                                                                ;WHEN MASKING IS READY

                    ;070104
                    ;REPLACE statsMask WITH defaultMask ABOVE.
                    ;maskmbin = self->statsMask()
                    ;
                    ;NOTE:  REMOVING THE statsMask STEP HAS RESULTED
                    ;       IN A TREMENDOUS PERFORMANCE IMPROVEMENT
                    ;       WHEN READING IN THE DATA FILES!!! YES!!!


                    sz = size(*(self.e))

                    newfixed = intarr(6,sz[1],sz[3])
                    fixedtmp = (*self.fixed)[*,0,0]
                    newfixed[0,*,*] = fixedtmp[0]
                    newfixed[1,*,*] = fixedtmp[1]
                    newfixed[2,*,*] = fixedtmp[2]
                    newfixed[3,*,*] = fixedtmp[3]
                    newfixed[4,*,*] = fixedtmp[4]
                    newfixed[5,*,*] = fixedtmp[5]
                    if ptr_valid(self.fixed) gt 0 then ptr_free,self.fixed
                    self.fixed = ptr_new(newfixed)

                    newparms = dblarr(12,sz[1],sz[3])+1.0
                    newparms[0,*,*] = 200.0
                    newparms[1,*,*] = 100.0
                    newparms[2,*,*] = 200.0
                    newparms[3,*,*] = 702.0
                    newparms[4,*,*] = 1.0
                    newparms[5,*,*] = 0.0
                    newparmsOld = newparms
                    newchisq = $
                        dblarr(self.x_dim*self.y_dim,self.no_of_fourier_times) + 100000000.0
                    newchisqOld = newchisq

                    if ptr_valid(self.fitparms) gt 0 then ptr_free,self.fitparms
                    self.fitparms = ptr_new(newparms)
                    if ptr_valid(self.chisq) gt 0 then ptr_free,self.chisq
                    self.chisq = ptr_new(newchisq)
                    if ptr_valid(self.fitparmsOld) gt 0 then ptr_free,self.fitparmsOld
                    self.fitparmsOld = ptr_new(newparmsOld)
                    if ptr_valid(self.chisqOld) gt 0 then ptr_free,self.chisqOld
                    self.chisqOld = ptr_new(newchisqOld)
                    if ptr_valid(self.Iup) gt 0 then ptr_free,self.Iup
                    self.Iup = ptr_new(dblarr(sz[1],sz[3])+1.0)
                    if ptr_valid(self.Idown) gt 0 then ptr_free,self.Idown
                    self.Idown = ptr_new(dblarr(sz[1],sz[3])+1.0)
                    if ptr_valid(self.sIup) gt 0 then ptr_free,self.sIup
                    self.sIup = ptr_new(dblarr(sz[1],sz[3])+1.0)
                    if ptr_valid(self.sIdown) gt 0 then ptr_free,self.sIdown
                    self.sIdown = ptr_new(dblarr(sz[1],sz[3])+1.0)
                    if ptr_valid(self.S) gt 0 then ptr_free,self.S
                    self.S = ptr_new(dblarr(sz[1],sz[3])+1.0)
                    if ptr_valid(self.sS) gt 0 then ptr_free,self.sS
                    self.sS = ptr_new(dblarr(sz[1],sz[3])+1.0)
                    if ptr_valid(self.QVals) gt 0 then ptr_free,self.QVals
                    self.QVals = ptr_new(dblarr(sz[1],sz[3])+self.qactual);q)

                    self.reduced = 0        ;INDICATE THAT THE DATA ARE NO LONGER REDUCED
                    self.reducedOld = 0
                    self.QValsSwitch = 0    ;INDICATE THAT QValues ARE NOT CALCULATED
                    self.IupdownSwitch = 0  ;INDICATE THAT Iup,down ARE NOT CALCULATED



        endelse;new factor ne old factor

    ;endelse;TIME AVERAGE



end;ooEchoMagnetic::bin
