; $Id: nsediffractionviewer.pro,v 1.34 2007/03/01 21:04:48 kneller Exp $
;###############################################################################
;
;FILENAME:
;        nsediffractionviewer.pro
;
;PURPOSE:
;
;CATEGORY:
;
;
;METHODS IN FILE:
;
;METHODS:
;    NSEDiffractionViewer_deadTime
;    NSEDiffractionViewer_read
;    NSEDiffractionViewer_open
;    NSEDiffractionViewer_event
;    NSEDiffractionViewer_cleanup
;    NSEDiffractionViewer
;
;
; AUTHOR:
; Larry Kneller
; NIST Center for Neutron Research
; 100 Bureau Drive, Gaithersburg, MD 20899
; United States
; kneller@nist.gov  301-975-8839
; Thu May 18 14:29:00 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.
;
;###############################################################################




;###############################################################################
;NAME:
;        NSEDiffractionViewer_deadTime
;
;PURPOSE:
;           PERFORM THE DEADTIME AND MONITOR CORRECTIONS FOR A SINGLE DETECTOR IMAGE.
;PARAMETERS:
;           im      A SINGLE DETECTOR IMAGE TO CORRECT.
;KEYWORDS:
;           none
;RETURN VALUE:
;           THE CORRECTED DETECTOR IMAGE.
;;
;###############################################################################
function NSEDiffractionViewer_deadTime,im,counter0,counter4,preset,counter1,counter2,counter3


;counters[*,i,j] = double(segs[1:10])
;counters    42448.0       0.0       0.0       0.0  184792.0       0.0       0.0       0.0       0.0       0.0

;IF counter4 is 0, THEN COUNTS ARE RECORDED IN
;LATER ADD TEST FOR FILE NUMBER OR OTHER PARAMETERS.
;if filenum ge 4158 then begin
    if counter4 eq 0 then begin
        counter4 = counter0 ;actual preset  (NOMINAL PRESET IS preset)
        counter0 = counter3 ;time
    endif
;endif
    ;SCALE DATA TO ACTUAL NUMBER OF MONITOR COUNTS.

;WHY IS THIS SCALE HERE?  IS THIS A MISTAKE?????
;WHAT IS PRESET?
;SET TO 1 FOR NOW.
    monitorscale = 1.0;(double(preset)/double(counter4))
    DeadTime = 0.7e-6

    CountRate = mean(im*monitorscale)*double(n_elements(im))/(double(counter0)/9871.5d)
    deadScale = 1.0/(1-DeadTime*CountRate)
    newim = im*deadScale;long(im*deadScale)

    return,newim
end;deadTime


Function NSEDiffractionViewer_f_polanalysisgeneral,Verbose,$
                                                self_p,$
                                                self_no_of_fourier_time,$
                                                self_Eff_BPW,$
                                                self_f,$
                                                self_xyzupdownscale,$
                                                xdown,$
                                                xup,$
                                                ydown,$
                                                yup,$
                                                zdown,$
                                                zup,$
                                                self_mask2d,$
                                                self_preset,$
                                                self_q,$
                                                self_qvals,$
                                                self_narcs,$
                                                self_arcmat,$
;CALL THIS WITH THE ABOVE ARGUMENTS EACH TIME A NEW SET OF SIX ARRAYS IS READ
                                                xvals=xvals,$
                                                plotdata=plotdata,$
                                                eplotdata=eplotdata,$
                                                image=image,$
                                                eimage=eimage,$
                                                theimageindex=theimageindex,$
                                                magneticImage=magneticImage,$
                                                emagneticImage=emagneticImage,$
                                                spinCoherentImage=spinCoherentImage,$
                                                espinCoherentImage=espinCoherentImage,$
                                                CoherentAndIsotopeIncoherentImage=CoherentAndIsotopeIncoherentImage,$
                                                eCoherentAndIsotopeIncoherentImage=eCoherentAndIsotopeIncoherentImage,$
                                                TotalImage=TotalImage,$
                                                eTotalImage=eTotalImage,$
                                                pixel=pixel,$
                                                magq1d=magq1d,$
                                                sq1dtotal=sq1dtotal,$
                                                sq1dmagnetic=sq1dmagnetic,$
                                                sq1dspinIncoherent=sq1dspinIncoherent,$
                                                sq1dCoherentAndIsotopeIncoherent=sq1dCoherentAndIsotopeIncoherent,$
                                                timeaverage=timeaverage



;
;NAME:
;        NSEDiffractionViewer_f_polanalysisgeneral
;
;PURPOSE:
;               Calculate components of S(Q) for the magnetic systems.
;PARAMETERS:
;               Verbose             Flag for print the results.
;
;KEYWORDS:
;               xvals               Fourier times
;               plotdata            An array containing the 4 data sets to be plotted (averaged over entire image???)
;               image               Time averaged image of choice theImageIndex
;               eimage              error bars for the image
;               theimageindex       The choice of image
;                                       theimageindex = 4  ;magnetic
;                                       theimageindex = 6  ;spin incoherent
;                                       theimageindex = 8  ;coherent and isotope incoherent
;                                       theimageindex = 10 ;total (SHOULD EQUAL S(Q)!!!!)
;
;               pixel               Pixel choice for single pixel return values.
;                                   (For plot of Mag variable v. time at each pixel.)
;                                   Value of pixel should be (ysize*ycoord + xcoord), i.e. a 1-d index
;
;SPECIFIC IMAGE CHOICES:
;               magneticImage
;               emagneticImage
;               spinCoherentImage
;               espinCoherentImage
;               CoherentAndIsotopeIncoherentImage
;               eCoherentAndIsotopeIncoherentImage
;               TotalImage
;               eTotalImage




;CURRENTLY I PRODUCE THE IMAGE.
;IT SHOULD BE A SIMPLE EXPANSION TO GET THE 4 IMAGES, AND USE AN OUTSIDE METHOD TO DO THE
;TIME AVERAGING FOR EACH Q-ARC.
;
;BUT I NEED TO TELL S(Q) TO PLOT ALL 4 COMPONENTS.  CAN I DO THIS BY HAVING THE MAGNETIC CASE POP UP 4 TIMES
;IN THE EXISTING S(Q) PLOTTER????
;
;
;


	;	This calculates the different scattering cross sections from a xyz polarization
	;	measurement (waves PCounts and PCountsErr2) and puts the result in a
	;	wave "Sc". The background is neglected. It is assumed that the counts are
	;	arranged in the following order: P perpendicular to Q and horizontal (x), DOWN and UP;
	;	P vertical (z), DOWN and UP; P parallel to Q and horizontal (y), DOWN and UP.
	;	It is assumed that UP is counted with the flipper ON. General formulae are used,
	;	no assumptions about inelasticity or symmetric alignment are made.
	;	If Verbose is true, the results are printed in the history area.

	;	This version takes different beam polarisations in all 3 directions into account.
	;	Consequently, there is only one expression for the magnetic scattering, not two.
	;	Supply the beam polarisation as waves eff_BeamPol[ndet][3] and eff_BeamPolErr2[ndet][3] (xzy).
	;	gPolEff accounts for another global depolarisation due to the sample.
	;	The flipper efficiency is still a global.

    if n_elements(verbose) eq 0 then verbose = 0
    if n_elements(timeaverage) eq 0 then timeaverage = 0

;020706
;
;THERE ARE TESTING PROBLEMS WITH VERBOSE SET TO 1, SO ALWAYS SET TO 0 FOR NOW.

    verbose = 0
    if n_elements(pixel) eq 0 then pixel = -1
    if n_elements(magq1d) eq 0 then magq1d = 0 ; SET THIS TO 0,1,2,3,4 FOR EACH OF THE COMPONENTS????

;
;	Wave PAC = PCounts

;REPLACE self.x_dim*self.ydim WITH 1024 AND self.no_of_fourier_times WITH 1
;PAC = dblarr(6,self.x_dim*self.y_dim,self.no_of_fourier_times)   ;SET VALUE IN LOOP BELOW.
PAC = dblarr(6,n_elements(xup),1)   ;SET VALUE IN LOOP BELOW.
dimSize = size(PAC)
;	ndet = dimSize(PAC,1)
ndet = n_elements(xup);dimSize[2];self.x_dim*self.y_dim
;	ntof = dimSize(PAC,2)
ntof = 1;dimSize[3];self.no_of_fourier_times

;print,'ntof=',ntof

;	Wave Err2 = PCountsErr2
Err2 = dblarr(6,ndet,ntof)
;	Wave eff_BPW = eff_BeamPol
eff_BPW = dblarr(ndet,3)
eff_BPW[*,0] = self_eff_BPW
eff_BPW[*,1] = self_eff_BPW
eff_BPW[*,2] = self_eff_BPW  ;THIS IS ONLY A SCALAR RIGHT NOW

;	Wave eff_BPE2 = eff_BeamPolErr2
eff_BPE2 = dblarr(ndet,3)
eff_BPE2 = 0.02*eff_BPW      ;I DON'T HAVE THESE VALUES RIGHT NOW.  Just assume 2%.

;020706
;THIS IS ERROR SQUARED
eff_BPE2 = (0.02*eff_BPW)^2

;	Variable Pol,PolErr,FlipEff,FlipEffErr
Pol = self_P
PolErr = 0.02*Pol
FlipEff = self_f
FlipEffErr = 0.02*self_f

;	Variable/g gPolEff,gPieff
gPolEff = 0.0
gPieff = 0.0
;	Variable/g gPolEffErr,gPieffErr
gPolEffErr = 0.0
gPieffErr = 0.0

;	String cmd
cmd = ''

;	Make/O/N=(14,ndet,ntof) Sc			;	values and squared errors
Sc = dblarr(14,ndet,ntof)
;	Make/N=(ndet,ntof) xx,yy,zz,aa,bb,cc
xx = dblarr(ndet,ntof)
yy = dblarr(ndet,ntof)
zz = dblarr(ndet,ntof)
aa = dblarr(ndet,ntof)
bb = dblarr(ndet,ntof)
cc = dblarr(ndet,ntof)
Sc = dblarr(14,ndet,ntof)
sxx = dblarr(ndet,ntof)
syy = dblarr(ndet,ntof)
szz = dblarr(ndet,ntof)

xx_tave = dblarr(ndet)
yy_tave = dblarr(ndet)
zz_tave = dblarr(ndet)
aa_tave = dblarr(ndet)
bb_tave = dblarr(ndet)
cc_tave = dblarr(ndet)
Sc_tave = dblarr(14,ndet)
sxx_tave = dblarr(ndet)
syy_tave = dblarr(ndet)
szz_tave = dblarr(ndet)




;
;	; 1. Provide the beam polarization and the flipper efficiency.
	if (gPolEff eq 0.0) then begin
		gPolEff = 1.0
		gPolEffErr = 0.0
	endif
	if (gPieff eq 0.0) then begin
		gPieff = 1
		gPieffErr = 0
	endif
	Pol = gPolEff
	PolErr = gPolEffErr		;	will be neglected
	FlipEff = gPieff
	FlipEffErr = gPieffErr

;	; 2. dummies
	Sc[0,*,*] = 0.0
	Sc[1,*,*] = 0.0
	Sc[2,*,*] = 0.0
	Sc[3,*,*] = 0.0

;	; 3. Preparation
        for k=0,ntof-1 do begin

                tauind = k

;02/07/06
;THE Err2 VALUES ARE THE ERROR BARS SQUARED!!!!!
;ADDING THE SQUARE OPERATIONS TODAY.

                pac[0,*,k]  = xdown;self->helpChirpIup_downXYZArray(self.point_to_down_x,tauind)

                Err2[0,*,k] = sqrt(xdown);(self->helpChirpIup_downXYZArray_eb(self.point_to_down_x,tauind))^2

                pac[1,*,k]  = xup;self->helpChirpIup_downXYZArray(self.point_to_up_x,tauind)
                Err2[1,*,k] = sqrt(xup);(self->helpChirpIup_downXYZArray_eb(self.point_to_up_x,tauind))^2

                pac[4,*,k]  = ydown;self->helpChirpIup_downXYZArray(self.point_to_down_y,tauind)
                Err2[4,*,k] = sqrt(ydown);(self->helpChirpIup_downXYZArray_eb(self.point_to_down_y,tauind))^2

                pac[5,*,k]  = yup;self->helpChirpIup_downXYZArray(self.point_to_up_y,tauind)
                Err2[5,*,k] = sqrt(yup);(self->helpChirpIup_downXYZArray_eb(self.point_to_up_y,tauind))^2

                pac[2,*,k]  = zdown;self->helpChirpIup_downXYZArray(self.point_to_down_z,tauind)
                Err2[2,*,k] = sqrt(zdown);(self->helpChirpIup_downXYZArray_eb(self.point_to_down_z,tauind))^2

                pac[3,*,k]  = zup;self->helpChirpIup_downXYZArray(self.point_to_up_z,tauind)
                Err2[3,*,k] = sqrt(zup);(self->helpChirpIup_downXYZArray_eb(self.point_to_up_z,tauind))^2


                xx[*,k]  = self_xyzupdownscale*(pac[1,*,k]-pac[0,*,k])/(self_p*self_eff_BPW*(self_f+1.0))
                sxx[*,k] = self_xyzupdownscale*sqrt(Err2[1,*,k]^2.0 + Err2[0,*,k]^2.0)/ $
                                                                (self_p*self_eff_BPW*(self_f+1.0))

                yy[*,k]  = self_xyzupdownscale*(pac[5,*,k]-pac[4,*,k])/(self_p*self_eff_BPW*(self_f+1.0))
                syy[*,k] = self_xyzupdownscale*sqrt(Err2[5,*,k]^2.0 + Err2[4,*,k]^2.0)/ $
                                                                (self_p*self_eff_BPW*(self_f+1.0))

                zz[*,k]  = self_xyzupdownscale*(pac[3,*,k]-pac[2,*,k])/(self_p*self_eff_BPW*(self_f+1.0))
                szz[*,k] = self_xyzupdownscale*sqrt(Err2[3,*,k]^2.0 + Err2[2,*,k]^2.0)/ $
                                                                (self_p*self_eff_BPW*(self_f+1.0))


                aa[*,k] = self_xyzupdownscale*(self_f*pac[0,*,k] + pac[1,*,k])/(self_f+1.0)
                bb[*,k] = self_xyzupdownscale*(self_f*pac[2,*,k] + pac[3,*,k])/(self_f+1.0)
                cc[*,k] = self_xyzupdownscale*(self_f*pac[4,*,k] + pac[5,*,k])/(self_f+1.0)



                ;SET UP CRUDE TIME AVERAGES
                xx_tave = xx_tave + xx[*,k]
                yy_tave = yy_tave + yy[*,k]
                zz_tave = zz_tave + zz[*,k]
                aa_tave = aa_tave + aa[*,k]
                bb_tave = bb_tave + bb[*,k]
                cc_tave = cc_tave + cc[*,k]



        endfor;k



;THIS WILL BE HANDLED OUTSIDE, BUT IT MAY BE USEFUL TO HANDLE HERE AS WELL,
;SINCE ANTONIO REQUESTED A
        if timeaverage ne 0 then begin
            print,'f_polanal... test time average'
            for k = 0,ntof-1 do begin
                ;CALCULATE TIME AVERAGES
                xx[*,k] = xx_tave/ntof
                yy[*,k] = yy_tave/ntof
                zz[*,k] = zz_tave/ntof
                aa[*,k] = aa_tave/ntof
                bb[*,k] = bb_tave/ntof
                cc[*,k] = cc_tave/ntof
            endfor;k
        endif;timeaverage
;
;	; 4. Calculate the magnetic scattering
    Sc[4,*,*] = 4.0*zz-2.0*xx-2.0*yy


	Sc[5,*,*] = FlipEffErr*FlipEffErr*(-4*zz/(FlipEff+1)+2*xx/(FlipEff+1)+2*yy/(FlipEff+1))^2
	Sc[5,*,*] += eff_BPE2[0,0]*(2*xx/eff_BPW[0,0])^2
	Sc[5,*,*] += eff_BPE2[0,1]*(4*zz/eff_BPW[0,1])^2
	Sc[5,*,*] += eff_BPE2[0,2]*(2*yy/eff_BPW[0,2])^2
	Sc[5,*,*] += (Err2[3,*,*]+Err2[2,*,*])*(4/Pol/eff_BPW[0,1]/(FlipEff+1))^2		;	count err z
	Sc[5,*,*] += (Err2[1,*,*]+Err2[0,*,*])*(2/Pol/eff_BPW[0,0]/(FlipEff+1))^2		;	count err x
	Sc[5,*,*] += (Err2[5,*,*]+Err2[4,*,*])*(2/Pol/eff_BPW[0,2]/(FlipEff+1))^2		;	count err y





;
;	; 5. Calculate spin incoherent scattering

	Sc[6,*,*] = -9*zz+3*xx+3*yy+aa+bb+cc
	Sc[7,*,*] = FlipEffErr*FlipEffErr* $
	            ((9*zz-3*xx-3*yy-(Pol*eff_BPW[0,0]*xx+Pol*eff_BPW[0,1]*zz+Pol*eff_BPW[0,2]*yy))/(FlipEff+1))^2
	Sc[7,*,*] += eff_BPE2[0,0]*(3*xx/eff_BPW[0,0])^2
	Sc[7,*,*] += eff_BPE2[0,1]*(9*zz/eff_BPW[0,1])^2
	Sc[7,*,*] += eff_BPE2[0,2]*(3*yy/eff_BPW[0,2])^2
	Sc[7,*,*] += (Err2[1,*,*]*(Pol*eff_BPW[0,0]+3)^2+ $
	              Err2[0,*,*]*(FlipEff*Pol*eff_BPW[0,0]-3)^2)*(1/Pol/eff_BPW[0,0]/(FlipEff+1))^2		;	count err x
	Sc[7,*,*] += (Err2[5,*,*]*(Pol*eff_BPW[0,2]+3)^2+ $
	              Err2[4,*,*]*(FlipEff*Pol*eff_BPW[0,2]-3)^2)*(1/Pol/eff_BPW[0,2]/(FlipEff+1))^2		;	count err y
	Sc[7,*,*] += (Err2[3,*,*]*(Pol*eff_BPW[0,1]-9)^2+ $
	              Err2[2,*,*]*(FlipEff*Pol*eff_BPW[0,1]+9)^2)*(1/Pol/eff_BPW[0,1]/(FlipEff+1))^2		;	count err z
	Sc[6,*,*] /= 2
	Sc[7,*,*] /= 4




