; $Id: hfbs_fwsanalysis.pro,v 1.11 2007/06/19 19:36:54 azuah Exp $
;###############################################################################
;
; NAME:
;  HFBS_FWSANALYSIS
;
; PURPOSE:
;  Early version of the fixed window scan data analysis application.
;
; CATEGORY:
;  DAVE, HFBS, Fixed Window Scans, Analysis
;
; AUTHOR:
;   Robert M. Dimeo, Ph.D.
;   NIST Center for Neutron Research
;   100 Bureau Drive
;   Gaithersburg, MD 20899
;   Phone: (301) 975-8135
;   E-mail: robert.dimeo@nist.gov
;   http://www.ncnr.nist.gov/staff/dimeo
;
; 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 of if the code in this file is
;  included in another product.
;
;###############################################################################
; HFBS_FWSanalysis.pro
;
; Widget-based utility in which user can plot the elastic intensity as a
; function of time or temperature.  Also user can calculate the mean square
; displacements based on the Debye-Waller factor for a simple harmonic
; solid.  Data assumed collected in a "fixed window scan" on the HFBS.
;
; When this program is run from the DAVE environment, the DAVE workspace
; files will NOT be read in directly into the program.  User must select the
; Load DAVE option under the file menu.
;
; Written by R.M.Dimeo (3/2/2000)
;
; Modified 3/3/2000: corrected a calculation error and improved
;                    error catching methods (taking logs of negative
;                    numbers, for instance)
; Modified 3/9/2000: added ability to calculate the Debye temperature
;                    based on a linear fit to <u2> over a limited T range
; Uses InformationPanel.pro, a widget utility written by Ronn Kling
;
; Modified 3/13/2000:	-Uses the sample temperature for the temperature field
; Modified 4/6/2000:	-Different x axes can be selected for the plots in detector
; Modified 4/7/2000:	-Allows postscript output of the mean squared displacements
;                        with both PC and Linux platforms supported
;                       -Displays file name and comments in a dialog box
; Modified 7/4/2000:	-User can print out individual detector intensities
; Modified 7/12/2000:   -User can autoscale axes
;                       -User can plot derivative of the intensity as a function of
;                        time, sample temperature, or control temperature
; Modified 7/17/2000:   -Added ability to plot the ratio of the transmitted beam monitor
;                        to the fission chamber
; Modified 7/17/2000:   -Added rubberband box type zooming
; Modified 7/20/2000:   -Added color
; Modified 7/21/2000:   -Added "temperature history" plotting option
; Modified 8/3/2000:	-Improved memory management by including /no_copy keyword in the "get_uvalue"
;						 and "set_uvalue" statements.
; Modified 8/3/2000:	-Changed the calculation of the mean squared displacements so that the
;						 Debye-Waller factor is exp(-(1/3)*Q^2*<u^2>) rather than exp(-Q^2*<u^2>).
; Modified 8/26/2000:	-Enabled zoom with mouse so that user simply places cursor over the plotting
;						 window, hits the left button, and drags the mouse.  The autoscale and zoom
;						 buttons have been removed. Also the right mouse button autoscales the plot.
; Modified 8/27/2000:	-Enabled zoom capability for multiple curves on a plot.
; Modified 8/31/2000:	-Eliminated redrawing using the pixmap and device,copy abilities of IDL.
; Modified 10/22/2001:	-Began to transform code to work within DAVE.
; Modified 10/31/2001:  -Changed uvalue to be pState rather than state in order to work
;                                     properly in DAVE.
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;==========================================
pro HFBS_FWSCLEANUP,tlb
widget_control,tlb,get_uvalue = pState,/no_copy
tvlct,(*pState).rorig,(*pState).gorig,(*pState).borig
state = *pState


ptr_free,	(*pState).sigenergyPtr,$
            (*pState).bgenergyPtr,$
            (*pState).sigdataPtr,$
            (*pState).bgdataPtr,$
            (*pState).sigerrPtr,$
            (*pState).bgerrPtr,$
            (*pState).energyPtr,$
            (*pState).dataPtr,$
            (*pState).errorPtr,$
            (*pState).usqPtr,$
            (*pState).uerrPtr,$
            (*pState).xfitPtr,$
            (*pState).yfitPtr,$
            (*pState).xdatPtr,$
            (*pState).ydatPtr,$
            (*pState).ydaterrPtr,$
            (*pState).ctempPtr,$
            (*pState).stempPtr,$
            (*pState).timePtr,$
            (*pState).bgctempPtr,$
            (*pState).bgstempPtr,$
            (*pState).bgtimePtr,$
            (*pState).TBMPtr,$
            (*pState).FCPtr,$
            (*pState).WBMPtr,$
            (*pState).curxPtr,$
            (*pState).curyPtr,$
            (*pState).curyerrPtr


s = size(state.notifyIDs)
if s[0] eq 1 then count = 0 else count = s[2] - 1
for j = 0,count do begin
  pseudoEvent = {fwsEvent,$
                 ID:state.notifyIDs[0,j],$
                 top:state.notifyIDs[1,j],$
                 handler:0l}
  if widget_info(state.notifyIDs[0,j],/valid_id) then $
     widget_control,state.notifyIDs[0,j],send_event = pseudoEvent,/no_copy
endfor

wdelete,(*pState).pixId
ptr_free,pState
print,'Valid pointers after FWS_ANALYSIS: ',n_elements(ptr_valid())-1
return
end
;==========================================
PRO HFBS_FWSDone,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState
state = *pState
s = size(state.notifyIDs)
if s[0] eq 1 then count = 0 else count = s[2] - 1
for j = 0,count do begin
  pseudoEvent = {fwsEvent,$
                 ID:state.notifyIDs[0,j],$
                 top:state.notifyIDs[1,j],$
                 handler:0l}
  if widget_info(state.notifyIDs[0,j],/valid_id) then $
     widget_control,state.notifyIDs[0,j],send_event = pseudoEvent,/no_copy
endfor
widget_control,event.top,/destroy
END
;==========================================
;+
; NAME:
;       hfbs_RebinDataMSD
;
; PURPOSE:
;       Fast rebinning algorithm for one-dimensional data
;
; CATEGORY:
;       Mathematical routine
;
; CALLING SEQUENCE:
;       Result = hfbs_RebinDataMSD(xobins,nbins,yo,yoerr)
;
; INPUTS:  xobins:    original bins
;          nbins:     new number of bins
;          yo:        unbinned data
;          yoerr:     error bars for unbinned data
;
;
; KEYWORD PARAMETERS:
;       None
;
; OUTPUTS:
;       This function returns a three dimensional array consisting of the
;       bins, data, and new error bars
;
; COMMON BLOCKS:
;       None.
;
; PROCEDURE:
;
;
; SIDE EFFECTS:
;       None known
;
; EXAMPLE:
;
;
; MODIFICATION HISTORY:
;       Written by:
;       Robert Dimeo
;       robert.dimeo@nist.gov
;       November 17, 1999
;
function hfbs_RebinDataMSD,xobins,nbins,yo,yoerr
oldpts = n_elements(xobins)
newpts = nbins
if nbins ge oldpts then begin
  print,'error:  number of bins cannot exceed the number of existing channels!'
  yout = fltarr(newpts,3)
endif else begin
  binlo = xobins[0] & binhi = xobins[oldpts-1]
  dbin = (binhi-binlo)/(newpts-1)
  newbins = fltarr(newpts)
  newbins = binlo+dbin*findgen(newpts)
  yn = fltarr(newpts)
  ynerr = fltarr(newpts)
  for i = 0,newpts-1 do begin
    wherevalid = where(abs(xobins-newbins[i]) le 0.5*dbin,count)
    if count eq 0 then begin
      yn[i] = 0.0 & ynerr[i] = 0.0
    endif else begin
      yn[i] = total(yo[wherevalid])/count
      ynerr[i] = sqrt(total((yoerr[wherevalid])^2))/count
    endelse
  endfor
  yout = fltarr(newpts,3)
  yout[0:newpts-1,0] = newbins[0:nbins-1]
  yout[0:newpts-1,1] = yn[0:nbins-1]
  yout[0:newpts-1,2] = ynerr[0:nbins-1]
endelse
print,''
print,''
return,yout
end
;==========================================
pro hfbs_PlotCurrentScreenMSD,event
; This has the same content as the NewPlotZoomMSD
; and is used by the hfbs_PrintScreen2PsMSD
; procedure.


;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState

y = *state.curyPtr
ysize = size(y)

if ysize[1] eq 1 then begin
  state.autoscale = 0
  x = *state.curxPtr & y = *state.curyPtr & yerr = *state.curyerrPtr
  thiscolor = state.colors.black
  errcolors = {thiscolor:thiscolor}
  plot,x,y,psym=hfbs_selsym(state.symbolid),xrange=[state.xlo,state.xhi],yrange=[state.ylo,state.yhi],$
       xstyle=1,ystyle=1,xtitle = state.curxtitle,ytitle = state.curytitle,$
       title = state.curtitle,color = thiscolor
  hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
endif else begin
       state.autoscale = 0
       thiscolor = state.colors.black
       errcolors = {thiscolor:thiscolor}
       nchoices = ysize[1]
       x = *state.curxPtr & y = *state.curyPtr & yerr = *state.curyerrPtr
       plot,x,y[0,*],psym=hfbs_selsym(state.symbolid),yrange=[state.ylo,state.yhi],$
            ystyle=1,xtitle = state.curxtitle,xrange=[state.xlo,state.xhi],xstyle = 1,$
            ytitle = 'Intensity (arb units)',color = thiscolor
       hfbs_cerrplot,x,y[0,*]-yerr[0,*],$
               y[0,*]+yerr[0,*],errcolors = errcolors,width = 0.0
       if nchoices gt 1 then begin
         for i = 1,nchoices-1 do begin
           if i gt 7 then symbol = i-6
           if i ge 13 then symbol = i-13
           oplot,x,y[i,*],psym=symbol,color = thiscolor
           hfbs_cerrplot,x,y[i,*]-yerr[i,*],$
                   y[i,*]+yerr[i,*],errcolors = errcolors,width = 0.0
         endfor
       endif
endelse
widget_control,event.top,set_uvalue = pState,/no_copy
return
end
;==========================================
pro hfbs_AutoScaleAxesMSD,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
state.autoscale = 1
if not ptr_valid(state.curxPtr) then begin
  widget_control,state.textWid,set_value = 'No data loaded yet'
  widget_control,event.top,set_uvalue = state,/no_copy
  return
endif
y = *state.curyPtr
ysize = size(y)

if ysize[1] eq 1 then begin

  x = *state.curxPtr & y = *state.curyPtr & yerr = *state.curyerrPtr
  deltay = max(y)-min(y)
  yylo = 0.0
  yyhi = max(y)+0.1*deltay
  deltax = max(x)-min(x)
  xxlo = min(x)-0.1*deltax
  xxhi = max(x)+0.1*deltax
  thiscolor = state.symcolor
  errcolors = {thiscolor:thiscolor}
  wset,state.pixId
  plot,x,y,psym=hfbs_Selsym(state.symbolid),xrange=[xxlo,xxhi],$
       xstyle=1,xtitle = state.curxtitle,ytitle = state.curytitle,$
       title = state.curtitle,color = thiscolor;,yrange = [ylo,yhi],ystyle=1
  hfbs_cerrplot,x,y-yerr,y+yerr,errcolors = errcolors,width = 0.0
  wset,state.winval
  device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]
endif else begin
       thiscolor = state.symcolor
       errcolors = {thiscolor:thiscolor}
       nchoices = ysize[1]
       deltay = max(y)-min(y)
       yyhi = max(y)+0.1*deltay

       x = *state.curxPtr & y = *state.curyPtr & yerr = *state.curyerrPtr
         deltax = max(x)-min(x)
  		xxlo = min(x)-0.1*deltax
  		xxhi = max(x)+0.1*deltax
       wset,state.pixId
       yylo = 0.0
       plot,x,y[0,*],psym=hfbs_selsym(state.symbolid),yrange=[yylo,yyhi],$
            ystyle = 1,xtitle = state.curxtitle,xrange=[xxlo,xxhi],xstyle = 1,$
            ytitle = 'Intensity (arb units)',color = thiscolor
       hfbs_cerrplot,x,y[0,*]-yerr[0,*],$
               y[0,*]+yerr[0,*],errcolors = errcolors,width = 0.0
       if nchoices gt 1 then begin
         for i = 1,nchoices-1 do begin
           if i gt 7 then symbol = i-6
           if i ge 13 then symbol = i-13
           oplot,x,y[i,*],psym=symbol,color = thiscolor
           hfbs_cerrplot,x,y[i,*]-yerr[i,*],$
                   y[i,*]+yerr[i,*],errcolors = errcolors,width = 0.0
         endfor
       endif
       wset,state.winval
       device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]
       state.xlo = xxlo & state.xhi = xxhi & state.ylo = yylo
       state.yhi = yyhi
