;+
; NAME:
;             WBDA
; PURPOSE:
;             to provide widget interface to Yohkoh BCS data
; CALLING SEQUENCE:
;             WBDA
; INPUTS:
;             bda_index = BDA index structure array
;             bda_data  = BDA spectral data  array 
; OPTIONAL OUTPUTS:
;             bsc_index = BSC index structure 
;             bsc_data  = BSC data structure
; RESTRICTIONS: 
;             needs X-windows 
; MODIFICATION HISTORY:
;             Oct'92, DMZ (ARC) -- written
;             Oct'93, DMZ -- changed bsc_index and bsc_data to argument inputs
;             1- Jun'94, DMZ -- fixed potential bug in BDA roadmap/index usage
;            30- Jun'94, DMZ -- separated lightcurve and spectrum window bases
;-

pro wbda_event, event                         ;WBDA event handler


;--initialize

@wbda_com_blk
if !version.os eq 'vms' then delim='' else delim='/'
shard=0 & lhard=0 & fit=0
dsecs=24.*60.*60.

widget_control, event.id, GET_UVALUE = USERVALUE
if (n_elements(uservalue) eq 0) then uservalue=''
wtype=strmid(tag_names(event,/structure_name),7,1000)

;-- SLIDER widget?

if (wtype eq 'SLIDER') then begin
 accum=float(event.value)
 widget_control,comment,$
  set_value='SELECTED ACCUMULATION TIME:'+string(accum(0),'(f6.2)'),/append
 plot_lc=1 & get_lc=1 & get_sp=1 
 return
endif

;-- DRAW widget?
;   save latest two cursor positions in plot range variables for later 
;   zooming or fitting applications)

if (wtype eq 'DRAW') then begin

 if event.press eq 0b then return

;-- lightcurve window?

 if (event.id eq ldraw)  then begin  

  if (n_elements(tb) eq 0) then return

  wset,lval & !x=lx & !y=ly & !p=lp
  data_x=(float(event.x)/float(ld.x_vsize) -float(lx.s(0)))/float(lx.s(1))
  data_y=(float(event.y)/float(ld.y_vsize) -float(ly.s(0)))/float(ly.s(1))

  if log then ylim=10.^ly.crange else ylim=ly.crange
  if n_elements(lxrange) eq 0 then lxrange=[data_x,data_x] else begin
   if (lxrange(0) gt min(lx.crange)) and (lxrange(0) lt max(lx.crange)) then $
    oplot,[lxrange(0),lxrange(0)],ylim,color=0
   lxrange=[lxrange(1),data_x]
  endelse

  if n_elements(lyrange) eq 0 then lyrange=[data_y,data_y] else $
   lyrange=[lyrange(1),data_y]
  if n_elements(linestyle) eq 0 then linestyle=0
  oplot,[data_x,data_x],ylim,linestyle=linestyle
  if linestyle eq 0 then linestyle=1 else linestyle=0
  
  stime=data_x
  plot_lc=0 & get_lc=0 & plot_sp=1 
 endif

;-- spectrum window?
 
 if (event.id eq sdraw) then begin
  if (n_elements(w) eq 0) or (sval eq -1) then return

  wset,sval & !x=sx & !y=sy & !p=sp
  data_x=(float(event.x)/float(sd.x_vsize)-float(sx.s(0)))/float(sx.s(1))
  data_y=(float(event.y)/float(sd.y_vsize)-float(sy.s(0)))/float(sy.s(1))

  if n_elements(sxrange) eq 0 then sxrange=[data_x,data_x] else begin
   if (sxrange(0) gt min(sx.crange)) and (sxrange(0) lt max(sx.crange)) then $
    oplot,[sxrange(0),sxrange(0)],sy.crange,color=0
   sxrange=[sxrange(1),data_x]
  endelse
  if n_elements(syrange) eq 0 then syrange=[data_y,data_y] else $
   syrange=[syrange(1),data_y]
   oplot,[data_x,data_x],sy.crange,linestyle=2
  return
 endif

endif

;-- BUTTON widget?

if wtype eq  'BUTTON' then begin
 buttname=strtrim(uservalue,2)

