; $Id: fans_datreduc.pro,v 1.23 2007/10/12 22:55:59 azuah Exp $
;###############################################################################
;
; NAME:
;   fans_datreduc
;
; PURPOSE:
;   FANS data redunction module. It performs the following tasks
;   ** Load one or more sample files
;   ** Load one or more background files
;   ** Load one or more Fast bkgd files
;   ** Allows user to mask (remove) detectors after visual inspection
;      of data
;   ** Correct data for fast bkgd (using a polynomial fit to it)
;   ** Perform bkgd subtraction if required.
;
; CATEGORY:
;   FANS Data Reduction
;
; AUTHOR:
;   Richard Tumanjong Azuah
;   NIST Center for Neutron Research
;   100 Bureau Drive, Gaithersburg, MD 20899
;   United States
;   azuah@nist.gov; (301) 9755604
;   May, 2002
;
; 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.
;
;###############################################################################



;===============================================================================
; dummy
;
; PURPOSE:
;  dummy event handler
;
; PARAMETERS:
;   event [in] - event structure to be handled.
;
pro dummy, event
if (!debug) then begin
    print,'Dummy handler called...'

    help, event,/structure

    widget_control, event.top, get_uvalue=sPtr
    
    widget_control, event.id, get_value=value
    widget_control, event.id, get_uvalue=uvalue
    uname = widget_info(event.id,/uname)
    print,'DUMMY: Value = ',value,'  **Uname = ',uname ;,'  **Uvalue = ',uvalue
endif

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



;===============================================================================
; fans_datReduc_cleanup
;
; 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 fans_datReduc_cleanup, tlbID

;print, 'Cleaning up...'
widget_control, tlbID, get_uvalue=sPtr

if (!debug) then print,'Validity of sPtr is ',ptr_valid(sPtr)

;---- BEGIN DAVE specific cleanup section
fansInfo = {FANSDATREDUCEVENT,$
          id:(*sPtr).notifyIDs[0],$
          top:(*sPtr).notifyIDs[1],$
          handler:0L}
if widget_info((*sPtr).notifyIDs[0],/valid_id) then begin
  widget_control,(*sPtr).notifyIDs[0],send_event = fansInfo
endif
;---- END DAVE specific section

tvlct,(*sPtr).oldrgb.r,(*sPtr).oldrgb.g,(*sPtr).oldrgb.b
; delete all data currently in memory
if (ptr_valid((*sPtr).sDataPtr)) then $
  fans_cleanDataPtrs, sPtr,'samp' ; sample data
if (ptr_valid((*sPtr).bDataPtr)) then $
  fans_cleanDataPtrs, sPtr,'bkgd' ; background data
if (ptr_valid((*sPtr).fDataPtr)) then $
  fans_cleanDataPtrs, sPtr,'fast' ; fast background data
if (ptr_valid((*sPtr).oDataPtr)) then $
  fans_cleanDataPtrs, sPtr,'outp' ; output data
wdelete, (*sPtr).winPix         ; delete pixmap window

; deal with the remainder of the state pointer
ptr_free, (*sPtr).mfoPtr, $
          (*sPtr).sampListPtr, $
          (*sPtr).bkgdListPtr, $
          (*sPtr).fastListPtr, $
          (*sPtr).outpListPtr, $
          (*sPtr).mskListPtr, $
          (*sPtr).fitParsPtr, $
          sPtr

if (!debug) then print,'Validity of sPtr is ',ptr_valid(sPtr)

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



;===============================================================================
; fans_browser
;
; PURPOSE:
;   Main entry point and dialog builder for application.
;
; PARAMETERS:
;   davePtr [in|out] - a DAVE pointer. The reduced data will be placed
;                      in it.
;
; KEYWORDS:
;   notifyIds [in] - widget id(s) of that are interested in receiving
;                    notification messages from this application.
;
;   group_leader [in] - the ID of the parent widget from which this
;                       dialog was launched.
;
pro fans_datReduc, davePtr,notifyIds=notifyIds,group_leader=group_leader

