; $Id: readbt1.pro,v 1.5 2008/03/07 20:44:55 kneller Exp $

function strendsub,s,ssub,n
    ;SUBSTITUTE THE LAST n LETTERS OF s WITH ssub

    snew = strarr(n_elements(s))
    lens = strlen(s)

    for i=0,n_elements(s)-1 do begin
        stemp = strmid(s[i],0,lens[i]-n)
        snew[i] =  stemp + ssub
    endfor;i

    return,snew
end;strendsub


function bt1_writeDave,r,filename,work_dir=work_dir,xindex=xindex,xm4=xm4,xt=xt,xh=xh,_Extra=extra
;
;NAME:
;        bt1_writeDave
;
;PURPOSE:
;               Write a Dave pointer of the BT-1 data to a file.
;PARAMETERS:
;               filename        The output filename
;KEYWORDS:
;               work_dir        The working directory for the output file
;RETURN VALUE:
;               1 for success 0 for failure

    ;if n_elements(work_dir) eq 0 then work_dir = '.'
    if n_elements(xIndex) eq 0 then xIndex = 0 else xIndex = xIndex
    if n_elements(xT) eq 0 then xT = 0 else xT = xT
    if n_elements(xH) eq 0 then xH = 0 else xH = xH
    if n_elements(xM4) eq 0 then xM4 = 0 else xM4 = xM4


    if ((xH eq 0) and (xIndex eq 0) and (xT eq 0) and (xM4 eq 0)) then xIndex = 1

    if n_elements(filename) eq 0 then begin
        filename = dialog_pickfile(/write,$
                        title='BT-1 DAVE export file:',$
                        path=work_dir,$
                        /overwrite_prompt,$
                        filter='*.dave')
    endif


    readbt1_addDotDave,filename

    if filename eq '' then begin
        void = dialog_message('NO OUTPUT FILE SELECTED.')
        return,0
        filename = 'bt1_reduced_data.dave'
    endif else begin

        instrument = 'BT1'
        qty = r.y
        sz = size(r.y)

;print,tag_names(r)
        dqty = sqrt(r.y)    ;NOTE THAT THIS DOES NOT PROPERLY TAKE INTO ACCOUNT THE ERROR BARS SINCE
                            ;A SCALING OCCURS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        dqty = r.dy

        y = findgen(sz[2])  ;DETECTOR CHANNEL NUMBER


        ;SELECT X VALUES (ONLY ONE CONDITION SHOULD BE SATISFIED):
        xlabel = 'Data Point'
        xunits = 'Data Point Number'
        if xIndex ne 0 then begin
            xlabel = 'Data Point Index';r.fields[0]
            xunits = 'Data Point Number'
            x = r.xIndex
        endif
        if xT     ne 0 then begin
            xlabel = 'Temperature'
            xunits = 'K'
            x = r.xT
        endif
        if xH     ne 0 then begin
            xlabel = 'Field'
            xunits = 'kG????'
            x = r.xH
        endif
        if xM4    ne 0 then begin
            xlabel = 'Motor 4'
            xunits = 'degrees'
            x = r.xM4
        endif
        ;print,'XLABEL=',xlabel


        specificstr = {x:x,xindex:(r.x),xM4:(r.xM4),xT:(r.xT),xN:(r.xN),xH:(r.xH),yrsf:(r.yrsf),yrza:(r.yrza)}

        xlabel = xlabel;r.fields[0];'time (s)'
        ylabel = 'Detector Channel'
        xunits = xunits;'pointNumber'
        yunits = 'Channel'
        histlabel = 'I (counts)'
        histunits = ''
;        specificstr = {x:x}
;        treatment = 'NSE data reduced'
        ret = create_dave_pointer( $
                    daveptr,              $
                    instrument = instrument,    $
                    qty = qty,            $
                    qtunits = histunits,       $
                    qtlabel = histlabel,       $
                    err = dqty,            $
                    xvals = x,          $
                    xtype = 'point',          $
                    xunits = xunits,         $
                    xlabel = xlabel,         $
                    yvals = y,          $
                    ytype = 'point',          $
                    yunits = yunits,         $
                    ylabel = ylabel,         $
                    specificstr = specificstr);,  $