;-- prompt user for output filename if WRITE button was pressed

 wbutt=where(buttname eq ['S_ASCII','S_XDR','L_ASCII','L_XDR'],count)
 if count ne 0 then begin     
  widget_control,wbase,/realize
  widget_control,wbase,show=1
  xmanager,'wbda',wbase,group_leader=base
  wopt=buttname & return
 endif

 case buttname of 


  'ABORT':    begin
               if event.id eq wabort then widget_control,wbase,show=0
               if event.id eq eabort then widget_control,ebase,show=0
               return
              end

   'APPLY'  : begin
               if n_elements(accum(0)) ne 0 then begin
                if (bname eq 'NO FILES') and (not dinput) then return
                plot_lc=1 & get_lc=1 & get_sp=1 
                if sval gt -1 then widget_control,sbase,show=0
               endif else begin
                widget_control,comment,$
                 set_value='PLEASE SELECT AN ACCUMULATION TIME',/append
                return
               endelse
              end

  'BLUEWING': begin
               fit=1 & funct='fludra' 
              end

  'COMP'   :  begin                                 ;-- compare spectra
               if n_elements(zlast) eq 0 then begin
                widget_control,slabel,set_value='SELECT A SECOND SPECTRUM AND TRY AGAIN'
                return
               endif
               oplot,w,zlast*max(z)/max(zlast),linestyle=1
               return
              end

  'TYPE'   :  begin                              ;-- change directory
               widget_control,ebase,/realize
               widget_control,ebase,show=1
               xmanager,'wbda',ebase,group_leader=base
               return
              end

  'FIND'    : begin
               widget_control,flist,set_value=direcs,set_uvalue='D_'+direcs
               widget_control,llabel,set_value='PLEASE SELECT A DIRECTORY'
               fext='*.*'
               return
              end

  'DERIV'   : begin 
               if event.select eq 1 then diff=1 else diff=0 
               plot_lc=1
              end

  'FLUDRA2' : begin fit=1 & funct='fludra2' & end


  'ERRORS'  : begin
               if event.select eq 1 then err=1 else err=0
               plot_lc=1 
              end

  'DEADTIME' : begin
               if event.select eq  1 then deadtime=1 else deadtime=0
               if accum(0) le min_accum then begin
                widget_control,slabel,set_value='PLEASE ACCUMULATE SPECTRA FIRST'
                return
               endif
               plot_sp=1 & plot_lc=0 & get_sp=1 & get_lc=1
              end

  'FLUXCAL' : begin
               if event.select eq  1 then fluxcal=1 else fluxcal=0
               if (fluxcal eq 1) and (xcorr eq 0) then begin
                widget_control,slabel,set_value='MUST APPLY CURVATURE CORRECTION'
                xcorr=1 & widget_control,splotb(1),set_button=1
               endif
               plot_sp=1 & plot_lc=0 
              end

  'WAVECAL' : begin
               if event.select eq 1 then wavecal=1 else wavecal=0
               plot_sp=1 & plot_lc=0 & szoom=0
              end

  'GAUSS'   : begin 
               if event.select eq 1 then begin
                fit=1 & funct='gauss' 
               endif
              end

  'HELP'    : begin                                        ;-- get help
               if event.select eq 1 then begin
                chelp=chklog('DIR_BCS_DOC')
                help_file=concat_dir('$DIR_BCS_DOC','bsc_software.txt')
                clook=findfile(help_file,count=nf)
                if nf eq 0 then begin
                 widget_control,comment,set_value='NO HELP FILES ON LINE',/append
                endif else xdisplayfile,clook(0),group=base
                return
               endif
              end

  'INTEG'   : begin 
               stime=lxrange & plot_lc=0 & plot_sp=1  ;-- integrate spectra
              end

  'LINE'    : begin                          
               if event.select eq 1 then psym=0 else psym=1
               plot_lc=1 
              end


  'LHARD'   : begin             ;-- hardcopy lightcurve
               if test_open(/write) then begin
                lhard=1 & plot_lc=1 
               endif else begin
                widget_control,llabel,$
                 set_value='Cannot open plot file on current directory',/app
                return
               endelse
              end     

  'LOG'     : begin                               ;-- log lightcurve
               if event.select eq 1 then log=1 else log=0
               plot_lc=1
              end

  'LRESET'  : begin lxrange=[0,0] & plot_sp=0 & plot_lc=1 & lzoom=0 & end


  'LZOOM'   : begin                 ;-- zoom lightcurve
               plot_lc=1
               wset,lval & !p=lp & !x=lx & !y=ly & lzoom=1
               if n_elements(lxrange) eq 2 then begin
                xz=[lxrange(0),lxrange(1),lxrange(1),lxrange(0),lxrange(0)]
                yz=[lyrange(1),lyrange(1),lyrange(0),lyrange(0),lyrange(1)]
                if log then yz=10.^yz  & oplot,xz,yz 
               endif else return
              end

  'OVER'    : begin over=1 & return & end              ;-- overplot spectra

  'QUIT'    : goto, exit

  'SBIN'    : begin                              ;-- double bin spectra
               if event.select eq 1 then sbin=2 else sbin=1
               plot_sp=1 & plot_lc=0
              end

  'SDA'     : begin                              ;-- search on date
               twidget,sdate,group_leader=base,error=err
               if err then return
               if sdate.year le 1979 then yy='*' else $
                yy=strmid(string(sdate.year,'(i4.2)'),2,2)
               if sdate.month le 0 then mm='*' else mm=string(sdate.month,'(i2.2)')
               if sdate.day le 0 then dd='*' else dd=string(sdate.day,'(i2.2)')
               fext=yy+mm+dd+'.*'
               widget_control,llabel,set_value='SEARCHING DATABASE...'
               widget_control,base,sensitive=0
               fnames=loc_file('bda'+fext,path=direcs,/all,count=count)
               widget_control,base,sensitive=1
               if count eq 0 then fext='*.*' 
               wflist,fnames,flist,llabel
               return 
              end

  'SHARD'   : begin            ; -- hard copy spectra
               if test_open(/write) then begin
                shard=1 & plot_sp=1 & & plot_lc=0
               endif else begin
                widget_control,slabel,$
                 set_value='Cannot open plot file on current directory',/app
                return
               endelse
              end     

  'SRESET'  : begin sxrange=[0,0] & plot_sp=1 & plot_lc=0 & szoom=0 & end

  'SZOOM'   : begin                         ;-- zoom on spectra
               wset,sval & !p=sp & !x=sx & !y=sy & szoom=1
               plot_sp=1 & plot_lc=0 & get_sp=0 & get_lc=0
               if n_elements(sxrange) eq 2 then begin
                xz=[sxrange(0),sxrange(1),sxrange(1),sxrange(0),sxrange(0)]
                yz=[syrange(1),syrange(1),syrange(0),syrange(0),syrange(1)]
                oplot,xz,yz
               endif else return
              end

  'OS'     : begin                                   ;-- spawn to OS
               widget_control,base,show=0 & spawn
               widget_control,base,show=1 & return
              end

  'VOIGT'   : begin 
               if event.select eq 1 then begin fit=1 & funct='voigt' & endif
              end

  'WAVE'    : begin 
               szoom=0 
               if event.select eq 1 then wave=1 else wave=0
              end


  'XCORR'  :  begin
               if event.select eq  1 then xcorr=1 else xcorr=0
               if (fluxcal eq 1) and (xcorr eq 0) then begin
                widget_control,splotb(2),set_button=0
                widget_control,slabel,$
                 set_value='MUST ALSO SWITCH OFF FLUX CALIBRATION'
                fluxcal=0
               endif
               plot_sp=1 & plot_lc=0 
              end

  else:       begin
               det=strpos(buttname,'D_')    ;-- channel button
               if det ge 0 then begin
                dname=fix(strmid(buttname,2,2))
                if (dname eq chan(0)) and (event.select eq 0) then begin
                 widget_control,detb(chan(0)-1),set_button=1 
                 if not plot_lc then return
                 get_lc=1
                endif
                if (dname ne chan(0)) and (event.select eq 1) then begin
                 widget_control,detb(chan(0)-1),set_button=0
                 chan=dname & get_lc=1 & get_sp=1
                endif
                widget_control,comment,set_value='SELECTED CHANNEL: '+string(chan(0),'(i2)'),/append
                lzoom=0 & szoom=0 & plot_lc=1 & plot_sp=1 
                if sval gt -1 then widget_control,sbase,show=0
               endif else begin
                widget_control,comment,set_value='SELECTED INVALID BUTTON',/append
                return
               endelse
               if (bname eq 'NO FILES') and (not dinput) then return
              end
 endcase