compile_opt idl2

tvlct,rorig,gorig,borig,/get
oldrgb = {r:rorig,g:gorig,b:borig}
device,decomposed = 0
colors = hfbs_GetColor(/Load, Start=1) ; custom (16) color table

; define container base widgets; make it resizeable
tlbID = widget_base(group_leader=group_leader,/col,title='FANS DATA REDUCTION',mbar=mbar,/tlb_size_events)

cb2ID = widget_base(tlbID,/row,frame=1,/align_center)

cb3ID = widget_base(tlbID,/col,frame=1,/align_center)
cb3aID = widget_base(cb3ID,/row)
cb3bID = widget_base(cb3aID,/row)
cb3cID = widget_base(cb3aID,/row,/exclusive,event_pro='fans_changeviewdata')
cb3dID = widget_base(cb3aID,/row,frame=1)

cb4ID = widget_base(tlbID,/col,frame=1);,/align_center)
cb4aID = widget_base(cb4ID,/row,event_pro='fans_sliderEvent',/align_center)
cb4bID = widget_base(cb4ID,/row,event_pro='fans_sliderEvent',/align_center)
cb4cID = widget_base(cb4ID,/row,event_pro='fans_sliderEvent',/align_center)

cb5ID = widget_base(tlbID,/row,frame=1,/align_center)
cb5aID = widget_base(cb5ID,/row)
cb5bID = widget_base(cb5ID,/row,/nonexclusive,/grid_layout)
cb5cID = widget_base(cb5ID,/row)
;void = widget_base(cb5ID,/row)
;cb5cID = widget_base(void,/row,/nonexclusive,/grid_layout)
;cb5dID = widget_base(void,/row)

; bulid the menus. There are three drop-down menus: file, settings and help
fileMenu = widget_button(mbar, value='File',/menu, $
                         event_pro='fans_filemenu')
settingsMenu = widget_button(mbar, value='Settings',/menu, $
                         event_pro='fans_settings')
helpMenu = widget_button(mbar, value='Help',/menu, $
                         event_pro='fans_Help')

; fill the 'File' drop-down menu
dirMID = widget_button(fileMenu,value='Change Data Directory',uname='dir')
sampMID = widget_button(fileMenu,value='Select Sample File(s)',uname='samp')
bkgdMID = widget_button(fileMenu,value='Select Bkgd File(s)',uname='bkgd')
fbkgdMID = widget_button(fileMenu,value='Select Fast Bkgd File(s)',uname='fast')
save1MID = widget_button(fileMenu,value='Save (DAVE) File',uname='sdave',/separator)
save2MID = widget_button(fileMenu,value='Save (ASCII) File',uname='ascii')
save3MID = widget_button(fileMenu,value='Save (2D DAVE) File',uname='s2dave')
exitMID = widget_button(fileMenu,value='Quit',uname='exit',/separator)

; 'Settings' menu
optsID = widget_button(settingsMenu,value='Change Options',uname='opts')

; fill the 'Help' drop-down menu
;aboutMID = widget_button(helpMenu,value='About FANS_DATREDUC',uname='about')
manMID = widget_button(helpMenu,value='Manual',uname='man')

empty='  No files yet  '
voID = widget_label(cb2ID,value='Samples:')
sampID = widget_droplist(cb2ID,value=empty,uname='samp',uvalue=0,event_pro='fans_dropList')
voID = widget_label(cb2ID,value='Bkgd:')
bkgdID = widget_droplist(cb2ID,value=empty,uname='bkgd',event_pro='fans_dropList')
voID = widget_label(cb2ID,value='Fast Bkgd:',xoffset=50)
fastID = widget_droplist(cb2ID,value=empty,uname='fast',event_pro='fans_dropList')