;	; 6. Calculate isotope incoherent and coherent scattering

	Sc[8,*,*] = 3*zz +3*xx +3*yy +aa +bb +cc
	Sc[9,*,*] = FlipEffErr*FlipEffErr*((-3*zz -3*xx -3*yy -(Pol*eff_BPW[0,0]*xx +Pol*eff_BPW[0,1]*zz +Pol*eff_BPW[0,2]*yy ))/(FlipEff+1))^2
	Sc[9,*,*] += eff_BPE2[0,0]*(3*xx /eff_BPW[0,0])^2
	Sc[9,*,*] += eff_BPE2[0,1]*(3*zz /eff_BPW[0,1])^2
	Sc[9,*,*] += eff_BPE2[0,2]*(3*yy /eff_BPW[0,2])^2
	Sc[9,*,*] += (Err2[1,*,*]*(Pol*eff_BPW[0,0]+3)^2+Err2[0,*,*]*(FlipEff*Pol*eff_BPW[0,0]-3)^2)*(1/Pol/eff_BPW[0,0]/(FlipEff+1))^2		;	count err x
	Sc[9,*,*] += (Err2[5,*,*]*(Pol*eff_BPW[0,2]+3)^2+Err2[4,*,*]*(FlipEff*Pol*eff_BPW[0,2]-3)^2)*(1/Pol/eff_BPW[0,2]/(FlipEff+1))^2		;	count err y
	Sc[9,*,*] += (Err2[3,*,*]*(Pol*eff_BPW[0,1]+3)^2+Err2[2,*,*]*(FlipEff*Pol*eff_BPW[0,1]-3)^2)*(1/Pol/eff_BPW[0,1]/(FlipEff+1))^2		;	count err z
	Sc[8,*,*] /= 6
	Sc[9,*,*] /= 36


;	; 7. Calculate the sum of all contributions

	Sc[10,*,*] = aa +bb +cc
	Sc[11,*,*] = FlipEffErr*FlipEffErr*((Pol*eff_BPW[0,0]*xx +Pol*eff_BPW[0,1]*zz +Pol*eff_BPW[0,2]*yy )/(FlipEff+1))^2
	Sc[11,*,*] += (Err2[0,*,*]+Err2[1,*,*]+Err2[2,*,*]+Err2[3,*,*]+Err2[4,*,*]+Err2[5,*,*])/(FlipEff+1)^2
	Sc[10,*,*] /= 1.5
	Sc[11,*,*] /= 2.25




;
;	; 8. Calculate the angle epsilon

    ww = dblarr(6,ndet,ntof)

	ww[5,*,*] = abs((PAC[0,*,*]-PAC[2,*,*])/(PAC[4,*,*]-PAC[2,*,*]))
	ww[1,*,*] = atan(sqrt(abs(PAC[0,*,*]-PAC[2,*,*])),sqrt(abs(PAC[4,*,*]-PAC[2,*,*])))
	ww[3,*,*] = 1/4/ww[5,*,*]/((1+ww[5,*,*])^2)/((PAC[4,*,*]-PAC[2,*,*])^4)*(Err2[0,*,*]*(PAC[4,*,*]-PAC[2,*,*])^2+Err2[2,*,*]*(PAC[0,*,*]-PAC[4,*,*])^2+Err2[4,*,*]*(PAC[0,*,*]-PAC[2,*,*])^2)
	ww[5,*,*] = abs((PAC[3,*,*]-PAC[1,*,*])/(PAC[3,*,*]-PAC[5,*,*]))
	ww[2,*,*] = atan(sqrt(abs(PAC[3,*,*]-PAC[1,*,*])),sqrt(abs(PAC[3,*,*]-PAC[5,*,*])))
	ww[4,*,*] = 1/4/ww[5,*,*]/((1+ww[5,*,*])^2)/((PAC[5,*,*]-PAC[3,*,*])^4)*(Err2[1,*,*]*(PAC[5,*,*]-PAC[3,*,*])^2+Err2[3,*,*]*(PAC[1,*,*]-PAC[5,*,*])^2+Err2[5,*,*]*(PAC[1,*,*]-PAC[3,*,*])^2)
	ww[0,*,*] = 1/ww[3,*,*]+1/ww[4,*,*]
	Sc[12,*,*] = 180/!PI*(ww[1,*,*]/ww[3,*,*]+ww[2,*,*]/ww[4,*,*])/ww[0,*,*]
	Sc[13,*,*] = 180/!PI*180/!PI/ww[0,*,*]
;	Sc[13,*,*] = 180/!PI*sqrt(1/ww[0,*,*])




;
;	; 9. Results - sum over the whole detector

;DO AVERAGE IN THE
;   1) T DIRECTION
;   2) x-y DIRECTION


;1)
sz = size(Sc)

;ALTER SIZE RESULT SINCE THE 3rd DIM IS 1
sz[3] = 1


;CREATE AREA AVERAGED- AND TIME AVERAGED- ARRAYS
m011_Sc = dblarr(14,1,ntof)
mtimeAv_Sc = dblarr(14,ndet,1)



wh = where(self_mask2d gt 0,count);*self.mask2d gt 0,count)


;AREA AVERAGING
if count gt 0 then begin
    for j=0,ntof-1 do begin
        count = 0
;120705
;CONVERT THE NEXT TO ARRAY OPS
;        for i=0,ndet-1 do begin
;            if (*self.mask2d)[i,j] gt 0 then begin
;                for k=0,(sz[1]/2)-1 do begin
;                    ;if j eq 0 then print,2*k,'_____',Sc[2*k,i,j],'+/-',Sc[2*k+1,i,j]
;                    m011_Sc[2*k,0,j] += Sc[2*k,i,j]/Sc[2*k+1,i,j]^2.0
;                    m011_Sc[2*k+1,0,j] += 1.0d/Sc[2*k+1,i,j]^2.0
;                endfor;k
;                count++
;            endif
;        endfor;i

        wh_mask2d = where(self_mask2d[*,j] gt 0,count);(*self.mask2d)[*,j] gt 0,count)

        if count gt 0 then begin
            for k=0,(sz[1]/2)-1 do begin

;ORIGINAL PRIOR TO 02/07/06
;                m011_Sc[2*k,0,j] = total((Sc[2*k,wh_mask2d,j]/Sc[2*k+1,wh_mask2d,j]^2.0),2)
;                m011_Sc[2*k+1,0,j] = total((1.0d/Sc[2*k+1,wh_mask2d,j]^2.0),2)

;I BELIEVE THAT THE ODD INDEX VALUES ARE THE ERROR BARS SQUARED!!!!
                m011_Sc[2*k,0,j] = total((Sc[2*k,wh_mask2d,j]/Sc[2*k+1,wh_mask2d,j]),2)
                m011_Sc[2*k+1,0,j] = total((1.0d/Sc[2*k+1,wh_mask2d,j]),2)



            endfor;k
        endif


        for k=0,(sz[1]/2)-1 do begin

;THIS SHOULD BE UNCHANGED
            m011_Sc[2*k,0,j] = m011_Sc[2*k,0,j]/m011_Sc[2*k+1,0,j];(m011_Sc[2*k+1,0,j] eq 0 ? double('NaN')  : m011_Sc[2*k,0,j]/m011_Sc[2*k+1,0,j])
            m011_Sc[2*k+1,0,j] = 1.0d/sqrt(m011_Sc[2*k+1,0,j])
        endfor;k
    endfor;j
endif


;TIME AVERAGING
;120705
;CONVERT TO ARRAY OPS IF POSSIBLE
if count gt 0 then begin
    for j=0,ndet-1 do begin
        count = 0
        for i=0,ntof-2 do begin
            if self_mask[j,i] gt 0 then begin;(*self.mask2d)[j,i] gt 0 then begin
                for k=0,sz[1]-1 do begin
                    mtimeAv_Sc[k,j,0] += Sc[k,j,i]
                endfor;k
                count++
            endif
        endfor;i
        for k=0,sz[1]-1 do begin
            mtimeAv_Sc[k,j,0] = (count eq 0 ? 0.0  : mtimeAv_Sc[k,j,0]/double(count))

        endfor;k
    endfor;j
endif




device,get_decomposed = dc

                    if n_elements(theimageindex) eq 0 then theimageindex = 0
                    theimageindex = 4+2*theimageindex
                    ;theimageindex = 4  ;magnetic
                    ;theimageindex = 6  ;spin incoherent
                    ;theimageindex = 8  ;coherent and isotope incoherent
                    ;theimageindex = 10 ;total
                    if arg_present(image) then $
                        image = reform(mtimeAv_Sc[theimageindex,*,0],sqrt(ndet),sqrt(ndet))
                    if arg_present(eimage) then $
                        eimage = reform(mtimeAv_Sc[theimageindex+1,*,0],sqrt(ndet),sqrt(ndet))


                ;020606 SET UP INDIVIDUAL PIXEL SELECTION
                    ;HERE

                    if arg_present(plotdata) gt 0 or arg_present(eplotdata) gt 0 then begin
                        if pixel ne -1 then begin
                        ;DO I HAVE THE CURRENTLY SELECTED PIXEL?
                            ;print,pixel
                            Sc_pixel = [Sc[4,pixel,*],Sc[6,pixel,*],Sc[8,pixel,*],Sc[10,pixel,*]]
                            eSc_pixel = sqrt([Sc[4+1,pixel,*],Sc[6+1,pixel,*],Sc[8+1,pixel,*],Sc[10+1,pixel,*]])
                            plotdata = reform(Sc_pixel,4*sz[3])
                            eplotdata = reform(eSc_pixel,4*sz[3])
                        endif else begin
                                ;plotdata = reform(m011_Sc[4,0,*],sz[3])
                                m011_Sc_all = [reform(m011_Sc[4,0,*],sz[3]),$
                                                reform(m011_Sc[6,0,*],sz[3]),$
                                                reform(m011_Sc[8,0,*],sz[3]),$
                                                reform(m011_Sc[10,0,*],sz[3])]


                        ;IS THE NEXT LINE REALLY THE ERROR BARS OR SOMETHING FROM WHICH THEY WOULD BE DERIVED?????
                                em011_Sc_all = sqrt([m011_Sc[4+1,0,*],m011_Sc[6+1,0,*],m011_Sc[8+1,0,*],m011_Sc[10+1,0,*]])
                            plotdata = reform(m011_Sc_all,4*sz[3])
                            eplotdata = reform(em011_Sc_all,4*sz[3])
                        endelse
                        ;help,m011_Sc_all
                        ;help,plotdata
                    endif;arg_present(plotdata)

;#############################################
;HAVING THESE IMAGES AND THE ABILITY TO GET THE Q ARCS MATRIX AND Q VALUES MEANS THAT I CAN
;EASILY MAKE EACH COMPONENT OF THE S(Q) AVAILABLE.
;#############################################

    if arg_present(magneticImage) gt 0 then begin
            MagneticImage = reform(mtimeAv_Sc[4,*,0],sqrt(ndet),sqrt(ndet))
    endif
    if arg_present(emagneticImage) gt 0 then begin
            eMagneticImage = sqrt(reform(mtimeAv_Sc[4+1,*,0],sqrt(ndet),sqrt(ndet)))
    endif
    if arg_present(spinCoherentImage) gt 0 then begin
            spinCoherentImage = reform(mtimeAv_Sc[6,*,0],sqrt(ndet),sqrt(ndet))
    endif
    if arg_present(espinCoherentImage) gt 0 then begin
            espinCoherentImage = sqrt(reform(mtimeAv_Sc[6+1,*,0],sqrt(ndet),sqrt(ndet)))
    endif
    if arg_present(CoherentAndIsotopeIncoherentImage) gt 0 then begin
            CoherentAndIsotopeIncoherentImage = reform(mtimeAv_Sc[8,*,0],sqrt(ndet),sqrt(ndet))
    endif
    if arg_present(eCoherentAndIsotopeIncoherentImage) gt 0 then begin
            eCoherentAndIsotopeIncoherentImage = sqrt(reform(mtimeAv_Sc[8+1,*,0],sqrt(ndet),sqrt(ndet)))
    endif

;print,'BEGIN TOTAL'
if arg_present(SQ1DTotal) gt 0 or $
    arg_present(TotalImage) gt 0 or $
     arg_present(eTotalImage) gt 0 then begin


                mask = self_mask2d;fix(0*xup + 1)
                mat = self_arcmat;fix(0*xup)
                theQvals = self_qvals;(0*xup) + self_q


                sz = size(Sc)

            ;ALTER SIZE RESULT SINCE THE 3rd DIM IS 1
            sz[3] = 1


                whrmask = where(mask le 0,count)
                if count ne 0 then begin
                    mask[whrmask] = 0
                endif

                etot = reform(Sc[10,*,*],sz[2],sz[3])  ;total(e[*,0:self->term()-1,*],2)
                setot = reform(sqrt(Sc[11,*,*]),sz[2],sz[3])



                if n_elements(narcs) eq 0 then narcs = self_narcs


            ;SORT BY ARCS
            SQ1DTotal = NSEDiffractionViewer_sortByQArcs(narcs,theQVals,etot,setot,$
                                                         mask,mat,self_q,self_preset)

endif;SQ1DTotal


;print,'BEGIN MAGNETIC'
if arg_present(sq1dmagnetic) gt 0 or $
    arg_present(TotalImage) gt 0 or $
     arg_present(eTotalImage) gt 0 then begin


                mask = self_mask2d;fix(0*xup + 1)
                mat = self_arcmat;fix(0*xup)
                theQvals = self_qvals;(0*xup) + self_q

                sz = size(Sc)

            ;ALTER SIZE RESULT SINCE THE 3rd DIM IS 1
            sz[3] = 1


                whrmask = where(mask le 0,count)
                if count ne 0 then begin
                    mask[whrmask] = 0
                endif

                etot = reform(Sc[4,*,*],sz[2],sz[3])  ;total(e[*,0:self->term()-1,*],2)
                setot = reform(sqrt(Sc[5,*,*]),sz[2],sz[3])


                if n_elements(narcs) eq 0 then narcs = self_narcs

SQ1Dmagnetic = NSEDiffractionViewer_sortByQArcs(narcs,theQVals,etot,setot,$
                                                mask,mat,self_q,self_preset)


endif;sq1dmagnetic






;print,'BEGIN SPININCOHERENT'
if arg_present(sq1dspinIncoherent) gt 0 or $
    arg_present(TotalImage) gt 0 or $
     arg_present(eTotalImage) gt 0 then begin


                mask = self_mask2d;fix(0*xup + 1)
                mat = self_arcmat;fix(0*xup)
                theQvals = self_qvals;(0*xup) + self_q

                sz = size(Sc)


        ;ALTER SIZE RESULT SINCE THE 3rd DIM IS 1
        sz[3] = 1

                whrmask = where(mask le 0,count)
                if count ne 0 then begin
                    mask[whrmask] = 0
                endif

                etot = reform(Sc[6,*,*],sz[2],sz[3])  ;total(e[*,0:self->term()-1,*],2)
                setot = reform(sqrt(Sc[7,*,*]),sz[2],sz[3])


                mat = intarr(sz[2])

                if n_elements(narcs) eq 0 then narcs = self_narcs

        SQ1Dspinincoherent = NSEDiffractionViewer_sortByQArcs(narcs,theQVals,etot,setot,$
                                                              mask,mat,self_q,self_preset)


endif;sq1dspinIncoherent


;print,'BEGIN COHERENT'
if arg_present(sq1dCoherentAndIsotopeIncoherent) gt 0 or $
    arg_present(TotalImage) gt 0 or $
     arg_present(eTotalImage) gt 0 then begin


        mask = self_mask2d;fix(0*xup + 1)
        mat = self_arcmat;fix(0*xup)
        theQvals = self_qvals;(0*xup) + self_q

        sz = size(Sc)

        ;ALTER SIZE RESULT SINCE THE 3rd DIM IS 1
            sz[3] = 1


        whrmask = where(mask le 0,count)
        if count ne 0 then begin
            mask[whrmask] = 0
        endif

        ;help,mask

        etot = reform(Sc[8,*,*],sz[2],sz[3])  ;total(e[*,0:self->term()-1,*],2)
        setot = reform(sqrt(Sc[9,*,*]),sz[2],sz[3])

        if n_elements(narcs) eq 0 then narcs = self_narcs
        SQ1DCoherentandIsotopeIncoherent = $
               NSEDiffractionViewer_sortByQArcs(narcs,theQVals,etot,setot,$
                                                mask,mat,self_q,self_preset)


endif;sq1dCoherentAndIsotopeIncoherent


;print,'DONE'



    return,1
end;NSEDiffractionViewer_f_polanalysisgeneral


function NSEDiffractionViewer_sortByQArcs,narcs,theQVals,etot,setot,$
                                            mask,mat,self_q,self_preset

;print,'BEGIN NSEDiffractionViewer_sortByQArcs'
                s = dblarr(narcs)
                sS = dblarr(narcs)
                q = dblarr(narcs)
                qcount = intarr(narcs)
                sz = size(etot)
                if sz[0] eq 1 then sz[2] = 1
                for i=0,sz[1]-1 do begin
                    for j=0,sz[2]-1 do begin
                        for k=0,narcs-1 do begin
                            if mat[i] eq k and mask[i,j] ne 0 then begin
                                if finite (etot[i,j]) gt 0  and finite(1.0d/setot[i,j]) gt 0 then begin
                                    s[k] += etot[i,j]/setot[i,j]^2
                                    ss[k] += 1.0d/setot[i,j]^2

                                    q[k] += theQVals[i,j]
                                    qcount[k] += 1
                                endif;finite

                            endif

                        endfor;k
                    endfor;j
                endfor;i
