;+                                                                      
;************************************************************************ 
; Name:
;	READ_SHERB
; Call:
;	READ_SHERB, filename, det_id, data, start_time, end_time, 
;	dselected=dselected, error=error, file_type=file_type, head=head,
;	fits=fits, burst_str=burst_str, sched=sched, dstrct_in=dstrct_in,
;	burst_time=base_time
;       
; Category:
;	BATSE, SPEX
; Inputs:	
;		Filename - full file descriptor for file in native
;		format.  Corrected data may be used.  If the extension
;		is ".fits", then fits readers are used.
;		Must contain the substrings 'herb' or 'sherb'. 
;		Otherwise, these strings may be input
;		through FILE_TYPE.  String may contain wildcards.
;		Det_id - id (0-7) of the detector to select. Defaults to
;		DSELECTED(0), the id of the brightest LAD
;
; Optional Keywords
;		FILE_TYPE - string containing the substrings which specify
;		the data structure to be read.
;		FITS - if set, then fits reader used.
;		HEAD - only read the first data record to return the 
;			burst selected detector ids, dselected and base_time
; Outputs:	Data - Count data unpacked as whole numbers into 
;			 fltarr( nch, nspec)
;				nch - number of energy bins
;				nspec - number os spectra in memory for
;					dselected
;			 
;		Start_time - time in s from 79/1/1 for each time interval
;			  dblarr( nrep, nspec)
;		End_time - time in s from 79/1/1 for each time interval
;			  dblarr( nrep, nspec)
;
; Optional Outputs:
;		DSELECTED - The ids (0-7) of the four detectors selected
;		BURST_STR - data structure from the first record read.
;               SCHED     - schedule of readouts in data file and data
;			    if det_id is not one of dselected.  To
;			    return all of the spectra for all of the
;			    detetectors, select det_id > 7.
;		DSTRCT_IN - raw packets read in
;		BURST_TIME - burst time in seconds from 79/1/1
; Restrictions:  File name must contain the words Her or Sher and 
;		 the word Cor for corrected data.  Otherwise the
;		 correct data structure must be provided.
;		 File Definition Record
;		 includes NUM_AUDIT_REC tag name specifying the
;		 number of data records.  
;
; ras, 93/10/17
; ras, 21-dec-93, only valid for sherb
; ras, 31-jan-94, used load_struct and conv_vax_unix to make
;	machine independent
; ras, 18-feb-94, head option
; ras, 3-mar-94, corrected time conversion to include no packet offset 
;		 and use burst load time not burst start time
; Version 1	ras, 25-Mar-96 
;************************************************************************
;-

Pro READ_SHERB, filename, det_id, data, start_time, end_time, $
	dselected=dselected, error=error, file_type=file_type, head=head, $
	fits=fits, burst_str=burst_str, sched=sched, dstrct_in=dstrct_in, $
	burst_time=base_time

error = 0 ;assume no problems to start

@burst_str
@fdr_msfc_str
@audit_trail_str

filenamed = (findfile(filename,count=nfile))(0)
if nfile eq 0 then begin
	error=1
	print,"!!!!!!!!!Can't find "+filename
	return
endif

her=1
break_file, filenamed, disk, dir, filnam, ext
if keyword_set(fits) or strpos(strlowcase(ext),'fits') ne -1 then itsfits=1 $
	else itsfits=0

if n_elements(file_type) eq 0 then begin $
	if strpos(strlowcase(filnam),'sherb') ne -1 then her =0
endif else begin
	if strpos(strlowcase(file_type),'sherb') ne -1 then her =0
endelse
;pick the right data structure and repeat cycle

ndet = 1
if her then begin
	nrep = 1  ;number of spectra in one packet
	nch = 128
endif
if not her then begin
	nrep = .5
	nch = 256
endif
	
if itsfits then begin
	head1 = headfits( filenamed)
	if keyword_set(head) then begin
			data_fits = readfits( filenamed, head2, /ext, numrow=1) 
		endif else begin
			data_fits = readfits( filenamed, head2, /ext)
			nspec = n_elements( data_fits(0,*) )
		endelse
	load_struct, data_fits, burst_str, dstrct

