;###############################################################################
;
; NAME:   Raw_FocusFile_Display  Tue Jan 30 10:55:33 2007
;
;
;Authors:
;PD Dr. Philip Tregenna-Piggott,
;Laboratory for Neutron Scattering,
;ETH Zurich and Paul-Scherrer Institute,
;CH-5232 Villigen PSI,
;Switzerland.
;
;Tel. :+41 56 310 54 05
;Fax. :+41 56 310 29 39
;Email:philip.tregenna@psi.ch
;
;
;
;Dr. Thierry Straessle,
;Laboratory for Neutron Scattering,
;ETH Zurich and Paul-Scherrer Institute,
;CH-5232 Villigen PSI,
;Switzerland.
;
;Tel. :+41 56 310 32 46
;Fax. :+41 56 310 29 39
;Email:thierry.straessle@psi.ch
;
;
;
; CATEGORY:
;
;       FOCUS Tools
;
; CALLING SEQUENCE:
;
;      Raw_FocusFile_Display
;
;
; INPUT FIELDS:
;
;
; EXAMPLES FOR POTENTIALS (must use IDL syntax as shown below):
;
;
; DISCLAIMER
;
;     This software is provided as is without any warranty whatsoever.
;     Permission to use, copy, modify, and distribute modified or
;     unmodified copies is granted, provided this disclaimer
;     is included unchanged.
;
; MODIFICATION HISTORY:
;
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;get routines to read nexus files
@napi45
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro RFF_cleanup,tlb
widget_control,tlb,get_uvalue = pState
device, decomposed = (*pState).old_dc
wdelete,(*pState).winState.winPix
heap_free,pState

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro RFF_exit,event
widget_control,event.top,/destroy
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function getbank1d,a,bank=bank,tth=tth

  if n_elements(a) EQ 0 then message,"specify 1d structure"
  if n_elements(bank) EQ 0 then begin
    cnts=a.cnts & tth=a.tth
  endif else begin
    case bank of
      0 : begin
            cnts=a.cnts0
            tth=a.tth0
          end
      1 : begin
            cnts=a.cnts1
            tth=a.tth1
          end
      2 : begin
            cnts=a.cnts2
            tth=a.tth2
          end
    endcase
  endelse
  return,cnts

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function qrange1d,a,bank=bank

  if n_elements(a) EQ 0 then message,"specify 1d structure"

  t2e,a,lambda=lambda
  cnts=getbank1d(a,bank=bank,tth=tth)

  ei=replicate(81.81/lambda^2,n_elements(a.ee))
  ef=ei-a.ee
  li=9.045/sqrt(ei)
  lf=9.045/sqrt(ef)
  ki=2.*!pi/li##[0.,0.,1.]
  qabs=0.*cnts
  for i=0,n_elements(tth)-1 do begin
    kf=2.*!pi/lf##[sin(tth[i]/!radeg),0.,cos(tth[i]/!radeg)]
    dk=ki-kf
    qabs[*,i]=sqrt(dk[0,*]*dk[0,*]+dk[1,*]*dk[1,*]+dk[2,*]*dk[2,*])
  endfor

  return,qabs

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro LoadFocusFile,event
widget_control,event.top,get_uvalue = pState

datDir = (*pState).datDir

fname = dialog_pickfile(dialog_parent=event.top, $
                           title='Select Raw Focus File to Load', $
                           /read,filter='*.hdf', $
                           path=datDir)


;    fname=dialog_pickfile(filter="*.hdf")

  handle=0L
  hdlerror=0

    msg=strarr(2)
    msg[0]='Error in LoadFocusFile Procedure.'


  dummy=nxopen(fname,'NXACC_READ',handle)
  if NOT dummy then begin
    msg[1]='cannot open NEXUS file.'
    void = dialog_message(dialog_parent = event.top,/error,msg)
    return
  endif


  dummy = nxopengroup(handle,'entry1','NXentry')
  if NOT dummy then message,"cannot open 'entry1'."

  dummy*= nxopendata(handle,'title')
  dummy*= nxgetdata(handle,title)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'start_time')
  dummy*= nxgetdata(handle,tstart)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'end_time')
  dummy*= nxgetdata(handle,tend)
  dummy*= nxclosedata(handle)
  if NOT dummy then message,"cannot read title and times."