;print,'Middle NSEDiffractionViewer_sortByQArcs'
                ;print,'qcount=',qcount
                qmin = min(theqvals)
                qmax = max(theqvals)

                for i=0,narcs-1 do begin
                    if qcount[i] ne 0 then begin
                        s[i] = s[i]/ss[i]
                        ss[i] = 1.0d/sqrt(ss[i])
                        q[i] = q[i]/double(qcount[i])
                    endif else begin
                        s[i] = 0.0
                        ss[i] = 0.0
                        if narcs ne 1 then begin
                            qstep = (qmax-qmin)/double(narcs-1)
                            q[i] = qmin + (double(i)+0.5)*qstep
                        endif else begin
                            q[i] = self_q;self->getproperty(tag='q')
                        endelse
                    endelse
                endfor;i

                s = s/double(self_preset)

                ss = ss/double(self_preset)

;help,/traceback

;print,'FINISH NSEDiffractionViewer_sortByQArcs'
    return,{s:ptr_new(s),ss:ptr_new(ss),q:ptr_new(q)}


end;NSEDiffractionViewer_sortByQArcs

function NSEDiffractionViewer_sortNonMagneticByQArcs,narcs,theQVals,dumup,dumdn,$
                                            mask,mat,self_q,self_preset,f


            etot = 0.5*(dumup+dumdn)
            setot = sqrt(0.5*(dumup+dumdn))


        ;SET UP CALCULATIONS FOR coherent and incoherent HERE
        ;BASED ON THE MATHEMATICA NOTEBOOK ANTONIO GOT FROM MONKENBUSCH.
        ;
            ;ecoh = ((-1-2*f)*dumdn - (f+2)*dumup - (-b + f*b))/(2*(f^2 - 1))
            ;eincoh = (-3*dumdn + 3*f*dumup - 3*(-b + f*b))/(2*(f^2 - 1))

            ecoh = ((1+2*f)*dumdn - (f+2)*dumup)/(2*(f^2 - 1))

            ;NOTE: FOR ADDING ERRORS IN QUADRATURE:
            ;sdumdn = sqrt(dumdn)
            ;sdumdn^2 = dumdn
            ;etc.
            secoh = sqrt(((1+2*f)^2)*dumdn + ((f+2)^2)*dumup)/abs(2*(f^2 - 1))

            eincoh = (-3*dumdn + 3*f*dumup)/(2*(f^2 - 1))
            seincoh = sqrt((((-3)^2)*dumdn + ((3)^2)*f*dumup))/abs(2*(f^2 - 1))



;HOW ARE COHERENT AND INCOHERENT SUMMED OVER Q ARCS???????
;SAME AS TOTAL?????????????
;
;HERE I WILL USE THE SAME METHOD AS TOTAL TO CALCULATE THE VALUES FOR EACH ARC.
;
;ONCE THIS IS COMPLETE FOR NONMAGNETIC SYSTEMS, THE SAME SHOULD BE EASILY
;CALCULABLE FOR MAGNETIC SYSTEMS, ____AND____ I COULD DO THESE CALCULATIONS AND
;COMPARE WITH GEORG'S USING AN INDEPENDENT METHOD!!!
;
;
;print,'BEGIN NSEDiffractionViewer_sortByQArcs'
                s = dblarr(narcs)
                sS = dblarr(narcs)

                s_coh = dblarr(narcs)
                s_scoh = dblarr(narcs)
                s_incoh = dblarr(narcs)
                s_sincoh = dblarr(narcs)

                q = dblarr(narcs)
                qcount = intarr(narcs)
                sz = size(etot)
                if sz[0] eq 1 then sz[2] = 1
                for i=0,sz[1]-1 do begin
                    for j=0,sz[2]-1 do begin
                        for k=0,narcs-1 do begin
                            if mat[i] eq k and mask[i,j] ne 0 then begin
                                if finite (etot[i,j]) gt 0  and finite(1.0d/setot[i,j]) gt 0 then begin
                                    s[k] += etot[i,j]/setot[i,j]^2
                                    ss[k] += 1.0d/setot[i,j]^2

                                    ;USE SAME WEIGHTINGS AS FOR TOTAL
                                    s_coh[k] += ecoh[i,j]/setot[i,j]^2
                                    s_scoh[k] += 1.0d/setot[i,j]^2
                                    s_incoh[k] += eincoh[i,j]/setot[i,j]^2
                                    s_sincoh[k] += 1.0d/setot[i,j]^2

                                    q[k] += theQVals[i,j]
                                    qcount[k] += 1
                                endif;finite
                            endif
                        endfor;k
                    endfor;j
                endfor;i
;print,'Middle NSEDiffractionViewer_sortByQArcs'
                ;print,'qcount=',qcount
                qmin = min(theqvals)
                qmax = max(theqvals)

                for i=0,narcs-1 do begin
                    if qcount[i] ne 0 then begin
                        s[i] = s[i]/ss[i]
                        ss[i] = 1.0d/sqrt(ss[i])

                        s_coh[i] = s_coh[i]/s_scoh[i]
                        s_scoh[i] = 1.0d/sqrt(s_scoh[i])
                        s_incoh[i] = s_incoh[i]/s_sincoh[i]
                        s_sincoh[i] = 1.0d/sqrt(s_sincoh[i])

                        q[i] = q[i]/double(qcount[i])
                    endif else begin
                        s[i] = 0.0
                        ss[i] = 0.0
                        s_coh[i] = 0.0
                        s_scoh[i] = 0.0
                        s_incoh[i] = 0.0
                        s_sincoh[i] = 0.0

                        if narcs ne 1 then begin
                            qstep = (qmax-qmin)/double(narcs-1)
                            q[i] = qmin + (double(i)+0.5)*qstep
                        endif else begin
                            q[i] = self_q;self->getproperty(tag='q')
                        endelse
                    endelse
                endfor;i

                s = s/double(self_preset)
                ss = ss/double(self_preset)

                s_coh = s_coh/double(self_preset)
                s_scoh = s_scoh/double(self_preset)
                s_incoh = s_incoh/double(self_preset)
                s_sincoh = s_sincoh/double(self_preset)

                s_tot = s_coh + s_incoh
                s_stot = sqrt(s_scoh^2 + s_sincoh^2)

;help,/traceback
;print,'FINISH NSEDiffractionViewer_sortByQArcs'
    return,{s:ptr_new(s),ss:ptr_new(ss),q:ptr_new(q),$
            s_tot:ptr_new(s_tot),s_stot:ptr_new(s_stot),$
            s_coh:ptr_new(s_coh),s_scoh:ptr_new(s_scoh),$
            s_incoh:ptr_new(s_incoh),s_sincoh:ptr_new(s_sincoh)}


end;NSEDiffractionViewer_sortNonMagneticByQArcs


function NSEDiffractionViewer_qvals,qmat,xcen,ycen,lambda,qactual

    ;lambda in Ang
    ;qactual in 1/Ang
    ;xcen,ycen in pixel value

    ;return 0 if there are NaN's in the qmat.
    ;else return,1



;    print,'NSEDiffractionViewer_qvals'
    qmat = dblarr(32,32)



;FIRST:
;NEED TO  GET LAMBDA
    wl = double(lambda);self.lambda)

;VARIABLES
    detdist = 4.35d
    xpixel = 0.01
    ypixel = 0.01


    qmin = 0.0d & qpix = 0.0d $
    & qc = 0.0d & qstep = 0.0d & il = 0 $
    & jl = 0 & iq = 0 $
    & qlmin = 0.0d & qlmax = 0.0d $
    & it = 0 & nt = 0

    qx = 0.0d & qy = 0.0d $
    & Fshift = 0 & filenum = 0



    ;THESE ARE NOT NECESSARY IN MY CONVENTIONS
    blockx = 1;self.x_dim_orig/self.x_dim
    blocky = 1;self.y_dim_orig/self.y_dim

    block = double(blockx)

    DetSizeX = 32;self.x_dim_orig
    DetSizeY = 32;self.y_dim_orig

    maxx = 32;DetSizeX/blockx  ;=self.x_dim
    maxy = 32;DetSizeY/blocky  ;=self.y_dim

    x_dim = 32
    y_dim = 32

    x_dim_orig = 32
    y_dim_orig = 32

    ;THE NEXT ASSIGNMENT IS DUE TO THE CONFUSION BETWEEN
    ;X,Y,HORIZONTAL AND VERTICAL.  THESE VALUES ARE READ
    ;FROM THE "SCAN" HEADER.


    ;030805
    ;UPDATE THE NEXT LINE TO USE self.qactual

    ;052005
    ;UPDATE THE NEXT LINE TO USE qy NOW THAT qy IS BEING READ FROM THE 6th SEGMENT
    ;OF THE Q LINE, AS IT IS IN IGOR.



    DetCenX = double(xcen);self.x_cen_orig)
    DetCenY = double(ycen);self.y_cen_orig)



    QArray = dblarr(maxx,maxy)


    hDetCen = double(xcen);self.x_cen_orig)
    vDetCen = double(ycen);self.y_cen_orig)

    hIndex = maxx
    vindex = maxy





;THIRD
;GET qactual
qcy = -1.0*qactual;self.qactual

    for il=0,hIndex-1 do begin
        for jl=0,vindex-1 do begin

            ilflip = double(x_dim - il)
            hDetCenflip = double(x_dim_orig - hDetCen)
            jlflip = double(jl)
            vDetCenflip = double(vDetCen)


            hQ = sin(asin((-1.0d)*qcy*double((10.0d)^(10.0d))*wl/4.0d/!DPI)- $
            atan((hDetCenflip-block*(ilflip))*xPixel/detdist)/2.0d)*4.0d*!DPI/wl
            vQ = sin(atan((block*(jlflip)- $
                vDetCenflip)*yPixel/detdist)/2.0d)*4.0d*!DPI/wl

            totQ = sqrt(vQ^2 + hQ^2)
            QArray[il,jl] = totQ/((10.0d)^(10.0d))   ;CONVERT TO 1/ANG
        endfor;jl
    endfor;il
    qmin = min(QArray)
    qmax = max(QArray)


    sz = size(QArray)

    QArray = transpose(reform(QArray,sz[n_elements(sz)-1]))

    QArray = transpose(QArray);New)

    qmat = QArray

    qmat = reform(qmat,1024)

    ;CHECK FOR NaN'S
    wh = where(finite(qmat,/nan) eq 1,wh_count)
    if wh_count eq 0 then return,1 else return,0

