; $Id: dave.pro,v 1.169 2008/04/28 15:02:45 azuah Exp $
;###############################################################################
;
; NAME:
;   dave
;
; PURPOSE:
;   Data Analysis and Visualization Environment
;   This file defines the core DAVE application framework.
;
; CATEGORY:
;   DAVE framework
;
; AUTHORS:
;   Robert M. Dimeo
;   John R.D. Copley
;   Alan Munter
;   Richard Tumanjong Azuah
;   Larry Kneller
;
;   NIST Center for Neutron Research
;   100 Bureau Drive, Gaithersburg, MD 20899
;   United States
;
; LICENSE:
;  The software in this file is written by an employee of
;  National Institute of Standards and Technology
;  as part of the DAVE software project.
;
;  The DAVE software package is not subject to copyright protection
;  and is in the public domain. It should be considered as an
;  experimental neutron scattering data reduction, visualization, and
;  analysis system. As such, the authors assume no responsibility
;  whatsoever for its use, and make no guarantees, expressed or
;  implied, about its quality, reliability, or any other
;  characteristic. The use of certain trade names or commercial
;  products does not imply any endorsement of a particular product,
;  nor does it imply that the named product is necessarily the best
;  product for the stated purpose. We would appreciate acknowledgment
;  if the DAVE software is used of if the code in this file is
;  included in another product.
;
;###############################################################################



;===============================================================================
; daveCleanup
;
; PURPOSE:
;   Cleanup routine called when the main widget is destroyed
;
; PARAMETERS:
;   tlbID [in] - the widget id of the top-level-base that is being
;                killed.
;
pro daveCleanup,tlb
widget_control,tlb,get_uvalue = pState
obj_destroy,(*(*pState).extraPtr).panInfo.panContainer

ptr_free,(*pState).extraPtr

heap_free, (*pState).davePtr    ; RTA (Feb,03) - replace previous 7 'ptr_free' statements with one 'heap_free'
ptr_free,pState
;ptr_free, !dave_e_window        ; RMD (Feb 04)
heap_free, !dave_defaults        ; RTA (Feb,03)
help,/heap,/brief
temp = ptr_valid(count=nptr)
print,'Number of dangling pointers: ',nptr
managed_widgets = widget_info(/managed)
;if managed_widgets[0] eq 0 then begin ; RTA - remove b/c makes it difficult to pick up leaks from otherDAVE modules
;  heap_free,ptr_valid() & obj_destroy, obj_valid()
;endif
temp = ptr_valid(count=nptr)
print,'Number of pointers left after cleanup: ',nptr
;if nptr eq 0 then print,'...pointers freed'

; If in the development environment, and running Windows,
; restore the launchtime current directory.
if (not lmgr(/runtime) and !version.os_family eq "Windows") then cd,!thisDir

end
;-------------------------------------------------------------------------------



;===============================================================================
; dave_gui_init_window
;
; PURPOSE:
;   Initialize routine. Ensure a graphics window can be created.
;
; PARAMETERS:
;
pro dave_gui_init_window
catch,the_error
if the_error ne 0 then begin
  catch,/cancel
  wdelete,!d.window
  return
endif
window,/free,/pixmap
if !d.window ne -1 then wdelete,!d.window
catch,/cancel
end
;-------------------------------------------------------------------------------



;===============================================================================
; fdaveQuit
;
; PURPOSE:
;   Event handler. Exit DAVE application without saving tree widget state.
;
; PARAMETERS:
;   event [in] - the event structure.
;
pro fdaveQuit,event
;
widget_control,event.top,/destroy
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; fdaveExit
;
; PURPOSE:
;   Event handler. Exit DAVE application after saving the tree widget
;   menu state.
;
; PARAMETERS:
;   event [in] - the event structure.
;
pro fdaveExit,event
;
id = widget_info(event.top,find_by_uname = 'TREE_WIDGET')
if (id gt 0l) then begin
    ids = get_all_ids(id)
    nids=n_elements(ids)
    button_names=strarr(nids)
    button_state=intarr(nids)
    for k=0,nids-1 do begin
        widget_control,ids[k],get_value=temp
        button_names[k]=temp
        temp=widget_info(ids[k],/tree_expanded)
        button_state[k]=temp
    endfor
    dave_defs=*!dave_defaults
    if (ptr_valid(dave_defs.tree_menu_pointer)) then ptr_free,dave_defs.tree_menu_pointer
    dave_defs.tree_menu_pointer=ptr_new({button_state:button_state,button_names:button_names})
    pdd=!dave_defaults
    heap_free, pdd
    pdd=ptr_new(dave_defs)


    save,filename=!defaults_file,pdd
    heap_free, pdd
endif
;
widget_control,event.top,/destroy
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; fdaveAboutDave
;
; PURPOSE:
;   Event handler. Display version info.
;
; PARAMETERS:
;   event [in] - the event structure.
;
pro fdaveAboutDave,event
aboutDave,group_leader = event.top
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; dave_wait_message
;
; PURPOSE:
;   Create a dialog box to display the specified message.
;
; PARAMETERS:
;   msg [in] - text message to be displayed.
;
; RETURN VALUE:
;   The tlb of the created dialog.
;
function dave_wait_message,msg
tlb = widget_base(/col,title = 'DAVE',tlb_frame_attr=13)
; Determine the color depth of the computer
device,get_visual_depth = thisDepth
if thisDepth eq 8 then begin
    image = read_png(!DAVE_AUXILIARY_DIR+'DAVE_title.png',r,g,b)
    s = size(image)
    sx = s[1] & sy = s[2]
endif else begin
    read_jpeg,!DAVE_AUXILIARY_DIR+'DAVE_title.jpg',image
    s = size(image)
    sx = s[2] & sy = s[3]
endelse
aspect = 1.0*sy/sx              ; find the aspect ratio of the image...
; ...and set the display window's dimensions based on this
; aspect ratio.
winxsize = 500 & winysize = fix(aspect*winxsize)
winbase = widget_base(tlb,xsize = winxsize,ysize = winysize)
win = widget_draw(winbase,xsize = winxsize,ysize = winysize)
void = widget_text(tlb,value = msg,xsize = 40, $
                   font = 'GARAMOND*BOLD*24')
centertlb,tlb
widget_control,tlb,/realize

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

;wset,winPix
if thisDepth eq 8 then begin
    device,decomposed = 0
    tvlct,r,g,b                 ; load the proper color tables as found in
                                ; read_png above.
    dispImage = congrid(image,winxsize,winysize)
endif else begin
    device,decomposed = 1
    dispimage = image
endelse

wset,winPix
tvimage,dispImage
wset,winVis
device,copy = [0,0,!d.x_size,!d.y_size,0,0,winPix]
wdelete,winPix

return,tlb
end
;-------------------------------------------------------------------------------



;===============================================================================
; dave_defs_checkout
;
; PURPOSE:
;   Certain user settings are saved between DAVE sessions. This
;   routine ensures that the saved structure has all the proper
;   fields.
;
; PARAMETERS:
;   dave_defs [in] - An IDL structure conatining the session variables
;                    fields to be saved.
;
; RETURN VALUE:
;   status flag. Insignificant.
;
function dave_defs_checkout, dave_defs
; RTA - completely revamp code to insert the necessary tags in the
;       dave_defs structure instead of simply checking.
;
; "WEB_BROWSER" tag added 2-4-04 (RMD)
cd,current=cwd
tags_present = strupcase(tag_names(dave_defs))
; insert 'datDir' field if necessary
void = where(tags_present eq 'DATDIR', count)
if (count le 0) then dave_defs = create_struct(dave_defs, 'datDir', cwd)
; insert 'workDir' field if necessary
void = where(tags_present eq 'WORKDIR', count)
if (count le 0) then dave_defs = create_struct(dave_defs, 'workDir', cwd)
; insert PDF Reader field if necessary
void = where(tags_present eq 'PDFREADER', count)
if (count le 0) then dave_defs = create_struct(dave_defs, 'PDFReader', '')
; insert Web Browser field if necessary
void = where(tags_present eq 'WEB_BROWSER', count)
if (count le 0) then dave_defs = create_struct(dave_defs, 'web_browser', '')
; insert classic field if necessary
void = where(tags_present eq 'CLASSIC', count)
if (count le 0) then dave_defs = create_struct(dave_defs, 'classic', 1B)
; insert show_choice field if necessary
void = where(tags_present eq 'SHOW_CHOICE', count)
if (count le 0) then dave_defs = create_struct(dave_defs, 'show_choice', 1B)
; insert tree menu pointer field if necessary
void = where(tags_present eq 'TREE_MENU_POINTER', count)
if (count le 0) then dave_defs = create_struct(dave_defs, 'tree_menu_pointer', ptr_new(/allocate_heap))

