; Written by  Craig Brown
;************************************************************************************************
;###############################################################################
;
; LICENSE:
;  The software in this file is written by an employee of
;  National Institute of Standards and Technology
;  as part of the DAVE software project.
;
;  The DAVE software package is not subject to copyright protection
;  and is in the public domain. It should be considered as an
;  experimental neutron scattering data reduction, visualization, and
;  analysis system. As such, the authors assume no responsibility
;  whatsoever for its use, and make no guarantees, expressed or
;  implied, about its quality, reliability, or any other
;  characteristic. The use of certain trade names or commercial
;  products does not imply any endorsement of a particular product,
;  nor does it imply that the named product is necessarily the best
;  product for the stated purpose. We would appreciate acknowledgment
;  if the DAVE software is used or if the code in this file is
;  included in another product.
;
;###############################################################################
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function convert_symbol,shape,fill
case strupcase(shape) of
'CIRCLE': psym = hfbs_plotsym(/circle,fill = fill)
'TRIANGLE': psym = hfbs_plotsym(/triangle,fill = fill)
'BOX': psym = hfbs_plotsym(/box,fill = fill)
'DIAMOND': psym = hfbs_plotsym(/diamond,fill = fill)
else: psym = 4
endcase
return,psym
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::update_status,str
text_id = widget_info(self.tlb,find_by_uname = 'STATUS_TEXT')
widget_control,text_id,set_value = str
return,1
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro dcs_test_gui::cleanup
; This is the cleanup routine.
ptr_free,self.dave_color_ptr,self.color_ptr,self.sym_ptr
ptr_free,self.ddcs_color_ptr,self.sel_colors_ptr
ptr_free,self.widget_info_ptr,self.mask_ptr
ptr_free,self.maskedX,self.maskedY
ptr_free,self.notifyIdPtr, self.sff_ptr
ptr_free,self.pgroup_leader
;heap_free,self.daveptr
n = self.dcs_container->count()
if n gt 0 then begin
   oall = self.dcs_container->get(/all)
   for i = 0,n-1 do self.dcs_container->remove,oall[i]
   obj_destroy,oall
endif
obj_destroy,self.dcs_container

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro dcs_test_gui_cleanup,tlb
widget_control,tlb,get_uvalue = self
obj_destroy,self
help,/heap,/brief
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::quit,event
widget_control,event.top,/destroy
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::clipboard,event
ret= self->update_status('Copying to clipboard...')

; get window
windowIndex = !D.Window
Catch, error
IF error NE 0 THEN BEGIN
   Catch, /Cancel
   ok = Dialog_Message('Specified window is unavailable: ' + $
      StrTrim(windowIndex, 2) + '. Returning...')
   WSet, thisWindow
   RETURN,0
ENDIF
thisWindow = !D.Window
WSet, windowIndex
Catch, /Cancel

Device, Get_Visual_Depth=thisDepth
IF thisDepth GT 8 THEN BEGIN
   snapshot = TVRD(True=1)
   snapshot = Color_Quan(snapshot, 1, r, g, b)
ENDIF ELSE BEGIN
   snapshot = TVRD()
   TVLCT, r, g, b, /Get
ENDELSE
s = Size(snapshot, /Dimensions)

   ; Create an object graphics image and hierarchy.

palette = Obj_New('IDLgrPalette', r, g, b)
image = Obj_New('IDLgrImage', snapshot, Palette=palette)
model = Obj_New('IDLgrModel')
model->Add, image
thisView = Obj_New('IDLgrView', ViewPlane_Rect=[0,0,s[0],s[1]])
thisView->Add, model

   ; Create a clipboard

theClipboard = Obj_New('IDLgrClipboard', Color_Model=1, $
   Dimensions=[s[0], s[1]], N_Colors=!D.Table_Size, $
   Resolution=[1.0/!D.X_PX_CM, 1.0/!D.Y_PX_CM], $
   Palette=palette)

   ; Copy the snapshot to the clipboard.

theClipboard->Draw, thisView

   ; Destroy the objects.

Obj_Destroy, palette
Obj_Destroy, model
Obj_Destroy, thisView
Obj_Destroy, theClipboard

   ; Restore the current window.

IF thisWindow NE -1 THEN WSet, thisWindow

return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::save_as_png,event
ret= self->update_status('Screen dump to PNG')

filename=Dialog_Pickfile(/Write, path=self.work_dir,$
      Title='Name of png file...', File='screendump.png')
if filename eq '' then return,0

; get window
windowIndex = !D.Window
Catch, error
IF error NE 0 THEN BEGIN
   Catch, /Cancel
   ok = Dialog_Message('Specified window is unavailable: ' + $
      StrTrim(windowIndex, 2) + '. Returning...')
   WSet, thisWindow
   RETURN,0
ENDIF
thisWindow = !D.Window
WSet, windowIndex
Catch, /Cancel

Device, Get_Visual_Depth=thisDepth
IF thisDepth GT 8 THEN BEGIN
   snapshot = TVRD(True=1)
   snapshot = Color_Quan(snapshot, 1, r, g, b)
ENDIF ELSE BEGIN
   snapshot = TVRD()
   TVLCT, r, g, b, /Get
ENDELSE
s = Size(snapshot, /Dimensions)

image3d = BYTARR(3, s(0), s(1))
image3d(0, *, *) = r(snapshot)
image3d(1, *, *) = g(snapshot)
image3d(2, *, *) = b(snapshot)
WRITE_PNG, filename, image3d

return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::save_as_jpeg,event
ret= self->update_status('Screen dump to JPEG...')

filename=Dialog_Pickfile(/Write, path=self.work_dir,$
      Title='Name of jpeg file...', File='screendump.jpg')
if filename eq '' then return,0

; get window
windowIndex = !D.Window
Catch, error
IF error NE 0 THEN BEGIN
   Catch, /Cancel
   ok = Dialog_Message('Specified window is unavailable: ' + $
      StrTrim(windowIndex, 2) + '. Returning...')
   WSet, thisWindow
   RETURN,0
ENDIF
thisWindow = !D.Window
WSet, windowIndex
Catch, /Cancel

Device, Get_Visual_Depth=thisDepth
IF thisDepth GT 8 THEN BEGIN
   snapshot = TVRD(True=1)
   snapshot = Color_Quan(snapshot, 1, r, g, b)
ENDIF ELSE BEGIN
   snapshot = TVRD()
   TVLCT, r, g, b, /Get
ENDELSE
s = Size(snapshot, /Dimensions)

image3d = BYTARR(3, s(0), s(1))
image3d(0, *, *) = r(snapshot)
image3d(1, *, *) = g(snapshot)
image3d(2, *, *) = b(snapshot)
WRITE_JPEG, filename, image3d, TRUE=1, QUALITY=100

return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::print_to_ps,event
ret= self->update_status('Dumps a BITMAP into postscript.')

filename=Dialog_Pickfile(/Write, path=self.work_dir,$
      Title='Name of PostScript File...', File='screendump.ps')
if filename eq '' then return,0

screenDump = TVRD()

inches = 1
shortside = 8.5
longside = 11.0
aspectRatio=1.
margin=0.05

aspectRatio = FLOAT(!D.Y_VSIZE) / !D.X_VSIZE
pAspectRatio = longside / shortside

IF (aspectRatio LE pAspectRatio) THEN BEGIN
   xstart = margin
   ystart = 0.5 - (0.5 - margin) * (aspectRatio / pAspectRatio)
   xend = 1.0 - margin
   yend = 0.5 + (0.5 - margin) * (aspectRatio / pAspectRatio)
ENDIF ELSE BEGIN
   xstart = 0.5 - (0.5 - margin) * (pAspectRatio / aspectRatio)
   ystart = margin
   xend = 0.5 + (0.5 - margin) * (pAspectRatio / aspectRatio)
   yend = 1.0 - margin
ENDELSE

pos = [xstart, ystart, xend, yend]

   ; Convert normalized position coordinates to size units.
   xsize = (pos[2] - pos[0]) * shortside
   ysize = (pos[3] - pos[1]) * longside
   xoffset = pos[0] * shortside
   yoffset = pos[1] * longside
   landscape = 0
   portrait = 1

thisDevice = !D.NAME
SET_PLOT, 'PS', /Copy

DEVICE, FILENAME=filename, XSIZE=xsize, YSIZE=ysize, $
XOFFSET=xoffset, YOFFSET=yoffset, COLOR=0, $
ENCAPSULATED=Keyword_Set(encapsulated), Inches=inches
   ; Display the screen dump. Fill up the window.

IF Size(screenDump, /N_Dimensions) EQ 2 THEN $
   TV, screenDump, XSize=xsize, YSize=ysize, Inches=inches ELSE $
   TV, screenDump, XSize=xsize, YSize=ysize, Inches=inches, TRUE=1
DEVICE, /CLOSE_FILE
SET_PLOT, thisDevice


return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::dcs_save_mask,event
    filename=Dialog_Pickfile(/Write, path=self.work_dir,$
                   Title='Save Mask Information As');, File='screendump.png')
    if filename eq '' then return,0

    textBox = widget_info(event.top,find_by_uname="MASK")
    widget_control,textBox,get_value=tempString
    tempString = tempString[0]
    storedMask = tempString
    save,storedMask,filename=filename
    void = self->update_status("Mask saved.")
    ;help,tempString

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::dcs_save_dave,event

;find out which option was pressed
option=widget_info(event.id,/uname)