voID = widget_label(cb3bID,value='Display:',/dynamic_resize)
sViewID = widget_button(cb3cID,value='Sample',uname='samp',uvalue=1,sensitive=0)
bViewID = widget_button(cb3cID,value='Bkgd',uname='bkgd',uvalue=0,sensitive=0)
fViewID = widget_button(cb3cID,value='Fast',uname='fast',uvalue=0,sensitive=0)
oViewID = widget_button(cb3cID,value='Output',uname='outp',uvalue=0,sensitive=0)
widget_control, sViewID,/set_button
fitBkgdID = widget_button(cb3dID,value='Fit Fast Bkgd',sensitive=0,event_pro='fans_Fastfit')
; dropdown for available fit functions
funcs = ['Arcsin','Linear','Quadratic','Cubic']
fnameID = widget_combobox(cb3dID,value=funcs,event_pro='fans_fitFuncSel',xsize=85)
void =  widget_label(cb3dID,value='<--Select model function',/dynamic_resize)

cbInfo = widget_info(cb3ID,/geometry)
xSize = fix(cbInfo.scr_xsize - 2*cbInfo.xpad)
ySize = fix(0.6*xSize)
winVisID = widget_draw(cb4bID,xsize=xsize,ysize=ysize,/button_events,/motion_events,event_pro='fans_plotClick')
eSliderID = cw_fslider(cb4cID,title='Energy Transfer Cut',xsize=xSize,uname='eslider', $
                       min=0.0,max=220.0,format='(F6.2)',uvalue=0)
widget_control, eSliderID, sensitive=0

voID = widget_label(cb4aID,value='Masked detector list:',/dynamic_resize)
vInfo = widget_info(voID,/geometry)
mskListID = widget_text(cb4aID,value='',scr_xsize=0.98*(xSize-vInfo.xsize))

voID = widget_label(cb5aID,value='Output Settings:')
;geom = widget_info(void,/geometry)
mskOnID = widget_button(cb5bID,value='Apply Mask',uvalue=0,sensitive=0,uname='mskon', $
                        event_pro='fans_outpOpts')
subBkgdID = widget_button(cb5bID,value='Sub Bkgd',uvalue=0,sensitive=0,uname='sbkgd', $
                          event_pro='fans_outpOpts')
subFastID = widget_button(cb5bID,value='Sub Fast Fit',uvalue=0,sensitive=0,uname='sfast', $
                          event_pro='fans_outpOpts')
setMonID = widget_button(cb5bID,value='Use this mon:',uvalue=0,uname='USEMON', $
                          event_pro='fans_outpOpts',xoffset=100)
monValID = cw_field(cb5cID,title='',value=1,/long,xsize=10,uname='MONVAL')
; realise widgets
widget_control, tlbID, /realize

tlbInfo = widget_info(tlbID,/geometry)
restOfHeight = tlbInfo.scr_ysize - ySize
restOfWidth = tlbInfo.scr_xsize - xSize

; create a pixmap window with same size as visible window
; and note its number
window,/free,/pixmap,xsize=xsize,ysize=ysize
winPix = !d.window 

; get the visible window nos and set it as default plot window;
widget_control, winVisID, get_value=winVis,sensitive=1
wset, winVis