; insert 'psd_a4_spacing' field if necessary
void = where(strlowcase(tags_present) eq 'psd_a4_spacing', count)
if (count le 0) then dave_defs = create_struct(dave_defs, 'psd_a4_spacing','')


; insert 'psd_channel_Eff' field if necessary
void = where(strlowcase(tags_present) eq 'psd_channel_eff', count)
if (count le 0) then dave_defs = create_struct(dave_defs, 'psd_channel_eff','')

; insert 'psd_Ef_spacing' field if necessary
void = where(strlowcase(tags_present) eq 'psd_ef_spacing', count)
if (count le 0) then dave_defs = create_struct(dave_defs, 'psd_ef_spacing', '')


return, 0

end
;-------------------------------------------------------------------------------



;===============================================================================
; fdaveSelBothDirectories
;
; PURPOSE:
;   Event handler. Let user specify data and working directories. The specified
;   values are stored in a global variable and also saved for future  DAVE
;   sessions.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro fdaveSelBothDirectories,event
daveDeSensitizeButtons,event
dave_defs=*!dave_defaults
old_directory=dave_defs.datDir
directory = DIALOG_PICKFILE(title = 'Select directory',/directory,path=old_directory)
if (directory eq '' or directory eq ' ') then begin
    daveSensitizeButtons,event
    return
endif
dave_defs.datDir=directory
dave_defs.workDir=directory
pdd=!dave_defaults
ptr_free,pdd
pdd=ptr_new(dave_defs)

	save,filename=!defaults_file,pdd
defsysv,'!dave_defaults',pdd
cd,current=curDir
if (old_directory ne directory) then $
  x=dialog_message(["The raw (and working) directory is "+ $
                    (*!dave_defaults).datDir,""],$
                   /information)
daveSensitizeButtons,event
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; fdaveSelDataDirectory
;
; PURPOSE:
;   Event handler. Let user specify data directory. The specified
;   value is stored in a global variable and also saved for future DAVE
;   sessions.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro fdaveSelDataDirectory,event
daveDeSensitizeButtons,event
dave_defs=*!dave_defaults
old_directory=dave_defs.datDir
directory = DIALOG_PICKFILE(title = 'Select data directory',/directory,path=old_directory)
if (directory eq '' or directory eq ' ') then begin
    daveSensitizeButtons,event
    return
endif
dave_defs.datDir=directory
pdd=!dave_defaults
ptr_free,pdd
pdd=ptr_new(dave_defs)

	;LRK 051507
	;ADDING THE CHECKING BECAUSE OF POTENTIAL NETWORK DRIVE INACCESSIBLE ISSUES
	if file_test(!defaults_file,/write) eq 0 then begin

		yn = dialog_message('Your chosen home directory appears to be inaccessible.  Would you like to choose a new one?',/question)
		print,yn

		if strupcase(yn) eq 'YES' then begin
			print,'!defaults_file=',!defaults_file
			hmdir = dialog_pickfile(/directory)

			if hmdir ne '' then begin
				!defaults_file = hmdir+path_sep()+file_basename(!defaults_file)
				save,filename=!defaults_file,pdd
			endif
		endif

	endif else begin
		save,filename=!defaults_file,pdd
	endelse
;	LRK 051507 COMMENTED THE FOLLOWING LINE
;	save,filename=!defaults_file,pdd
defsysv,'!dave_defaults',pdd
cd,current=curDir
if (old_directory ne directory) then $
  x=dialog_message(["The raw data directory is "+(*!dave_defaults).datDir,"",$
                    "The working directory is "+(*!dave_defaults).workDir],$
                   /information)
daveSensitizeButtons,event
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; fdaveSelWorkDirectory
;
; PURPOSE:
;   Event handler. Let user specify working directory. The specified
;   value is stored in a global variable and also saved for future DAVE
;   sessions.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro fdaveSelWorkDirectory,event
daveDeSensitizeButtons,event
dave_defs=*!dave_defaults
old_directory=dave_defs.workDir
directory = DIALOG_PICKFILE(title = 'Select working directory',/directory,path=old_directory)
if (directory eq '' or directory eq ' ') then begin
    daveSensitizeButtons,event
    return
endif
dave_defs.workDir=directory
pdd=!dave_defaults
ptr_free,pdd
pdd=ptr_new(dave_defs)

	save,filename=!defaults_file,pdd


defsysv,'!dave_defaults',pdd
cd,current=curDir
if (old_directory ne directory) then $
  x=dialog_message(["The raw data directory is "+(*!dave_defaults).datDir,"",$
                    "The working directory is "+(*!dave_defaults).workDir],$
                   /information)
daveSensitizeButtons,event
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; fdaveDisplayDirectories
;
; PURPOSE:
;   Event handler. Display current settings for data and working directories.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro fdaveDisplayDirectories,event
daveDeSensitizeButtons,event
;cd,current=curDir
x=dialog_message(["The raw data directory is "+(*!dave_defaults).datDir,"",$
                  "The working directory is "+(*!dave_defaults).workDir],$
                 /information)
daveSensitizeButtons,event
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; fdaveSELpdfreader
;
; PURPOSE:
;   Event handler. Let user specify a PDF Reader app. The specified
;   value is stored in a global variable and also saved for future DAVE
;   sessions.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro fdaveSELpdfreader,event

dave_defs=*!dave_defaults
PDFReader=dave_defs.PDFReader
;print,"Current pdfreader is ",PDFReader

; check and then exit if reader's selected reader is okay
readerNotOkay = 'Yes'
if (strtrim(PDFReader,2) ne '') then begin
    message_text = ['Your PDF reader is currently set to:',PDFReader, $
                    'Are you sure you want to change this setting?']
    readerNotOkay = dialog_message(message_text,/question,/default_no, $
                                   title='PDF Reader Setting')
    readerBaseDir = strmid(PDFReader,0,strpos(PDFReader,!delimiter,/reverse_search))
endif
if (readerNotOkay eq 'No') then return ; nothing to do

; let user select select a reader
daveDeSensitizeButtons,event
if n_elements(event.top) gt 0 then begin
    acroread = dialog_pickfile(dialog_parent = event.top,/read, $
                               title="Please select your PDF reader", $
                               path=readerBaseDir, $
                               file = PDFReader)
endif else begin
    acroread = dialog_pickfile(/read, title="Please select your PDF reader", $
                               path=readerBaseDir, $
                               file = PDFReader)
endelse

if (acroread eq '' or acroread eq ' ') then begin
    daveSensitizeButtons,event
    return
endif
dave_defs.PDFReader=acroread
pdd=!dave_defaults
ptr_free,pdd
pdd=ptr_new(dave_defs)



	save,filename=!defaults_file,pdd


defsysv,'!dave_defaults',pdd
print,"New pdfreader is ",(*!dave_defaults).PDFReader
daveSensitizeButtons,event
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; fdaveSELbrowser
;
; PURPOSE:
;   Event handler. Let user specify a web browser. The specified
;   value is stored in a global variable and also saved for future DAVE
;   sessions.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro fdaveSELbrowser,event
; Added this routine: RMD, February 7, 2004
dave_defs=*!dave_defaults
web_browser = dave_defs.web_browser

; check and then exit if reader's selected browser is okay
readerNotOkay = 'Yes'
if (strtrim(web_browser,2) ne '') then begin
    message_text = ['Your web_browser reader is currently set to:',web_browser, $
                    'Are you sure you want to change this setting?']
    readerNotOkay = dialog_message(message_text,/question,/default_no, $
                                   title='Web browser Setting')
    readerBaseDir = strmid(web_browser,0,strpos(web_browser,!delimiter,/reverse_search))
endif
if (readerNotOkay eq 'No') then return ; nothing to do

; let user select select a reader
daveDeSensitizeButtons,event
if n_elements(event.top) gt 0 then begin
    browser = dialog_pickfile(dialog_parent = event.top,/read, $
                              title="Please select your web browser", $
                              path=readerBaseDir, $
                              file = web_browser)
endif else begin
    browser = dialog_pickfile(/read, title="Please select your web_browser", $
                              path=readerBaseDir, $
                              file = web_browser)
endelse

if ((browser eq '') or (browser eq ' ')) then begin
    daveSensitizeButtons,event
    return
endif
dave_defs.web_browser = browser
pdd=!dave_defaults
ptr_free,pdd
pdd=ptr_new(dave_defs)



	save,filename=!defaults_file,pdd


defsysv,'!dave_defaults',pdd
print,"New web browser is ",(*!dave_defaults).web_browser
daveSensitizeButtons,event
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; fdaveSwapDebugFlag
;
; PURPOSE:
;   Event handler. Toggle debug flag on|off. The debug flag is stored
;   as a global variable, !debug, which can be used to conditionally
;   avoid blocks of code when it is off.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro fdaveSwapDebugFlag, event