endif

;-- TEXT widgets

if (event.id eq etext) then begin                   ;-- change input directory
 widget_control,etext,get_value=edir,set_value=''
 edir=edir(0)
 if edir ne '' then begin
  cur_dir=edir(0) & cur_log=chklog(edir)
  if cur_log ne '' then cur_dir=cur_log
 endif 
 cur_dir=strtrim(cur_dir,2)
 widget_control,comment,set_value='SELECTED: '+cur_dir,/append
 widget_control,ebase,show=0
 fnames=loc_file('bda'+fext,path=cur_dir,count=count)
 if count eq 0 then fext='*.*' 
 wflist,fnames,flist,llabel
 return
endif

;-- write data 

if (event.id eq wtext) then begin    
 widget_control,wtext,get_value=outfile,set_value=''
 outfile=outfile(0)
 if outfile eq '' then outfile='bda.dmp'
 widget_control,comment,set_value='WRITING DATA TO '+outfile,/append
 case wopt of
   'S_ASCII': begin
               if (n_elements(w) ne 0) then begin     ;-- write spectrum
                wr_asc,outfile,slabels,w,z
               endif
              end
   'L_ASCII': begin
               if (n_elements(yb) ne 0) then begin  ;-- write lightcurve
                wr_asc,outfile,llabels,tb,yb
               endif
              end
   'S_XDR'  : begin
               if (n_elements(w) ne 0) then begin     ;-- write spectrum
                save,slabels,w,z,filename=outfile,/verbose,/xdr
               endif
              end
   'L_XDR'  :  if (n_elements(yb) ne 0) then begin     ;-- write lightcurve
                save,llabels,tb,yb,filename=outfile,/verbose,/xdr
               endif
   else     :  return
 endcase
  widget_control,wbase,show=0 & return
endif

;-- LIST widgets

