## -*-SM-*- Set SM-mode in emacs
entropy	13	# Find the entropy of a vector. Usage: entropy vec [min max]
		# If min and max are provided, take them as the minimum
		# and maximum values of the vector (if omitted, they
		# will be found for you). E.g. calc entropy(image[*,*])
		define min local  define max local  
		if($?2) {
		   if(!$?3) {
		      user abort "$0: if you specify min you must specify max"
		   }
		   define min $2  define max $3
		} else {
		   vecminmax $1 min max
		}
		local set h=histogram($1: do($min, $max))/dimen($1)
		set $0=-sum(h*(h == 0 ? 0 : ln(h)/ln(2)))
		#
hist_equalise 2	# Histogram equalise an image. 
		# Usage: hist_equalise min max
		set ii local  set h local
		set ii=image[*,*]
		set h=histogram(ii:do($1-1,$2+1))
		set h[0] = 0  set h[dimen(h)-1] = 0
		set ii=(ii < $1) ? $1 : (ii > $2 ? $2 : ii)
		set h=cumulate(h)/sum(h)
		set image[*,*] = h[ii-$1]
		#
gamma	3	# Gamma correct an image, for values between $1 and $2;
		# $3 is the value of gamma
		set ii local
		set ii = image[*,*]
		set ii = (ii < $1) ? 0 : (ii > $2 ? 1 : (ii - $1)/($2 - $1))
		set ii = $1 + ($2 - $1)*(1 + $3)*ii/(1 + $3*ii)
		set image[*,*] = ii
		#
M51	02	# Draw an image of M51. 
		# If $1 == 1, gamma correct
		# If $1 == 2, histogram equalise
		# If $?2, also plot contours of linear image
		if(!$?1) { define 1 0 }

		if(!is_vector(save_image)) {
		   image "/u/rhl/disdata/m51blu.fts"
		   set save_image=image[*,*]
		}
		levels do(3000,30000,1000)
		lim 100 512 50 452
		ptype 1 1
		define missing_data 0
		set image[*,*] = save_image

		if($?2) {
		   ctype cyan contour ctype 0
		}
		if($1 == 0) {
		   dither x y 2800 30000 1
		   define 1 "Linear"
		} else { if($1 == 1) {
		   gamma 2800 30000 2
		   dither x y 2800 30000 1
		   define 1 "Gamma corrected"
		} else {
		   hist_equalise 2800 30000
		   dither x y 0 1 1
		   define 1 "Histogram equalised"
		}}
		
		poi x y

		RELOCATE $(int($fx1+0.1*($fx2 - $fx1))) $fy2
		puts M51
		if($?2) {
		   puts Contouring: Linear in raw image
		}
		puts Dithered image: $1
		#