if (!debug) then $
  print,'!debug Old value: ',!debug

!debug = (!debug eq 0)? 1 : 0   ; switch !debug b/n 0 and 1

case !debug of                  ; set appropriate label
    0: widget_control, event.id, set_value='Switch on debug flag'
    1: widget_control, event.id, set_value='Switch off debug flag'
endcase

if (!debug) then $
  print,'!debug New value: ',!debug

end
;-------------------------------------------------------------------------------



;===============================================================================
; DCSreductionHelp
;
; PURPOSE:
;   Event handler. Display DCS data reduction help info.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro DCSreductionHelp,event
widget_control,event.top,get_uvalue = pState
xdisplayfile,!DAVE_AUXILIARY_DIR+'DCSreductionHelp.txt'
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; hfbs_Help
;
; PURPOSE:
;   Event handler. Display HFBS data reduction manual.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro hfbs_Help,event
widget_control,event.top,get_uvalue = pState
void = launch_help(!DAVE_AUXILIARY_DIR+'hfbsreduction.pdf',tlb = event.top)
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; fcs_Help
;
; PURPOSE:
;   Event handler. Display FCS data reduction manual.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro fcs_Help,event
widget_control,event.top,get_uvalue = pState
void = launch_help(!DAVE_AUXILIARY_DIR+'fcs_manual.pdf',tlb = event.top)
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; fans_Help
;
; PURPOSE:
;   Event handler. Display FANS data reduction manual.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro fans_Help,event
widget_control,event.top,get_uvalue = pState
void = launch_help(!DAVE_AUXILIARY_DIR+'fans_dave_manual.pdf',tlb = event.top)
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; dataBrowser_Help
;
; PURPOSE:
;   Event handler. Display DataBrowser manual.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro dataBrowser_Help,event
widget_control,event.top,get_uvalue = pState
void = launch_help(!DAVE_AUXILIARY_DIR+'databrowser.pdf',tlb = event.top)
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; menuitems_Help
;
; PURPOSE:
;   Event handler. Displays brief description of all current menu
;   items in DAVE.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro menuitems_Help,event
widget_control,event.top,get_uvalue = pState
void = launch_help(!DAVE_AUXILIARY_DIR+'menuitems.pdf',tlb = event.top)
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; pan_Help
;
; PURPOSE:
;   Event handler. Display PAN manual.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro pan_Help,event
widget_control,event.top,get_uvalue = pState
;void = launch_help(!DAVE_AUXILIARY_DIR+'pandoc.pdf',tlb = event.top)
void = launch_help(!DAVE_AUXILIARY_DIR+'pandoc_DAVE.pdf',tlb = event.top)
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; rains_Help
;
; PURPOSE:
;   Event handler. Display RAINS manual.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro rains_Help,event
widget_control,event.top,get_uvalue = pState
void = launch_help(!DAVE_AUXILIARY_DIR+'rains_models.pdf',tlb = event.top)
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; mslice_Help
;
; PURPOSE:
;   Event handler. Display MSlice manual.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro mslice_Help,event
widget_control,event.top,get_uvalue = pState
void = launch_help(!DAVE_AUXILIARY_DIR+'dcs_mslice.pdf',tlb = event.top)
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; ascii_Help
;
; PURPOSE:
;   Event handler. Display ASCII Reader manual.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro ascii_Help,event
widget_control,event.top,get_uvalue = pState
void = launch_help(!DAVE_AUXILIARY_DIR+'ascii_help.pdf',tlb = event.top)
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; gaussian98_Help
;
; PURPOSE:
;   Event handler. Display GAUSSIAN98 manual.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro gaussian98_Help,event
widget_control,event.top,get_uvalue = pState
void = launch_help(!DAVE_AUXILIARY_DIR+'gaussian1.pdf',tlb = event.top)
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; rotord_Help
;
; PURPOSE:
;   Event handler. Display Diatomic Rotor Calculation manual.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro rotord_Help,event
widget_control,event.top,get_uvalue = pState
void = launch_help(!DAVE_AUXILIARY_DIR+'diatomiccalc.pdf',tlb = event.top)
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; rotorm_Help
;
; PURPOSE:
;   Event handler. Display Methyl Rotor Calculation manual.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro rotorm_Help,event
widget_control,event.top,get_uvalue = pState
void = launch_help(!DAVE_AUXILIARY_DIR+'methylcalc.pdf',tlb = event.top)
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; ToolsHelp
;
; PURPOSE:
;   Event handler. Display Tools manual.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro ToolsHelp,event
widget_control,event.top,get_uvalue = pState
xdisplayfile,!DAVE_AUXILIARY_DIR+'ToolsHelp.txt'
return
end
;-------------------------------------------------------------------------------



;===============================================================================
; DCSToolsHelp
;
; PURPOSE:
;   Event handler. Display DCS Tools help info.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro DCSToolsHelp,event
widget_control,event.top,get_uvalue = pState
xdisplayfile,!DAVE_AUXILIARY_DIR+'DCSToolsHelp.txt'
return
end
;-------------------------------------------------------------------------------


;;===============================================================================
;; NSE_Help
;;
;; PURPOSE:
;;   Event handler. Display NSE manual.
;;
;; PARAMETERS:
;;   event [in] - event structure.
;;
pro NSE_Help,event
    widget_control,event.top,get_uvalue = pState
    void = launch_help(!DAVE_AUXILIARY_DIR+'nse_reduction_manual.pdf',tlb = event.top)
    ;void = dialog_message('NSE Help file is coming soon!',/info)
    return
end
;-------------------------------------------------------------------------------






;===============================================================================
; dave_menu_choice
;
; PURPOSE:
;   Event handler. Save user's DAVE menu choice.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro dave_menu_choice,event


;LRK 051507
;DO I NEED TO CHECK FOR THIS FILE AS WELL?????
restore,!defaults_file
(*pdd).show_choice = 1B
defsysv,'!dave_defaults',pdd
save,filename=!defaults_file,pdd
end
;-------------------------------------------------------------------------------



;===============================================================================
; dave_loadfile
;
; PURPOSE:
;   Event handler. Load an existing DAVE file.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro dave_loadfile, event

; select file to load
filename = dialog_pickfile(dialog_parent=event.top $
                           ,title='Select DAVE data file to load' $
                           ,/read,filter='*.dave' $
                           ,path=(*!dave_defaults).workDir $
                           ,get_path = this_path)
if filename[0] eq '' then return

restore,filename[0], /relaxed_structure_assignment

; make sure a valid davePtr was restored
if (ptr_valid(davePtr)) then begin
    widget_control, event.top, get_uvalue=pState
    heap_free,(*pState).davePtr
    (*pState).davePtr = davePtr
endif

end
;-------------------------------------------------------------------------------



;===============================================================================
; dave_build_menu
;
; PURPOSE:
;   Construct DAVE's menu hierarchy in classic mode
;
; PARAMETERS:
;   tlb [in] - widget id of tlb of main DAVE widget.
;

;
;050307 - LRK
;PLEASE SEE FILE DaveMenuXMLSpecification.xml IN THE auxiliary
;DIRECTORY TO ADD A MENU ITEM. --- PLEASE BE SURE TO UPDATE FROM THE REPOSITORY
;                                  BEFORE ADDING AN ITEM.
;
pro dave_build_menu,tlb

; Determine the color depth of the computer
device,get_visual_depth = thisDepth
if thisDepth eq 8 then begin
    image = read_png(!DAVE_AUXILIARY_DIR+'DAVE_title.png',r,g,b)
    s = size(image)
    sx = s[1] & sy = s[2]
endif else begin
    read_jpeg,!DAVE_AUXILIARY_DIR+'DAVE_title.jpg',image
    s = size(image)
    sx = s[2] & sy = s[3]
endelse

aspect = 1.0*sy/sx              ; find the aspect ratio of the image...
; ...and set the display window's dimensions based on this
; aspect ratio.
winxsize = 600 & winysize = fix(aspect*winxsize)
if (lmgr(/runtime)) then tlb_title = 'DAVE: Data Analysis and Visualization Environment' $
else tlb_title = 'DAVE: Data Analysis and Visualization Environment - running under IDLDE'
tlb = widget_base(/row,tlb_frame_attr = 0,mbar = bar, title = tlb_title,uname = 'DAVE')
win = widget_draw(tlb,xsize = winxsize,ysize = winysize)

filemenu = widget_button(bar,value = 'File',/menu)
void = widget_button(filemenu,value='Load an existing DAVE file',event_pro='dave_loadfile')
void = widget_button(filemenu,value = 'Select raw data directory',$
                     xsize=butsize,event_pro='fdaveSelDataDirectory',/separator)