endelse
state.xlo = xxlo & state.xhi = xxhi & state.ylo = yylo
state.yhi = yyhi
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
return
end
;==========================================
PRO hfbs_PrintScreen2PsMSD,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
if not ptr_valid((*pState).curxPtr) then begin
  widget_control,(*pState).textWid, set_value = 'Nothing loaded yet'
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

  printPath = (*pState).printPath
  cd,printPath
  thisDevice = !d.name
  ; use one of Fanning's routines, PS_FORM.PRO, to allow
  ; user to interactively configure
  ; the postscript output
  deviceKeywords = ps_form(Cancel = canceled,parent = event.top)
  if canceled ne 1 then begin
    SET_PLOT, 'PS'
    DEVICE, _EXTRA = deviceKeywords
    widget_control,event.top,set_uvalue = pState,/no_copy
    hfbs_PlotCurrentScreenMSD,event
    widget_control,event.top,get_uvalue = pState,/no_copy
    DEVICE, /CLOSE_FILE
    set_plot,thisDevice
  endif
widget_control,event.top,set_uvalue = pState,/no_copy
return
END
;==========================================
PRO hfbs_ClearFieldsMSD,event
widget_control,event.top,get_uvalue = pState,/no_copy
free_ptr,(*pState).energyPtr
free_ptr,(*pState).bgenergyPtr
free_ptr,(*pState).sigenergyPtr
free_ptr,(*pState).dataPtr
free_ptr,(*pState).bgdataPtr
free_ptr,(*pState).sigdataPtr
free_ptr,(*pState).xdatPtr
free_ptr,(*pState).ydatPtr
free_ptr,(*pState).xfitPtr
free_ptr,(*pState).yfitPtr
free_ptr,(*pState).usqPtr
free_ptr,(*pState).uerrPtr
free_ptr,(*pState).ctempPtr
free_ptr,(*pState).stempPtr
free_ptr,(*pState).bgctempPtr
free_ptr,(*pState).bgstempPtr
free_ptr,(*pState).timePtr
(*pState).sigcomments = 'No files loaded'
(*pState).bgcomments = 'No files loaded'
widget_control,(*pState).textWid,set_value = 'Fields cleared'
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO ReadBgFileMSD,event
widget_control,event.top,get_uvalue = pState,/no_copy
cd,(*pState).file_path
bgfile = DIALOG_PICKFILE(dialog_parent = event.top,$
            title = 'Background area file',filter='*.txt')
openr,lun,bgfile,/get_lun
ndet = (*pState).ndet
a = fltarr(ndet)
for i = 0,ndet-1 do begin
  readf,lun,x
  a[i] = x
endfor
if not ptr_valid((*pState).areaPtr) then begin
  (*pState).areaPtr = ptr_new(a)
endif else begin
  *(*pState).areaPtr = a
endelse
free_lun,lun
(*pState).areas = 'true'
widget_control,(*pState).textWid,set_value = 'Background file read'
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_AboutMSD,event
disp_text = [['Written by R.M.Dimeo'],['March 2, 2000'],$
             ['NIST Center for Neutron Research'],$
             ['High Flux Backscattering Spectrometer']]
void = dialog_message(dialog_parent = event.top,$
         disp_text,/information,title = 'About FWS Analysis')
RETURN
END
;==========================================
Function ChooseDetsMSD,strdets
;
; Input: 	string containing detector numbers separated either by
;        	commas or - (hyphens).  A hyphen indicates to include the
;        	two detectors and all detectors in between.  A comma simply
;        	means to append that detector to the current list.
;
; Output:	a pointer to an array containing all of the detectors to be
;			summed together.
;
; Catch errors in input string
;nerror = strmid(strdets,0)
nerror = strmid(strdets,0,1)
if (nerror[0] eq '-') or (nerror[0] eq ',') or (nerror[0] eq ' ') then begin
  void = dialog_message('Not a valid input field',$
           dialog_parent=event.top)
  return,0
endif
strdets = strcompress(strdets)
test1 = strpos(strdets,'-,')
test2 = strpos(strdets,',-')
if test1[0] ne -1 or test2[0] ne -1 then begin
  void = dialog_message('Not a valid input field',$
           dialog_parent=event.top)
  return,0
endif

; count the number of commas occurring in the string
i = 0
inum = 0
cnt = 0
commacnt = intarr(50)
while (inum ne -1) do begin
  i = strpos(strdets,',',i)
  inum = i[0]
  if (inum ne -1) then begin
    commacnt[cnt] = inum
    cnt = cnt+1
    inum = inum + 1
    i = inum
  endif
endwhile
ncommas = cnt
if ncommas gt 0 then begin
  commaPos = intarr(ncommas)
  commaPos = commacnt[0:ncommas-1]
endif
;commaPos = [-1,commaPos[0:ncommas-1]]

; if there are no commas then there are two possibilities
; either there is a single detector present.....
ndash = strpos(strdets,'-')
if (ncommas eq 0) and (ndash[0] eq -1) then begin
  detnum = fix(strdets)
  ndets = 1
  dets = detnum
endif

; or there are a sum of detectors present
if (ncommas eq 0) and (ndash[0] ne -1) then begin
  pos = strpos(strdets,'-')
  len = strlen(strdets)
  numstr1 = strmid(strdets,0,pos[0])
  numstr2 = strmid(strdets,pos[0]+1,len[0]-1)
  num1 = fix(numstr1)
  num2 = fix(numstr2)
  ndets = num2[0] - num1[0] + 1
  dets = intarr(ndets)
  dets = num1[0] + INDGEN(ndets)
endif

; are there one or more commas?
if (ncommas gt 0) then begin
  dets = intarr(100)
  totlen=strlen(strdets)		; total length of the input string
  smallLen = intarr(ncommas+1)	; array defining the length of all substrings in string
								; variable strdets
  smallLen[0] = commaPos[0]
  for i=1,ncommas-1 do begin
      smallLen[i] = commaPos[i]-commaPos[i-1]-1
  endfor
  smallLen[ncommas] = totlen-commaPos[ncommas-1]-1

  substrings = strarr(ncommas+1)	; string array representing string form of detectors to sum
  substrings[0]=strmid(strdets,0,smallLen[0])
  for i = 1,ncommas do begin
    substrings[i]=strmid(strdets,commaPos[i-1]+1,smallLen[i])
  endfor

  ; convert substrings to an array of numbers
  count = 0
  for i = 0,ncommas do begin

    dashpresent = strpos(substrings[i],'-')
    dash = dashpresent[0]

    if dash eq -1 then begin
      detnum = fix(substrings[i])
      ndets = 1
      dets[count] = detnum[0]
      count = count+1
    endif

    if dash ne -1 then begin

      pos = strpos(substrings[i],'-')
      len = strlen(substrings[i])
      numstr1 = strmid(substrings[i],0,pos[0])
      numstr2 = strmid(substrings[i],pos[0]+1,len[0]-1)
      num1 = fix(numstr1)
      num2 = fix(numstr2)
      ndets = num2[0] - num1[0] + 1
      singledets = intarr(ndets)
      singledets = num1[0] + INDGEN(ndets)
      dets[count:count+ndets-1] = singledets[0:ndets-1]
      count = count+ndets
    endif
  endfor

ndets = count
tempdets = intarr(ndets)
tempdets[0:ndets-1] = dets[0:ndets-1]
dets = intarr(ndets)
dets[0:ndets-1] = tempdets[0:ndets-1]
endif
if not ptr_valid(newdetPtr) then begin
  newdetPtr = ptr_new(dets)
endif else begin
  *newdetPtr = dets
endelse
RETURN,newdetPtr
END
;==========================================
pro SelDirMSD,event
widget_control,event.top,get_uvalue = pState,/no_copy
cd,(*pState).file_path
if (*pState).platform eq 0 or (*pState).platform eq 1 then begin
  directory = DIALOG_PICKFILE(dialog_parent = event.top,$
                   title = 'Select Directory',/directory)
  (*pState).file_path = directory
endif else begin
  result = DIALOG_PICKFILE(dialog_parent = event.top,$
              title = 'Select file',filter = '*.hscn')
  result = strpos(sigfile,'hscn')
  lenstr = result-12
  filename = strmid(sigfile,result-12,lenstr)
  (*pState).file_path = strmid(sigfile,0,lenstr)
endelse
widget_control,event.top,set_uvalue = pState,/no_copy
return
end
;==========================================
pro HFBSLoadDaveScanFile,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
widget_control,(*pState).siggroup,get_value = whichfile

cd,(*pState).file_path
if whichfile eq 2 then begin
  void = DIALOG_MESSAGE(dialog_parent = event.top,$
           'Cannot read in a difference file')
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
end
widget_control,(*pState).scaleFactor,get_value = scaleFactorTxt
sf = float(scaleFactorTxt)

if whichfile eq 0 then begin	; read in the signal file
   ; restore DAVE signal file
  ; cd,(*(*pState).inPtr).workDir
   filename = DIALOG_PICKFILE(dialog_parent = event.top,$
                                                title = 'Select data file to restore',$
                                                /read,filter = '*.dave',$
                                                path = (*!dave_defaults).workDir);(*(*pState).inPtr).workDir)
  if filename eq '' then begin
    widget_control,event.top,set_uvalue = pState,/no_copy
    return
  endif
  restore,filename
  state = *davePtr
  ptr_free,davePtr
   instrument = (*(*state.dataStrPtr).specificPtr).instrument
   daqmode = (*(*state.dataStrPtr).specificPtr).daqmode
   if (instrument ne 'HFBS') or (strupcase(daqmode) ne 'ELASTIC') then begin
     void = dialog_message(dialog_parent = event.top,'Not a valid data file')
     widget_control,event.top,set_uvalue = pState,/no_copy
     return
   endif

	workDir = (*!dave_defaults).workDir
	datDir = (*!dave_defaults).datDir

   (*pState).sigfile = filename


   (*pState).sigcomments = (*(*state.dataStrPtr).specificPtr).comments[0]
   TBM = *(*(*state.dataStrPtr).specificPtr).TBMPtr
   WBM = *(*(*state.dataStrPtr).specificPtr).WBMPtr
   FC = *(*(*state.dataStrPtr).specificPtr).FCPtr
   ctemp = (*(*state.dataStrPtr).specificPtr).temp_control
   stemp = (*(*state.dataStrPtr).specificPtr).temp_sample
   time = *(*(*state.dataStrPtr).specificPtr).timePtr
   q = (*(*state.dataStrPtr).commonStr.histPtr).y
   energy = (*(*state.dataStrPtr).commonStr.histPtr).x
   sigenergy = energy
   sigdata = (*(*state.dataStrPtr).commonStr.histPtr).qty
   sigerror = (*(*state.dataStrPtr).commonStr.histPtr).err

   mon = *(*(*state.dataStrPtr).specificPtr).monPtr
   monErr = *(*(*state.dataStrPtr).specificPtr).monErrPtr
; Now reform the arrays		(added 11/29/01)
  data = transpose(sigdata)
  dataSize = size(data)
  error = transpose(sigerror)
  ndet = dataSize[1] + 1
  nchan = dataSize[2]
  newData = fltarr(ndet,nchan)
  newError = fltarr(ndet,nchan)
  newData[0,0:nchan-1] = mon[0:nchan-1]
  newError[0,0:nchan-1] = monErr[0:nchan-1]
  newData[1:ndet-1,0:nchan-1] = data[0:ndet-2,0:nchan-1]
  newError[1:ndet-1,0:nchan-1] = error[0:ndet-2,0:nchan-1]
  sigdata = newData
  sigerror = newError

   *(*pState).timePtr = time
   *(*pState).ctempPtr = ctemp
   *(*pState).stempPtr = stemp
   *(*pState).WBMPtr = WBM
   *(*pState).TBMPtr = TBM
   *(*pState).FCPtr = FC
   *(*pState).sigenergyPtr = ctemp
   *(*pState).sigdataPtr = sigdata
   *(*pState).sigerrPtr = sigerror
   sigresult = size(sigdata)
   sigdets = sigresult[1]
   sigchan = sigresult[2]
   (*pState).nchan = sigchan & nchan = sigchan
   *(*pState).dataPtr = sigData
   *(*pState).energyPtr = sigenergy
   *(*pState).errorPtr = sigerror
