; $Id: nsefilelist.pro,v 1.9 2007/11/20 21:30:01 kneller Exp $
;###############################################################################
;
;FILENAME:
;        nsefilelist.pro
;
;PURPOSE:
;
;CATEGORY:
;       File chooser utility.
;
;METHODS:
;    NSEFileList_event
;    NSEFileList_getQandComment
;    NSEFileList_get_value
;    NSEFileList_cleanup
;    launch_NSEFileList
;    NSEFileList
;
;
; AUTHOR:
; Larry Kneller
; NIST Center for Neutron Research
; 100 Bureau Drive, Gaithersburg, MD 20899
; United States
; kneller@nist.gov  301-975-8839
; Sat Mar 18 01:18:22 2006
;
; 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.
;
;###############################################################################




pro nsefilelist_help_event,event

    uname = widget_info(event.id,/uname)
    tlb = event.handler
    stash = widget_info(tlb,find_by_uname='NSEFILELISTHELPCLOSE')
    widget_control,stash,get_uvalue=pstate

    case uname of
    'NSEFILELISTHELPCLOSE':begin
        widget_control,tlb,/destroy
    end
    else:
    endcase


end


function NSEFileList_helpstring

    s = [ $
         'This program displays the Q value and comment field ', $
         'for each .echo file in the selected directory. ', $
         'Select files from the list to open and then ', $
         'choose "Open Selected File(s)" from the file menu.',$
         'If there is an NSE Data Reduction window open in this ',$
         'session, then the files will open there.',$
         'To browse another directory select "Choose New Directory" ',$
         'from the file menu.' $
        ]
    return,s
end;NSEFilelist_helpstring












;###############################################################################
;
;NAME:
;        NSEFileList_event
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro NSEFileList_event,event


    uname = widget_info(event.id,/uname)



    tlb = event.handler

;    print,'tlb=',tlb
    stash = widget_info(tlb,find_by_uname='NSEFILELISTSTASH')