void = widget_button(filemenu,value = 'Select working directory',$
                     xsize = butsize,event_pro = 'fdaveSelWorkDirectory')
void = widget_button(filemenu,value = 'Select data AND working directory',$
                     xsize = butsize,event_pro = 'fdaveSelBothDirectories')
void = widget_button(filemenu,value = 'Display directories',$
                     xsize = butsize,event_pro = 'fdaveDisplayDirectories')
void = widget_button(filemenu,value = 'Select pdf reader',$
                     xsize = butsize,event_pro = 'fdaveSELpdfreader')
void = widget_button(filemenu,value = 'Select web browser',$
                     xsize = butsize,event_pro = 'fdaveSELbrowser')
void = widget_button(filemenu,value = 'Start E-notebook',/separator,$
                     xsize = butsize,event_pro = 'dave_launch_e_notes')
void = widget_button(filemenu,value = 'Give user choice of menu system next time',/separator,$
                     xsize = butsize,event_pro = 'dave_menu_choice')
; debug flag widget should not appear in embedded version
if (not lmgr(/runtime)) then $
  void = widget_button(filemenu,value='Switch on debug flag',event_pro='fdaveSwapDebugFlag')
void = widget_button(filemenu,value = 'Exit',event_pro = 'fdaveExit',$
                     xsize = butsize)

redMenu = widget_button(bar,value = 'Data Reduction',/menu)


dcsred = widget_button(redMenu,value = 'DCS',/menu)
void = widget_button(dcsRed,value = 'GUI: DCS reduction',$
                     event_pro = 'launch_dcsgui')
void = widget_button(dcsRed,value = 'Reduce DCS raw data',$
                     event_pro = 'DCSReduceRawData')
void = widget_button(dcsRed,value = 'DCS Mslice', $
                     event_pro = 'dcs_mslice')
fcsred = widget_button(redMenu,value = 'FCS',/menu)
void = widget_button(fcsRed,value = 'Reduce FCS raw data',$
                     event_pro = 'launchfcsreduction')
void = widget_button(fcsRed,value = 'Help on FCS reduction',$
                     event_pro = 'fcs_help')
hfbsRed = widget_button(redMenu,value = 'HFBS',/menu)
void = widget_button(hfbsRed,value = 'Reduce .HFBS data',$
                     event_pro = 'launch_hfbsred')
void = widget_button(hfbsRed,value = 'Reduce .HSCN data',$
                     event_pro = 'hfbs_reduce_hscn')
void = widget_button(hfbsRed,value = 'Convert DAVE to CON',$
                     event_pro = 'hfbs_runCon')
void = widget_button(hfbsRed,value = 'Help on HFBS reduction',$
                     event_pro = 'hfbs_help')


tasred = widget_button(redMenu,value = 'TAS',/menu)

void = widget_button(tasRed,value = 'TASXP',$
                     event_pro = 'fdaveTAS', uvalue='XP')
void = widget_button(tasRed,value = 'TAS Data Reduction',$
                     event_pro = 'launch_dtas')
void = widget_button(tasRed,value = 'SPINS PSD Calibration',$
                     event_pro = 'launch_dave_calibratepsd')
;     void = widget_button(tasRed,value = 'HB1A TAS Data Reader',$
;         event_pro = 'launch_hb1a_tas')
fansRed = widget_button(redMenu,value = 'FANS',/menu)
void = widget_button(fansRed,value='Reduce FANS (*.bt4) data',event_pro='launchfansdatreduc')
void = widget_button(fansRed,value = 'Help on FANS reduction',$
                     event_pro = 'fans_help')


nsered = widget_button(redMenu,value = 'NSE',/menu)

void = widget_button(nseRed,value = 'Reduce NSE data',$
                     event_pro = 'launch_nse')
void = widget_button(nseRed,value = 'Help on NSE reduction',$
                     event_pro = 'nse_help')

reflred = widget_button(redMenu,value = 'REFLECTOMETRY',/menu)
void = widget_button(reflRed,value = 'ReflRed: Reduce Reflectometry Data',$
                     event_pro = 'launch_reflpak',uvalue='reflred')




PSIredMenu = widget_button(redMenu,value = 'PSI',/menu)

void = widget_button(PSIredMenu,value = 'Reduce FOCUS Data',$
                     event_pro = 'launch_FOCUSred')


asciiMenu = widget_button(redMenu,value = 'ASCII data',/menu)
void = widget_button(asciiMenu,value = 'ASCII data->DAVE',event_pro = 'launch_ascii')



visMenu = widget_button(bar, value = 'Visualization', /menu)
;   twoDRen = widget_button(visMenu, value = 'Trifenestra (Three Windows)' $
;     , event_pro = 'fdaveTAS', uvalue='PSD')
;   void = widget_button(visMenu,value = 'Simple image slicer',event_pro = 'daveLaunchIS')
void = widget_button(visMenu,value='Data Browser',event_pro='launch_dave_db')
void = widget_button(visMenu,value = 'DAVE PEEK',event_pro = 'launch_dave_peek')
anMenu = widget_button(bar,value = 'Data Analysis',/menu)
rainsButton = widget_button(anMenu,value = 'RAINS (Refinement Analysis of Inelastic Neutron Spectra)', $
                            event_pro = 'launch_rains')
panButton = widget_button(anMenu,value = 'PAN (Peak Analysis)',event_pro = 'launch_opan')
void = widget_button(anMenu,value = 'Fourier Transform Toolkit',event_pro = 'launch_ft_toolkit')
reflanMenu = widget_button(anMenu,value = 'Reflectometry Analysis',/menu)
reflfitButton = widget_button(reflanMenu,value = 'ReflFit: Nonpolarized Reflectivity Analysis',event_pro = 'launch_reflpak',uvalue='reflfit')
reflpolButton = widget_button(reflanMenu,value = 'ReflPol: Polarized Reflectivity Analysis',event_pro = 'launch_reflpak',uvalue='reflpol')





planMenu = widget_button(bar,value = 'Planning',/menu)
void = widget_button(planMenu,value = 'Number density calculator',$
                     event_pro = 'launch_numdencalc')
void = widget_button(planMenu,value = 'Neutron calculator',$
                     event_pro = 'fdaveLaunchNeutCalc')
xsection = widget_button(planMenu,value = 'Neutron cross section',/menu)
void = widget_button(xsection,value = 'Table',$
                     event_pro = 'launch_xs_table')
void = widget_button(xsection,value = 'Calculations',$
                     event_pro = 'launch_xs_calc')
sshield = widget_button(planMenu,value='Self-shielding',/menu)
void = widget_button(sshield,value = 'Cylindrical/annular geometry',$
                     event_pro = 'fdaveLaunchANNSCA')
void = widget_button(sshield,value = 'Slab geometry',$
                     event_pro = 'fdaveLaunchslab')
rotor = widget_button(planMenu,value = 'Hindered rotor calculators',/menu)
void = widget_button(rotor,value = 'Diatomic rigid rotor',$
                     event_pro = 'dave_rotor')
void = widget_button(rotor,value = 'Methyl rotor',$
                     event_pro = 'dave_mrotor')
tasTools = widget_button(planMenu,value = 'TAS Tools',/menu)
void = widget_button(tasTools,value = 'Spurion calculator',event_pro = 'launchSpur')
void = widget_button(tasTools,value = 'RESCAL',$
                     event_pro = 'launch_rescal')



toolsMenu = widget_button(bar,value = 'Tools',/menu)
genTools = widget_button(toolsMenu,value = 'General Tools',/menu)
genDataTools = widget_button(genTools,value = 'Data Tools',/menu)
void = widget_button(genDataTools,value = 'Examine data directories',$
                     event_pro = 'launch_quicklook',uvalue='')
void = widget_button(genDataTools,value = 'Create a DAVE data summary file',$
                     event_pro = 'dave_summarize_ascii')
void = widget_button(genDataTools,value = 'Examine a DAVE datafile',$
                     event_pro = 'dave_examineDAVEfiles')
void = widget_button(genDataTools,value = 'View a DAVE datafile treatment',$
                     event_pro = 'dave_view_treatment')
void = widget_button(genDataTools,value = 'Save DAVE data in ascii format',$
                     event_pro = 'dave_save_ascii')
void = widget_button(genDataTools,value = 'Rebin DAVE data file(s)',$
                     event_pro = 'dave_rebindave')
genMiscTools = widget_button(genTools,value = 'Miscellaneous',/menu)
void = widget_button(genMiscTools,value = 'DAVE Calculator',$
                   event_pro = 'launch_dave_calc')
void = widget_button(genMiscTools,value = 'Points Digitizer (POD)',$
                     event_pro = 'fdaveLaunchPOD')