;--- SAMPLE ---------------------------------------------------------------

  dummy = nxopengroup(handle,'sample','NXsample')
  if NOT dummy then message,"cannot open 'SAMPLE'."
  dummy*= nxopendata(handle,'name')
  dummy*= nxgetdata(handle,sample)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'temperature')
  dummy*= nxgetdata(handle,temp)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'distance')
  dummy*= nxgetdata(handle,sampledist)
  dummy*= nxclosedata(handle)
  dummy*= nxclosegroup(handle)
  if NOT dummy then message,"cannot read 'SAMPLE'."

;--- FOCUS ---------------------------------------------------------------

  dummy = nxopengroup(handle,'FOCUS','NXinstrument')
  if NOT dummy then message,"cannot open 'FOCUS'."

  src='counter'
  dummy = nxopengroup(handle,src,'NXmonitor')
  dummy*= nxopendata(handle,'monitor')
  dummy*= nxgetdata(handle,mon)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'count_mode')
  dummy*= nxgetdata(handle,countmode)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'preset')
  dummy*= nxgetdata(handle,preset)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'time')
  dummy*= nxgetdata(handle,time)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'proton_beam_monitor')
  dummy*= nxgetdata(handle,pmon)
  dummy*= nxclosedata(handle)
  dummy*= nxclosegroup(handle)
  if NOT dummy then message,"cannot read",src,"."

  src='disk_chopper'
  dummy = nxopengroup(handle,src,'NXchopper')
  dummy*= nxopendata(handle,'rotation_speed')
  dummy*= nxgetdata(handle,disk)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'ratio')
  dummy*= nxgetdata(handle,ratio)
  dummy*= nxclosedata(handle)
  dummy*= nxclosegroup(handle)
  if NOT dummy then message,"cannot read",src,"."

  src='fermi_chopper'
  dummy = nxopengroup(handle,src,'NXchopper')
  dummy*= nxopendata(handle,'rotation_speed')
  dummy*= nxgetdata(handle,fermi)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'phase')
  dummy*= nxgetdata(handle,phase)
  dummy*= nxclosedata(handle)
  dummy*= nxclosegroup(handle)
  if NOT dummy then message,"cannot read",src,"."

  src='be_filter'
  dummy = nxopengroup(handle,src,'NXfilter')
  dummy*= nxopendata(handle,'status')
  dummy*= nxgetdata(handle,bef)
  dummy*= nxclosedata(handle)
  dummy*= nxclosegroup(handle)
  if NOT dummy then message,"cannot read",src,"."

  src='flight_path'
  dummy = nxopengroup(handle,src,'NXfilter')
  dummy*= nxopendata(handle,'length')
  dummy*= nxgetdata(handle,flightlength)
  dummy*= nxclosedata(handle)
  dummy*= nxclosegroup(handle)
  if NOT dummy then message,"cannot read",src,"."

  src='monochromator'
  dummy = nxopengroup(handle,src,'NXmonochromator')
  dummy*= nxopendata(handle,'d_spacing')
  dummy*= nxgetdata(handle,mono_dd)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'energy')
  dummy*= nxgetdata(handle,mono_ee)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'lambda')
  dummy*= nxgetdata(handle,mono_ll)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'two_theta')
  dummy*= nxgetdata(handle,mono_tth)
  dummy*= nxclosedata(handle)
  dummy*= nxclosegroup(handle)
  if NOT dummy then message,"cannot read ",src,"."

  src='tof_monitor'
  dummy*= nxopendata(handle,src)
  dummy*= nxgetdata(handle,tofmon)
  dummy*= nxclosedata(handle)
  if NOT dummy then message,"cannot read ",src,"."

  dummy = nxclosegroup(handle)
  if NOT dummy then message,"cannot close 'FOCUS'."