endif else begin
;************************************************************************
;HEADER RECORD
;
	test   = bytarr( n_tags(burst_str,/length))

        files = findfile(filenamed(0), c=cnt)
        if cnt eq 0 then begin
                printx,'Error finding/reading file'
                error = 1      
                return
        endif

        printx, 'Reading '+ filenamed(0)
        openr,/get,lu,filenamed(0)

        readu,lu, test  ;READ HEADER RECORD
	load_struct, test, fdr_msfc, fdr, /noieee
;************************************************************************
;AUDIT RECORDS?
;
        if fdr.num_audit_rec ge 1 then begin
                audit = replicate( audit_trail, fdr.num_audit_rec)
                for i=0,fdr.num_audit_rec - 1 do begin ;READ AUDIT TRAIL
                        readu,lu,test
			load_struct, test, audit_trail, audit_trail, /noieee
                        audit(i) = audit_trail
                endfor & npck = audit(i-1).data_recs_num
        endif else npck= fdr.data_recs_num

;************************************************************************

	if keyword_set(head) then npck=1
	dstrct = replicate( burst_str, npck) 
	for i=0, npck-1 do begin
		readu, lu, test
		load_struct, test, burst_str, burst_str, /noieee
		dstrct(i) = burst_str
	endfor
	free_lun,lu
endelse
;************************************************************************




dstrct_in = dstrct ;data file without eliminating any odd packets
dselected = [dstrct(0).dselh1, dstrct(0).dselh2,dstrct(0).dselh3,$
	dstrct(0).dselh4]
base_time = (sc_seconds_ed( dstrct(0).bstlt, /no_offset ))(0)	;ras, 9-mar-94
if keyword_set(head) then return

;Look for any odd packets and eliminate from dstrct
bad_packets:
	ps = dstrct.pakseq 
	wpse = where( ps mod 2 eq 0)
	bad = where( wpse mod 2 ne 1, nbad)
        if nbad ge 1 then begin
		bad = wpse(bad(0)) ;this is a bad packet, an even after an even
		iimask=bytarr(n_elements(dstrct))+1
		iimask(bad) = 0
	        wm = where( iimask eq 1)
		dstrct = dstrct(wm)
		goto, bad_packets
	endif

nbins = fix(n_elements( dstrct ) * nrep) ; should be 192
if not her and nbins ne 192 then $
	printx,string(/print,'Possible error, Number of spectra = ',nbins,' Should be 192')
if her and nbins ne 128 then $
	printx,string(/print,'Possible error, Number of spectra = ',nbins,' Should be 128')


burst_str = dstrct(0)
dstrct = dstrct(0:(nbins/nrep)-1)
data = reform(float( 65535 and dstrct.sci), nch, nbins)

start_time = base_time + rebin( .064*dstrct.time(0), nbins)
end_time = start_time + rebin(.064 *dstrct.time(1),nbins)

;************************************************************************
;select the spectrum and times for det_id
sherb_schedule=[1,2,3,4, 1,1, 2, 1]

if not her then sched = (rebin(sherb_schedule,8,24))(*) else $
		sched = (rebin(sherb_schedule,8,16))(*) 

dselected = [dstrct(0).dselh1, dstrct(0).dselh2,dstrct(0).dselh3,$
	dstrct(0).dselh4]

checkvar, det_id, dselected(0)
wdet = where( det_id eq dselected, num)

if num ne 1 then begin
	printx,string(/print,'Possible Error, selected ',strtrim(det_id,2), $
		', available det_id are:')
	printx,dselected
	error = 1
	return
endif
if not her then pseq = (ps -1) mod 16 /2 else pseq = (ps-1) mod 8

sched_seq = sherb_schedule( pseq ) ;each packet is associated with a schedule id (1-4)

sched_id = where( (wdet(0) + 1) eq sched_seq)
num_selected = n_elements( sched_id )
if num_selected /2 *2 ne num_selected then begin
	printx,string(/print,'Warning odd number of data packets for detector id ', det_id)
	printx,string(/print,'Number of data packets is ',num_selected)
endif else case her of
		0: printx,string(/print,num_selected/2, ' SHERB spectra for detector id ', det_id)
		1: printx,string(/print, num_selected,  ' HERB  spectra for detector id ', det_id)
	   endcase

if not her then sched_id = sched_id(indgen(num_selected/2)*2)/2
	

;stop
data = data( *, sched_id)
start_time = start_time( sched_id)
end_time   = end_time( sched_id)

return
end