;    print,'stash=',stash
    widget_control,stash,get_uvalue=pstate

    case uname of
    'NSEFILELISTTLB':begin
        ;print,event.x,event.y

        if !version.os eq 'Win32' then begin
            xresizemagic = 15
            yresizemagic = 55
        endif else begin
            xresizemagic = 10
            yresizemagic = 40
        endelse



        tlbgeom = widget_info(tlb,/geometry)
        list = widget_info(tlb,find_by_uname='NSEFILELISTLIST')
        text = widget_info(tlb,find_by_uname='NSEFILELISTTEXT')

        textgeom = widget_info(text,/geometry)

        widget_control,list,scr_xsize=tlbgeom.scr_xsize-xresizemagic,$
                            scr_ysize=tlbgeom.scr_ysize-textgeom.scr_ysize-yresizemagic
        widget_control,text,scr_xsize=tlbgeom.scr_xsize-xresizemagic


    end;NSEFILELISTTLB
    'NSEFILELISTOPEN':begin
        dir = dialog_pickfile(/directory,path = (*pstate).startdir)

        if dir ne '' then begin
            (*pstate).startdir = dir

            fullfiles = file_search(dir+'*.echo')


            NSEFileList_getQandComment,fullfiles,list=list

            id = widget_info(tlb,find_by_uname='NSEFILELISTLIST')
            tx = widget_info(tlb,find_by_uname='NSEFILELISTTEXT')

            widget_control,tx,set_value=dir
            widget_control,id,set_value=list,set_uvalue=fullfiles
        endif

    end;NSEFILELISTOPEN
    'NSEFILELISTWRITE':begin
		fn = dialog_pickfile(filter='*.txt',/write,/overwrite_prompt)
        if fn ne '' then begin
 			fn = fn+'.txt'
            listid = widget_info(tlb,find_by_uname='NSEFILELISTLIST')
            widget_control,listid,get_uvalue=list
			dir = (*pstate).startdir

            fullfiles = file_search(dir+path_sep()+'*.echo')
            NSEFileList_getQandComment,fullfiles,list=list

            openw,lun,fn,/get_lun
			for i =0,n_elements(list)-1 do begin
				;print,list[i]
				printf,lun,list[i]
			endfor;i
			free_lun,lun
        endif

    end;NSEFILELISTOPEN

    'NSEFILELISTQUIT':begin
        widget_control,tlb,/destroy
    end;NSEFILELISTQUIT
    'NSEFILELISTSTASH':begin

    end;NSEFILELISTLIST
    'NSEFILELISTHELP':begin

        (*pstate).helpbase = widget_base(title='About NSE File List:',/floating,/modal,$
                                            group_leader = tlb,/col)

        text = NSEFileList_helpstring()
        xsize = max(strlen(text))
        ysize = n_elements(text)
        t1 = widget_text((*pstate).helpbase,ysize=ysize,xsize=xsize,value=text)
        (*pstate).helpclose = widget_button((*pstate).helpbase,value='Close',uname='NSEFILELISTHELPCLOSE',uvalue=pstate)
        widget_control,(*pstate).helpbase,/realize
        xmanager,'NSEFILELIST_HELP',(*pstate).helpbase,/no_block


    end;NSEFILELISTHELP

    'NSEFILELISTOPENSELECTION':begin
        list = widget_info(event.handler,find_by_uname='NSEFILELISTLIST')

        widget_control,list,get_uvalue = fulllist

        selection = widget_info(list,/list_select)

        count = n_elements(selection)
        if count gt 0 then begin
            nobj = checkforobjinstance('ooDisplayEcho',ref=ref)

            if nobj ne 0 then begin
                if selection[0] ne -1 then begin


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
                    ;SET UP HERE TO DEAL WITH MULTIPLE SELECTIONS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

                    ref->fileopen,filename=fulllist[selection];add,obj_new('ooEchoMagnetic',filename=fulllist[i])
                endif else begin
                    void = dialog_message('No files selected.',/info)
                endelse
            endif else begin


                void = dialog_message('NSE Reduction not open. In DAVE select: Data Reduction->NCNR->NSE->Reduce NSE Data')
;                print,fulllist[selection]
                ;SET UP TO OPEN ooDisplayEcho WITH DAVE INFO IF RUNNING FROM DAVE.

;                help,!dave_defaults


;                work_dir = (*!dave_defaults).workDir
;                data_dir = (*!dave_defaults).datDir
;                onse = obj_new('ooDisplayEcho', notify_ids = [event.id,event.top], $
;                                                group_leader = event.top,work_dir = work_dir,$
;                                                data_dir = data_dir,dave_id=event.top)

            endelse


        endif;count


    end;NSEFILELISTOPENSELECTION
    else:
    endcase

end;NSEFileList_event



;###############################################################################
;
;NAME:
;        NSEFileList_getQandComment
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro NSEFileList_getQandComment,full_list,list=list


    nfiles = n_elements(full_list)

    prog = nseprogress([nfiles],title='Searching files . . .',labels=['File#: '],xsize=200)

;    base = widget_base(title='Searching files . . .',xoffset=300,yoffset = 300)
;    prog = cw_progress(base,value=[nfiles])
;    widget_control,base,/realize