;                    treatment = treatment);,   $
;;                    dname = dname,          $
;;                    dunits = dunits,         $
;;                   dlegend = dlegend,       $
;;                    dqty = dqty,          $
;;                    derr = derr,          $
;;                    ermsg = errmsg              )
;;




        testfile = file_info(filename)
;        print,tag_names(testfile)
;        print,testfile
;;;;;        if testfile.write ne 0 and testfile.exists eq 0 then begin
            save,filename=filename,daveptr

			void = dialog_message('Wrote: '+filename,/info)

;;;;;        endif else begin
;;;;;            void = dialog_message('This file is not writable.  Please select a different output location:')
;;;;;            void = dialog_message('e.g. Copy your .bt1 data to your local computer and read from that directory:')
;;;;;            filename = dialog_pickfile(filter='*.dave',/write)
;;;;;            if filename eq '' then begin
;;;;;                return,0
;;;;;            endif else begin
;;;;;                testfile = file_info(filename)
;;;;;                print,filename
;;;;;                if testfile.write ne 0 then begin
;;;;;                    save,filename=filename,daveptr
;;;;;                endif else begin
;;;;;                    void = dialog_message('Invalid file.  No write.')
;;;;;                endelse
;;;;;            endelse
;;;;;        endelse

    endelse

    return,1
end;writeDave
function readbt1_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;readbt1_getExt

pro readbt1_addDotDave,ofn

        ext = readbt1_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')
                ofn = strendsub(ofn,'dave',sublen)
                ;void = dialog_message('AFTER strendsub call')

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

end;readbt1_addDotDave


  
pro readbt1_combineResults,rPtr,ofn=ofn,xIndex=xxIndex,xT=xxT,xH=xxH,xc=xxC,xN=xxN,$
                           workdir=workdir,datadir=datadir,_Extra=extra