dcsTools = widget_button(toolsMenu,value = 'DCS Tools',/menu)
dcsPlanTools = widget_button(dcsTools,value = 'Planning and execution',/menu)
void = widget_button(dcsPlanTools,value = 'Intensity and resolution',$
                     event_pro = 'launch_DCSToolsPerformance')
void = widget_button(dcsPlanTools,value = 'Experiment planner',$
                     event_pro = 'launch_DCSToolsPlanner')
void = widget_button(dcsPlanTools,value = 'Calculate sample heights',$
                     event_pro = 'launch_DCSToolsHeights')
void = widget_button(dcsPlanTools,value = 'Chopper phase calculator',$
                     event_pro = 'launch_DCSToolsPhases')
void = widget_button(dcsPlanTools,value = '"Revenge" calculator',$
                     event_pro = 'launch_DCSToolsRevenge')
void = widget_button(dcsPlanTools,value = 'Detector information',$
                     event_pro = 'launch_DCSToolsDetectors')
dcsDataTools = widget_button(dcsTools,value = 'Data Tools',/menu)
void = widget_button(dcsDataTools,value = 'Examine DCS data directories',$
                     event_pro = 'launch_quicklook',uvalue='dcs')
void = widget_button(dcsDataTools,value = 'Create a DCS raw data summary file',$
         event_pro = 'DCSSummarize_ascii')
void = widget_button(dcsDataTools,value = 'Examine a DCS raw data file',$
                     event_pro = 'dave_examinedcsfiles')
void = widget_button(dcsDataTools,value = 'Save DCS raw data in ascii format',$
                     event_pro = 'DCSSave_ascii')
void = widget_button(dcsDataTools,value = 'Save DCS raw data in DAVE format',$
                     event_pro = 'DCSSaveRawData_DAVE')
void = widget_button(dcsDataTools,value = 'Convert sqw_i files to DAVE format',$
                     event_pro = 'DCSConvertSqwiFile_DAVE')
void = widget_button(dcsDataTools,value = 'Plot single crystal alignment files',$
                     event_pro = 'dcs_cryst_align',/separator)
dcsPlotTools = widget_button(dcsTools,value = 'DCS Multiplot utility',$
                             event_pro = 'launchdcs_multiplot')
dcsMiscTools = widget_button(dcsTools,value = 'Miscellaneous',/menu)
void = widget_button(dcsMiscTools,value = 'Plot DCS run information',$
                     event_pro = 'launch_DCS_runsinfo')
void = widget_button(dcsMiscTools,value = 'Perform raw data sanity checks',$
                     event_pro = 'DCSToolsSanitycheck')
void = widget_button(dcsMiscTools,value = 'Piecewise constant energy width time channels',$
                     event_pro = 'DCSToolsTchannels_energy')
void = widget_button(dcsMiscTools,value = 'Piecewise constant time width time channels',$
                     event_pro = 'DCSToolsTchannels_time')

hfbsTools = widget_button(toolsMenu,value = 'HFBS Tools',/menu)

void = widget_button(hfbsTools,value = 'Raw data detector view',$
                   event_pro = 'launch_rmd_detview')
void = widget_button(hfbsTools,value = 'Databrowser',event_pro = 'davelaunchhfbsdb')
fwsAnalysis = widget_button(hfbsTools,value = 'FWS Analysis',event_pro = 'fdaveLaunchFWS')

;  nseTools = widget_button(toolsMenu,value = 'Spin Echo Tools',/menu)

fansTools = widget_button(toolsMenu,value = 'FANS Tools',/menu)
;void = widget_button(fansTools,value = 'Gaussian98/03 Calculation',event_pro = 'launchgaussian98')
void = widget_button(fansTools,value = 'Gaussian98/03 Calculation',event_pro = 'launch_g3dview')
void = widget_button(fansTools,value = 'FANS Monochromator',event_pro = 'launchFansmonofit')
void = widget_button(fansTools,value = 'FANS Data Browser',event_pro = 'launchFansBrowser')


helpMenu = widget_button(bar,value = 'Help',/menu)
void = widget_button(helpMenu,value='Menu descriptions',event_pro='menuitems_help')
uman = widget_button(helpMenu,value='User manuals',/menu)
void = widget_button(uman,value='ASCII reader',event_pro='ascii_help')
void = widget_button(uman,value='Data Browser',event_pro='databrowser_Help')
void = widget_button(uman,value='Diatomic rigid rotor',event_pro='rotord_help')
void = widget_button(uman,value='FANS data reduction',event_pro='fans_help')
void = widget_button(uman,value='FCS data reduction',event_pro='fcs_help')
void = widget_button(uman,value='Gaussian98',event_pro='gaussian98_help')
void = widget_button(uman,value='HFBS data reduction',event_pro='hfbs_help')
void = widget_button(uman,value='Methyl rotor',event_pro='rotorm_help')
void = widget_button(uman,value='Mslice',event_pro='mslice_help')
void = widget_button(uman,value='NSE data reduction',event_pro='nse_help')
void = widget_button(uman,value='PAN',event_pro='pan_help')
void = widget_button(uman,value='RAINS',event_pro='rains_help')

void = widget_button(helpMenu,value = 'About DAVE',event_pro = 'fdaveAboutDave')

if file_search(!DAVE_DIR,'dave_users.pro',/fully_qualify_path) ne '' then begin
    result = dave_users(bar)
endif

centertlb,tlb

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

;wset,winPix
if thisDepth eq 8 then begin
    device,decomposed = 0
    tvlct,r,g,b                 ; load the proper color tables as found in
                                ; read_png above.
    dispImage = congrid(image,winxsize,winysize)
endif else begin
    device,decomposed = 1
    dispimage = image
endelse

wset,winPix
tvimage,dispImage
wset,winVis
device,copy = [0,0,!d.x_size,!d.y_size,0,0,winPix]
wdelete,winPix
end
;-------------------------------------------------------------------------------



;===============================================================================
; dave_do_nothing
;
; PURPOSE:
;   dummy event handler
;
; PARAMETERS:
;   event [in] - event structure.
;
pro dave_do_nothing,event
end
;-------------------------------------------------------------------------------



;===============================================================================
; dave_expand_menus
;
; PURPOSE:
;   Event handler. Fully expand all the tree widget menus.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro dave_expand_menus,event

id = widget_info(event.top,find_by_uname = 'TREE_WIDGET')
ids = get_all_ids(id)
nids = n_elements(ids)
id = widget_info(event.top,find_by_uname = 'EXPAND_BUTTON')
expand = event.id eq id
for i = 0,nids-1 do widget_control,ids[i],set_tree_expanded = expand

end
;-------------------------------------------------------------------------------



;===============================================================================
; dave_build_tree_menu
;
; PURPOSE:
;   Construct DAVE's menu hierarchy in tree mode
;
; PARAMETERS:
;   tlb [in] - widget id of tlb of main DAVE widget.
;
;
;050307 - LRK
;PLEASE SEE FILE DaveMenuXMLSpecification.xml IN THE auxiliary
;DIRECTORY TO ADD A MENU ITEM. --- PLEASE BE SURE TO UPDATE FROM THE REPOSITORY
;                                  BEFORE ADDING AN ITEM.
;

pro dave_build_tree_menu,tlb
; Application icon
bmp_file = !DAVE_AUXILIARY_DIR+'dm.bmp'
app_icon = convert_bmp(bmp_file)

; notebook icon
bmp_file = !DAVE_AUXILIARY_DIR+'copy.bmp'
notebook_icon = convert_bmp(bmp_file)

; Visualization icon
bmp_file = !DAVE_AUXILIARY_DIR+'image.bmp'
vis_icon = convert_bmp(bmp_file)

; Reduction icon
bmp_file = !DAVE_AUXILIARY_DIR+'hist.bmp'
reduction_icon = convert_bmp(bmp_file)

; Analysis icon
bmp_file = !DAVE_AUXILIARY_DIR+'scatter.bmp'
analysis_icon = convert_bmp(bmp_file)

; Tools icon
bmp_file = !DAVE_AUXILIARY_DIR+'cut.bmp'
tools_icon = convert_bmp(bmp_file)

; Help icon
bmp_file = !DAVE_AUXILIARY_DIR+'help.bmp'
help_icon = convert_bmp(bmp_file)

if (lmgr(/runtime)) then tlb_title = 'DAVE: Data Analysis and Visualization Environment' $
else tlb_title = 'DAVE: Data Analysis and Visualization Environment - running under IDLDE'
tlb = widget_base(/col,mbar = bar, title = tlb_title,uname = 'DAVE', $
                  xoff = 10,yoff = 20,/tlb_size_events)

filemenu = widget_button(bar,value = 'File',/menu)
void = widget_button(filemenu,value='Load an existing DAVE file',event_pro='dave_loadfile')
void = widget_button(filemenu,value = 'Select raw data directory',$
                     xsize = butsize,event_pro = 'fdaveSelDataDirectory',/separator)