endif else begin	; read in the background file
   ; restore DAVE background file
   cd,(*!dave_defaults).workDir;(*(*pState).inPtr).workDir
   filename = DIALOG_PICKFILE(dialog_parent = event.top,$
                                                title = 'Select background file to restore',$
                                                /read,filter = '*.dave')
  if filename eq '' then begin
    widget_control,event.top,set_uvalue = pState,/no_copy
    return
  endif
  restore,filename,/verbose
  state = *davePtr
  ptr_free,davePtr
  *(*pState).inPtr = state
   (*pState).bgfile = filename
   instrument = (*(*state.dataStrPtr).specificPtr).instrument
   daqmode = (*(*state.dataStrPtr).specificPtr).daqmode
   if (instrument ne 'HFBS') or (daqmode ne 'elastic') then begin
     widget_control,event.top,set_uvalue = pState,/no_copy
     return
   endif
   (*pState).bgcomments = (*(*(*(*pState).inPtr).dataStrPtr).specificPtr).comments[0]
   TBM = *(*(*state.dataStrPtr).specificPtr).TBMPtr
   WBM = *(*(*state.dataStrPtr).specificPtr).WBMPtr
   FC = *(*(*state.dataStrPtr).specificPtr).FCPtr
   bgctemp = (*(*state.dataStrPtr).specificPtr).temp_control
   bgstemp = (*(*state.dataStrPtr).specificPtr).temp_sample
   time = *(*(*state.dataStrPtr).specificPtr).timePtr
   energy = (*(*state.dataStrPtr).commonStr.histPtr).x
   bgdata = (*(*(*(*pState).inPtr).dataStrPtr).commonStr.histPtr).qty
   bgerror = (*(*state.dataStrPtr).commonStr.histPtr).err


   bgmon = *(*(*state.dataStrPtr).specificPtr).monPtr
   bgmonErr = *(*(*state.dataStrPtr).specificPtr).monErrPtr
; Now reform the arrays		(added 11/29/01)
  bgdata = transpose(bgdata)
  bgdataSize = size(bgdata)
  bgerror = transpose(bgerror)
  ndet = bgdataSize[1] + 1
  nchan = bgdataSize[2]
  newbgData = fltarr(ndet,nchan)
  newbgError = fltarr(ndet,nchan)
  newbgData[0,0:nchan-1] = bgmon[0:nchan-1]
  newbgError[0,0:nchan-1] = bgmonErr[0:nchan-1]
  newbgData[1:ndet-1,0:nchan-1] = bgdata[0:ndet-2,0:nchan-1]
  newbgError[1:ndet-1,0:nchan-1] = bgerror[0:ndet-2,0:nchan-1]
  bgdata = newbgData
  bgerror = newbgError




;;;;start here;;;;
   widget_control,(*pState).xgroup,get_value = xselect
   *(*pState).bgtimePtr = bgtime
   *(*pState).bgctempPtr = bgctemp
   *(*pState).bgstempPtr = bgstemp

   case xselect of
   1: begin
        *(*pState).bgenergyPtr = bgstemp
        bgenergy = fltarr(n_elements(bgstemp)) & bgenergy = bgstemp
        sigenergy = *(*pState).stempPtr
      end
   2: begin
        *(*pState).bgenergyPtr = bgctemp
        bgenergy = fltarr(n_elements(bgctemp)) & bgenergy = bgctemp
        sigenergy = *(*pState).ctempPtr
      end
   0: begin
      widget_control,(*pState).textWid,set_value = 'Cannot subtract in time!'
      widget_control,event.top,set_uvalue = pState,/no_copy
      return
      end
   endcase
   *(*pState).bgdataPtr = bgdata
   *(*pState).bgerrPtr = bgerror
   ; calculate the difference fields if the signal file is present
   if n_elements(*(*pState).sigdataPtr) lt 2 then begin
     widget_control,(*pState).textWid,set_value='No signal field yet'
     widget_control,event.top,set_uvalue = pState,/no_copy
     return
   endif

   sigdata = *(*pState).sigdataPtr
   sigerr = *(*pState).sigerrPtr
   sigresult = size(sigdata)
   sigdets = sigresult[1]
   sigchan = sigresult[2]
   (*pState).nchan = sigchan
   bgenergy = *(*pState).bgenergyPtr
   bgdata = *(*pState).bgdataPtr
   bgerr = *(*pState).bgerrPtr
   bgresult = size(bgdata)
   bgdets = bgresult[1]
   bgchan = bgresult[2]
   newbg = fltarr(sigdets,sigchan)
   newbgerr = fltarr(sigdets,sigchan)
   energy = fltarr(sigchan)
   energy = sigenergy
   data = fltarr(sigdets,sigchan)
   error = fltarr(sigdets,sigchan)
 ; calculate the background counts interpolated to the signal grid
   for i = 0,sigdets-1 do begin
     newbg[i,0:sigchan-1] = interpol(bgdata[i,0:bgchan-1],bgenergy[0:bgchan-1],$
                            energy[0:sigchan-1])
     newbgerr[i,0:sigchan-1] = interpol(bgerr[i,0:bgchan-1],$
                            bgenergy[0:bgchan-1],energy[0:sigchan-1])
   endfor
 ; normalize bg counts to the monitor and subtract
   for i = 1,sigdets-1 do begin
     ratio = fltarr(sigchan) & ratio = sigdata[0,0:sigchan-1]/newbg[0,0:sigchan-1]
     newbg[i,0:sigchan-1] = newbg[i,0:sigchan-1]*ratio
     newbgerr[i,0:sigchan-1] = newbgerr[i,0:sigchan-1]*ratio
     data[i,0:sigchan-1] = sigdata[i,0:sigchan-1] - sf[0]*newbg[i,0:sigchan-1]
     error[i,0:sigchan-1] = sqrt(sf^2*newbgerr[i,0:sigchan-1]^2+sigerr[i,0:sigchan-1]^2)
   endfor
   *(*pState).dataPtr = data
   *(*pState).energyPtr = energy
   *(*pState).errorPtr = error
endelse

widget_control,(*pState).int_slider,set_slider_max = (*pState).nchan-1
widget_control,(*pState).textWid,set_value = 'Data successfully read!'

; When we read in a DAVE file we are also reading in the working
; directory and data directory of the system on which it was created.
; If different from the machine user is currently using then we must
; catch this error and have user select an appropriate directory.
;
;yout = hfbs_dirValid((*(*pState).inPtr).datDir)
;if yout eq 0 then begin
;  strout = ['Data directory is invalid on this system','Please select another']
;  void = dialog_message(dialog_parent = event.top,strout,/error)
;  directory = DIALOG_PICKFILE(title = 'Select data directory',/directory)
;  (*(*pState).inPtr).datDir = directory
;endif

;yout = hfbs_dirValid((*(*pState).inPtr).workDir)
;if yout eq 0 then begin
;  strout = ['Working directory is invalid on this system','Please select another']
;  void = dialog_message(dialog_parent = event.top,strout,/error)
;  directory = DIALOG_PICKFILE(title = 'Select data directory',/directory)
;  (*(*pState).inPtr).workDir = directory
;endif

widget_control,event.top,set_uvalue = pState,/no_copy
return
end
;==========================================
PRO hfbs_PlotDataMSD,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
widget_control,(*pState).PlotSelDetField,get_value = strdets
widget_control,(*pState).siggroup,get_value = whichfile
widget_control,(*pState).xgroup,get_value = xselect

indexPtr = ChooseDetsMSD(strdets)
index = *indexPtr
nchoices = n_elements(index)
case whichfile of
0: begin	; signal file
     if not ptr_valid((*pState).sigdataPtr) then begin
       widget_control,(*pState).textWid,set_value = 'No data in the signal field'
       widget_control,event.top,set_uvalue = pState,/no_copy
       return
     endif else begin
      case xselect of
      0:  begin
          sigenergy = *(*pState).timePtr
          xlab = 'time (min)'
          end
      1:  begin
          sigenergy = *(*pState).stempPtr
          xlab = 'T (K): sample '
          end
      2:  begin
          sigenergy = *(*pState).ctempPtr
          xlab = 'T (K): control '
          end
      endcase
       ;sigenergy = *state.sigenergyPtr
       sigdata = *(*pState).sigdataPtr
       sigerr = *(*pState).sigerrPtr
       maxy = max(sigdata[index[0:nchoices-1],*])
       thiscolor = (*pState).symcolor
       errcolors = {thiscolor:thiscolor}

       datsize = size(sigdata)
       nchan = datsize[2]
       x = fltarr(nchan)
       y = fltarr(nchoices,nchan)
       yerr = fltarr(nchoices,nchan)
       x = sigenergy
       y[0:nchoices-1,0:nchan-1] = sigdata[index[0:nchoices-1],0:nchan-1]
       yerr[0:nchoices-1,0:nchan-1] = sigerr[index[0:nchoices-1],0:nchan-1]
     endelse
   end
1: begin	; background file
     if not ptr_valid((*pState).bgenergyPtr) then begin
       widget_control,(*pState).textWid,set_value = 'No data in the background field'
       widget_control,event.top,set_uvalue = pState,/no_copy
       return
     endif else begin
      case xselect of
      0:  begin
          bgenergy = *(*pState).bgtimePtr
          xlab = 'time (min)'
          end
      1:  begin
          bgenergy = *(*pState).bgstempPtr
          xlab = 'T (K): sample '
          end
      2:  begin
          bgenergy = *(*pState).bgctempPtr
          xlab = 'T (K): control '
          end
      endcase

       bgenergy = *(*pState).bgenergyPtr
       bgdata = *(*pState).bgdataPtr
       bgerr = *(*pState).bgerrPtr
       maxy = max(bgdata[index[0:nchoices-1],*])
       thiscolor = (*pState).symcolor
       errcolors = {thiscolor:thiscolor}

       datsize = size(bgdata)
       nchan = datsize[2]
       x = fltarr(nchan)
       y = fltarr(nchoices,nchan)
       yerr = fltarr(nchoices,nchan)
       x = bgenergy
       y[0:nchoices-1,0:nchan-1] = bgdata[index[0:nchoices-1],0:nchan-1]
       yerr[0:nchoices-1,0:nchan-1] = bgerr[index[0:nchoices-1],0:nchan-1]
     endelse
   end
2: begin
     if not ptr_valid((*pState).energyPtr) then begin
       widget_control,(*pState).textWid,set_value = 'No data in the difference field'
       widget_control,event.top,set_uvalue = pState,/no_copy
       return
     endif else begin

      case xselect of
      0:  begin
          bgenergy = *(*pState).bgtimePtr
          xlab = 'time (min)'
          end
      1:  begin
          bgenergy = *(*pState).bgstempPtr
          xlab = 'T (K): sample '
          end
      2:  begin
          bgenergy = *(*pState).bgctempPtr
          xlab = 'T (K): control '
          end
      endcase
       energy = *(*pState).energyPtr
       data = *(*pState).dataPtr
       err = *(*pState).errorPtr
       maxy = max(data[index[0:nchoices-1],*])
       thiscolor = (*pState).symcolor
       errcolors = {thiscolor:thiscolor}

       datsize = size(data)
       nchan = datsize[2]
       x = fltarr(nchan)
       y = fltarr(nchoices,nchan)
       yerr = fltarr(nchoices,nchan)
       x = energy
       y[0:nchoices-1,0:nchan-1] = data[index[0:nchoices-1],0:nchan-1]
       yerr[0:nchoices-1,0:nchan-1] = err[index[0:nchoices-1],0:nchan-1]
     endelse
   end
endcase