end;NSEDiffractionViewer_qvals

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function NSEDiffractionViewer_checkmagnetic,fn

                catch,error_status
                if error_status ne 0 then begin
                    catch,/cancel

                    help,lun,output=out
                    if stregex(out[0],'UNDEFINED',/fold_case,/boolean) eq 0 then begin
                        help,lun,/files,output=out
                        if stregex(out[1],'closed',/fold_case,/boolean) eq 0 then $
                        free_lun,lun
                    endif

                    if n_elements(x) gt 1 then begin
                        x = x[1:*]
                        if n_elements(y) gt 1 then y = y[1:*]
                        if n_elements(y) gt 1 then sy = sqrt(y)
                    endif else begin
                        x  = [-1.]
                        y  = [-1.]
                        sy = [-1.]
                    endelse
                    ;print,'WTF???'
                    return,-1;,dat
                endif


            detcount = 0
            qcount = 0



            nread = 0
            nlines = file_lines(fn)
            npix = 1024

            line=''
            q = 0.0d
            counters = dblarr(5)
            dumup = dblarr(npix)
            dumdn = dblarr(npix)
            x  = [-1.0d]
            y  = [-1.0d]
            sy = [-1.0d]


            openr,lun,fn,/get_lun



            readf,lun,line & nread++
            segs = strsplit(line,/extract)

            while nread lt nlines do begin

            ;{#################################################################################
                ;GET Q
                while strcmp(segs[0],'Q',/fold_case) eq 0 do begin ;readcount lt lines do begin
                    readf,lun,line & nread++
                    segs = strsplit(line,/extract)
                endwhile
                q = double(segs[1])
                ;print,'q=',q


                ;GET UP COUNTERS
                while strcmp(segs[0],'counters',/fold_case) eq 0 do begin
                    readf,lun,line & nread++
                    segs = strsplit(line,/extract)
                endwhile
                readf,lun,counters & nread++
                ;print,'counters=',counters
                ;GET UP IMAGE
                while strcmp(segs[0],'detector',/fold_case) eq 0 do begin
                    readf,lun,line & nread++
                    segs = strsplit(line,/extract)
                endwhile
                readf,lun,dumup  & nread += npix

                dumup = NSEDiffractionViewer_deadTime(dumup,counters[0],counters[4],counters[0],$;preset,$
                                                            counters[1],counters[2],counters[3])

                ;GET DOWN COUNTERS
                while strcmp(segs[0],'counters',/fold_case) eq 0 do begin
                    readf,lun,line & nread++
                    segs = strsplit(line,/extract)
                endwhile
                readf,lun,counters & nread++
                ;print,'counters=',counters
                ;GET DOWN IMAGE
                while strcmp(segs[0],'detector',/fold_case) eq 0 do begin
                    readf,lun,line & nread++
                    segs = strsplit(line,/extract)
                endwhile

                free_lun,lun
                if n_elements(segs) eq 3 then return,0 else return,1
        nread = nlines
    endwhile


end;NSEDiffractionViewer_checkmagnetic

pro NSEDiffractionViewer_readNonMagnetic,fn,x,y,sy,tot,incoh,coh,$
                                         stot,sincoh,scoh,$
                                         narcs,xcen,ycen,$
                                         detxrange,detyrange,lambda,$
                                         results,psym,f

                ;f is the flipping ratio.

;print,'TEST1'
;void=dialog_message('Begin NSEDiffractionViewer_readNonMagnetic')

                if n_elements(f) eq 0 then begin
                    f = 7.0
                    print,'NSEDiffractionViewer_readNonMagnetic, setting f=7.0'
                endif

;                print,'NSEDiffractionViewer_readNonMagnetic'
;                print,narcs,xcen,ycen,detxrange,detyrange,lambda
;print,'TEST2'


                catch,error_status
                if error_status ne 0 then begin
                    catch,/cancel

;void = dialog_message(['NSEDiffractionViewer_readNonMagnetic catch:',!error_state.msg])
                    help,lun,output=out
                    if stregex(out[0],'UNDEFINED',/fold_case,/boolean) eq 0 then begin
                        help,lun,/files,output=out
                        if stregex(out[1],'closed',/fold_case,/boolean) eq 0 then $
                        free_lun,lun
                    endif

                    if n_elements(x) gt 1 then begin

;print,'test8a'
;void = dialog_message('NSEDiffractionViewer_readNonMagnetic n_elements(x) gt 1')

                        x = x[1:*]
                        if n_elements(y) gt 1 then begin
                            y = y[1:*]
                            sy = sy[1:*];sqrt(y)
                        endif

;THE NEXT STATEMENT MAY HAVE A PROBLEM IN THAT I MAY CHANGE THE SIZE OF
;y JUST BEFORE I USE THE SIZE OF y AS A TEST.  WAS THIS INTENTIONAL????
;I DOUBT IT SO I REPLACED IT WITH THE STATEMENT ABOVE.

;                        if n_elements(y) gt 1 then y = y[1:*]
;                        if n_elements(y) gt 1 then sy = sy[1:*];sqrt(y)

                        if n_elements(tot) gt 1 then tot = tot[1:*];y
                        if n_elements(stot) gt 1 then stot = stot[1:*];sy

                        if n_elements(incoh) gt 1 then incoh = incoh[1:*]
                        if n_elements(sincoh) gt 1 then sincoh = sincoh[1:*]
                        if n_elements(coh) gt 1 then coh = coh[1:*]
                        if n_elements(scoh) gt 1 then scoh = scoh[1:*]
                        if n_elements(results) gt 1 then begin

;print,'test8a1'
;void = dialog_message('NSEDiffractionViewer_readNonMagnetic n_elements(results) gt 1')

                            temp = results[0]
                            results = results[1:*]
                            if obj_valid(temp) gt 0 then obj_destroy,temp

help,results,output=rout
;void = dialog_message(['NSEDiffractionViewer_readNonMagnetic ',rout])


                        endif else begin
;print,'test8a2'
;void = dialog_message('NSEDiffractionViewer_readNonMagnetic n_elements(results) le 1')
                            dat = obj_new('NSEDiffractionViewerMagnetic_data',x,y,sy,$
                                                              coh=coh,$
                                                              scoh=scoh,$
                                                              /nonmagnetic,$
                                                              incoh=incoh,$
                                                              sincoh=sincoh,$
                                                              tot=tot,$
                                                              stot=stot,$
                                                              legend=file_basename(fn)+'_q'+strtrim(string(n_elements(results)),2),$
                                                              psym=psym,$
                                                              showlegend=1,showdata=1)
                            ;help,dat
                            results = [dat]


                        endelse
                    endif else begin
;print,'test8b'
;void = dialog_message('NSEDiffractionViewer_readNonMagnetic n_elements(x) le 1')
                        x  = [-1.]
                        y  = [-1.]
                        sy = [-1.]
                        tot = y
                        stot = sy
                        coh = y
                        scoh = sy
                        incoh = y
                        sincoh = sy
                        result = [-1]
                    endelse

;void = dialog_message('NSEDiffractionViewer_readNonMagnetic end of catch.')

 ;                   print,'test 9 WTF???'
                    return;,dat
                endif

;print,'TEST3'
;void = dialog_message('NSEDiffractionViewer_readNonMagnetic Initializing variables.')
            detcount = 0
            qcount = 0

            nread = 0
            nlines = file_lines(fn)
            npix = 1024

            results = objarr(1)

            line=''
            q = 0.0d
            counters = dblarr(5)
            dumup = dblarr(npix)
            dumdn = dblarr(npix)
            x  = [-1.0d]
            y  = [-1.0d]
            sy = [-1.0d]
            tot = [-1.0d]
            stot = [-1.0d]
            coh = [-1.0d]
            scoh = [-1.0d]
            incoh = [-1.0d]
            sincoh = [-1.0d]

;void = dialog_message('NSEDiffractionViewer_readNonMagnetic Opening file.')
            openr,lun,fn,/get_lun


;void = dialog_message('NSEDiffractionViewer_readNonMagnetic Begin line-by-line read')
            readf,lun,line & nread++
            segs = strsplit(line,/extract)
;print,'TEST4'
debugcounter = 0
            while nread lt nlines do begin
;print,'TEST5'

            ;{#################################################################################
                ;GET Q
                segs = strsplit(line,/extract)
                while strcmp(segs[0],'Q',/fold_case) eq 0 do begin ;readcount lt lines do begin
                    readf,lun,line & nread++
                    segs = strsplit(line,/extract)
                endwhile
                q = double(segs[1])
                ;print,'q=',q


                ;REINSTANTIATE THESE SINCE THERE SIZE MAY CHANGE IN THE NEXT STEP.
                dumup = dblarr(npix)
                dumdn = dblarr(npix)

                ;GET UP
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumup

                ;GET DOWN
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumdn


                ;NOW NEED TO GET THE RANGES AND Q ARCS AND DO TOTAL AND Q'S FROM THERE
                if narcs eq 1 then begin



                    ;NEED TO CONSIDER THE MASK RANGE FOR A SINGLE Q ARC.

;                    print,detxrange
;                    print,detyrange
;
                    xminindex = (fix(min(detxrange)) ge 0 ? fix(min(detxrange)) : 0)
                    xmaxindex = (fix(max(detxrange)) le 31 ? fix(max(detxrange)) : 31)
                    yminindex = (fix(min(detyrange)) ge 0 ? fix(min(detyrange)) : 0)
                    ymaxindex = (fix(max(detyrange)) le 31 ? fix(max(detyrange)) : 31)
;
;
;print,xminindex,xmaxindex,yminindex,ymaxindex
;help,dumup
;help,dumdn
;
                    dumup = reform(dumup,32,32)
                    dumdn = reform(dumdn,32,32)

;print,'TEST1'

                    dumup = dumup[xminindex:xmaxindex,yminindex:ymaxindex]
                    dumdn = dumdn[xminindex:xmaxindex,yminindex:ymaxindex]

                    sum = 0.5*(total(dumup+dumdn))

                    ssum = 0.5*sqrt(total(dumup) + total(dumdn))

                    cohsum = ((1+2*f)*total(dumdn) - (f+2)*total(dumup))/(2*(f^2 -1))
                    scohsum = sqrt((((1+2*f)^2)*total(dumdn) + ((f+2)^2)*total(dumup)))/abs((2*(f^2 -1)))

                    incohsum = (-3*total(dumdn) + 3*f*total(dumup))/(2*(f^2 -1))
                    sincohsum = sqrt(((3^2)*total(dumdn) + (3^2)*total(dumup)))/abs((2*(f^2 -1)))

;print,'TEST2'

                    x = [x,q]
                    y = [y,sum]
                    sy = [sy,ssum]

                    coh = [coh,cohsum]
                    scoh = [scoh,scohsum]
                    incoh = [incoh,incohsum]
                    sincoh = [sincoh,sincohsum]

                    tot = [tot,cohsum+incohsum]
                    stot = [stot,sqrt(scohsum^2 + sincohsum^2)]


;print,'TEST5a'
;print,tot-coh-incoh



                endif else begin
;                        mask = self_mask2d;fix(0*xup + 1)
;                        mat = self_arcmat;fix(0*xup)
;                        theQvals = self_qvals;(0*xup) + self_q
;
;
;                        if n_elements(narcs) eq 0 then narcs = self_narcs
;void = dialog_message('NSEDiffractionViewer_readNonMagnetic narcs gt 1')


                    goodq = NSEDiffractionViewer_qvals(qmat,xcen,ycen,lambda,q)
                    if goodq eq 1 then begin
                        ;print,'Q VALUES ARE GOOD.'
                    endif else begin
                        print,'BAD Q VALUES, CHECK YOUR LAMBDA, ETC.'
                        void = dialog_message('BAD Q VALUES, CHECK YOUR LAMBDA, ETC.')
                    endelse
                    NSEDiffractionViewer_maskmat,mask,detxrange[0],detxrange[1],$
                                                      detyrange[0],detyrange[1]
                    NSEDiffractionViewer_arcsmat,mat,narcs,qmat

                    theQVals = qmat
                    whrmask = where(mask le 0,count)
                    if count ne 0 then begin
                        mask[whrmask] = 0
                    endif

                    esum = 0.5*(dumup+dumdn)
                    sesum = sqrt(0.5*(dumup+dumdn))

                    self_q = q;x
                    self_preset = 1.0
;help,qmat
;help,esum
;help,sesum
;help,mat
;help,narcs
;help,self_preset
;help,mask

                    ;SORT BY ARCS
;                    datTotal = NSEDiffractionViewer_sortByQArcs(narcs,qmat,esum,sesum,$
;                                                                 mask,mat,self_q,$
;                                                                 self_preset)

                    datTotal = $
                    NSEDiffractionViewer_sortNonMagneticByQArcs(narcs,qmat,dumup,dumdn,$
                                                                mask,mat,self_q,$
                                                                self_preset,f)

;help,datTotal
;                    dat = obj_new('cwo_drawplot_data',*(datTotal.q),$
;                                                      *(datTotal.s),$
;                                                      *(datTotal.ss),$
;                                                      legend=file_basename(fn)+'_q'+strtrim(string(self_q,format='(f6.4)'),2),$
;                                                      psym=(psym+n_elements(results)) mod 9,showlegend=1,showdata=1)
;                                                      ;psym=psym,showlegend=1,showdata=1)
;                    results = [results,dat]

;print,*(datTotal.q)
;print,*(datTotal.s)


                    x = [x,*(datTotal.q)]
                    y = [y,*(datTotal.s)]
                    sy = [sy,*(datTotal.ss)]

                    tot = [tot,*(datTotal.s_tot)]
                    stot = [stot,*(datTotal.s_stot)]
                    coh = [coh,*(datTotal.s_coh)]
                    scoh = [scoh,*(datTotal.s_scoh)]
                    incoh = [incoh,*(datTotal.s_incoh)]
                    sincoh = [sincoh,*(datTotal.s_sincoh)]

;void = dialog_message('NSEDiffractionViewer_readNonMagnetic create a dat object')

;print,'TEST'
;ADD DATA TO RESULTS
dat = obj_new('NSEDiffractionViewerMagnetic_data',*(datTotal.q),$
                                                  *(datTotal.s),$
                                                  *(datTotal.ss),$
                                                  coh=*(datTotal.s_coh),$
                                                  scoh=*(datTotal.s_scoh),$
                                                  /nonmagnetic,$
                                                  incoh=*(datTotal.s_incoh),$
                                                  sincoh=*(datTotal.s_sincoh),$
                                                  tot=*(datTotal.s_tot),$
                                                  stot=*(datTotal.s_stot),$
                                                  legend=file_basename(fn)+'_q'+strtrim(string(n_elements(results)),2),$
                                                  psym=psym,$
                                                  showlegend=1,showdata=1)
;print,'readNonmagnetic '
;help,results
                    results = [results,dat]
;print,'readNonmagnetic '
;help,results

                    ;FREE POINTERS!!!!
                    tags = tag_names(datTotal)
                    for itags = 0,n_elements(tags)-1 do begin
                        if ptr_valid(datTotal.(itags)) gt 0 then ptr_free,datTotal.(itags)
                    endfor;itags
;print,'TEST5b'

                endelse


            endwhile
;void = dialog_message('NSEDiffractionViewer_readNonMagnetic Finished reading file')
            ;if stregex(out[0],'UNDEFINED',/fold_case,/boolean) eq 0 then begin
;void = dialog_message('NSEDiffractionViewer_readNonMagnetic Close data file.')

                help,lun,/files,output=out
                if stregex(out[1],'closed',/fold_case,/boolean) eq 0 then $
                free_lun,lun
            ;endif
;void = dialog_message('NSEDiffractionViewer_readNonMagnetic File closed')


            if n_elements(x) gt 1 then x = x[1:*]
            if n_elements(y) gt 1 then y = y[1:*]
            if n_elements(sy) gt 1 then sy = sy[1:*]

            if n_elements(tot) gt 1 then tot = tot[1:*]
            if n_elements(stot) gt 1 then stot = stot[1:*]

            if n_elements(incoh) gt 1 then incoh = incoh[1:*]
            if n_elements(sincoh) gt 1 then sincoh = sincoh[1:*]
            if n_elements(coh) gt 1 then coh = coh[1:*]
            if n_elements(scoh) gt 1 then scoh = scoh[1:*]

;print,'TEST6'
;print,'#################################################'
            if n_elements(results) gt 1 then begin
;void = dialog_message('NSEDiffractionViewer_readNonMagnetic n_elements(results) gt 1')

                temp = results[0]
                results = results[1:*]
                if obj_valid(temp) gt 0 then obj_destroy,temp
;print,'NSEDiffractionViewer_readNonMagnetic endif n_elements(results) gt 1'

            endif else begin
;void = dialog_message('NSEDiffractionViewer_readNonMagnetic n_elements(results) le 1')


;ADD DATA TO RESULTS
                dat = obj_new('NSEDiffractionViewerMagnetic_data',x,y,sy,$
                                                  coh=coh,$
                                                  scoh=scoh,$
                                                  /nonmagnetic,$
                                                  incoh=incoh,$
                                                  sincoh=sincoh,$
                                                  tot=tot,$
                                                  stot=stot,$
                                                  legend=file_basename(fn)+'_q'+strtrim(string(n_elements(results)),2),$
                                                  psym=psym,$
                                                  showlegend=1,showdata=1)
;                help,dat

;                help,/traceback

                temp = results[0]

                results = [dat]
                if obj_valid(temp) gt 0 then obj_destroy,temp

;void = dialog_message('NSEDiffractionViewer_readNonMagnetic results=[dat]')
;print,'NSEDiffractionViewer_readNonMagnetic endelse n_elements(results) le 1'
            endelse
;print,'NSEDiffractionViewer_readNonMagnetic end'
end;NSEDiffractionViewer_readNonMagnetic
;function NSEDiffractionViewer_qvals,qmat,xcen,ycen,lambda,qactual
;
;    ;lambda in Ang
;    ;qactual in 1/Ang
;    ;xcen,ycen in pixel value
;
;    ;return 0 if there are NaN's in the qmat.
;    ;else return,1
;
;
;
;;    print,'NSEDiffractionViewer_qvals'
;    qmat = dblarr(32,32)
;
;
;
;;FIRST:
;;NEED TO  GET LAMBDA
;    wl = double(lambda);self.lambda)
;
;;VARIABLES
;    detdist = 4.35d
;    xpixel = 0.01
;    ypixel = 0.01
;
;
;    qmin = 0.0d & qpix = 0.0d $
;    & qc = 0.0d & qstep = 0.0d & il = 0 $
;    & jl = 0 & iq = 0 $
;    & qlmin = 0.0d & qlmax = 0.0d $
;    & it = 0 & nt = 0
;
;    qx = 0.0d & qy = 0.0d $
;    & Fshift = 0 & filenum = 0
;
;
;
;    ;THESE ARE NOT NECESSARY IN MY CONVENTIONS
;    blockx = 1;self.x_dim_orig/self.x_dim
;    blocky = 1;self.y_dim_orig/self.y_dim
;
;    block = double(blockx)
;
;    DetSizeX = 32;self.x_dim_orig
;    DetSizeY = 32;self.y_dim_orig
;
;    maxx = 32;DetSizeX/blockx  ;=self.x_dim
;    maxy = 32;DetSizeY/blocky  ;=self.y_dim
;
;    x_dim = 32
;    y_dim = 32
;
;    x_dim_orig = 32
;    y_dim_orig = 32
;
;    ;THE NEXT ASSIGNMENT IS DUE TO THE CONFUSION BETWEEN
;    ;X,Y,HORIZONTAL AND VERTICAL.  THESE VALUES ARE READ
;    ;FROM THE "SCAN" HEADER.
;
;
;    ;030805
;    ;UPDATE THE NEXT LINE TO USE self.qactual
;
;    ;052005
;    ;UPDATE THE NEXT LINE TO USE qy NOW THAT qy IS BEING READ FROM THE 6th SEGMENT
;    ;OF THE Q LINE, AS IT IS IN IGOR.
;
;
;
;    DetCenX = double(xcen);self.x_cen_orig)
;    DetCenY = double(ycen);self.y_cen_orig)
;
;
;
;    QArray = dblarr(maxx,maxy)
;
;
;    hDetCen = double(xcen);self.x_cen_orig)
;    vDetCen = double(ycen);self.y_cen_orig)
;
;    hIndex = maxx
;    vindex = maxy
;
;
;
;
;
;;THIRD
;;GET qactual
;qcy = -1.0*qactual;self.qactual
;
;    for il=0,hIndex-1 do begin
;        for jl=0,vindex-1 do begin
;
;            ilflip = double(x_dim - il)
;            hDetCenflip = double(x_dim_orig - hDetCen)
;            jlflip = double(jl)
;            vDetCenflip = double(vDetCen)
;
;
;            hQ = sin(asin((-1.0d)*qcy*double((10.0d)^(10.0d))*wl/4.0d/!DPI)- $
;            atan((hDetCenflip-block*(ilflip))*xPixel/detdist)/2.0d)*4.0d*!DPI/wl
;            vQ = sin(atan((block*(jlflip)- $
;                vDetCenflip)*yPixel/detdist)/2.0d)*4.0d*!DPI/wl
;
;            totQ = sqrt(vQ^2 + hQ^2)
;            QArray[il,jl] = totQ/((10.0d)^(10.0d))   ;CONVERT TO 1/ANG
;        endfor;jl
;    endfor;il
;    qmin = min(QArray)
;    qmax = max(QArray)
;
;
;    sz = size(QArray)
;
;    QArray = transpose(reform(QArray,sz[n_elements(sz)-1]))
;
;    QArray = transpose(QArray);New)
;
;    qmat = QArray
;
;    qmat = reform(qmat,1024)
;
;    ;CHECK FOR NaN'S
;    wh = where(finite(qmat,/nan) eq 1,wh_count)
;    if wh_count eq 0 then return,1 else return,0
;
;end;NSEDiffractionViewer_qvals

function NSEDiffractionViewer_sortAltMagneticByQArcs,narcs,$
                                            theQVals,$
                                            dumXup,dumXdn,$
                                            dumZup,dumZdn,$
                                            dumYup,dumYdn,$
                                            mask,mat,self_q,self_preset,f


;print,'b1'
                xyzupdown = 1.0
                eff_bpw = 1.0
                polarization = 1.0
                    xx = xyzupdown*(dumXup - dumXdn)/(polarization*eff_bpw*(1+f))
                    sxx = xyzupdown*(sqrt(dumXup + dumXdn))/(polarization*eff_bpw*(1+f))
                    yy = xyzupdown*(dumYup - dumYdn)/(polarization*eff_bpw*(1+f))
                    syy = xyzupdown*(sqrt(dumYup + dumYdn))/(polarization*eff_bpw*(1+f))
                    zz = xyzupdown*(dumZup - dumZdn)/(polarization*eff_bpw*(1+f))
                    szz = xyzupdown*(sqrt(dumZup + dumZdn))/(polarization*eff_bpw*(1+f))

                    aa = xyzupdown*(f*dumXdn + dumXup)/(1+f)
                    saa = xyzupdown*(sqrt(f*dumXdn + dumXup))/(1+f)
                    bb = xyzupdown*(f*dumYdn + dumYup)/(1+f)
                    sbb = xyzupdown*(sqrt(f*dumYdn + dumYup))/(1+f)
                    cc = xyzupdown*(f*dumZdn + dumZup)/(1+f)
                    scc = xyzupdown*(sqrt(f*dumZdn + dumZup))/(1+f)

                    sum = (aa+bb+cc)/1.5
                    ssum = (sqrt(aa+bb+cc))/1.5

                    cohsum = (3*(zz+xx+yy) + aa+bb+cc)/6.0
                    scohsum = (sqrt(3*(zz+xx+yy) + aa+bb+cc))/6.0

                    incohsum = (3*(-3*zz+xx+yy)+aa+bb+cc)/2.0
                    sincohsum = (sqrt(3*(3*zz+xx+yy)+aa+bb+cc))/2.0

                    magsum = (4*zz - 2*xx - 2*yy)
                    smagsum = (sqrt(4*zz + 2*xx + 2*yy))


                    etot = sum
                    setot = ssum
                    ecoh = cohsum
                    secoh = scohsum
                    eincoh = incohsum
                    seincoh = sincohsum
                    emag = magsum
                    semag = smagsum

;print,'b2'
                s = dblarr(narcs)
                sS = dblarr(narcs)

                s_coh = dblarr(narcs)
                s_scoh = dblarr(narcs)
                s_incoh = dblarr(narcs)
                s_sincoh = dblarr(narcs)
                s_mag = dblarr(narcs)
                s_smag = dblarr(narcs)
;print,'b3'
                q = dblarr(narcs)
                qcount = intarr(narcs)
                sz = size(etot)

;print,'b3a'
                if sz[0] eq 1 then sz[2] = 1
                for i=0,sz[1]-1 do begin
                    for j=0,sz[2]-1 do begin
                        for k=0,narcs-1 do begin
                            if mat[i] eq k and mask[i,j] ne 0 then begin
                                if finite (etot[i,j]) gt 0  and finite(1.0d/setot[i,j]) gt 0 then begin
                                    s[k] += etot[i,j]/setot[i,j]^2
                                    ss[k] += 1.0d/setot[i,j]^2

                                    ;USE SAME WEIGHTINGS AS FOR TOTAL
                                    s_coh[k] += ecoh[i,j]/setot[i,j]^2
                                    s_scoh[k] += 1.0d/setot[i,j]^2
                                    s_incoh[k] += eincoh[i,j]/setot[i,j]^2
                                    s_sincoh[k] += 1.0d/setot[i,j]^2
                                    s_mag[k] += emag[i,j]/setot[i,j]^2
                                    s_smag[k] += 1.0d/setot[i,j]^2

                                    q[k] += theQVals[i,j]
                                    qcount[k] += 1
                                endif;finite
                            endif
                        endfor;k
                    endfor;j
                endfor;i
;print,'Middle NSEDiffractionViewer_sortByQArcs'
                ;print,'qcount=',qcount