if wtype eq 'LIST' then begin
 lname=strtrim(uservalue(event.index),2)
 if (strpos(lname,'D_') ne -1) then begin     ;-- directory selected
  cur_dir=strmid(lname,2,100)
  widget_control,comment,set_value='SELECTED: '+cur_dir,/append  
  fnames=loc_file('bda'+fext,path=cur_dir,count=count)
  if count eq 0 then fext='*.*' 
  wflist,fnames,flist,llabel
  return
 endif else begin                             ;-- file selected
  if (lname eq 'NO FILES') then return
  bname=lname
  zpos=strpos(strupcase(bname),'_Z')
  if zpos gt -1 then begin
   widget_control,llabel,set_value='CANNOT READ A COMPRESSED BDA FILE',/append
   return
  endif
  break_file,bname,dsk,direc,name,ext,version
  widget_control,comment,set_value='SELECTED: '+name+ext,/append  
  read_roadmap=1 & dinput=0 & cur_dir=direc
  widget_control,comment,set_value='FROM DIRECTORY: '+cur_dir,/append
  widget_control,dets,sensitive=1
  widget_control,acc,sensitive=1
  accum=0. & widget_control,acc,set_value=0.
  lzoom=0 & szoom=0
 endelse
endif

;-- read BDA roadmap for fast lightcurve

if read_roadmap then begin
 get_lc=1 & plot_lc=1 & read_index=1 & get_sp=1
 if bname eq 'NO FILES' then begin
  widget_control,llabel,set_value='PLEASE SELECT A FILE' & return
 endif
 roadmap=0
 widget_control,llabel,set_value='READING BDA ROADMAP, PLEASE STAND BY....'
 rd_roadmap,bname,roadmap,ndset
 if total(ndset) eq 0 then begin
   widget_control,comment,set_value='NO DATA IN '+bname,/append
  widget_control,llabel,set_value='ZERO DATA, PLEASE TRY ANOTHER FILE' & return
 endif
 read_roadmap=0
endif

;-- get light curve from INDEX if non-accumulated, else accumulate using MK_BSA

if get_lc then begin

 widget_control,llabel,set_value='GETTING LIGHTCURVE, PLEASE WAIT...'
 if sval gt  -1 then begin
  wset,sval & erase
  widget_control,slabel,set_value=''
 endif

;-- was INDEX entered?

 if strupcase((tag_names(roadmap))(0)) eq 'GEN' then begin
  sdgi=roadmap.bcs.dgi*.125
  modeid=roadmap.bcs.modeid
 endif else begin 
  sdgi=roadmap.dgi*.125
  modeid=roadmap.modeid
 endelse


;-- get lightcurve

 min_accum=min(sdgi)
 sdgi=(sdgi > .01)
 if accum(0) le min_accum then begin
  day=gt_day(roadmap)
  tb=gt_time(roadmap)/1000.+(day-day(0))*dsecs
  yb=gt_total_cnts(roadmap,chan) > .01
  interval=0
 endif else begin
  mk_bsa_stc,bindex,chans=chan,accum=accum,$
  deadtime=deadtime,xcorr=0,fluxcal=0,wavecal=0
  mk_bsa_interv,roadmap,bindex,err=err_flag

  if err_flag then begin
   widget_control,comment,set_value='ERROR ACCUMULATING DATA',/append
   return
  endif
  cfind=where(bindex.bsc.chan eq chan(0),count)
  sdgi=((bindex.bsc.actim)(cfind)/1000.) > .01
  day=gt_day(bindex(cfind))
  tb=gt_time(bindex(cfind))/1000.+(day-day(0))*dsecs
  yb=((bindex.bsc.total_cnts)(cfind)/sdgi) > .01
  interval=(bindex.bsc.interval)(cfind)/1000.
 endelse

 tbase=dsecs*(day(0)-1)   ;-- need this for UTPLOT to work with array inputs
 get_lc=0 & yb=yb(*)
endif

;-- plot lightcurve?

if plot_lc then begin
 widget_control,lbase,sensitive=1

 if not lhard then wset,lval
 if n_elements(lp) ne 0 then begin
  !x=lx & !y=ly & !p=lp         
 endif
 set_utlabel,0  & lxtitle='UNIVERSAL TIME'
 if not lzoom then lxrange=[0,0] & lyrange=[0,0]

 llabels=['DATE: '+strmid(atime(tbase),0,9),'ION: '+bions(chan(0)-1), $
          'CHANNEL: '+string(chan(0),'(i1)'),$
          'ACCUM (SECS): '+string(accum(0) > min_accum,'(f6.2)')]
 binterval=interval

;-- plot derivatives and/or error bars?
 
 if diff then begin
  ybuff=deriv(tb,yb)
  lytitle='COUNTS PER SEC^2' 
  uncert=0 & blog=0 & binterval=0
 endif else begin
  lytitle='COUNTS PER SEC' & ybuff=yb
  if err then uncert=sqrt(yb/sdgi) else uncert=0
  blog=log
 endelse

 if lhard then set_hard

 sxl=sort(lxrange)
 syl=sort(lyrange)

 plotltc,tb,ybuff,atime(tbase),ebar=uncert,log=blog,psym=psym,$
         xrange=lxrange(sxl),ytitle=lytitle,$
         yrange=lyrange(syl),xtitle=lxtitle,/draw,interval=binterval

 if not lhard then begin
  widget_control,llabel,set_value=llabels(*) 
  lx=!x & ly=!y & lp=!p & ld=!d    
 endif else begin
  set_hard,llabels,/send
 endelse

;-- return and wait for user to select spectrum

 widget_control,llabel,set_value='USE CURSOR TO SELECT TIME OF SPECTRUM'
 plot_lc=0 & return
