; $Id: cwo_convertbt1todave.pro,v 1.7 2008/03/07 20:44:55 kneller Exp $
;###############################################################################
;
;
;CLASS NAME:
;    cwo_ConvertBT1ToDave
;
;PURPOSE:
;
;CATEGORY:
;
;
;SUPERCLASSES:
;    inherits idl_container
;
;
;METHODS:
;    cwo_ConvertBT1ToDave_event
;    cwo_ConvertBT1ToDave::event
;    cwo_ConvertBT1ToDave::displayHelp
;    cwo_ConvertBT1ToDave::quit
;    cwo_ConvertBT1ToDave::selectFiles
;    cwo_ConvertBT1ToDave::convertFiles
;    cwo_ConvertBT1ToDave::convertData
;    cwo_ConvertBT1ToDave::addDotDave
;    cwo_ConvertBT1ToDave::getExt
;    cwo_ConvertBT1ToDave::writeDave
;    cwo_ConvertBT1ToDave::draw
;    cwo_ConvertBT1ToDave::setproperty
;    cwo_ConvertBT1ToDave::getproperty
;    cwo_ConvertBT1ToDave_cleanup
;    cwo_ConvertBT1ToDave::cleanup
;    cwo_ConvertBT1ToDave::init
;    cwo_ConvertBT1ToDave__define
;    cwo_ConvertBT1ToDave
;
;
; AUTHOR:
; Larry Kneller
; NIST Center for Neutron Research
; 100 Bureau Drive, Gaithersburg, MD 20899
; United States
; kneller@nist.gov  301-975-8839
; Fri Oct 27 20:53:03 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.
;
;###############################################################################




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


	catch, catchError
	if (catchError ne 0) then begin
	    ;;print, 'Error handled!'
	    eTitle = 'BT1 To Dave Converter: Error encountered'
	    eMsg = 'An error or unusual condition was encountered at cwo_ConvertBT1ToDave_event!'
	    eMsg = [eMsg,'Please, report the following to Larry (kneller@nist.gov) on the DAVE team:']
	    eMsg = [eMsg,!error_state.msg]
	    void = dialog_message(/error,eMsg,title=eTitle,dialog_parent=event.top)
	    catch, /cancel
	    return
	endif


    widget_control,event.handler,get_uvalue=obj

    ret = obj->event(event)

    ;DO I HAVE TO PASS THIS EVENT DIRECTLY TO THE PARENT SOMEHOW??????
end;cwo_ConvertBT1ToDave_event
;###############################################################################
;
;NAME:
;        cwo_ConvertBT1ToDave::event
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;RETURN VALUE:
;
;###############################################################################
function cwo_ConvertBT1ToDave::event,event

    case event.id of
    self.quitbutton:begin
        self->quit
    end;quitbutton
    self.quitbuttonfile:begin
        self->quit
    end;quitbutton
    self.filebutton:begin
        self->selectFiles
    end;filebutton
    self.filebuttonfile:begin
        self->selectFiles
    end;filebutton
    self.workdirbutton:begin
        self->selectWorkingDirectory
    end;workdirbutton
    self.workdirbuttonfile:begin
        self->selectWorkingDirectory
    end;workdirbuttonfile
    self.mergebutton:begin
        self->ConvertFiles
    end;mergebutton
    self.mergebuttonfile:begin
        self->ConvertFiles
    end;mergebutton
    self.helpbutton:begin
        self->displayHelp
    end;helpbutton
    self.helpbuttonhelp:begin
        self->displayHelp
    end;helpbutton
    else:
    endcase

    return,-1
end;cwo_ConvertBT1ToDave_event

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

    b = widget_base(group_leader=self.tlb,title='Help on BT-1 to DAVE converter',/floating,/col)
    text = widget_text(b,xsize=60,ysize = 10)
    s = ['ConvertBT1ToDave: Written by Larry Kneller',$
         'Use this to convert BT-1 data files to DAVE format',$
         'to facilitate use in the DAVE applications "DataBrowser" ',$
         'and "PAN".',$
         '',$
         'DataBrowser (Data Visulization->DataBrowser) provides utilities',$
         'for viewing and taking cuts through the data at any detector you',$
         'choose.  It also provides good facilities for both 1d and 2d',$
         'visualizations.' $
         ]

    widget_control,text,set_value=s
    widget_control,b,/realize