;print,'b4'
                qmin = min(theqvals)
                qmax = max(theqvals)

                for i=0,narcs-1 do begin
                    if qcount[i] ne 0 then begin
                        s[i] = s[i]/ss[i]
                        ss[i] = 1.0d/sqrt(ss[i])

                        s_coh[i] = s_coh[i]/s_scoh[i]
                        s_scoh[i] = 1.0d/sqrt(s_scoh[i])
                        s_incoh[i] = s_incoh[i]/s_sincoh[i]
                        s_sincoh[i] = 1.0d/sqrt(s_sincoh[i])
                        s_mag[i] = s_mag[i]/s_smag[i]
                        s_smag[i] = 1.0d/sqrt(s_smag[i])


                        q[i] = q[i]/double(qcount[i])
                    endif else begin
                        s[i] = 0.0
                        ss[i] = 0.0
                        s_coh[i] = 0.0
                        s_scoh[i] = 0.0
                        s_incoh[i] = 0.0
                        s_sincoh[i] = 0.0
                        s_mag[i] = 0.0
                        s_smag[i] = 0.0

                        if narcs ne 1 then begin
                            qstep = (qmax-qmin)/double(narcs-1)
                            q[i] = qmin + (double(i)+0.5)*qstep
                        endif else begin
                            q[i] = self_q;self->getproperty(tag='q')
                        endelse
                    endelse
                endfor;i
;print,'b6'
                s = s/double(self_preset)
                ss = ss/double(self_preset)

                s_coh = s_coh/double(self_preset)
                s_scoh = s_scoh/double(self_preset)
                s_incoh = s_incoh/double(self_preset)
                s_sincoh = s_sincoh/double(self_preset)
                s_mag = s_mag/double(self_preset)
                s_smag = s_smag/double(self_preset)

                s_tot = s_coh + s_incoh + s_mag
                s_stot = sqrt(s_scoh^2 + s_sincoh^2 + s_smag^2)

;help,/traceback
;print,'FINISH NSEDiffractionViewer_sortByQArcs'
    return,{s:ptr_new(s),ss:ptr_new(ss),q:ptr_new(q),$
            s_tot:ptr_new(s_tot),s_stot:ptr_new(s_stot),$
            s_coh:ptr_new(s_coh),s_scoh:ptr_new(s_scoh),$
            s_incoh:ptr_new(s_incoh),s_sincoh:ptr_new(s_sincoh),$
            s_mag:ptr_new(s_mag),s_smag:ptr_new(s_smag)}

end;NSEDiffractionViewer_sortAltMagneticByQArcs

;#################################################################################
pro NSEDiffractionViewer_readAltMagnetic,fn,x,y,sy,t,inc,c,m,st,sinc,sc,sm,$
                                         narcs,xcen,ycen,detxrange,detyrange,lambda,$
                                         results,psym,f

;print,'TESTING NSEDiffractionViewer_readAltMagnetic'
;THE PLAN IS TO MODIFY THIS METHOD (readNonMagnetic) SO THAT IT
;RUNS JUST LIKE THE readNonMagnetic AND DOES THE CALCULATIONS IN THE
;SAME MANNER, BUT IT WILL DO THE MAGNETIC CALCULATIONS.


                ;f is the flipping ratio.

;print,'TEST1'
help,/traceback
                if n_elements(f) eq 0 then begin
                    f = 7.0
                    print,'NSEDiffractionViewer_readAltMagnetic, setting f=7.0'
                endif

;                print,'NSEDiffractionViewer_readAltMagnetic'
;                print,narcs,xcen,ycen,detxrange,detyrange,lambda
;print,'TEST2'


                catch,error_status
                if error_status ne 0 then begin
                    catch,/cancel

                    help,lun,output=out
                    if stregex(out[0],'UNDEFINED',/fold_case,/boolean) eq 0 then begin
                        help,lun,/files,output=out
                        if stregex(out[1],'closed',/fold_case,/boolean) eq 0 then $
                        free_lun,lun
                    endif

                    if n_elements(x) gt 1 then begin

;print,'test8a'
                        x = x[1:*]
                        if n_elements(y) gt 1 then y = y[1:*]
                        if n_elements(y) gt 1 then sy = sy[1:*];sqrt(y)
                        if n_elements(tot) gt 1 then tot = tot[1:*];y
                        if n_elements(stot) gt 1 then stot = stot[1:*];sy

                        if n_elements(incoh) gt 1 then incoh = incoh[1:*]
                        if n_elements(sincoh) gt 1 then sincoh = sincoh[1:*]
                        if n_elements(coh) gt 1 then coh = coh[1:*]
                        if n_elements(scoh) gt 1 then scoh = scoh[1:*]

                        if n_elements(mag) gt 1 then mag = mag[1:*]
                        if n_elements(smag) gt 1 then smag = smag[1:*]

                        t = tot
                        inc = incoh
                        c = coh
                        m = mag
                        st = stot
                        sinc = sincoh
                        sc = scoh
                        sm = smag

                        if n_elements(results) gt 1 then begin
;print,'test8a1'
                    ;print,'NSEDiffractionViewer_readAltMagnetic COMPLETION via CATCH:'
                    ;void = dialog_message('NSEDiffractionViewer_readAltMagnetic n_elements(results) gt 1')
                    ;void = dialog_message('Message = '+!error_state.msg)

                            temp = results[0]
                            results = results[1:*]
                            if obj_valid(temp) gt 0 then obj_destroy,temp
                        endif else begin
;print,'test8a2'
                    ;print,'NSEDiffractionViewer_readAltMagnetic COMPLETION via CATCH:'
                    ;void = dialog_message('NSEDiffractionViewer_readAltMagnetic n_elements(results) le 1')
                    ;void = dialog_message('Message = '+!error_state.msg)

                            dat = obj_new('NSEDiffractionViewerMagnetic_data',x,y,sy,$
                                                              coh=coh,$
                                                              scoh=scoh,$
                                                              nonmagnetic=0,$
                                                              incoh=incoh,$
                                                              sincoh=sincoh,$
                                                              tot=tot,$
                                                              stot=stot,$
                                                              mag=mag,$
                                                              smag=smag,$
                                                              legend=file_basename(fn)+'_q'+strtrim(string(n_elements(results)),2),$
                                                              psym=psym,$
                                                              showlegend=1,showdata=1)
                            ;help,dat
                            results = [dat]
                        endelse
                    endif else begin
;print,'test8b'
                    ;print,'NSEDiffractionViewer_readAltMagnetic COMPLETION via CATCH:'
                    ;void = dialog_message('NSEDiffractionViewer_readAltMagnetic n_elements(results) eq 0')
                    ;void = dialog_message('NSEDiffractionViewer_readAltMagnetic n_elements(x) eq 0')

                    ;void = dialog_message('Message = '+!error_state.msg)


                        x  = [-1.]
                        y  = [-1.]
                        sy = [-1.]
                        tot = y
                        stot = sy
                        coh = y
                        scoh = sy
                        incoh = y
                        sincoh = sy
                        mag = y
                        smag = sy
                        result = [-1]

                        t = tot
                        inc = incoh
                        c = coh
                        m = mag
                        st = stot
                        sinc = sincoh
                        sc = scoh
                        sm = smag
                    endelse
 ;                   print,'test 9 WTF???'
                    ;print,'NSEDiffractionViewer_readAltMagnetic COMPLETION via CATCH:'
                    ;void = dialog_message('NSEDiffractionViewer_readAltMagnetic Bad Data File: COMPLETION via CATCH:')
                    ;void = dialog_message('NSEDiffractionViewer_readAltMagnetic Bad Data File: END OF CATCH STATEMENT')
                    return;,dat
                endif

;print,'TEST3'

            detcount = 0
            qcount = 0

            nread = 0
            nlines = file_lines(fn)
            npix = 1024

            results = objarr(1)

            line=''
            q = 0.0d
            counters = dblarr(5)
            dumXup = dblarr(npix)
            dumXdn = dblarr(npix)
            dumZup = dblarr(npix)
            dumXdn = dblarr(npix)
            dumYup = dblarr(npix)
            dumYdn = dblarr(npix)
            x  = [-1.0d]
            y  = [-1.0d]
            sy = [-1.0d]
            tot = [-1.0d]
            stot = [-1.0d]
            coh = [-1.0d]
            scoh = [-1.0d]
            incoh = [-1.0d]
            sincoh = [-1.0d]
            mag = [-1.0d]
            smag = [-1.0d]
;void = dialog_message('NSEDiffractionViewer_readAltMagnetic About to open file:')

            openr,lun,fn,/get_lun
;void = dialog_message('NSEDiffractionViewer_readAltMagnetic About to read file one line at a time:')

            readf,lun,line & nread++
            segs = strsplit(line,/extract)
;print,'TEST4'

            while nread lt nlines do begin
;print,'TEST5'

            ;{#################################################################################
                ;GET Q
                segs = strsplit(line,/extract)
                while strcmp(segs[0],'Q',/fold_case) eq 0 do begin ;readcount lt lines do begin
                    readf,lun,line & nread++
                    segs = strsplit(line,/extract)
                endwhile
                q = double(segs[1])
;                print,'q=',q
;
;                ;GET UP
;                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumup
;
;                ;GET DOWN
;                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumdn


;print,'test'
;void = dialog_message('NSEDiffractionViewer_readAltMagnetic About to read images:')


                ;READ XDOWN
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumXDn
;print,'test xdn'
                ;READ XUP
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumXUp
;print,'test xup'

                ;READ ZDOWN
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumZDn
;print,'test zdn'

                ;READ ZUP
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumZup
;print,'test zup'


                ;READ YDOWN
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumYDn
;print,'test ydn'


                ;READ YUP
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumYUp

;print,'test yup'

;void = dialog_message('NSEDiffractionViewer_readAltMagnetic READ 6 IMAGES:')

;DOES THIS ACCOUNT FOR THE LIMITS PLACES ON THE DETECTOR RANGES??????????

                ;NOW NEED TO GET THE RANGES AND Q ARCS AND DO TOTAL AND Q'S FROM THERE
                if narcs eq 1 then begin
;print,'test 1 arc'
;                    sum = 0.5*(total(dumup+dumdn))
;                    ssum = 0.5*sqrt(total(dumup) + total(dumdn))
;                    cohsum = ((1+2*f)*total(dumdn) - (f+2)*total(dumup))/(2*(f^2 -1))
;                    scohsum = sqrt((((1+2*f)^2)*total(dumdn) + ((f+2)^2)*total(dumup)))/abs((2*(f^2 -1)))
;                    incohsum = (-3*total(dumdn) + 3*f*total(dumup))/(2*(f^2 -1))
;                    sincohsum = sqrt(((3^2)*total(dumdn) + (3^2)*total(dumup)))/abs((2*(f^2 -1)))
                xyzupdown = 1.0
                eff_bpw = 1.0
                polarization = 1.0
;print,'test 1 arc a'
                    xx = xyzupdown*(dumXup - dumXdn)/(polarization*eff_bpw*(1+f))
                    sxx = xyzupdown*(sqrt(dumXup + dumXdn))/(polarization*eff_bpw*(1+f))
                    yy = xyzupdown*(dumYup - dumYdn)/(polarization*eff_bpw*(1+f))
                    syy = xyzupdown*(sqrt(dumYup + dumYdn))/(polarization*eff_bpw*(1+f))
                    zz = xyzupdown*(dumZup - dumZdn)/(polarization*eff_bpw*(1+f))
                    szz = xyzupdown*(sqrt(dumZup + dumZdn))/(polarization*eff_bpw*(1+f))

;print,'test 1 arc b'

                    aa = xyzupdown*(f*dumXdn + dumXup)/(1+f)
                    saa = xyzupdown*(sqrt(f*dumXdn + dumXup))/(1+f)
                    bb = xyzupdown*(f*dumYdn + dumYup)/(1+f)
                    sbb = xyzupdown*(sqrt(f*dumYdn + dumYup))/(1+f)
                    cc = xyzupdown*(f*dumZdn + dumZup)/(1+f)
                    scc = xyzupdown*(sqrt(f*dumZdn + dumZup))/(1+f)


;print,'test 1 arc c'


                    sum = (total(aa+bb+cc)/1.5)/n_elements(aa)
                    ssum = (total(sqrt(abs(aa+bb+cc)))/1.5)/n_elements(aa)

                    cohsum = (total(3*(zz+xx+yy) + aa+bb+cc)/6.0)/n_elements(aa)
                    scohsum = (total(sqrt(abs(3*(zz+xx+yy) + aa+bb+cc)))/6.0)/n_elements(aa)

                    incohsum = (total(3*(-3*zz+xx+yy)+aa+bb+cc)/2.0)/n_elements(aa)
                    sincohsum = (total(sqrt(abs(3*(3*zz+xx+yy)+aa+bb+cc)))/2.0)/n_elements(aa)

                    magsum = (total(4*zz - 2*xx - 2*yy))/n_elements(aa)
sqrtval=sqrt(abs(4*zz + 2*xx + 2*yy))
                    smagsum = (total(sqrtval))/n_elements(aa)
;print,'magsum=',magsum
;print,'smagsum=',smagsum
;print,'total(aa+bb+cc)/1.5=',sum
;print,'total(aa+bb+cc)/1.5 = ?',cohsum+incohsum+magsum

;print,'test 1 arc d'


                    x = [x,q]
                    y = [y,sum]
                    sy = [sy,ssum]
;print,'test 1 arc e'

                    coh = [coh,cohsum]
                    scoh = [scoh,scohsum]
                    incoh = [incoh,incohsum]
                    sincoh = [sincoh,sincohsum]
;print,'test 1 arc f'

                    mag = [mag,magsum]
                    smag = [smag,smagsum]
;print,'test 1 arc g'

                    tot = [tot,cohsum+incohsum+magsum]
                    stot = [stot,sqrt(scohsum^2 + sincohsum^2 + smagsum^2)]
;print,'test 1 arc complete'

                    t = tot
                    inc = incoh
                    c = coh
                    m = mag
                    st = stot
                    sinc = sincoh
                    sc = scoh
                    sm = smag




                endif else begin
;                        mask = self_mask2d;fix(0*xup + 1)
;                        mat = self_arcmat;fix(0*xup)
;                        theQvals = self_qvals;(0*xup) + self_q
;
;
;                        if n_elements(narcs) eq 0 then narcs = self_narcs

;print,'a1'
                    goodq = NSEDiffractionViewer_qvals(qmat,xcen,ycen,lambda,q)
                    if goodq eq 1 then begin
                        ;print,'Q VALUES ARE GOOD.'
                    endif else begin
                        print,'BAD Q VALUES, CHECK YOUR LAMBDA, ETC.'
                        void = dialog_message('BAD Q VALUES, CHECK YOUR LAMBDA, ETC.')
                    endelse
                    NSEDiffractionViewer_maskmat,mask,detxrange[0],detxrange[1],$
                                                      detyrange[0],detyrange[1]
                    NSEDiffractionViewer_arcsmat,mat,narcs,qmat
;print,'a2'
                    theQVals = qmat
                    whrmask = where(mask le 0,count)
                    if count ne 0 then begin
                        mask[whrmask] = 0
                    endif
;print,'a3'
;                    esum = 0.5*(dumup+dumdn)
;                    sesum = sqrt(0.5*(dumup+dumdn))
;print,'b'
                    self_q = q;x
                    self_preset = 1.0
;help,qmat
;help,esum
;help,sesum
;help,mat
;help,narcs
;help,self_preset
;help,mask

                    ;SORT BY ARCS
;                    datTotal = NSEDiffractionViewer_sortByQArcs(narcs,qmat,esum,sesum,$
;                                                                 mask,mat,self_q,$
;                                                                 self_preset)

;
;                    datTotal = $
;                    NSEDiffractionViewer_sortNonMagneticByQArcs(narcs,qmat,dumup,dumdn,$
;                                                                mask,mat,self_q,$
;                                                                self_preset,f)

;print,'a4'
                    datTotal = $
                    NSEDiffractionViewer_sortAltMagneticByQArcs( $
                                            narcs,$
                                            qmat,$
                                            dumXup,dumXdn,$
                                            dumZup,dumZdn,$
                                            dumYup,dumYdn,$
                                            mask,mat,self_q,$
                                            self_preset,f)

;print,'a5'
;help,datTotal
;                    dat = obj_new('cwo_drawplot_data',*(datTotal.q),$
;                                                      *(datTotal.s),$
;                                                      *(datTotal.ss),$
;                                                      legend=file_basename(fn)+'_q'+strtrim(string(self_q,format='(f6.4)'),2),$
;                                                      psym=(psym+n_elements(results)) mod 9,showlegend=1,showdata=1)
;                                                      ;psym=psym,showlegend=1,showdata=1)
;                    results = [results,dat]

;print,*(datTotal.q)
;print,*(datTotal.s)


                    x = [x,*(datTotal.q)]
                    y = [y,*(datTotal.s)]
                    sy = [sy,*(datTotal.ss)]
;print,'a'
                    tot = [tot,*(datTotal.s_tot)]
                    stot = [stot,*(datTotal.s_stot)]
                    coh = [coh,*(datTotal.s_coh)]
                    scoh = [scoh,*(datTotal.s_scoh)]
                    incoh = [incoh,*(datTotal.s_incoh)]
                    sincoh = [sincoh,*(datTotal.s_sincoh)]
;print,'b'
                    mag = [mag,*(datTotal.s_mag)]
                    smag = [smag,*(datTotal.s_smag)]


                    t = tot
                    inc = incoh
                    c = coh
                    m = mag
                    st = stot
                    sinc = sincoh
                    sc = scoh
                    sm = smag

;print,'c'

;help,*(datTotal.s_coh)
;help,*(datTotal.s_mag)
;print,'TEST'
;ADD DATA TO RESULTS
dat = obj_new('NSEDiffractionViewerMagnetic_data',*(datTotal.q),$
                                                  *(datTotal.s),$
                                                  *(datTotal.ss),$
                                                  coh=*(datTotal.s_coh),$
                                                  scoh=*(datTotal.s_scoh),$
                                                  nonmagnetic=0,$
                                                  incoh=*(datTotal.s_incoh),$
                                                  sincoh=*(datTotal.s_sincoh),$
                                                  tot=*(datTotal.s_tot),$
                                                  stot=*(datTotal.s_stot),$
                                                  mag=*(datTotal.s_mag),$
                                                  smag=*(datTotal.s_smag),$
                                                  legend=file_basename(fn)+'_q'+strtrim(string(n_elements(results)),2),$
                                                  psym=psym,$
                                                  showlegend=1,showdata=1)


;print,'readNonmagnetic '
;help,results
                    results = [results,dat]