endif 

;-- get a spectrum

if get_sp then begin
 if read_index then begin
  widget_control,llabel,set_value='READING BCS SPECTRA, PLEASE WAIT...'
  ndset=-1 & index=0. & data=0. & dp_sync=0.
  widget_control,base,sensitive=0
  rd_bda,bname,ndset,index,data,roadmap,dp_sync
  roadmap=index
  mk_bsa_stc,bindex,chans=chan,accum=accum,$
  deadtime=deadtime,xcorr=0,fluxcal=0,wavecal=0
  mk_bsa_interv,roadmap,bindex,err=err_flag

  if err_flag then begin
   widget_control,comment,set_value='ERROR ACCUMULATING DATA',/append
   return
  endif

  widget_control,base,sensitive=1

;-- check possible bad records

  clean=bcs_clean(index,err=err_flag)
  if err_flag then begin
   widget_control,comment,set_value='NO VALID MODES IN '+bname
   widget_control,llabel,set_value='TRY ANOTHER FILE'
   return
  endif
  read_index=0
 endif

 sdgi=(index.bcs.dgi*.125 > .01) & min_accum=min(sdgi)

 if accum(0) le min_accum then begin
  bdata=ext_bcschan(index,data,chan(0),/lastbin)
  if datatype(bdata) eq 'BYT' then bdata=bcs_decomp(bdata)
 endif else begin
  widget_control,llabel,set_value='MAKING BSC ARRAY...'
  widget_control,base,sensitive=0
  mk_bsc_data,index,data,bindex,bdata,dp_sync=dp_sync,/novalid
  widget_control,base,sensitive=1
  cfind=where(bindex.bsc.chan eq chan(0),count)
  sdgi=((bindex.bsc.actim)(cfind)/1000.) > .01
  day=gt_day(bindex(cfind))
  tb=gt_time(bindex(cfind))/1000.+(day-day(0))*dsecs
  yb=(bindex.bsc.total_cnts)(cfind)/sdgi
  bdata=bdata(cfind).counts
  tbase=(day(0)-1)*dsecs
  modeid=(bindex.bsc.modeid)(cfind)
 endelse

 get_sp=0
endif

;-- plot spectrum?

if plot_sp then begin

 if not shard then begin
  if (sval eq -1) then begin     
   widget_control,base,tlb_get_size=wsize,tlb_get_offset=woff
   widget_control,sbase,/realize,$
    tlb_set_xoffset=woff(0)+wsize(0)/2.
   widget_control,get_value=sval,sdraw
   xmanager,'wbda',sbase,group=base
  endif else begin
   widget_control,sbase,show=1,sensitive=1
   wset,sval
  endelse
 endif

 if n_elements(sp) ne 0 then begin   
  !p=sp & !x=sx & !y=sy
 endif 

;-- find spectrum nearest to cursor position

 dmin=abs(tb-min(stime)) & dmax=abs(tb-max(stime))
 imin=where(dmin eq min(dmin),c1) & imax=where(dmax eq min(dmax),c2)
 if (c1 eq 0) or (c2 eq 0) or $
   (min(stime) lt min(tb)) or (max(stime) gt max(tb)) then begin
   widget_control,comment,set_value='SELECTED INVALID SPECTRUM',/append
  plot_lc=1 & return
 endif

;-- get calibration values for this channel and mode

 nspec=imax(0)-imin(0)+1
 vspec=imin(0)+indgen(nspec)
 bincal=gt_bsc_bincal(chan,modeid(vspec(0)),/novalid)
 nbins=bincal.nbins-1

 if n_elements(z) ne 0 then zlast=z
 if nspec gt 1 then begin
  saccum=total(sdgi(vspec))
  z=(total(bdata(0:nbins-1,vspec),2)/saccum) > 0.
 endif else begin
  saccum=sdgi(vspec(0))
  z=(bdata(0:nbins-1,vspec(0))/saccum) > 0.
 endelse

;-- wavelength scale?

 if wavecal then begin
  w=bincal.w0+bincal.dw*(bincal.physpos)(0:nbins-1)
  sxtitle='LAMBDA (A)'
 endif else begin
  w=findgen(nbins)+1 & sxtitle='BIN NO.' 
 endelse

;-- curvature correct?

 if xcorr then begin
  xcorrf=(bincal.sensit)(0:nbins-1)
  z=z/xcorrf
 endif

;-- flux calibrate?

 if fluxcal then begin
  fluxfac=(bincal.fluxfac)(0:nbins-1)
  z=z*fluxfac
 endif