void = widget_button(filemenu,value = 'Select working directory',$
                     xsize = butsize,event_pro = 'fdaveSelWorkDirectory')
void = widget_button(filemenu,value = 'Select data AND working directory',$
                     xsize = butsize,event_pro = 'fdaveSelBothDirectories')
void = widget_button(filemenu,value = 'Display directories',$
                     xsize = butsize,event_pro = 'fdaveDisplayDirectories')
void = widget_button(filemenu,value = 'Select pdf reader',$
                     xsize = butsize,event_pro = 'fdaveSELpdfreader')
void = widget_button(filemenu,value = 'Select web browser',$
                     xsize = butsize,event_pro = 'fdaveSELbrowser')
if (not lmgr(/runtime)) then $  ; debug flag widget should not appear in embedded version
  void = widget_button(filemenu,value='Switch on debug flag',event_pro='fdaveSwapDebugFlag')
void = widget_button(filemenu,value = 'Give user choice of menu system next time',/separator,$
                     xsize = butsize,event_pro = 'dave_menu_choice')
void = widget_button(filemenu,value = 'Quit (do not save tree structure)',event_pro = 'fdaveQuit',$
                     xsize = butsize)
void = widget_button(filemenu,value = 'Exit (save current tree structure)',event_pro = 'fdaveExit',$
                     xsize = butsize)
bbase = widget_base(tlb,/row)
void = widget_button(bbase,value = 'expand tree',event_pro = 'dave_expand_menus', $
                     /dynamic_resize,uname = 'EXPAND_BUTTON')
void = widget_button(bbase,value = 'contract tree',event_pro = 'dave_expand_menus', $
                     /dynamic_resize,uname = 'CONTRACT_BUTTON')
device,get_screen_size = screen_size
tot_y_size = 0.75*screen_size[1]
this_size = tot_y_size          ;-winysize

tree_base = widget_base(tlb,/col,uname = 'TREE_BASE',xsize = 300, $ ;winxsize, $
                        ysize = this_size)

file_tree = widget_tree(tree_base,ysize = this_size,uname = 'TREE_WIDGET')

reduction = widget_tree(file_tree,value = 'Data Reduction',/folder,$
                        event_pro = 'dave_do_nothing',bitmap = reduction_icon)
dcs_reduction_tree = widget_tree(reduction,value = 'DCS',/folder,$
                                 event_pro = 'dave_do_nothing',bitmap = reduction_icon)
void = widget_tree(dcs_reduction_tree,value = 'GUI: DCS reduction', $
                   event_pro = 'launch_dcsgui',bitmap = app_icon)
void = widget_tree(dcs_reduction_tree,value = 'Reduce DCS raw data', $
                   event_pro = 'DCSReduceRawData',bitmap = app_icon)
void = widget_tree(dcs_reduction_tree,value = 'DCS Mslice', $
                   event_pro = 'dcs_mslice',bitmap = app_icon)

fcs_reduction_tree = widget_tree(reduction,value = 'FCS',/folder,$
                                 event_pro = 'dave_do_nothing',bitmap = reduction_icon)
void = widget_tree(fcs_reduction_tree,value = 'Reduce FCS raw data', $
                   event_pro = 'launchfcsreduction',bitmap = app_icon)
void = widget_tree(fcs_reduction_tree,value = 'Help on FCS reduction', $
                   event_pro = 'fcs_help')

hfbs_reduction_tree = widget_tree(reduction,value = 'HFBS',/folder,$
                                  event_pro = 'dave_do_nothing',bitmap = reduction_icon)
void = widget_tree(hfbs_reduction_tree,value = 'Reduce .HFBS data', $
                   event_pro = 'launch_hfbsred',bitmap = app_icon)
void = widget_tree(hfbs_reduction_tree,value = 'Reduce .HSCN data', $
                   event_pro = 'hfbs_reduce_hscn',bitmap = app_icon)
void = widget_tree(hfbs_reduction_tree,value = 'Convert DAVE to CON', $
                   event_pro = 'hfbs_runCon',bitmap = app_icon)
void = widget_tree(hfbs_reduction_tree,value = 'Help on HFBS reduction', $
                   event_pro = 'hfbs_help')

tas_reduction_tree = widget_tree(reduction,value = 'TAS',/folder,$
                                 event_pro = 'dave_do_nothing',bitmap = reduction_icon)
void = widget_tree(tas_reduction_tree,value = 'TASXP', $
                   event_pro = 'fdaveTAS',bitmap = app_icon,uvalue='XP')
void = widget_tree(tas_reduction_tree,value = 'TAS data reduction', $
                   event_pro = 'launch_dtas',bitmap = app_icon)
void = widget_tree(tas_reduction_tree,value = 'SPINS PSD Calibration', $
                   event_pro = 'launch_dave_calibratepsd',bitmap = app_icon)

fans_reduction_tree = widget_tree(reduction,value = 'FANS',/folder,$
                                  event_pro = 'dave_do_nothing',bitmap = reduction_icon)
void = widget_tree(fans_reduction_tree,value = 'Reduce FANS (*.bt4) data', $
                   event_pro = 'launchfansdatreduc',bitmap = app_icon)
void = widget_tree(fans_reduction_tree,value = 'Help on FANS reduction', $
                   event_pro = 'fans_help')

nse_reduction_tree = widget_tree(reduction,value = 'NSE',/folder,$
                                 event_pro = 'dave_do_nothing',bitmap = reduction_icon)
void = widget_tree(nse_reduction_tree,value = 'Reduce NSE data', $
                   event_pro = 'launch_nse',bitmap = app_icon)
void = widget_tree(nse_reduction_tree,value = 'Help on NSE reduction', $
                   event_pro = 'nse_help')


reflred = widget_tree(reduction,value = 'REFLECTOMETRY',/folder,$
                                 event_pro = 'dave_do_nothing',bitmap = reduction_icon)
void = widget_tree(reflRed,value = 'ReflRed: Reduce Reflectometry Data',$
                     event_pro = 'launch_reflpak',uvalue='reflred',bitmap = app_icon)


ascii_reduction_tree = widget_tree(reduction,value = 'ASCII',/folder,$
                                   event_pro = 'dave_do_nothing',bitmap = reduction_icon)
void = widget_tree(ascii_reduction_tree,value = 'ASCII data->DAVE', $
                   event_pro = 'launch_ascii',bitmap = app_icon)

visualization = widget_tree(file_tree,value = 'Data Visualization',/folder,$
                            event_pro = 'dave_do_nothing',bitmap = vis_icon)
void = widget_tree(visualization,value = 'Data Browser',$
                   event_pro = 'launch_dave_db',bitmap = app_icon)
void = widget_tree(visualization,value = 'DAVE PEEK',$
                   event_pro = 'launch_dave_peek',bitmap = app_icon)

analysis = widget_tree(file_tree,value = 'Data Analysis',/folder,$
                       event_pro = 'dave_do_nothing',bitmap = analysis_icon)
void = widget_tree(analysis,value = 'RAINS (Refinement Analysis of Inelastic Neutron Spectra)',$
                   event_pro = 'launch_rains',bitmap = app_icon)
void = widget_tree(analysis,value = 'PAN (Peak Analysis)',$
                   event_pro = 'launch_opan',bitmap = app_icon)
void = widget_tree(analysis,value = 'Fourier Transform Toolkit',   $
                   bitmap = app_icon,event_pro = 'launch_ft_toolkit')

reflanMenu = widget_tree(analysis,value = 'Reflectometry Analysis',/folder, $
                       event_pro = 'dave_do_nothing',bitmap = analysis_icon)
reflfitButton = widget_tree(reflanMenu,$
                    value = 'ReflFit: Nonpolarized Reflectivity Analysis',$
                    event_pro = 'launch_reflpak',uvalue='reflfit',$
                    bitmap = app_icon)
reflpolButton = widget_tree(reflanMenu,$
                    value = 'ReflPol: Polarized Reflectivity Analysis',$
                    event_pro = 'launch_reflpak',uvalue='reflpol',$
                    bitmap = app_icon)




planning = widget_tree(file_tree,value='Planning',/folder, $
                       event_pro='dave_do_nothing',bitmap=tools_icon)

void = widget_tree(planning,value='Number density calculator', $
                   event_pro='launch_numdencalc',bitmap=app_icon)
void = widget_tree(planning,value='Neutron calculator', $
                   event_pro='fdaveLaunchNeutCalc',bitmap=app_icon)
xsection = widget_tree(planning,value = 'Neutron cross section',/folder, $
                       event_pro='dave_do_nothing',bitmap=tools_icon)
void = widget_tree(xsection,value='Table', $
                   event_pro='launch_xs_table',bitmap=app_icon)