;print,'readNonmagnetic '
;help,results

                    ;FREE POINTERS!!!!
                    tags = tag_names(datTotal)
                    for itags = 0,n_elements(tags)-1 do begin
                        if ptr_valid(datTotal.(itags)) gt 0 then ptr_free,datTotal.(itags)
                    endfor;itags
;print,'TEST5b'

                endelse
            endwhile
            ;if stregex(out[0],'UNDEFINED',/fold_case,/boolean) eq 0 then begin
                help,lun,/files,output=out
                if stregex(out[1],'closed',/fold_case,/boolean) eq 0 then $
                free_lun,lun
            ;endif

            if n_elements(x) gt 1 then x = x[1:*]
            if n_elements(y) gt 1 then y = y[1:*]
            if n_elements(sy) gt 1 then sy = sy[1:*]

            if n_elements(tot) gt 1 then tot = tot[1:*]
            if n_elements(stot) gt 1 then stot = stot[1:*]

            if n_elements(incoh) gt 1 then incoh = incoh[1:*]
            if n_elements(sincoh) gt 1 then sincoh = sincoh[1:*]
            if n_elements(coh) gt 1 then coh = coh[1:*]
            if n_elements(scoh) gt 1 then scoh = scoh[1:*]
            if n_elements(mag) gt 1 then mag = mag[1:*]
            if n_elements(smag) gt 1 then smag = smag[1:*]
                    t = tot
                    inc = incoh
                    c = coh
                    m = mag
                    st = stot
                    sinc = sincoh
                    sc = scoh
                    sm = smag

;print,'TEST6'

;print,'#################################################'
            if n_elements(results) gt 1 then begin
                temp = results[0]
                results = results[1:*]
                if obj_valid(temp) gt 0 then obj_destroy,temp
            endif else begin


;ADD DATA TO RESULTS
                dat = obj_new('NSEDiffractionViewerMagnetic_data',x,y,sy,$
                                                  coh=coh,$
                                                  scoh=scoh,$
                                                  nonmagnetic=0,$
                                                  incoh=incoh,$
                                                  sincoh=sincoh,$
                                                  tot=tot,$
                                                  stot=stot,$
                                                  mag=mag,$
                                                  smag=smag,$
                                                  legend=file_basename(fn)+'_q'+strtrim(string(n_elements(results)),2),$
                                                  psym=psym,$
                                                  showlegend=1,showdata=1)
;                help,dat

;                help,/traceback
                results = [dat]

            endelse
help,/traceback
end;NSEDiffractionViewer_readAltMagnetic

;;;;;function NSEDiffractionViewer_sortAltMagneticByQArcs,narcs,$
;;;;;                                            theQVals,$
;;;;;                                            dumXup,dumXdn,$
;;;;;                                            dumZup,dumZdn,$
;;;;;                                            dumYup,dumYdn,$
;;;;;                                            mask,mat,self_q,self_preset,f
;;;;;
;;;;;
;;;;;;print,'b1'
;;;;;                xyzupdown = 1.0
;;;;;                eff_bpw = 1.0
;;;;;                polarization = 1.0
;;;;;                    xx = xyzupdown*(dumXup - dumXdn)/(polarization*eff_bpw*(1+f))
;;;;;                    sxx = xyzupdown*(sqrt(dumXup + dumXdn))/(polarization*eff_bpw*(1+f))
;;;;;                    yy = xyzupdown*(dumYup - dumYdn)/(polarization*eff_bpw*(1+f))
;;;;;                    syy = xyzupdown*(sqrt(dumYup + dumYdn))/(polarization*eff_bpw*(1+f))
;;;;;                    zz = xyzupdown*(dumZup - dumZdn)/(polarization*eff_bpw*(1+f))
;;;;;                    szz = xyzupdown*(sqrt(dumZup + dumZdn))/(polarization*eff_bpw*(1+f))
;;;;;
;;;;;                    aa = xyzupdown*(f*dumXdn + dumXup)/(1+f)
;;;;;                    saa = xyzupdown*(sqrt(f*dumXdn + dumXup))/(1+f)
;;;;;                    bb = xyzupdown*(f*dumYdn + dumYup)/(1+f)
;;;;;                    sbb = xyzupdown*(sqrt(f*dumYdn + dumYup))/(1+f)
;;;;;                    cc = xyzupdown*(f*dumZdn + dumZup)/(1+f)
;;;;;                    scc = xyzupdown*(sqrt(f*dumZdn + dumZup))/(1+f)
;;;;;
;;;;;                    sum = (aa+bb+cc)/1.5
;;;;;                    ssum = (sqrt(aa+bb+cc))/1.5
;;;;;
;;;;;                    cohsum = (3*(zz+xx+yy) + aa+bb+cc)/6.0
;;;;;                    scohsum = (sqrt(3*(zz+xx+yy) + aa+bb+cc))/6.0
;;;;;
;;;;;                    incohsum = (3*(-3*zz+xx+yy)+aa+bb+cc)/2.0
;;;;;                    sincohsum = (sqrt(3*(3*zz+xx+yy)+aa+bb+cc))/2.0
;;;;;
;;;;;                    magsum = (4*zz - 2*xx - 2*yy)
;;;;;                    smagsum = (sqrt(4*zz + 2*xx + 2*yy))
;;;;;
;;;;;
;;;;;                    etot = sum
;;;;;                    setot = ssum
;;;;;                    ecoh = cohsum
;;;;;                    secoh = scohsum
;;;;;                    eincoh = incohsum
;;;;;                    seincoh = sincohsum
;;;;;                    emag = magsum
;;;;;                    semag = smagsum
;;;;;
;;;;;;print,'b2'
;;;;;                s = dblarr(narcs)
;;;;;                sS = dblarr(narcs)
;;;;;
;;;;;                s_coh = dblarr(narcs)
;;;;;                s_scoh = dblarr(narcs)
;;;;;                s_incoh = dblarr(narcs)
;;;;;                s_sincoh = dblarr(narcs)
;;;;;                s_mag = dblarr(narcs)
;;;;;                s_smag = dblarr(narcs)
;;;;;;print,'b3'
;;;;;                q = dblarr(narcs)
;;;;;                qcount = intarr(narcs)
;;;;;                sz = size(etot)
;;;;;
;;;;;;print,'b3a'
;;;;;                if sz[0] eq 1 then sz[2] = 1
;;;;;                for i=0,sz[1]-1 do begin
;;;;;                    for j=0,sz[2]-1 do begin
;;;;;                        for k=0,narcs-1 do begin
;;;;;                            if mat[i] eq k and mask[i,j] ne 0 then begin
;;;;;                                if finite (etot[i,j]) gt 0  and finite(1.0d/setot[i,j]) gt 0 then begin
;;;;;                                    s[k] += etot[i,j]/setot[i,j]^2
;;;;;                                    ss[k] += 1.0d/setot[i,j]^2
;;;;;
;;;;;                                    ;USE SAME WEIGHTINGS AS FOR TOTAL
;;;;;                                    s_coh[k] += ecoh[i,j]/setot[i,j]^2
;;;;;                                    s_scoh[k] += 1.0d/setot[i,j]^2
;;;;;                                    s_incoh[k] += eincoh[i,j]/setot[i,j]^2
;;;;;                                    s_sincoh[k] += 1.0d/setot[i,j]^2
;;;;;                                    s_mag[k] += emag[i,j]/setot[i,j]^2
;;;;;                                    s_smag[k] += 1.0d/setot[i,j]^2
;;;;;
;;;;;                                    q[k] += theQVals[i,j]
;;;;;                                    qcount[k] += 1
;;;;;                                endif;finite
;;;;;                            endif
;;;;;                        endfor;k
;;;;;                    endfor;j
;;;;;                endfor;i
;;;;;;print,'Middle NSEDiffractionViewer_sortByQArcs'
;;;;;                ;print,'qcount=',qcount
;;;;;
;;;;;;print,'b4'
;;;;;                qmin = min(theqvals)
;;;;;                qmax = max(theqvals)
;;;;;
;;;;;                for i=0,narcs-1 do begin
;;;;;                    if qcount[i] ne 0 then begin
;;;;;                        s[i] = s[i]/ss[i]
;;;;;                        ss[i] = 1.0d/sqrt(ss[i])
;;;;;
;;;;;                        s_coh[i] = s_coh[i]/s_scoh[i]
;;;;;                        s_scoh[i] = 1.0d/sqrt(s_scoh[i])
;;;;;                        s_incoh[i] = s_incoh[i]/s_sincoh[i]
;;;;;                        s_sincoh[i] = 1.0d/sqrt(s_sincoh[i])
;;;;;                        s_mag[i] = s_mag[i]/s_smag[i]
;;;;;                        s_smag[i] = 1.0d/sqrt(s_smag[i])
;;;;;
;;;;;
;;;;;                        q[i] = q[i]/double(qcount[i])
;;;;;                    endif else begin
;;;;;                        s[i] = 0.0
;;;;;                        ss[i] = 0.0
;;;;;                        s_coh[i] = 0.0
;;;;;                        s_scoh[i] = 0.0
;;;;;                        s_incoh[i] = 0.0
;;;;;                        s_sincoh[i] = 0.0
;;;;;                        s_mag[i] = 0.0
;;;;;                        s_smag[i] = 0.0
;;;;;
;;;;;                        if narcs ne 1 then begin
;;;;;                            qstep = (qmax-qmin)/double(narcs-1)
;;;;;                            q[i] = qmin + (double(i)+0.5)*qstep
;;;;;                        endif else begin
;;;;;                            q[i] = self_q;self->getproperty(tag='q')
;;;;;                        endelse
;;;;;                    endelse
;;;;;                endfor;i
;;;;;;print,'b6'
;;;;;                s = s/double(self_preset)
;;;;;                ss = ss/double(self_preset)
;;;;;
;;;;;                s_coh = s_coh/double(self_preset)
;;;;;                s_scoh = s_scoh/double(self_preset)
;;;;;                s_incoh = s_incoh/double(self_preset)
;;;;;                s_sincoh = s_sincoh/double(self_preset)
;;;;;                s_mag = s_mag/double(self_preset)
;;;;;                s_smag = s_smag/double(self_preset)
;;;;;
;;;;;                s_tot = s_coh + s_incoh + s_mag
;;;;;                s_stot = sqrt(s_scoh^2 + s_sincoh^2 + s_smag^2)
;;;;;
;;;;;;help,/traceback
;;;;;;print,'FINISH NSEDiffractionViewer_sortByQArcs'
;;;;;    return,{s:ptr_new(s),ss:ptr_new(ss),q:ptr_new(q),$
;;;;;            s_tot:ptr_new(s_tot),s_stot:ptr_new(s_stot),$
;;;;;            s_coh:ptr_new(s_coh),s_scoh:ptr_new(s_scoh),$
;;;;;            s_incoh:ptr_new(s_incoh),s_sincoh:ptr_new(s_sincoh),$
;;;;;            s_mag:ptr_new(s_mag),s_smag:ptr_new(s_smag)}
;;;;;
;;;;;end;NSEDiffractionViewer_sortAltMagneticByQArcs


pro NSEDiffractionViewer_maskmat,maskmat,detxmin,detxmax,detymin,detymax
    ;print,'NSEDiffractionViewer_maskmat'

    if detxmin lt 0 then detxmin = 0
    if detymin lt 0 then detymin = 0
    if detxmax gt 31 then detxmax = 31
    if detymax gt 31 then detymax = 31

    ;0 = masked
    ;1 = unmasked
    maskmat = intarr(32,32)
    maskmat[detxmin:detxmax,detymin:detymax] = 1
    maskmat = reform(maskmat,1024)

end;NSEDiffractionViewer_maskmat

pro NSEDiffractionViewer_arcsmat,arcmat,narcs,qmat;xcen,ycen,qarcs

    x_dim = 32
    y_dim = 32

;    check = NSEDiffractionViewer_qvals(qmat,xcen,ycen)
    ;NSEDiffractionViewer_maskmat,maskmat,detxmin,detxmax,detymin,detymax
    ;arcmat = 0*fix(qmat)

    ;CREATE A MATRIX INDEXING THE PIXELS BASED ON THE
    ;Q-ARCS.

    if narcs eq 0 then narcs = 1


;101404
;
;STEVE SIMPLY SETS THE VALUES OF qmin AND qmax TO BE
;THE MINIMUM AND MAXIMUM QVALUES IN THE QArray.

 qmin = min(qmat)
 qmax = max(qmat)


    if narcs ne 0 and narcs gt 1 then begin
        qstep = (qmax - qmin)/(narcs-1)

        qarcs = dblarr(narcs)
        for i=0,n_elements(qarcs)-1 do begin
            qarcs[i] = qmin + qstep*double(i)
        endfor

        sz = [2,x_dim,y_dim]
        arcmat = intarr(sz[1],sz[2])
        for k = 0,narcs-1 do begin
            Q1 = qarcs[k] - qstep/2.0
            Q2 = qarcs[k] + qstep/2.0

            for j=0,sz[2]-1 do begin
                for i=0,sz[1]-1 do begin

                    ;STEVE'S IMPLEMENTATION IS:
                    kq = round(((qmat)[i+j*x_dim]-qmin)/qstep)
                    arcmat[i,j] = kq
                endfor;i
            endfor;j
        endfor;k
    endif else begin
        if narcs eq 1 then begin
            sz = [2,x_dim,y_dim]
            arcmat = intarr(sz[1],sz[2])
        endif else begin
            void = dialog_message('narcs = 0!  IQT not calculated')
        endelse

    endelse

    arcmat = reform(arcmat,sz[1]*sz[2]) ;RETURNED VIA THE KEYWORD.

end;NSEDiffractionViewer_arcsmat


pro NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,image


    segs = strsplit(line,/extract)

    ;READ XDOWN
    ;GET XDOWN COUNTERS
    while strcmp(segs[0],'counters',/fold_case) eq 0 do begin
        readf,lun,line & nread++
        segs = strsplit(line,/extract)
    endwhile
    readf,lun,counters & nread++
    ;GET XDOWN IMAGE
    while strcmp(segs[0],'detector',/fold_case) eq 0 do begin
        readf,lun,line & nread++
        segs = strsplit(line,/extract)
    endwhile
    readf,lun,image & nread += npix
    image = NSEDiffractionViewer_deadTime(image,counters[0],counters[4],counters[0],$;preset,$
                                                counters[1],counters[2],counters[3])

end;NSEDiffractionViewer_readImage,lun,line,nread,image



pro NSEDiffractionViewer_readMagnetic,fn,x,y,sy,t,inc,c,m,st,sinc,sc,sm,$
                                      narcs,xcen,ycen,detxrange,detyrange,lambda,$
                                      results,psym

;                print,'NSEDiffractionViewer_readMagnetic'
;                print,narcs,xcen,ycen,detxrange,detyrange,lambda

                catch,error_status
                if error_status ne 0 then begin
                    ;print,'ERROR OCCURRED IN NSEDiffractionViewer_readMagnetic'
                    ;print,'error_status=',error_status
                    ;help,!error_state
                    ;print,!error_state.msg
                    catch,/cancel

                    help,lun,output=out
                    if stregex(out[0],'UNDEFINED',/fold_case,/boolean) eq 0 then begin
                        help,lun,/files,output=out
                        if stregex(out[1],'closed',/fold_case,/boolean) eq 0 then $
                        free_lun,lun
                    endif

                    if n_elements(x) gt 1 then begin

                        NSEDiffractionViewer_truncateData,x,y,sy,t,st,inc,sinc,c,sc,m,sm
                        if n_elements(results) gt 1 then begin
                            temp = results[0]
                            results = results[1:*]
                            if obj_valid(temp) gt 0 then obj_destroy,temp
                        endif
                    endif else begin
                        x  = [-1.0d]
                        y  = [-1.0d]
                        sy = [-1.0d]
                        inc = [-1.0d]
                        sinc = [-1.0d]
                        t = [-1.0d]
                        st = [-1.0d]
                        c = [-1.0d]
                        sc = [-1.0d]
                        m = [-1.0d]
                        sm = [-1.0d]
                        result = [-1]
                    endelse
                    return
                endif;error_status ne 0

            ;INITIALIZE VARIABLES
            detcount = 0
            qcount = 0
            nread = 0
            nlines = file_lines(fn)
            npix = 1024
            line=''
            q = 0.0d
            nq = 0
            counters = dblarr(5)
            dumup    = dblarr(npix)
            dumdn    = dblarr(npix)
            dumXup   = dblarr(npix)
            dumXdn   = dblarr(npix)
            dumYup   = dblarr(npix)
            dumYdn   = dblarr(npix)
            dumZup   = dblarr(npix)
            dumZdn   = dblarr(npix)
            results = objarr(1)
            x  = [-1.0d]
            y  = [-1.0d]
            sy = [-1.0d]
            inc = [-1.0d]
            sinc = [-1.0d]
            t = [-1.0d]
            st = [-1.0d]
            c = [-1.0d]
            sc = [-1.0d]
            m = [-1.0d]
            sm = [-1.0d]


            ;OPEN FILE
            openr,lun,fn,/get_lun


            ;READ THROUGH FILE
            readf,lun,line & nread++
;            segs = strsplit(line,/extract)

            while nread lt nlines do begin

                ;GET Q
                segs = strsplit(line,/extract)
                while strcmp(segs[0],'Q',/fold_case) eq 0 do begin ;readcount lt lines do begin
                    readf,lun,line & nread++
                    segs = strsplit(line,/extract)
                endwhile
                q = double(segs[1])
                nq++

                ;READ XDOWN
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumXDn

                ;READ XUP
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumXUp

                ;READ ZDOWN
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumZDn

                ;READ ZUP
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumZup

                ;READ YDOWN
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumYDn

                ;READ YUP
                NSEDiffractionViewer_readImage,lun,line,nread,npix,counters,dumYUp


     ;CALCULATE VALUES WITH THESE IMAGES
            self_preset = 1;counters[0]
            self_q = q
            ;print,'q=',q

            goodq = NSEDiffractionViewer_qvals(qmat,xcen,ycen,lambda,q);actual)

;            if goodq eq 1 then print,'Q VALUES ARE GOOD.' else print,'BAD Q VALUES, CHECK YOUR LAMBDA, ETC.'
            if goodq ne 1 then void = dialog_message('BAD Q VALUES, CHECK YOUR LAMBDA, ETC.')

            NSEDiffractionViewer_maskmat,mask,detxrange[0],detxrange[1],detyrange[0],detyrange[1]

            NSEDiffractionViewer_arcsmat,arcmat,narcs,qmat