;-- update plot labels

 
 mtime=tbase+.5*(tb(imin(0))+tb(imax(0)))
 dtime=atime(mtime)
 slabels=['DATE: '+strmid(atime(tbase),0,9),   $
          'START TIME: '+strmid(dtime,9,100),    $
          'ION: '+bions(chan(0)-1), $
          'CHANNEL: '+string(chan(0),'(i1)'),$
          'INTERVAL (SECS): '+string(saccum(0),'(f7.2)')]
 if deadtime then slabels=[slabels,'DEADTIME CORRECTED']
 if xcorr then slabels =[slabels,'CURVATURE CORRECTED']
 if not szoom then sxrange=[0,0]     ;-- zoom?
 syrange=[0,0]
 
 if fluxcal then sytitle='PHOTONS CM-2 S-1 A-1' else sytitle='COUNTS PER SEC PER BIN' 
 wok=where(w gt 0,count)
 if count eq 0 then begin
  widget_control,comment,set_value='INVALID X-AXIS',/append
  return
 endif

 if shard then set_hard

 sxs=sort(sxrange)
 sys=sort(syrange)

 plotspec,w(wok),z(wok),xtitle=sxtitle,ytitle=sytitle,$
          yrange=syrange(sys),/draw,$
          xrange=sxrange(sxs),over=over,psym=10

 if not shard then begin
  widget_control,slabel,set_value=slabels(*)
  sx=!x & sy=!y & sp=!p & sd=!d
 endif else set_hard,slabels,/send

;-- return and wait for user to make another selection

 plot_sp=0
 return
endif

exit:

clear_utplot
widget_control,event.top,/destroy,/clear_events,bad_id=destroyed

return & end

;-----------------------------------------------------------------------------

pro wflist,files,flist,comment

;-- list FILES array to list widget FLIST
;-- write message out to text widget COMMENT
;-- called from WBDA

;HISTORY -- written by Zarro (ARC) Nov'92

count=n_elements(files)
if count eq 0 then files=''
if files(0) eq '' then begin
 tfile='NO FILES FOUND' & result='NO FILES'
  widget_control,flist,set_value=tfile,set_uvalue=result
  widget_control,comment,set_value=tfile
  widget_control,comment,set_value='PLEASE MAKE ANOTHER SELECTION',/append
  return
endif else begin
 tfile=strarr(count)
 for i=0,count-1 do begin
  break_file,files(i),dsk,direc,name,ext
  tfile(i)=name+ext
 endfor
endelse
widget_control,flist,set_value=tfile,set_uvalue=files
widget_control,comment,set_value='PLEASE MAKE A SELECTION'

return & end

;------------------------------------------------------------------------------

pro wbda,bda_index,bda_data,bsc_index,bsc_data, $
         group_leader=group,dp_sync=dp_sync_sav,bdafile=bdafile

;-- initialize

if (!d.flags and 65536) eq 0 then message,'widgets are unavailable'
@wbda_com_blk
set_plot,'X'
if !version.os eq 'vms' then delim='' else delim='/'

if n_elements(group) eq 0 then begin
 widget_control,/reset,/clear_events
 group=0l
endif else begin
 if xregistered('wbda') then begin
  message,'WBDA already registered',/continue
  return
 endif
endelse

;-- autosize screen

cleanplot
device,get_screen_size=sc
fspace=.0146*sc(0)*.5
fxpad=.0117*sc(0)*.5
fypad=.0146*sc(1)*.5
scx=sc(0)/1280. & scy=sc(1)/1024.

;-- data entered on command line? If so, then don't prompt for files

if datatype(bdafile) eq 'STR' then $
 rd_bda,bdafile,-1,bda_index,bda_data,roadmap,dp_sync
str_checks,/off
sz_index=size(bda_index) & sz_data=size(bda_data)
ndsets=sz_data(2)
nstruct=sz_index(1)
dinput=0
if (datatype(bda_index) eq 'STC') and (ndsets eq nstruct) then begin
 dinput=1 & read_roadmap=0 & index=bda_index & data=bda_data
 read_index=0 & roadmap=index
endif else begin
 if (n_elements(roadmap) eq 0) then read_roadmap=1
 if (n_elements(index) eq 0) or (n_elements(data) eq 0) then read_index=1
 sz=size(roadmap) 
 if (sz(n_elements(sz)-2) eq 8) then begin
  if strupcase((tag_names(roadmap))(0)) eq 'GEN' then read_roadmap=1
 endif
 print,'N.B. type WBDA,INDEX,DATA if BCS data already read by YODAT'
endelse


;-- some defaults

over=0 
fit=0 & diff=0 & stime=0
szoom=0 & lzoom=0 & lhard=0 & shard=0 & deadtime=0 & wavecal=1 & xcorr=0
plot_lc=1 & get_lc=1 & get_sp=1 & plot_sp=0 & fluxcal=0
psym=0
log=0 & err=0 & sbin=0
if n_elements(accum) eq 0 then accum=0.
if n_elements(chan) eq 0 then chan=3
if n_elements(bname) eq 0 then bname='NO FILES'
if n_elements(slabels) eq 0 then slabels=''
if n_elements(llabels) eq 0 then llabels=''
direcs=strtrim(data_paths(),2)
if n_elements(cur_dir) eq 0 then cur_dir=direcs(0)
if n_elements(fext) eq 0 then fext='*.*'

;
;-- go to a specific file and directory
;