end;cwo_ConvertBT1ToDave::displayHelp


;###############################################################################
;
;NAME:
;        cwo_ConvertBT1ToDave::quit
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro cwo_ConvertBT1ToDave::quit
    widget_control,self.tlb,/destroy
end;cwo_ConvertBT1ToDave::quit

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

    dir = dialog_pickfile(title='Select BT-1 Data File Directory:',$
                         /directory,$
                         path=self.datadir)
;                         ,$
;                         filter = ['*.dave','*.dat','*.iqt'])

    if dir[0] ne '' then begin
        widget_control,self.text,set_value = 'Data directory: '+dir
        self.datadir = dir;file_dirname(fn[0])
        ;self.workdir = dir;file_dirname(fn[0])

        files = file_search(dir+'*.bt1')

        comment = file_basename(files)

        s = strarr(3)
        for i=0,n_elements(files)-1 do begin
;            comment[i] = file_basename(files[i])
            if file_test(files[i],/read) gt 0 then begin
                openr,lun,files[i],/get_lun
                readf,lun,s
                free_lun,lun
                comment[i] = comment[i] + '     |     ' + s[2]
            endif
        endfor;i

        widget_control,self.filelist,set_value=comment,set_uvalue=files
    endif

end;cwo_ConvertBT1ToDave::selectFiles
;###############################################################################
;
;NAME:
;        cwo_ConvertBT1ToDave::selectFiles
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro cwo_ConvertBT1ToDave::selectWorkingDirectory

    dir = dialog_pickfile(title='Select BT-1 Working Directory:',$
                         /directory,$
                         path=self.workdir)

    if dir[0] ne '' then begin
        self.workdir = dir
    endif

end;cwo_ConvertBT1ToDave::selectWorkingDirectory


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

    widget_control,self.filelist,get_uvalue=uval
    widget_control,self.combineFilesCheckbox,get_value=combineFilesFlag
    widget_control,self.xaxisbgroup,get_value=val;,get_uvalue=choices

    ;print,'combineFilesFlag=',combineFilesFlag

    selection = widget_info(self.filelist,/list_select)

    ;help,uval
    ;print,selection
    case combineFilesFlag of
    0:begin
      nodavewrite = 0
    end;0
    1:begin
            nodavewrite = 1
            xIndex = 0
            xT  = 0
            xH  = 0
            xM4 = 0
        
            case val of
            0:xIndex = 1
            1:xT = 1
            2:xH = 1
            3:xM4 = 1
            else:xIndex = 1
            endcase

    end;1
    else:begin
      nodavewrite = 0
    endelse
    endcase

    nfiles = n_elements(selection)

    resultPtr = ptrarr(nfiles,/allocate)

    if selection[0] ne -1 then begin
        widget_control,self.text,get_value=savetext
        for i=0,n_elements(selection)-1 do begin
            newtext = 'Converting '+file_basename(uval[selection[i]])
            widget_control,self.text,set_value=newtext

            sel = uval[selection[i]]
            self->convertData,sel,result,nodavewrite=nodavewrite
            
            *resultPtr[i] = result
        endfor;i
        if combineFilesFlag eq 1 then begin  
          readbt1_combineResults,resultPtr,xt=xt,xh=xh,xn=xIndex,xIndex=xIndex,$
                                 workdir=self.workdir,datadir=self.datadir
        endif

        widget_control,self.text,set_value=savetext
    endif else begin
        void = dialog_message('Please select files from the list.')
    endelse
    
    ptr_free,resultPtr
    
end;cwo_ConvertBT1ToDave::convertFiles

;###############################################################################
;
;NAME:
;        cwo_ConvertBT1ToDave::convertData
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro cwo_ConvertBT1ToDave::convertData,fn,result,nodavewrite=nodavewrite

    ;READ A BT-1 FILE INTO A STRUCTURE:
    ;
    ;THEN CREATE A 2d DATA SET WITH
    ;
    ;   I[nQ,nt],sI[nQ,nT]
    ;   IF nt VARIES, THEN FILL IN I AT UNIQUE t'S WITH NaN'S --- WHAT ABOUT ROUNDING FOR Q,t????
    ;                                                             SEE WHAT WAS DONE IN ooEcho.
    ;
    ; THEN WRITE A DAVE FILE.

    if n_elements(nodavewrite) eq 0 then nodavewrite = 0
  
    widget_control,self.xaxisbgroup,get_value=val;,get_uvalue=choices
    ;help,choices[0]


    xIndex = 0
    xT  = 0
    xH  = 0
    xM4 = 0