;COMBINE MULTIPLE RESULT STRUCTURES INTO A SINGLE DAVE FILE
;WHEN M4 IS THE ONLY THING VARIED.

          catch, es
          if es ne 0 then begin
              void=dialog_message(['Error occurred in readbt1_combineResults!','Report the following to DAVE team:',!error_state.msg])
              catch,/cancel
          endif

          if n_elements(xxT) eq 0 then xxT = 0
          if n_elements(xxC) eq 0 then xxC = 0
          if n_elements(xxN) eq 0 then xxN = 0
          if n_elements(xxH) eq 0 then xxH = 0
          if n_elements(xxIndex) eq 0 then xxIndex = 0
          
          
          if ((xxT eq 0) and (xxC eq 0) and (xxN eq 0) and (xxH eq 0) and (xxIndex eq 0)) then xxN = 1

          ;NOT SURE WHY THERE ARE SEPARATED xxN and xxIndex, BUT THESE SEEM TO BE THE SAME THING.
          if (xxIndex eq 1) then xxN = 1
          
          ndet = 32
          
          if n_elements(rptr) eq 0 then begin

                    ;SARAH'S EXAMPLE
                    ;path = '\\Charlotte\ICP Data\bt1\200707\spoulton\mailin2007\'
                    if n_elements(datadir) eq 0 then begin
                      path = '\\Charlotte\ICP Data\bt1\'
                    endif else begin
                      path = datadir
                    endelse
                    fn = dialog_pickfile(path=path,filter='*.bt1',/multi)
                    if fn[0] eq '' or n_elements(fn) eq 0 then return
                    
                    tempbase = widget_base(title='Reading BT-1 Data')
                    temptext = widget_text(tempbase,value='Please wait',xsize=80)
                    centertlb,tempbase
                    widget_control,tempbase,/realize
                    rptr = ptrarr(n_elements(fn),/allocate)
                    temp = dblarr(n_elements(fn))
                    for i=0,n_elements(fn)-1 do begin
                      readbt1,r1,fn = fn[i],/nodavewrite
                      *rptr[i] = r1
                      valid = widget_info(temptext,/valid)
                      if valid then begin
                        widget_control,temptext,get_value=tempval
                        widget_control,temptext,set_value=tempval+'.'
                      endif
                    endfor;i
                    widget_control,tempbase,/destroy
                   
          endif

          nresults = n_elements(rptr)
          
          ;CREATE POSSIBLE GROUP Y VALUE ARRAYS
          tset = dblarr(nresults)
          cset = dblarr(nresults)
          nset = dblarr(nresults)
          hset = dblarr(nresults)

          tempbase = widget_base(title='Processing BT-1 Data')
          temptext = widget_text(tempbase,value='Please wait',xsize=80)
          centertlb,tempbase
          widget_control,tempbase,/realize

          for k=0,nresults-1 do begin
                  ;FOR ONE SET:
                  ;CALCULATE AVERAGES AND PLACE UPDATE DATA ARRAY WITH UNIQUE SET OF X VALUES
                if n_elements(*rptr[k]) ne 0 then begin
                      yvals=(*rptr[k]).y
    
                      szy = size(yvals)
                      if szy[0] eq 1 then begin
                        nx = szy[1]
                        ny = 1
                      endif else begin
                        nx = szy[1]
                        ny = szy[2]
                      endelse
    
                      ;DO THESE NEXT TWO SCALE FACTORS VARY FROM SCAN TO SCAN?
                      yrsf = (*rptr[k]).yrsf
                      yrza = (*rptr[k]).yrza
    
                      xm4new = rebin((*rptr[k]).xm4,nx,ny)
    
                      ;STANDARD DETECTOR POSITIONAL OFFSET (5 deg PER DETECTOR, SAME FOR ALL SCANS)
                      ;MUST RESET THIS TO 1D BEFORE THE MATRIX MULTIPLICATION IN THE NEXT STEP.
                      offset = dindgen(ndet)*5.0
              
                      ;CONVERT offset INTO A 2d ARRAY
                      offset = (dblarr(nx)+1.0)#offset
              
                      ;OFFSET THE DETECTOR NUMBERS BY THEIR ANGULAR OFFSET ON BT1
                      ;5 deg per detector.
                      xvals = xm4new+offset
              
                      newyvals = 0.0*yvals
                      newsyvals = 0.0*yvals
              
                      ;GET OPTIONAL GROUP Y VALUES
                      tset[k] = mean((*rptr[k]).xt)
                      cset[k] = mean((*rptr[k]).xc)
                      nset[k] = mean((*rptr[k]).xn)
                      hset[k] = mean((*rptr[k]).xh)
    
                      ;INITIALIZE THE DATA ARRAYS
                      tempxset = [-9999.0]
                      tempyset = [-9999.0]
                      tempsyset = [-9999.0]
    
                      ;WORK WITH 2d ARRAYS AS THOUGH THEY ARE A LONG 1D ARRAY.
                      for i=0,n_elements(yvals)-1 do begin;nx-1 do begin
                        ;wh = where(xvals eq xvals[i,0])
                        ;wh = where(xvals eq xvals[i])
                        wh = where(abs(xvals - xvals[i]) lt 0.00001)  ;NE eq DUE TO POSSIBLE DOUBLE TYPE ISSUE
                        newyvals[i] = total(yvals[wh])/double(n_elements(wh))
                        newsyvals[i] = sqrt(total(yvals[wh]))/double(n_elements(wh))
              
                        ;SELECT UNIQUE X VALUES
                        ;whset = where(tempxset eq xvals[i],count)
                        whset = where(abs(tempxset - xvals[i]) lt 0.0001,count)
                        if count eq 0 then begin
                          tempxset = [tempxset,xvals[i]]
                          tempyset = [tempyset,newyvals[i]]
                          tempsyset = [tempsyset,newsyvals[i]]
                        endif
              
                      endfor;i
                      if n_elements(tempxset) gt 1 then begin
                        
                        xset = tempxset[1:*]
                        yset = tempyset[1:*]
                        syset = tempsyset[1:*]
                        tempxset = tempxset[1:*]
                        tempyset = tempyset[1:*]
                        tempsyset = tempsyset[1:*]
                      endif
                      
                      if k eq 0 then begin
                        ;ASSUME ALL DATA SETS AFTER THIS WILL BE THE SAME SIZE.
                        ;IS THIS A REASONABLE ASSUMPTION???
                        x = xset
                        y = dindgen(nresults)
                        qty = dblarr(n_elements(xset),nresults)
                        err = dblarr(n_elements(xset),nresults)

                        ;GET THE MONITOR VALUES FOR THE ORIGINAL DATA SET
                        mon0  = (*rptr[k]).monitor                        
                        pref0 = (*rptr[k]).prefactor
              
                      endif;k eq 0

                      ;GET MONITOR VALUE FOR THE CURRENT DATA SET
                      mon  = (*rptr[k]).monitor
                      pref = (*rptr[k]).prefactor

                      ;SCALE DATA BY MONITOR AND PREFACTOR OF ZEROTH SET
                      qty[*,k] = tempyset*(mon0/mon)*(pref0/pref)
                      err[*,k] = tempsyset*(mon0/mon)*(pref0/pref)

                      valid = widget_info(temptext,/valid)
                      if valid then begin
                        widget_control,temptext,get_value=tempval
                        widget_control,temptext,set_value=tempval+'.'          
                      endif
                endif;*rptr[k] defined
          endfor;k
          widget_control,tempbase,/destroy
          
          xlabel = '2Theta'
          xunits = 'degrees'

          if xxT gt 0 then begin
            ylabel = 'Temperature'
            yunits = 'K'  
            ;y = tset
            sorting = sort(tset)
            y = tset[sorting]          
            qty = qty[*,sorting]
            err = err[*,sorting]
          endif
          if xxC gt 0 then begin
            ylabel = 'C Values'  
            yunits = ''
            ;y = cset
            sorting = sort(cset)
            y = cset[sorting]          
            qty = qty[*,sorting]
            err = err[*,sorting]

          endif
          if xxN gt 0 then begin
            ylabel = 'Measurement Number'
            yunits = ''
            sorting = sort(nset)
            y = nset[sorting]          
            qty = qty[*,sorting]
            err = err[*,sorting]
          endif  
          if xxH gt 0 then begin
            hset = hset[1:*]
            ylabel = 'Field'
            yunits = ''
            sorting = sort(hset)
            y = hset[sorting]          
            qty = qty[*,sorting]
            err = err[*,sorting]
          endif

          ;IF Y VALUES ARE ALL THE SAME, THEN SET THEM TO INDICES TO AVOID
          ;PROBLEMS WITH DATABROWSER.
          if min(y) eq max(y) then begin
            ylabel = 'Group Number'
            yunits = '#'  
            y = dindgen(n_elements(y))
          endif
          
          ;IN THE  FINAL DAVE FILE:
          ;              x = xset 
          ;              y = Temp/H/C/N array 
          ;              qty = merged ysets 
          ;              err = merged sysets
          ;

          
          ;NOW GET FILENAME, CREATE DAVE PTR AND WRITE TO FILE.
          if n_elements(ofn) eq 0 then begin

            ofn = dialog_pickfile(/write,$
                                  title='BT-1 DAVE export file:',$
                                  path=work_dir,$
                                  /overwrite_prompt,$
                                  filter='*.dave')
            
            if ofn ne '' then begin
              readbt1_addDotDave,ofn
              specificstr = {x:x,xindex:findgen(n_elements(x)),xM4:xset,xT:tset,xN:nset,xH:hset,yrsf:yrsf,yrza:yrza}

              xlabel = xlabel
              ylabel = ylabel;'Detector Channel'
              xunits = xunits;'pointNumber'
              yunits = yunits;'Channel'
              histlabel = 'I (counts)'
              histunits = ''
              treatment = 'BT1Reader Combined Sets'
              instrument = 'BT-1'

              ret = create_dave_pointer( $
                          daveptr,              $
                          instrument = instrument,    $
                          qty = qty,            $
                          qtunits = histunits,       $
                          qtlabel = histlabel,       $
                          err = err,            $
                          xvals = x,          $
                          xtype = 'point',          $
                          xunits = xunits,         $
                          xlabel = xlabel,         $
                          yvals = y,          $
                          ytype = 'point',          $
                          yunits = yunits,         $
                          ylabel = ylabel,         $
                          specificstr = specificstr)

              testfile = file_info(ofn)
              save,filename=ofn,daveptr

              void = dialog_message('Wrote: '+ofn,/info)

            endif
          endif;ofn