if not dinput then begin
 if (bname eq 'NO FILES') or (fext eq '*.*') then begin
  print,'* If there is a particular date that you are interested in then'
  print,'  please enter that date now in a format like 9-OCT-92 (for example):'
  print,'  [hit return to continue without entering a specific date]'
  fext='' & read,'---> ',fext
  if fext ne '' then begin
   tinput=anytim2ex(fext)
   yy=string(tinput(6),'(i2)')
   mm=string(tinput(5),'(i2.2)')
   dd=string(tinput(4),'(i2.2)')
   fext=yy+mm+dd+'.*' & fname='bda'+fext
   tname=loc_file(fname,path=direcs,loc=cur_dir,/all,count=count)
   if count eq 0 then begin
    print,'- Sorry, BDA file for that date is not present in the directory path'
    print,'- Select BDA files using widget menus'
    fext='*.*' & cur_dir=direcs(0)
   endif else begin bname=tname(0) & cur_dir=cur_dir(0) & endelse
  endif else fext='*.*
 endif
endif

;-- parent widget

btitle='YOHKOH BCS DATA ANALYSIS WORKBENCH'
base = widget_base(TITLE =btitle, XPAD =fxpad, YPAD =fypad,$
                   SPACE = fspace,/frame,/row)

lbase=widget_base(base,/column,space=fspace,xpad=fxpad,ypad=fypad)   

;-- top row of buttons

row1=widget_base(lbase,/row,space=fspace,xpad=fxpad,ypad=fypad,/frame)   


;-- quit button

main = widget_button(row1,value='Quit',uvalue='QUIT',/no_release,/frame)

;-- OS button

osb=widget_button(row1,value='Spawn To OS',uvalue='OS',/no_release)

;-- find file buttons

desc=['"Find Files" {',               $
      '"Find by Directory" FIND',     $
      '"Find by Date"      SDA',      $
      '"Type Directory Name" TYPE',   $
      '"Return             " ABORT','}']
xpdmenu,desc,row1

;-- help button

help = widget_button(row1,value='Help',uvalue='HELP',/no_release)

;-- replot

;reset = widget_button(row1,value='Reset',uvalue='RESET',/no_release)



;-- 3rd row

row3=widget_base(lbase,/column,space=fspace,xpad=fxpad,ypad=fypad,/frame)

;-- comment window

temp=widget_base(row3,/column,xpad=fxpad,ypad=fypad,space=fspace)
 mlabel=widget_label(temp,value='INFORMATION WINDOW')
 comment=widget_text(temp,/scroll,ysize=8*scy)

;-- 4th row


row4=widget_base(lbase,/row,space=fspace,xpad=fxpad,ypad=fypad,/frame)

;-- 1st column

;-- file or directory window

r4c1=widget_base(row4,/column,space=fspace,xpad=fxpad,ypad=fypad)
temp=widget_base(r4c1,/column,/frame,xpad=fxpad,ypad=fypad)
dlabel=widget_label(temp,value='FILE/DIRECTORY SELECTION')
flist=widget_list(temp,ysize=10*scy)

;-- 2nd column

r4c2=widget_base(row4,/column,space=fspace,xpad=fxpad,ypad=fypad,/frame)

;-- channel buttons

bions = ['Fe XXVI', 'Fe XXV', 'Ca XIX', 'S XV']
dets=widget_base(r4c2,/column,xpad=fxpad,ypad=fypad,space=fspace)
channels=strtrim(string(indgen(4)+1),2)
detb=lonarr(n_elements(channels))
xmenu,'CH '+channels+' - '+bions,dets,buttons=detb,/nonexclusive,$
 title='CHANNEL BUTTONS', /column,space=fspace,uvalue='D_'+strtrim(channels,2),/no_release

widget_control,detb(chan(0)-1),set_button=1

;-- integration time


acc=widget_slider(r4c2,minimum=0,maximum=100,title='ACCUMULATION TIME (S)',$
    value=accum(0))

app=widget_button(r4c2,value='APPLY ACCUM',uvalue='APPLY')

;-- lightcurve window in row2 of column 2

col2=widget_base(base,/column,space=fspace,xpad=fxpad,ypad=fypad,/frame)   

r1c2=widget_label(col2,value='LIGHTCURVE WINDOW')

;-- lightcurve buttons

popts=['Log Scale','Uncertainties','Derivative','Line'] 
pvalues=['LOG','ERRORS','DERIV','LINE']

xmenu,popts,col2,buttons=lplotb,/nonexclusive,/row,title='PLOT OPTIONS',$
 uvalue=pvalues,space=fspace
widget_control,lplotb(3),set_button=1 

ldraw=widget_draw(col2,xsize=300*scx,ysize=300*scy,retain=2,/button_events)
llabel=widget_text(col2,ysize=5*scy,/frame)

temp=widget_base(col2,/row,space=fspace,xpad=fxpad,ypad=fypad)
desc=['"Zoom" {',               $
      '"Zoom in Time" LZOOM',     $
      '"Reset to Original"      LRESET','}']

xpdmenu,desc,temp

integ=widget_button(temp,value='Integrate',uvalue='INTEG',/no_release)

;-- save buttons