;print,'val=',val

    case val of
    0:xIndex = 1
    1:xT = 1
    2:xH = 1
    3:xM4 = 1
    else:xIndex = 1
    endcase

;print,'xIndex=',xIndex
;print,'xT=',xT
;print,'xH=',xH
;print,'xM4=',xM4


;help,/traceback
	basename = file_basename(fn)

    if nodavewrite eq 0 then begin
  	  ofn = self.workdir+path_sep()+basename
  
  
      ext = self->getExt(fn,iext=iext,len=len)
      sublen=len-iext
  
      ;void = dialog_message('BEFORE strendsub call cwo_ConvertBT1ToDave::convertData')
      ofn = strendsub(ofn,'.dave',sublen)
      ;void = dialog_message('AFTER strendsub call')
  
      exists = file_test(ofn)
      if exists ne 0 then begin
          yn = dialog_message('File '+file_basename(ofn)+' exists.  Overwrite?',/question)
          if yn eq 'No' then begin
              ofn = dialog_pickfile(path=self.workdir,$;file_dirname(ofn),$
              					  filter='*.dave',title='Select DAVE output file for '+file_basename(fn))
  			if ofn ne '' then begin
  				self.workdir = file_dirname(ofn)
              	self->addDotDave,ofn
  			endif else begin
  				return
  			endelse
          endif
          self->addDotDave,ofn
      endif
    endif else begin
      ;set ofn to nothing so the next if statement will bypass file write.
      ofn = ''
    endelse

    if ofn ne '' then begin

;        exists = file_test(ofn)
;        if exists ne 0 then begin
;            writeable = file_test(ofn,/write)
;        endif else begin
;            writeable = 1
;        endelse

        writeableDir = file_test(file_dirname(ofn),/write,/directory)

        if writeableDir ne 0 then begin	;and writeable ne 0 then begin
            ;print,val,xIndex,xT,xH,xM4,fn,ofn

            readbt1,result,fn=fn,ofn=ofn,xIndex=xIndex,xT=xT,xH=xH,xM4=xM4

        endif else begin
            void = dialog_message('Directory not writable: '+file_dirname(ofn))
;            void = dialog_message(file_basename(ofn)+' exists or is not writeable in that directory.')
        endelse

    endif else begin
        ;NEED TO TAKE THIS APPROACH IN CASE THERE IS NO ofn SELECTED BUT THE USER STILL 
        ;WANTS result FOR USE ELSEWHERE (e.g. TO MERGE MULTIPLE FILES INTO A SINGLE DAVE FILE.)
        readbt1,result,fn=fn,ofn=ofn,xIndex=xIndex,xT=xT,xH=xH,xM4=xM4,/nodavewrite
    endelse

end;cwo_ConvertBT1ToDave::convertData



pro cwo_ConvertBT1ToDave::addDotDave,ofn

        ext = self->getExt(ofn,iext=iext,len=len)
        if ext ne 'dave' then begin
            if iext gt 0 then begin
                sublen=len-iext
                ;print,'ofn before=',ofn
                ;void = dialog_message('BEFORE strendsub call cwo_ConvertBT1ToDave::addDotDave')
                ofn = strendsub(ofn,'dave',sublen)
                ;void = dialog_message('AFTER strendsub call')

                ;print,'ofn after=',ofn
            endif else begin
                ofn = ofn+'.dave'
            endelse
        endif

end;cwo_ConvertBT1ToDave::addDotDave


;###############################################################################
;
;NAME:
;        cwo_ConvertBT1ToDave::getExt
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;RETURN VALUE:
;
;###############################################################################
function cwo_ConvertBT1ToDave::getExt,s,iext=iext,len=len
        iext = strpos(s,'.',/reverse_search)

        if iext ne -1 then begin
            len  = strlen(s)
            ext  = strmid(s,iext+1,len-iext)
        endif else begin
            ext = ''
        endelse
        return,ext