;print,'TESTING NSEDiffractionViewer_readMagnetic'
            ret = NSEDiffractionViewer_f_polanalysisgeneral(0,$;Verbose,$
                                                            1.0,$;self_p,$
                                                            1,$;self_no_of_fourier_time,$
                                                            1.0,$;self_Eff_BPW,$
                                                            1.0,$;self_f,$
                                                            1.0,$;self_xyzupdownscale,$
                                                            dumXdn,$
                                                            dumXup,$
                                                            dumYdn,$
                                                            dumYup,$
                                                            dumZdn,$
                                                            dumZup,$
                                                            mask,$;self_mask2d,$
                                                            self_preset,$ ;GET VALUE FROM FILE IN COUNTERS???
                                                            self_q,$      ;GET FROM FILE.
                                                            qmat,$;self_qvals,$
                                                            narcs,$;1,$;self_narcs,$
                                                            arcmat,$
                                                            sq1dtotal=sq1dtotal,$
                                                            sq1dmagnetic=sq1dmagnetic,$
                                                            sq1dspinIncoherent=sq1dspinIncoherent,$
                                                            sq1dCoherentAndIsotopeIncoherent=sq1dCoherentAndIsotopeIncoherent,$
                                                            timeaverage=0);timeaverage



;NOW NEED TO CREATE A NEW OBJECT EACH TIME.

            ;GET THE Q VALUES HERE.
            ;NOTE: THESE MAY GET OUT OF ORDER DUE TO THE Q RANGES OVER THE DETECTOR.
                x =    [x,*(sq1dtotal.q)]
                y =    [y,*(sq1dtotal.s)]
                sy =   [sy,*(sq1dtotal.ss)]

                t =    [t,*(sq1dtotal.s)]
                st =   [st,*(sq1dtotal.ss)]
                inc =  [inc,*(sq1dspinIncoherent.s)]
                sinc = [sinc,*(sq1dspinIncoherent.ss)]
                c =    [c,*(sq1dCoherentAndIsotopeIncoherent.s)]
                sc =   [sc,*(sq1dCoherentAndIsotopeIncoherent.ss)]
                m =    [m,*(sq1dmagnetic.s)]
                sm =   [sm,*(sq1dmagnetic.ss)]

                ;print,'NSEDiffractionViewer_readMagnetic'
                ;print,'*(sq1dtotal.q)=',*(sq1dtotal.q)

                ;MAGNETIC OBJECT WITH 4 DATA SETS
                dat = obj_new('NSEDiffractionViewerMagnetic_data',*(sq1dtotal.q),$
                                                                  *(sq1dtotal.s),$
                                                                  *(sq1dtotal.ss),$
                                                                  coh=*(sq1dCoherentAndIsotopeIncoherent.s),$
                                                                  scoh=*(sq1dCoherentAndIsotopeIncoherent.ss),$
                                                                  mag=*(sq1dmagnetic.s),$
                                                                  smag=*(sq1dmagnetic.ss),$
                                                                  incoh=*(sq1dspinIncoherent.s),$
                                                                  sincoh=*(sq1dspinIncoherent.ss),$
                                                                  tot=*(sq1dtotal.s),$
                                                                  stot=*(sq1dtotal.ss),$
                                                                  legend=file_basename(fn)+'_q'+strtrim(string(nq),2),$
                                                                  psym=psym,$
                                                                  showlegend=1,showdata=1)

                results = [results,dat]

            endwhile
;            if stregex(out[0],'UNDEFINED',/fold_case,/boolean) eq 0 then begin
                help,lun,/files,output=out
                if stregex(out[1],'closed',/fold_case,/boolean) eq 0 then $
                free_lun,lun
;            endif

            if n_elements(results) gt 1 then begin
                temp = results[0]
                results = results[1:*]
                if obj_valid(temp) gt 0 then obj_destroy,temp
            endif

            NSEDiffractionViewer_truncateData,x,y,sy,t,st,inc,sinc,c,sc,m,sm

end;NSEDiffractionViewer_readMagnetic

pro NSEDiffractionViewer_truncateData,x,y,sy,t,st,inc,sinc,c,sc,m,sm
            if n_elements(x) gt 1 then x = x[1:*]
            if n_elements(y) gt 1 then y = y[1:*]

            if n_elements(sy) gt 1 then sy = sy[1:*]

            if n_elements(t) gt 1 then t = t[1:*]
            if n_elements(st) gt 1 then st = st[1:*]

            if n_elements(inc) gt 1 then inc = inc[1:*]
            if n_elements(sinc) gt 1 then sinc = sinc[1:*]

            if n_elements(c) gt 1 then c = c[1:*]
            if n_elements(sc) gt 1 then sc = sc[1:*]

            if n_elements(m) gt 1 then m = m[1:*]
            if n_elements(sm) gt 1 then sm = sm[1:*]
end;NSEDiffractionViewer_truncateData

pro NSEDiffractionViewer_makemask,mask,detxrange,detyrange

    mask = intarr(32,32)
    mask[detxrange[0]:detxrange[1],detyrange[0]:detyrange[1]] = 1
    mask = reform(mask,1024)

end;NSEDiffractionViewer_makemask
;###############################################################################
;
;NAME:
;        NSEDiffractionViewer_read
;
;PURPOSE:
;       READ A .dfr DATA FILE AND SET x,y,sy
;PARAMETERS:
;       event   event passed in to get pstate
;       fn      The filename or array of filenames.
;       x       The results of reading the data.
;       y
;       sy
;
;KEYWORDS:
;
;
;
;
;COMMENTS:  This function reads a data file and passes the file to either NSEDiffractionViewer_readAltMagnetic or
;           NSEDiffractionViewer_readNonMagnetic.  These return the "results" variable which is an array of data
;           objects to add to the plot object.
;
;###############################################################################
function NSEDiffractionViewer_read,event,fn,narcs,xcen,ycen,detxrange,detyrange,$
                                   lambda,results,psym,f;,x,y,sy,magnetic
;help,/traceback
    widget_control,event.handler,get_uvalue=pstate

    magnetic = -1

    nfn = n_elements(fn)


    if nfn gt 0 then begin

;void = dialog_message('NSEDiffractionViewer_read:  nfn gt 0')
        if fn[0] ne '' then begin
;void = dialog_message("NSEDiffractionViewer_read:  fn[0] ne ''")
;void = dialog_message("NSEDiffractionViewer_read:  fn[0] eq "+file_basename(fn[0]))
;void = dialog_message("NSEDiffractionViewer_read:  fn[0] eq "+fn[0])

            magnetic = NSEDiffractionViewer_checkmagnetic(fn)

            case magnetic of
            0:begin
;void = dialog_message(['################################################################',$
                       ;"NSEDiffractionViewer_read:  magnetic eq 0 #1",$
                       ;'################################################################'])

;print,'Before NSEDiffractionViewer_readNonMagnetic'

                NSEDiffractionViewer_readNonMagnetic,fn,x,y,sy,$
                                                     t,i,c,st,si,sc,$
                                                     narcs,xcen,ycen,$
                                                     detxrange,detyrange,lambda,$
                                                     results,psym,f
    help,results,output=routput
    ;void = dialog_message('help,results='+routput)
;print,'After NSEDiffractionViewer_readNonMagnetic'

    ;            print,';_read ############### NONMAGNETIC ###############'
    ;            help,results
    ;            help,results[0]

                order = sort(x)
                x = x[order]
                y = y[order]
                sy = sy[order]

                ;NEW STUFF
                t = t[order]
                st = st[order]
                i = i[order]
                si = si[order]
                c = c[order]
                sc = sc[order]
    ;help,results
            end;0
            1:begin
    ;            NSEDiffractionViewer_readMagnetic,fn,x,y,sy,t,i,c,m,st,si,sc,sm,$
    ;                                              narcs,xcen,ycen,detxrange,detyrange,lambda,$
    ;                                              results,psym
             NSEDiffractionViewer_readAltMagnetic,fn,x,y,sy,t,i,c,m,st,si,sc,sm,$
                                                  narcs,xcen,ycen,detxrange,detyrange,lambda,$
                                                  results,psym,f



;void = dialog_message("NSEDiffractionViewer_read:  after NSEDiffractionViewer_readAltMagnetic")


    ;help,m
    ;help,sm
    ;help,t
    ;help,x
    ;help,results
                ;print,';_read ############### MAGNETIC ###############'
                ;help,results
                ;help,results[0]


                order = sort(x)
                x = x[order]
                y = y[order]
                sy = sy[order]
                t = t[order]
                st = st[order]
                i = i[order]
                si = si[order]
                c = c[order]
                sc = sc[order]
                m = m[order]
                sm = sm[order]
     ;           help,results
            end;1
            -1:begin
;void = dialog_message("NSEDiffractionViewer_read:  magnetic eq -1 #1")

                x  = [-1.0d]
                y  = [-1.0d]
                sy = [-1.0d]
            end;-1
            else:begin
;void = dialog_message("NSEDiffractionViewer_read:  magnetic else #1")
                x  = [-1.0d]
                y  = [-1.0d]
                sy = [-1.0d]
            end;else
            endcase

        endif else begin
                x  = [-1.0d]
                y  = [-1.0d]
                sy = [-1.0d]
        endelse

    ;    order = sort(x)
    ;
    ;    x = x[order]
    ;    y = y[order]
    ;    sy = sy[order]

    ;    print,'COUNT=',(*pstate).plotobj->count()+1
    ;    print,'psym=',psym
        ;CREATE DATA OBJECT
        case magnetic of
        0:begin
            ;help,results
            ;print,n_elements(results)
            ;(*pstate).nsets += 1;= (*pstate).plotobj->count()+1
            ;psym = -(((*pstate).nsets)+1 mod 9)

    ;REPLACING THE NEXT LINES WITH THE FOLLOWING TO ACCOMMODATE coh,incoh
    ;        dat = obj_new('cwo_drawplot_data',x,y,sy,legend=file_basename(fn),$
    ;                                psym=psym,showlegend=1,showdata=1)
;void = dialog_message("NSEDiffractionViewer_read:  magnetic eq 0 #2")

            dat = obj_new('NSEDiffractionViewerMagnetic_data',x,y,sy,$
                                                                coh=c,$
                                                                scoh=sc,$
                                                                incoh=i,$
                                                                sincoh=si,$
                                                                tot=t,$
                                                                stot=st,$
                                                                /nonmagnetic,$
                                                                legend=file_basename(fn),$
                                                                psym=psym,$
                                                                showlegend=1,showdata=1)
        end;nonmagnetic
        1:begin
            ;help,results
            ;print,n_elements(results)
            ;(*pstate).nsets += 1;= (*pstate).plotobj->count()+1
            ;psym = -(((*pstate).nsets)+1 mod 9)
;void = dialog_message("NSEDiffractionViewer_read:  magnetic eq 1 #2")

            ;print,'NSEDiffractionViewer_read  Magnetic Data set'
            ;MAGNETIC OBJECT WITH 4 DATA SETS
            dat = obj_new('NSEDiffractionViewerMagnetic_data',x,y,sy,$
                                                                coh=c,$
                                                                scoh=sc,$
                                                                mag=m,$
                                                                smag=sm,$
                                                                incoh=i,$
                                                                sincoh=si,$
                                                                tot=t,$
                                                                stot=st,$
                                                                nonmagnetic=0,$
                                                                legend=file_basename(fn),$
                                                                psym=psym,$
                                                                showlegend=1,showdata=1)

help,dat,output=doutput
;void = dialog_message("NSEDiffractionViewer_read:  magnetic eq 1 #2 doutput="+doutput)


        end;magnetic
        else:begin
;void = dialog_message("NSEDiffractionViewer_read:  magnetic else #2")

            print,'NSEDiffractionViewer_read  else'
            dat=-1
            results = -1
        endelse
        endcase

    endif else begin    ;nfn gt 0

        void = dialog_message('NO FILES PASSED TO NSEDiffractionViewer_read')

        dat = -1
        results = -1

    endelse

;SET showlegend TO 1 FOR ONLY THE FIRST OBJECT FROM EACH FILE.
;void = dialog_message("NSEDiffractionViewer_read:  obj_valid(results[0]) = "+string(obj_valid(results[0])))

    if obj_valid(results[0]) gt 0 then begin
;void = dialog_message("NSEDiffractionViewer_read:  obj_valid(results[0]) gt 0 ")

        results[0]->setproperty,showlegend=1
        if n_elements(results) gt 1 then begin
;void = dialog_message("NSEDiffractionViewer_read:  n_elements(results) gt 1 ")
            for i=1,n_elements(results)-1 do begin
                results[i]->setproperty,showlegend=0
            endfor;i
        endif
    endif


;help,/traceback
;help,dat
    ;RETURN DATA OBJECT

;THIS DATA OBJECT IS PROBABLY SUPERFLUOUS.  CHECK IN CALLING ROUTINE.
;I THINK ONLY THE results OBJECT ARRAY IS USED.
    return,dat

end;NSEDiffractionViewer_read

;###############################################################################
;
;NAME:
;        NSEDiffractionViewer_open
;
;PURPOSE:
;       GET A FILENAME AND RETURN A cwo_drawplot_data
;       DATA OBJECT FOR PLOTTING.
;PARAMETERS:
;       event   THE EVENT THAT PROMPTED THE CALL.
;KEYWORDS:
;       none
;RETURN VALUE:
;       dat THE DATA OBJECT OR -1 IF NO VALID DATA READ.
;###############################################################################
;function NSEDiffractionViewer_open,event,narcs,xcen,ycen,detxrange,detyrange,$
;                                   lambda,results,f,fn=fn
function NSEDiffractionViewer_open,event,results,fn=fn,update=update
;if n_elements(fn) gt 0 then print,'NSEDiffractionViewer_open: fn=',transpose(fn)
;help,/traceback

;print,'NSEDiffractionViewer_open Test1'

    if n_elements(update) eq 0 then update = 0


    widget_control,event.handler,get_uvalue=pstate

    ;1) GET INFORMATION
    widget_control,(*pstate).narcsfield,get_value=narcs
;print,'narcs=',narcs

    widget_control,(*pstate).xcenfield ,get_value=xcen
;print,'xcen=',xcen

    widget_control,(*pstate).ycenfield ,get_value=ycen
;print,'ycen=',ycen


    detxrange = (*pstate).xminmaxobj->getvalues()
;print,'detxrange=',detxrange


    detyrange = (*pstate).yminmaxobj->getvalues()
;print,'detyrange=',detyrange

    widget_control,(*pstate).lambdafield,get_value=lambda
    lambda = 1.0e-10*lambda
;print,'lambda=',lambda



    widget_control,(*pstate).flippingratiofield,get_value=f
    if f eq 0 then begin
        f = 7
        widget_control,(*pstate).flippingratiofield,set_value=f
    endif

;print,'flipping ratio=',f
;print,'NSEDiffractionViewer_open Test2',narcs,xcen,ycen,detxrange,detyrange,lambda,f
;void = dialog_message('NSEDiffractionViewer_open Test2'+string([narcs,xcen,ycen,detxrange,detyrange,lambda,f]))


    ;IF NO fn THEN GET fn FROM USER NOW
    if n_elements(fn) eq 0 then begin
        ;013007 ADD /multiple KEYWORD
        fn = dialog_pickfile(filter='*.dfr',path = (*pstate).workdir,/multiple)
    ;    print,fn
    endif

    newdata = 0
    loadedfilelist = *((*pstate).loadedfiles)

;print,'NSEDiffractionViewer_open Test3 loadedfilelist='+string(loadedfilelist)
;void = dialog_message('NSEDiffractionViewer_open Test3 loadedfilelist='+string(loadedfilelist))



    ;PROCESS THE fn
    if n_elements(fn) gt 0 then begin
;void = dialog_message('NSEDiffractionViewer_open Test4 loadedfilelist='+string(fn))

        progtitle = update eq 0 ? 'Reading selected files:' : 'Updating selected files:'

        prog = nseprogress([n_elements(fn)],$
                            title=progtitle,$
                            labels=['File #'],$
                            xsize=300,$
                            start=[0],$
                            group_leader=(*pstate).tlb,$
                            stopbutton=0)
        for i=0,n_elements(fn)-1 do begin

                    nseprogress_step,prog
                    ;013007
                    ;
                    psym = ((*pstate).nsets + 1) mod 9      ;ADD 1 HERE.  IF IT IS USED IN THE APPROPRIATE
                                                            ;READ METHOD THEN THEY WILL HAVE THE ONE
                                                            ;ADDITIONAL SET.




        ;ALL OF THE INFORMATION IS PASSED VIA THE results ARRAY IN THE FOLLOWING CALL:
                    dat = NSEDiffractionViewer_read(event,fn[i],narcs,xcen,ycen,detxrange,detyrange,$
                                                        lambda,results,psym,f);,x,y,sy)


help,dat,output=doutput
;void = dialog_message('NSEDiffractionViewer_open help,dat:'+doutput)


        ;ADDED THE HANDLING OF THE FILE LIST HERE
                    if obj_valid(dat) gt 0 then begin
                        (*pstate).workdir = file_dirname(fn[i])

                        ;013007 NOW NEED TO RECORD EACH FILENAME AS IT IS PROCESSED.
                        if (*pstate).nsets eq 0 then begin
                            loadedfilelist = [fn[i]]
                        endif else begin
                            loadedfilelist = [loadedfilelist,fn[i]]
                        endelse
;print,'help,results[0]'
;help,results[0],output=routput
;print,'obj_valid(results[0]) = ',obj_valid(results[0])
;void = dialog_message('help,results[0]='+routput)

;void = dialog_message('obj_valid(results[0]) = '+string(obj_valid(results[0])))

                        if obj_valid(results[0]) ne 0 then begin

                        ;THE PROPERTIES OF EACH OF THE DATA SETS REPRESENTED IN results ARE ALREADY SET.
                        ;ADD THE DATA SET(S) TO THE PLOT OBJECT
                            for j=0,n_elements(results)-1 do begin
