; Main program to read the GRS fits files and print a text file listing the time range and duration of
; each of the FD, DB, and DA files, and print the difference in start times between flare data and day before,
; and flare data and day after (in preparation for G. Share determining whether enough background exists
; and where to start each file in order for them to line up.
; Kim

f = file_search('/data/smm/grs', 'smm_grs_19*.fits')

fbase = file_basename(f)

qfd = where(strpos(f, 'FD.') ne -1, nfd)
fd_all = f[qfd]

td_all = dblarr(2,nfd)
tb_all = dblarr(2,nfd)
ta_all = dblarr(2,nfd)
durd = fltarr(nfd)
durb = fltarr(nfd)
dura = fltarr(nfd)
diff_db = fltarr(nfd)
diff_ad = fltarr(nfd)

out = ''

for i=0,nfd-1 do begin
  out = [out, ' ']
  
  fd = fd_all[i]
  a = mrdfits(fd, 0, h, /silent)
  td = anytim([fxpar(h,'DATE_OBS'), fxpar(h,'DATE_END')])
  td_all[*,i] = td
  durd[i] = td[1] - td[0]
  
  origf = strmid(file_basename(fd, '.fits'), 27, 99)
  
  origdb = str_replace(origf, 'FD', 'DB')
  qb = where(strpos(f, origdb) ne -1, nb)
  if nb gt 1 then stop,' More than one origf DB file.
  if nb eq 1 then begin
    fb = f[qb]
    a = mrdfits(fb, 0, h, /silent)
    tb = anytim([fxpar(h,'DATE_OBS'), fxpar(h,'DATE_END')])
    tb_all[*,i] = tb
    durb[i] = tb[1] - tb[0]
    diff_db[i] = td[0] - tb[0]
    sdiff_db = ', ' + trim(diff_db[i] / 60.)
  endif else sdiff_db = ', 0.'
  
  origda = str_replace(origf, 'FD', 'DA')
  qa = where(strpos(f, origda) ne -1, na)
  if na gt 1 then stop,' More than one origf DA file.
  if na eq 1 then begin
    fa = f[qa]
    a = mrdfits(fa, 0, h, /silent)
    ta = anytim([fxpar(h,'DATE_OBS'), fxpar(h,'DATE_END')])
    ta_all[*,i] = ta
    dura[i] = ta[1] - ta[0]
    diff_ad[i] = ta[0] - td[0]
    sdiff_ad = ', ' + trim(diff_ad[i] / 60.)
  endif else sdiff_ad = ', 0.'
    
  out = [out, origf + ', ' + arr2str(anytim(td, /vms, /trunc), ', ') + ', ' + trim(durd[i]) + sdiff_db + sdiff_ad]
  if nb gt 0 then out = [out, origdb + ', ' + arr2str(anytim(tb, /vms, /trunc), ', ') + ', ' + trim(durb[i])]
  if na gt 0 then out = [out, origda + ', ' + arr2str(anytim(ta, /vms, /trunc), ', ') + ', ' + trim(dura[i])]
endfor

prstr, out, file='USE_file_times2.txt'
save, file='USE_file_times2.sav', td_all, tb_all, ta_all, durd, durb, dura, diff_db, diff_ad

linecolors
utplot,td_all[0,*], diff_ad/60.,psym=2,yra=[80000,86500.]/60., title='Difference between file start times', ytitle='Minutes', /xstyle, charsize=1.4
outplot,td_all[0,*], diff_db/60.,psym=1,col=2
ssw_legend,['After - Flare', 'Flare - Before'], col=[255,2], psym=[2,1], /bottom_leg, box=0,charsize=1.4

end