end;readbt1_comineResults



;USE .bt1 DATA READER AS A TEST DATA READER FOR iPlot
pro readbt1,result,fn=fn,ofn=ofn,xIndex=xxIndex,xT=xxT,xH=xxH,xM4=xxM4,$
            nodavewrite=nodavewrite

    if n_elements(fn) eq 0 then fn = dialog_pickfile(filter='*.bt1')
    if n_elements(nodavewrite) eq 0 then nodavewrite = 0  ;FLAG TO TURN OFF DAVE WRITE WHEN ONLY result IS NEEDED
                                                          ;e.g. WHEN MULTIPLE RESULTS ARE TO BE COMBINED INTO A SINGLE 
                                                          ;     DAVE FILE.
    ndet = 32
    result = {x:dblarr(1),$
              xIndex:dblarr(1),$
              xT:dblarr(1),$
              xM4:dblarr(1),$
              xC:dblarr(1),$
              xN:dblarr(1),$
              xH:dblarr(1),$
              y:dblarr(1,1),$
              dy:dblarr(1,1),$
              yrsf:[1.0],$
              yrza:dblarr(1),$
              fields:['x: indices', 'xIndex: indices','xM4: Motor 4','xT: Temperature',$
                      'xC: ???','xN: ???','xH: Magnetic Field',$
                      'y: data[npts,ndet]','yrsf: relative scale factors',$
                      'yrza: relative zero angles'],$
              filename:fn,$
              headerline:''}


    if fn ne '' then begin

        ;void = dialog_message('BEFORE strendsub call')
        hfn = strendsub(fn,'.bH1',4)
        ;void = dialog_message('AFTER strendsub call')

        ;print,hfn

    ;THE FIRST TEST SHOULD BE DONE FOR ANY WRITE STATEMENT IN DAVE
    ;BECAUSE IT CAN BE USED TO PREVENT THE PROBLEM OF NOT HAVING WRITE
    ;PERMISSIONS FOR A GIVEN LOCATION.
        ;print,file_test(file_dirname(hfn),/write)

    ;THE SECOND TEST CHECKS TO SEE IF THE GIVEN FILE EXISTS.
        hfn_test = file_test(hfn)
        fn_test  = file_test(fn)

    ;THERE SHOULD BE A CATCH STATEMENT BEFORE EACH FILE READ TO
    ;PREVENT CRASHES IF THE FILE FORMAT IS NOT AS EXPECTED.
        catch, es
        if es ne 0 then begin
            void=dialog_message('Problem reading '+file_basename(fn))
            fn_test = 0
            free_lun,lun
            catch,/cancel
        endif
        if fn_test ne 0 then begin

            nlines = file_lines(fn)
            s = strarr(nlines)
            line=''
            openr,lun,fn,/get_lun
            for i=0,nlines-1 do begin
                readf,lun,line
                s[i] = line
            endfor;i
            free_lun,lun
        endif
        startswitch = 0

        ;print,'RELATIVE SCALE FACTORS:'
        rsf = [double(strsplit(s[8],/extract))]
        rsf = [rsf,double(strsplit(s[9],/extract))]
        rsf = [rsf,double(strsplit(s[10],/extract))]
        yrsf = rsf
        ;print,rsf
        ;help,rsf

        ;print,'RELATIVE ZERO ANGLES:'
        rza = [double(strsplit(s[12],/extract))]
        rza = [rza,double(strsplit(s[13],/extract))]
        rza = [rza,double(strsplit(s[14],/extract))]
        yrza = rza
        ;print,rza
        ;help,rza

        x = [-1.0]
        y = [-1.0]

        ;print,'FIND DATA START LINE:'
        ;FIND LINE WHERE DATA BEGIN
        startline = -1
        for i=0,nlines-1 do begin
            ;USING strmid TO EXTRACT '$' b/c IT IS A WILDCARD CHARACTER FOR stregex
            fc = strmid(s[i],0,1)
            if startline eq -1 then begin
                if fc[0] eq '$' then begin
                    startline = i
                    segs = strsplit(s[i],'=',/regex,/extract)
                endif
            endif
        endfor;i

