pro norp_rd_daily,arg0,arg1,arg2,arg3,freq=freq,avgdir=avgdir

;+
; NAME:
;       NORP_RD_DAILY
;
; PURPOSE:
;       This procedure is for reading and daily averaged NoRP data.
;
; CALLING SEQUENCE:
;       norp_rd_avg,st_day,ed_day,day,fiavg
;       norp_rd_avg,day_in,day,fiavg
;
; INPUTS:
;
; OPTIONAL INPUT KEYWORDS:
; OUTPUTS:
; HISTORY:
;-


if n_elements(avgdir) eq 0 then avgdir=getenv('NORP_DLY')

case n_params() of
  4 : begin                         ; "st_time,ed_time"
      st_time=arg0
      ed_time=arg1
  end
  3 : begin                         ; "date"
      st_time=arg0
      ed_time=anytim(st_time,/ints)
      ed_time.day=ed_time.day+1
  end
  else : begin
  end
endcase

  freq=[1,2,3.75,9.4,17]
  mx=5 
mxf=strtrim(mx,2)

st_daytim=anytim(st_time,/ints)
ed_daytim=anytim(ed_time,/ints)

ndayx=ed_daytim.day-st_daytim.day+1

ex=anytim(transpose([[lonarr(ndayx)],[st_daytim.day+lindgen(ndayx)]]),/ex)
yyyy=reform(ex(6,*))
mm=reform(ex(5,*))
dd=reform(ex(4,*))
yy=yyyy-yyyy/100*100
yymm=string(yy*100+mm)
if (n_elements(yymm) ge 2) then yymm=yymm(uniq(yymm))
yymmdd=$
  string(yymm,format="(i4.4)")
  
if (n_elements(yymmdd) ge 2) then yymmdd=yymmdd(uniq(yymmdd))
files='nbym'+yymmdd
dir=avgdir
infil=file_list(dir,files)
  if (n_elements(infil) eq 1) then begin
  if (infil(0) eq '') then begin
    print,'No files found'
    return
  endif
  endif

mfilx=n_elements(infil)

mfil=0
text0=rd_tfile(infil(mfil),mx+1,11,nocomment='#')
dummy=0
if (text0(0) ne '') then text=text0 else begin
  text=strarr(mx+1,2)
  dummy=2
endelse
if ((size(text))(0) eq 1) then begin
  text=strarr(mx+1,2)
  text(*,1)=text0
  dummy=1
endif


if (mfilx ge 2) then begin
 for mfil=1,mfilx-1 do begin
  text0=rd_tfile(infil(mfil),mx+1,11,nocomment='#')
 if (text0(0) ne '') then begin
  if ((size(text0))(0) eq 1) then text=[[text],[text0]] else $
    text=concat2d(text,text0)
 endif
 endfor
endif

if (dummy ne 0) then text=text(*,dummy:*)


sz=size(text)

date=reform(text(0,*))
date=anytim(date,/ints)

whr=where(((date.day ge st_daytim.day) $
       and (date.day lt ed_daytim.day)) ,cnts)

if (cnts eq 0) then begin
  print,'No observation in this duration'
  goto,Lend
endif

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;  sort & uniq

date=date(whr)
tmp=reform(text(1:*,whr))
whr1=where(tmp eq '-',cnt)
if (cnt ge 1) then tmp(whr1)='-1'
fiavg=float(tmp)

nday0=n_elements(date)

if (nday0 eq 1) then begin
  date=date(0)
  fiavg=fiavg(0)
endif

case n_params() of
  4 : begin                         ; "st_time,ed_time"
      arg2=date
      arg3=fiavg
  end
  3 : begin                         ; "date"
      arg1=date
      arg2=fiavg
  end
  else : begin
  end
endcase
Lend:

return
end