;    print,nfiles
;    help,full_list
;    print,transpose(full_list)

    if nfiles gt 0 then begin
        q = strarr(nfiles)
        comment = strarr(nfiles)
        list = string(lindgen(nfiles),format='(i6)')

        line = ''

        CATCH, Error_status
        ;HANDLE ERRORS IN READING THE DATA FILE.
        IF (Error_status NE 0) THEN BEGIN
            free_lun,lun,/force
            print,'NSEFileList_getQandComment DATA FILE '+file_basename(full_list[i])+' IS INCOMPLETE.'

            help,/traceback
            CATCH, /CANCEL
        ;return
        ENDIF

        for i=0,nfiles-1 do begin
            nseprogress_step,prog
            ;widget_control,prog,set_value=[i]
            if full_list[i] ne '' then begin


                list[i] = string(i,format = '(i6)') + '   ' + file_basename(full_list[i])

                nlines = file_lines(full_list[i])
                if nlines gt 300 then begin

                    ;print,full_list[i]
                    openr,lun,full_list[i],/get_lun
                    readf,lun,line
                    counter = 0

                    ;GET COMMENT FROM scan HEADER
                    ;READ AWAY LINES UNTIL THE COMMENT SECTION
                    while stregex(line,'automatic',/fold_case,/boolean) eq 0 and $
                                counter lt 200 do begin
                                    readf,lun,line
                                    counter = counter + 1
                    endwhile

                    ;GET THE COMMENT
                    counter = 0
                    readf,lun,line
                    while stregex(line,'eof',/fold_case,/boolean) eq 0 and $
                            counter lt 100 do begin

                                    comment[i] = comment[i] + ' ' + strtrim(line,2)
                                    readf,lun,line
                                    counter = counter + 1
                    endwhile


                    ;GET q FROM physics HEADER
                    ;READ DOWN TO hkl LINE.
                    counter = 0
                    while stregex(line,'hkl',/fold_case,/boolean) eq 0 and $
                            counter lt 100 do begin
                                    readf,lun,line
                                    counter = counter + 1
                    endwhile

                    free_lun,lun


                    segs = strsplit(line,/extract)

                    if n_elements(segs) ge 3 then dq = double(segs[2]) else dq = double('NaN')

                    q[i] = string(dq,format='(f6.4)')


                    if finite(dq,/nan) eq 0 then begin
                        list[i] = list[i] + '   ' + q[i] + '   ' + comment[i]
                    endif else begin
                        list[i] = list[i] + '   ' + q[i]
                    endelse


;                    list[i] = string(i,format = '(i6)') + '   ' + file_basename(full_list[i]) + $
;                                     '   ' + q[i] + '   ' + comment[i]


                endif;nlines
            endif;NULL FILENAME
        endfor;i
        nseprogress_close,prog
    endif else begin    ;nfiles gt 0

        list = ['']

    endelse

end;NSEFileList_getQandComment


;###############################################################################
;
;NAME:
;        NSEFileList_get_value
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;RETURN VALUE:
;
;###############################################################################
function NSEFileList_get_value,id
    widget_control,id,get_uvalue=value
    return,value
end;NSEFileList_get_value

;###############################################################################
;
;NAME:
;        NSEFileList_cleanup
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro NSEFileList_cleanup,id
    print,'NSEFileList_cleanup'
    widget_control,id,get_uvalue = pstate
    if ptr_valid(pstate) then ptr_free,pstate
end;NSEFileList_cleanup

;;###############################################################################
;;
;;NAME:
;;        launch_NSEFileList
;;
;;PURPOSE:
;;
;;PARAMETERS:
;;
;;KEYWORDS:
;;
;;_EXTRA - is used to pass keywords meant for the superclass.
;;
;;###############################################################################
;pro launch_NSEFileList,event
;
;
;    if ptr_valid(!dave_defaults) gt 0 then begin
;        work_dir = (*!dave_defaults).workDir
;        data_dir = (*!dave_defaults).datDir
;    endif else begin
;        work_dir = '.'
;        data_dir = '.'
;    endelse
;
;    nseFileList,group_leader = event.top,data_dir = data_dir,work_dir=work_dir,$
;                startdir = data_dir,notify_ids=[event.id,event.top]
;
;;    ;SET UP THIS LAUNCH METHOD SO IT BEHAVES SAME AS launchNse WITH THE SAME ARGUMENTS SO THAT
;;    ;THEY WILL BE AVAILABLE TO PASS TO launchNSE if an ooDisplayEcho data object is not available.
;;
;;    this_event = tag_names(event,/structure_name)
;;    print,this_event
;;    case this_event of
;;    'WIDGET_BUTTON':begin
;;        work_dir = (*!dave_defaults).workDir
;;        data_dir = (*!dave_defaults).datDir
;;        device,decomposed = 0
;;        onse = obj_new('ooDisplayEcho',notify_ids = [event.id,event.top], $
;;            group_leader = event.top,work_dir = work_dir,data_dir = data_dir,dave_id=event.top)
;;    end
;;    'WIDGET_TREE_SEL':begin
;;        device,decomposed = 0
;;        work_dir = (*!dave_defaults).workDir
;;        data_dir = (*!dave_defaults).datDir
;;        onse = obj_new('ooDisplayEcho',notify_ids = [event.id,event.top], $
;;            group_leader = event.top,work_dir = work_dir, data_dir = data_dir,dave_id=event.top)
;;    end
;;    'NSE_EVENT':begin
;;        widget_control,event.top,/show,/input_focus,iconify = 0
;;    end
;;    else:
;;    endcase
;end;launchNSEFileList
;