wset,(*pState).winval
  if (*pState).autoscale eq 1 then begin
    (*pState).xlo = min(x) & (*pState).xhi = max(x)
    (*pState).ylo = min(y) & (*pState).yhi = 1.2*max(y)
  endif else begin

  endelse
       plot,x,y[0,*],psym=hfbs_selsym((*pState).symbolid),yrange=[(*pState).ylo,(*pState).yhi],$
            ystyle=1,xtitle = xlab,xrange=[(*pState).xlo,(*pState).xhi],xstyle=1,$
            ytitle = 'Intensity (arb units)',color = thiscolor
       hfbs_cerrplot,x,y[0,*]-yerr[0,*],$
               y[0,*]+yerr[0,*],errcolors = errcolors,width = 0.0
       if nchoices gt 1 then begin
         for i = 1,nchoices-1 do begin
           if i gt 7 then symbol = i-6
           if i ge 13 then symbol = i-13
           oplot,x,y[i,*],psym=symbol,color = thiscolor
           hfbs_cerrplot,x,y[i,*]-yerr[i,*],$
                   y[i,*]+yerr[i,*],errcolors = errcolors,width = 0.0
         endfor
       endif


wset,(*pState).pixId

       plot,x,y[0,*],psym=hfbs_selsym((*pState).symbolid),yrange=[(*pState).ylo,(*pState).yhi],$
            ystyle=1,xtitle = xlab,xrange=[(*pState).xlo,(*pState).xhi],xstyle=1,$
            ytitle = 'Intensity (arb units)',color = thiscolor
       hfbs_cerrplot,x,y[0,*]-yerr[0,*],$
               y[0,*]+yerr[0,*],errcolors = errcolors,width = 0.0
       if nchoices gt 1 then begin
         for i = 1,nchoices-1 do begin
           if i gt 7 then symbol = i-6
           if i ge 13 then symbol = i-13
           oplot,x,y[i,*],psym=symbol,color = thiscolor
           hfbs_cerrplot,x,y[i,*]-yerr[i,*],$
                   y[i,*]+yerr[i,*],errcolors = errcolors,width = 0.0
         endfor
       endif

*(*pState).curxPtr = x
*(*pState).curyPtr = y
*(*pState).curyerrPtr = yerr
(*pState).curtitle = 'Summed Detectors' & (*pState).curytitle = 'Intensity (arb units)'
(*pState).curxtitle = xlab

widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_PlotFitsMSD,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
if not ptr_valid((*pState).xfitPtr) then begin
  widget_control,(*pState).textWid,set_value = 'Displacements not calculated yet'
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
ndet = (*pState).ndet
xfit = *(*pState).xfitPtr & yfit = *(*pState).yfitPtr
xdat = *(*pState).xdatPtr & ydat = *(*pState).ydatPtr & ydaterr = *(*pState).ydaterrPtr
widget_control,(*pState).fit_slider,get_value = channel
x1 = fltarr(ndet) & y1 = fltarr(ndet) & y1err = fltarr(ndet)
x1[0:ndet-1] = xdat[0:ndet-1,channel]
y1[0:ndet-1] = ydat[0:ndet-1,channel]
y1err[0:ndet-1] = ydaterr[0:ndet-1,channel]
temp = *(*pState).energyPtr
temperature = temp[channel]
xf = fltarr(ndet) & yf = fltarr(ndet)
xf[0:ndet-1] = xfit[0:ndet-1,channel]
yf[0:ndet-1] = yfit[0:ndet-1,channel]
ymin = min(-ydat[*,*]) & ymax = max(-ydat[*,*])
thiscolor = (*pState).symcolor

wset,(*pState).pixId
errcolors = {thiscolor:thiscolor}
plot,x1,-y1,psym=hfbs_selsym((*pState).symbolid),xtitle = 'Q!u2!n',ytitle = 'Log(I(Q,T)/I(Q,T=0)',$
     yrange=[ymin,ymax],ystyle=1,color = thiscolor
hfbs_cerrplot,width = 0.0,x1,-y1-y1err,-y1+y1err,errcolors = errcolors
oplot,xf,-yf,psym=0,color = thiscolor
wset,(*pState).winval
device,copy = [0,0,(*pState).xsize,(*pState).ysize,0,0,(*pState).pixId]

widget_control,(*pState).textWid,set_value = 'T = '+string(temperature)
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PRO HFBS_PrintFits2PSMSD,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
if not ptr_valid((*pState).xfitPtr) then begin
  widget_control,(*pState).textWid,set_value = 'Displacements not calculated yet'
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
ndet = (*pState).ndet
xfit = *(*pState).xfitPtr & yfit = *(*pState).yfitPtr
xdat = *(*pState).xdatPtr & ydat = *(*pState).ydatPtr & ydaterr = *(*pState).ydaterrPtr
widget_control,(*pState).fit_slider,get_value = channel
x1 = fltarr(ndet) & y1 = fltarr(ndet) & y1err = fltarr(ndet)
x1[0:ndet-1] = xdat[0:ndet-1,channel]
y1[0:ndet-1] = ydat[0:ndet-1,channel]
y1err[0:ndet-1] = ydaterr[0:ndet-1,channel]
temp = *(*pState).energyPtr
temperature = temp[channel]
xf = fltarr(ndet) & yf = fltarr(ndet)
xf[0:ndet-1] = xfit[0:ndet-1,channel]
yf[0:ndet-1] = yfit[0:ndet-1,channel]
ymin = min(-ydat[*,*]) & ymax = max(-ydat[*,*])

  printPath = (*pState).printPath
  cd,printPath
  thisDevice = !d.name

  deviceKeywords = ps_form(Cancel = canceled,parent = event.top)
  if canceled ne 1 then begin
    SET_PLOT, 'PS'
    DEVICE, _EXTRA = deviceKeywords
    plot,x1,-y1,psym=hfbs_selsym((*pState).symbolid),$
         xtitle = 'Q!u2!n',ytitle = 'Log(I(Q,T)/I(Q,T=0)',$
         yrange=[ymin,ymax],ystyle=1
    errplot,x1,-y1-y1err,-y1+y1err
    oplot,xf,-yf,psym=0
    DEVICE, /CLOSE_FILE
    set_plot,thisDevice
  endif

widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_SaveFitMSD,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
if not ptr_valid((*pState).xfitPtr) then begin
  widget_control,(*pState).textWid,set_value = 'Displacements not calculated yet'
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
ndet = (*pState).ndet
xfit = *(*pState).xfitPtr & yfit = *(*pState).yfitPtr
xdat = *(*pState).xdatPtr & ydat = *(*pState).ydatPtr & ydaterr = *(*pState).ydaterrPtr
widget_control,(*pState).fit_slider,get_value = channel
x1 = fltarr(ndet) & y1 = fltarr(ndet) & y1err = fltarr(ndet)
x1[0:ndet-1] = xdat[0:ndet-1,channel]
y1[0:ndet-1] = ydat[0:ndet-1,channel]
y1err[0:ndet-1] = ydaterr[0:ndet-1,channel]

xf = fltarr(ndet) & yf = fltarr(ndet)
xf[0:ndet-1] = xfit[0:ndet-1,channel]
yf[0:ndet-1] = yfit[0:ndet-1,channel]

cd,(*pState).file_path
file = DIALOG_PICKFILE(dialog_parent = event.top,$
         title = 'Name of fit file',filter='*.out')
file = file+'.out'
openw,lun,file,/get_lun
for i = 0,ndet-1 do begin
  printf,lun,x1[i],-y1[i],y1err[i],xf[i],-yf[i],format = '(5f15.6)'
endfor
free_lun,lun

widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_SaveAllFitsMSD,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
if not ptr_valid((*pState).xfitPtr) then begin
  widget_control,(*pState).textWid,set_value = 'Displacements not calculated yet'
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
nchan = (*pState).nchan-1
ndet = (*pState).ndet
xfit = *(*pState).xfitPtr & yfit = *(*pState).yfitPtr
xdat = *(*pState).xdatPtr & ydat = *(*pState).ydatPtr & ydaterr = *(*pState).ydaterrPtr
energy = *(*pState).energyPtr

cd,(*pState).file_path
file = DIALOG_PICKFILE(dialog_parent = event.top,$
         title = 'Name of fit file',filter='*.out')
file = file+'.out'
openw,lun,file,/get_lun
for j = 0,nchan-1 do begin
  x1 = fltarr(ndet) & y1 = fltarr(ndet) & y1err = fltarr(ndet)
  x1[0:ndet-1] = xdat[0:ndet-1,j]
  y1[0:ndet-1] = ydat[0:ndet-1,j]
  y1err[0:ndet-1] = ydaterr[0:ndet-1,j]

  xf = fltarr(ndet) & yf = fltarr(ndet)
  xf[0:ndet-1] = xfit[0:ndet-1,j]
  yf[0:ndet-1] = yfit[0:ndet-1,j]
  printf,lun,'Temperature: '+string(energy[j])
  printf,lun,'Q^2    Log(I(Q,T)/I(Q,T=0))    error    Fit'
  for i = 0,ndet-1 do begin
    printf,lun,x1[i],-y1[i],y1err[i],-yf[i],format = '(4f15.6)'
  endfor
  printf,lun,''
endfor
free_lun,lun

widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
pro hfbs_zoomMSD,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
if not ptr_valid((*pState).curxPtr) then begin
  widget_control,(*pState).textWid,set_value = 'No data loaded'
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

y = *(*pState).curyPtr
ysize = size(y)

if ysize[1] eq 1 then begin
  (*pState).autoscale = 0
  x = *(*pState).curxPtr & y = *(*pState).curyPtr & yerr = *(*pState).curyerrPtr
  thiscolor = (*pState).symcolor
  errcolors = {thiscolor:thiscolor}
  wset,(*pState).pixId
  plot,x,y,psym=hfbs_selsym((*pState).symbolid),$
       xrange=[(*pState).xlo,(*pState).xhi],yrange=[(*pState).ylo,(*pState).yhi],$
       xstyle=1,ystyle=1,xtitle = (*pState).curxtitle,ytitle = (*pState).curytitle,$
       title = (*pState).curtitle,color = thiscolor
  hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
  wset,(*pState).winval
  device,copy = [0,0,(*pState).xsize,(*pState).ysize,0,0,(*pState).pixId]
endif else begin
       (*pState).autoscale = 0
       thiscolor = (*pState).symcolor
       errcolors = {thiscolor:thiscolor}
       nchoices = ysize[1]
       x = *(*pState).curxPtr & y = *(*pState).curyPtr & yerr = *(*pState).curyerrPtr
       wset,(*pState).pixId
       plot,x,y[0,*],psym=hfbs_selsym((*pState).symbolid),yrange=[(*pState).ylo,(*pState).yhi],$
            ystyle=1,xtitle = (*pState).curxtitle,xrange=[(*pState).xlo,(*pState).xhi],xstyle = 1,$
            ytitle = 'Intensity (arb units)',color = thiscolor
       hfbs_cerrplot,x,y[0,*]-yerr[0,*],$
               y[0,*]+yerr[0,*],errcolors = errcolors,width = 0.0
       if nchoices gt 1 then begin
         for i = 1,nchoices-1 do begin
           if i gt 7 then symbol = i-6
           if i ge 13 then symbol = i-13
           oplot,x,y[i,*],psym=symbol,color = thiscolor
           hfbs_cerrplot,x,y[i,*]-yerr[i,*],$
                   y[i,*]+yerr[i,*],errcolors = errcolors,width = 0.0
         endfor
       endif
       wset,(*pState).winval
       device,copy = [0,0,(*pState).xsize,(*pState).ysize,0,0,(*pState).pixId]
endelse
widget_control,event.top,set_uvalue = pState,/no_copy
return
end
;==========================================
pro hfbs_WritePlotMSD,event
widget_control,event.top,get_uvalue = pState,/no_copy
if not ptr_valid((*pState).curxPtr) then begin
  widget_control,(*pState).textWid,set_value = 'No data loaded'
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
state = *pState
x = *state.curxPtr & y = *state.curyPtr & yerr = *state.curyerrPtr
npts = n_elements(x)
file = dialog_pickfile(/write,filter = '*.txt')
if file eq '' then begin
  widget_control,state.textWid,set_value = 'No data file selected'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
file = file+'.txt'
openw,lun,file,/get_lun
for i = 0,npts-1 do begin
  printf,lun,x[i],y[i],yerr[i]
endfor
free_lun,lun
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
return
end
;==========================================
PRO hfbs_PlotDetsMSD,event
; Plots the individual detectors based on the slider position


;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState

widget_control,state.siggroup,get_value = whichfile
widget_control,state.xgroup,get_value = xselect
widget_control,state.plot_slider,get_value = detector