void = widget_tree(xsection,value='Calculations', $
                   event_pro='launch_xs_calc',bitmap=app_icon)
sshield = widget_tree(planning,value = 'Self-shielding',/folder, $
                      event_pro='dave_do_nothing',bitmap=tools_icon)
void = widget_tree(sshield,value='Cylindrical/annular geometry', $
                   event_pro='fdaveLaunchANNSCA',bitmap=app_icon)
void = widget_tree(sshield,value='Slab geometry', $
                   event_pro='fdaveLaunchslab',bitmap=app_icon)

rotor = widget_tree(planning,value = 'Hindered rotor calculators',/folder, $
                    event_pro='dave_do_nothing',bitmap=tools_icon)
void = widget_tree(rotor,value='Diatomic rigid rotor', $
                   event_pro='dave_rotor',bitmap=app_icon)
void = widget_tree(rotor,value='Methyl rotor', $
                   event_pro='dave_mrotor',bitmap=app_icon)
tasTools = widget_tree(planning,value = 'TAS Tools',/folder, $
                       event_pro='dave_do_nothing',bitmap=tools_icon)
void = widget_tree(tasTools,value='Spurion calculator', $
                   event_pro='launchSpur',bitmap=app_icon)
void = widget_tree(tasTools,value='RESCAL', $
                   event_pro='launch_rescal',bitmap=app_icon)



tools = widget_tree(file_tree,value = 'Tools',/folder,$
                    event_pro = 'dave_do_nothing',bitmap = tools_icon)
gen_tools = widget_tree(tools,value = 'General Tools',/folder,$
                        event_pro = 'dave_do_nothing',bitmap = tools_icon)
gen_data_tools = widget_tree(gen_tools,value = 'Data Tools',/folder,$
                             event_pro = 'dave_do_nothing',bitmap = tools_icon)
void = widget_tree(gen_data_tools,value = 'Examine data directories',$
                   event_pro = 'launch_quicklook',bitmap = app_icon,uvalue = '')
void = widget_tree(gen_data_tools,value = 'Create a DAVE data summary file',$
                   event_pro = 'dave_summarize_ascii',bitmap = app_icon)
void = widget_tree(gen_data_tools,value = 'Examine a DAVE datafile',$
                   event_pro = 'dave_examineDAVEfiles',bitmap = app_icon)
void = widget_tree(gen_data_tools,value = 'View a DAVE datafile treatment',$
                   event_pro = 'dave_view_treatment',bitmap = app_icon)
void = widget_tree(gen_data_tools,value = 'Save DAVE data in ascii format',$
                   event_pro = 'dave_save_ascii',bitmap = app_icon)
void = widget_tree(gen_data_tools,value = 'Rebin DAVE data file(s)',$
                   event_pro = 'dave_rebindave',bitmap = app_icon)

gen_misc_tools = widget_tree(gen_tools,value = 'Miscellaneous',/folder,$
                             event_pro = 'dave_do_nothing',bitmap = tools_icon)
void = widget_tree(gen_misc_tools,value = 'DAVE Calculator',$
                   event_pro = 'launch_dave_calc',bitmap = app_icon)
void = widget_tree(gen_misc_tools,value = 'Points Digitizer (POD)',$
                   event_pro = 'fdaveLaunchPOD',bitmap = app_icon)
dcs_tools = widget_tree(tools,value = 'DCS Tools',/folder,$
                        event_pro = 'dave_do_nothing',bitmap = tools_icon)
dcs_plan_tools = widget_tree(dcs_tools,value = 'Planning and execution',/folder,$
                             event_pro = 'dave_do_nothing',bitmap = tools_icon)
void = widget_tree(dcs_plan_tools,value = 'Intensity and resolution',$
                   event_pro = 'launch_DCSToolsPerformance',bitmap = app_icon)
void = widget_tree(dcs_plan_tools,value = 'Experiment planner',$
                   event_pro = 'launch_DCSToolsPlanner',bitmap = app_icon)
void = widget_tree(dcs_plan_tools,value = 'Calculate sample heights',$
                   event_pro = 'launch_DCSToolsHeights',bitmap = app_icon)
void = widget_tree(dcs_plan_tools,value = 'Chopper phase calculator',$
                   event_pro = 'launch_DCSToolsPhases',bitmap = app_icon)
void = widget_tree(dcs_plan_tools,value = '"Revenge" calculator',$
                   event_pro = 'launch_DCSToolsRevenge',bitmap = app_icon)
void = widget_tree(dcs_plan_tools,value = 'Detector information',$
                   event_pro = 'launch_DCSToolsDetectors',bitmap = app_icon)

dcs_data_tools = widget_tree(dcs_tools,value = 'Data Tools',/folder,$
                             event_pro = 'dave_do_nothing',bitmap = tools_icon)
void = widget_tree(dcs_data_tools,value = 'Examine DCS data directories',$
                   event_pro = 'launch_quicklook',uvalue = 'dcs',bitmap = app_icon)
void = widget_tree(dcs_data_tools,value = 'Create a DCS raw data summary file',$
                   event_pro = 'DCSSummarize_ascii',bitmap = app_icon)
void = widget_tree(dcs_data_tools,value = 'Examine a DCS raw data file',$
                   event_pro = 'dave_examinedcsfiles',bitmap = app_icon)
void = widget_tree(dcs_data_tools,value = 'Save DCS raw data in ascii format',$
                   event_pro = 'DCSSave_ascii',bitmap = app_icon)
void = widget_tree(dcs_data_tools,value = 'Save DCS raw data in DAVE format',$
                   event_pro = 'DCSSaveRawData_DAVE',bitmap = app_icon)
void = widget_tree(dcs_data_tools,value = 'Convert sqw_i files to DAVE format',$
                   event_pro = 'DCSConvertSqwiFile_DAVE',bitmap = app_icon)
void = widget_tree(dcs_data_tools,value = 'Plot single crystal alignment files',$
                   event_pro = 'dcs_cryst_align',bitmap = app_icon)
void = widget_tree(dcs_data_tools,value = 'DCS Multiplot utility',$
                   event_pro = 'launchdcs_multiplot',bitmap = app_icon)

dcs_misc_tools = widget_tree(dcs_tools,value = 'Miscellaneous',/folder,$
                             event_pro = 'dave_do_nothing',bitmap = tools_icon)
void = widget_tree(dcs_misc_tools,value = 'Plot DCS run information',$
                   event_pro = 'launch_DCS_runsinfo',bitmap = app_icon)
void = widget_tree(dcs_misc_tools,value = 'Perform raw data sanity checks',$
                   event_pro = 'DCSToolsSanitycheck',bitmap = app_icon)
void = widget_tree(dcs_misc_tools,value = 'Piecewise constant energy width time channels',$
                   event_pro = 'DCSToolsTchannels_energy',bitmap = app_icon)
void = widget_tree(dcs_misc_tools,value = 'Piecewise constant time width time channels',$
                   event_pro = 'DCSToolsTchannels_time',bitmap = app_icon)

hfbs_tools = widget_tree(tools,value = 'HFBS Tools',/folder,$
                         event_pro = 'dave_do_nothing',bitmap = tools_icon)
void = widget_tree(hfbs_tools,value = 'Raw data detector view',$
                   event_pro = 'launch_rmd_detview',bitmap = app_icon)
void = widget_tree(hfbs_tools,value = 'Databrowser',$
                   event_pro = 'davelaunchhfbsdb',bitmap = app_icon)
void = widget_tree(hfbs_tools,value = 'FWS Analysis',$
                   event_pro = 'fdaveLaunchFWS',bitmap = app_icon)
fans_tools = widget_tree(tools,value = 'FANS Tools',/folder,$
                         event_pro = 'dave_do_nothing',bitmap = tools_icon)
;void = widget_tree(fans_tools,value = 'Gaussian98 Calculation',$
;                   event_pro = 'launchgaussian98',bitmap = app_icon)
void = widget_tree(fans_tools,value = 'Gaussian98/03 Calculation',$
                   event_pro = 'launch_g3dview',bitmap = app_icon)
void = widget_tree(fans_tools,value = 'FANS Monochromator',$
                   event_pro = 'launchFansmonofit',bitmap = app_icon)
void = widget_tree(fans_tools,value = 'FANS Data Browser',$
                   event_pro = 'launchFansBrowser',bitmap = app_icon)


help_menu = widget_tree(file_tree,value = 'Help',/folder,$
                        event_pro = 'dave_do_nothing',bitmap = help_icon)
void = widget_tree(help_menu,value = 'Menu descriptions',$
                   event_pro = 'menuitems_help',bitmap = app_icon)
manual_menu = widget_tree(help_menu,value = 'User manuals',/folder,$
                          event_pro = 'dave_do_nothing',bitmap = help_icon)
