pro divyup, index, data, start=start, minsamp=minsamp, deltasec,$
	dout, tout, nout, dvout, loud=loud

;+
; NAME
;	divyup
; PURPOSE
;	To group and average a time sequence of data into equal
;	time interval bins.
; CALLING SEQUENCE
;	divyup,index,data,minsamp=2,deltasec,dout,tout,nout,dvout
;	divyup,index,data,start='1-feb-92 00:00',(24.*60.*60.),dout,tout
;	divyup,seconds,data,60,dout,tout,nout,dvout
; INPUTS
;	index, either index structure OR array of times in seconds.
;	data, one-dimensional array of data to be grouped and averaged.
;	deltasec, group/average interval in sec.
; OPTIONAL KEYWORD INPUT
;	start, start time for grouping in any format.  Default: index(0).
;	minsamp, minimum samples in an interval required for processing,
;		default = 1
;	/loud prints out some diagnostic information
; OUTPUT
;	dout, array of grouped averaged data with intervals of no data
;	      set to -1.
; OPTIONAL OUTPUT
;	tout, time structure matching the center times of the dout 
;		grouping time bins.
;	nout, number of data averaged for each value of dout.
;	dvout, standard deviations of dout.  If there are less than
;		3 samples in an interval dvout is set = -1.
; PROGRAMS CALLED
;	size, int2secarr, where, total
; HISTORY
;	8-Dec-95, LWA  Written for radiance analysis.
;	11-Dec-95, LWA  Clarified header re/ tout.
;	12-Dec-95, LWA  Used 'temporary' one place to save core.
;	11-Jan-96, LWA  Added dvout.
;	12-Jan-96, LWA  Added keyword minsamp.
;	 4-Jul-99, LWA  Added keyword loud.
;	21-Dec-02, LWA  Changed some fixed to longwords.
;-

siz=size(index)

; Get the time array set up.

if ((siz(0) eq 1) and (siz(2) eq 8)) then begin
   if keyword_set(start) then start=start else start=index(0)
   secs=int2secarr(index,start)
endif else begin
   secs=index
endelse
if keyword_set(loud) then help,start,secs,deltasec
if keyword_set(minsamp) then minsamp=minsamp else minsamp=1

; Get the data arrays set up.

nmax=long(max(secs)/deltasec)
dout = fltarr(1+nmax)
dout = dout - 1
nout = intarr(1+nmax)
dvout = fltarr(1+nmax)
dvout = dvout - 1
if keyword_set(loud) then help,nmax,dout,nout,dvout,minsamp

; Group and average the data.

for i=0L,nmax do begin
   ii=where(secs ge i*deltasec and secs lt (i+1)*deltasec,nn)	
   case 1 of
      nn ge minsamp and nn ge 3 :  begin
                    dvout(i) = stdev(data(ii),avg)
                    dout(i) = avg
                    nout(i) = nn
                 end
      nn ge minsamp and nn lt 3 :  begin
                                dout(i) = total(data(ii))/nn
                                nout(i) = nn
                             end
      else : nout(i) = nn
   endcase
endfor

; Prepare the time structure for times at the middle of the 
; grouping time bins.

tstart=timegrid(start,seconds=deltasec/2.,nsamp=1)
tout=timegrid(tstart,seconds=deltasec,nsamp=(1+nmax))

if keyword_set(loud) then begin
   help,tstart,tout
   print,fmt_tim(tstart)
   print,'tout(0) =  ',fmt_tim(tout(0))
endif

end

