pro Mk_stdim, filename, stexp=stexp, save=save, $
              centre_pick=centre_pick

;+
; MK_STDIM
;	Form a "Standard" mask image from the current image set
;
; Usage:
;	mk_stdim[, stdim, stexp=stexp, filename=filename]
;
; Arguments:
;	filename string	input	The name to give to the image. If
;				unset, then use "stdim.fts"
;
; Keywords:
;	stexp	float	output	The integrated exposures of each
;				pixel.
;	save	??	input	If set, then save the generated image
;				to disk
;
; Effects:
;	A "standard" average image is generated and added to the end
;	of the list of loaded images. Most of its header information
;	is derived from the first image of the set. N.B. The image is
;	NOT saved to disk, use one of the SAVE options in DISPLAY to
;	do this.
;
; WARNING:
;	It is the responsibility of the user to ensure that the image
;	set being used is homogeneous.
;
; History:
;	Original: Mar 96, SJT
;	Reduce number of arrays to try to speed it up: 4/4/96; SJT
;	Use NO_COPY handle extraction instead of GHANDLE for the same
;	reason: 22/4/96; SJT
;-

@wload.com
@chandle.com

nim = n_elements(sel_array)     ; Only use the selected images.

for j = 0, nim-1 do begin
                                ;   ghandle, sel_array(j)
    handle_value, h_array(sel_array(j)), img, /no_copy
    handle_value, h_head(sel_array(j)), f_hdr, /no_copy
    nom = string_name(sel_array(j))
;;    handle_value, h_name(sel_array(j)), nom, /no_copy
    
    s = size(img)
    if (j eq 0) then begin
        
	stdim = fltarr(s(1), s(2))
        stexp = fltarr(s(1), s(2))
        hdr = f_hdr
        cgrf = strtrim(sxpar(f_hdr, 'DETECTOR'), 2)
        cgrp = strtrim(sxpar(f_hdr, 'READPORT'), 2)
        ddc = offset_bias(cgrf, cgrp)
        if (((mi = min(img))) ge ddc) then begin
            ans = ''
            print, "* * W A R N I N G * *"
            print, "Min(image) [", mi, "] < offset bias [", ddc, "]"
Dcr:            
            read, "Has the bias already been subtracted? (y|n) " + $
              ":_", ans
            case strupcase(ans) of
                'Y':
                'N': ddc = 0
                Else: goto, dcr
            endcase
        endif
    endif                       ; End of first-pass only stuff

    n_exp = sxpar(f_hdr, 'EXPTIME')
    n_csum = sxpar(f_hdr, 'SUMROW') * sxpar(f_hdr, 'SUMCOL') > 1
    n_lebsum = sxpar(f_hdr, 'LEBYSUM')*sxpar(f_hdr, 'LEBXSUM') > 1
    print, j, nom, n_exp, n_csum, n_lebsum, format = $
      "(//i4,2x,a,2x,f8.3,2x,2i3)"

    mask = 0                    ; Just a memory saving trick
    mask = mask_out(img, f_hdr)
    
    mask = rebin(temporary(mask), s(1), s(2), /samp)
    
    mask = mask and sigma_mask(img, 15, n_sigma=4., /all,  outbox = 3)
    
    
    if (max(img)*n_exp le 16383*n_lebsum) then exposure = float(mask)  $
    else exposure = mask  and n_exp
    
    stexp = stexp + exposure
    
    stdim = stdim + (mask * img/float(n_csum))
    
    handle_value, h_array(sel_array(j)), img, /no_copy, /set
    handle_value, h_head(sel_array(j)), f_hdr, /set
;;    handle_value, h_name(sel_array(j)), nom, /no_copy, /set
    
endfor

locs = where(stexp eq 0., nzero)
if (nzero ne 0) then begin
    print, "**** ++++ Generated image still has " + $
	string(nzero,format="(I0)") + " holes."
    stexp(locs) = 1.
endif

stdim = stdim/stexp

;  Here comes the risky bit

if (not keyword_set(filename)) then filename='stdim.fts'

mk_stdim_hdr, hdr, f_hdr, stdim, filename, nim

head = temporary(hdr)

name = filename
image = float(temporary(stdim))

;     Need to have a centre & radius for the occulting disk to allow
;	 masking options 

if (keyword_set(centre_pick)) then scan4limb, image, name, head, h_head, $
  index, 1, min = min(image, max = mx), max = mx $
else begin
    cntr = OCCLTR_CNTR(head)
    suncol = cntr(0)-(sxpar(head, 'R1COL')-20)
    sunrow = cntr(1)- sxpar(head, 'R1ROW')
    sxaddpar, head, 'CENTER_X', suncol
    sxaddpar, head, 'CENTER_Y', sunrow
endelse

chandle
sel_img = [sel_img, 0]

if (keyword_set(save)) then begin
            
    wdir = GETENV('WORK')+GETENV('USER')+!Delimiter+ 'fits'+!Delimiter
    IF chk_dir(wdir) EQ 0 THEN BEGIN
        cmd = 'mkdirhier '
        spawn, cmd + " " + wdir
    ENDIF
    wdir = wdir + !Delimiter
    writefits, wdir + name, image, head
endif

end
