
;+
; Project: SDAC
;
;  Name:   HKG_DBASE
;
;
; PURPOSE:  extract BATSE SPEC parameters from housekeeping data in batse fdb files.
;
;
; CATEGORY: BATSE
;
;
; CALLING SEQUENCE:  hkg_dbase, flare
;
;
; CALLED BY:
;
;
; CALLS:
;	setup_batse_arrays, read_flare,  read_dd
;
; INPUTS:
;       nflares - extract new housekeeping for this number of flares
;
; OPTIONAL INPUTS:
;	none
;
; OUTPUTS:
;       none explicit, only through commons;
;
; OPTIONAL OUTPUTS:
;	none
;
; COMMON BLOCKS:
;	none
;
; SIDE EFFECTS:
;	The file, perm_data:spec_hsk.txt is opened and updated with the data for each event.
;
; RESTRICTIONS:
;	runs only on SDAC
;
; PROCEDURE:
;	The data is extracted from each fdb file sequentially.
;
; MODIFICATION HISTORY:
;	ras, 18-nov-1995
;       Version 2, RAS, 25-Jul-1997, changed PERM_DATA to SSWDB_BATSE
;-
pro hkg_dbase, nflares

hsk0 = {hsk2, fnam:bytarr(12), flare:0L, specvolt:intarr(8), slld:bytarr(8), basetemp:intarr(8)}
outfile = 'spec_hsk2.dat'
file    = loc_file(path=[curdir(),'SSWDB_BATSE'], outfile, count=nout)

if nout eq 0 then begin
	dir1 = '~/soft/batsedev'

	fdbfile = file_list(chklog('BATSE_FDB'),'*',/cd)
	break_file,fdbfile,disk,dir,fnam,ext
	fnum=long(strsplit(ext,'.fdb_',/tail))
	s=sort(fnum)
	fnum=fnum(s)
	
	nfile = n_elements(fnum)
	hsk = replicate( hsk0, nfile)
	hsk.flare=fnum
	hsk.fnam = [byte(fnam(s)),bytarr(1,nfile)]
	openw,lu,/get,outfile
	writeu,lu,nfile
	writeu,lu,hsk
	free_lun,lu
endif

outfile    = loc_file(path=[curdir(),'SSWDB_BATSE'], outfile, count=nout)
openu,lu,/get,outfile
ahsk  = assoc(lu, hsk0, 4)
total_flares = 0L
point_lun, lu, 0
readu, lu, total_flares
all_hsk = replicate( hsk0, total_flares)
readu, lu, all_hsk
wfill  = where( total( all_hsk.specvolt, 1) eq 0, nfill)

setup_batse_arrays, ntimes=5000

flarestart = wfill(0)
tbl = bytarr(8,8)

help, flarestart
for iflare=flarestart, flarestart+nflares  do begin
	hsk = ahsk(iflare)
	flrnum = hsk.flare
	if flrnum mod 20 eq 0 then print,'FLRNUM -',flrnum
	
	read_flare, flrnum, fld, error=error
	if error then goto, no_flare
	last_time=fld.start_secs+300.
	hmod = 0
	hseq = 0
	mtb  = 0
	file = concat_dir('BATSE_FDB',string((hsk.fnam)(0:10))+'.fdb_'+strtrim(flrnum,2))
	read_dd, times, file=file,dd_type=1, endt=last_time, hkgmod=hmod, hkgseq=hseq, hkgmtb=mtb, $
		 error=error
	if error then begin
		hsk.specvolt = hsk.specvolt*0 -1
		goto, no_flare
	endif
	;Get the analogue SPEC MOD PMT high voltage
	hsk.specvolt = hkg_module( hmod, hseq, 4)
	if total( hsk.specvolt ) eq 0 then hsk.specvolt = hsk.specvolt*0 -1
	hsk.basetemp = hkg_module( hmod, hseq, 23)

;Get the SPEC LLD setting
	offset1= 2*(32-hseq(0))
	tblend = offset1 + 63
	while n_elements(mtb) gt tblend do begin
		tbl(*) = mtb(offset1:tblend)
		hsk.slld = (tbl(6,*))(*)
		offset1 = offset1+64
		tblend  = tblend+64
		if total(hsk.slld) ne 0 then tblend = n_elements(mtb) ;done here
	endwhile		 
no_flare:
	ahsk(iflare) = hsk
endfor

free_lun, lu

end 