thiscolor = state.symcolor
errcolors = {thiscolor:thiscolor}

case whichfile of
0:  begin	; signal field
      if not ptr_valid(state.sigenergyPtr) then begin
        widget_control,state.textWid,set_value = 'Signal field empty'
        *pState = state
        widget_control,event.top,set_uvalue = pState,/no_copy
        return
      endif
      case xselect of
      0:  begin
          sigenergy = *state.timePtr
          xlab = 'time (min)'
          end
      1:  begin
          sigenergy = *state.stempPtr
          xlab = 'T (K): sample '
          end
      2:  begin
          sigenergy = *state.ctempPtr
          xlab = 'T (K): control '
          end
      endcase
      ;sigenergy = *state.sigenergyPtr
      sigdata = *state.sigdataPtr
      sigerror = *state.sigerrPtr
      sigresult = size(sigdata)
      sigdets = sigresult[1]
      sigchan = sigresult[2]
      x = fltarr(sigchan) & x = sigenergy
      y = fltarr(sigchan) & yerr = fltarr(sigchan)
      y = sigdata[detector,0:sigchan-1]
      yerr = sigerror[detector,0:sigchan-1]
    end
1:  begin	; background field
      if not ptr_valid(state.bgdataPtr) then begin
        widget_control,state.textWid,set_value = 'Background field empty'
        *pState = state
        widget_control,event.top,set_uvalue = pState,/no_copy
        return
      endif
      case xselect of
      0:  begin
          bgenergy = *state.bgtimePtr
          xlab = 'time (min)'
          end
      1:  begin
          bgenergy = *state.bgstempPtr
          xlab = 'T (K): sample '
          end
      2:  begin
          bgenergy = *state.bgctempPtr
          xlab = 'T (K): control '
          end
      endcase

      ;bgenergy = *state.bgenergyPtr
      bgdata = *state.bgdataPtr
      bgerror = *state.bgerrPtr
      bgresult = size(bgdata)
      bgdets = bgresult[1]
      bgchan = bgresult[2]
      x = fltarr(bgchan) & x = bgenergy
      y = fltarr(bgchan) & yerr = fltarr(bgchan)
      y = bgdata[detector,0:bgchan-1]
      yerr = bgerror[detector,0:bgchan-1]
    end
2:  begin	; difference field
      if not ptr_valid(state.energyPtr) then begin
        widget_control,state.textWid,set_value = 'Difference field empty'
        *pState = state
        widget_control,event.top,set_uvalue = pState,/no_copy
        return
      endif
      case xselect of
      0:  begin
          energy = *state.timePtr
          xlab = 'time (min)'
          end
      1:  begin
          energy = *state.stempPtr
          xlab = 'T (K): sample '
          end
      2:  begin
          energy = *state.ctempPtr
          xlab = 'T (K): control '
          end
      endcase
      ;energy = *state.energyPtr
      data = *state.dataPtr
      error = *state.errorPtr
      result = size(data)
      ndets = result[1]
      nchan = result[2]
      x = fltarr(nchan) & x = energy
      y = fltarr(nchan) & yerr = fltarr(nchan)
      y = data[detector,0:nchan-1]
      yerr = error[detector,0:nchan-1]
    end
endcase


wset,state.pixId
      if state.autoscale eq 1 then begin
        plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = xlab,ytitle = 'Intensity (arb units)',$
             xrange=[min(x),max(x)],xstyle=1,color = thiscolor
        hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
      endif else begin
        plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = xlab,ytitle = 'Intensity (arb units)',$
             xrange=[state.xlo,state.xhi],xstyle=1,yrange=[state.ylo,state.yhi],ystyle=1,$
             color = thiscolor
        hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
      endelse
wset,state.winval
device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]

output = strcompress('Q ='+string(state.q[detector-1])+$
               '  Det: '+string(detector))
widget_control,state.textWid,set_value = output

*state.curxPtr = x
*state.curyPtr = y
*state.curyerrPtr = yerr
state.curxtitle = xlab
state.curytitle = 'Intensity (arb units)'
state.curtitle = ''
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_PlotRatioMSD,event
; Plots the ratio of transmitted beam monitor to the fission chamber


;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
widget_control,state.xgroup,get_value = xselect

if not ptr_valid(state.sigenergyPtr) then begin
  widget_control,state.textWid,set_value = 'No data loaded'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
case xselect of
  0:  begin
      sigenergy = *state.timePtr
      xlab = 'time (min)'
      end
  1:  begin
      sigenergy = *state.stempPtr
      xlab = 'T (K): sample '
      end
  2:  begin
      sigenergy = *state.ctempPtr
      xlab = 'T (K): control '
      end
endcase
nchan = n_elements(sigenergy)
x = fltarr(nchan) & x = sigenergy
a = fltarr(nchan) & a = *state.TBMPtr
aerr = fltarr(nchan) & aerr = sqrt(a)
b = fltarr(nchan) & b = *state.FCPtr
berr = fltarr(nchan) & berr = sqrt(b)
y = fltarr(nchan) & y = a/b
yerr = fltarr(nchan) & yerr = sqrt((aerr/b)^2+(berr*a/(b)^2)^2)

thiscolor = state.symcolor
errcolors = {thiscolor:thiscolor}

wset,state.pixId
if state.autoscale eq 1 then begin
   plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = xlab,ytitle = 'Ratio',title = 'TBM/IBM',$
        xrange=[min(x),max(x)],xstyle=1,color = thiscolor
   hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
endif else begin
   plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = xlab,ytitle = 'Ratio',title = 'TBM/IBM',$
        xrange=[state.xlo,state.xhi],xstyle=1,yrange=[state.ylo,state.yhi],ystyle=1,$
        color = thiscolor
   hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
endelse
wset,state.winval
device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]


*state.curxPtr = x
*state.curyPtr = y
*state.curyerrPtr = yerr
state.curxtitle = xlab
state.curytitle = 'Ratio'
state.curtitle = 'TBM/IBM'
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_PlotTBMMSD,event
; Plots the ratio of transmitted beam monitor to the fission chamber


;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
widget_control,state.xgroup,get_value = xselect

if not ptr_valid(state.sigenergyPtr) then begin
  widget_control,state.textWid,set_value = 'No data loaded'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
case xselect of
  0:  begin
      sigenergy = *state.timePtr
      xlab = 'time (min)'
      end
  1:  begin
      sigenergy = *state.stempPtr
      xlab = 'T (K): sample '
      end
  2:  begin
      sigenergy = *state.ctempPtr
      xlab = 'T (K): control '
      end
endcase
nchan = n_elements(sigenergy)
x = fltarr(nchan) & x = sigenergy
y = fltarr(nchan) & y = *state.TBMPtr
yerr = fltarr(nchan) & yerr = sqrt(y)

thiscolor = state.symcolor
errcolors = {thiscolor:thiscolor}
wset,state.pixId
if state.autoscale eq 1 then begin
   plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = xlab,ytitle = 'Transmitted Beam Monitor',title = 'TBM',$
        xrange=[min(x),max(x)],xstyle=1,color = thiscolor
   hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
endif else begin
   plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = xlab,ytitle = 'Transmitted Beam Monitor',title = 'TBM',$
        xrange=[state.xlo,state.xhi],xstyle=1,yrange=[state.ylo,state.yhi],ystyle=1,$
        color = thiscolor
   hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
endelse

wset,state.winval
device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]

*state.curxPtr = x
*state.curyPtr = y
*state.curyerrPtr = yerr
state.curxtitle = xlab
state.curytitle = 'Transmitted Beam Monitor'
state.curtitle = 'TBM'
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_PlotWBMMSD,event
; Plots the ratio of transmitted beam monitor to the fission chamber


;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
widget_control,state.xgroup,get_value = xselect

if not ptr_valid(state.sigenergyPtr) then begin
  widget_control,state.textWid,set_value = 'No data loaded'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
case xselect of
  0:  begin
      sigenergy = *state.timePtr
      xlab = 'time (min)'
      end
  1:  begin
      sigenergy = *state.stempPtr
      xlab = 'T (K): sample '
      end
  2:  begin
      sigenergy = *state.ctempPtr
      xlab = 'T (K): control '
      end
endcase
nchan = n_elements(sigenergy)
x = fltarr(nchan) & x = sigenergy
y = fltarr(nchan) & y = *state.WBMPtr
yerr = fltarr(nchan) & yerr = sqrt(y)

thiscolor = state.symcolor
errcolors = {thiscolor:thiscolor}
wset,state.pixId
if state.autoscale eq 1 then begin
   plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = xlab,ytitle = 'White Beam Monitor',title = 'WBM',$
        xrange=[min(x),max(x)],xstyle=1,color = thiscolor
   hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
endif else begin
   plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = xlab,ytitle = 'White Beam Monitor',title = 'WBM',$
        xrange=[state.xlo,state.xhi],xstyle=1,yrange=[state.ylo,state.yhi],ystyle=1,$
        color = thiscolor
   hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
endelse

wset,state.winval
device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]

*state.curxPtr = x
*state.curyPtr = y
*state.curyerrPtr = yerr
state.curxtitle = xlab
state.curytitle = 'White Beam Monitor'
state.curtitle = 'WBM'
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_PlotIBMMSD,event
; Plots the ratio of transmitted beam monitor to the fission chamber


;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
widget_control,state.xgroup,get_value = xselect

if not ptr_valid(state.sigenergyPtr) then begin
  widget_control,state.textWid,set_value = 'No data loaded'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
case xselect of
  0:  begin
      sigenergy = *state.timePtr
      xlab = 'time (min)'
      end
  1:  begin
      sigenergy = *state.stempPtr
      xlab = 'T (K): sample '
      end
  2:  begin
      sigenergy = *state.ctempPtr
      xlab = 'T (K): control '
      end
endcase
nchan = n_elements(sigenergy)
x = fltarr(nchan) & x = sigenergy
y = fltarr(nchan) & y = *state.FCPtr
yerr = fltarr(nchan) & yerr = sqrt(y)

thiscolor = state.symcolor
errcolors = {thiscolor:thiscolor}
wset,state.pixId
if state.autoscale eq 1 then begin
   plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = xlab,ytitle = 'Incident Beam Monitor',title = 'IBM',$
        xrange=[min(x),max(x)],xstyle=1,color = thiscolor
   hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
endif else begin
   plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = xlab,ytitle = 'Incident Beam Monitor',title = 'IBM',$
        xrange=[state.xlo,state.xhi],xstyle=1,yrange=[state.ylo,state.yhi],ystyle=1,$
        color = thiscolor
   hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
endelse

wset,state.winval
device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]

*state.curxPtr = x
*state.curyPtr = y
*state.curyerrPtr = yerr
state.curxtitle = xlab
state.curytitle = 'Incident Beam Monitor'
state.curtitle = 'IBM'
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_PlotIntensityMSD,event
; Plots the intensity as a function of Q at different temperatures


;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
widget_control,state.int_slider,get_value = tempindex
widget_control,state.xgroup,get_value = xselect

if not ptr_valid(state.timePtr) then begin
  widget_control,state.textWid,set_value = 'No data loaded yet'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

thiscolor = state.symcolor
errcolors = {thiscolor:thiscolor}

case xselect of
  0:  begin
      sigenergy = *state.timePtr
      end
  1:  begin
      sigenergy = *state.stempPtr
      end
  2:  begin
      sigenergy = *state.ctempPtr
      end
endcase
temperature = sigenergy[tempindex]

q = state.q
sigdata = *state.sigdataPtr
sigerr = *state.sigerrPtr
sigresult = size(sigdata)
sigdets = sigresult[1]
sigchan = sigresult[2]

x = fltarr(16) & x = q
y = fltarr(16) & y = sigdata[1:16,tempindex]
yerr = fltarr(16) & yerr = sigerr[1:16,tempindex]

ymax = max(sigdata[1:16,*])

widget_control,state.textWid,set_value = 'T = '+string(temperature)
wset,state.pixId
if state.autoscale eq 1 then begin
   plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = 'Q',ytitle = 'Intensity',title = 'I(Q)',$
        xrange=[0.0,2.0],xstyle=1,color = thiscolor,yrange=[0.0,ymax],ystyle=1
   hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