void = widget_tree(manual_menu,value = 'ASCII reader',$
                   event_pro = 'ascii_help')
void = widget_tree(manual_menu,value='Data Browser',event_pro='databrowser_Help')

void = widget_tree(manual_menu,value = 'Diatomic rigid rotor',$
                   event_pro = 'rotord_help')
void = widget_tree(manual_menu,value = 'FANS data reduction',$
                   event_pro = 'fans_help')
void = widget_tree(manual_menu,value = 'FCS data reduction',$
                   event_pro = 'fcs_help')
void = widget_tree(manual_menu,value = 'Gaussian98',$
                   event_pro = 'gaussian98_help')
void = widget_tree(manual_menu,value = 'HFBS data reduction',$
                   event_pro = 'hfbs_help')
void = widget_tree(manual_menu,value = 'Methyl rotor',$
                   event_pro = 'rotorm_help')
void = widget_tree(manual_menu,value = 'Mslice',$
                   event_pro = 'mslice_help')
void = widget_tree(manual_menu,value = 'NSE data reduction',$
                   event_pro = 'nse_help')
void = widget_tree(manual_menu,value = 'PAN',$
                   event_pro = 'pan_help')
void = widget_tree(manual_menu,value = 'RAINS',$
                   event_pro = 'rains_help')

void = widget_tree(help_menu,value = 'About DAVE',$
                   event_pro = 'fdaveAboutDave',bitmap = app_icon)
void = widget_tree(file_tree,value = 'Start E-notebook',$
                   event_pro = 'dave_launch_e_notes')

if file_search(!DAVE_DIR,'dave_users.pro',/fully_qualify_path) ne '' then begin
    result = dave_users(bar)
endif

dave_defs=*!dave_defaults
if (n_elements(*dave_defs.tree_menu_pointer) gt 0) then begin
    button_names=(*dave_defs.tree_menu_pointer).button_names
    button_state=(*dave_defs.tree_menu_pointer).button_state
    id = widget_info(tlb,find_by_uname = 'TREE_WIDGET')
    ids = get_all_ids(id)
    nids=n_elements(ids)
    bnames=strarr(nids)
    for k=0,nids-1 do begin
        widget_control,ids[k],get_value=temp
        bnames[k]=temp
    endfor
    if (nids eq n_elements(button_names)) then begin
        if (min(bnames eq button_names) eq 1) then begin
            for k=0,nids-1 do widget_control,ids[k],set_tree_expanded=button_state[k]
        endif
    endif
endif

widget_control,tlb,/realize
end
;-------------------------------------------------------------------------------



;===============================================================================
; dave_resize
;
; PURPOSE:
;   Event handler. Resize main widget in widget tree mode.
;
; PARAMETERS:
;   event [in] - event structure.
;
pro dave_resize,event

if (~strcmp(tag_names(event,/struct),'WIDGET_BASE')) then return	; must be a widget base event

tlb_geom = widget_info(event.top,/geometry)
tree_base_id = widget_info(event.top,find_by_uname = 'TREE_BASE')
tree_base_geom = widget_info(tree_base_id,/geometry)
button_id = widget_info(event.top,find_by_uname = 'EXPAND_BUTTON')
button_geom = widget_info(button_id,/geometry)
miny = 200
minx = 200
new_tree_ysize = (event.y-button_geom.ysize) > miny
new_tree_xsize = (event.x) > minx
tree_id = widget_info(event.top,find_by_uname = 'TREE_WIDGET')
widget_control,tree_base_id,  $
               xsize = new_tree_xsize,    $
               ysize = new_tree_ysize
widget_control,tree_id,       $
               xsize = new_tree_xsize,    $dave
               ysize = new_tree_ysize
end
;-------------------------------------------------------------------------------



;===============================================================================
; dave
;
; PURPOSE:
;   Main entry point of DAVE application. Construct main UI and
;   modular framework including the DAVE internal data structure used
;   for storing experimental data.
;
; PARAMETERS:
;
pro dave

; Define directory heirarchies in the DAVE distributions
delim = path_sep()
defsysv,'!DAVE_DIR', sourceroot() ; DAVE install directory
defsysv,'!DAVE_AUXILIARY_DIR',!DAVE_DIR+'auxiliary'+delim
defsysv,'!DAVE_SUMMARYFILES_DIR',!DAVE_DIR+'summaryfiles'+delim
defsysv,'!DAVE_BITMAP_DIR',!DAVE_DIR+'resource'+delim+'bitmaps'+delim
print,'*******************DAVE from SourceForge**********************'
; determine color capabilties of graphics card
colorset

; Define useful DAVE global variables (defined as system variables)
davesysvars


if file_test(!home_dir,/write) eq 0 then begin

	warning = [	'Your home directory appears to be: '+!home_dir,$
				'This directory is unwritable.  Please contact your system administrator.',$
				'Starting DAVE with temporary settings.']

	;AT THIS STAGE OMIT MESSAGE SINCE DAVE SHOULD START WITHOUT PROBLEM.
	;void = dialog_message(warning,/error)

	if !version.os_family eq 'Windows' then begin
		!home_dir = getenv('TEMP')
	endif else begin
		!home_dir = '/tmp'
	endelse

	defaults_file = !home_dir+path_sep()+'.dave_defs.sav'
	defsysv,'!defaults_file',defaults_file


	return

	;USE /tmp FOR UNIX
	;USE getenv('TEMP') for win.

endif


; If in the development environment, and running Windows,
; store the current directory.  Then make "C:\" the current directory.
if (not lmgr(/runtime) and !version.os_family eq "Windows") then begin
    cd,current=thisDir
    defsysv,'!thisDir',thisDir
    cd,"C:\"
endif



; No matter what, !dave_defaults is defined in the next few lines of code.
if (file_test(!defaults_file)) then begin
    restore,!defaults_file
    dave_defs=*pdd
    void = dave_defs_checkout(dave_defs)
    ptr_free, pdd
endif else begin
    cd,current = thisDir
    dave_defs = {datDir:!home_dir,workDir:!home_dir,PDFReader:'', $ ; RTA -change thisDir->!home_dir as default workDir
                 web_browser:'',classic:1B,show_choice:255B,tree_menu_pointer:ptr_new(/allocate_heap)}
endelse

; if no web browser is currently set, try locating one automatically
if (strlen(strtrim(dave_defs.web_browser)) eq 0) then $
  dave_defs.web_browser = locate_web_browser()
pdd=ptr_new(dave_defs)

save,filename=!defaults_file,pdd


defsysv,'!dave_defaults',pdd
print,(*pdd).show_choice
if (*pdd).show_choice then begin
    choice = dave_choose_menu_system(classic = (*pdd).classic,  $
                                     show_choice = (*pdd).show_choice)
    (*pdd).show_choice = choice.show_choice
    (*pdd).classic = choice.classic
endif
wait_id = dave_wait_message('Building the user interface...please wait')


save,filename=!defaults_file,pdd

defsysv,'!dave_defaults',pdd

;090105
;INSERTING THE XML MENUING SYSTEM.
if !version.release lt 6.1 then begin
    if not (*pdd).classic then $
      dave_build_tree_menu,tlb else $
        dave_build_menu,tlb
endif else begin
    if not (*pdd).classic then $
      tree=1 else $
        tree=0
        DaveMenu_XML,tlb,tree=tree
endelse

widget_control,wait_id,/destroy


;device,/cursor_original
commonStr = {instrument:'',$
             histPtr:ptr_new(/allocate_heap),$
             xlabel:'',$
             ylabel:'',$
             xtype:'',$
             ytype:'',$
             xunits: '',$
             yunits: '',$
             histLabel:'',$
             histUnits:'',$
             treatmentPtr:ptr_new(/allocate_heap),$
             commonStrPtr:ptr_new()}

dataStr = {commonStr:commonStr,$
           specificPtr:ptr_new(/allocate_heap)}

dataStrPtr = ptr_new(dataStr,/no_copy)

panContainer = obj_new('IDL_CONTAINER')
panInfo = {panContainer:panContainer}

; DAVE developers can put whatever they like into
; this extra structure
extra = {panInfo:panInfo}
extraPtr = ptr_new(extra,/no_copy)

daveStr = {davePtrStr, $        ; RTA - make davePtr structure a named structure
           dataStrPtr:dataStrPtr, $
           descriPtr:ptr_new()} ; remove /allocate_heap flag

davePtr = ptr_new(daveStr,/no_copy)
state = {davePtr:davePtr,extraPtr:extraPtr}

pState = ptr_new(state,/no_copy)
widget_control,tlb,set_uvalue = pState,/no_copy
xmanager,'dave',tlb,cleanup = 'daveCleanup', $
         event_handler = 'dave_resize',/no_block

return
end