;dcs_object
  red_id = widget_info(self.file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
  widget_control,red_id,get_uvalue = uval
  dcs_data = uval.dcs_object

if not obj_valid(dcs_data) then return,0

;see if we have a combined data object
index=-99
com_id = widget_info(self.tlb,find_by_uname = 'CORRECTED_DATA_FOLDER')
ret = dcs_data->get_property(corrected = com_container)
   c_int = com_container->count()
   if c_int gt 0 then begin
      com_all = com_container->get(/all)
      for i = 0,n_elements(com_all)-1 do begin
         if obj_valid(com_all[i]) then begin
            ret = com_all[i]->get_property(signal_type = signal_type)
            if signal_type eq 'CORRECTED_SIGNAL' then index=i
         endif
      endfor
   endif
if index lt 0 then  begin
     strout = 'No data to save'
     void = dialog_message(dialog_parent = event.top,strout,/information, $
     title = 'DCS Reduction Error')
   return,0
endif


;det efficiency flag
      ;get yes or no:
      dc_id = widget_info(self.tlb,find_by_uname = 'USE_DETEFF')
      widget_control,dc_id,get_value=dodeteff

;set energy zero to '0.0' flag
      ;get yes or no:
      dz_id = widget_info(self.tlb,find_by_uname = 'ZERO_ENERGY')
      widget_control,dz_id,get_value=dozeroenergy

;detailed balance?:
      db_id = widget_info(self.tlb,find_by_uname = 'USE_DETAILEDB')
      widget_control,dz_id,get_value=dodetailed

;get a generic filename?
      file = DIALOG_PICKFILE(title = 'Enter the basename of the file',$
                             path=self.work_dir,$
                            ; path='C:\Documents and Settings\craig\My Documents\work pc\ncnr\dcs\users\teresa\reduced\',$
                             /write,filter = '*',$
                              dialog_parent = self.tlb)


if (n_elements(file_basename(file)) le 0) then return,0
if file eq '' then return,0
count=-99
if (n_elements(file_basename(file)) le 0) then return,0
if file eq '' then return,0
filebase=file_basename(file)
res=strsplit(filebase,'.',count=count,/extract)
if count ge 1 then filename=res[n_elements(res)-count]

work_dir=file_dirname(file,/mark_directory)
if n_elements(work_dir) ge 1 then self.work_dir = work_dir
file=self.work_dir+filename

ret=self->update_status('Saving Dave Format')

all=0
if option eq 's_all_d' then all=1

if all then option = 's_gw_d'
if option eq 's_gw_d' then begin
      dim='CUT'  ;always override
      ;need to over ride...
      dodetailed=1
      TEMP_ID = widget_info(self.tlb,find_by_uname = 'TDEF')
      widget_control,TEMP_ID,get_value=temperatures
      ret = com_all[index]->get_property(display_name = display_name,comments=comments,$
             treatment=treatment)
      type='GDOS'
      ret  = dcs_data->Scatter(type=type,$
                    temperatures=temperatures,dodeteff=dodeteff,dozeroenergy=dozeroenergy,$
                    dodetailed=dodetailed,qty=qty,err=err,$
                    xaxis=xaxis,xunits=xunits,xlabel=xlabel)
     ; make a dave_ptr
      ret       = CREATE_DAVE_POINTER(daveptr,$
                               qty=qty,    $
                               err=err    ,     $
                               QTUNITS = 'arb_units',$
                               QTLABEL = 'Summed g(w)',$                     $
                               XVALS = xaxis,$
                               XLABEL =  'Energy Transfer',     $
                               XUNITS = 'meV',       $
                               XTYPE = 'POINTS',$
                               ylabel=display_name     ,$
                               YVALS = temperatures ,                      $
                               YUNITS = 'K',       $
                               INSTRUMENT='DCS',$
                               TREATMENT = treatment,     $
                               DNAME = 'Temperature',          $
                               DUNITS = 'K',        $
                               DLEGEND = 'T',       $
                               DQTY = temperatues, $
                               ERMSG = ermsg )
      ;print,'Error message:',ermsg
;       add some info to the sample information tag:
       (*(*daveptr).descriptr).qty=temperatures
       (*(*daveptr).descriptr).units='K'
       (*(*daveptr).descriptr).legend='Temperature'
       (*(*daveptr).descriptr).name='Temperature'
       save,daveptr,filename = file+'_gw.dave'
       heap_free,daveptr
  endif

if all then option = 's_sum_d'
if option eq 's_sum_d' then begin
           dim='CUT'  ;always override
      ret = com_all[index]->get_property(display_name = display_name, xlabel=xlabel,$
                         xunits=xunits,histlabel=histlabel,comments=comments,$
                         plot_sums=plot_sums,q_props=q_props,angle_props=angle_props,$
                         temp_setpoint=temp_setpoint,$
                         treatment=treatment)
     ; make a dave_ptr
     if n_elements(plot_sums)-1 eq 0 then begin
       ttt=fltarr(1)
       ttt[0]=plot_sums
       plot_sums=ttt
       ;dave thing generator needs an array here...
     endif else begin
       q_props=q_props[1:n_elements(plot_sums)-1]
     endelse

      ret       = CREATE_DAVE_POINTER(daveptr,$
                               qty=plot_sums,    $
                               err=sqrt(plot_sums)    ,     $
                               QTUNITS = 'Counts',$
                               QTLABEL = 'Total Intensity',$                     $
                               XVALS = q_props,$
                               XLABEL =  'Mean Q',     $
                               XUNITS = 'A!E-1!N',       $
                               XTYPE = 'POINTS',$
                               ylabel=display_name     ,$
                               YVALS = temp_setpoint ,                      $
                               YUNITS = 'K',       $
                               INSTRUMENT='DCS',$
                               TREATMENT = treatment,     $
                               DNAME = 'Temperature',          $
                               DUNITS = 'K',        $
                               DLEGEND = 'T',       $
                               DQTY = temp_setpoint, $
                               ERMSG = ermsg )
      ;print,'Error message:',ermsg
;       add some info to the sample information tag:
       (*(*daveptr).descriptr).qty=temp_setpoint
       (*(*daveptr).descriptr).units='K'
       (*(*daveptr).descriptr).legend='Temperature'
       (*(*daveptr).descriptr).name='Temperature'
       save,daveptr,filename = file+'_sum.dave'
       heap_free,daveptr
endif



if all then option = 's_sqw_d'
if option eq 's_sqw_d' then begin
       ret = com_all[index]->get_property(display_name = display_name,comments=comments)
       type='SQOM'
       ret  = dcs_data->Scatter(type=type,$
                    temperatures=temperatures,dodeteff=dodeteff,dozeroenergy=dozeroenergy,$
                    dodetailed=dodetailed,qty=qty,err=err,qelmean=qelmean,tthmean=tthmean,$
                    xaxis=xaxis,xunits=xunits,xlabel=xlabel,$
                    treatment=treatment)
       x=xaxis[0:n_elements(xaxis)-2]    ;XXX WHY IS THIS 1001 elements?
       y=tthmean
       ylabel=xlabel
       xlabel='Q (A!E-1!N)'
       histlabel=''
       index_title="Image"

     ; make a dave_ptr
      ret       = CREATE_DAVE_POINTER(daveptr,$
                               qty=qty,    $
                               err=err    ,     $
                               QTUNITS = 'Arb. Units',$
                               QTLABEL = 'S(Q,w)',$                     $
                               YVALS = qelmean,$
                               YLABEL =  'Mean Q',     $
                               YUNITS = 'A!E-1!N',       $
                               YTYPE = 'POINTS',$
                               Xlabel='Energy Transfer'     ,$
                               XVALS = x ,                      $
                               XUNITS = 'meV',       $
                               INSTRUMENT='DCS',$
                               TREATMENT = treatment,     $
                               ERMSG = ermsg )
      ;print,'Error message:',ermsg
       save,daveptr,filename = file+'_sqw.dave'
       print,'saved '+file
       heap_free,daveptr
endif


if all then option = 's_iw_d'
if option eq 's_iw_d' then begin
       ret = com_all[index]->get_property(display_name = display_name,comments=comments)
       type='DODE'
       ret  = dcs_data->Scatter(type=type,$
                    temperatures=temperatures,dodeteff=dodeteff,dozeroenergy=dozeroenergy,$
                    dodetailed=dodetailed,qty=qty,err=err,qelmean=qelmean,tthmean=tthmean,$
                    xaxis=xaxis,xunits=xunits,xlabel=xlabel,$
                    treatment=treatment)

       x=xaxis[0:n_elements(xaxis)-2]    ;XXX WHY IS THIS 1001 elements?

     ; make a dave_ptr
      ret       = CREATE_DAVE_POINTER(daveptr,$
                               qty=qty,    $
                               err=err    ,     $
                               QTUNITS = 'Counts',$
                               QTLABEL = 'I(!62!4h!6,w)',$                     $
                               YVALS = tthmean,$
                               YLABEL =  '!3Scattering angle',     $
                               YUNITS = '!Eo!N',       $
                               YTYPE = 'POINTS',$
                               Xlabel='Energy Transfer'     ,$
                               XVALS = x ,                      $
                               XUNITS = 'meV',       $
                               INSTRUMENT='DCS',$
                               TREATMENT = treatment,     $
                               ERMSG = ermsg )
      ;print,'Error message:',ermsg
       save,daveptr,filename = file+'_iw.dave'
       heap_free,daveptr
endif

if all then option = 's_it_d'
if option eq 's_it_d' then begin
     ret = com_all[index]->get_property(display_name = display_name,comments=comments)
     type='DODT'
     ret  = dcs_data->Scatter(type=type,dodetailed=dodetailed,$
                    temperatures=temperatures,dodeteff=dodeteff,dozeroenergy=dozeroenergy,$
                    qty=qty,err=err,qelmean=qelmean,tthmean=tthmean,$
                    xaxis=xaxis,xunits=xunits,xlabel=xlabel,$
                    treatment=treatment)
     x=xaxis[0:n_elements(xaxis)-2]    ;XXX WHY IS THIS 1001 elements?
     y=tthmean
     ylabel=xlabel
     xlabel='!3Scattering angle (!E0!N)'
     histlabel=''
     index_title="Image"
     ; make a dave_ptr
     ret       = CREATE_DAVE_POINTER(daveptr,$
                               qty=qty,    $
                               err=err    ,     $
                               QTUNITS = 'Counts',$
                               QTLABEL = 'I(!62!4h!6,t)',$                     $
                               YVALS = tthmean,$
                               YLABEL =  '!3Scattering angle',     $
                               YUNITS = '!Eo!N',       $
                               YTYPE = 'POINTS',$
                               Xlabel='Time-of-flight'     ,$
                               XVALS = x ,                      $
                               XUNITS = 'usec',       $
                               INSTRUMENT='DCS',$
                               TREATMENT = treatment,     $
                               ERMSG = ermsg )
      ;print,'Error message:',ermsg
       save,daveptr,filename = file+'_it.dave'
       heap_free,daveptr
endif



ret=self->update_status('Finished Saving')

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::dcs_save_asc,event

;find out which option was pressed
option=widget_info(event.id,/uname)

;dcs_object
  red_id = widget_info(self.file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
  widget_control,red_id,get_uvalue = uval
  dcs_data = uval.dcs_object

if not obj_valid(dcs_data) then return,0

;see if we have a combined data object
index=-99
com_id = widget_info(self.tlb,find_by_uname = 'CORRECTED_DATA_FOLDER')
ret = dcs_data->get_property(corrected = com_container)
   c_int = com_container->count()
   if c_int gt 0 then begin
      com_all = com_container->get(/all)
      for i = 0,n_elements(com_all)-1 do begin
         if obj_valid(com_all[i]) then begin
            ret = com_all[i]->get_property(signal_type = signal_type)
            if signal_type eq 'CORRECTED_SIGNAL' then index=i
         endif
      endfor
   endif
if index lt 0 then  begin
     strout = 'No data to save'
     void = dialog_message(dialog_parent = event.top,strout,/information, $
     title = 'DCS Reduction Error')
   return,0
endif


;det efficiency flag
      ;get yes or no:
      dc_id = widget_info(self.tlb,find_by_uname = 'USE_DETEFF')
      widget_control,dc_id,get_value=dodeteff

;set energy zero to '0.0' flag
      ;get yes or no:
      dz_id = widget_info(self.tlb,find_by_uname = 'ZERO_ENERGY')
      widget_control,dz_id,get_value=dozeroenergy

;detailed balance?:
      db_id = widget_info(self.tlb,find_by_uname = 'USE_DETAILEDB')
      widget_control,dz_id,get_value=dodetailed

;get a generic filename?
      file = DIALOG_PICKFILE(title = 'Enter the basename of the file',$
                             path=self.work_dir,$
                             ;path='C:\Documents and Settings\craig\My Documents\work pc\Work\',$
                             /write,filter = '*',$
                              dialog_parent = self.tlb)
count=-99
if (n_elements(file_basename(file)) le 0) then return,0
if file eq '' then return,0
filebase=file_basename(file)
res=strsplit(filebase,'.',count=count,/extract)
if count ge 1 then filename=res[n_elements(res)-count]

work_dir=file_dirname(file,/mark_directory)
if n_elements(work_dir) ge 1 then self.work_dir = work_dir
file=self.work_dir+filename


ret=self->update_status('Saving Ascii')

all=0
if option eq 's_all_a' then all=1

if all then option = 's_gw_a'
if option eq 's_gw_a' then begin
      dim='CUT'  ;always override
      ;need to over ride...
      dodetailed=1
      TEMP_ID = widget_info(self.tlb,find_by_uname = 'TDEF')
      widget_control,TEMP_ID,get_value=temperatures
      ret = com_all[index]->get_property(display_name = display_name,comments=comments)
      type='GDOS'
       ret  = dcs_data->Scatter(type=type,$
                    temperatures=temperatures,dodeteff=dodeteff,dozeroenergy=dozeroenergy,$
                    dodetailed=dodetailed,qty=qty,err=err,$
                    xaxis=xaxis,xunits=xunits,xlabel=xlabel)
       filename = file+'_gw.dat'
       openw,lun,filename,/get_lun
          PRINTF,lun,'#    Energy(meV)        GDOS            Error'
          for io=0,n_elements(qty)-1 do begin
            printf,lun,xaxis[io],qty[io],err[io]
          endfor
       free_lun,lun
  endif

if all then option = 's_sum_a'
if option eq 's_sum_a' then begin
           dim='CUT'  ;always override
      ret = com_all[index]->get_property(display_name = display_name, xlabel=xlabel,$
                         xunits=xunits,histlabel=histlabel,comments=comments,$
                         plot_sums=plot_sums,q_props=q_props,angle_props=angle_props,$
                         temp_setpoint=temp_setpoint)
       filename = file+'_sum.dat'
       openw,lun,filename,/get_lun
          PRINTF,lun,'#     Q(A-1)       TOTALS        Error'
          for io=0,n_elements(plot_sums)-1 do begin
            printf,lun,q_props[io],plot_sums[io],sqrt(plot_sums[io])
          endfor
       free_lun,lun
endif



if all then option = 's_sqw_a'
if option eq 's_sqw_a' then begin
       ret = com_all[index]->get_property(display_name = display_name,comments=comments)
       type='SQOM'
       ret  = dcs_data->Scatter(type=type,$
                    temperatures=temperatures,dodeteff=dodeteff,dozeroenergy=dozeroenergy,$
                    dodetailed=dodetailed,qty=qty,err=err,qelmean=qelmean,tthmean=tthmean,$
                    xaxis=xaxis,xunits=xunits,xlabel=xlabel)
       x=xaxis[0:n_elements(xaxis)-2]    ;XXX WHY IS THIS 1001 elements?
       y=tthmean
       ylabel=xlabel
       xlabel='Q (A!E-1!N)'
       histlabel=''
       index_title="Image"
       filename = file+'_sqw.dat'
       openw,lun,filename,/get_lun
         ; PRINTF,lun,'#Number of x-values'
         ; Printf,lun,n_elements(x)-1
         ; PRINTF,lun,'#Number of y-values'
         ; Printf,lun,n_elements(qelmean)-1
          ;PRINTF,lun,'#x-values'
          ;for i=0,n_elements(x)-1 do begin
          ;  Printf,lun,xaxis[i]
          ;endfor
          ;PRINTF,lun,'#y-values'
          ;for i=0,n_elements(qelmean)-1 do begin
          ;  Printf,lun,qelmean[i]
          ;endfor
          for j=0,n_elements(qelmean)-1 do begin
             printf,lun,'# group '+strcompress(string(j+1))+', Qmean '+string(qelmean[j])
             printf,lun,'# x y err'
             for io=0,n_elements(x)-1 do begin
               printf,lun,x[io],qty[io,j],err[io,j]
               if io eq n_elements(x)-1 then printf,lun
             endfor
          endfor
       free_lun,lun
endif



if all then option = 's_iw_a'
if option eq 's_iw_a' then begin
       ret = com_all[index]->get_property(display_name = display_name,comments=comments)
       type='DODE'
       ret  = dcs_data->Scatter(type=type,$
                    temperatures=temperatures,dodeteff=dodeteff,dozeroenergy=dozeroenergy,$
                    dodetailed=dodetailed,qty=qty,err=err,qelmean=qelmean,tthmean=tthmean,$
                    xaxis=xaxis,xunits=xunits,xlabel=xlabel)

       x=xaxis[0:n_elements(xaxis)-2]    ;XXX WHY IS THIS 1001 elements?
       filename = file+'_iw.dat'
       openw,lun,filename,/get_lun
         ; PRINTF,lun,'#Number of x-values'
         ; Printf,lun,n_elements(x)-1
         ; PRINTF,lun,'#Number of y-values'
         ; Printf,lun,n_elements(qelmean)-1
          ;PRINTF,lun,'#x-values'
          ;for i=0,n_elements(x)-1 do begin
          ;  Printf,lun,xaxis[i]
          ;endfor
          ;PRINTF,lun,'#y-values'
          ;for i=0,n_elements(qelmean)-1 do begin
          ;  Printf,lun,qelmean[i]
          ;endfor
          for j=0,n_elements(tthmean)-1 do begin
             printf,lun,'# group '+strcompress(string(j+1))+', 2th '+string(tthmean[j])
             printf,lun,'# x y err'
             for io=0,n_elements(x)-1 do begin
               printf,lun,x[io],qty[io,j],err[io,j]
               if io eq n_elements(x)-1 then printf,lun
             endfor
          endfor
       free_lun,lun
endif

if all then option = 's_it_a'
if option eq 's_it_a' then begin
     ret = com_all[index]->get_property(display_name = display_name,comments=comments)
     type='DODT'
     ret  = dcs_data->Scatter(type=type,dodetailed=dodetailed,$
                    temperatures=temperatures,dodeteff=dodeteff,dozeroenergy=dozeroenergy,$
                    qty=qty,err=err,qelmean=qelmean,tthmean=tthmean,$
                    xaxis=xaxis,xunits=xunits,xlabel=xlabel)
     x=xaxis[0:n_elements(xaxis)-2]    ;XXX WHY IS THIS 1001 elements?
     y=tthmean
     ylabel=xlabel
     xlabel='!3Scattering angle (!E0!N)'
     histlabel=''
     index_title="Image"

       x=xaxis[0:n_elements(xaxis)-2]    ;XXX WHY IS THIS 1001 elements?
       filename = file+'_it.dat'
       openw,lun,filename,/get_lun
         ; PRINTF,lun,'#Number of x-values'
         ; Printf,lun,n_elements(x)-1
         ; PRINTF,lun,'#Number of y-values'
         ; Printf,lun,n_elements(qelmean)-1
          ;PRINTF,lun,'#x-values'
          ;for i=0,n_elements(x)-1 do begin
          ;  Printf,lun,xaxis[i]
          ;endfor
          ;PRINTF,lun,'#y-values'
          ;for i=0,n_elements(qelmean)-1 do begin
          ;  Printf,lun,qelmean[i]
          ;endfor
          for j=0,n_elements(tthmean)-1 do begin
             printf,lun,'# group '+strcompress(string(j+1))+', 2th '+string(tthmean[j])
             printf,lun,'# x y err'
             for io=0,n_elements(x)-1 do begin
               printf,lun,x[io],qty[io,j],err[io,j]
               if io eq n_elements(x)-1 then printf,lun
             endfor
          endfor
       free_lun,lun
endif



ret=self->update_status('Finished Saving')

end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::update_mask,event
;text_id = widget_info(event.top,find_by_uname = 'MASK')
text_id = widget_info(self.tlb,find_by_uname = 'MASK')
widget_control,text_id,get_value=numbers

nbmax=self.nhedet
blist=intarr(nbmax)+1; a set of 913 1's
detarr=opan_selectgroups(numbers)
if n_elements(detarr) eq 1 then begin
    if ( (detarr eq 0) && (numbers ne '0') ) then begin
        *self.mask_ptr=intarr(913)+1
        *self.maskedX = -1
        *self.maskedY = -1
        return,0
    endif
endif
;subtract 1 from each number for arrays in IDL
;detarr=detarr-1
;if any element is le 0 make it 0:
under=where(detarr le 0,count)
if (count ge 1) then detarr[under]=0
;if any element is over nbmax make it nbmax:
over=where(detarr ge nbmax,count)
if (count ge 1) then detarr[over]=nbmax-1
;need to check this array for duplicated values,max value and maximum array size
detarr=detarr[sort(detarr)]        ;put them in order
detarr=detarr[uniq(detarr)]        ;remove duplicates
if n_elements(detarr) ge nbmax then begin     ;make nhedet elements
   detarr1 = detarr
   detarr =detarr1[0:nbmax-1]
endif
;at anypoint, make a delta function of the mask
for i=0,n_elements(detarr)-1 do begin
  blist[detarr[i]]=0
endfor
;make global
*self.mask_ptr=blist

; taken from the update_plot function
; long story short it reads the data file and gives
; me my y values (which I put into the var y)

;this really should be the data for the detector sums only. WIll not work otherwise!
;CCC XXX CCC XXX
;
pplottype_id = widget_info(self.tlb,find_by_uname = 'DCS_PLOT_SEL')
pplottype=widget_info(pplottype_id,/combobox_gettext)
if pplottype ne 'DETECTOR PLOT' then begin
       reduceButton = widget_info(event.top, find_by_uname="RED_BUTTON")
       tempEvent2 = {   WIDGET_BUTTON,    $
               ID:0,      $
               top:0,       $
               handler:0,   $
               select:1       $
              }
       ;help, tempEvent2, /structure
       widget_control,reduceButton,send_Event=tempEvent2,/no_copy
       return,1
endif

file_tree = self.file_tree
red_id = widget_info(file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
widget_control,red_id,get_uvalue = uval
dcs_data = uval.dcs_object
;see if we have a combined data object
index=-99
com_id = widget_info(red_id,find_by_uname = 'CORRECTED_DATA_FOLDER')
ret = dcs_data->get_property(corrected = com_container)
c_int = com_container->count()
if c_int gt 0 then begin
    com_all = com_container->get(/all)
    for i = 0,n_elements(com_all)-1 do begin
       if obj_valid(com_all[i]) then begin
         ret = com_all[i]->get_property(signal_type = signal_type)
         if signal_type eq 'CORRECTED_SIGNAL' then index=i
       endif
    endfor
endif
ret = com_all[index]->get_property(display_name = display_name, xlabel=xlabel,$
             xunits=xunits,histlabel=histlabel,comments=comments,$
             plot_sums=plot_sums,q_props=q_props,angle_props=angle_props)
y = plot_sums
; populate my x data
; ASSUMPTION: the data is in order
x=indgen(n_elements(y))



;print,"blist:", blist
;if(detarr[0] ne 0) then begin
    if((*self.maskedX)[0] ne -1) then begin
       xNew = [*self.maskedX, x[detarr]]
       yNew = [*self.maskedY, y[detarr]]
       indices = where(yNew ne 0)
       xNew = xNew(indices)
       yNew = yNew(indices)
    endif else begin
       Xnew = x[detarr]
       Ynew = y[detarr]
    endelse
;    print, "detarr: ", detarr
;    print, "xNew before: ", xNew
;    print, "yNew before: ", yNew
    ;print,uniq(xNew, sort(xNew))

    uniqueIndex = uniq(xNew, sort(xNew))
    xNew = xNew[uniqueIndex]
    yNew = yNew[uniqueIndex]

;    print, "xNew after: ", xNew
;    print, "yNew after: ", yNew

    ptr_free,self.maskedX
    ptr_free,self.maskedY
    self.maskedX = ptr_new(xNew)
    self.maskedY = ptr_new(yNew)
;endif else begin
;   self.maskedX = ptr_new([-1L])
;   self.maskedY = ptr_new([-1L])
;endelse

       reduceButton = widget_info(event.top, find_by_uname="RED_BUTTON")
       tempEvent2 = {   WIDGET_BUTTON,    $
               ID:0,      $
               top:0,       $
               handler:0,   $
               select:1       $
              }
       ;help, tempEvent2, /structure
       widget_control,reduceButton,send_Event=tempEvent2,/no_copy

;add this to the dcs_reduce object
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::q_widget,event

uname = widget_info(event.id,/uname)
case uname of
'NO_DET_GROUP': $
   begin
       ;check to see if checked
       if (widget_info(event.id,/button_set)) then begin
          ;make the q/2th inputs insensitive
          q_id = widget_info(self.tlb,find_by_uname = 'QSTEP')
          tth_id = widget_info(self.tlb,find_by_uname = 'TTSTEP')
          widget_control,q_id,sensitive=0
          widget_control,tth_id,sensitive=0
       endif else begin
          ;make the q/2th inputs sensitive
          equal2_id = widget_info(self.tlb,find_by_uname = 'EQUAL2')
          test2=widget_info(equal2_id,/button_set)
          if test2 eq 1 then begin
              tth_id = widget_info(self.tlb,find_by_uname = 'TTSTEP')
              widget_control,tth_id,sensitive=1
          endif else begin
             q_id = widget_info(self.tlb,find_by_uname = 'QSTEP')
             widget_control,q_id,sensitive=1
          endelse
       endelse
   end

 'EQUAL2': $
    begin
       tth_id = widget_info(self.tlb,find_by_uname = 'TTSTEP')
       widget_control,tth_id,sensitive=1
       q_id = widget_info(self.tlb,find_by_uname = 'QSTEP')
       widget_control,q_id,sensitive=0

    end
  'EQUALQ': $
     begin
        tth_id = widget_info(self.tlb,find_by_uname = 'TTSTEP')
        widget_control,tth_id,sensitive=0
        q_id = widget_info(self.tlb,find_by_uname = 'QSTEP')
        widget_control,q_id,sensitive=1
     end
endcase


end


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::plotranges,event

;   GET x AND Y VALUES FROM WIDGET. IF NO VALUE MAKE THEM THE MIN AND MAX VALUES
    ;find which one is active
    fyes = widget_info(self.tlb,find_by_uname = 'FORCE_YES')
    set = widget_info(fyes,/button_set)
    if set then begin
       self.force_range=1
    endif else begin
       self.force_range=0
;       return,1
    endelse

xmin_id = widget_info(self.tlb,find_by_uname = 'DCS_XMIN')
xmax_id = widget_info(self.tlb,find_by_uname = 'DCS_XMAX')
ymin_id = widget_info(self.tlb,find_by_uname = 'DCS_YMIN')
ymax_id = widget_info(self.tlb,find_by_uname = 'DCS_YMAX')

widget_control,xmin_id,get_value=xmin
if xmin eq '' then xmin = self.xrange[0]
xmin=float(xmin)
if xmin ge self.xrange[1] then xmin = self.xrange[0]
widget_control,xmax_id,get_value=xmax
if xmax eq '' then xmax = self.xrange[1]
xmax=float(xmax)
if xmax le self.xrange[0] then xmax = self.xrange[1]
widget_control,ymin_id,get_value=ymin
if ymin eq '' then ymin = self.yrange[0]
ymin=float(ymin)
if ymin ge self.yrange[1] then ymin = self.yrange[0]
widget_control,ymax_id,get_value=ymax
if ymax eq '' then ymax = self.yrange[1]
ymax=float(ymax)
if ymax le self.yrange[0] then ymax = self.yrange[1]
self.xrange = [xmin,xmax]
self.yrange = [ymin,ymax]


ret = self->update_plot(scale=1)
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::widget_handler,event

uname = widget_info(event.id,/uname)
widget_control,event.id,get_uvalue = cmd

if uname eq 'DCS_DESIRED_IMAGE_MAX' then begin
   dplot=self.plot1D2D
   dim=widget_info(dplot,/combobox_gettext)
   if dim ne 'CUT' then ret = self->update_plot(event)
   return,1
endif

plottype_id = widget_info(self.tlb,find_by_uname = 'DCS_PLOT_SEL')
plottype=widget_info(plottype_id,/combobox_gettext)
case plottype of
'PLOT SUMS': $
   begin
       ;make the slider insensitive
       grp_id = widget_info(self.tlb,find_by_uname = 'DCS_GROUP_SLIDER')
       widget_control,grp_id,sensitive=0
   end
'DETECTOR PLOT': $
   begin
       ;make the slider insensitive
       grp_id = widget_info(self.tlb,find_by_uname = 'DCS_GROUP_SLIDER')
       widget_control,grp_id,sensitive=0
   end
'G(w)': $
   begin
       ;make the slider insensitive
       grp_id = widget_info(self.tlb,find_by_uname = 'DCS_GROUP_SLIDER')
       widget_control,grp_id,sensitive=0
   end
else: $
    begin
       ;make the slider sensitive
       grp_id = widget_info(self.tlb,find_by_uname = 'DCS_GROUP_SLIDER')
       widget_control,grp_id,sensitive=1
    end
endcase



void = self->checkForToolbar()
;continue the call
if (plottype eq "DETECTOR PLOT") then begin
    self.iwasmasking=1
;    print,"autoscale ranges"
    self.autoscale=1
    reduceButton = widget_info(event.top, find_by_uname="RED_BUTTON")
    tempEvent2 =   { WIDGET_BUTTON,  $
                 ID:0,        $
                 top:0,         $
                 handler:0,       $
                 select:1   $
              }
    widget_control,reduceButton,send_Event=tempEvent2,/no_copy
endif else begin
    if self.Iwasmasking eq 1 then begin
       self.iwasmasking=0
       reduceButton = widget_info(event.top, find_by_uname="RED_BUTTON")
       tempEvent2 =   { WIDGET_BUTTON,  $
                 ID:0,        $
                 top:0,         $
                 handler:0,       $
                 select:1   $
              }
 ;      print,"if relevent, autoscale ranges"
 ;      print,"Reducing with actual choices"
       widget_control,reduceButton,send_Event=tempEvent2,/no_copy
       if self.force_range ne 1 then begin
        self.autoscale=1
       endif else begin
         ;there must be a forced range then so obey that:
         self.autoscale=0
       endelse
    endif
    ret = self->update_plot(event)
endelse
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::update_plot,event,scale=scale,_Extra = extra
   ; print,"update_plot called"
  file_tree = self.file_tree
  ; is there any dcs data in the file_tree?
  this_id = widget_info(file_tree,/tree_select)
  if not widget_info(this_id,/valid_id) then begin
    title='NO DATA'
    xtitle='x (units)'
    ytitle='y (units)'
    colors = *self.sel_colors_ptr
    sym_str = *self.sym_ptr
  ; Get the symbol out
    fill = sym_str.fill[0]
    shape = sym_str.shape[0]
    psym = convert_symbol(shape,fill)
    axis_color = (*self.color_ptr).black
    bg_color = (*self.color_ptr).white
    sym_color = sym_str.color[0]
    position = [0.15,0.15,.95,0.9]
    x=[0,1]
    y=[0,1]
    plot,x,y,xrange = [0.,1.],yrange = [0.,1.],/nodata,$
     xtitle =  xtitle,ytitle = ytitle,color = axis_color, $
     background = bg_color,title = title,position = position
    return,0
  endif else begin
 ; ret = self->refresh(event)
  red_id = widget_info(file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
  ;widget_control,red_id,/set_tree_select
  widget_control,red_id,get_uvalue = uval
  if not obj_valid(uval.dcs_object) then begin
     strout = 'No files have been loaded yet'
     void = dialog_message(dialog_parent = event.top,strout,/information, $
        title = 'DCS Reduction Error')
     return,0
  endif
  endelse
  dcs_data = uval.dcs_object


wset,self.winPix
;default values
title='NO DATA'
xtitle='x (units)'
ytitle='y (units)'
xrange=self.xrange
yrange=self.yrange
position = [0.15,0.15,.95,0.9]

if self.colortable le 0 then self.colortable=5
colortable = self.colorTable
colors = *self.sel_colors_ptr
sym_str = *self.sym_ptr
; Get the symbol out
fill = sym_str.fill[0]
shape = sym_str.shape[0]
psym = convert_symbol(shape,fill)
axis_color = (*self.color_ptr).black
bg_color = (*self.color_ptr).white
sym_color = sym_str.color[0]

;see if we have a combined data object
index=-99
com_id = widget_info(red_id,find_by_uname = 'CORRECTED_DATA_FOLDER')
ret = dcs_data->get_property(corrected = com_container)
   c_int = com_container->count()
   if c_int gt 0 then begin
      com_all = com_container->get(/all)
      for i = 0,n_elements(com_all)-1 do begin
         if obj_valid(com_all[i]) then begin
            ret = com_all[i]->get_property(signal_type = signal_type)
            if signal_type eq 'CORRECTED_SIGNAL' then index=i
         endif
      endfor
   endif
if index lt 0 then  return,0


;continue plotting

;what do i need to know?
;(a) the function I am plotting
;(b) if it is 2D or cut
;(c) the group number.
;(d) axes
;(e) ranges
;(f) Titles
;(g) colors if applicable
;(h) intensity scales if applicable

;(a) the function I am plotting
   plottype_id = widget_info(self.tlb,find_by_uname = 'DCS_PLOT_SEL')
   plottype=widget_info(plottype_id,/combobox_gettext)

;(b) Cut or 2D
   dplot=self.plot1D2D
   dim=widget_info(dplot,/combobox_gettext)

;det efficiency flag
      ;get yes or no:
      dc_id = widget_info(self.tlb,find_by_uname = 'USE_DETEFF')
      widget_control,dc_id,get_value=dodeteff

;set energy zero to '0.0' flag
      ;get yes or no:
      dz_id = widget_info(self.tlb,find_by_uname = 'ZERO_ENERGY')
      widget_control,dz_id,get_value=dozeroenergy

;detailed balance?: THe list is contrasense 1=no 0=yes
      db_id = widget_info(self.tlb,find_by_uname = 'USE_DETAILEDB')
      widget_control,db_id,get_value=dodetailed
      ;it is always zero!???

      if dodetailed eq 0 then begin
           dodetailed=1
      endif else  begin
        dodetailed=0
      endelse

case plottype of
'PLOT SUMS': $
   begin
      dim='CUT'  ;always override
      ret = com_all[index]->get_property(display_name = display_name, xlabel=xlabel,$
                         xunits=xunits,histlabel=histlabel,comments=comments,$
                         plot_sums=plot_sums,q_props=q_props,angle_props=angle_props)
      y=plot_sums
      dy=sqrt(abs(y))

      x=indgen(n_elements(y))
      ;x=q_props[0:n_elements(y)-1]
      ;print,size(x)
      xlabel= 'Average Q'
      xunits ='A-1'
      index_title=""
   end
'DETECTOR PLOT': $
   begin
      dim='CUT'  ;always override
      ret = com_all[index]->get_property(display_name = display_name, xlabel=xlabel,$
                         xunits=xunits,histlabel=histlabel,comments=comments,$
                         plot_sums=plot_sums,q_props=q_props,angle_props=angle_props)
      y=plot_sums
      dy=sqrt(abs(y))

      x=indgen(n_elements(y))
      ;x=q_props[0:n_elements(y)-1]
      ;print,size(x)
      xlabel= 'Detector Number'
      xunits =''
      index_title=""
   end
'G(w)': $
   begin
      dim='CUT'  ;always override
      TEMP_ID = widget_info(self.tlb,find_by_uname = 'TDEF')
      widget_control,TEMP_ID,get_value=temperatures

      ret = com_all[index]->get_property(display_name = display_name,comments=comments)
      ;need to over ride...
      dodetailed=1

      type='GDOS'
       ret  = dcs_data->Scatter(type=type,$
                    temperatures=temperatures,dodeteff=dodeteff,dozeroenergy=dozeroenergy,$
                    dodetailed=dodetailed,qty=qty,err=err,$
                    xaxis=xaxis,xunits=xunits,xlabel=xlabel)
      x=xaxis
      y=qty
      dy=err
      histlabel='Summed g(w)'
      index_title=""


   end
'I(2th,t)': $
   begin
       ret = com_all[index]->get_property(display_name = display_name,comments=comments)
      ;get the index from the plotter
       slider_id = widget_info(self.tlb,find_by_uname = 'DCS_GROUP_SLIDER')
       widget_control,slider_id,get_value=index

       type='DODT'
       ret  = dcs_data->Scatter(type=type,dodetailed=dodetailed,$
                    temperatures=temperatures,dodeteff=dodeteff,dozeroenergy=dozeroenergy,$
                    qty=qty,err=err,qelmean=qelmean,tthmean=tthmean,$
                    xaxis=xaxis,xunits=xunits,xlabel=xlabel)
     if dim eq'CUT' then begin
       x=xaxis
       y=qty[*,index-1]
       dy=err[*,index-1]
       histlabel='Counts'
       index_title="mean !62!4h!6=" + strtrim(string(tthmean[index-1]),2)+'!E0!N'
     endif else begin
       x=xaxis[0:n_elements(xaxis)-2]    ;XXX WHY IS THIS 1001 elements?
       y=tthmean
       ylabel=xlabel
       xlabel='!3Scattering angle (!E0!N)'
       histlabel=''
       index_title="Image"
     endelse
   end
'I(2th,w)': $
   begin
       ret = com_all[index]->get_property(display_name = display_name,comments=comments)
      ;get the index from the plotter
       slider_id = widget_info(self.tlb,find_by_uname = 'DCS_GROUP_SLIDER')
       widget_control,slider_id,get_value=index

       type='DODE'
       ret  = dcs_data->Scatter(type=type,$
                    temperatures=temperatures,dodeteff=dodeteff,dozeroenergy=dozeroenergy,$
                    dodetailed=dodetailed,qty=qty,err=err,qelmean=qelmean,tthmean=tthmean,$
                    xaxis=xaxis,xunits=xunits,xlabel=xlabel)
     if dim eq'CUT' then begin
       x=xaxis
       y=qty[*,index-1]
       dy=err[*,index-1]
       histlabel='Counts'
       index_title="mean !62!4h!6=" + strtrim(string(tthmean[index-1]),2)+'!E0!N'
     endif else begin
       x=xaxis[0:n_elements(xaxis)-2]    ;XXX WHY IS THIS 1001 elements?
       y=tthmean
       ylabel=xlabel
       xlabel='!3Scattering angle (!E0!N)'
       histlabel=''
       index_title="Image"
     endelse
   end
'S(Q,w)': $
   begin
       ret = com_all[index]->get_property(display_name = display_name,comments=comments)
      ;get the index from the plotter
       slider_id = widget_info(self.tlb,find_by_uname = 'DCS_GROUP_SLIDER')
       widget_control,slider_id,get_value=index

       type='SSQW'
          TEMP_ID = widget_info(self.tlb,find_by_uname = 'TDEF')
            widget_control,TEMP_ID,get_value=temperatures
       ret  = dcs_data->Scatter(type=type,$
                    temperatures=temperatures,dodeteff=dodeteff,dozeroenergy=dozeroenergy,$
                    dodetailed=dodetailed,qty=qty,err=err,qelmean=qelmean,tthmean=tthmean,$
                    xaxis=xaxis,xunits=xunits,xlabel=xlabel)
     if dim eq'CUT' then begin
       x=xaxis
       y=qty[*,index-1]
       dy=err[*,index-1]
       histlabel='S(Q,omega)'
       index_title="mean Q_el=" + strtrim(string(Qelmean[index-1]),2)
     endif else begin
       x=xaxis[0:n_elements(xaxis)-2]    ;XXX WHY IS THIS 1001 elements?
       y=qelmean
       ylabel=xlabel
       xlabel='Q (A!E-1!N)'
       histlabel=''
       index_title="Image"
     endelse
   end
else:
endcase



;(f) generate a title
;   ret = com_all[index]->get_property(display_name = display_name, xlabel=xlabel,$
;                         xunits=xunits,histlabel=histlabel,comments=comments)
 ; if n_elements (comments) eq 0 then comments='unknown'
 ;  if n_elements (display_name) eq 0 then display_name='unknown'

   Result1 = STRSPLIT(comments,' ', /EXTRACT)
   Result2 = STRSPLIT( display_name,'_', /EXTRACT)
   if(xunits ne '') then begin
    xtitle=xlabel+' ('+xunits+')'
   endif else begin
    xtitle=xlabel
   endelse
   ytitle=histlabel
   title=Result2[0]+' '+Result1[0] +' :'+index_title

;check to see what range to use:
force_range=self.force_range
if force_range then begin
   xmin_id = widget_info(self.tlb,find_by_uname = 'DCS_XMIN')
   xmax_id = widget_info(self.tlb,find_by_uname = 'DCS_XMAX')
   ymin_id = widget_info(self.tlb,find_by_uname = 'DCS_YMIN')
   ymax_id = widget_info(self.tlb,find_by_uname = 'DCS_YMAX')

   widget_control,xmin_id,get_value=xmin
   if xmin eq '' then xmin = self.xrange[0]
   xmin=float(xmin)
   widget_control,xmax_id,get_value=xmax
   if xmax eq '' then xmax = self.xrange[1]
   xmax=float(xmax)
   widget_control,ymin_id,get_value=ymin
   if ymin eq '' then ymin = self.yrange[0]
   ymin=float(ymin)
   widget_control,ymax_id,get_value=ymax
   if ymax eq '' then ymax = self.yrange[1]
   ymax=float(ymax)

   self.xrange = [xmin,xmax]
   if xmin eq xmax then return,0
   self.yrange = [ymin,ymax]
   if ymin eq ymax then return,0

   endif
if dim eq 'CUT' then begin
  if KEYWORD_SET(scale) then begin
  ;skip
  endif else begin
    xmin = min(x,max = xmax) & ymin = min(y,max = ymax)
    if self.autoscale then begin
      if xmax eq xmin then delx=1.0 else delx = 0.2*(xmax-xmin)
      if ymax eq ymin then dely=1.0 else dely = 0.2*(ymax-ymin+max(dy))
      self.xrange = [xmin-delx,xmax+delx]
      self.yrange = [ymin-dely,ymax+dely]

    ; if the ranges are too small then the plot dies. limit x and y not to be equal
     if self.xrange[0] eq self.xrange[1] then self.xrange = [xmin-x,xmax+x]
     if self.yrange[0] eq self.yrange[1] then self.yrange = [ymin-y,ymax+y]
    endif
  endelse


;if y is a float single value here make it an array to plotit!
if size(y,/DIMENSIONS) eq 0 then y=[y]

  plot,x,y,psym = 0,xrange = self.xrange,yrange = self.yrange,/xsty,/ysty, /nodata,$
     xtitle =  xtitle,ytitle = ytitle,color = axis_color, $
     background = bg_color,title = title,position = position
  textBox = widget_info(self.tlb,find_by_uname="MASK")
  widget_control,textBox,get_value=tempString
  plotWidget = widget_info(self.tlb,find_by_uname="DCS_PLOT_SEL")
  plotType = widget_info(plotWidget,/combobox_gettext)
  if( ((*self.maskedX)[0] ne -1) && (plotType eq "DETECTOR PLOT") ) then begin
    ;help,*self.maskedX, /structure
    ;help,*self.maskedY, /structure
    oplot,[*self.maskedX],[*self.maskedY], color = (*self.color_ptr).red,psym = psym
  endif
  oplot,x,y,psym = psym,color = sym_color
  color_errplot,x,y-dy,y+dy,width = 0.0,color = sym_color

endif else begin

    uname = 'DCS_DESIRED_IMAGE_MAX'
    id = widget_info(self.tlb,find_by_uname = uname)
    widget_control,id,get_value = ivalue
    if n_elements(ivalue) eq 0 then ivalue = max(qty)
    uname = 'DCS_IMAGE_MAX'
    thisId = widget_info(self.tlb,find_by_uname = uname)
    widget_control,thisId,set_value = (max(qty))

    if self.autoScale then begin
     yrange = [min(x),max(x)]
     xrange = [min(y),max(y)]
    endif else begin
     xrange = self.xrange
     yrange = self.yrange
    endelse

    axis_color = (*self.color_ptr).white
    bg_color = (*self.color_ptr).black

    loadct,colortable,/silent
    contour,(transpose(qty) < ivalue),y,x,/fill, $
    nlevels = 30,$
    xtitle = xlabel, $
    ytitle = ylabel, $
    xrange = xrange,yrange = yrange, /xsty,/ysty



endelse
wset,self.winVis
device,copy = [0,0,!d.x_size,!d.y_size,0,0,self.winPix]

return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::refresh,event,IMAGE = image,XCOLOR = xcolor, $
   _Extra = extra
if keyword_set(image) then begin
   if not keyword_set(xcolor) then begin
      device,decomposed = 0
      loadct,15,/silent
   endif
   device,decomposed = self.dave_dc
   tvlct,(*self.dave_color_ptr).r,(*self.dave_color_ptr).g,(*self.dave_color_ptr).b
   empty
endif else begin
   device,decomposed = self.ddcs_dc
   tvlct,(*self.ddcs_color_ptr).r,(*self.ddcs_color_ptr).g,(*self.ddcs_color_ptr).b
   ret = self->update_plot(event,_Extra = extra)
;   device,decomposed = self.dave_dc
 ;  tvlct,(*self.dave_color_ptr).r,(*self.dave_color_ptr).g,(*self.dave_color_ptr).b
   empty
endelse
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::do_nothing,event
file_tree = self.file_tree
sel_id = widget_info(file_tree,/tree_select)
n_sel = n_elements(sel_id)
if n_sel ne 1 then return,0
if not widget_info(sel_id,/valid_id) then return,0
uname = widget_info(sel_id,/uname)
   if (uname eq 'SIGNAL_DATA_FOLDER') or (uname eq 'EMPTY_DATA_FOLDER') or $
      (uname eq 'ABSORBER_DATA_FOLDER') or $
      (uname eq 'VANADIUM_DATA_FOLDER') or (uname eq 'DARKCOUNT_DATA_FOLDER') or $
      (uname eq 'INTERMEDIATE_DATA_FOLDER') or (uname eq 'REDUCED_DATA_FOLDER') $
      then begin
      widget_control,self.fileinfo,set_value=''
   endif
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::checkForToolbar

; this method is called after the plot type changes or the
; reduce button is clicked.  It checks to see if the
; zoom, mask, and pan buttons should be disabled or not

    ; getting the values for the data that determines whether or not
    ; the buttons are diabled or not
    plotType = widget_info(self.tlb,find_by_uname = 'DCS_PLOT_SEL')
    plotTypeValue=widget_info(plotType,/combobox_gettext)
    ;noGroup = widget_info(self.tlb,find_by_uname="NO_DET_GROUP")
    ;noGroupValue=widget_info(noGroup,/button_set)
    ;combineNegPos= widget_info(self.tlb,find_by_uname="NEGPOS")
    ;combineNegPosValue=widget_info(combineNegPos,/button_set)

    ; get the ID's to the buttons themselves
    zoom_button = widget_info(self.tlb, find_by_uname="ZOOM_MODE")
    mask_button = widget_info(self.tlb, find_by_uname="MASK_MODE")
    pan_button = widget_info(self.tlb, find_by_uname="PAN_MODE")
    ; if values check out, enable buttons
    if(plotTypeValue eq "DETECTOR PLOT") then begin
       widget_control,zoom_button,sensitive=1
       widget_control,mask_button,sensitive=1
       widget_control,pan_button,sensitive=1
    ; otherwise, disable
    endif else begin
       widget_control,zoom_button,sensitive=1
       widget_control,zoom_button,/set_button
       ;and activate
       tempEvent2 =   { WIDGET_BUTTON,  $
                 ID:0,        $
                 top:0,         $
                 handler:0,       $
                 select:1   $
              }
       widget_control,zoom_button,send_Event=tempEvent2,/no_copy
       widget_control,mask_button,sensitive=0
       widget_control,pan_button,sensitive=0
    endelse
    return,0
end



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::reduce_data,event

log=''
;use this route if coming from the reduce button
; Which folder has been selected?
;print,widget_info(event.id,/uname)
;print,widget_info(event.top,/uname)
if widget_info(event.id,/uname) eq 'RED_BUTTON' then begin
  file_tree = self.file_tree
  ; is there any dcs data in the file_tree?
  this_id = widget_info(file_tree,/tree_select)
  if not widget_info(this_id,/valid_id) then begin
  ; Find the first reduction group id
     ret=self->update_status('Load files first...')
     return,0
  endif else begin
  red_id = widget_info(file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
  ;widget_control,red_id,/set_tree_select
  widget_control,red_id,get_uvalue = uval
  if not obj_valid(uval.dcs_object) then begin
     ret=self->update_status('Load files first...')
     return,0
  endif

  ret = self->update_status('Reducing data')
  dcs_data = uval.dcs_object
  endelse
endif else begin   ; or this route if coming from the tree
  file_tree = self.file_tree
  sel_id = widget_info(file_tree,/tree_select)
  n_sel = n_elements(sel_id)
  if n_sel ne 1 then return,0
  if not widget_info(sel_id,/valid_id) then return,0
  uname = widget_info(sel_id,/uname)
  if uname ne 'REDUCTION_GROUP_FOLDER' then return,0
  red_id = sel_id
  widget_control,red_id,get_uvalue = uval
  if not obj_valid(uval.dcs_object) then begin
     strout = 'No files have been loaded yet'
     void = dialog_message(dialog_parent = event.top,strout,/information, $
        title = 'DCS Reduction Error')
     return,0
  endif
  ret = self->update_status('Reducing data')
  dcs_data = uval.dcs_object

endelse

;get then NORMALIZATION value if desired
n_id = widget_info(event.top,find_by_uname = 'USE_NORMALIZATION')
widget_control,n_id,get_value=use_norm
if use_norm eq 0 then begin
    ;i.e. by time
    norm=7
endif else begin
    norm=2
endelse
;these are chosen to fit with John Copley's reduction style

;get then darkcount value if desired
ud_id = widget_info(event.top,find_by_uname = 'USE_DARKCOUNT_ARRAY')
widget_control,ud_id,get_value=use_dark
if use_dark eq 0 then begin
    ;i.e. we will use the values given
    dark=[self.dark,self.darkerr]
endif else begin
    dark=[0.0,0.0]
endelse

;check file associations and their groups
ret = dcs_data->check_contents()

;clear the intermediate files and the leaves
ret = self->update_status('Clearing Additional Data')

int_id = widget_info(red_id,find_by_uname = 'INTERMEDIATE_FILE')
while int_id gt 0 do begin
  int_id = widget_info(red_id,find_by_uname = 'INTERMEDIATE_FILE')
     if int_id gt 0 then begin
              widget_control,int_id,/destroy
     endif
endwhile

;clear the corrected files and the leaves
com_id = widget_info(red_id,find_by_uname = 'CORRECTED_FILE')
while com_id gt 0 do begin
  com_id = widget_info(red_id,find_by_uname = 'CORRECTED_FILE')
     if com_id gt 0 then begin
              widget_control,com_id,/destroy
     endif
endwhile

;some more clearings
ret = dcs_data->clear_int()
ret = dcs_data->clear_com()

;get the vanarr value if desired
ud_id = widget_info(event.top,find_by_uname = 'USE_VAN_ARRAY')
widget_control,ud_id,get_value=use_vanarr
if use_vanarr eq 0 then begin
    ;i.e. we will use the values given
    vanarr=self.vanarr
    if total(self.vanarr) eq 913 then vanarr=0
    ret = self->update_status('Using efficiency array given')
endif else begin
    vanarr=0
endelse

;get the Q info
ud_id = widget_info(event.top,find_by_uname = 'NO_DET_GROUP')
no_det_grouping=widget_info(ud_id,/button_set)

;Combine negative and positive angle detectors
ud_id = widget_info(event.top,find_by_uname = 'NEGPOS')
NEGPOS=widget_info(ud_id,/button_set)
ud_id = widget_info(event.top,find_by_uname = 'LOMIUP') ;Combine lower, middle and upper banks
LOMIUP=widget_info(ud_id,/button_set)
ud_id = widget_info(event.top,find_by_uname = 'LOWUPP') ;Combine lower and upper banks only
LOWUPP=widget_info(ud_id,/button_set)
ud_id = widget_info(event.top,find_by_uname = 'DONOTC') ;Do not combine detector banks
DONOTC=widget_info(ud_id,/button_set)
ud_id = widget_info(event.top,find_by_uname = 'EQUAL2')
EQUAL2=widget_info(ud_id,/button_set)
ud_id = widget_info(event.top,find_by_uname = 'EQUALQ')
EQUALQ=widget_info(ud_id,/button_set)
ud_id = widget_info(event.top,find_by_uname = 'TTSTEP')
widget_control,ud_id,get_value=TTSTEP
if float(TTSTEP) lt 1 then begin
   TTSTEP = '1'
   widget_control,ud_id,set_value=TTSTEP
endif
ud_id = widget_info(event.top,find_by_uname = 'QSTEP')
widget_control,ud_id,get_value=QSTEP
if float(QSTEP) lt 0.01 then begin
   QSTEP = '0.01'
   widget_control,ud_id,set_value=string(QSTEP)
endif

; if the DETECTOR PLOT mode is selected from the drop down, set
; no_det_grouping and NEGPOS to 1 and 0, respectively
plottype_id = widget_info(self.tlb,find_by_uname = 'DCS_PLOT_SEL')
plottype=widget_info(plottype_id,/combobox_gettext)
if (plottype eq "DETECTOR PLOT") then begin
    no_det_grouping = 1
    NEGPOS = 0
endif

q_group={no_det_grouping:no_det_grouping,NEGPOS:NEGPOS,LOMIUP:LOMIUP,LOWUPP:LOWUPP,DONOTC:DONOTC,$
        EQUAL2:EQUAL2, EQUALQ:EQUALQ, TTSTEP:TTSTEP, QSTEP:QSTEP}
;
; *self.mask_ptr
if n_elements(*self.mask_ptr) gt 1 then begin
    mask=*self.mask_ptr
endif else begin
    mask=intarr[913]+1
endelse

if n_elements(*self.sff_ptr) gt 1 then begin
   ;check if we want to use the array
   sff_id = widget_info(event.top,find_by_uname = 'USE_SSF_ARRAY')
   widget_control,sff_id,get_value=use
   if use eq 1 then begin
      attenuation=self.attenuation
   endif else begin
      ;really should be the array, but for now...
      attenuation=*self.sff_ptr
   endelse
endif else begin
   attenuation = self.attenuation
endelse

slider=-1
ro  = dcs_data->reduce( mask=mask, $
                        msg=msg,             $
                        dark=dark,        $
                        vanarr = vanarr,     $
                        q_group = q_group,   $
                        no_det_grouping=no_det_grouping,$
                        attenuation = attenuation,$
                        norm=norm,           $
                        log=log,$
                        slider=slider)

ret = self->update_status('Finished Reducing')
if 'Done!' ne string(ro) then begin
   void = dialog_message(dialog_parent = event.top,msg,title = 'DCS Reduction Error')
   return,0
endif
;make the grouping slider current size of data dimensions

;XXX MAKE SURE OF THIS DIMENSION! ngroups-1?
;current size is:
slider_id = widget_info(self.tlb,find_by_uname = 'DCS_GROUP_SLIDER')
current_size=widget_info(slider_id,/slider_min_max)
;if slider is different update:
if current_size[1] ne slider then begin
   widget_control,slider_id,set_value=current_size[0]
   widget_control,slider_id,set_slider_max=slider
endif

; check what was put in the intermediate container.
int_id = widget_info(red_id,find_by_uname = 'INTERMEDIATE_DATA_FOLDER')
ret = dcs_data->get_property(intermediate = int_container)
   n_int = int_container->count()
   if n_int gt 0 then begin
      int_all = int_container->get(/all)
      for i = 0,n_elements(int_all)-1 do begin
         if obj_valid(int_all[i]) then begin
         ret = int_all[i]->get_property(display_name = display_name)
         ; get the average temperature for the GUI
         ;actually make that the setpoint.
         if display_name eq 'SUMMED_SIGNAL' then begin
            ret = int_all[i]->get_property(temp_sample=temp_sample,temp_setpoint=temp_setpoint)
            t_id = widget_info(event.top,find_by_uname = 'TDEF')
            widget_control,t_id,get_value=test
            if test eq "" then widget_control,t_id,set_value=temp_setpoint
         endif
         data_leaf = widget_tree(int_id,value = display_name,        $
                     uname = 'INTERMEDIATE_FILE',                    $
                    ; bitmap = *self.file_icon,                       $
                     uvalue = {  object:self,                        $
                                 method:'select_data',               $
                                 data_object:int_all[i]              })
         endif
      endfor
   endif

; check what was put in the CORRECTED container.
com_id = widget_info(red_id,find_by_uname = 'CORRECTED_DATA_FOLDER')
ret = dcs_data->get_property(CORRECTED = com_container)
   c_int = com_container->count()
   if c_int gt 0 then begin
      com_all = com_container->get(/all)
      for i = 0,n_elements(com_all)-1 do begin
         if obj_valid(com_all[i]) then begin
         ret = com_all[i]->get_property(display_name = display_name)
         data_leaf = widget_tree(com_id,value = display_name,        $
                     uname = 'CORRECTED_FILE',                    $
                    ; bitmap = *self.file_icon,                       $
                     uvalue = {  object:self,                        $
                                 method:'select_data',               $
                                 data_object:com_all[i]              })
         endif
      endfor
   endif

ret=self->update_plot()



void = self->checkForToolbar()

ret = self->update_status('Reduction complete')
return,1
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::load_mask,event
    filename = dialog_pickfile(path=self.work_dir, title="Select Mask File")
    if filename eq '' then return,0

    catch, error
    if (error ne 0) then begin
       void = dialog_message("The file you selected is not a valid mask file.")
       return, 0
    endif
    restore, filename
    catch,/cancel
    textBox = widget_info(event.top,find_by_uname="MASK")
    widget_control,textBox,set_value=storedMask
    return,0
end



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::load_signal_files,event
; Pop up the file browser and allow the user to select a file
file_tree = self.file_tree
files = dialog_pickfile(dialog_parent = event.top,path = self.data_dir,    $
    filter=['*.dcs.gz','*.dcs'], $
   title = 'dcs data selection',/multiple_files, get_path = this_path,  $
   display_name = 'Select one or more dcs "signal" files to load')
if files[0] eq '' then return,0

str = 'Loading signal files in...'
ret = self->update_status(str)

self.data_dir=file_dirname(files[0],/MARK_DIRECTORY)

nfiles = n_elements(files)
files = files[sort(files)]
settozero=0

;check to see if the file was already in the list by comparing filenames.
;needs working on
; Is there a REDUCTION GROUP folder selected?
this_id = widget_info(file_tree,/tree_select)
if n_elements(this_id) gt 1 then begin
   return,0
endif
if not widget_info(this_id,/valid_id) then begin
; Find the first reduction group id
   red_id = widget_info(file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
   widget_control,red_id,/set_tree_select
endif else begin
   uname = widget_info(this_id,/uname)
   if (uname eq 'SIGNAL_DATA_FOLDER') or (uname eq 'SIGNAL_FILE')$
      then begin
         widget_control,this_id,get_uvalue = uval
         red_id = uval.parent
   endif
   if (uname eq 'REDUCTION_GROUP_FOLDER') then red_id = this_id
endelse
widget_control,red_id,get_uvalue = uval
if obj_valid(uval.dcs_object) then begin
   ret=uval.dcs_object->get_property(SIGNAL=signal)
   os=signal->get(/all)
   if (n_elements(os) ge 1) and (obj_valid(os[0])) then begin
      oldfiles=strarr(n_elements(os))
      for  i=0,n_elements(os)-1 do begin
         ret=os[i]->get_property(filename=filename)
         oldfiles[i]=filename
      endfor
      for i=0,n_elements(files)-1 do begin

      test=where(oldfiles eq files[i], count)
         if count ge 1 then begin
            if n_elements(files) eq 1 then return,0
            files[i]=''
            settozero=settozero+1
         endif
      endfor
   endif
endif


;reset the object array size
nnfiles=nfiles-settozero
if nnfiles eq 0 then return,0
oarray = objarr(nnfiles)
obj_increment = 0
for i = 0,nfiles-1 do begin
   ; Create the dcs data objects and read them in
      if (files[i] ne '') then begin
         o = obj_new('ddcs_data',filename = files[i],nhedet=self.nhedet, ntchan =self.ntchan, $
                   signal_type = 'SIGNAL',/read)
         if obj_valid(o) then begin
            ret = o->sanity_check(value=0)
            oarray[obj_increment] = o
            obj_increment = obj_increment + 1
         endif
      endif
endfor
if obj_increment lt 1 then begin
   str = 'File loading failure'
   ret = self->update_status(str)
   return,0
endif
self.data_dir = this_path
oarray = oarray[0:obj_increment-1]

; Is there a REDUCTION GROUP folder selected?
this_id = widget_info(file_tree,/tree_select)
if n_elements(this_id) gt 1 then begin
   obj_destroy,oarray
   str = 'File loading failure'
   ret = self->update_status(str)
   return,0
endif

if not widget_info(this_id,/valid_id) then begin
; Find the first reduction group id
   red_id = widget_info(file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
   widget_control,red_id,/set_tree_select
endif else begin
   uname = widget_info(this_id,/uname)
   if (uname eq 'SIGNAL_DATA_FOLDER') or (uname eq 'EMPTY_DATA_FOLDER') or $
      (uname eq 'ABSORBER_DATA_FOLDER') or $
      (uname eq 'VANADIUM_DATA_FOLDER') or (uname eq 'DARKCOUNT_DATA_FOLDER') or $
      (uname eq 'INTERMEDIATE_DATA_FOLDER') or (uname eq 'REDUCED_DATA_FOLDER') $
      then begin
         widget_control,this_id,get_uvalue = uval
         red_id = uval.parent
   endif
   if (uname eq 'REDUCTION_GROUP_FOLDER') then red_id = this_id
endelse

widget_control,red_id,get_uvalue = uval
if obj_valid(uval.dcs_object) then begin
   ret = uval.dcs_object->add(oarray)
   dcs_data = uval.dcs_object
endif else begin
   dcs_data = obj_new('ddcs_reduce',oarray,group_leader=self.tlb)
   uval.dcs_object = dcs_data
endelse
widget_control,red_id,set_uvalue = uval
self.dcs_container->add,dcs_data
; Now create the data "leaves" and stuff a reference to the data object
; into the file
for i=0,nnfiles-1 do begin
   ret = oarray[i]->get_property(display_name = display_name)
   signal_id = widget_info(red_id,find_by_uname = 'SIGNAL_DATA_FOLDER')
   data_leaf = widget_tree(signal_id,value = display_name,     $
               uname = 'SIGNAL_FILE',                          $
               ;bitmap = *self.file_icon,                       $
               uvalue = {  object:self,                        $
                           method:'select_data',               $
                           data_object:oarray[i],              $
                           parent:red_id                       })
endfor
str = 'Signal files loaded'
ret = self->update_status(str)
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::load_vanadium_files,event
; Pop up the file browser and allow the user to select a file
file_tree = self.file_tree
files = dialog_pickfile(dialog_parent = event.top,path = self.data_dir,    $
    filter=['*.dcs.gz','*.dcs'], $
   title = 'vanadium data selection',/multiple_files, get_path = this_path,  $
   display_name = 'Select one or more dcs "Vanadium" container files to load')
if files[0] eq '' then return,0
str = 'Loading vanadium files'
ret = self->update_status(str)
self.data_dir=file_dirname(files[0],/MARK_DIRECTORY)

nfiles = n_elements(files)
files = files[sort(files)]
oarray = objarr(nfiles)

obj_increment = 0
for i = 0,nfiles-1 do begin
   ; Create the dcs data objects and read them in
      if (files[i] ne '') then begin
         o = obj_new('ddcs_data',filename = files[i],nhedet=self.nhedet, ntchan =self.ntchan, $
                   signal_type = 'VANADIUM',/read)
         if obj_valid(o) then begin
            ret = o->sanity_check(value=0)
            oarray[obj_increment] = o
            obj_increment = obj_increment + 1
         endif
      endif
endfor


; Is there a REDUCTION GROUP folder selected?
this_id = widget_info(file_tree,/tree_select)
if n_elements(this_id) gt 1 then begin
   str = 'File loading failure'
   ret = self->update_status(str)
   obj_destroy,oarray
   return,0
endif
self.data_dir = this_path
if not widget_info(this_id,/valid_id) then begin
; Find the first reduction group id
   red_id = widget_info(file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
   widget_control,red_id,/set_tree_select
endif else begin
   uname = widget_info(this_id,/uname)
   if (uname eq 'SIGNAL_DATA_FOLDER') or (uname eq 'EMPTY_DATA_FOLDER') or $
      (uname eq 'ABSORBER_DATA_FOLDER') or $
      (uname eq 'VANADIUM_DATA_FOLDER') or (uname eq 'DARKCOUNT_DATA_FOLDER') or $
      (uname eq 'INTERMEDIATE_DATA_FOLDER') or (uname eq 'REDUCED_DATA_FOLDER') or $
      (uname eq 'SIGNAL_FILE') or (uname eq 'EMPTY_FILE') or $
      (uname eq 'VANADIUM_FILE') or (uname eq 'DARKCOUNT_FILE') or $
      (uname eq 'REDUCED_FILE') or (uname eq 'INTERMEDIATE_FILE') or $
      (uname eq 'ABSORBER_FILE')  $
      then begin
         widget_control,this_id,get_uvalue = uval
         red_id = uval.parent
   endif
   if (uname eq 'REDUCTION_GROUP_FOLDER') then red_id = this_id
endelse

widget_control,red_id,get_uvalue = uval
if obj_valid(uval.dcs_object) then begin
   ret = uval.dcs_object->add(oarray)
   dcs_data = uval.dcs_object
endif else begin
   dcs_data = obj_new('ddcs_reduce',oarray,group_leader=self.tlb)
   uval.dcs_object = dcs_data
endelse
widget_control,red_id,set_uvalue = uval
self.dcs_container->add,dcs_data
; Now create the data "leaves" and stuff a reference to the data object
; into the file
for i=0,nfiles-1 do begin
   ret = oarray[i]->get_property(display_name = display_name)
   van_id = widget_info(red_id,find_by_uname = 'VANADIUM_DATA_FOLDER')
   data_leaf = widget_tree(van_id,value = display_name,     $
               uname = 'VANADIUM_FILE',                           $
               ;bitmap = *self.file_icon,                       $
               uvalue = {  object:self,                        $
                           method:'select_data',               $
                           data_object:oarray[i]               })
endfor
str = 'Vanadium files loaded'
ret = self->update_status(str)
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::load_darkcount_files,event
; Pop up the file browser and allow the user to select a file
file_tree = self.file_tree
files = dialog_pickfile(dialog_parent = event.top,path = self.data_dir,    $
    filter=['*.dcs.gz','*.dcs'], $
   title = 'darkcount data selection',/multiple_files, get_path = this_path,  $
   display_name = 'Select one or more dcs "Dark Count" container files to load')
if files[0] eq '' then return,0
str = 'Loading dark count files'
ret = self->update_status(str)
self.data_dir=file_dirname(files[0],/MARK_DIRECTORY)

nfiles = n_elements(files)
files = files[sort(files)]
oarray = objarr(nfiles)
obj_increment = 0
for i = 0,nfiles-1 do begin
   ; Create the dcs data objects and read them in
      if (files[i] ne '') then begin
         o = obj_new('ddcs_data',filename = files[i],nhedet=self.nhedet, ntchan =self.ntchan, $
                   signal_type = 'DARKCOUNT',/read)
         if obj_valid(o) then begin
            ret = o->sanity_check(value=0)
            oarray[obj_increment] = o
            obj_increment = obj_increment + 1
         endif
      endif
endfor

; Is there a REDUCTION GROUP folder selected?
this_id = widget_info(file_tree,/tree_select)
if n_elements(this_id) gt 1 then begin
   str = 'File loading failure'
   ret = self->update_status(str)
   obj_destroy,oarray
   return,0
endif
self.data_dir = this_path
if not widget_info(this_id,/valid_id) then begin
; Find the first reduction group id
   red_id = widget_info(file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
   widget_control,red_id,/set_tree_select
endif else begin
   uname = widget_info(this_id,/uname)
   if (uname eq 'SIGNAL_DATA_FOLDER') or (uname eq 'EMPTY_DATA_FOLDER') or $
      (uname eq 'ABSORBER_DATA_FOLDER') or $
      (uname eq 'VANADIUM_DATA_FOLDER') or (uname eq 'DARKCOUNT_DATA_FOLDER') or $
      (uname eq 'INTERMEDIATE_DATA_FOLDER') or (uname eq 'REDUCED_DATA_FOLDER') or $
      (uname eq 'SIGNAL_FILE') or (uname eq 'EMPTY_FILE') or $
      (uname eq 'VANADIUM_FILE') or (uname eq 'DARKCOUNT_FILE') or $
      (uname eq 'REDUCED_FILE') or (uname eq 'INTERMEDIATE_FILE') or $
      (uname eq 'ABSORBER_FILE')  $
      then begin
         widget_control,this_id,get_uvalue = uval
         red_id = uval.parent
   endif
   if (uname eq 'REDUCTION_GROUP_FOLDER') then red_id = this_id
endelse

widget_control,red_id,get_uvalue = uval
if obj_valid(uval.dcs_object) then begin
   ret = uval.dcs_object->add(oarray)
   dcs_data = uval.dcs_object
endif else begin
   dcs_data = obj_new('ddcs_reduce',oarray,group_leader=self.tlb)
   uval.dcs_object = dcs_data
endelse
widget_control,red_id,set_uvalue = uval
self.dcs_container->add,dcs_data
; Now create the data "leaves" and stuff a reference to the data object
; into the file
for i=0,nfiles-1 do begin
   ret = oarray[i]->get_property(display_name = display_name)
   dark_id = widget_info(red_id,find_by_uname = 'DARKCOUNT_DATA_FOLDER')
   data_leaf = widget_tree(dark_id,value = display_name,     $
               uname = 'DARKCOUNT_FILE',                           $
               ;bitmap = *self.file_icon,                       $
               uvalue = {  object:self,                        $
                           method:'select_data',               $
                           data_object:oarray[i]               })
endfor
str = 'Dark Count files loaded'
ret = self->update_status(str)
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::load_absorber_files,event
; Pop up the file browser and allow the user to select a file
file_tree = self.file_tree
files = dialog_pickfile(dialog_parent = event.top,path = self.data_dir,    $
    filter=['*.dcs.gz','*.dcs'], $
   title = 'absorber data selection',/multiple_files, get_path = this_path,  $
   display_name = 'Select one or more dcs "Absorber" container files to load')
if files[0] eq '' then return,0
str = 'Loading absorber files'
ret = self->update_status(str)
self.data_dir=file_dirname(files[0],/MARK_DIRECTORY)

nfiles = n_elements(files)
files = files[sort(files)]
oarray = objarr(nfiles)
obj_increment = 0
for i = 0,nfiles-1 do begin
   ; Create the dcs data objects and read them in
      if (files[i] ne '') then begin
         o = obj_new('ddcs_data',filename = files[i],nhedet=self.nhedet, ntchan =self.ntchan, $
                   signal_type = 'ABSORBER',/read)
         if obj_valid(o) then begin
            ret = o->sanity_check(value=0)
            oarray[obj_increment] = o
            obj_increment = obj_increment + 1
         endif
      endif
endfor

; Is there a REDUCTION GROUP folder selected?
this_id = widget_info(file_tree,/tree_select)
if n_elements(this_id) gt 1 then begin
   str = 'File loading failure'
   ret = self->update_status(str)
   obj_destroy,oarray
   return,0
endif
self.data_dir = this_path
if not widget_info(this_id,/valid_id) then begin
; Find the first reduction group id
   red_id = widget_info(file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
   widget_control,red_id,/set_tree_select
endif else begin
   uname = widget_info(this_id,/uname)
   if (uname eq 'SIGNAL_DATA_FOLDER') or (uname eq 'EMPTY_DATA_FOLDER') or $
      (uname eq 'ABSORBER_DATA_FOLDER') or $
      (uname eq 'VANADIUM_DATA_FOLDER') or (uname eq 'DARKCOUNT_DATA_FOLDER') or $
      (uname eq 'INTERMEDIATE_DATA_FOLDER') or (uname eq 'REDUCED_DATA_FOLDER') or $
      (uname eq 'SIGNAL_FILE') or (uname eq 'EMPTY_FILE') or $
      (uname eq 'VANADIUM_FILE') or (uname eq 'DARKCOUNT_FILE') or $
      (uname eq 'REDUCED_FILE') or (uname eq 'INTERMEDIATE_FILE') or $
      (uname eq 'ABSORBER_FILE')  $
      then begin
         widget_control,this_id,get_uvalue = uval
         red_id = uval.parent
   endif
   if (uname eq 'REDUCTION_GROUP_FOLDER') then red_id = this_id
endelse

widget_control,red_id,get_uvalue = uval
if obj_valid(uval.dcs_object) then begin
   ret = uval.dcs_object->add(oarray)
   dcs_data = uval.dcs_object
endif else begin
   dcs_data = obj_new('ddcs_reduce',oarray,group_leader=self.tlb)
   uval.dcs_object = dcs_data
endelse
widget_control,red_id,set_uvalue = uval
self.dcs_container->add,dcs_data
; Now create the data "leaves" and stuff a reference to the data object
; into the file
for i=0,nfiles-1 do begin
   ret = oarray[i]->get_property(display_name = display_name)
   absorber_id = widget_info(red_id,find_by_uname = 'ABSORBER_DATA_FOLDER')
   data_leaf = widget_tree(absorber_id,value = display_name,     $
               uname = 'ABSORBER_FILE',                           $
               ;bitmap = *self.file_icon,                       $
               uvalue = {  object:self,                        $
                           method:'select_data',               $
                           data_object:oarray[i]               })
endfor
str = 'Absorber files loaded'
ret = self->update_status(str)
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::load_empty_files,event
; Pop up the file browser and allow the user to select a file
file_tree = self.file_tree
files = dialog_pickfile(dialog_parent = event.top,path = self.data_dir,    $
    filter=['*.dcs.gz','*.dcs'], $
   title = 'dcs empty data selection',/multiple_files, get_path = this_path,  $
   display_name = 'Select one or more dcs "Empty" container files to load')
if files[0] eq '' then return,0
str = 'Loading empty files'
self.data_dir=file_dirname(files[0],/MARK_DIRECTORY)

ret = self->update_status(str)
nfiles = n_elements(files)
files = files[sort(files)]
oarray = objarr(nfiles)
obj_increment = 0
for i = 0,nfiles-1 do begin
   ; Create the dcs data objects and read them in
      if (files[i] ne '') then begin
         o = obj_new('ddcs_data',filename = files[i],nhedet=self.nhedet, ntchan =self.ntchan, $
                   signal_type = 'EMPTY',/read)
         if obj_valid(o) then begin
            ret = o->sanity_check(value=0)
            oarray[obj_increment] = o
            obj_increment = obj_increment + 1
         endif
      endif
endfor

; Is there a REDUCTION GROUP folder selected?
this_id = widget_info(file_tree,/tree_select)
if n_elements(this_id) gt 1 then begin
   str = 'File loading failure'
   ret = self->update_status(str)
   obj_destroy,oarray
   return,0
endif
self.data_dir = this_path
if not widget_info(this_id,/valid_id) then begin
; Find the first reduction group id
   red_id = widget_info(file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
   widget_control,red_id,/set_tree_select
endif else begin
   uname = widget_info(this_id,/uname)
   if (uname eq 'SIGNAL_DATA_FOLDER') or (uname eq 'EMPTY_DATA_FOLDER') or $
      (uname eq 'ABSORBER_DATA_FOLDER') or $
      (uname eq 'VANADIUM_DATA_FOLDER') or (uname eq 'DARKCOUNT_DATA_FOLDER') or $
      (uname eq 'INTERMEDIATE_DATA_FOLDER') or (uname eq 'REDUCED_DATA_FOLDER') $
      (uname eq 'SIGNAL_FILE') or (uname eq 'EMPTY_FILE') or $
      (uname eq 'VANADIUM_FILE') or (uname eq 'DARKCOUNT_FILE') or $
      (uname eq 'REDUCED_FILE') or (uname eq 'INTERMEDIATE_FILE') or $
      (uname eq 'ABSORBER_FILE') $
      then begin
         widget_control,this_id,get_uvalue = uval
         red_id = uval.parent
   endif
   if (uname eq 'REDUCTION_GROUP_FOLDER') then red_id = this_id
endelse

widget_control,red_id,get_uvalue = uval
if obj_valid(uval.dcs_object) then begin
   ret = uval.dcs_object->add(oarray)
   dcs_data = uval.dcs_object
endif else begin
   dcs_data = obj_new('ddcs_reduce',oarray,group_leader=self.tlb)
   uval.dcs_object = dcs_data
endelse
widget_control,red_id,set_uvalue = uval
self.dcs_container->add,dcs_data
; Now create the data "leaves" and stuff a reference to the data object
; into the file
for i=0,nfiles-1 do begin
   ret = oarray[i]->get_property(display_name = display_name)
   empty_id = widget_info(red_id,find_by_uname = 'EMPTY_DATA_FOLDER')
   data_leaf = widget_tree(empty_id,value = display_name,      $
               uname = 'EMPTY_FILE',                           $
               ;bitmap = *self.file_icon,                      $
               uvalue = {  object:self,                        $
                           method:'select_data',               $
                           data_object:oarray[i]               })
endfor
str = 'Background files loaded'
ret = self->update_status(str)
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::load_SSF_array,event
ssffile = dialog_pickfile(dialog_parent = event.top,path = self.data_dir,    $
    filter=['*.txt','*.dat'], $
   title = 'Self Shielding factor File', get_path = this_path,  $
   display_name = 'Select a file to load')
if ssffile eq '' then return,0

str = 'Loading self shielding factors in...'
ret = self->update_status(str)

header = strarr(15)
dumstr=  fltarr(7)
tmp=fltarr(100000,7)
j=0
openr,lun,ssffile,/get_lun
readf,lun,header
WHILE (NOT EOF(lun)) DO BEGIN
     readf,lun,dumstr
     tmp[j,*]=dumstr
     j=j+1
ENDWHILE
free_lun,lun,/force

sffarr=tmp[0:j-1,*]
;Angle, SSF, fcsc, fcc, SAF, tS, tC
;The interesting values are 0,1 and 4

*self.sff_ptr=sffarr

return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::load_van_array,event
print,"should load a file and check it here"
print,"Get a linear vector of 913 (nhedet) values. if not enough values make them unity"


vfile = dialog_pickfile(dialog_parent = event.top,path = self.data_dir,    $
    filter=['*.txt','*.dat'], $
   title = '1D vector for Vanadium', get_path = this_path,  $
   display_name = 'Select one "vanadium normalization" file to load')
if vfile eq '' then return,0

str = 'Loading vanadium normalization file in...'
ret = self->update_status(str)

;if the elements dont fit into 913, then
;make the rest unity

van=self.vanarr

i=0
openr,lun,vfile,/get_lun
WHILE (NOT EOF(lun)) DO BEGIN
   readf,lun,dumstr
   if dumstr ne '' then begin
      van[i]=float(dumstr)
      i=i+1
   endif
ENDWHILE
free_lun,lun,/force

self.vanarr=van
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::set_darkcount_rate,event
value=event.value
if value lt 0.0 then begin
    value=-value
    widget_control,event.id,set_value=value
endif
if value eq 0 then begin
    value=0.0
    widget_control,event.id,set_value=value
endif
;update new values
self.dark=value
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::set_attenuation,event
value=event.value
;if value eq 0 then begin
;    value=0.0
;    widget_control,event.id,set_value=value
;endif
;update new values
self.attenuation=value
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::set_darkerr_rate,event
value=event.value
if value lt 0.0 then begin
    value=-value
    widget_control,event.id,set_value=value
endif
if value eq 0 then begin
    value=0.0
    widget_control,event.id,set_value=value
endif
;update new values
self.darkerr=value
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::context_events,event
; Which child has been selected?
sel_id = widget_info(event.id,/tree_select)
n_sel = n_elements(sel_id)
if not widget_info(sel_id[0],/valid_id) then return,0
unames = strarr(n_sel)
for i = 0,n_sel-1 do unames[i] = widget_info(sel_id[i],/uname)
if n_elements(uniq(unames)) eq 1 then begin
   uname = unames[0]
   case uname of
   'REDUCTION_GROUP_FOLDER':   $
      begin
         context_base = widget_info(event.top,find_by_uname = 'REDUCTION_GROUP_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'SIGNAL_FILE':   $
      begin
         context_base = widget_info(event.top,find_by_uname = 'SIGNAL_DATA_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'ABSORBER_FILE':   $
      begin
         context_base = widget_info(event.top,find_by_uname = 'ABSORBER_DATA_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'EMPTY_FILE':   $
      begin
         context_base = widget_info(event.top,find_by_uname = 'EMPTY_DATA_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'VANADIUM_FILE':   $
      begin
         context_base = widget_info(event.top,find_by_uname = 'VANADIUM_DATA_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
    'DARKCOUNT_FILE':   $
      begin
         context_base = widget_info(event.top,find_by_uname = 'DARKCOUNT_DATA_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'SIGNAL_DATA_FOLDER': $
      begin
         context_base = widget_info(event.top,find_by_uname = 'SIGNAL_FOLDER_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'EMPTY_DATA_FOLDER': $
      begin
         context_base = widget_info(event.top,find_by_uname = 'EMPTY_FOLDER_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'VANADIUM_DATA_FOLDER': $
      begin
         context_base = widget_info(event.top,find_by_uname = 'VANADIUM_FOLDER_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'DARKCOUNT_DATA_FOLDER': $
      begin
         context_base = widget_info(event.top,find_by_uname = 'DARKCOUNT_FOLDER_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'CORRECTED_DATA_FOLDER': $
      begin
         context_base = widget_info(event.top,find_by_uname = 'CORRECTED_FOLDER_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'INTERMEDIATE_DATA_FOLDER': $
      begin
         context_base = widget_info(event.top,find_by_uname =  $
            'INTERMEDIATE_FOLDER_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'ABSORBER_DATA_FOLDER': $
      begin
         context_base = widget_info(event.top,find_by_uname = 'ABSORBER_FOLDER_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'INTERMEDIATE_FILE': $
      begin
         context_base = widget_info(event.top,find_by_uname = 'INTERMEDIATE_DATA_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   'CORRECTED_FILE': $
      begin
         context_base = widget_info(event.top,find_by_uname = 'CORRECTED_DATA_MENU')
         widget_displaycontextmenu, event.id, event.x, event.y, context_base
      end
   else:
   endcase
endif else begin
; Now we want to display a context-sensitive menu that appears when multiple
; file tabs are selected from different folders.
   sel_names = unames[uniq(unames)]
   red_index = where(unames eq 'REDUCED_FILE',count_red)
   int_index = where(unames eq 'INTERMEDIATE_FILE',count_int)
   absorber_index = where(unames eq 'ABSORBER_FILE',count_int)
   van_index = where(unames eq 'VANADIUM_FILE',count_van)
   dark_index = where(unames eq 'DARKCOUNT_FILE',count_dark)
   sig_index = where(unames eq 'SIGNAL_FILE',count_sig)
   bg_index = where(unames eq 'EMPTY_FILE',count_bg)
   tot_good_file_types = count_red+count_int+count_sig+count_bg+count_van+count_dark
   if (tot_good_file_types eq 0) or $
      (tot_good_file_types lt n_elements(unames)) then return,0
   context_base = widget_info(event.top,find_by_uname = 'MULTIPLE_FILES_MENU')
   widget_displaycontextmenu, event.id, event.x, event.y, context_base
endelse
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::dcs_delete_files,event
; Which files were selected?
file_tree_id = self.file_tree
if not widget_info(file_tree_id,/valid_id) then return,0
; Determine if any of the children of FILE_TREE were selected
sel_id = widget_info(file_tree_id,/tree_select)
n_sel = n_elements(sel_id)
if not widget_info(sel_id[0],/valid_id) then return,0
uname = widget_info(sel_id[0],/uname)
if (uname eq 'SIGNAL_FILE') or   $
   (uname eq 'DARKCOUNT_FILE') or  $
   (uname eq 'ABSORBER_FILE') or  $
   (uname eq 'VANADIUM_FILE') or  $
   (uname eq 'REDUCED_FILE') or  $
   (uname eq 'EMPTY_FILE') or (uname eq 'CORRECTED_FILE') or $
   (uname eq 'INTERMEDIATE_FILE') then begin
   ; Now cycle through and remove the objects from the dcs_REDUCE object
   red_id = widget_info(file_tree_id,find_by_uname = 'REDUCTION_GROUP_FOLDER')
   widget_control,red_id,get_uvalue = uval
   dcs_object = uval.dcs_object
   for i = 0,n_sel-1 do begin
      widget_control,sel_id[i],get_uvalue = uv_sel
      if uname eq 'CORRECTED_FILE' then o = uv_sel.image_object else $
         o = uv_sel.data_object
      ret = dcs_object->destroy_element(o)
      widget_control,sel_id[i],/destroy
   endfor
   str = 'Deleted selected files'
   ret = self->update_status(str)
endif
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::dcs_delete_all,event
; This method deletes all of the files contained in a particular data group
; folder.
; Which folder was selected?
file_tree_id = self.file_tree
if not widget_info(file_tree_id,/valid_id) then return,0
sel_id = widget_info(file_tree_id,/tree_select)
n_sel = n_elements(sel_id)
if n_sel ne 1 then return,0
if not widget_info(sel_id,/valid_id) then return,0
uname = widget_info(sel_id,/uname)
if uname ne 'REDUCTION_GROUP_FOLDER' then return,0
widget_control,sel_id,get_uvalue = uval
dcs_object = uval.dcs_object

; Get the widget ids of each of the child folders
signal_id = widget_info(sel_id,find_by_uname = 'SIGNAL_DATA_FOLDER')
van_id = widget_info(sel_id,find_by_uname = 'VANADIUM_DATA_FOLDER')
dark_id = widget_info(sel_id,find_by_uname = 'DARKCOUNT_DATA_FOLDER')
int_id = widget_info(sel_id,find_by_uname = 'INTERMEDIATE_DATA_FOLDER')
empty_id = widget_info(sel_id,find_by_uname = 'EMPTY_DATA_FOLDER')
;reduced_id = widget_info(sel_id,find_by_uname = 'REDUCED_DATA_FOLDER')
absorber_id = widget_info(sel_id,find_by_uname = 'ABSORBER_DATA_FOLDER')
CORRECTED_id = widget_info(sel_id,find_by_uname = 'CORRECTED_DATA_FOLDER')
signal_list = get_list_items(signal_id,IDS = sig_ids,unames = names)
van_list = get_list_items(van_id,IDS = van_ids,unames = names)
dark_list = get_list_items(dark_id,IDS = dark_ids,unames = names)
int_list = get_list_items(int_id,IDS = int_ids,unames = names)
empty_list = get_list_items(empty_id,IDS = empty_ids,unames = names)
absorber_list = get_list_items(absorber_id,IDS = absorber_ids,unames = names)
;reduced_list = get_list_items(reduced_id,IDS = reduced_ids,unames = names)
CORRECTED_list = get_list_items(CORRECTED_id,IDS = CORRECTED_ids,unames = names)
if n_elements(sig_ids) ne 0 then begin
   for i = 0,n_elements(sig_ids)-1 do begin
      widget_control,sig_ids[i],get_uvalue = uv_sel
      ret = dcs_object->destroy_element(uv_sel.data_object)
      widget_control,sig_ids[i],/destroy
   endfor
endif

if n_elements(dark_ids) ne 0 then begin
   for i = 0,n_elements(dark_ids)-1 do begin
      widget_control,dark_ids[i],get_uvalue = uv_sel
      ret = dcs_object->destroy_element(uv_sel.data_object)
      widget_control,dark_ids[i],/destroy
   endfor
endif

if n_elements(van_ids) ne 0 then begin
   for i = 0,n_elements(van_ids)-1 do begin
      widget_control,van_ids[i],get_uvalue = uv_sel
      ret = dcs_object->destroy_element(uv_sel.data_object)
      widget_control,van_ids[i],/destroy
   endfor
endif

if n_elements(absorber_ids) ne 0 then begin
   for i = 0,n_elements(absorber_ids)-1 do begin
      widget_control,absorber_ids[i],get_uvalue = uv_sel
      ret = dcs_object->destroy_element(uv_sel.data_object)
      widget_control,absorber_ids[i],/destroy
   endfor
endif

if n_elements(int_ids) ne 0 then begin
   for i = 0,n_elements(int_ids)-1 do begin
      widget_control,int_ids[i],get_uvalue = uv_sel
      ret = dcs_object->destroy_element(uv_sel.data_object)
      widget_control,int_ids[i],/destroy
   endfor
endif

if n_elements(empty_ids) ne 0 then begin
   for i = 0,n_elements(empty_ids)-1 do begin
      widget_control,empty_ids[i],get_uvalue = uv_sel
      ret = dcs_object->destroy_element(uv_sel.data_object)
      widget_control,empty_ids[i],/destroy
   endfor
endif

if n_elements(CORRECTED_ids) ne 0 then begin
   for i = 0,n_elements(CORRECTED_ids)-1 do begin
      widget_control,CORRECTED_ids[i],get_uvalue = uv_sel
      ret = dcs_object->destroy_element(uv_sel.data_object)
      widget_control,CORRECTED_ids[i],/destroy
   endfor
endif

widget_control,self.fileinfo,set_value=''
str = 'Deleted all files'
ret = self->update_status(str)
ret = self->update_plot()
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::dcs_move_files_to_signal,event
; Which files were selected?
file_tree_id = self.file_tree
if not widget_info(file_tree_id,/valid_id) then return,0
; Determine if any of the children of FILE_TREE were selected
sel_id = widget_info(file_tree_id,/tree_select)
n_sel = n_elements(sel_id)
if not widget_info(sel_id[0],/valid_id) then return,0
uname = widget_info(sel_id[0],/uname)
if uname ne 'EMPTY_FILE' then return,0
; Now cycle through and remove the objects from the DCS_REDUCE object
empty_id = widget_info(sel_id[0],/parent)
red_id = widget_info(empty_id,/parent)
signal_id = widget_info(red_id,find_by_uname = 'SIGNAL_DATA_FOLDER')
widget_control,red_id,get_uvalue = uval
dcs_object = uval.dcs_object
ret = dcs_object->get_property(signal = signal_container,empty = empty_container)
nsignal = signal_container->count()
nempty = empty_container->count()
if nempty eq 0 then return,0
; ...and create new leaf widgets in the empty folder...
for i = 0,n_sel-1 do begin
   widget_control,sel_id[i],get_uvalue = uval
   o = uval.data_object
   ret=o->get_property(filename=efile)
   widget_control,sel_id[i],/destroy
   empty_container->remove,o
   ;should check to see if it is
   ;already in the tree
   count=0
   os=signal_container->get(/all)
   if (n_elements(os) ge 1) and (obj_valid(os[0])) then begin
      oldfiles=strarr(n_elements(os))
      for  j=0,n_elements(os)-1 do begin
         ret=os[j]->get_property(filename=filename)
         oldfiles[j]=filename
      endfor
      test=where(oldfiles eq efile, count)
   endif
   if count ge 1 then continue
   signal_container->add,o
   ret = o->get_property(display_name = display_name)
   ret = o->set_property(signal_type = 'SIGNAL')
   data_leaf = widget_tree(signal_id,value = display_name,     $
               uname = 'SIGNAL_FILE',                          $
              ; bitmap = *self.file_icon,                       $
               uvalue = {  object:self,                        $
                           method:'select_data',               $
                           data_object:o                       })
endfor
str = 'Moved files to Signal'
ret = self->update_status(str)
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::dcs_move_files_to_empty,event
; Which files were selected?
file_tree_id = self.file_tree
if not widget_info(file_tree_id,/valid_id) then return,0
; Determine if any of the children of FILE_TREE were selected
sel_id = widget_info(file_tree_id,/tree_select)
n_sel = n_elements(sel_id)
if not widget_info(sel_id[0],/valid_id) then return,0
uname = widget_info(sel_id[0],/uname)
if uname ne 'SIGNAL_FILE' then return,0
; Now cycle through and remove the objects from the DTAS_REDUCE object
signal_id = widget_info(sel_id[0],/parent)
red_id = widget_info(signal_id,/parent)
empty_id = widget_info(red_id,find_by_uname = 'EMPTY_DATA_FOLDER')
widget_control,red_id,get_uvalue = uval
dcs_object = uval.dcs_object
ret = dcs_object->get_property(signal = signal_container,empty = empty_container)
nsignal = signal_container->count()
if nsignal eq 0 then return,0
osignal = signal_container->get(/all)
; ...and create new leaf widgets in the empty folder...
for i = 0,n_sel-1 do begin
   widget_control,sel_id[i],get_uvalue = uval
   o = uval.data_object
   widget_control,sel_id[i],/destroy
   signal_container->remove,o
   empty_container->add,o
   ret = o->get_property(display_name = display_name)
   ret = o->set_property(signal_type = 'EMPTY')
   data_leaf = widget_tree(empty_id,value = display_name,      $
               uname = 'EMPTY_FILE',                           $
               ;bitmap = *self.file_icon,                       $
               uvalue = {  object:self,                        $
                           method:'select_data',               $
                           data_object:o                       })
endfor
str = 'Moved files to Empty'
ret = self->update_status(str)
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::dcs_delete_all_folder_files,event
; This method deletes all of the files contained in a particular signal, empty,
; intermediate, or reduced folder.
; Which folder was selected?
file_tree_id = self.file_tree
if not widget_info(file_tree_id,/valid_id) then return,0
sel_id = widget_info(file_tree_id,/tree_select)
n_sel = n_elements(sel_id)
if n_sel ne 1 then return,0
if not widget_info(sel_id,/valid_id) then return,0
uname = widget_info(sel_id,/uname)

if (uname eq 'EMPTY_DATA_FOLDER') or (uname eq 'SIGNAL_DATA_FOLDER') or $
   (uname eq 'ABSORBER_DATA_FOLDER') or $
   (uname eq 'VANADIUM_DATA_FOLDER') or (uname eq 'DARKCOUNT_DATA_FOLDER') or $
   (uname eq 'INTERMEDIATE_DATA_FOLDER') or $
   (uname eq 'REDUCED_DATA_FOLDER') or (uname eq 'CORRECTED_DATA_FOLDER') then begin
   list = get_list_items(sel_id,ids = ids,unames = unames)
   if n_elements(ids) eq 0 then return,0
   widget_control,sel_id,get_uval = uval
   red_id = uval.parent
   widget_control,red_id,get_uvalue = uvalue
   dcs_object = uvalue.dcs_object
   for i = 0,n_elements(ids)-1 do begin
      widget_control,ids[i],get_uvalue = uv_sel
      tags = tag_names(uv_sel)
      where_image_object = where(tags eq 'IMAGE_OBJECT',count_image)
      where_data_object = where(tags eq 'DATA_OBJECT',count_data)
      if count_data gt 0 then o = uv_sel.data_object
      if count_image gt 0 then o = uv_sel.image_object
      ret = dcs_object->destroy_element(o)
      widget_control,ids[i],/destroy
   endfor
endif

return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::add_data_group,event
;root_id = widget_info(event.top,find_by_uname = 'ROOT')
widget_control,self.file_tree,set_tree_select = 0
root_id = self.file_tree
red_group = widget_tree(root_id,value = 'Data Group',/folder,$
   /expanded,uname = 'REDUCTION_GROUP_FOLDER',uvalue = {object:self,method:'do_nothing', $
      dcs_object:obj_new()})
signal_group = widget_tree(red_group,value = 'Signal Data',/folder,$
   /expanded,uname = 'SIGNAL_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
      parent:red_group})
empty_group = widget_tree(red_group,value = 'Background Data',/folder, $
   /expanded,uname = 'EMPTY_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
      parent:red_group})
van_group = widget_tree(red_group,value = 'Vanadium Data',/folder, $
   /expanded,uname = 'VANADIUM_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
   parent:red_group})
dark_group = widget_tree(red_group,value = 'Darkcount Data',/folder, $
   /expanded,uname = 'DARKCOUNT_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
   parent:red_group})
absorber_group = widget_tree(red_group,value = 'Absorber Data',/folder, $
   /expanded,uname = 'ABSORBER_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
   parent:red_group})
int_group = widget_tree(red_group,value = 'Intermediate Steps',/folder, $
   /expanded,uname = 'INTERMEDIATE_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
   parent:red_group})
CORRECTED_group = widget_tree(red_group,value = 'CORRECTED Data',/folder, $
   /expanded,uname = 'CORRECTED_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
   parent:red_group})

return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::select_data,event
widget_control,event.id,get_uvalue = uval
uname = widget_info(event.id,/uname)
sel_id = widget_info(self.file_tree,/tree_select)
   if n_elements(sel_id) lt 55 then begin
      ;try to add info to the text widget
      if n_elements(sel_id) eq 1 then begin
         widget_control,sel_id,get_uvalue=uval
         o=uval.data_object
         ret=o->get_property(display_name=display_name)
         ret=o->get_property(user=user)
         ret=o->get_property(command=command)
         ret=o->get_property(comments=comments)
         ret=o->get_property(start_date=start_date)
         ret=o->get_property(stop_date=stop_date)
         ret=o->get_property(duration=duration)
         ret=o->get_property(ch_wl=ch_wl)
         ret=o->get_property(ch_ms=ch_ms)
         ret=o->get_property(ch_res=ch_res)
         ret=o->get_property(ch_srmode=ch_srmode)
         ret=o->get_property(ch_srdenom=ch_srdenom)
         ret=o->get_property(tsdmin=tsdmin)
         ret=o->get_property(ch_phase=ch_phase)
         ret=o->get_property(ch_delay=ch_delay)

         ret=o->get_property(treatment=treatment)
         ; Define the string array "contents", to be displayed on the screen.
        contents=[$
        "User(s):  "+user,$
       "Command:  "+command,$
       "Comments: "+comments,$
       "Start and stop times:   "+$
          start_date+"       "+$
          stop_date+"       ",$
       "Run duration: "+$
         string(duration,format='(f10.1)')+" sec,  i.e."+$
         string(duration/3600.0,format='(f8.2)')+" hrs.","",$
       "Wavelength, master speed, resolution, SR mode, SR denominator, Tsdmin:",$
         "     "+$
         string(ch_wl,format='(f7.3)')+$
         string(ch_ms,format='(f10.1)')+$
         string(ch_res,format='(i3)')+$
         string(ch_srmode,format='(i3)')+$
         string(ch_srdenom,format='(i3)')+$
         string(tsdmin,format='(f8.1)'),$
       "Chopper phases:            "+$
         strjoin(string(ch_phase*0.01,format='(f8.2)')),$
       "Chopper programmed delays: "+$
         strjoin(string(ch_delay,format='(f8.1)')),""]
;;
;;
       ret=o->get_property(temp_sample=temp_sample)
       ret=o->get_property(temp_control=temp_control)
       ret=o->get_property(temp_setpoint=temp_setpoint)
;;      ; Compute means and standard deviations of sample and control temperatures.
       result=where(temp_sample ge 0,ntemps)
       t_sample=0.0
       t_control=0.0
       if (ntemps ge 1) then begin
           if (ntemps eq 1) then begin
             t_sample=temp_sample[0]
          mean_temp_sample=t_sample
          stdv_temp_sample=0.0
           endif else begin
         t_sample=temp_sample[0:ntemps-1]
         result=moment(t_sample)
         mean_temp_sample=result[0]
         stdv_temp_sample=sqrt(result[1])
           endelse
           result=where(temp_control ge 0,ntemps)
           if (ntemps eq 1) then begin
             t_control=temp_control[0]
             mean_temp_control=t_control
             stdv_temp_control=0.0
           endif else begin
             t_control=temp_control[0:ntemps-1]
             result=moment(t_control)
             mean_temp_control=result[0]
             stdv_temp_control=sqrt(result[1])
           endelse
;;
;;
; Write temperature information (or an appropriate message).
        addition=[$
            "T_Setpoint="+$
              string(temp_setpoint,format='(f7.2)')+"   "+$
             "T_Sample= "+$
             strcompress(string(mean_temp_sample,format='(f7.2)')+"("+$
             string(stdv_temp_sample,format='(f7.2)'),/remove_all)+")   "+$
             "T_Control= "+$
             strcompress(string(mean_temp_control,format='(f7.2)')+"("+$
             string(stdv_temp_control,format='(f7.2)'),/remove_all)+") ["+$
             strcompress(string(ntemps),/remove_all)+" values]"]
          endif else addition="No temperature monitoring performed."
          contents=[contents,addition,""]

        ret=o->get_property(repeats=repeats)
        ret=o->get_property(resets=resets)
        ret=o->get_property(badbrd=badbrd)
        ret=o->get_property(baddet=baddet)
        ret=o->get_property(bitflips=bitflips)
;
; Add some sanity check information (regarding repeats, resets and bit flips).
        if (total(repeats) + $
          total(resets) eq 0) then $
          addition="No repeats or resets." else $
          addition=[$
          "Repeats, crate 0:  "+strjoin(strtrim(transpose(repeats[0,*]),1),"  "),$
          "Repeats, crate 1:  "+strjoin(strtrim(transpose(repeats[1,*]),1),"  "),$
          "Resets,  crate 0:  "+strjoin(strtrim(transpose(resets[0,*]),1),"  "),$
          "Resets,  crate 1:  "+strjoin(strtrim(transpose(resets[1,*]),1),"  ")]
       contents=[contents,addition]
       if (badbrd + baddet eq 0) then $
          addition="No bad boards or bad inputs." else $
          addition="BAD BOARDS = "+string(badbrd,format='(i3)')+"   "+$
            "BAD INPUTS = "+string(baddet,format='(i3)')
       contents=[contents,addition]
       nflips=0
       for k=0,4 do begin
          if (bitflips[1,k] ne 1000) then begin
            addition="BIT FLIP --> time, detector, value = "+$
             strtrim(string(bitflips[0,k]),1)+" "+$
             strtrim(string(bitflips[1,k]),1)+" "+$
             strtrim(string(bitflips[2,k]),1)
            contents=[contents,addition]
            nflips=nflips+1
          endif
       endfor
       if (nflips eq 0) then  contents=[contents,"No bit flips."]


         widget_control,self.fileinfo,set_value=contents
      endif
   endif
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::dcs_show_treatment,event
file_tree_id = self.file_tree
if not widget_info(file_tree_id,/valid_id) then return,0
; Determine if any of the children of FILE_TREE were selected
sel_id = widget_info(file_tree_id,/tree_select)
n_sel = n_elements(sel_id)
if n_sel ne 1 then return,0
uname = widget_info(sel_id,/uname)
if (uname eq 'SIGNAL_FILE') or (uname eq 'EMPTY_FILE') or $
   (uname eq 'ABSORBER_FILE') or $
   (uname eq 'VANADIUM_FILE') or (uname eq 'DARKCOUNT_FILE') or $
   (uname eq 'REDUCED_FILE') or (uname eq 'INTERMEDIATE_FILE') or $
   (uname eq 'CORRECTED_FILE') then begin
      widget_control,sel_id,get_uvalue = uval
      tags = tag_names(uval)
      where_image = where(tags eq 'IMAGE_OBJECT',count_image)
      where_data = where(tags eq 'DATA_OBJECT',count_data)
      if count_image gt 0 then o = uval.image_object else $
         o = uval.data_object
      ret = o->get_property(display_name = display_name,treatment = treatment)
      title = 'DCS Data Treatment: '+display_name
      dcs_test_launch_text_display,event,group_leader = sel_id,o,title = title, $
         txt = treatment
endif
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::about,event
strout = strarr(4)
strout[0] = 'DCS Data Reduction'
strout[1] = 'Written by Craig Brown and John Copley'
strout[2] = 'June 17, 2005'
strout[3] = 'NIST Center for Neutron Research'
void = dialog_message(dialog_parent = event.top,strout,  $
   title = 'About DCS Data Reduction',/information)
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro dcs_test_launch_text_display,event,o,title = title,txt = txt,   $
   group_leader = group_leader
this_event = tag_names(event,/structure_name)
case this_event of
'WIDGET_BUTTON':  $
   begin
      ddcs_text_display, group_leader = group_leader,        $
                        notify_ids = [event.id,event.top],  $
                        o = o,                              $
                        title = title,                      $
                        txt = txt
   end
else:
endcase
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::resize,event

;get the original size ofthe base
tlbx=(*self.widget_info_ptr).tlbgeo.scr_xsize
tlby=(*self.widget_info_ptr).tlbgeo.scr_ysize
;get the new size of the base
tlbgeo=widget_info(self.tlb,/geometry)
tlbnewx=tlbgeo.scr_xsize
tlbnewy=tlbgeo.scr_ysize

;if the new base is smaller than the original, set everything to the old
if tlbnewx lt tlbx then begin
   tlbnewx=tlbx
endif
if tlbnewy lt tlby then begin
   tlbnewy=tlby
endif
widget_control,self.tlb,scr_xsize=tlbnewx,scr_ysize=tlbnewy

;ftab
ftab_id = widget_info(event.top,find_by_uname = 'FTAB')
;change the tab size by the previous amount
widget_control,ftab_id,scr_ysize=(*self.widget_info_ptr).ftabgeo.scr_ysize+(tlbnewy-tlby)

;1st tab bases and widget
row_id = widget_info(event.top,find_by_uname = 'ROW_BASE')
widget_control,row_id,scr_ysize=(*self.widget_info_ptr).rowgeo.scr_ysize+(tlbnewy-tlby),$
      scr_xsize=(*self.widget_info_ptr).rowgeo.scr_xsize+(tlbnewx-tlbx)
widget_control,self.fileinfo,$
   scr_xsize=(*self.widget_info_ptr).infogeo.scr_xsize+(tlbnewx-tlbx),$
   scr_ysize=(*self.widget_info_ptr).infogeo.scr_ysize+(tlbnewy-tlby)
widget_control,self.file_tree,$
   scr_ysize=(*self.widget_info_ptr).infogeo.scr_ysize+(tlbnewy-tlby)


;2nd tab widgets and bases
bpb_id = widget_info(event.top,find_by_uname = 'BIGPLOT_BASE')
widget_control,bpb_id,scr_ysize=(*self.widget_info_ptr).bigplotinfo.scr_ysize+(tlbnewy-tlby),$
      scr_xsize=(*self.widget_info_ptr).bigplotinfo.scr_xsize+(tlbnewx-tlbx)
c2_id = widget_info(event.top,find_by_uname = 'CHOICE2_BASE')
widget_control,c2_id,scr_ysize=(*self.widget_info_ptr).plotinfo.scr_ysize+(tlbnewy-tlby),$
      scr_xsize=(*self.widget_info_ptr).plotinfo.scr_xsize+(tlbnewx-tlbx)
widget_control,self.win,scr_ysize=(*self.widget_info_ptr).wininfo.scr_ysize+(tlbnewy-tlby),$
      scr_xsize=(*self.widget_info_ptr).wininfo.scr_xsize+(tlbnewx-tlbx)
;create a new pixmap
widget_control,self.win,get_value = winvis
self.winvis = winvis
winxsize = !d.x_size
winysize = !d.y_size
window,/free,/pixmap,xsize = winxsize,ysize = winysize
self.winpix = !d.window
;check if there is data, if not replot the screen
file_tree = self.file_tree
; is there any dcs data in the file_tree?
this_id = widget_info(file_tree,/tree_select)
if not widget_info(this_id,/valid_id) then begin
   wset,self.winPix
   PLOT, [0, 1],[0, 1], xrange = [0,1],yrange = [0,1],/xsty,/ysty,$
       /NODATA ,background = 255,color =0,xtitle='x (units)', ytitle='y (units)',$
       position = [0.15,0.15,.95,0.9], title='NO DATA'
   wset,self.winVis
   device,copy = [0,0,!d.x_size,!d.y_size,0,0,self.winPix]
endif else begin
   ret = self->update_plot()
endelse

return,1
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro dcs_test_gui_events,event

if tag_names(event,/structure_name) eq 'WIDGET_BASE' then begin
   widget_control,event.top,get_uvalue = the_object
   ret = the_object->resize(event)
   return
endif
if tag_names(event,/structure_name) eq 'WIDGET_TAB' then begin
   widget_control,event.top,get_uvalue = the_object
   return
endif
uname = widget_info(event.id,/uname)
widget_control,event.id,get_uvalue = cmd
;print,cmd.method
;help, event, /structure
ret = call_method(cmd.method,cmd.object,event)
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::init_colors
color_names = fsc_color(/names)
ncolors = n_elements(color_names)
s = create_struct(color_names[0],FSC_COLOR(color_names[0], !D.Table_Size-1))
for i = 1,ncolors-1 do begin
   s = create_struct(s,color_names[i],FSC_COLOR(color_names[i], !D.Table_Size-1-i))
endfor
*self.color_ptr = s
;color_array = [s.yellow,s.green,s.aquamarine,s.red,s.salmon,s.white,s.purple]
color_array = [s.black,s.blue,s.red,s.purple,s.green,s.maroon,s.aquamarine]
*self.sel_colors_ptr = color_array
tvlct,r,g,b,/get
*self.ddcs_color_ptr = {r:r,g:g,b:b}
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::dcs_rename_data_group,event
sel_id = widget_info(self.file_tree,/tree_select)
n_sel = n_elements(sel_id)
if n_sel ne 1 then return,0
uname = widget_info(sel_id,/uname)
if uname ne 'REDUCTION_GROUP_FOLDER' then return,0
widget_control,sel_id,get_value = old_name
new_name = ddcs_new_name(old_name,group_leader = event.top)
widget_control,sel_id,set_value = new_name
return,1
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::dcs_rename_file,event
sel_id = widget_info(self.file_tree,/tree_select)
n_sel = n_elements(sel_id)
if n_sel ne 1 then return,0
uname = widget_info(sel_id,/uname)
if (uname eq 'SIGNAL_FILE') or (uname eq 'EMPTY_FILE') or $
   (uname eq 'ABSORBER_FILE') or $
   (uname eq 'VANADIUM_FILE') or (uname eq 'DARKCOUNT_FILE') or $
   (uname eq 'INTERMEDIATE_FILE') or (uname eq 'REDUCED_FILE') or $
   (uname eq 'CORRECTED_FILE') then begin
   widget_control,sel_id,get_uvalue = uval
   if uname eq 'CORRECTED_FILE' then o = uval.image_object else $
      o = uval.data_object
   ret = o->get_property(display_name = display_name)
   new_name = ddcs_new_name(display_name,group_leader = event.top, $
      title = 'Enter new file name with extension')
   if new_name ne '' then begin
;      ret = o->get_property(plot_str = plot_str)
;      plot_str.title = new_name
      ret = o->set_property(display_name = new_name);,plot_str = plot_str)
      widget_control,sel_id,set_value = new_name
      ret = self->update_plot_info(sel_id)
   endif
endif
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::init_symbols
n = 55
; Create the fill array so that there are alternating unfilled and filled
; symbols respectively
fill = intarr(n)
one_index = where(indgen(n) mod 2 ne 0)
fill[one_index] = 1
; Create the shape array
shape = strarr(n)

; The following lines define the symbol shapes for the new version of
; this software
prim_shapes = ['circle','circle','triangle','triangle','box','box',  $
               'diamond','diamond']
for i = 0,7 do begin
   if i eq 0 then shape = prim_shapes else $
      shape = [shape,prim_shapes]
endfor

; Create the color array
colors = *self.color_ptr
color_choices = *self.sel_colors_ptr
ncolors = n_elements(color_choices)

; The following lines define the colors for the new version of
; this software
color = lonarr(n)
for j = 0,ncolors-2 do begin
   for i = 0,7 do begin
      if j eq 0 and i eq 0 then color = color_choices[j] else $
         color = [color,color_choices[j]]
   endfor
endfor


*self.sym_ptr = {fill:fill,shape:shape,color:color}
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::modeChange,event
    ; if this is a button being released, don't care (ignore)
   ; print, event.select
    if event.select ne 1 then begin
       return,1
    endif

    ; find out which button was pressed
    mode = widget_info(event.id,/uname)
    self.plot_mode = mode

    return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::formatMaskString,event

    tempString=""
    numberSet = [-1L]
    detectorString = ''
    char = ""
    num1 = -1
    dashSet = [-1L]

    maskedIndices = (*self.maskedX)

;    print,"maskedIndices (", n_elements(maskedIndices), " elements):", maskedIndices
    numberSet = maskedIndices


    numberSet = numberSet[uniq(numberSet, sort(numberSet))]

    setSize = n_elements(numberSet)
    i = 0
    if(i lt setSize-2) then begin
        for i = 0, setSize-2 do begin
        ;   print, "i: " , i
           if(numberSet[i] eq -1) then continue   ; if -1 value, then invalid data and restart
           ;print, numberSet[i], "vs", numberSet[i+1]
           if( numberSet[i] eq (numberSet[i+1]-1) ) then begin   ; if the two indexed number are consecutive, possible dash set
             ;print, "possible match"
             if(dashSet[0] eq -1) then begin       ; if dashSet is empty, then we haven't started a set yet
              dashSet = numberSet[i]
             endif else begin
              dashSet = [dashSet, numberSet[i]]
             endelse
           endif else begin            ; set is broken or there never was one
             if(n_elements(dashSet) gt 1) then begin  ; there was a set
              ;print, "big enough"
              if(dashSet[0] eq -1) then begin        ; if dashSet is empty, then we haven't started a set yet
                  dashSet = numberSet[i]
              endif else begin
                  dashSet = [dashSet, numberSet[i]]
              endelse
              detectorString = detectorString + "," + strtrim(dashSet[0], 1) + $
                        "-" + strtrim(dashSet[n_elements(dashSet)-1],1)
             endif else begin
              ;print, "not big enough"
              if(dashSet[0] eq -1) then begin        ; if dashSet is empty, then we haven't started a set yet
                  dashSet = numberSet[i]
              endif else begin
                  dashSet = [dashSet, numberSet[i]]
              endelse
              detectorString = detectorString + "," + strjoin(strtrim(string(dashSet),1),",")
             endelse
             dashSet = [-1L]
             ;detectorString = detectorString + "," + numberSet[i-1]
           endelse
             ;print, "detectorString: ", detectorString
        endfor
    endif

    if(dashSet[0] ne -1) then begin
       dashSet = [dashSet, numberSet[i]]
    endif else begin
       dashSet = numberSet[i]
    endelse
    if(n_elements(dashSet) gt 1) then begin    ; there was a set
       detectorString = detectorString + "," + strtrim(dashSet[0], 1) + $
                 "-" + strtrim(dashSet[n_elements(dashSet)-1],1)
    endif else begin
       detectorString = detectorString + "," + strjoin(strtrim(string(dashSet),1),",")
    endelse

    detectorString = strmid(detectorString,1)
    if (detectorString eq "-1") then begin
       detectorString = ""
    endif


;    print, "numberSet: ", numberSet
;    print, "dashSet: ", dashSet
;    print,"final detector string: ", detectorString
    return,detectorString

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::plot_events,event
  ;if we do not have a dcs object, do not enter this part of the code...
  red_id = widget_info(self.file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
  widget_control,red_id,get_uvalue = uval
  if not obj_valid(uval.dcs_object) then return,0

;if n_elements(*self.plot_info) eq 0 then return,0
tvlct,(*self.ddcs_color_ptr).r,(*self.ddcs_color_ptr).g,(*self.ddcs_color_ptr).b
case event.type of
0: begin    ; button press
      self.mouse = event.press
      if self.mouse eq 4 then begin
        if (self.plot_mode eq "MASK_MODE") then begin
            self.xbox[0] = event.x
            self.ybox[0] = event.y
            ; added storing of second corner for when
            ; user doesn't drag the mouse before releasing
            self.xbox[1] = event.x
            self.ybox[1] = event.y
            wset,self.winVis
            device,copy = [0,0,!d.x_size,!d.y_size,0,0,self.winPix]
            empty
            self.autoscale = 0
         endif else begin
            self.autoscale = 1
            ret = self->refresh(event)
         endelse
      endif
      if self.mouse eq 1 then begin
         self.xbox[0] = event.x
         self.ybox[0] = event.y
         ; added storing of second corner for when
         ; user doesn't drag the mouse before releasing
         self.xbox[1] = event.x
         self.ybox[1] = event.y
         wset,self.winVis
         device,copy = [0,0,!d.x_size,!d.y_size,0,0,self.winPix]
         empty
         self.autoscale = 0
      endif
   end
1: begin ; button release
      if( (self.mouse eq 1) || (self.mouse eq 4) ) then begin
        if( (self.plot_mode eq "ZOOM_MODE") || (self.plot_mode eq "") ) then begin
            xll = self.xbox[0] < self.xbox[1]
            yll = self.ybox[0] < self.ybox[1]
            w = abs(self.xbox[1] - self.xbox[0])
            h = abs(self.ybox[1] - self.ybox[0])
            xur = xll + w
            yur = yll + h
            ll = convert_coord(xll,yll,/device,/to_data)
            ur = convert_coord(xur,yur,/device,/to_data)
            self.xrange = [ll[0],ur[0]]
            self.yrange = [ll[1],ur[1]]
       endif else begin
       if(self.plot_mode eq "MASK_MODE") then begin


       ; taken from the update_plot function
       ; long story short it reads the data file and gives
       ; me my y values (which I put into the var y)
       file_tree = self.file_tree
       red_id = widget_info(file_tree,find_by_uname = 'REDUCTION_GROUP_FOLDER')
       widget_control,red_id,get_uvalue = uval
       dcs_data = uval.dcs_object
       ;see if we have a combined data object
       index=-99
       com_id = widget_info(red_id,find_by_uname = 'CORRECTED_DATA_FOLDER')
       ret = dcs_data->get_property(corrected = com_container)
        c_int = com_container->count()
       if c_int gt 0 then begin
       com_all = com_container->get(/all)
       for i = 0,n_elements(com_all)-1 do begin
         if obj_valid(com_all[i]) then begin
            ret = com_all[i]->get_property(signal_type = signal_type)
            if signal_type eq 'CORRECTED_SIGNAL' then index=i
         endif
       endfor
       endif
       ret = com_all[index]->get_property(display_name = display_name, xlabel=xlabel,$
                    xunits=xunits,histlabel=histlabel,comments=comments,$
                    plot_sums=plot_sums,q_props=q_props,angle_props=angle_props)
       y = plot_sums
       ; populate my x data
       ; ASSUMPTION: the data is in order
       x=indgen(n_elements(y))

       ; if we're demasking, then I only need to go through the currently masked data
       if(self.mouse eq 4) then begin
         y = *self.maskedY
         x = *self.maskedX
       endif

       ; we have no idea which corner the user is starting from
       ; this block will take a box constructed any way and give
       ; us the lower left & upper right corners
       xLowerLeft = self.xbox[0] < self.xbox[1]
       yLowerLeft = self.ybox[0] < self.ybox[1]
       width = abs(self.xbox[1] - self.xbox[0])
       height = abs(self.ybox[1] - self.ybox[0])
       xUpperRight = xLowerLeft + width
       yUpperRight = yLowerLeft + height

       ; convert the pixel points to data coordinates on the plot
       lowerLeftCoord = convert_coord(xLowerLeft,yLowerLeft,/device,/to_data)
       upperRightCoord = convert_coord(xUpperRight,yUpperRight,/device,/to_data)
;       print, "coords: (", lowerLeftCoord[0],",",lowerLeftCoord[1],") -> (",upperRightCoord[0],",",upperRightCoord[1], ")"
;       print, "y: ", y

       ; nice fancy array operation (since they told me they'd beat me for every loop I used)
       ; basically it tells me what points are within the selection box and gives me their indices
       selectedIndices = where( ((x < upperRightCoord[0]) > lowerLeftCoord[0] eq x) AND $
                          ((y < upperRightCoord[1]) > lowerLeftCoord[1] eq y ) AND (fix(y) ne 0), $
                          count, complement=deselectedIndices)
;       print, "selectedIndices: ", selectedIndices
       ; if it's the left mouse, then we're adding masked points
       if(self.mouse eq 1) then begin
         if(count ne 0) then begin         ; make sure we've got some points to add
          ; kludge for IDL's poor implementation of arrays
          if( (*self.maskedX)[0] ne -1) then begin    ; append
              xNew = [*self.maskedX, x[selectedIndices]]
              yNew = [*self.maskedY, y[selectedIndices]]
          endif else begin                   ; create new
              xNew = x[selectedIndices]
              yNew = y[selectedIndices]
          endelse

;          print, "yNew before: ", yNew
          ; removing duplicate entries
          tempIndices = uniq(xNew, sort(xNew)) ; storing separately so I can use it twice
          xNew = xNew[tempIndices]
          yNew = yNew[tempIndices]
;          print, "yNew after: ", yNew

          ; freeing old storage of masked arrays and storing new
          ptr_free,self.maskedX
          ptr_free,self.maskedY
          self.maskedX = ptr_new(xNew)
          self.maskedY = ptr_new(yNew)
         endif
       endif else begin
       ; right mouse, removing masked points
       if(self.mouse eq 4) then begin
         if(count ne 0) then begin         ; make sure we've got points to remove
          if(deselectedIndices[0] ne -1) then begin
              xNew = (*self.maskedX)[deselectedIndices]
              yNew = (*self.maskedY)[deselectedIndices]
          endif else begin
              xNew = [-1L]
              yNew = [-1L]
          endelse

          ; free up the old stuff, put in the new
          ptr_free,self.maskedX
          ptr_free,self.maskedY
          self.maskedX = ptr_new(xNew)
          self.maskedY = ptr_new(yNew)
         endif
       endif
       endelse


       detectorString = self->formatMaskString(event)

       ; get widget id for mask text box
       textBox = widget_info(event.top,find_by_uname="MASK")
       ; create dummy event so we can update the text box
       tempEvent = {    widget_text_ch,    $
              ID:0,         $
              TOP:0       , $
              HANDLER:0,     $
              TYPE:0,       $
              OFFSET:strlen(detectorString),   $
              CH:0        $
            }
       ;help, event, /structure
       ;help, tempEvent, /structure
       ; update the text box and notify the textbox of the change
       widget_control,textBox,set_value=detectorString
       widget_control,textBox,send_event=tempEvent,/no_copy

       ;void = self->update_plot(event)

       reduceButton = widget_info(event.top, find_by_uname="RED_BUTTON")
       tempEvent2 = {   WIDGET_BUTTON,    $
               ID:0,      $
               top:0,       $
               handler:0,   $
               select:1       $
              }
       ;help, tempEvent2, /structure
       widget_control,reduceButton,send_Event=tempEvent2,/no_copy



    endif
    endelse
    ret = self->refresh(event)
    self.mouse = 0B
    endif
   end
2: begin ; mouse motion
    if ( (self.mouse eq 1) || (self.mouse eq 4) ) then begin
        if(self.plot_mode eq "PAN_MODE") then begin
            ; get current location of mouse pointer and convert to plot coordinates
            currX = event.x
            currY = event.y
            currentLocation = convert_coord(currX,currY,/device,/to_data)

            ; get starting points and convert
            oldLocation = convert_coord(self.xbox[0],self.ybox[0],/device,/to_data)

            distance = [currentLocation[0] - oldLocation[0],currentLocation[1] - oldLocation[1]]

            ; find new coordinates to display
            ; since the zoom factor can't change in move mode,
            ; we take the current range and just recalculate the corners
            newXLowerLeft = self.xrange[0] - distance[0]
            newYLowerLeft = self.yrange[0] - distance[1]
            newXUpperRight = self.xrange[1] - distance[0]
            newYUpperRight = self.yrange[1] - distance[1]

         ;print, "(", newXLowerLeft, ",", newYLowerLeft, ")"
         ;print, "(", newXUpperRight, ",", newYUpperRight, ")"

            ; convert pixel points to plot coordinates
            ;lowerLeft = convert_coord(newXLowerLeft,newYLowerLeft,/device,/to_data)
            ;upperRight = convert_coord(newXUpperRight,newYUpperRight,/device,/to_data)

            ; re-set the x and y range and redraw
            self.xrange = [newXLowerLeft,newXUpperRight]
            self.yrange = [newYLowerLeft,newYUpperRight]
            ret = self->refresh(event)
            self.xbox[0] = currX
            self.ybox[0] = currY
        endif else begin
         self.xbox[1] = event.x
            self.ybox[1] = event.y
            xc = [self.xbox[0],event.x,event.x,$
                  self.xbox[0],$
                  self.xbox[0]]
            yc = [self.ybox[0],self.ybox[0],$
                  event.y,event.y,$
                  self.ybox[0]]
            wset,self.winvis
            device,copy = [0,0,!d.x_size,!d.y_size,0,0,self.winpix]
            plots,xc,yc,/device,color = (*self.color_ptr).purple
            empty
        endelse
    endif else begin
       str = 'Zooming->Hold down left mouse button, drag rubberband box, '+ $
               'and release button. Autoscale->Press right mouse button'
       ret = self->update_status(str)
    endelse
   end
else:
endcase
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

function dcs_test_gui::change_colors,event
thisEvent = tag_names(event,/structure_name)
case thisEvent of
'WIDGET_BUTTON': $
   begin
      XColors, Group_Leader=event.top, NotifyID=[event.id, event.top]
   end
'XCOLORS_LOAD': $
   begin
      self.colorTable = event.index
      ret = self->update_plot(event)
   end
else:
endcase

return,1
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::build_gui

; Get the DAVE colors
device,get_decomposed = dc
self.dave_dc = dc
tvlct,r,g,b,/get
*self.dave_color_ptr = {r:r,g:g,b:b}
ret = self->init_colors()
ret = self->init_symbols()

if n_elements(*self.pgroup_leader) eq 0 then begin
  tlb = widget_base(title = 'Disc Chopper Spectrometer Data Reduction',  $
                        /col,mbar = bar,/tlb_size_events)
endif else begin
   tlb = widget_base(title = 'Disc Chopper Spectrometer Data Reduction',  $
                        /col,mbar = bar,/tlb_size_events,   $
                           group_leader = *self.pgroup_leader)
endelse
self.tlb = tlb
;Make a set of tabs;
fTab = WIDGET_TAB(self.tlb,uname='FTAB')

filemenu = widget_button(bar,value = 'FILE',/menu)
void = widget_button(filemenu,value = 'Load Signal File',   $
   uvalue = {object:self, method:'LOAD_SIGNAL_FILES'},ACCELERATOR = "Ctrl+SHIFT+C")
void = widget_button(filemenu,value = 'Load Empty File',   $
   uvalue = {object:self, method:'LOAD_EMPTY_FILES'},ACCELERATOR = "Ctrl+SHIFT+E")
void = widget_button(filemenu,value = 'Load Vanadium File',   $
   uvalue = {object:self, method:'LOAD_VANADIUM_FILES'},ACCELERATOR = "Ctrl+Shift+V")
void = widget_button(filemenu,value = 'Load Darkcount File',   $
   uvalue = {object:self, method:'LOAD_DARKCOUNT_FILES'},ACCELERATOR = "Ctrl+SHIFT+D")
void = widget_button(filemenu,value = 'Load Absorber File',   $
   uvalue = {object:self, method:'LOAD_ABSORBER_FILES'},ACCELERATOR = "Ctrl+SHIFT+A")
void = widget_button(filemenu,value = 'Load Mask File',   $
   uvalue = {object:self,method:'load_mask'},uname='loadMask')
void = widget_button(filemenu,value = 'Reduce',$
        uvalue = {object:self,method:'reduce_data'},ACCELERATOR = "Ctrl+SHIFT+R",/separator)
void = widget_button(filemenu,value = 'Save reduced (DAVE)',   $
   uvalue = {object:self,method:'dcs_save_dave'},/separator,uname='s_all_d',ACCELERATOR = "Ctrl+S")
void = widget_button(filemenu,value = 'Save reduced (Ascii)',   $
   uvalue = {object:self,method:'dcs_save_asc'},uname='s_all_a',ACCELERATOR = "Ctrl+SHIFT+S")
void = widget_button(filemenu,value = 'Save mask',   $
   uvalue = {object:self,method:'dcs_save_mask'},uname='saveMask')
void = widget_button(filemenu,value = 'QUIT',   $
   uvalue = {object:self, method:'QUIT'},/separator)
plot_menu = widget_button(bar,value = 'PLOT')
void = widget_button(plot_menu,value = 'Print to postscript file',   $
   uvalue = {object:self,method:'print_to_ps'},ACCELERATOR = "Ctrl+SHIFT+p")
void = widget_button(plot_menu,value = 'Save as JPEG',   $
   uvalue = {object:self,method:'save_as_jpeg'},ACCELERATOR = "Ctrl+SHIFT+j")
void = widget_button(plot_menu,value = 'Save as PNG',   $
   uvalue = {object:self,method:'save_as_png'},ACCELERATOR = "Ctrl+SHIFT+g")
void = widget_button(plot_menu,value = 'Copy to clipboard',   $
   uvalue = {object:self,method:'clipboard'},ACCELERATOR = "Ctrl+Shift+B")
misc_menu = widget_button(bar,value = 'MISC')
void = widget_button(misc_menu,value = 'About dcs Data Reduction',   $
   uvalue = {object:self, method:'about'})

device,get_screen_size = scr_size
aspect_ratio = float(scr_size[0])/float(scr_size[1])
dual_monitor = aspect_ratio ge 4./3.
xsize = 400 & ysize = 300
tree_ysize = ysize+75
if dual_monitor then begin
   tree_xsize = fix(0.5*0.5*scr_size[0])
endif else begin
   tree_xsize = fix(0.5*0.5*scr_size[0])
endelse

;fill in the file tab
row_base = widget_base(fTab,/row,title='FILES',uname = 'ROW_BASE')
self.file_tree = widget_tree(row_base,/context_events, multiple = 1,$
   scr_xsize = tree_xsize,scr_ysize = tree_ysize,$
   uvalue = {object:self,method:'context_events'})
self.fileinfo = widget_text(row_base,/scroll,scr_xsize = tree_xsize,$
                 scr_ysize = tree_ysize)
root_id = self.file_tree
red_group = widget_tree(root_id,value = 'Data Group',/folder,$
   /expanded,uname = 'REDUCTION_GROUP_FOLDER',uvalue = {object:self,method:'do_nothing', $
      dcs_object:obj_new()})
signal_group = widget_tree(red_group,value = 'Signal Data',/folder,$
   /expanded,uname = 'SIGNAL_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
      parent:red_group})
empty_group = widget_tree(red_group,value = 'Empty Data',/folder, $
   /expanded,uname = 'EMPTY_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
      parent:red_group})
van_group = widget_tree(red_group,value = 'Vanadium Data',/folder, $
   /expanded,uname = 'VANADIUM_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
   parent:red_group})
absorber_group = widget_tree(red_group,value = 'Absorber Data',/folder, $
   /expanded,uname = 'ABSORBER_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
   parent:red_group})
dark_group = widget_tree(red_group,value = 'Dark Count Data',/folder, $
   /expanded,uname = 'DARKCOUNT_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
   parent:red_group})
int_group = widget_tree(red_group,value = 'Intermediate Steps',/folder, $
   /expanded,uname = 'INTERMEDIATE_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
   parent:red_group})
CORRECTED_group = widget_tree(red_group,value = 'Corrected Data',/folder, $
   /expanded,uname = 'CORRECTED_DATA_FOLDER',uvalue = {object:self,method:'do_nothing', $
   parent:red_group})
; Create the reduction group menu
red_menu = widget_base(self.tlb,/context_menu,uname = 'REDUCTION_GROUP_MENU')
void = widget_button(red_menu,value = 'Reduce Data',   $
   uvalue = {object:self,method:'reduce_data'})
void = widget_button(red_menu,value = 'Remove all data files in all folders',   $
   uvalue = {object:self,method:'dcs_delete_all'},/separator)
; Create the signal file group menu
data_menu = widget_base(self.tlb,/context_menu,uname = 'SIGNAL_DATA_MENU')
void = widget_button(data_menu,value = 'Show data treatment',   $
   uvalue = {object:self,method:'dcs_show_treatment'})
void = widget_button(data_menu,value = 'Remove selected data file(s)',   $
   uvalue = {object:self,method:'dcs_delete_files'})
void = widget_button(data_menu,value = 'Move selected data file(s) to EMPTY folder',   $
   uvalue = {object:self,method:'dcs_move_files_to_empty'})
; Create the signal data group menu
data_menu = widget_base(self.tlb,/context_menu,uname = 'SIGNAL_FOLDER_MENU')
void = widget_button(data_menu,value = 'Load file(s)',   $
   uvalue = {object:self,method:'load_signal_files',type:'SIGNAL'})
void = widget_button(data_menu,value = 'Remove all signal files',   $
   uvalue = {object:self,method:'dcs_delete_all_folder_files'})
; Create the CORRECTED file group menu
data_menu = widget_base(self.tlb,/context_menu,uname = 'CORRECTED_DATA_MENU')
void = widget_button(data_menu,value = 'Show data treatment',   $
   uvalue = {object:self,method:'dcs_show_treatment'})
void = widget_button(data_menu,value = '-----SAVE ALL DAVE-----',   $
   uvalue = {object:self,method:'dcs_save_dave'},/separator,uname='s_all_d')
void = widget_button(data_menu,value = 'S(Q,w) as DAVE',   $
   uvalue = {object:self,method:'dcs_save_dave'},uname='s_sqw_d')
void = widget_button(data_menu,value = 'G(w) as DAVE',   $
   uvalue = {object:self,method:'dcs_save_dave'},uname='s_gw_d')
void = widget_button(data_menu,value = 'Sums as DAVE',   $
   uvalue = {object:self,method:'dcs_save_dave'},uname='s_sum_d')
void = widget_button(data_menu,value = 'I(2th,w) as DAVE',   $
   uvalue = {object:self,method:'dcs_save_dave'},uname='s_iw_d')
void = widget_button(data_menu,value = 'I(2th,t) as DAVE',   $
   uvalue = {object:self,method:'dcs_save_dave'},uname='s_it_d')
void = widget_button(data_menu,value = '----SAVE ALL ASCII----',   $
   uvalue = {object:self,method:'dcs_save_asc'},/separator,uname='s_all_a')
void = widget_button(data_menu,value = 'S(Q,w) as txt',   $
   uvalue = {object:self,method:'dcs_save_asc'},uname='s_sqw_a')
void = widget_button(data_menu,value = 'G(w) as txt',   $
   uvalue = {object:self,method:'dcs_save_asc'},uname='s_gw_a')
void = widget_button(data_menu,value = 'Sums as txt',   $
   uvalue = {object:self,method:'dcs_save_asc'},uname='s_sum_a')
void = widget_button(data_menu,value = 'I(2th,w) as txt',   $
   uvalue = {object:self,method:'dcs_save_asc'},uname='s_iw_a')
void = widget_button(data_menu,value = 'I(2th,t) as txt',   $
   uvalue = {object:self,method:'dcs_save_asc'},uname='s_it_a')
comb_menu = widget_base(self.tlb,/context_menu,uname = 'CORRECTED_FOLDER_MENU')
void = widget_button(comb_menu,value = 'Remove all corrected files',   $
   uvalue = {object:self,method:'dcs_delete_all_folder_files'})
; Create the empty folder group menu
data_menu = widget_base(self.tlb,/context_menu,uname = 'EMPTY_FOLDER_MENU')
void = widget_button(data_menu,value = 'Load file(s)',               $
   uvalue = {object:self,method:'LOAD_EMPTY_FILES',type:'EMPTY'})
void = widget_button(data_menu,value = 'Remove all background files',     $
   uvalue = {object:self,method:'dcs_delete_all_folder_files'})
; Create the intermediate folder group menu
van_data_menu = widget_base(self.tlb,/context_menu,uname = 'VANADIUM_FOLDER_MENU')
void = widget_button(van_data_menu,value = 'Load file(s)',               $
   uvalue = {object:self,method:'LOAD_VANADIUM_FILES',type:'VANADIUM'})
void = widget_button(van_data_menu,value = 'Remove all vanadium files',     $
   uvalue = {object:self,method:'dcs_delete_all_folder_files'})
; Create the intermediate folder group menu
dark_data_menu = widget_base(self.tlb,/context_menu,uname = 'DARKCOUNT_FOLDER_MENU')
void = widget_button(dark_data_menu,value = 'Load file(s)',               $
   uvalue = {object:self,method:'LOAD_DARKCOUNT_FILES',type:'DARKCOUNT'})
void = widget_button(dark_data_menu,value = 'Remove all darkcount files',     $
   uvalue = {object:self,method:'dcs_delete_all_folder_files'})
; Create the intermediate folder group menu
absorber_data_menu = widget_base(self.tlb,/context_menu,uname = 'ABSORBER_FOLDER_MENU')
void = widget_button(absorber_data_menu,value = 'Load file(s)',               $
   uvalue = {object:self,method:'LOAD_ABSORBER_FILES',type:'ABSORBER'})
void = widget_button(absorber_data_menu,value = 'Remove all absorber files',     $
   uvalue = {object:self,method:'dcs_delete_all_folder_files'})
; Create the intermediate folder group menu
int_data_menu = widget_base(self.tlb,/context_menu,uname = 'INTERMEDIATE_FOLDER_MENU')
void = widget_button(int_data_menu,value = 'Remove all intermediate files',     $
   uvalue = {object:self,method:'dcs_delete_all_folder_files'})
; Create the empty data group menu
empty_data_menu = widget_base(self.tlb,/context_menu,uname = 'EMPTY_DATA_MENU')
void = widget_button(empty_data_menu,value = 'Show data treatment',   $
   uvalue = {object:self,method:'dcs_show_treatment'})
void = widget_button(empty_data_menu,value = 'Remove selected data file(s)',   $
   uvalue = {object:self,method:'dcs_delete_files'})
void = widget_button(empty_data_menu,value = 'Move selected data file(s) to signal folder',   $
   uvalue = {object:self,method:'dcs_move_files_to_signal'})
van_data_menu = widget_base(self.tlb,/context_menu,uname = 'VANADIUM_DATA_MENU')
void = widget_button(van_data_menu,value = 'Show data treatment',   $
   uvalue = {object:self,method:'dcs_show_treatment'})
void = widget_button(van_data_menu,value = 'Remove selected data file(s)',   $
   uvalue = {object:self,method:'dcs_delete_files'})
dark_data_menu = widget_base(self.tlb,/context_menu,uname = 'DARKCOUNT_DATA_MENU')
void = widget_button(dark_data_menu,value = 'Show data treatment',   $
   uvalue = {object:self,method:'dcs_show_treatment'})
void = widget_button(dark_data_menu,value = 'Remove selected data file(s)',   $
   uvalue = {object:self,method:'dcs_delete_files'})
absorber_data_menu = widget_base(self.tlb,/context_menu,uname = 'ABSORBER_DATA_MENU')
void = widget_button(absorber_data_menu,value = 'Show data treatment',   $
   uvalue = {object:self,method:'dcs_show_treatment'})
void = widget_button(absorber_data_menu,value = 'Remove selected data file(s)',   $
   uvalue = {object:self,method:'dcs_delete_files'})
; Create the intermediate data group menu
int_data_menu = widget_base(self.tlb,/context_menu,uname = 'INTERMEDIATE_DATA_MENU')
void = widget_button(int_data_menu,value = 'Show data treatment',   $
   uvalue = {object:self,method:'dcs_show_treatment'})
void = widget_button(int_data_menu,value = 'Remove selected data file(s)',   $
   uvalue = {object:self,method:'dcs_delete_files'})
;other bits at the end
void = widget_button(self.tlb,value = 'R E D U C E',uname='RED_BUTTON',$
        uvalue = {object:self,method:'reduce_data'})
;void = widget_label(self.tlb,value = 'PROGRAM STATUS/INFORMATION')
status_id = widget_text(self.tlb,value = '',uname = 'STATUS_TEXT')

;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
;fill in the PLOT tab
geo=widget_info(row_base,/geometry)
bigplot_base = widget_base(fTab,/row,title='PLOT',uname = 'BIGPLOT_BASE',frame=0)
choice_base=widget_base(bigplot_base,/column,uname = 'CHOICE_BASE',frame=0);$
;scr_xsize=(geo.scr_xsize-2*geo.xpad)/4-4*geo.xpad)
choice2_base=widget_base(bigplot_base,/column,uname = 'CHOICE2_BASE',frame=0);$
;scr_xsize=(geo.scr_xsize-2*geo.xpad)/4-4*geo.xpad)
base1=widget_base(choice_base,/column,frame=0)
;base2a=widget_base(base1,/row,xpad=0)
base2=widget_base(base1,/row,frame=1)
;base3=widget_base(choice_base,/column,xpad=0)
output = ['I(2th,t)','I(2th,w)','S(Q,w)','G(w)','PLOT SUMS', 'DETECTOR PLOT']
void = widget_combobox(base2,value=output, uname = 'DCS_PLOT_SEL',uvalue={object:self,method:'widget_handler'})
widget_control,void,SET_COMBOBOX_SELECT=2
type = ['IMAGE','CUT']
self.plot1D2D = widget_combobox(base2, value=type, uname = 'DCS_PLOT_TYPE',$
                 uvalue={object:self,method:'update_plot'})
widget_control,self.plot1d2d,SET_COMBOBOX_SELECT=1
baseboss1=widget_base(base1,/col,frame=1)
baseboss=widget_base(baseboss1,/row,frame=0)
base1a1=widget_base(baseboss,/col,frame=0)
void = widget_slider(baseboss1,title = 'Group selection',min = 1, max = 913, $
    value = 1,scr_xsize=44,uname = 'DCS_GROUP_SLIDER',$
    uvalue={object:self,method:'update_plot'})
void =widget_label(base1a1,value=' Min.     Max.')
base1a=widget_base(base1a1,/row,frame=0)
void=widget_label(base1a,value='x:')
void=widget_text(base1a,value='',xsize=4,ysize=1,/editable,uname='DCS_XMIN',$
    uvalue={object:self,method:'plotranges'})
void=widget_text(base1a,value='',xsize=4,ysize=1,/editable,uname='DCS_XMAX',$
    uvalue={object:self,method:'plotranges'})
base1b=widget_base(base1a1,/row,frame=0)
void=widget_label(base1b,value='y:')
void=widget_text(base1b,value='',xsize=4,ysize=1,/editable,uname='DCS_YMIN',$
    uvalue={object:self,method:'plotranges'})
void=widget_text(base1b,value='',xsize=4,ysize=1,/editable,uname='DCS_YMAX',$
    uvalue={object:self,method:'plotranges'})
base1b2=widget_base(baseboss,/col,frame=0)
void =widget_label(base1b2,value='Force')
base1a2=widget_base(base1b2,/col,/exclusive,frame=0)
void = widget_button(base1a2,value = 'yes',uname='FORCE_YES',$
     uvalue={object:self,method:'plotranges'})
no = widget_button(base1a2,value = 'no',uname='FORCE_NO',$
     uvalue={object:self,method:'plotranges'},xsize=10)
widget_control,no,set_button=1
base_max=widget_base(base1,/col,frame=1)
void = cw_field(base_max,/row,value = '1.0',title = 'Image Max  ', $
    uname = 'DCS_IMAGE_MAX',/noedit,$
    uvalue={object:self,method:'do_nothing'},xsize=15)
void = cw_field(base_max,/row,value = '1.0',title = 'Desired Max', $
    uname = 'DCS_DESIRED_IMAGE_MAX',/return_events,/floating,$
    uvalue={object:self,method:'widget_handler'},xsize=15)
void = widget_button(base_max,value = 'Image colors',xsize=5,$
   uname = 'COLORS',uvalue={object:self,method:'Change_colors'})
void =widget_label(choice_base,value='Masked Detectors')
void = widget_text(choice_base,/editable,value='',$
       uname='MASK',uvalue={object:self,method:'update_mask'})
mask_base = widget_base(choice_base,/row)
void = widget_label(mask_base, value="Plot Mode:  ")
mask_exclusive = widget_base(mask_base,/row,/exclusive)
zoom_button = widget_button(mask_exclusive, value=!dave_auxiliary_dir + "zoom.bmp", $
    /bitmap, uname="ZOOM_MODE", uvalue={object:self,method:'modeChange'}, tooltip="testing", /sensitive)
mask_button = widget_button(mask_exclusive,value=!dave_auxiliary_dir + "marquee.bmp", $
    /bitmap, uname="MASK_MODE", uvalue={object:self,method:'modeChange'}, /sensitive)
pan_button = widget_button(mask_exclusive,value=!dave_auxiliary_dir + "\move.bmp", $
    /bitmap, uname="PAN_MODE", uvalue={object:self,method:'modeChange'}, /sensitive)
widget_control,zoom_button,/set_button
widget_control,zoom_button,sensitive=1
widget_control,mask_button,sensitive=0
widget_control,pan_button,sensitive=0
ret=self->update_mask()
;set an initital mask
;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

;fill in the MISC tab
misc_row_base = widget_base(fTab,/row,title='MISC',uname = 'MISC_ROW_BASE',frame=1)
a_col_base=widget_base(misc_row_base,/col,uname = 'A_COL_BASE')
a_base=widget_base(a_col_base,/col,frame=1,uname = 'A_BASE')
a2 = ['Time','Monitor']
void = cw_bgroup(a_base, a2, /col, /exclusive,$
         label_top='Normalization',/no_release,$
         frame=0,set_value=1,/return_index, $
         uname = 'USE_NORMALIZATION',uvalue={object:self,method:'do_nothing'})

ac_base=widget_base(a_col_base,/col,frame=1,uname = 'A_BASE')
ac2 = ['No','Yes']
void = cw_bgroup(ac_base, ac2, /col, /exclusive,$
         label_top='Det. Efficiency?',/no_release,$
         frame=0,set_value=1,/return_index, $
         uname = 'USE_DETEFF',uvalue={object:self,method:'do_nothing'})

ad_base=widget_base(a_col_base,/col,frame=1,uname = 'A_BASE')
void = cw_bgroup(ad_base, ac2, /col, /exclusive,$
         label_top='Zero the Energy?',/no_release,$
         frame=0,set_value=0,/return_index, $
         uname = 'ZERO_ENERGY',uvalue={object:self,method:'do_nothing'})

ba_col_base=widget_base(misc_row_base,/col,uname = 'BA_COL_BASE')
ba_base=widget_base(ba_col_base,/col,frame=1,uname = 'BA_BASE')
void = CW_FIELD(ba_base,title='Temperature',/floating,xsize=12,/column,$ ;value=self.tnominal
                 /all_events,uname='TDEF',uvalue={object:self,method:'do_nothing'})
dbc = ['Yes','No']
void = cw_bgroup(ba_base, dbc, /col, /exclusive,$
         label_top='Detailed Balance',/no_release,$
         frame=0,set_value=1,/return_index, $
         uname = 'USE_DETAILEDB',uvalue={object:self,method:'do_nothing'})

ba2_base=widget_base(ba_col_base,/col,frame=1,uname = 'BA2_BASE')
atten = CW_FIELD(ba2_base,title='Attenuation Factor',/column,/floating,value=self.attenuation,xsize=12,$
                 /all_events,uvalue={object:self,method:'set_attenuation'})
void = cw_bgroup(ba2_base, dbc, /row, /exclusive,$
         label_top='Use Loaded Array?',/no_release,$
         frame=0,set_value=1,/return_index, $
         uname = 'USE_SSF_ARRAY',uvalue={object:self,method:'do_nothing'})
void = WIDGET_BUTTON(ba2_base,value='LOAD',uvalue={object:self,method:'load_SSF_array'})
widget_control,void,sensitive=0
;
;fast bg choice add extra fields for additional counts.linear 0,0 plus radio button
;from file (if available) default radio
fb_col_base=widget_base(misc_row_base,/col,uname = 'FB_COL_BASE')
fb_base=widget_base(fb_col_base,/col,frame=1,uname = 'FB_BASE')
void = WIDGET_LABEL(fb_base, VALUE='Darkcount Choice')
fb2= widget_base(fb_base,/col,frame=1)
dark2 = ['Yes','No']
void = cw_bgroup(fb2, dark2, /row, /exclusive,$
         label_top='Use Given Value?',/no_release,$
         frame=0,set_value=1,/return_index, $
         uname = 'USE_DARKCOUNT_ARRAY',uvalue={object:self,method:'do_nothing'})
void = CW_FIELD(fb2,title='rate/det./hr',/floating,value=self.dark,xsize=5,$
                 /all_events,uvalue={object:self,method:'set_darkcount_rate'})
void = CW_FIELD(fb2,title='error/det./hr',/floating,value=self.darkerr,xsize=5,$
                 /all_events,uvalue={object:self,method:'set_darkerr_rate'})

;vanadium choice load an array for this instead? to override having to choose same wavelength?
;overall E fit ot over each detector
van_base=widget_base(fb_col_base,/col,frame=1,uname = 'VAN_BASE')
void = WIDGET_LABEL(van_base, VALUE='Det. Norm. Choice')
v2= widget_base(van_base,/col,frame=1)
vanfile = ['Yes','No']
void = cw_bgroup(v2, vanfile, /row, /exclusive,$
         label_top='Use Loaded Array?',/no_release,$
         frame=0,set_value=1,/return_index, $
         uname = 'USE_VAN_ARRAY',uvalue={object:self,method:'do_nothing'})
void = WIDGET_BUTTON(v2,value='LOAD',uvalue={object:self,method:'load_van_array'})

;Q groups
q_base=widget_base(misc_row_base,frame=1,/col,uname = 'Q_BASE')
void = WIDGET_LABEL(q_base, VALUE='Detector Grouping Choices')
mainchoice=widget_base(q_base,/nonexclusive)
         gng=widget_button(mainchoice,value="DO NOT GROUP DETECTORS",$
         uname = 'NO_DET_GROUP',uvalue = {object:self,method:'q_widget'})
       bbase=widget_base(q_base,/col,/frame)
         bb1=widget_base(bbase,/col,/nonexclusive,/frame)
          negpos=widget_button(bb1,value="Combine negative and positive angle detectors",$
                uname = 'NEGPOS',uvalue = {object:self,method:'do_nothing'})
         bb2=widget_base(bbase,/col,/exclusive,/frame)
          lomiup=widget_button(bb2,value="Combine lower, middle and upper banks",$
              uname = 'LOMIUP',uvalue = {object:self,method:'do_nothing'})
          lowupp=widget_button(bb2,value="Combine lower and upper banks only",$
               uname = 'LOWUPP',uvalue = {object:self,method:'do_nothing'})
          donotc=widget_button(bb2,value="Do not combine detector banks",$
                uname = 'DONOTC',uvalue = {object:self,method:'do_nothing'})
         bb3=widget_base(bbase,/col,/exclusive,/frame)
          equal2=widget_button(bb3,value="Combine into groups with equal widths in 2theta",$
                  uname = 'EQUAL2',uvalue = {object:self,method:'q_widget'})
          equalQ=widget_button(bb3,value="Combine into groups with equal widths in ''Q''",$
                  uname = 'EQUALQ',uvalue = {object:self,method:'q_widget'})
         qthbase=widget_base(bbase,/row,/align_center)
          tthstepb=widget_base(qthbase,/col,sensitive=1)
              tthsteplabel=widget_label(tthstepb,value='Step in 2theta')
              tthsteptext=widget_text(tthstepb,/editable,/all_events,xsize=10,$
                       uname = 'TTSTEP',uvalue = {object:self,method:'do_nothing'})
          qstepb=widget_base(qthbase,/col,sensitive=1)
              qsteplabel=widget_label(qstepb,value="Step in ''Q''")
              qsteptext=widget_text(qstepb,/editable,/all_events,xsize=10,$
                       uname = 'QSTEP',uvalue = {object:self,method:'do_nothing'})
widget_control,tthsteptext,sensitive=0
widget_control,negpos,set_button=1
widget_control,lomiup,set_button=1
widget_control,equalq,set_button=1
widget_control,tthsteptext,set_value='20'
widget_control,qsteptext,set_value='0.25'
widget_control,atten,set_value='1,00'

;xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx  finished widget creation
centertlb,self.tlb
widget_control,self.tlb,/realize

;adjust base widgets after realizing
;1st tab
sizer=widget_info(row_base,/geometry)
;2nd tab
sizec=widget_info(choice_base,/geometry)
xs=sizer.scr_xsize-sizec.scr_xsize
widget_control,choice2_base,scr_xsize=xs
; changed "ysize=sizer.scr_ysize" to "ysize=sizec.scr_ysize"
; (since it's on the second tab) - EAB
self.win = widget_draw(choice2_base,xsize=xs,ysize=sizec.scr_ysize, $
   uvalue = {object:self,method:'plot_events'},/button_events,frame=1,uname='plotWin', $
   /motion_events)

widget_control,self.win,get_value = winvis
self.winvis = winvis
if !windows then begin
  winxsize = !d.x_size-2*!d.fill_dist
  winysize = !d.y_size-2*!d.fill_dist
endif else begin
  winxsize = !d.x_size
  winysize = !d.y_size
endelse
window,/free,/pixmap,xsize = winxsize,ysize = winysize
self.winpix = !d.window
wset,self.winPix
PLOT, [0, 1],[0, 1], xrange = [0,1],yrange = [0,1],/xsty,/ysty,$
       /NODATA ,background = 255,color =0,xtitle='x (units)', ytitle='y (units)',$
       position = [0.15,0.15,.95,0.9], title='NO DATA'
wset,self.winVis
device,copy = [0,0,!d.x_size,!d.y_size,0,0,self.winPix]

widget_control,self.tlb,set_uvalue = self
register_name = 'DCS_REDUCE'

;create a structure to keep all the initial geometries in
tlbgeo=widget_info(tlb,/geometry)
ftabgeo=widget_info(ftab,/geometry)
rowgeo=widget_info(row_base,/geometry)
infogeo=widget_info(self.fileinfo,/geometry)
bigplotinfo=widget_info(bigplot_base,/geometry)
plotinfo=widget_info(choice2_base,/geometry)
wininfo=widget_info(self.win,/geometry)
*(self.widget_info_ptr)={tlbgeo:tlbgeo,ftabgeo:ftabgeo,rowgeo:rowgeo,$
 infogeo:infogeo, bigplotinfo:bigplotinfo, plotinfo:plotinfo,wininfo:wininfo}

xmanager,register_name,self.tlb,event_handler = 'dcs_test_gui_events', $
   cleanup = 'dcs_test_gui_cleanup',/no_block
return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
function dcs_test_gui::init,  group_leader = group_leader,     $
                              work_dir = work_dir,             $
                              data_dir = data_dir,             $
                              notifyId = notifyId

registerName = 'DCS_REDUCE'
if xregistered(registerName) then begin ;only allow one DCS_REDUCE running
   FORWARD_FUNCTION LookupManagedWidget
   id = LookupManagedWidget(registername)
   widget_control,id,iconify=0
   return,0
endif

self.notifyIdPtr = ptr_new(/allocate_heap)
self.pgroup_leader = ptr_new(/allocate_heap)
if n_elements(notifyId) ne 0 then $
  *self.notifyIdPtr = notifyId
if n_elements(group_leader) ne 0 then begin
  *self.pgroup_leader = group_leader
  widget_control,group_leader,get_uvalue = statePtr
  self.daveptr=(*stateptr).daveptr
endif else begin
  ;need to define a useful pointer if using stand alone or it breaks.
   self.daveptr = ptr_new(/allocate_heap)
endelse

if n_elements(work_dir) eq 0 then cd,current = work_dir
if n_elements(data_dir) eq 0 then cd,current = data_dir
if n_elements(data_dir) ne 0 then self.data_dir=data_dir
if n_elements(work_dir) ne 0 then self.work_dir=work_dir


;FYI: INCASE THESE EVER CHANGE THEY ARE PASSED INTO THE DCS_DATA OBJECT
self.nhedet = 913
self.ntchan = 1024
self.mask_ptr=ptr_new(intarr(913)+1)
self.maskedX = ptr_new([-1])
self.maskedY = ptr_new([-1])
self.iwasmasking=0
self.sel_colors_ptr = ptr_new(/allocate_heap)
self.sym_ptr = ptr_new(/allocate_heap)
self.work_dir = work_dir
self.data_dir = data_dir
self.tlb = 0L
self.dcs_container = obj_new('IDL_CONTAINER')
self.ddcs_color_ptr = ptr_new(/allocate_heap)
self.dave_color_ptr = ptr_new(/allocate_heap)
self.color_ptr = ptr_new(/allocate_heap)
self.plot1D2D=0L
self.widget_info_ptr = ptr_new(/allocate_heap)
self.vanarr = fltarr(913)+1

ret = self->build_gui()

self.sff_ptr = ptr_new(/allocate_heap)
self.ddcs_dc = 0
self.dark=0.0
self.darkerr=0.0
self.attenuation=1.00
device,decomposed = self.ddcs_dc
self.xrange = [0.0,1.0] & self.yrange = [0.0,1.0]
self.autoscale = 1
self.force_range = 0


return,1
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pro dcs_test_gui__define
class =  {  dcs_test_gui,                 $
            tlb:0L,                             $   ; my top level base
            notifyIdPtr:ptr_new(),              $   ; incase I need to tell DAVE what is happening
            pgroup_leader:ptr_new(),            $   ; calling program ID
            dave_color_ptr:ptr_new(),           $   ; dave colors
            ddcs_color_ptr:ptr_new(),           $   ; current colors
            dave_dc:0,                          $   ; device decomposed from calling function
            ddcs_dc:0,                          $   ; device decomposed here
            color_ptr:ptr_new(),                $   ; 2D plotting colors
            sel_colors_ptr:ptr_new(),           $
            colorTable:5,                       $   ; this is where I put the color index
            sym_ptr:ptr_new(),                  $   ; Store symbol definitions if needed
            work_dir:'',                        $   ; DAVE paths
            data_dir:'',                        $   ; DAVE paths
            daveptr:ptr_new(),                  $   ; the DAVE POINTER from calling program is available
                                       ; DELETE IN THIS PROGRAM? YES or NO?
            widget_info_ptr:ptr_new(),          $   ;  all the initial widget size needed to resize properly
            file_tree:0L,                       $   ; 1st TAB file tree widget
            fileinfo:0L,                        $   ; 1st TAB information text widget
            win:0L,                             $   ; draw widget value
            winvis:0L,                          $   ; visible window value
            winpix:0L,                          $   ; pixmap widget value
            mouse:0B,                           $   ; Mouse coordinate on the PIXMAP
            xbox:intarr(2),                     $   ; Mouse selection
            ybox:intarr(2),                     $   ; Mouse selection
            xrange:fltarr(2),                   $   ; plotting parameters
            yrange:fltarr(2),                   $
            force_range:0,                      $   ; force the plot range to the widget values?
            autoscale:1,                        $   ; will I autoscale or not?
            plot1D2D:0L,                        $   ; plot selection type 1D or 2D
            dark:0.0,                           $   ; darkcount rate for widget input
            darkerr:0.0,                        $   ; corresponding error
            attenuation:1.0,                    $   ; scalar attenuation factor
            sff_ptr:ptr_new(),                  $   ; if available the array of self shielding factors
            vanarr:fltarr(913),                 $   ; an external 913 element scaling array
            mask_ptr:ptr_new(),                 $   ; Detector masking vector 0 or 1
            nhedet:0,                           $   ; hard wired values 913 detectors
            ntchan:0,                           $   ; 1000 time channels
            dcs_container:obj_new(),            $
            plot_mode:"ZOOM_MODE",          $ ; mode user is in on the Plot tab
            maskedX:ptr_new(),            $    ; x coords of masked points
            maskedY:ptr_new(),             $ ; y coords of masked points
            iwasmasking:0                   $ ; flag to change gui
            }
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; to do
; check all arrays for correct output
;self_shielding transmission factors
;masking procedure
;log intensities
;
;