endif else begin
   plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = 'Q',ytitle = 'Intensity',title = 'I(Q)',$
        xrange=[state.xlo,state.xhi],xstyle=1,yrange=[state.ylo,state.yhi],ystyle=1,color = thiscolor
   hfbs_cerrplot,x,y-yerr,y+yerr,errcolors = errcolors
endelse

wset,state.winval
device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]

ynew = y
nchan = n_elements(x)
y = fltarr(1,nchan) & y[0,0:nchan-1] = ynew[0:nchan-1]
*state.curxPtr = x
*state.curyPtr = y
*state.curyerrPtr = yerr
state.curxtitle = 'Q'
state.curytitle = 'Intensity'
state.curtitle = 'I(Q)'
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_PlotDerivMSD,event
; Plots the derivative


;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
widget_control,state.siggroup,get_value = whichfile
widget_control,state.xgroup,get_value = xselect
widget_control,state.plot_slider,get_value = detector

if not ptr_valid(state.curxPtr) then begin
  widget_control,state.textWid,set_value = 'No data loaded yet'
  *pState = state
  widget_control,event.top,set_uvalue = state,/no_copy
  return
endif

ydata = *state.curyPtr
ysize = size(ydata)
if ysize[1] gt 1 then begin
  widget_control,event.top,set_uvalue = state,/no_copy
  return
endif

thiscolor = state.symcolor
errcolors = {thiscolor:thiscolor}

x = *state.curxPtr & y = *state.curyPtr & yerr = *state.curyerrPtr
yd = fltarr(n_elements(x)) & yderr = fltarr(n_elements(x))
yderr = derivsig(x,y,0.0,yerr)
yd = deriv(x,y)
ylab = 'd'+state.curytitle+'/d('+state.curxtitle+')'
curtitle = 'Derivative of '+state.curtitle
wset,state.pixId
      if state.autoscale eq 1 then begin
        plot,x,yd,psym=hfbs_selsym(state.symbolid),xtitle = state.curxtitle,ytitle = ylab,$
             xrange=[min(x),max(x)],xstyle=1,color = thiscolor,title = curtitle
        hfbs_cerrplot,width = 0.0,x,yd-yderr,yd+yderr,errcolors = errcolors
        state.xlo = min(x) & state.xhi = max(x)
        state.ylo = min(yd) & state.yhi = 1.2*max(yd)
      endif else begin
        plot,x,yd,psym=hfbs_selsym(state.symbolid),xtitle = state.curxtitle,ytitle = ylab,$
             xrange=[state.xlo,state.xhi],xstyle=1,yrange=[state.ylo,state.yhi],ystyle=1,$
             color = thiscolor,title = curtitle
        hfbs_cerrplot,width = 0.0,x,yd-yderr,yd+yderr,errcolors = errcolors
      endelse
wset,state.winval
device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]

*state.curxPtr = x
*state.curyPtr = yd
*state.curyerrPtr = yderr
state.curytitle = ylab
state.curtitle = curtitle
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_PlotMSD,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
if not ptr_valid(state.usqPtr) then begin
  widget_control,state.textWid, set_value = 'Displacements not calculated yet'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

energy = *state.energyPtr
usq = *state.usqPtr
uerr = *state.uerrPtr
thiscolor = state.symcolor
errcolors = {thiscolor:thiscolor}

wset,state.pixId
if state.autoscale eq 1 then begin
  plot,energy,usq,psym=hfbs_selsym(state.symbolid),title = 'Mean Squared Displacements',xtitle = 'T (K)',$
       ytitle = '<u!u2!n>(T)-<u!u2!n>(T=0)',xrange=[min(energy),max(energy)],xstyle=1,$
       color = thiscolor
  hfbs_cerrplot,width = 0.0,energy,usq-uerr,usq+uerr,errcolors = errcolors
endif else begin
  plot,energy,usq,psym=hfbs_selsym(state.symbolid),title = 'Mean Squared Displacements',xtitle = 'T (K)',$
       ytitle = '<u!u2!n>(T)-<u!u2!n>(T=0)',xrange=[state.xlo,state.xhi],xstyle=1,$
       yrange=[state.ylo,state.yhi],ystyle=1,color = thiscolor
  hfbs_cerrplot,width = 0.0,energy,usq-uerr,usq+uerr,errcolors = errcolors
endelse
wset,state.winval
device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]
*state.curxPtr = energy
nchan = n_elements(energy)
y = fltarr(1,nchan) & y[0,0:nchan-1] = usq[0:nchan-1]

*state.curyPtr = y
*state.curyerrPtr = uerr

state.curytitle = '<u!u2!n>(T)-<u!u2!n>(T=0)'
state.curxtitle = 'T (K)'
state.curtitle = 'Mean Squared Displacements'
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_CalcDisp,event
; Algorithm to calculate the mean squared displacement as a function
; of temperature


;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
widget_control,(*pState).PlotSelDetField,get_value = strdets
widget_control,(*pState).xgroup,get_value = xselect
indexPtr = ChooseDetsMSD(strdets)
index = *indexPtr
nchoices = n_elements(index)
if xselect eq 0 then begin
  widget_control,(*pState).textWid,set_value = 'Must use a temperature field!'
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

; test for presence of data sets
if not ptr_valid((*pState).sigdataPtr) then begin
  widget_control,(*pState).textWid,set_value = 'Signal field empty'
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

case xselect of
1:	begin
	sigenergy = *(*pState).stempPtr
	energy = fltarr(n_elements(sigenergy))
	energy = sigenergy
	end
2:  begin
	sigenergy = *(*pState).ctempPtr
	energy = fltarr(n_elements(sigenergy))
	energy = sigenergy
	end
endcase

; test for presence of data sets
if not ptr_valid((*pState).sigdataPtr) then begin
  widget_control,(*pState).textWid,set_value = 'Signal field empty'
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
ndet = (*pState).ndet
nchan = n_elements(energy)
detangles = (*pState).detangles;*(*(*(*(*pState).inPtr).dataStrPtr).specificPtr).phiPtr
q = (*pState).q;*(*(*(*(*pState).inPtr).dataStrPtr).specificPtr).qPtr
(*pState).q = q

sigdata = *(*pState).sigdataPtr
sigerr = *(*pState).sigerrPtr
sigresult = size(sigdata)
sigdets = sigresult[1]
sigchan = sigresult[2]
if not ptr_valid((*pState).bgenergyPtr) then begin	; there is a background file
  widget_control,(*pState).textWid,set_value = 'Background field empty'
endif
;;;;;;;;;;;;
data = *(*pState).dataPtr
error = *(*pState).errorPtr

sigchan = (*pState).nchan & nchan = sigchan
widget_control,(*pState).fit_slider,set_slider_max = nchan-1

wheremin = where(energy eq min(energy))
nt = 1	; number of temperatures over which to average the
		; normalization factor

datanew = data
for i = 1,ndet do begin
  if energy[0] gt energy[nchan-1] then begin
    normfact = total(data[i,nchan-nt:nchan-1])/nt
  endif else begin
    normfact = total(data[i,0:nt-1])/nt
  endelse
  datanew[i,*] = data[i,*]/normfact
  error[i,*] = error[i,*]/normfact
  data[i,*] = datanew[i,*]
endfor
;print,'normfact: ',normfact
usq = fltarr(nchan)
intensity = fltarr(ndet)
uerr = fltarr(nchan)

qrange = index-1
qlim = q[qrange]
nlim = n_elements(qrange)

whereneg = where(data[index,*] lt 0.0)
if whereneg[0] ne -1 then begin
  void = dialog_message('There are negative intensities!')
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

xfit = fltarr(ndet,nchan)
yfit = fltarr(ndet,nchan)
xdat = fltarr(ndet,nchan)
ydat = fltarr(ndet,nchan)
ydaterr = fltarr(ndet,nchan)

; Calculate the mean squared displacements

for i = 0,nchan-1 do begin
  intensity[0:ndet-1] = -(alog(data[1:ndet,i]))*3.0
  interr = fltarr(ndet)
  interr[0:ndet-1] = abs(1.0/data[1:ndet,i])*error[1:ndet,i]
  intlim = fltarr(nlim)
  intlim = intensity[qrange]
  errlim = fltarr(nlim)
  errlim = interr[qrange]
  result = LINFIT(qlim^2,intlim,sdev = errlim,sigma = errs)

  xdat[0:ndet-1,i] = q^2
  ydat[0:ndet-1,i] = intensity[0:ndet-1]
  ydaterr[0:ndet-1,i] = interr[0:ndet-1]
  xfit[0:ndet-1,i] = q^2
  yfit[0:ndet-1,i] = (result[0]+result[1]*q^2)
  usq[i] = result[1]
  uerr[i] = errs[1]
endfor

*(*pState).xdatPtr = xdat
*(*pState).ydatPtr = ydat
*(*pState).ydaterrPtr = ydaterr
*(*pState).xfitPtr = xfit
*(*pState).yfitPtr = yfit
*(*pState).usqPtr = usq
*(*pState).uerrPtr = uerr
*(*pState).energyPtr = energy

widget_control,(*pState).textWid,set_value = 'Calculation complete'
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_SumDetsMSD,event
; Sum detectors and plot the result

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
widget_control,state.PlotSelDetField,get_value = strdets
widget_control,state.xgroup,get_value = xselect
indexPtr = ChooseDetsMSD(strdets)
index = *indexPtr
nchoices = n_elements(index)

; test for presence of data sets
if not ptr_valid(state.sigdataPtr) then begin
  widget_control,state.textWid,set_value = 'Signal field empty'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

case xselect of
0:      begin
        sigenergy = *state.timePtr
        energy = fltarr(n_elements(sigenergy))
        energy = sigenergy
        xlab = 'time (min)'
        end
1:	begin
	sigenergy = *state.stempPtr
	energy = fltarr(n_elements(sigenergy))
	energy = sigenergy
        xlab = 'T (K)'
	end
2:  begin
	sigenergy = *state.ctempPtr
	energy = fltarr(n_elements(sigenergy))
	energy = sigenergy
        xlab = 'T (K)'
	end
endcase

; test for presence of data sets
if not ptr_valid(state.dataPtr) then begin
  widget_control,state.textWid,set_value = 'Signal field empty'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
ndet = state.ndet
nchan = n_elements(energy)
data = *state.dataPtr
err = *state.errorPtr
result = size(data)
datadets = result[1]
datachan = result[2]

y = fltarr(nchan)
yerr = fltarr(nchan)

for i = 0,nchoices-1 do begin
  y = y + data[index[i],0:nchan-1]
  yerr = yerr+(err[index[i],0:nchan-1])^2
endfor
yerr = sqrt(yerr)
x = fltarr(nchan) & x = energy

thiscolor = state.symcolor
errcolors = {thiscolor:thiscolor}

wset,state.pixId

if state.autoscale eq 1 then begin
  plot,x,y,psym=hfbs_selsym(state.symbolid),title = 'Summed Intensity',xtitle = xlab,$
       ytitle = 'Intensity (arb units)',xrange=[min(x),max(x)],xstyle=1,$
       yrange=[0.0,1.2*max(y)],ystyle=1,color = thiscolor
  hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
endif else begin
  plot,x,y,psym=hfbs_selsym(state.symbolid),title = 'Summed Intensity',xtitle = xlab,$
       ytitle = 'Intensity (arb units)',xrange=[state.xlo,state.xhi],xstyle=1,$
       yrange=[state.ylo,state.yhi],ystyle=1,color = thiscolor
  hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
endelse

wset,state.winval
device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]

ynew = y
y = fltarr(1,nchan)
y[0,0:nchan-1] = ynew[0:nchan-1]
*state.curxPtr = x
*state.curyPtr = y
*state.curyerrPtr = yerr
state.curxtitle = xlab
state.curytitle = 'Intensity (arb units)'
state.curtitle = 'Summed Intensity'
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
pro hfbs_Fit_u2,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
; test if the <u2> data is present
if not ptr_valid(state.usqPtr) then begin
  widget_control,state.textWid,set_value = 'Displacements not calculated yet'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

usq = *state.usqPtr
t = *state.energyPtr
uerr = *state.uerrPtr
tsort = sort(t)
mint = min(t[tsort])
maxt = max(t[tsort])
minu = min(usq) & maxu = max(usq)

; get the range over which to fit
result = informationPanel(group_leader = event.top,title='Fitting range', mwt = 2.0, thi = maxt, $
                          tlo=mint)