end;cwo_ConvertBT1ToDave::getExt


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



end;writeDave




;###############################################################################
;
;NAME:
;        cwo_ConvertBT1ToDave::draw
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro cwo_ConvertBT1ToDave::draw
end;cwo_ConvertBT1ToDave::draw

;###############################################################################
;
;NAME:
;        cwo_ConvertBT1ToDave::setproperty
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro cwo_ConvertBT1ToDave::setproperty,_Extra=extra
    if n_elements(tlb) ne 0 then self.tlb =tlb
end;cwo_ConvertBT1ToDave::setproperty


;WHY THE FUCK DOES USING _Extra NOT WORK FOR RETRIEVING VALUES VIA get/setProperty???????????????
;###############################################################################
;
;NAME:
;        cwo_ConvertBT1ToDave::getproperty
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro cwo_ConvertBT1ToDave::getproperty,tlb=tlb,_Extra=extra


    ;print,'CALLED GETPROPERTY'
    if arg_present(tlb) ne 0 then tlb = self.tlb
end;cwo_ConvertBT1ToDave::getproperty

;###############################################################################
;
;NAME:
;        cwo_ConvertBT1ToDave_cleanup
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro cwo_ConvertBT1ToDave_cleanup,id
    widget_control,id,get_uvalue=obj
    obj_destroy,obj
end;cwo_ConvertBT1ToDave_cleanup

;###############################################################################
;
;NAME:
;        cwo_ConvertBT1ToDave::cleanup
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;###############################################################################
pro cwo_ConvertBT1ToDave::cleanup
    print,'cwo_ConvertBT1ToDave::cleanup'
    if ptr_valid(self.pdata) then begin
        if ptr_valid((*self.pdata)[0]) then ptr_free,(*self.pdata)
        ptr_free,self.pdata
    endif
end;cwo_ConvertBT1ToDave::cleanup

;###############################################################################
;
;NAME:
;        cwo_ConvertBT1ToDave::init
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;RETURN VALUE:
;
;###############################################################################
function cwo_ConvertBT1ToDave::init,parent,xsize=xsize,ysize=ysize,tlb=tlb,group_leader=group_leader,$
                                  datadir=datadir,workdir=workdir,_Extra=extra

    nobj = checkforobjinstance('cwo_ConvertBT1ToDave',ref=ref)
    if nobj gt 1 then begin
        help,ref[0],output=out0
        help,self,output=outself

        if strcmp(out0,outself,/fold_case) eq 0 then begin
            ref[0]->getproperty,tlb=tlb
        endif else begin
            ref[1]->getproperty,tlb=tlb
        endelse

        widget_control,tlb,/show
        return,0
    endif else begin

        if n_elements(parent) eq 0 then parent = -1L

        if n_elements(datadir) eq 0 then begin
			defsysv,'!dave_defaults',exists=exists
			if exists ne 0 then begin
				datadir = (*!dave_defaults).datdir
			endif else begin
				datadir = '.'
			endelse
		endif
		self.datadir = datadir

        if n_elements(workdir) eq 0 then begin
			defsysv,'!dave_defaults',exists=exists
			if exists ne 0 then begin
			workdir = (*!dave_defaults).workdir
			endif else begin
				workdir = '.'
			endelse

		endif
        self.workdir = workdir


        if parent ne -1L then begin
            tlb = widget_base(parent,title='ConvertBT1ToDAVE',group_leader=parent,/row,uvalue=self,$
                                kill_notify='cwo_ConvertBT1ToDave_cleanup')
        endif else begin
            tlb = widget_base(title='ConvertBT1ToDAVE',group_leader=group_leader,mbar=bar,/row,uvalue=self,$
                                kill_notify='cwo_ConvertBT1ToDave_cleanup')
        endelse

        llb1 = widget_base(tlb,/col)
        llb2 = widget_base(tlb,/col)

        value=['No Files Selected']
        self.filelist = widget_list(llb1,xsize=80,ysize = 15,$
                                    value=value,$
                                    uvalue=value,$
                                    /multiple)

        if n_elements(bar) ne 0 then begin
            filemenu = widget_button(bar,value='File',/menu)
            self.filebuttonfile = widget_button(filemenu,value='Choose Directory')
            self.workdirbuttonfile = widget_button(filemenu,value='Choose Working Directory')
            self.mergeButtonfile = widget_button(filemenu,value='Make DAVE file')
            self.quitbuttonfile = widget_button(filemenu,value='Quit')

            helpmenu = widget_button(bar,value='Help',/menu)
            self.helpbuttonhelp = widget_button(helpmenu,value='Help')
        endif

        self.fileButton  = Widget_button(llb2,value='Choose Data Directory',$
                                              tooltip='Choose location of files for conversion')
        self.workdirButton  = Widget_button(llb2,value='Choose Working Directory',$
                                              tooltip='Choose location of converted output files')
        self.mergeButton = Widget_button(llb2,value='Make DAVE file',$
                                              tooltip='Create DAVE files from the selected .bt1 files')