;        ;MARK THE ENDS OF ALL THE $ LINES:
;        for i=0,nlines-1 do begin
;            fc = strmid(s[i],0,1)
;            if fc[0] eq '$' then begin
;                s[i] = s[i] + '\$'
;            endif
;        endfor;i

        ;print,'COUNT THE DATA:'
        ;COUNT THE DATA
        npts = 0
        i=startline
        while i lt nlines-1 do begin

            fc = strmid(s[i],0,1)
            dataholder = dblarr(ndet)
            if fc eq '$' then begin
                segs = strsplit(s[i],'=',/extract)
                ;print,segs,strlen(s[i])
                i += 1
            endif else begin
                npix = 0
                while npix lt ndet do begin
                oldsegs = segs
                    segs = strsplit(s[i],',',/regex,/extract)

;                    ;COUNT THE commas IN CASE THERE IS AN EXTRA SPACE AT END OF LINE.
;                    ccount = 0
;                    for j=0,strlen(s[i])-1 do begin
;                        c = strmid(s[i],j,1)
;                        if c eq ',' then ccount++
;                    endfor


                    nsegs = n_elements(segs)

                    ccount = 0
                    for j=0,strlen(segs[nsegs-1])-1 do begin
                        c = strmid(segs[nsegs-1],j,1)
                        if c eq ' ' then ccount++
                    endfor
                    if ccount eq strlen(segs[nsegs-1]) then nsegs--