mwt = float(result.mwt) & tlo = float(result.tlo) & thi = float(result.thi)

t = t[tsort] & usq = usq[tsort] & uerr = uerr[tsort]
if thi le tlo then begin
  widget_control,state.textWid,set_value = 'Improper fit range'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
relind = where(t ge tlo and t le thi,count)
if count lt 2 then begin
  widget_control,state.textWid,set_value = 'Fit range too small'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
errs = fltarr(2)
fitResult = LINFIT(t[relind],usq[relind],sdev = uerr[relind],sigma = errs)
slope = fitResult[1]
tdebye = (8.49768*sqrt(2.0/mwt)/sqrt(slope))
terr = (0.5*8.49768*sqrt(2.0/mwt)*(1.0/sqrt(slope^3))*errs[1])
widget_control,state.textWid,set_value = 'Tdebye = '+string(tdebye)+'+/-'+string(terr)+' K'
oplot,t[relind],fitResult[0]+fitResult[1]*t[relind],psym=0,color = state.colors.white
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
return
end
;==========================================
pro RebDispMSD,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
; test if the <u2> data is present
if not ptr_valid(state.usqPtr) then begin
  widget_control,state.textWid,set_value = 'Displacements not calculated yet'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

; get the range over which to fit
result = informationPanel(group_leader = event.top,title='Number of bins', nbins = 50)
nbins = float(result.nbins)
usq = *state.usqPtr
t = *state.energyPtr
uerr = *state.uerrPtr
tsort = sort(t)
t = t[tsort] & usq = usq[tsort] & uerr = uerr[tsort]
newResult = fltarr(nbins,3)
newResult = hfbs_RebinDataMSD(t,nbins,usq,uerr)
t = fltarr(nbins) & usq = fltarr(nbins) & uerr = fltarr(nbins)
t = newResult[0:nbins-1,0]
usq = newResult[0:nbins-1,1]
uerr = newResult[0:nbins-1,2]
thiscolor = state.symcolor
errcolors = {thiscolor:thiscolor}

wset,state.pixId

plot,t,usq,psym=hfbs_selsym(state.symbolid),title = 'Mean Squared Displacements',xtitle = 'T (K)',$
     ytitle = '<u!u2!n>',xrange=[min(t),max(t)],xstyle=1,$
     yrange=[min(usq),1.2*max(usq)],ystyle=1,color = thiscolor
hfbs_cerrplot,width = 0.0,t,usq-uerr,usq+uerr,errcolors = errcolors
wset,state.winval
device,copy = [0,0,state.xsize,state,ysize,0,0,state.pixId]
*state.curxPtr = t
*state.curyPtr = usq
*state.curyerrPtr = uerr
state.curxtitle = 'T (K)'
state.curytitle = '<u!u2!n>(T)-<u!u2!n>(T=0)'
state.curtitle = 'Mean Squared Displacements'
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
return
end
;==========================================
pro hfbs_RebPlotMSD,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
if not ptr_valid(state.curxPtr) then begin
  widget_control,state.textWid,set_value = 'No data loaded yet'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

; get the range over which to fit
result = informationPanel(group_leader = event.top,title='Number of bins', nbins = 50)
nbins = float(result.nbins)
x = *state.curxPtr
y = *state.curyPtr
yerr = *state.curyerrPtr
xsort = sort(x)
x = x[xsort] & y = y[xsort] & yerr = yerr[xsort]
newResult = fltarr(nbins,3)
newResult = hfbs_RebinDataMSD(x,nbins,y,yerr)
x = fltarr(nbins) & y = fltarr(nbins) & y = fltarr(nbins)
x = newResult[0:nbins-1,0]
y = newResult[0:nbins-1,1]
yerr = newResult[0:nbins-1,2]
thiscolor = state.symcolor
errcolors = {thiscolor:thiscolor}

wset,state.pixId
plot,x,y,psym=hfbs_selsym(state.symbolid),title = state.curtitle,xtitle = state.curxtitle,$
     ytitle = state.curytitle,xrange=[min(x),max(x)],xstyle=1,$
     yrange=[min(y),1.2*max(y)],ystyle=1,color = thiscolor
hfbs_cerrplot,width = 0.0,x,y-yerr,y+yerr,errcolors = errcolors
wset,state.winval
device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]

ynew = y & nchan = n_elements(x)
y = fltarr(1,nchan) & y[0,0:nchan-1] = ynew[0:nchan-1]
*state.curxPtr = x
*state.curyPtr = y
*state.curyerrPtr = yerr

*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
return
end
;==========================================
PRO hfbs_WriteFile,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------


widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
if not ptr_valid(state.usqPtr) then begin
  widget_control,state.textWid, set_value = 'Displacements not calculated yet'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
energy = *state.energyPtr
nchan = state.nchan
usq = *state.usqPtr
uerr = *state.uerrPtr
cd,state.file_path
file = DIALOG_PICKFILE(dialog_parent = event.top,$
         title = 'output displacement file',filter='*.out')
file = file+'.out'
esort = sort(energy)
energy = energy[esort]
usq = usq[esort]
uerr = uerr[esort]
openw,lun,file,/get_lun
for i = 0,nchan-1 do begin
  printf,lun,energy[i],usq[i],uerr[i],format = '(3f15.6)'
endfor
free_lun,lun
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
pro hfbs_PlotTempRateMSD,event


;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------


widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
if not ptr_valid(state.timePtr) then begin
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif
x = *state.timePtr
x = x;/60.0

widget_control,state.xgroup,get_value = xselect
case xselect of
0:      begin
        widget_control,state.textWid,set_value = 'Cannot plot time vs. time!'
        *pState = state
        widget_control,event.top,set_uvalue = pState,/no_copy
        return
        end
1:	begin
	ynew = *state.stempPtr
    ysize = size(ynew)
    nchan = ysize[1]
    y = fltarr(1,nchan)
    y[0,0:nchan-1] = ynew[0:nchan-1]
        ylab = 'Tsample (K)'
	end
2:  begin
	ynew = *state.ctempPtr
	ysize = size(ynew)
    nchan = ysize[1]
    y = fltarr(1,nchan)
    y[0,0:nchan-1] = ynew[0:nchan-1]
        ylab = 'Tcontrol (K)'
	end
endcase

xlab = 'time (minutes)' & curtitle = 'Temperature History'
thiscolor = state.symcolor

wset,state.pixId
if state.autoscale eq 1 then begin
  plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = xlab,ytitle = ylab,$
       title = curtitle,color = thiscolor,xrange = [min(x),max(x)],xstyle=1
endif else begin
  plot,x,y,psym=hfbs_selsym(state.symbolid),xtitle = xlab,ytitle = ylab,$
       title = curtitle,color = thiscolor,xrange = [state.xlo,state.xhi],$
       xstyle=1,yrange = [state.ylo,state.yhi],ystyle=1
endelse

wset,state.winval
device,copy = [0,0,state.xsize,state.ysize,0,0,state.pixId]

*state.curxPtr = x
*state.curyPtr = y
*state.curyerrPtr = 0.0*findgen(n_elements(x))

state.curtitle = curtitle & state.curxtitle = xlab & state.curytitle = ylab

*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
return
end
;==========================================
PRO hfbs_WriteDiff,event


;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------


; Write the current difference field out to a text file
widget_control,event.top,get_uvalue = pState,/no_copy
state = *pState
if not ptr_valid(state.DataPtr) then begin
  widget_control,state.textWid, set_value = 'Difference field empty'
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

widget_control,state.plot_slider,get_value = detector

energy = *state.energyPtr
data = *state.dataPtr
error = *state.errorPtr
result = size(data)
ndets = result[1]
nchan = result[2]
x = fltarr(nchan) & x = energy
y = fltarr(nchan) & yerr = fltarr(nchan)
y = data[detector,0:nchan-1]
yerr = error[detector,0:nchan-1]
cd,state.file_path
file = DIALOG_PICKFILE(dialog_parent = event.top,$
         title = 'output difference file',filter='*.out')
file = file+'.out'
esort = sort(energy)
energy = energy[esort]
y = y[esort]
yerr = yerr[esort]
openw,lun,file,/get_lun
for i = 0,nchan-1 do begin
  printf,lun,x[i],y[i],yerr[i],format = '(3f15.6)'
endfor
free_lun,lun
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO hfbs_DisplayFileComments,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------


widget_control,event.top, get_uvalue = pState,/no_copy
state = *pState
widget_control,state.siggroup,get_value = whichfile
disp_text = strarr(2)
case whichfile of
0: begin
     disp_text[0] = state.sigfile
     disp_text[1] = state.sigcomments
   end
1: begin
     disp_text[0] = state.bgfile
     disp_text[1] = state.bgcomments
   end
2: begin
     disp_text[0] = ''
     disp_text[1] = 'Difference of two files'
   end
endcase
void = dialog_message(dialog_parent = event.top,$
          disp_text,/information,title = 'File comments')
*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PRO hfbs_FwsWinDraw, event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control, event.top, get_uvalue = pState, /no_copy
if not ptr_valid((*pState).curxPtr) then begin
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

case event.type of
0: begin  ; button press
	(*pState).mouse = event.press
	if (*pState).mouse eq 4 then begin
	  widget_control,event.top,set_uvalue = pState,/no_copy
	    hfbs_AutoScaleAxesMSD,event
	  widget_control,event.top,get_uvalue = pState,/no_copy
   	    (*pState).mouse = 0
   	    widget_control,event.top,set_uvalue = pState,/no_copy
	  return
	endif
	(*pState).xp1 = event.x
	(*pState).yp1 = event.y
	wset, (*pState).winval
	device, copy = [0,0,(*pState).xsize,(*pState).ysize,0,0, (*pState).pixId]
   end
1: begin	; button release
	if ((*pState).mouse eq 1) then begin
		x = (*pState).xp1 < (*pState).xp2
		y = (*pState).yp1 < (*pState).yp2
		w = abs((*pState).xp1 - (*pState).xp2)
		h = abs((*pState).yp1 - (*pState).yp2)
		x2 = x+w
		y2 = y+h
		lc = convert_coord(x, y, /device, /to_data)
		uc = convert_coord(x2, y2, /device, /to_data)
		wset,(*pState).winval
		(*pState).xlo = lc[0] & (*pState).xhi = uc[0]
		(*pState).ylo = lc[1] & (*pState).yhi = uc[1]

		widget_control,event.top,set_uvalue = pState,/no_copy
		hfbs_zoomMSD,event
		widget_control,event.top,get_uvalue = pState,/no_copy
	endif
	(*pState).mouse = 0
   end
2: begin	; mouse motion
    if ((*pState).mouse eq 1) then begin
    	(*pState).xp2 = event.x
    	(*pState).yp2 = event.y
    	xc = [(*pState).xp1, event.x, event.x, (*pState).xp1, (*pState).xp1]
    	yc = [(*pState).yp1, (*pState).yp1, event.y, event.y, (*pState).yp1]
    	wset, (*pState).winval
    	device, copy = [0,0,(*pState).xsize,(*pState).ysize,0,0, (*pState).pixId]
    	plots, xc, yc, /device,color = (*pState).colors.white
    endif
   end
else:
endcase

widget_control, event.top, set_uvalue = pState, /no_copy
END
;==========================================
PRO hfbs_VanNormalMSD,event

;begin error handler------------------------------------------------------------
; RTA - handler to catch misc. errors and provide a graceful exit so
;       that main app does not crash. Remember to switch off debug flag when debugging!
if (n_elements(!debug) && (!debug eq 0)) then begin
    catch, catchError
    if (catchError ne 0) then begin
        ;;print, 'Error handled!'
        eTitle = 'Error encountered'
        eMsg = 'An error or unusual condition was encountered!'
        eMsg = [eMsg,'Please, report the following to the DAVE team:']
        eMsg = [eMsg,!error_state.msg]
;    eMsg = [eMsg,'Function/module name: calledfunc()',!error_state.msg]
        void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
        catch, /cancel
        return
    endif
endif
;end error handler-------------------------------------------------------------

widget_control,event.top, get_uvalue = pState,/no_copy
state = *pState
; read in vanadium file
file = DIALOG_PICKFILE(dialog_parent = event.top,$
        /read,filter = '*.hfbs',title = 'vanadium filename')
Result2 = STRPOS(file, 'hfbs')
if strpos(file,'hfbs') eq -1 then begin
  *pState = state
  widget_control,event.top,set_uvalue = pState,/no_copy
  return
