;+
; NAME:
;	xrt_cleanjpg
; PUPROSE:
;	To remove jpeg artifacts due to cosmic ray hits.
; CALLING SEQUENCE:
;	result = xrt_cleanjpg(image[, sens=sens, thresh=thresh])
; INPUTS:
;	image = 2-dimensional image
; OPTIONAL KEYWORD INPUTS:
;   thresh = threshold for bad pixels
;   (thresh = 0.05 is default)
; PROCEDURE:
;	Undesired features are amplified and located by
;	convolution and thresholding. This information is used to generate
;	a map of good (undamaged) pixels. Bad pixels are replaced with a 
;	weighted average of nearby good pixels. In a second pass, the
;	result of this operation is subtracted from the original image.
;	The good pixel map is revised based on the difference image,
;	and pixel replacement is done again.
; SIDE-EFFECTS:
;	image is converted to a float array, if it's not already.
; MODIFICATION HISTORY:
;       2006-Nov-23 --- (JWC) Written. (Based heavily on
;                       <trace_cleanjpg.pro>.)
;-

function xrt_cleanjpg, image_in, thresh=thresh

if keyword_set(thresh) then threshold = thresh $
	else threshold = 0.02 ;a reasonable default
	
epsilon = 0.1

image=float(image_in > 0)+epsilon

; (1) Make map of good pixels.

AAT=1.0/[[16,8,16],[8,4,8],[16,8,16]]
smoothed=convol(image, AAT,/edge_truncate)
enhanced=abs(image - smoothed)/image

enhanced=ck_smooth(enhanced,1)

good_pixmap = float(enhanced LT threshold)

; (2) Replace bad pixels from smoothed image.

result = good_pixmap*image + (NOT good_pixmap)*smoothed

return, result

END