;                    print,strlen(segs[nsegs-1])
;                    if segs[nsegs-1] eq ' ' then nsegs--
;                    ;print,'npix=',npix
                    ;print,i,' nsegs=',nsegs,ccount
                    ;print,'segs=',segs
                    if nsegs gt 0 then begin
                        dataholder[npix:npix+nsegs-1] = double(segs[0:nsegs-1])
                        npix += nsegs
                    endif

                    i += 1
                endwhile;npix
                npts++
;                print,dataholder
            endelse

        endwhile;i

        ;print,'PARSE THE DATA:'
        ;PARSE THE DATA
        headerline = ''
        x      = dindgen(npts)
        xIndex = dindgen(npts)
        xM4 = dblarr(npts)
        xT  = dblarr(npts)
        xC  = dblarr(npts)
        xN  = dblarr(npts)
        xH  = dblarr(npts)

        y = dblarr(npts,ndet)
        dy = dblarr(npts,ndet)
        
        headerline = s[0]

        k=0
        i=startline
        while i lt nlines-1 do begin
            fc = strmid(s[i],0,1)
            dataholder = dblarr(ndet)
            if fc eq '$' then begin
                segs = strsplit(s[i],'=',/extract)
                ;print,segs,strlen(s[i])
                if n_elements(segs) gt 1 then begin
                ;
                    whT = where(stregex(segs,'T',/fold_case) gt 0,count)
                    if count eq 1 then xT[k] = double(segs[whT[0] + 1])
                    whN = where(stregex(segs,'N',/fold_case) gt 0,count)
                    if count eq 1 then xN[k] = double(segs[whN[0] + 1])
                    whC = where(stregex(segs,'C',/fold_case) gt 0,count)
                    if count eq 1 then xC[k] = double(segs[whC[0] + 1])
                    whM4 = where(stregex(segs,'M4',/fold_case) gt 0,count)
                    if count eq 1 then begin
                        xM4[k] = double(segs[whM4[0] + 1])
                        ;print,'Hey'
                    endif
                endif


                ;INCREMENT s ARRAY COUNTER
                i += 1
            endif else begin
                npix = 0
                while npix lt ndet do begin
                    oldsegs = segs
                    segs = strsplit(s[i],',',/regex,/extract)


                    nsegs = n_elements(segs)

                    ;VERIFY THAT LAST SEG IN LINE IS A NUMBER
                    ccount = 0
                    for j=0,strlen(segs[nsegs-1])-1 do begin
                        c = strmid(segs[nsegs-1],j,1)
                        if c eq ' ' then ccount++
                    endfor
                    if ccount eq strlen(segs[nsegs-1]) then nsegs--

                    ;PLACE DATA INTO ARRAY
                    if nsegs gt 0 then begin
                        dataholder[npix:npix+nsegs-1] = double(segs[0:nsegs-1])
                        npix += nsegs
                    endif

                    ;INCREMENT s ARRAY COUNTER
                    i += 1
                endwhile;npix


                ;SCALE THE DATA AND ERROR BARS
                if n_elements(yrsf) eq n_elements(dataholder) then begin
                    y[k,*]  = dataholder*yrsf
                    dy[k,*] = sqrt(dataholder)*yrsf
                endif else begin
                    y[k,*]  = dataholder
                    dy[k,*] = sqrt(dataholder)
                endelse

                k++
            endelse
        endwhile;i

        ;print,'GET MAGNETIC FIELD VALUES:'
        catch, es
        if es ne 0 then begin
            print,'Problem reading '+file_basename(hfn)
            hfn_test = 0
            free_lun,lun
            xh = 0.0*x
            catch,/cancel
        endif
        if hfn_test ne 0 then begin
            nlines = file_lines(hfn)
            s = strarr(nlines)
            line=''
            openr,lun,hfn,/get_lun
            readf,lun,s