endif

; display the hourglass symbol to indicate that we're doing some work here
widget_control,/hourglass
HFBS_ReadHFBS,file,0,energy,data,error,ndet,nchan,comments,$
              integ_int,Norm2Mon = 1

datsize = size(data)
nchan = datsize[2]
ndet = datsize[1]
normFactors = fltarr(16)
wherevalid = where(energy ge -3.0 and energy le 3.0,count)
; calculate the normalization factors
for i = 1,16 do begin
  normFactors[i-1] = int_tabulated(energy[wherevalid],data[i,wherevalid])
endfor

normFactors = normFactors/(moment(normFactors))[0]
sigdata = *state.sigdataPtr
sigerr = *state.sigerrPtr
data = *state.dataPtr
error = *state.errorPtr

for i = 1,16 do begin
  (*state.sigdataPtr)[i,*] = ((*state.sigdataPtr)[i,*])/(normFactors[i-1])
  (*state.dataPtr)[i,*] = ((*state.dataPtr)[i,*])/(normFactors[i-1])
  (*state.sigerrPtr)[i,*] = ((*state.sigerrPtr)[i,*])/(normFactors[i-1])
  (*state.errorPtr)[i,*] = ((*state.errorPtr)[i,*])/(normFactors[i-1])
endfor

*pState = state
widget_control,event.top,set_uvalue = pState,/no_copy
RETURN
END
;==========================================
PRO HFBS_FWSANALYSIS_event,event
RETURN
END
;==========================================
PRO hfbs_fwsanalysis,notifyIDs,group_leader = group_leader
; widget definition module
tvlct,rorig,gorig,borig,/get
if not keyword_set(platform) and not keyword_set(file_path) then optExit = 1 else optExit = 0
if not keyword_set(platform) then platform = 0
osName = !operating_system
file_path = (*!dave_defaults).workDir;(*inPtr).datDir

base = widget_base(/col,title='Fixed Window Scan Analysis Program',/tlb_frame_attr,$
                   /base_align_center,mbar = bar)
filemenu = WIDGET_BUTTON(bar, VALUE='File', /MENU)
printmenu = widget_button(bar,value = 'Print',/menu)
miscmenu = WIDGET_BUTTON(bar, VALUE='Misc', /MENU)

void = widget_button(filemenu,value = 'Load DAVE ',event_pro='HFBSLoadDAVEScanFile')
void = widget_button(filemenu,value = 'Write displacements to a file',event_pro='hfbs_WriteFile')
void = widget_button(filemenu,value = 'Save current fit to a file',event_pro='hfbs_SaveFitMSD')
void = widget_button(filemenu,value = 'Save all fits to a file',event_pro='hfbs_SaveAllFitsMSD')
void = widget_button(filemenu,value = 'Write difference field out to a file',event_pro='hfbs_WriteDiff')
void = widget_button(filemenu,value = 'Write current plot to a file',event_pro='hfbs_WritePlotMSD')
void = widget_button(filemenu,value = 'Vanadium normalization',event_pro='hfbs_VanNormalMSD')
void = widget_button(filemenu,value = 'Exit',event_pro='HFBS_FWSDone')

void = widget_button(miscmenu,value = 'Rebin Plot',event_pro='hfbs_RebPlotMSD')
void = widget_button(miscmenu,value = 'Display file comments',event_pro='hfbs_DisplayFileComments')
void = widget_button(miscmenu,value = 'Extract Debye temperature',event_pro='hfbs_Fit_u2')
void = widget_button(miscmenu,value = 'Clear current fields',event_pro='hfbs_ClearFieldsMSD')
void = widget_button(miscmenu,value = 'Display data treatment',event_pro = 'HFBS_DisplayTreatment')
void = widget_button(miscmenu,value = 'About',event_pro='hfbs_AboutMSD')

void = widget_button(printmenu,value = 'Print Screen',event_pro='hfbs_PrintScreen2PsMSD')
void = widget_button(printmenu,value = 'Print Current Fit',event_pro='hfbs_PrintFits2PSMSD')

base1 = widget_base(base,/row,/base_align_center)
base1a = widget_base(base1,/col,/base_align_center)
base1aa = widget_base(base1a,/row,/base_align_center)

base1b = widget_base(base1,/col,/base_align_center)
base1c = widget_base(base1,/col,/base_align_center)

void = widget_label(base1c,value = 'Plot')
base1cc = widget_base(base1c,/col,/base_align_center,/frame)
base1cca = widget_base(base1cc,/row,/base_align_center)
base1ccb = widget_base(base1cc,/row,/base_align_center)
base1ccc = widget_base(base1cc,/row,/base_align_center)
base1ccd = widget_base(base1cc,/row,/base_align_center)
base1cce = widget_base(base1cc,/row,/base_align_center)

but1size = 100
void = widget_button(base1cca,value = 'Sum Dets',event_pro='hfbs_SumDetsMSD',xsize = but1size)
void = widget_button(base1cca,value = 'WBM',event_pro='hfbs_PlotWBMMSD',xsize = but1size)
void = widget_button(base1ccb,value = 'Mult Dets',event_pro='hfbs_PlotDataMSD',xsize = but1size)
void = widget_button(base1ccb,value = 'TBM/IBM',event_pro='hfbs_PlotRatioMSD',xsize = but1size)
void = widget_button(base1ccb,value = 'Derivative',event_pro='hfbs_PlotDerivMSD',xsize = but1size)
void = widget_button(base1ccc,value = 'TBM',event_pro='hfbs_PlotTBMMSD',xsize = but1size)
void = widget_button(base1ccc,value = 'IBM',event_pro='hfbs_PlotIBMMSD',xsize = but1size)
void = widget_button(base1ccc,value = 'Temperature',event_pro='hfbs_PlotTempRateMSD',$
       xsize = but1size)

int_slider = widget_slider(base1ccd,title='Plot I(Q,T)',value = 0,maximum = 500,$
             event_pro='hfbs_PlotIntensityMSD',/suppress_value)
plot_slider = widget_slider(base1ccd,title='Plot detectors',value = 1,minimum = 1,$
              maximum = 16,event_pro='hfbs_PlotDetsMSD',/suppress_value)
fit_slider = widget_slider(base1ccd,title='Plot fits',value = 0,maximum = 500,$
             event_pro='hfbs_PlotFitsMSD',/suppress_value)

base1d = widget_base(base1c,/row,/base_align_center)
base2 = widget_base(base,/col,/base_align_center)

sigtypes = ['signal', 'background','difference']
siggroup = cw_bgroup(base1aa, sigtypes, /col, /exclusive,$
         label_top='Selection',/no_release,$
         frame=1,set_value=0,/return_index,uvalue = 'signals')
xtypes = ['time', 'T (sample)','T (control)']
xgroup = cw_bgroup(base1aa, xtypes, /col, /exclusive,$
         label_top='x axis',/no_release,$
         frame=1,set_value=1,/return_index,uvalue = 'temperatures')

scaleFactor  = cw_field(base1b,/string,title='Background factor',$
               value='1.0',xsize=5,/column)

base11b = widget_base(base1b,/row,/base_align_center)
PlotSelDetField  = cw_field(base11b,/string,title='Sel Dets',value='1-4',$
                   xsize=10,/column)

void = widget_label(base1a,value='Status/Info')
INIT_TEXT = ''
textWid = widget_text(base1a,value=INIT_TEXT,xsize=20,ysize=1,/scroll)

calculate = widget_button(base1b,value = 'Calc displacement',event_pro='hfbs_CalcDisp')
void = widget_button(base1b,value = 'Plot displacement',event_pro='hfbs_PlotMSD')

plotbase =  widget_draw(base2,xsize=650,ysize=350,/motion_events,$
                /button_events,EVENT_PRO = 'hfbs_FwsWinDraw')

; The following statements enable access to colors from
; the hfbs_GETCOLOR routine
colors = hfbs_GetColor(/Load, Start=1)
boxcolor = colors.white
symcolor = colors.yellow

nchan = 10
ndet = 16
areas = 'false'
sigcomments = 'No files loaded' & bgcomments = 'No files loaded'
sigfile = '' & bgfile = ''

autoscale = 1	; 1 for autoscale, 0 for manual
xlo = 0.0 & xhi = 1.0 & ylo = 0.0 & yhi = 1.0
plotType = 0	; 0 for intensities, 1 for u^2 vs. temperature
symbolid = 0

fsize = 1	; default font size
detangles = [14.46,20.98,27.08,32.31,36.0,43.75,51.5,59.25,67.0,$
             74.75,82.5,90.25,98.0,105.75,113.5,121.5]
lamo = 6.271
q = fltarr(ndet)
q = (4.0*!pi/lamo)*sin(0.5*!dtor*detangles)

printPath = (*!dave_defaults).workDir;(*inPtr).workDir
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
centertlb,base
widget_control,base,/realize

Device, Set_Character_Size=[9,12]

xxsize = 650 & yysize = 350
window, /free, /pixmap, xsize = xxsize, ysize = yysize
pixId = !d.window
widget_control,plotbase,get_value = winval

state = {siggroup:siggroup,$
            PlotSelDetField:PlotSelDetField,$
            fit_slider:fit_slider,$
            plotbase:plotbase,$
            file_path:file_path,$
            textWid:textWid,$
            sigenergyPtr:ptr_new(/allocate_heap),$
            bgenergyPtr:ptr_new(/allocate_heap),$
            sigdataPtr:ptr_new(/allocate_heap),$
            bgdataPtr:ptr_new(/allocate_heap),$
            sigerrPtr:ptr_new(/allocate_heap),$
            bgerrPtr:ptr_new(/allocate_heap),$
            energyPtr:ptr_new(/allocate_heap),$
            dataPtr:ptr_new(/allocate_heap),$
            errorPtr:ptr_new(/allocate_heap),$
            nchan:nchan,$
            usqPtr:ptr_new(/allocate_heap),$
            uerrPtr:ptr_new(/allocate_heap),$
            xfitPtr:ptr_new(/allocate_heap),$
            yfitPtr:ptr_new(/allocate_heap),$
            xdatPtr:ptr_new(/allocate_heap),$
            ydatPtr:ptr_new(/allocate_heap),$
            ydaterrPtr:ptr_new(/allocate_heap),$
            ndet:ndet,$
            plot_slider:plot_slider,$
            xp1:0,yp1:0,xp2:0,yp2:0,$
            scaleFactor:scaleFactor,$
            xgroup:xgroup,$
            ctempPtr:ptr_new(/allocate_heap),$
            stempPtr:ptr_new(/allocate_heap),$
            timePtr:ptr_new(/allocate_heap),$
            bgctempPtr:ptr_new(/allocate_heap),$
            bgstempPtr:ptr_new(/allocate_heap),$
            bgtimePtr:ptr_new(/allocate_heap),$
            platform:platform,$
            printPath:printPath,$
            sigcomments:sigcomments,$
            bgcomments:bgcomments,$
            sigfile:sigfile,$
            bgfile:bgfile,$
            xlo:xlo,xhi:xhi,ylo:ylo,$
            yhi:yhi,$
            autoscale:autoscale,$
            plotType:plotType,$
            TBMPtr:ptr_new(/allocate_heap),$
            FCPtr:ptr_new(/allocate_heap),$
            WBMPtr:ptr_new(/allocate_heap),$
            curxPtr:ptr_new(/allocate_heap),$
            curyPtr:ptr_new(/allocate_heap),$
            curyerrPtr:ptr_new(/allocate_heap),$
            curxtitle:'',$
            curytitle:'',$
            curtitle:'',$
            boxcolor:boxcolor,$
            symbolid:symbolid,$
            q:q,$
            symcolor:symcolor,$
            colors:colors,$
            int_slider:int_slider,$
            fsize:fsize,$
            detangles:detangles, $
            winval:winval,$
            mouse:0,$
            pixId:pixId,$
            xsize:xxsize,$
            ysize:yysize,$
            optExit:optExit,$
            rorig:rorig,$
            borig:borig,$
            gorig:gorig,$
          ;  inPtr:inPtr,$
            notifyIDs:notifyIDs}

pState = ptr_new(state,/no_copy)
widget_control,base,set_uvalue = pState,/no_copy
xmanager,'HFBS_FWSANALYSIS',base,cleanup = 'HFBS_FWSCLEANUP'
return
END