;                                ;print,j
;                                if j eq 0 then begin
;                                    results[j]->setproperty,showlegend=1
;                                endif else begin
;                                    results[j]->setproperty,showlegend=0
;                                endelse

                                (*pstate).plotObj->add,results[j],/no_draw
                            endfor;j
                            newdata = 1

                            (*pstate).nsets++
                        endif

                        ;DESTROY THIS UNUSED OBJECT.
                        obj_destroy,dat

                    endif;obj_valid(dat)
;help,newdata
        endfor;i
        dat = -1
    endif else begin
        print,'NO FILES SELECTED.'

        dat = -1

    endelse
;print,loadedfilelist


;print,'NSEDiffractionViewer_open Test5'


    ;UPDATE THE RECORD OF LOADED FILES
    if ptr_valid((*pstate).loadedfiles) gt 0 then ptr_free,(*pstate).loadedfiles
    (*pstate).loadedfiles = ptr_new(loadedfilelist)
;print,'NSEDiffractionViewer_open Test6'


    ;REDRAW THE PLOT
    if newdata ne 0 then begin
        (*pstate).plotObj->defaultDraw
    endif
;print,'NSEDiffractionViewer_open Test7'

    nseprogress_close,prog

;print,'NSEDiffractionViewer_open Test7'

    return,dat
end;NSEDiffractionViewer_open
;###############################################################################
;
;NAME:
;        NSEDiffractionViewer_updateCurrentSets
;
;PURPOSE:
;       UPDATE SETS ON NEW INPUT VALUES FROM USER.
;PARAMETERS:
;       event   EVENT THAT PROMPTED THE CALL TO THIS FUNCTION.
;KEYWORDS:
;       none
;###############################################################################
pro NSEDiffractionViewer_updateCurrentSets,event



        widget_control,event.handler,get_uvalue=pstate
        if (*pstate).nsets gt 0 then begin
;print,'NSEDiffractionViewer_updateCurrentSets test1'
            ;1) SAVE LIST OF FILES
            loadedfilelist = *(*pstate).loadedfiles
;print,'NSEDiffractionViewer_updateCurrentSets test2'
            ;SET THE NUMBER OF DATA FILES TO 0
            (*pstate).nsets = 0
;print,'NSEDiffractionViewer_updateCurrentSets test3'
            ;DELETE THE LOADED FILENAMES (THIS WILL BE RESET IN THE open METHOD)
            if ptr_valid((*pstate).loadedfiles) gt 0 then ptr_free,(*pstate).loadedfiles
            (*pstate).loadedFiles = ptr_new(strarr(1))

;print,'NSEDiffractionViewer_updateCurrentSets test4'
            ;2) CLEAR DATA FROM PLOT CONTAINER
            o = (*pstate).plotobj->get(/all)
            (*pstate).plotobj->remove,/all
            if obj_valid(o[0]) gt 0 then obj_destroy,o
;print,'NSEDiffractionViewer_updateCurrentSets test5'

            ;3) STEP THROUGH LIST OF LOADED FILES USING OPEN.
            obj = NSEDiffractionViewer_open(event,results,fn=loadedfilelist,/update)
;print,'NSEDiffractionViewer_updateCurrentSets test6'
            ;help,obj

            ;CHECK TO SEE THAT obj IS JUST A NUMBER AND DOES NOT REQUIRE CLEANUP.
            ;print,'NSEDiffractionViewer_updateCurrentSets obj=',obj

        endif

;print,'NSEDiffractionViewer_updateCurrentSets test7'

end;NSEDiffractionViewer_updateCurrentSets


;###############################################################################
;
;NAME:
;        NSEDiffractionViewer_event
;
;PURPOSE:
;       EVENT HANDLER
;PARAMETERS:
;       event   THE EVENT TO HANDLE
;KEYWORDS:
;       none
;###############################################################################
pro NSEDiffractionViewer_event,event


;print,tag_names(event)
;print,event
    widget_control,event.handler,get_uvalue=pstate
    case event.id of
    (*pstate).quit:begin
        widget_control,(*pstate).tlb,/destroy
    end;quit
    (*pstate).open:begin
        obj = NSEDiffractionViewer_open(event,results)
    end;open
    (*pstate).save:begin
        o = (*pstate).plotobj->get(/all)
        if obj_valid(o[0]) gt 0 then begin
            for i=0,n_elements(o)-1 do begin
                    o[i]->writeASCII
            endfor;i
        endif else begin
            void = dialog_message('No data to save')
        endelse
    end;save
    (*pstate).cleardata:begin
        o = (*pstate).plotobj->get(/all)
        (*pstate).plotobj->remove,/all
        if obj_valid(o[0]) gt 0 then obj_destroy,o
        (*pstate).plotObj->defaultDraw


       if ptr_valid((*pstate).loadedfiles) gt 0 then ptr_free,(*pstate).loadedfiles
        (*pstate).loadedfiles = ptr_new(strarr(1))
        (*pstate).nsets = 0

    end;cleardata
    (*pstate).tlb:begin
        print,'TLB Resize'

        if !version.os eq 'Win32' then begin
            geom = widget_info((*pstate).tlb,/geometry)
;print,tag_names(event)
;print,tag_names(geom)
            xpadding = 40
            ypadding = 40
            controlsize = widget_info((*pstate).controlbase,/geometry)
            plotsize    = widget_info((*pstate).plotbase,/geometry)


            if geom.xsize le 680 then xsize = 680 else xsize = geom.xsize
            if geom.ysize le 440 then ysize = 440 else ysize = geom.ysize

            window,/free,/pixmap,xsize=xsize,ysize=ysize
            (*pstate).winpix = !d.window

            erase,(*pstate).soothing

            widget_control,(*pstate).draw,xsize=xsize,ysize=ysize

            wset,(*pstate).winvis
            device,copy=[0,0,xsize,ysize,0,0,(*pstate).winpix]

            wdelete,(*pstate).winpix

            plotxsize = xsize - controlsize.xsize - xpadding
            plotysize = ysize - ypadding

            (*pstate).plotobj->resize,plotxsize,plotysize
        endif else begin
;            print,'Non-Win32 Resize'
;            print,tag_names(event)
;            print,event
;            geom = widget_info((*pstate).tlb,/geometry)
;            print,tag_names(geom,/structure_name)
;            print,tag_names(geom)
;            print,geom
;
;            xpadding = 40
;            ypadding = 40
;            controlsize = widget_info((*pstate).controlbase,/geometry)
;            plotsize    = widget_info((*pstate).plotbase,/geometry)
;
;
;            if geom.xsize le 680 then xsize = 680 else xsize = geom.xsize
;            if geom.ysize le 440 then ysize = 440 else ysize = geom.ysize
;
;            window,/free,/pixmap,xsize=xsize,ysize=ysize
;            (*pstate).winpix = !d.window
;
;            erase,(*pstate).soothing
;
;            widget_control,(*pstate).draw,xsize=xsize,ysize=ysize
;
;            wset,(*pstate).winvis
;            device,copy=[0,0,xsize,ysize,0,0,(*pstate).winpix]
;
;            wdelete,(*pstate).winpix
;
;            plotxsize = xsize - controlsize.xsize - xpadding
;            plotysize = ysize - ypadding
;
;            (*pstate).plotobj->resize,plotxsize,plotysize

;Updated:

;            print,'Non-Win32 Resize'
;            print,tag_names(event)
;            print,event
            geom = widget_info((*pstate).tlb,/geometry)
;            print,tag_names(geom,/structure_name)
;            print,tag_names(geom)
;            print,geom

            xpadding = 128
            ypadding = 50
	        yfudge = 36
            controlsize = widget_info((*pstate).controlbase,/geometry)
            plotsize    = widget_info((*pstate).plotbase,/geometry)

            minxsize = 680
            minysize = 530
            if geom.scr_xsize le minxsize then xsize = minxsize else xsize = geom.scr_xsize
            if geom.scr_ysize le minysize then ysize = minysize else ysize = geom.scr_ysize - yfudge

            window,/free,/pixmap,xsize=xsize,ysize=ysize
            (*pstate).winpix = !d.window

            erase,(*pstate).soothing

            widget_control,(*pstate).draw,xsize=xsize,ysize=ysize

            wset,(*pstate).winvis
            device,copy=[0,0,xsize,ysize,0,0,(*pstate).winpix]

            wdelete,(*pstate).winpix

            plotxsize = xsize - controlsize.xsize - xpadding
            plotysize = ysize - ypadding - yfudge

            (*pstate).plotobj->resize,plotxsize,plotysize



        endelse

    end;tlb
    (*pstate).controls:begin
        values = event.values

        (*pstate).plotobj->setvalues,xmin=values.xmin,$
                                     xmax=values.xmax,$
                                     ymin=values.ymin,$
                                     ymax=values.ymax,$
                                     xlog=values.xlog,$
                                     ylog=values.ylog

        (*pstate).plotobj->draw

    end;controls
    (*pstate).plot:begin
        (*pstate).plotobj->reportRanges,xlog=xlog,ylog=ylog,$
                                        xmin=xmin,ymin=ymin,$
                                        xmax=xmax,ymax=ymax

        (*pstate).controlsobj->setvalues, xmin=xmin,ymin=ymin,$
                                          xmax=xmax,ymax=ymax,$
                                          xlog=xlog,ylog=ylog

    end;plot
    (*pstate).narcsfield:begin
        print,'(*pstate).narcsfield event'
;print,'Hey!!!'
        NSEDiffractionViewer_updateCurrentSets,event

;print,'Hey2!!!'
    end;narcsfield
    (*pstate).xcenfield:begin
        print,'(*pstate).xcenfield event'
        NSEDiffractionViewer_updateCurrentSets,event
    end;xcenfield
    (*pstate).ycenfield:begin
        print,'(*pstate).ycenfield event'
        NSEDiffractionViewer_updateCurrentSets,event
    end;ycenfield
    (*pstate).lambdafield:begin
        print,'(*pstate).lambdafield event'
        NSEDiffractionViewer_updateCurrentSets,event
    end;lambdafield
    (*pstate).flippingratiofield:begin
        print,'(*pstate).flippingratiofield event'
        NSEDiffractionViewer_updateCurrentSets,event
    end;flippingratiofield
    (*pstate).xminmax:begin
        print,'(*pstate).xminmaxfield event'
        NSEDiffractionViewer_updateCurrentSets,event
    end;xminmax
    (*pstate).yminmax:begin
        print,'(*pstate).yminmaxfield event'
        NSEDiffractionViewer_updateCurrentSets,event
    end;yminmax
    else:
    endcase

end;NSEDiffractionViewer_event



;###############################################################################
;
;NAME:
;        NSEDiffractionViewer_cleanup
;
;PURPOSE:
;       CLEANUP METHOD.
;PARAMETERS:
;       id  WIDGET ID CHOSE DESTRUCTION PROMPTED CLEANUP.
;KEYWORDS:
;       none
;###############################################################################
pro NSEDiffractionViewer_cleanup,id

    catch,es

    if es ne 0 then begin
        catch,/cancel
        void = dialog_message('NSEDiffractionViewer_cleanup: '+!error_state.msg)
        return
    endif

    print,'NSEDiffractionViewer_cleanup'
    widget_control,id,get_uvalue=pstate

    if ptr_valid((*pstate).loadedfiles) gt 0 then ptr_free,(*pstate).loadedfiles
    ptr_free,pstate

end;NSEDiffractionViewer_cleanup

;###############################################################################
;
;NAME:
;       NSEDiffractionViewer
;
;PURPOSE:
;       VIEW NSE DATA COLLECTED IN DIFFRACTION MODE (theta-2theta)
;PARAMETERS:
;       none
;KEYWORDS:
;       group_leader    Optional group leader when called from separate application.
;###############################################################################
pro NSEDiffractionViewer,group_leader=group_leader,workdir=workdir,datadir=datadir

    if n_elements(group_leader) eq 1 then begin

        tlb = widget_base(group_leader=group_leader,$
                            title='NSE Diffraction Viewer',$
                            mbar=bar,$
                            kill_notify='NSEDiffractionViewer_cleanup',$
                            ;/row,$
                            xoffset=200,yoffset=200,/floating,$
                            /tlb_size_events)
    endif else begin
        tlb = widget_base(title='NSE Diffraction Viewer',$
                          mbar=bar,$
                          kill_notify='NSEDiffractionViewer_cleanup',$
                          ;/row,$
                          xoffset=200,yoffset=200,$
                          /tlb_size_events)
    endelse

    if n_elements(datadir) eq 0 then datadir = ''
    if n_elements(workdir) eq 0 then workdir = ''


    ;013007
    ;MAKE A DUMMY LOADED FILE AND KEEP TRACK OF THE FILES THAT ARE LOADED
    ;THIS IS NEEDED BECAUSE THE
    loadedfiles = strarr(1)

    filemenu    = widget_button(bar,value='File',/menu)
    open        = widget_button(filemenu,value='Open',uname='OPEN')
    save        = widget_button(filemenu,value='Save',uname='SAVE')
    quit        = widget_button(filemenu,value='Quit',uname='QUIT')


    if !version.os ne 'Win32' then draw = widget_draw(tlb,xoffset=0,yoffset=0,xsize=780,ysize=480)
    col1 = widget_base(tlb,/col,xoffset=10,yoffset=20,frame=2)

    col2xoffset = (!version.os eq 'Win32') ? 260 : 360
    col2 = widget_base(tlb,/col,xoffset=col2xoffset,yoffset=20)

    if !version.os eq 'Win32' then draw = widget_draw(tlb,xoffset=0,yoffset=0,xsize=680,ysize=480)

    controls = cwo_plotrangeloglin(col1,/col,obj=controlsobj)


    values = controlsobj->getvalues()

    xminmax = cwo_minmax(col1,$
                   range=[0,31],$
                   xsize = 5,$
                   ysize = 1,$
                   /row,$
                   labels=['detXmin','detXmax'],$
                   value=[0,31],$
                   title='XRANGE:',floating=0,integer=1,obj=xminmaxobj)

    yminmax = cwo_minmax(col1,$
                   range=[0,31],$
                   xsize = 5,$
                   ysize = 1,$
                   /row,$
                   labels=['detYmin','detYmax'],$
                   value=[5,24],$
                   title='YRANGE:',floating=0,integer=1,obj=yminmaxobj)

    lambdafield = cw_field(col1,title='Wavelength (Å)',value=10.0,/floating,xsize=9,/return_events)
    flippingratiofield = cw_field(col1,title='Flipping Ratio',value=7.0,/floating,xsize=4,/return_events)

    xcenfield  = cw_field(col1,title='DetXCen',value=16,/floating,xsize=9,/return_events)
    ycenfield  = cw_field(col1,title='DetYCen',value=16,/floating,xsize=9,/return_events)
    narcsfield = cw_field(col1,title='NARCS',value=1,/integer,xsize=5,/return_events)

    cleardata = widget_button(col1,value='Clear Data')

    colorbase = widget_base(col1)

    ;BLACK
    totlab = widget_label(colorbase,value='Total',xoffset = 0,yoffset=0)
    totdrw = widget_draw( colorbase,xsize=30,ysize=5,xoffset=0,yoffset=15)

    ;RED
    maglab = widget_label(colorbase,value='Mag',  xoffset = 40,yoffset=0)
    magdrw = widget_draw( colorbase,xsize=30,ysize=5,xoffset=40,yoffset=15)

    ;BLUE
    cohlab = widget_label(colorbase,value='Coh',  xoffset = 80,yoffset=0)
    cohdrw = widget_draw( colorbase,xsize=30,ysize=5,xoffset=80,yoffset=15)

    ;GREEN
    inclab = widget_label(colorbase,value='Incoh',xoffset = 120,yoffset=0)
    incdrw = widget_draw( colorbase,xsize=30,ysize=5,xoffset=120,yoffset=15)


    plot = cwo_drawplot(col2,xsize=400,ysize=400,$
                            Title ='NSE Diffraction Data',$
                            xtitle='Q',$
                            ytitle='Total Counts (Deadtime corrected)',$
                            obj=plotobj)

    plotobj->range,xmin=values.xmin,ymin=values.ymin,xmax=values.xmax,ymax=values.ymax
    plotobj->setxlog,values.xlog
    plotobj->setylog,values.ylog

    state = {   tlb:tlb,$
                nsets:0,$
                workdir:workdir,$
                datadir:datadir,$
                loadedfiles:ptr_new(loadedfiles),$
                controlbase:col1,$
                plotbase:col2,$
                lambdafield:lambdafield,$
                flippingratiofield:flippingratiofield,$
                controls:controls,$
                controlsobj:controlsobj,$
                xminmax:xminmax,$
                xminmaxobj:xminmaxobj,$
                yminmax:yminmax,$
                yminmaxobj:yminmaxobj,$
                cleardata:cleardata,$
                plot:plot,$
                plotobj:plotobj,$
                open:open,$
                save:save,$
                quit:quit,$
                narcsfield:narcsfield,$
                xcenfield:xcenfield,$
                ycenfield:ycenfield,$
                draw:draw,$
                winvis:0,$
                winpix:0,$
                incdrw:incdrw,$
                cohdrw:cohdrw,$
                magdrw:magdrw,$
                totdrw:totdrw,$
                incvis:0,$
                cohvis:0,$
                magvis:0,$
                totvis:0,$
                red:255L,$
                green:256L*255L,$
                blue:256L*256L*255L,$
                soothing:100L+256L*130L+256L*256L*200L}

    pstate = ptr_new(state)
    widget_control,tlb,/realize,set_uvalue=pstate

    widget_control,draw,get_value=winvis
    (*pstate).winvis = winvis
    wset,winvis
    device,decomposed=1
    erase,(*pstate).soothing;[255L,255L,255L]


    ;CREATE LEGENDS.
    widget_control,cohdrw,get_value=cohvis
    (*pstate).cohvis = cohvis
    wset,cohvis
    erase,(*pstate).blue

    widget_control,totdrw,get_value=totvis
    (*pstate).totvis = totvis
    wset,totvis
    erase,0L

    widget_control,magdrw,get_value=magvis
    (*pstate).magvis = magvis
    wset,magvis
    erase,(*pstate).red

    widget_control,incdrw,get_value=incvis
    (*pstate).incvis = incvis
    wset,incvis
    erase,(*pstate).green

    xmanager,'NSEDiffractionViewer',tlb,/no_block

end;

