function orbits_average, image, number, exclude = exclude

;+
; ORBITS_AVERAGE
;	Make an image that is the average of several orbits.
;
; Usage:
;	im=orbits_average(image, number)
;
; Return value:
;	A floating-point array with the image.
;
; Arguments:
;	image	obj	The smei_image object with the central orbit.
;	number	int	The number of orbits before and after to
;			average
;
; Keyword:
;	/exclude	If set, then do not include the current image
;			in the average.
;
; Example:
;	To make an image that is a 5-orbit average centred on a
;	specific image use:
;		img = orbits_average(image, 2)
;
; History:
;	Original: 11/3/08; SJT
;-

level = image -> get_pipe_level()

sz = image -> get_size()
img = fltarr(sz)
nis = fltarr(sz)

if ~keyword_set(exclude) then begin
    im = image -> get_image()
    imw = image -> get_raw_image(/weight)
    locs = where(imw ne 0)
    img[locs] = im[locs]
    nis[locs]++
endif

ih = image -> get_header(/fits)
solon = sxpar(ih, "SUN_ELOP", count = ns)
if ns eq 0 then begin
    solon = round(sxpar(ih, "SUN_ELON"))
    rflag = 0b
endif else rflag = 1b

imn = image -> get_next()
imp = image -> get_prev()

    
for j = 0, number-1 do begin
    if obj_valid(imn) then begin
        ih = imn -> get_header(/fits)
        if rflag then sn = sxpar(ih, "SUN_ELOP") $
        else sn = round(sxpar(ih, "SUN_ELON"))
        if sn eq solon then begin
            im = imn -> get_image()
            imw = imn -> get_raw_image(/weight)
            locs = where(imw ne 0)
            img[locs] += im[locs]
            nis[locs]++
        endif
        imn = imn -> get_next()
    endif
    if obj_valid(imp) then begin
        ih = imp -> get_header(/fits)
        if rflag then sn = sxpar(ih, "SUN_ELOP") $
        else sn = round(sxpar(ih, "SUN_ELON"))
        if sn eq solon then begin
            im = imp -> get_image()
            imw = imp -> get_raw_image(/weight)
            locs = where(imw ne 0)
            img[locs] += im[locs]
            nis[locs]++
        endif
        imn = imp -> get_prev()
    endif
endfor

locs = where(nis ne 0, nvp)
if nvp ne 0 then img[locs] /= nis[locs] $
else begin
    smei_msg, /warn, "No valid points to make baseline"
    img[*] = !values.f_nan
endelse

return, img

end
