;+                                                                      
;  Name:
;       EVAL_SHERB
;************************************************************************ 
; 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
;       
;
; 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.
;		det_id - id (0-7) of the detector to select.
;
; 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_unix2 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
;************************************************************************
;-

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

on_error,2
error = 0 ;assume no problems to start

@burst_str
@fdr_msfc_str
@audit_trail_str

her=1
break_file, filename, 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( filename)
	if keyword_set(head) then begin
			data_fits = readfits( filename, head2, /ext, numrow=1) 
		endif else begin
			data_fits = readfits( filename, 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(filename(0), c=cnt)
        if cnt eq 0 then begin
                printx,'Error finding/reading file'
                error = 1
                return
        endif

        printx, 'Reading '+ filename(0)
        openr,/get,lu,filename(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)

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]

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




pro eval_sherb, iflare, directory=directory, display=display

checkvar,display,'NULL'
checkvar,directory,'[]'


common eval_com, shfiles
if n_elements(shfiles) eq 0 then begin
	;setup_batse - routines that need it, call it
	read_seqfile, shfiles, '[richard.spex.new]shfiles.txt'
endif

print, 'Working on flare ',iflare,' in the file [richard.spex.new]shfiles.txt'
dbp = strpos(shfiles(iflare),'DB_')


burst=fix(strmid(shfiles(iflare),dbp+3,5))
flare=burst_flare(burst,/burst)
if flare ne 0 then begin

det_cosines,flare=flare, lad_sort=lad_sort,spec_sort=spec_sort,/sort
read_sherb,shfiles(iflare),lad_sort(0),data,uts, ute, dsel=dsel,burst_time=base

read_flare, flare, fldata
start = fldata.start_secs
endtime= (tjd2ymd(fldata.burst_tjd) + fldata.burst_trig_secs + 600 ) < $
	(fldata.start_secs + fldata.duration )
if fldata.duration gt 4000. then begin
   print, 'Duration is too long for flare ',flare
   return
endif

setutbase, atime(start,/date)
cont_read, tc, yc, flare=flare, error=cerror
discsp_read, td, yd, flare=flare, error=derror

test = intarr(8)
for j=0,7 do test(j)=(where(spec_sort(j) eq dsel))(0)
spec_sort = spec_sort(where(test ge 0))
print, 'These are the selected detectors in sensitivity order', spec_sort

sid = spec_sort(0)
!p.multi = [0,1,2]
!x.margin= [14,4]

lid = lad_sort(0)

set_plot,display
repeatplot:


if not cerror then begin
utplot,  tc, total(yc(1:12,lid,*),1), psym=10,timer=[start,endtime], $
	title='LAD'+strtrim(lid,2)+ ' Flare '+strtrim(flare,2),ymargin=[6,2],ytit='Counts s!u-1!n'
oplot, tc, total( yc(4:12,lid,*),1)
for j=0,n_elements(uts)-1 do oplot, uts(j) +fltarr(2)-getutbase(), $
	[!y.crange(0),!y.crange(0)*.9+.1*!y.crange(1)],linest=3
endif

if not derror then begin
utplot, td, total(yd(0:1,sid,*),1), psym=10,timer=[start,endtime], $
	title='SPEC'+strtrim(sid,2)+ ' Flare '+strtrim(flare,2),ymargin=[6,2],/nolabel, $
	subtitle='Edges at '+arr2str(string((discsp_edges(start, det=sid))(0:1)),delim=' ')+' keV', $
	ytit='Counts s!u-1!n'
oplot, td, yd(1,sid,*)
for j=0,n_elements(uts)-1 do oplot, uts(j) +fltarr(2) - getutbase(), $
	[!y.crange(0),!y.crange(0)*.9+.1*!y.crange(1)],linest=3

endif
if !d.name eq display then begin
	ps,/full
	device, file=concat_dir(directory,'eval_sherb.ps_'+strtrim(flare,2))
	goto, repeatplot
endif else device,/cl
endif
x
end