;###############################################################################
;
;NAME:
;        NSEFileList
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro NSEFileList,group_leader=group_leader,      $
                startdir=startdir,              $
                notify_ids = notify_ids,        $
                data_dir = data_dir,            $
                work_dir = work_dir,            $
                dave_id = dave_id


    tlb = widget_base(title='NSE File List',$
                        group_leader=group_leader,$
                        /col,$
                        xoffset = 300, yoffset = 300,$
                        mbar = bar,$
                        /tlb_size_events,$
                        uname='NSEFILELISTTLB')

    stash = widget_button(bar,/menu,value='File',UNAME='NSEFILELISTSTASH',kill_notify='NSEFileList_cleanup')
    open =      widget_button(stash,value='Choose New Directory',UNAME='NSEFILELISTOPEN')
    openfiles = widget_button(stash,value='Open Selected File(s)',uname='NSEFILELISTOPENSELECTION')
    writefiles = widget_button(stash,value='Write List to File',uname='NSEFILELISTWRITE')
    Quit =      widget_button(stash,value='Quit',uname='NSEFILELISTQUIT')

    helpmenu = widget_button(bar,value='Help',/menu)
    help = widget_button(helpmenu,value='Help on NSEFileList',uname='NSEFILELISTHELP')


    if n_elements(startdir)     eq 0 then startdir = ''
    if n_elements(data_dir)      eq 0 then data_dir = ''
    if n_elements(work_dir)      eq 0 then work_dir = ''
    if n_elements(dave_id)      eq 0 then dave_id = 0L
    if n_elements(notify_ids)   eq 0 then notify_ids = 0L
    if n_elements(group_leader) eq 0 then group_leader = 0L


    if n_elements(startdir) eq 0 then startdir = '.'

    dirlabel = 0L;widget_button(bar,value=startdir,xsize)


    fullfiles = file_search(startdir+'*.echo')

    NSEFileList_getQandComment,fullfiles,list=files

    list = widget_list(tlb,xsize=80,ysize = 15,$
                        value=files,uname='NSEFILELISTLIST',$
                        /multiple,$
                        func_get_value='NSEFileList_get_value',$
;                        pro_set_value ='NSEFileList_set_value',$
                        uvalue=fullfiles $
                        )

    text = widget_text(tlb, xsize=80,$
                            value=startdir,$
                            uname='NSEFILELISTTEXT')

    state = {tlb:tlb,open:open,openfiles:openfiles,quit:quit,$
            group_leader:group_leader,      $
            startdir:startdir,              $
            notify_ids : notify_ids,        $
            data_dir : data_dir,            $
            work_dir : work_dir,            $
            dave_id : dave_id,$
            text : text,$
            helpbase:0L,$
            helpclose:0L}

    pstate = ptr_new(state)

    widget_control,stash,set_uvalue=pstate
    widget_control,tlb,/realize
    xmanager,'nsefileList',tlb,/no_block
end;NSEFileList