; define and set uvalue for the top level base widget
state = {tlbID:tlbID, $
         mfoPtr:ptr_new([0,2,0,0]), $ ; options for multiple files - user configurable 
         nosActDets:50 , $      ; nos of active detectors - user configurable!
         datDir:(*!dave_defaults).datdir, $ ; the data directory (use !dave_defaults)
         workDir:(*!dave_defaults).workdir, $ ; the work directory (use !dave_defaults)
         sampID:sampID, $       ; Sample droplist widget ID
         sampListPtr:ptr_new(/allocate_heap), $ ; ptr to an array of sample files
         sampCount:0, $         ; nos of Sample files
         sampIndex:0, $         ;
         sampSepIndex:0, $
         sampStatus:0, $
         bkgdID:bkgdID, $       ; Bkgd widget ID
         bkgdListPtr:ptr_new(/allocate_heap), $ ; ptr to an array of Bkgd files
         bkgdCount:0, $         ; nos of Bkgd files
         bkgdIndex:0, $         ;
         bkgdSepIndex:0, $
         bkgdStatus:0, $
         fastID:fastID, $       ; Fast bkgd widget ID
         fastListPtr:ptr_new(/allocate_heap), $ ; ptr to a array of Fast bkgd files
         fastCount:0, $         ; nos of Fast bkgd files
         fastIndex:0, $         ;
         fastSepIndex:0, $
         fastStatus:0, $
         outpListPtr:ptr_new(/allocate_heap), $ ; ptr to output files
         outpCount:0, $         ; nos of Fast bkgd files
         outpIndex:0, $         ; 
         doOutpCalc:1, $        ; flag to indicate whether output should be calc.
         sViewID:sViewID, $     ; Disolay Sample widget ID
         bViewID:bViewID, $     ; Display bkgd widget ID
         fViewID:fViewID, $     ; Display Fast bkgd widget ID
         oViewID:oViewID, $     ; Display Output widget ID
         fitBkgdID:fitBkgdID, $ ; fIt bkgd widget ID
         fitFunc:0, $           ; the currently selected fit function index
         fitParsPtr:ptr_new(/allocate_heap), $ ; list of fit parameters
         fitPresent:0, $        ; is fast bkgd fitted
         ;parID:parID, $         ; fitted Fast bkgd parameters widget ID
         mskListID:mskListID, $ ; Masked detector list widget ID
         mskListPtr:ptr_new(), $ ; ptr to array of detectors to be masked
         updFast:0, $           ; = 1 whenever masked det list changes
         winVisID:winVisID, $   ; visible plot window widget ID
         winVis:winVis, $       ; visible window number
         winPix:winPix, $       ; pixmap window number
         winWidth:xsize, $      ; visible/pixmap window width
         winHeight:ysize, $     ; visible/pixmap window height
         restOfHeight:restOfHeight, $ ; height of tlb - plot window height
         restofWidth:restofWidth, $   ; width of tlb - plot window width
         minXSize:xSize, $      ; minimum width for plot window, set by initial value 
         minYSize:ySize, $      ; minimum plotwindow height, set by initial value
         eSliderID:eSliderID, $ ; Energy transfer cut widget ID
         mskOnID:mskOnID, $     ; Apply Mask widget ID
         subBkgdID:subBkgdID, $ ; sub Bkgd widget ID
         subFastID:subFastID, $ ; sub Fast Bkgd fit widget ID
         sDataPtr:ptr_new(), $  ; ptr to an array of sample data ptrs
         bDataPtr:ptr_new(), $  ; ptr to an array of bkgd data ptrs
         fDataPtr:ptr_new(), $  ; ptr to an array of Fast bkgd data ptrs
         oDataPtr:ptr_new(), $  ; ptr to an array of output data ptrs
         davePtr:davePtr, $     ; davePtr obtained from dave
         zp1:[0.0,0.0], $       ; zoom selection - first point
         zp2:[0.0,0.0], $       ; zoom selection - second point
         mouseType:0, $         ; mouse, 1==left, 2==middle, 4==right
         oldrgb:oldrgb, $       ; rbg values outside fans_datreduc
         colors:colors, $       ; colors within fans_datreduc from a custom 16-color table 
         mev2wnos:8.065541, $    ; meV to wavenumber conversion factor
         notifyIds:notifyIds $
        }
sPtr = ptr_new(state,/no_copy)
widget_control, tlbID, set_uvalue=sPtr

ret = dave_set_focus(tlbID)
xmanager, 'fans_datreduc',tlbID,event_handler='fans_resize',cleanup='fans_datreduc_cleanup',/no_block


end