;            help,lun,/files
            free_lun,lun

;print,i,nlines,npts
            for i=3,npts-1 do begin
                segs = strsplit(s[i],/extract)
                xH[i] = double(segs[1])
            endfor;i
         endif

  
       headsegs = strsplit(headerline,/extract)
       monitor = double(headsegs[10])
       prefactor = double(headsegs[11])
       base = headsegs[12]

       result = {x:x,xIndex:xIndex,xM4:xM4,xT:xT,xC:xC,xN:xN,xH:xH,y:y,dy:dy,yrsf:yrsf,yrza:yrza,$
                  fields:['x: indices', 'xIndex: indices','xM4: Motor 4','xT: Temperature',$
                          'xC: ???','xN: ???','xH: Magnetic Field',$
                          'y: data[npts,ndet]','dy: ddata[npts,ndet]',$
                          'yrsf: relative scale factors',$
                          'yrza: relative zero angles'],$
                          filename:fn,fieldfilename:hfn,$
                          headerline:headerline,$
                          monitor:monitor,$
                          prefactor:prefactor,$
                          base:base}



        if nodavewrite eq 0 then begin 

          ;HOW WOULD I TURN THIS INTO A DAVE POINTER?
          if n_elements(ofn) eq 0 then begin
              yn = dialog_message('Write a DAVE file?',/question)
          endif else begin
              yn = 'Yes'
          endelse
  
  
          ;print,yn
          if yn eq 'Yes' then begin
              test = bt1_writedave(result,ofn,xIndex=xxIndex,xT=xxT,xH=xxH,xM4=xxM4)
              ;print,test
          endif
          
        endif;nodavewrite eq 0


    endif;fn ne ''

end;readbt1
