;+
; PROJECT:
;	FERMI
; NAME:
;	GBM_QLOOK_SINGLE
;
; PURPOSE:
;	Reads the CSPEC files for the daily data and organizes it into rates for
;	the front and Rear facing GBM detectors as well as returning the composite
;	rates in the Synrate array used for flare finding.
;
; CATEGORY:
;	QUICKLOOK AND CATALOG GENERATION FOR FERMI GBM
;
; CALLING SEQUENCE:
;	gbm_qlook_single, daily_files,  data, synrate, $
;	 erange=erange, threshold=threshold, testscale=testscale, smoothbin=smoothbin
;
; ; INPUTS:
;       Daily_files -directory with daily cspec and poshist files for gbm or the
;		filenames themselves
;
; OPTIONAL INPUTS:
;  	ERANGE=ERANGE - energy ranges used for CSPEC rates, 6 values, default is [6,12,25,50,100,300]
;	THRESHOLD=THRESHOLD sets the value of synrate used to define flares, should not
;		be changed withouth examining SYNRATE
;	TESTSCALE=TESTSCALE constant used to normalize Synrate,  normally 1e6;
;	if this is changed then
;		the value of THRESHOLD must be similarly changed.  If TESTSCALE is increased by
;		X, then THRESHOLD will be reduced by X (factors and divisors)
;	SMOOTHBIN=SMOOTHBIN Passed to gbm_qlook_single - Normally set at 15 bins (60 seconds)
;		used to smooth fluctuations to help define the start and stop boundaries
;
; OUTPUTS:
;       Data - a structure containing the basic rate and ephemeris info
;			** Structure <75526d8>, 9 tags, length=336, data length=333, refs=1:
;		;   UTM             STRUCT    -> ANYTIM2INTS_FULL Array[1] ;Time
;		;   DUT             DOUBLE           4.0960001 ;diff in sec between intervals
;		;   DF              FLOAT     Array[5, 6] ; five energy ranges of rates, 6 Sunward detectors
;		;					Nominal energy ranges: [6,12,25,50,100,300] keV, Counts/s
;		;   DR              FLOAT     Array[5, 6] ;five energy ranges of rates, 6 A-Sunward detectors
;		;   RATE            FLOAT     Array[5]	  ; df-dr, totaled over detectors
;		;   HI              FLOAT      1.87337e-009 ;Higher energy GOES at UTM
;		;   LO              FLOAT      3.02004e-007 ;Lower energy GOES at UTM
;		;   DN              BYTE         1          ;Daynight flag, day is 1
;		;   DETCOSINES      FLOAT     Array[12]     ;detector cosines to Sun at UTM
;
;		Synrate - a synthetic rate built from data.rate[0:1], data.hi, and data.dn
;
; CALLS:
;	FERMI_DN - uses ephemeris to determine local day and night on FERMI
;	GBM_DET_COSINES - uses poshist quaternions to determine FERMI and nai orientation
;		to the Sun
;	GBM_GET_FILETYPE - pulls file descriptors for filetype from daily_files whether
;		its an array of file descriptors or a directory
; COMMON BLOCKS:
;	none
;
; SIDE EFFECTS:
;	none
;
; RESTRICTIONS:
;	none
;
; PROCEDURE:
;	none
;
; MODIFICATION HISTORY:
;	18-MAR-2010, richard.schwartz@nasa.gov
;	14-May-2010, richard.schwartz@nasa.gov  we reorganize df, dr, and rate for the 6 most sunward
;		and antisunward detectors which are not always 0-5, 6-11
;	10-jun-2014, richard.schwartz@nasa.gov, kim.tolbertl@nasa.gov -
;	   Added ENHANCE_SYNRATE_TIME table. For times in table, we know there's a small flare that wouldn't normally be
;	   found, so add higher energy channels into the synrate.  The new synrate will be used for the whole time interval
;	   we're working on, so there may be more flares added during this period even outside the enhance_synrate_time time.
;	   If we find more flare like this, we will edit this routine to add more times to ENHANCE_SYNRATE_TIME array.
;
;-



pro gbm_qlook_single, daily_files,  data, synrate, $
	 erange=erange, threshold=threshold, testscale=testscale, smoothbin=smoothbin, gtitle=gtitle, status=status
	 
gbm_compressed_rate, daily_files, utm, dut, r12, hi, lo, gtitle, erange=erange, status=status
if ~status then return

status = 0
poshistfile = gbm_get_filetype(daily_files,'poshist', count)
if count eq 0 then return

;help, poshistfile
default, threshold, 1e-6
default, testscale, 1e6
default, smoothbin, 15

; enhance_synrate_time should be a 2xn array with start/end times for each special interval
enhance_synrate_time = anytim(['19-apr-2014 07:21:00', '19-apr-2014 07:24:00'])
n_enhance = n_elements(enhance_synrate_time[0,*])

scale=testscale

data = replicate({utm: utm[0], dut: dut[0], df: r12[*,0:5,0], $
	dr: r12[*,6:11,0], rate: r12[*,0,0], hi:hi[0], lo:lo[0], dn:0b, detcosines:fltarr(12)}, n_elements(utm))
dn = fermi_dn( poshistfile[0], ut=utm)

; special will be >0 if time is in enhance_synrate_time list
special = 0
utm_sec = anytim(utm)
for ii = 0,n_enhance-1 do begin
  new_ind = where (utm_sec gt enhance_synrate_time[0,ii] and utm_sec lt enhance_synrate_time[1,ii], count)  
  if count gt 0 then begin
    enh_ind = exist(enh_ind) ? [enh_ind, new_ind] : new_ind
    special = 1
  endif
;  special += in_range(anytim( enhance_synrate_time[ii] ), minmax( anytim( utm ) ))
endfor

detcosines = gbm_det_cosines(poshistfile[0], utc=utc_dc)
data.detcosines = detcosines[*,value_locate(utc_dc, anytim(utm) )>0]
;Here we reorganize df, dr, and rate for the 6 most sunward
;and antisunward detectors which are not always 0-5, 6-11, ras, 14-may-2010
sorted=fix(data.detcosines)
ndata=n_elements(data)
for i=0L,ndata-1 do sorted[0,i]=sort(-data[i].detcosines)

for i=0L,ndata-1 do r12[*,*,i]=r12[*,sorted[*,i],i]
df  = r12[*,0:5,*]
dr  = r12[*,6:11,*]
rate = total(df-dr,2)>1

data.utm = utm
data.dut = dut
data.df  = df
data.dr  = dr
data.rate = rate
data.hi = hi
data.lo = lo
data.dn = dn
utms = anytim( data.utm)
utbase = anytim( utms[0], /date, /vms)
utms = utms - anytim(utbase)
synrate = (data.rate[0]*data.rate[1] * data.hi * data.dn)/scale

; if special not 0, then this is a small flare that otherwise wouldn't be detected
if special gt 0 then begin
  scale2 = ( data.rate[3] * data.rate[2]-smooth(data.rate[2] * data.rate[3], smoothbin, /edge_trun)) /1e4
  synrate[enh_ind] = synrate[enh_ind] * scale2[enh_ind]
endif
	
loscale = data.lo/1e-6
synrate = [[synrate],[smooth(synrate,smoothbin)], [data.dn*loscale],[loscale]]

status = 1

;if arg_present(plotman) then begin
;
;	utplot_obj = obj_new('utplot', utms, utbase=utbase, synrate>threshold,/ylog)
;	utplot_obj->plotman, plotman=plotman, desc=anytim(utms[0]+utbase,/vms)
;	endif
end