;+
; NAME:
;	SMEI_OPERATOR::COMPUTE_MAX
;
;
; PURPOSE:
;	Evaluate the %max operation on a SMEI_OPERATOR
;
;
; CATEGORY:
;	SMEI_OPERATOR
;
;
; CALLING SEQUENCE:
;	sop -> compute_max
;
;
; MODIFICATION HISTORY:
;	Original: 23/10/03; SJT
;	Pass projection information: 13/2/04; SJT
;	Modify for Pipe 2. images: 24/10/07; SJT
;-

pro smei_operator::compute_max


nargs = self -> get_arg_count()

stime = !values.d_infinity
etime = -!values.d_infinity

for jarg = 0, nargs-1 do begin
    arg = self -> get_argument(jarg)
    nimg = arg -> get_count()
    plane = arg -> get_plane()
    for jimg = 0, nimg-1 do begin
        img = arg -> get_image(jimg)
        data = img -> eval(plane = plane)
        if jarg eq 0 and jimg eq 0 then begin
            sz = size(data)
            maxd = make_array(size = sz)
            flg = uintarr(sz[1:2])
            maxd[*] = -!values.f_infinity
            unit = img -> get_unit()
            centre = img -> get_centre()
            scale = img -> get_scale()
            flags = img -> get_flags()
            projection = img -> get_projection()
            ancil = img -> eval(/ancil)
            fhdr = img -> get_header(/fitshead)
            ahdr = img -> get_header(/ancil, /fitshead)
            flhdr = img -> get_header(/flag, /fitshead)
        endif
        mflg = img -> eval(flags)

        if img -> get_planes() ge 2 then $
          wp = img -> get_raw_image(/weight) $
        else $
          wp = finite(data)

        locs = where(wp ne 0, nl)
        if nl ne 0 then begin
            l2 = where((data[locs] gt maxd[locs] and $
                       mflg[locs] eq flg[locs]) or $
                       mflg[locs] lt flg[locs], ng)
            if ng ne 0 then begin
                maxd[locs[l2]] = data[locs[l2]]
                flg[locs[l2]] = mflg[locs[l2]]
            endif
        endif

        stime = stime < img -> get_time(/start)
        etime = etime > img -> get_time(/stop)
    endfor
endfor

im = self.sequence -> add_image(image_data = maxd, $
                                start = stime, $
                                stop = etime, $
                                unit = unit, $
                                centre = centre, $
                                scale = scale, $
                                flags = flags, $
                                projection = projection, $
                                /last, $
                                ancil_data = ancil, $
                                flag_data = flg, $
                                fitshead = fhdr, $
                                ancilhead = ahdr, $
                                flaghead = flhdr)

end