desc=['"Write " {',               $
      '"Write to ASCII file" L_ASCII',     $
      '"Save in IDL/XDR saveset"      L_XDR',      $
      '"No write" ABORT','}'] 

xpdmenu,desc,temp

lhardb=widget_button(temp,value='Hard Copy',uvalue='LHARD',/no_release)

;-- spectrum window in row 2 column 3

sbase=widget_base(title=' ',/column,space=fspace,xpad=fxpad,ypad=fypad,/frame)   
r1c3=widget_label(sbase,value='SPECTRUM WINDOW')

popts=['Deadtime','Curvature','Flux']
pvalues=['DEADTIME','XCORR','FLUXCAL']

xmenu,popts,sbase,buttons=splotb,/nonexclusive,/row,title='PROCESSING OPTIONS',$
 uvalue=pvalues,space=fspace

sdraw=widget_draw(sbase,xsize=500*scx,ysize=300*scy,retain=2,/button_events)
slabel=widget_text(sbase,ysize=5*scy,/frame)

temp=widget_base(sbase,/row,space=fspace,xpad=fxpad,ypad=fypad)

desc=['"Zoom" {',               $
      '"Zoom in Lambda" SZOOM',     $
      '"Compare Spectra From Cursor Positions" COMP', $
      '"Reset to Original"      SRESET','}']
xpdmenu,desc,temp


desc=['"Write " {',               $
      '"Write to ASCII file" S_ASCII',     $
      '"Save in IDL/XDR saveset"      S_XDR',      $
      '"No write" ABORT','}'] 

xpdmenu,desc,temp

shardb=widget_button(temp,value='Hard Copy',uvalue='SHARD',/no_release)

;-- read file or data?


if (bname eq 'NO FILES') and (not dinput) then begin   
 widget_control,llabel,set_value='PLEASE SELECT A FILE'
 widget_control,dets,sensitive=0
 widget_control,acc,sensitive=0
endif else begin
 if (bname ne 'NO FILES') then begin
  break_file,bname,dsk,direc,name,ext,version
  widget_control,comment,set_value='CURRENT BDA FILE: '+name+ext,/append
 endif
 if dinput then begin
  widget_control,comment,set_value='BDA DATA INPUT ON COMMAND LINE',/append
 endif
 widget_control,set_value='PLEASE SELECT A CHANNEL',llabel
endelse

;-- list available files first time thru

if not dinput then begin
 if cur_dir(0) ne '' then begin
  widget_control,comment,set_value='CURRENT DIRECTORY:'+cur_dir(0),/append
  fnames=loc_file('bda'+fext,path=cur_dir,count=count)
  if count eq 0 then fext='*.*' 
  wflist,fnames,flist,llabel
 endif else begin
  widget_control,llabel,set_value='PLEASE SELECT A DIRECTORY',/append
  widget_control,flist,set_value=direcs,set_uvalue='D_'+direcs
 endelse
endif


;-- current accumulation and channel settings

widget_control,comment,$
 set_value='CURRENT ACCUMULATION TIME: '+string(accum(0),'(f6.2)'),/append
widget_control,comment,$
 set_value='CURRENT CHANNEL:'+string(chan(0),'(i2)'),/append

;-- type directory window

ebase=widget_base(title='  ',/column,xpad=fxpad,ypad=fypad,$
                  space=fspace,/frame)
temp=widget_base(ebase,/column,space=fspace,xpad=fxpad,ypad=fypad)
elabel=widget_label(temp,value='ENTER NEW DIRECTORY NAME')
elabel2=widget_label(temp,value='DEFAULT: '+cur_dir(0))
etext=widget_text(temp,/editable,ysize=2.*scy,xsize=80*scx)
eabort=widget_button(ebase,uvalue='ABORT',value='ABORT',/no_release)

;-- output file name window

wbase=widget_base(title='  ',/column,xpad=fxpad,ypad=fypad,$
                  space=fspace)
temp=widget_base(wbase,/column,space=fspace,xpad=fxpad,ypad=fypad)
wlabel=widget_label(temp,value='ENTER OUTPUT FILE NAME')
wlabel2=widget_label(temp,value='DEFAULT: BDA.DMP')
wtext=widget_text(temp,/editable,ysize=2*scy,xsize=80.*scx)
wabort=widget_button(wbase,uvalue='ABORT',value='ABORT',/no_release)


;-- realize main widget; 
;   initially make lightcurve and spectrum windows insensitive

widget_control,base,/realize
widget_control,lbase,sensitive=1
widget_control,get_value=lval,ldraw
sval=-1
xmanager,'wbda',base,group_leader=group
xmanager

if group eq 0 then begin
 message,'cleaning up...',/continue
 clearplot
endif

;-- pass data out of widget

if (n_elements(index) ne 0) and (n_params() ge 1) then bda_index=index
if (n_elements(data) ne 0) and (n_params() ge 2) then bda_data=data
if (n_elements(bindex) ne 0) then bsc_index=bindex
if (n_elements(bdata) ne 0) then bsc_data=bdata
if n_elements(dp_sync) ne 0 then dp_sync_sav=dp_sync
empty
return & end
    