;--- BANKS ---------------------------------------------------------------

  src='bank1'
  dummy = nxopengroup(handle,src,'NXdata')
  if NOT dummy then message,"cannot open ",src,"."
  dummy*= nxopendata(handle,'counts')
  dummy*= nxgetdata(handle,cnts0)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'theta')
  dummy*= nxgetdata(handle,tth0)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'time_binning')
  dummy*= nxgetdata(handle,tt)
  dummy*= nxclosedata(handle)
  if NOT dummy then message,"cannot read ",src,"."
  dummy = nxclosegroup(handle)
  if NOT dummy then message,"cannot close ",src,"."

  src='upperbank'
  dummy = nxopengroup(handle,src,'NXdata')
  if NOT dummy then message,"cannot open ",src,"."
  dummy*= nxopendata(handle,'counts')
  dummy*= nxgetdata(handle,cnts1)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'theta')
  dummy*= nxgetdata(handle,tth1)
  dummy*= nxclosedata(handle)
  if NOT dummy then message,"cannot read ",src,"."
  dummy = nxclosegroup(handle)
  if NOT dummy then message,"cannot close ",src,"."

  src='lowerbank'
  dummy = nxopengroup(handle,src,'NXdata')
  if NOT dummy then message,"cannot open ",src,"."
  dummy*= nxopendata(handle,'counts')
  dummy*= nxgetdata(handle,cnts2)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'theta')
  dummy*= nxgetdata(handle,tth2)
  dummy*= nxclosedata(handle)
  if NOT dummy then message,"cannot read ",src,"."
  dummy = nxclosegroup(handle)
  if NOT dummy then message,"cannot close ",src,"."

  src='merged'
  dummy = nxopengroup(handle,src,'NXdata')
  if NOT dummy then message,"cannot open ",src,"."
  dummy*= nxopendata(handle,'counts')
  dummy*= nxgetdata(handle,cnts)
  dummy*= nxclosedata(handle)
  dummy*= nxopendata(handle,'theta')
  dummy*= nxgetdata(handle,tth)
  dummy*= nxclosedata(handle)
  if NOT dummy then message,"cannot read ",src,"."
  dummy = nxclosegroup(handle)
  if NOT dummy then message,"cannot close ",src,"."

  dummy = nxclose(handle)
  if NOT dummy then message,"cannot close NEXUS-file"

  res={fname:fname, $
    tstart:tstart,tend:tend,title:title, $
    sample:sample,temp:temp[0],distFS:sampledist[0], $
    bef:bef[0],disk:disk[0],ratio:ratio[0],fermi:fermi[0],phase:phase[0], $
    mon:mon[0],pmon:pmon[0],time:time[0],preset:preset[0],countmode:countmode, $
    distFD:flightlength[0], $
    mono_dd:mono_dd[0],mono_ee:mono_ee[0],mono_ll:mono_ll[0],mono_tth:mono_tth[0], $
    tofmon:float(tofmon),tt:tt, $
    tth:tth,tth0:tth0,tth1:tth1,tth2:tth2, $
    cnts:float(cnts),cnts0:float(cnts0),cnts1:float(cnts1),cnts2:float(cnts2), $
    ee:tt*0.,k4corr:tt*0.}

*(*pState).FileInfo=res

t2e,event

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro elastic_line,x,p,y
  y = p[1]*exp(-(x-p[0])^2/p[2]^2)+p[3]+p[4]*x
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro tofmon,a,lambda=lambda,t0=t0,TOFshift=TOFshift,quiet=quiet

  if n_elements(a) EQ 0 then message,"specify 1d structure"

; elastic time from TOF monitor
  ymax=max(a.tofmon,imax)
  x0=a.tt(imax)
  p=[x0,ymax,20.0,1.0,0.001]
  w=a.tt*0.0+1.0
  yfit1=mpcurvefit(a.tt,a.tofmon,w,p,/noderivative,function_name='elastic_line',/quiet)
  tFM=p[0]

