;+
; Modifications:
; 21-Oct-2011, Kim.  Add check for existence of ostart before setting orb_start...
; 01-Sep-2014, Kim.  Add square bracket in histogram call for case when db has only one element
; 27-Sep-2016, Kim.  Modified print statements when no filedb file
; 16-Mar-2020, Kim.  filedb files often have two entries for an orbit.  I was joining them to get real start/end times
;                    of orbits, but didn't take care of case where last entry from previous month's filedb is for
;                    same orbit - need to join those too. (result was I made a separate orbit plot for each part of that orbit)
;-

pro gbm_get_rhessi_orbit_times, time_range, orb_start=orb_start, orb_end=orb_end, count=count


tr = anytim(time_range) + [-86400.d0,86400.d0] ; include previous and next day in case we're at month boundary, want those month files
day_grid = timegrid(tr[0], tr[1], /day, /quiet)
ym = get_uniq(strmid(time2file(day_grid), 0, 6))  ; yyyymm

nfile_tot = 0
for ifile=0,n_elements(ym)-1 do begin
  file = file_search('$HSI_FILEDB_ARCHIVE', 'hsi_filedb_'+ym[ifile]+'.fits', count=nfile)
  if nfile eq 0 then begin
    print, 'Days to plot: ', anytim(day_grid,/vms)
    print, 'No filedb file for year/month ' + ym[ifile] + '.  Can not do orbit plot.'
    goto, next
  endif  
  
  dbi = mrdfits(file[0], 1)
  
  db = nfile_tot eq 0 ? dbi : [db,dbi]
  
  nfile_tot = nfile_tot + nfile
  
next: 
endfor

if nfile_tot gt 0 then begin
  hist = histogram([db.start_hessi_orbit_number], binsize=1., reverse_indices=rind)
  
  for i = 0,n_elements(hist)-1 do begin

    tstart = db[rind[rind[i]]].DATA_START_TIME__ANYTIM_ 
    tend = db[rind[rind[i+1]-1]].DATA_END_TIME__ANYTIM_ 
    if tend gt tr[0] and tstart lt tr[1] then begin
      ostart = append_arr(ostart, tstart)
      oend = append_arr(oend, tend)
    endif
  endfor
  
endif

if nfile_tot eq 0 or ~exist(ostart) then begin
  atr = anytim(tr,/vms,/date)
  message,'No RHESSI orbit times for days ' + atr[0] + ' to ' +atr[1] + ' in file ' + file, /cont
  orb_start = -1
  orb_end = -1
  count = 0
  return
endif

; Now limit orbits times to those within original time_range
tr = anytim(time_range)
q  = where(ostart ge tr[0] and ostart le tr[1], count)
orb_start = ostart[q]
orb_end = oend[q]
;count = n_elements(orb_start)

end