;    result = {x:dblarr(1),$
;              xIndex:dblarr(1),$
;              xT:dblarr(1),$
;              xM4:dblarr(1),$
;              xC:dblarr(1),$
;              xN:dblarr(1),$
;              xH:dblarr(1),$

        xaxischoices =  ['xIndex (Point Index)',$
                        'T (Temp)',$
                        'H (Field)',$
                        'M4 (Motor 4)'];,$
                        ;'C (?????)',$
                        ;'N (Det Blocks)']
        xaxisnames   =  ['Index','T','H','M4'];,'C','N']
        xaxisunits   =  ['Point number','K?','kG?','deg?'];,'???','det blocks']

        xaxisuvalue = {xaxisnames:xaxisnames,naxisunits:xaxisunits}
        self.xaxisbgroup = cw_bgroup(llb2,xaxischoices,/exclusive,frame=2,/no_release,uvalue=xaxisuvalue,$
                                            label_top='X-Axis Choices')

        s_theta = textoidl('2\theta')
        self.combineFilesCheckbox = cw_bgroup(llb2,['Combine Multiple BT-1 Files (x=2theta,y=axis choice above)'],frame=2,/no_release,/nonexclusive)

        self.helpButton  = widget_button(llb2,value='Help',$
                                              tooltip='Help on ConvertBT1ToDAVE')
        self.quitButton  = widget_button(llb2,value='Quit',$
                                              tooltip='Exit ConvertBT1ToDAVE')

        

        self.text = widget_text(llb1,value='')

        widget_control,self.xaxisbgroup,set_value=1

        centertlb,tlb

        widget_control,tlb,/realize
        xmanager,'cwo_ConvertBT1ToDave',tlb,/no_block;,event_handler='cwo_ConvertBT1ToDave_event'

        self.tlb = tlb

        return,1
    endelse
end;init

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

    class = {cwo_ConvertBT1ToDave,$
                inherits idl_container,$
                pdata:ptr_new(),$
                datadir:'',$
                workdir:'',$
                tlb:0L,$
                filelist:0L,$
                quitbutton:0L,$
                quitbuttonfile:0L,$
                filebutton:0L,$
                workdirbutton:0L,$
                filebuttonfile:0L,$
                workdirbuttonfile:0L,$
                mergebutton:0L,$
                mergebuttonfile:0L,$
                combineFilesCheckbox:0L,$
                helpbutton:0L,$
                helpbuttonhelp:0L,$
                xaxisbgroup:0L,$
                text:0L}

end;cwo_ConvertBT1ToDave__define
;###############################################################################
;
;NAME:
;        cwo_ConvertBT1ToDave
;
;PURPOSE:
;
;PARAMETERS:
;
;KEYWORDS:
;
;_EXTRA - is used to pass keywords meant for the superclass.
;
;RETURN VALUE:
;
;###############################################################################
function cwo_ConvertBT1ToDave,parent,obj=obj,xsize=xsize,ysize=ysize,group_leader=group_leader,_Extra=extra

    if n_elements(parent) eq 0 then parent = -1L
    obj = obj_new('cwo_ConvertBT1ToDave',parent,$
                                        xsize=ysize,ysize=ysize,$
                                        tlb=tlb,group_leader=group_leader,$
                                        _Extra=extra)

    return,tlb

end;cwo_ConvertBT1ToDave