; elastic time from detector banks
  cnts=total(a.cnts,2)
  ymax=max(cnts,imax)
  x0=a.tt(imax)
  p=[x0,ymax,20.0,1.0,0.001]
  w=a.tt*0.0+1.0
  yfit2=mpcurvefit(a.tt,cnts,w,p,/noderivative,function_name='elastic_line',/quiet)
  tFD=p[0]

  c=252.78             ; FT constant
  distFM=215.7            ; distance F-M
  distMD=a.distFD-distFM       ; distance M-D
  period=60./a.fermi*1.e6/2.    ; fermi period
  tFM=tFM mod period         ; t(F-M)
  tMD=tFD-tFM             ; t(M-D)

  lambda=tMD/(c*distMD*0.001)
  tFD_calc=lambda*(c*a.distFD*0.001)
  TOFshift=tFD_calc-tFD
  t0=tFD ;uncorrected! (yes, that's o.k.) / TOF2E relative in S-D only

  if keyword_set(quiet) then return
  print,"t(FM) = ",tFM
  print,"t(FD) = ",tFD
  print,"t(MD) = ",tMD
  print,"d(MD) = ",distMD
  print,"lambda ->  ",lambda
  print,"-> t(FD)    ",tFD_calc
  print,"-> TOF shift",TOFshift
  pmulti=!p.multi
  !p.multi=[0,0,2]
  plot,a.tt,a.tofmon,title="TOF monitor",psym=4
  oplot,a.tt,yfit1,color=255
  plot,a.tt,cnts,title="detector",psym=4
  oplot,a.tt,yfit2,color=255
  !p.multi=pmulti
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro DisplayInfo,event
widget_control,event.top,get_uvalue = pState

a=*(*pState).FileInfo

  print,"filename               : ",a.fname
  print,"start time             : ",a.tstart
  print,"end time               : ",a.tend
  print,""
  print,"title                  : ",a.title
  print,"sample                 : ",a.sample
  print,"temperature (K)        : ",a.temp,format='(a,f0.2)'
  print,""
  print,"monitor (neutrons)     : ",a.mon,format='(a,i0)'
  print,"beam monitor (protons) : ",a.pmon,format='(a,e0.2)'
  print,"preset (monitor/time)  : ",long(a.preset),format='(a,i0)'
  print,"acquisition time (h)   : ",a.time/3600.,format='(a,f0.2)'
  print,"acquisition mode       : ",a.countmode
  print,""
  print,"lambda mono (AA)       : ",a.mono_ll,format='(a,f0.2,"   <---")'
  print,"energy mono (meV)      : ",a.mono_ee,format='(a,f0.2)'
  print,"twotheta mono (deg)    : ",a.mono_tth,format='(a,f0.3)'
  print,"d-value mono (AA)      : ",a.mono_dd,format='(a,f0.4,"   <---")'
  print,"beryllium filter       : ",(a.bef NE 0)?"IN":"OUT"
  print,""
  print,"fermi chopper (rpm)    : ",a.fermi,format='(a,f0.1,"   <---")'
  print,"disk chopper (rpm)     : ",a.disk,format='(a,f0.1)'
  print,"chopper ratio          : ",long(a.ratio),format='(a,i0,"   <---")'
  print,"phase D-F (deg)        : ",a.phase,format='(a,f0.1,"   <---")'
  print,"distance FC-S (mm)     : ",a.distFS,format='(a,f0.2)'
  print,"distance FC-D (mm)     : ",a.distFD,format='(a,f0.2)'
  print,""
  print,"time bins HM           : ",n_elements(a.tt),format='(a,i0)'
  print,"time delay HM (mus)    : ",long(a.tt[0]),format='(a,i0,"   <---")'
  print,"width/bin HM (mus)     : ",long(a.tt[1]-a.tt[0]),format='(a,i0,"   <---")'
  print,"detectors [all,M,U,L]  : ",[n_elements(a.tth),n_elements(a.tth0), $
    n_elements(a.tth1),n_elements(a.tth2)],format='(a,i3," /",3i4)'

  tofmon,a,lambda=lambda,TOFshift=TOFshift,/quiet
  print,""
  print,"lambda (AA) [TOF-mon]  : ",lambda,format='(a,f0.2)'
  print,"energy (meV) [TOF-mon] : ",81.81/lambda^2,format='(a,f0.2)'
  print,"TOF shift (mus) [FC]   : ",TOFshift,format='(a,f0.1)'
  print,""

str_array=strarr(35)

str_array[0]="filename               : "+strtrim(string(a.fname),2)
str_array[1]="start time             : "+strtrim(string(a.tstart),2)
str_array[2]="end time               : "+strtrim(string(a.tend),2)
str_array[3]="title                  : "+strtrim(string(a.title),2)
str_array[4]="sample                 : "+strtrim(string(a.sample),2)
str_array[5]="temperature (K)        : "+strtrim(string(a.temp),2)

widget_control,(*pState).Info_text,set_value = str_array


end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro PlotData,event,bank=bank,_Extra=extra,tth=tth,contour=contour,surface=surface,qrange=qrange, $
  log=log,max=max,energy=energy,npts=npts,dd=dd,qq=qq,qabs=qabs,symm=symm, to_window = to_window, $
  oplot=oplot
widget_control,event.top,get_uvalue = pState

widget_control,(*pState).SumDetectors, get_value = SumDetectors
if SumDetectors eq 1 then contour = 1


a=*(*pState).FileInfo

    if NOT keyword_set(to_window) then wset,(*pState).winState.winPix


  if n_elements(a) EQ 0 then message,"specify 1d structure"

  !p.subtitle=a.fname

  cnts=float(getbank1d(a,bank=bank,tth=twotheta))
  if keyword_set(log) then cnts=alog(cnts+1.)
  if n_elements(max) NE 0 then cnts=cnts<max
 ; print,"max intensity = ",max(cnts)

; intensity vs TTH
  if keyword_set(tth) then begin
    if NOT keyword_set(oplot) then begin
      plot,twotheta,total(cnts,1),title="twotheta spectrum", $
      xrange = (*pstate).xrange,yrange = (*pstate).yrange, $
        xtitle="twotheta",ytitle="intensity",_Extra=extra
    endif else oplot,twotheta,total(cnts,1),color=255
    return
  endif

; intensity vs d-value
  if keyword_set(dd) then begin
    tofmon,a,lambda=lambda,/quiet
    xx=lambda/(2.*sin(twotheta/2./!radeg))
    if NOT keyword_set(oplot) then begin
      plot,xx,total(cnts,1),title="diffraction (d-value)", $
      xrange = (*pstate).xrange,yrange = (*pstate).yrange, $
        xtitle="d (AA)",ytitle="intensity",_Extra=extra
    endif else oplot,xx,total(cnts,1),color=255
    return
  endif

; intensity vs Q-value
  if keyword_set(qq) then begin
    tofmon,a,lambda=lambda,/quiet
    xx=lambda/(2.*sin(twotheta/2./!radeg))
    xx=2*!pi/xx
    if NOT keyword_set(oplot) then begin
      plot,xx,total(cnts,1),title="diffraction (Q)", $
      xrange = (*pstate).xrange,yrange = (*pstate).yrange, $
        xtitle="Q (AA-1)",ytitle="intensity",_Extra=extra
    endif else oplot,xx,total(cnts,1),color=255
    return
  endif

  if keyword_set(energy) then begin
    t2e,a
    xx=a.ee
    dims=size(cnts,/dim)
    for i=0,dims[1]-1 do cnts[*,i]*=a.k4corr
    xtitle="energy transfer (meV)"
  endif else begin
    xx=a.tt
    xtitle="TOF (mus)"
  endelse

  if keyword_set(symm) then xrange=[-max(xx),max(xx)]

; contour plot intensity
  if keyword_set(contour) then begin
    if NOT keyword_set(energy) then begin
    ; TOF
z=cnts
if (*pState).winState.autoscale eq 1 then begin
  (*pState).winState.xrange = [min(xx),max(xx)]
  (*pState).winState.yrange = [1,n_elements(a.tth)]
endif else begin
xlo=((*pState).winState.xrange)[0]
xhi=((*pState).winState.xrange)[1]
ylo=((*pState).winState.yrange)[0]
yhi=((*pState).winState.yrange)[1]
;
diff=xx-xlo
void=min(diff,minx,/abs)
diff=xx-xhi
void=min(diff,maxx,/abs)
y=indgen(n_elements(a.tth))
diff=y-ylo
void=min(diff,miny,/abs)
diff=y-yhi
void=min(diff,maxy,/abs)

z=z[minx:maxx,miny:maxy]

endelse
widget_control, (*pState).logbutton, get_value = logbutton
if logbutton eq 1 then begin
wherelt1=where(z lt 1.0, count)
if count ne 0 then z[wherelt1] = 1.0
z=alog10(z)
endif
z=bytscl(z)


      plotimage,z,imgxrange=(*pState).winState.xrange,imgyrange=(*pState).winState.yrange, $
      xstyle = 1,ystyle = 1, $
        title="TOF spectrum",xtitle=xtitle,ytitle="twotheta",_Extra=extra,xrange=xrange

    endif else begin
    ; energy
      if n_elements(xrange) EQ 0 then xrange=[min(xx),max(xx)]
      if n_elements(npts) EQ 0 then npts=200
      xdest=makepts(xlo=xrange[0],xhi=xrange[1],npts=npts)
      xsrc=[a.ee,a.ee[n_elements(a.ee)-1]+1.]
      ysrc=cnts
      dsrc=ysrc*0.
      drebin_histo,xsrc,ysrc,dsrc,xdest,ydest,ddest
      plotimage,bytscl(ydest),imgxrange=xrange,imgyrange=[min(twotheta),max(twotheta)], $
        title="contour plot",xtitle=xtitle,ytitle="twotheta",_Extra=extra
    endelse
if NOT keyword_set(to_window) then begin
wset,(*pState).winState.winVis
device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
endif
return
  endif

; surface plot intensity
  if keyword_set(surface) then begin
    shade_surf,cnts,xx,twotheta,title="TOF spectrum",xtitle=xtitle,ytitle="twotheta", $
      _Extra=extra,xrange=xrange
    return
  endif

; q-range plot
  if (keyword_set(qrange)) OR (n_elements(qabs) NE 0) then begin
    qabs=qrange1d(a,bank=bank)
    ymax=max(qabs) & ymin=min(qabs)
    dims=size(qabs,/dim)
    for i=dims[1]-1,0,-1 do begin
      if i EQ dims[1]-1 then begin
        plot,a.ee,qabs[*,i], $
          title="Q-range",xtitle="energy transfer (meV)",ytitle="Q (AA-1)", $
      xrange = (*pstate).xrange,yrange = (*pstate).yrange, $
          _Extra=extra
      endif else oplot,a.ee,qabs[*,i]
    endfor
    qabsmean=total(qabs,2)
    oplot,a.ee,qabsmean/n_elements(twotheta),color=255,thick=5
    return
  endif

; TOF/energy plot (default)
  if NOT keyword_set(oplot) then begin
    y =   total(cnts,2)
widget_control, (*pState).logbutton, get_value = logbutton
if logbutton eq 1 then begin
wherelt1=where(y lt 1.0, count)
if count ne 0 then y[wherelt1] = 1.0
y=alog10(y)
endif

if (*pState).winState.autoscale eq 1 then begin
  xlo = min(xx) & xhi = max(xx)
  ylo = min(y) & yhi = max(y)
  (*pState).winState.xrange = [xlo,xhi]
  (*pState).winState.yrange = [ylo,yhi]
endif

    plot,xx,y,title="spectrum", $
      xrange = (*pstate).winState.xrange,yrange = (*pstate).winState.yrange, $
      xstyle = 1,ystyle = 1, $
      xtitle=xtitle,ytitle="intensity",psym=4,_Extra=extra
  endif else oplot,xx,total(cnts,2),psym=4

*(*pState).data=[[xx],[y]]

if NOT keyword_set(to_window) then begin
wset,(*pState).winState.winVis
device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
endif

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro t2e,event
widget_control,event.top,get_uvalue = pState

a=*(*pState).FileInfo


  tofmon,a,lambda=lambda,t0=t0,/quiet

  c=252.78             ; flight-constant
  l2E=81.81               ; lambda->E conversion factor
  d=(a.distFD-a.distFS)/1000.   ; distance sample-detector
  tt=a.tt
  ll=lambda+(tt-t0)/(c*d)
  kk=2.*!pi/ll & k0=2.*!pi/lambda
  a.ee=l2E/lambda^2-l2E/ll^2
  a.k4corr=(k0/kk)^4

*(*pState).FileInfo=a

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro RFF_MouseEvents,event
widget_control,event.top,get_uvalue = pState



case event.type of
0:  begin       ; button press
      (*pState).winState.mouse = event.press
      if (*pState).winState.mouse eq 4 then begin
        (*pState).winState.autoscale = 1
        wset,(*pState).winState.winPix
        PlotData,event
        wset,(*pState).winState.winVis
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
      endif
      if (*pState).winState.mouse eq 1 then begin
        (*pState).winState.xbox[0] = event.x
        (*pState).winState.ybox[0] = event.y
        wset,(*pState).winState.winVis
        device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
        empty
        (*pState).winState.autoscale = 0
        widget_control,(*pState).winState.win,/draw_motion_events
      endif
    end
1:  begin    ; button release
     if (*pState).winState.mouse eq 1 then begin
      xll = (*pState).winState.xbox[0] < (*pState).winState.xbox[1]
      yll = (*pState).winState.ybox[0] < (*pState).winState.ybox[1]
      w = abs((*pState).winState.xbox[1] - (*pState).winState.xbox[0])
      h = abs((*pState).winState.ybox[1] - (*pState).winState.ybox[0])
      xur = xll + w
      yur = yll + h
      ll = convert_coord(xll,yll,/device,/to_data)
      ur = convert_coord(xur,yur,/device,/to_data)
      (*pState).winState.xrange = [ll[0],ur[0]]
      (*pState).winState.yrange = [ll[1],ur[1]]
      wset,(*pState).winState.winPix
        PlotData,event
      wset,(*pState).winState.winVis
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
      (*pState).winState.mouse = 0B
;      widget_control,(*pState).winState.win,draw_motion_events = 0
     endif
     if (*pState).winState.mouse eq 4 then begin
      wset,(*pState).winState.winPix
         PlotData,event
      wset,(*pState).winState.winVis
      device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
      (*pState).winState.mouse = 0B
;      widget_control,(*pState).winState.win,draw_motion_events = 0
     endif
    end
2:  begin    ; mouse motion


data_coords = convert_coord(event.x,event.y,/device,/to_data)
; Now get the nearest data coordinate
xrange = (*pState).winState.xrange
yrange =  (*pState).winState.yrange
x = (xrange[1]-1) < (data_coords[0] > (xrange[0]))
void=min(((*(*pState).data)[*,0]-x),minx,/abs)
x=((*(*pState).data)[*,0])[minx]
y=((*(*pState).data)[*,1])[minx]

widget_control,(*pState).SumDetectors, get_value = SumDetectors
if SumDetectors eq 0 then begin
PlotData,event
plots,x,y,psym = 4, thick = 4.0
endif

Energy_transfer=((*(*pState).FileInfo).ee)[minx]
;print,'Energy_transfer: ',Energy_transfer

Energy_transfer=strtrim(string(Energy_transfer),2)+' meV'

widget_control, (*pState).Energy_Transfer, set_value = Energy_transfer

      if (*pState).winState.mouse eq 1 then begin
       (*pState).winState.xbox[1] = event.x
       (*pState).winState.ybox[1] = event.y
       xc = [(*pState).winState.xbox[0],event.x,event.x,$
             (*pState).winState.xbox[0],$
             (*pState).winState.xbox[0]]
       yc = [(*pState).winState.ybox[0],(*pState).winState.ybox[0],$
             event.y,event.y,$
             (*pState).winState.ybox[0]]
       wset,(*pState).winState.winVis
       device,copy = [0,0,!d.x_size,!d.y_size,0,0,(*pState).winState.winPix]
       plots,xc,yc,/device
       empty
      endif
    end
else:
endcase



end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro ColorTable,event
widget_control,event.top,get_uvalue = pstate
this_event = tag_names(event,/structure_name)
case this_event of
'WIDGET_BUTTON':  $
   xcolors,group_leader = event.top,   $
      notifyid = [event.id,event.top]
'XCOLORS_LOAD':   plotdata,event
else:
endcase

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SaveImage,event,tiff=tiff,jpeg=jpeg,gif=gif
;widget_control,event.top,get_uvalue = pState

device, decomposed = 1
image24 = tvrd(True=1)
device, decomposed = 0

if keyword_set(tiff) then begin
image24=reverse(image24,3)
ok = dialog_write_image(image24,type='tiff',/fix_type,dialog_parent=event.top)
endif

if keyword_set(gif) then ok = dialog_write_image(image24,type='gif',/fix_type,dialog_parent=event.top)
if keyword_set(jpeg) then ok = dialog_write_image(image24,type='jpeg',/fix_type,dialog_parent=event.top)


;    ok = dialog_write_image(image24, path = datDir,type='jpeg',/fix_type,dialog_parent=event.top)


end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro SavePs,event
widget_control,event.top,get_uvalue = pState
datDir = (*pState).datDir
thisDevice = !d.name
deviceKeywords = PSConfig(Cancel=canceled,directory = datDir,group_leader = event.top)
if canceled ne 1 then begin
  SET_PLOT, 'PS'
  DEVICE, _Extra = deviceKeywords
   PlotData,event,/to_window
  DEVICE, /CLOSE_FILE
  set_plot,thisDevice
endif

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro PrintImage,event
widget_control,event.top,get_uvalue = pState
datDir = (*pState).datDir
thisDevice = !d.name
  SET_PLOT, 'printer',/copy
    result = dialog_printersetup(dialog_parent = event.top)
   PlotData,event,/to_window
  DEVICE, /CLOSE
  set_plot,thisDevice

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro RFFEvents,event
widget_control,event.top,get_uvalue = pState

   CATCH, Error_status
if Error_status ne 0 then begin
catch, /cancel
    void=dialog_message(dialog_parent=event.top,/error, $
    !ERROR_STATE.MSG)
return
endif


uname=widget_info(event.id,/uname)
case uname of
'RFF_exit':    $
begin
RFF_exit,event
end
'LoadFocusFile':    $
begin
LoadFocusFile,event
DisplayInfo,event
PlotData,event
end
'RFF_MouseEvents':    $
begin
if n_elements(*(*pState).FileInfo) eq 0 then return
RFF_MouseEvents,event
end
'SumDetectors':    $
begin
PlotData,event
end
'logbutton':    $
begin
PlotData,event
end
'Color_Table':    $
begin
ColorTable,event
end
'Save_jpeg':    $
begin
SaveImage,event,/jpeg
end
'Save_tiff':    $
begin
SaveImage,event,/tiff
end
'Save_gif':    $
begin
SaveImage,event,/gif
end
'Save_ps':    $
begin
SavePs,event
end
'Print_Image':    $
begin
PrintImage,event
end
else:
endcase

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro Raw_FocusFile_Display, group_leader = group_leader,notify_ids = notify_ids,  $
        register_name = register_name,datDir = datDir

;;;;;;;added following 4 lines for non-modal widget action
if n_elements(group_leader) eq 0 then group_leader = 0L
if n_elements(notify_ids) eq 0 then notify_ids = [0L,0L]
if n_elements(register_name) eq 0 then register_name = 'Raw_FocusFile_Display'
if xregistered(register_name) then return

if n_elements(datDir) eq 0 then begin
datDir='C:'
endif


device, get_decomposed = old_dc
device,decomposed = 0
loadCT,5;,NColors=20,Bottom=1 ,/silent


tlb = widget_base(/row, group_leader = group_leader, title = 'Display Raw FOCUS Data',mbar=bar)

       filebuttons=widget_button(bar,value='File',/menu)
          void=widget_button(filebuttons,$
              value='Load FOCUS file',uname='LoadFocusFile')
          void=widget_button(filebuttons,$
              value='EXIT',uname='RFF_exit')
       colorbuttons=widget_button(bar,value='Colours',/menu)
          void=widget_button(colorbuttons,$
              value='Change Colour Table',uname='Color_Table')
       saveimagebuttons=widget_button(bar,value='Save Image',/menu)
          void=widget_button(saveimagebuttons,$
              value='Save jpeg',uname='Save_jpeg')
          void=widget_button(saveimagebuttons,$
              value='Save gif',uname='Save_gif')
          void=widget_button(saveimagebuttons,$
              value='Save tiff',uname='Save_tiff')
          void=widget_button(saveimagebuttons,$
              value='Save PS',uname='Save_ps')
       printbuttons=widget_button(bar,value='Print Image',/menu)
          void=widget_button(printbuttons,$
              value='Print',uname='Print_Image')



basel =  widget_base(tlb,/col,/base_align_center)
baser =  widget_base(tlb,/col)

Info_text=widget_text(basel,xsize = 25,ysize=25,/scroll)

Energy_Transfer=cw_field(basel,/col,title='Energy Transfer',value='',/noedit)

basela =  widget_base(basel,/row,/base_align_center)


SumDetectors_Field=['Yes','No']

SumDetectors = cw_bgroup(basela,SumDetectors_Field,/exclusive,label_top='Sum Over Detectors', $
           set_value = 0,/return_index,/no_release,/frame,uname='SumDetectors',/row)

logbuttonTypes = ['log scale']


logbutton = cw_bgroup(basela,logbuttonTypes,/col,/nonexclusive,$
           set_value = 0,/return_index,uname='logbutton')


GoldenRatio=0.5*(1.0+sqrt(5.0))

xsize = 750 & ysize =xsize/GoldenRatio

win = widget_draw(baser,xsize = xsize,ysize = ysize,/button_events,/motion_events, $
      uname = 'RFF_MouseEvents')

centertlb,tlb
widget_control,tlb,/realize

widget_control,win,get_value = winVis
window,/free,/pixmap,xsize = xsize,ysize = ysize
winPix = !d.window


; Define winState
winState={$
         win:win, $
         winVis:winVis, $
         winPix:winPix, $
         mouse:0B, $
         xbox:[0.0,0.0], $
         ybox:[0.0,0.0], $
         autoscale:1, $
         xrange:[0.0,1.0], $
         yrange:[0.0,1.0]}

state = { Info_text:Info_text, $
         Energy_Transfer:Energy_Transfer, $
         winState:winState, $
         SumDetectors:SumDetectors, $
         logbutton:logbutton, $
         old_dc:old_dc, $
         datDir:datDir, $
         FileInfo:ptr_new(/allocate_heap), $
         data:ptr_new(/allocate_heap) $
         }



pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState

xmanager,'Raw_FocusFile_Display',tlb,event_handler = 'RFFEvents',cleanup= 'RFF_cleanup'


end