#!/bin/bash
#
# Developed by Fred Weinhaus 9/11/2011 .......... 7/14/2015
#
# ------------------------------------------------------------------------------
# 
# Licensing:
# 
# Copyright © Fred Weinhaus
# 
# My scripts are available free of charge for non-commercial use, ONLY.
# 
# For use of my scripts in commercial (for-profit) environments or 
# non-free applications, please contact me (Fred Weinhaus) for 
# licensing arrangements. My email address is fmw at alink dot net.
# 
# If you: 1) redistribute, 2) incorporate any of these scripts into other 
# free applications or 3) reprogram them in another scripting language, 
# then you must contact me for permission, especially if the result might 
# be used in a commercial or for-profit environment.
# 
# My scripts are also subject, in a subordinate manner, to the ImageMagick 
# license, which can be found at: http://www.imagemagick.org/script/license.php
# 
# ------------------------------------------------------------------------------
# 
####
#
# USAGE: tonemap4 [-m method] [-k kind] [-t threshold] [-b bri] [-c con] 
# [-s sat] [-e edge] [-r ramp] [-b blur] [-s shadows] [-h highlights] 
# [-w window] [-g gvals] [-l log] [-A] [-C] infile outfile
# 
# USAGE: tonemap4 [-help]
#
# OPTIONS:
# 
# -m     method         method of dual gamma processing; ramp (r) or 
#                       adaptive (a); default=ramp
# -k     kind      	    kind of extra processing; none (n), equalize (e), 
#                       gaussian (g), space (s), or retinex (r); 
#                       default=retinex
# -t     thresh         threshold for separating shadow and highlight
#                       regions; integers between 0 and 100; default is 
#                       the mean graylevel of the brightness channel
# -b     bri            brightness enhancement percent; integer between 
#                       -100 and 100; default=0
# -c     con            contrast enhancement percent; integer between 
#                       -100 and 100; default=0
# -s     sat            saturation enhancement factor; float>0; 
#                       default=0.6
# -e     edge           edge enhancement amount; float>=0; 
#                       default=0
# -r     ramp           ramp amount in pixels for method=ramp; integer>=0;
#                       default=20
# -B     blur       	blur amount for method=adaptive; float>0; 
#                       default=3
# -S     shadows      	desired shadow brightness in range 0 to 100 used 
#                       for autogamma processing; also can be used to 
#                       increase/decrease brightness in shadows;
#                       default=50
# -H     highlights     desired highlight brightness in range 0 to 100 used 
#                       for autogamma processing; also can be used to 
#                       increase/decrease brightness in highlights; 
#                       default=70
# -w     window         window size as percent of image dimensions for 
#                       kind=space; float>0; default=12.5
# -g     gvals          gaussian redistribution mean,lo,hi values for 
#                       kind=gaussian; integers>0; default=60,60,60
# -l     log     	    amount of scaling for log preprocessing expressed as 
#                       exponent for power of 10; float>=0; default=0 (none)
# -A                    preprocessing to apply autolevel stretch; default is
#                       not to apply autolevel stretch
# -C     colorproc      preprocessing to change colorspace to: RGB, sRGB;
#                       default is no change
# 
#
###
#
# NAME: TONEMAP4 
# 
# PURPOSE: Enhances the shadows and/or highlight regions in an image using a 
# dual gamma function plus an extra processing function.
# 
# DESCRIPTION: TONEMAP4 the shadows and/or highlight regions in an image 
# using a dual gamma function plus an extra processing function, which can 
# be either: none, equalize (histogram equalization), gaussian (histogram 
# redistribution), retinex (multiscale method) or space (spatially adaptive 
# contrast enhancement). The image is first converted to HSB colorspace. 
# Then the channels are separated. The brightness channel is then 
# thresholded to separate the shadow and highlight regions. The thresholded 
# image is used as a mask against the brightness image to find the mean 
# values in the two regions. These mean values are then used to compute 
# appropriate gamma values, which are then applied separately to the 
# brightness channel. These two modified brightness images are merged 
# either by a ramped blending or by an adaptive blending based upon 
# the local variances in the two modified brightness images. The resulting 
# megerd brightness image is then combined with the hue and (optionally 
# enhanced) saturation channels. Finally the resulting image is converted 
# back to RGB.
# 
# 
# OPTIONS: 
# 
# -m method ... METHOD of dual gamma processing; ramp (r) or adaptive (a). 
# The default=ramp.
# 
# -k kind ... KIND of extra processing. The choices are: none (n), equalize (e), 
# gaussian (g), retinex (r) or space (s). Equalize is a histogram equalization. 
# Gaussian is gaussian histogram redistribution. Retinex is multiscale 
# enhancement. Space is a spatially adaptive contrast enhancement. Generally, 
# retinex and none work the best, but for certain images, one or more of the 
# other approaches may also work as well or better. The default=retinex.
# 
# -t threshold ... THRESHOLD for separating shadow and highlight regions. 
# Values are integers between 0 and 100. The default is the mean graylevel 
# of the brightness channel.
# 
# -b bri ... BRIGHTNESS enhancement percent. Values are integers between 
# -100 and 100. The default=0
# 
# -c con ... CONTRAST enhancement percent. Values are integers between 
# -100 and 100. The default=0
# 
# -s sat ... SATURATION enhancement factor. Values are floats>0. A value 
# of sat=1 is no change. The default=0.6
# 
# -e edge ... EDGE enhancement amount. Values are floats>=0. The default=0
#
# -r ramp ... RAMP amount in pixels for method=ramp. Values are integers>=0;
# The default=0
# 
# -B blur ... BLUR amount for method=adaptive. Values are floats>0. The 
# default=0
# 
# -S shadows ... desired SHADOW brightness in the range 0 to 100, which is
# used for autogamma processing. It can also can be used to increase or 
# decrease brightness in shadows, though generally it does not need to 
# be adjusted. The default=50
# 
# -H highlights ... desired HIGHLIGHT brightness in the range 0 to 100,  
# which is used for autogamma processing. It can also can be used to  
# increase or decrease brightness in shadows, though generally it does 
# not need to be adjusted. The default=50
#
# -w window ... WINDOW is the moving window percentage of image size for 
# kind=space. Values are floats>0 and are nominally between 5 and 20. 
# Larger or smaller values can mitigate ringing. Larger values narrow 
# ringing and smaller values broaden or diffues ringing. The default=12.5
#
# -g gvals ... GVALS are the gaussian redistribution mean,lo,hi values 
# for kind=gaussian. Values are comma separated integers>0. The 
# default=60,60,60.
# 
# -l log ... LOG is the amount of scaling for log preprocessing expressed 
# as exponent for power of 10. Generally this will only be needed for HDR 
# images with very high dynamic range that require log processing in IM 
# HDRI mode. Values are floats>=0. The default=0 (no log processing).
# 
# -A ... Optional AUTOLEVEL preprocessing step. Generally this will only be 
# needed for HDR images with very high dynamic range that require log processing 
# in IM HDRI mode.
#
# -C colorproc ... COLORPROC is an optional preprocessing step to convert 
# the input image from some other colorspace to RGB or sRGB. This 
# seems to be needed for HDR Radiance images in XYZ colorspace (.hdr suffix) 
# prior to a bug fix in .hdr images in IM 6.7.2.0. The choices are: RGB 
# and sRGB. The default is no change. Note that somewhere between IM 6.7.5.5 
# and IM 6.7.6.7, colorspace RGB and sRGB were swapped to correct their meaning.
#
# REQUIREMENTS: redist, space and retinex scripts. Also IM 6.5.9-0 to support 
# the -brightness-contrast function.
# 
# NOTE: kind=space will be slow due to the use of -fx when not in HDRI mode. 
# 
# Note: For IM 6.7.5.5 or higher, in order to reproduce some of the examples 
# below, one may have to add, remove or change -C arguments, due to the 
# swap of the meaning of -colorspace RGB and -colorspace sRGB. Also if -c is
# not none for .hdr images, then some parameter changes may be needed. For more 
# details, see 
# http://www.fmwconcepts.com/imagemagick/tonemap4/tonemap_tests.txt
# 
# Reference for adaptive method: 
# http://www.ieice.org/proceedings/ITC-CSCC2008/pdf/p457_A4-3.pdf
#
# CAVEAT: No guarantee that this script will work on all platforms, 
# nor that trapping of inconsistent parameters is complete and 
# foolproof. Use At Your Own Risk. 
# 
######
#

# set default values
method="ramp"		# ramp or adaptive
kind="retinex"		# none, equalize, retinex, space, gaussian
thresh=""			# threshold percent; default=mean
bri=0				# brightness; -100 to 100
con=0				# contrast; -100 to 100
sat=0.6				# saturation; float>0
edge=0				# edge sharpening; float>=0
blur=3				# blur factor for method=adaptive; float>=0
ramp=20				# ramp amount for method=ramp; integer>=0
shadows=50			# shadow brightness (desired value for autogamma); 0 to 100
highlights=70		# highlight brightness (desired value for autogamma); 0 to 100
autolevel="no"		# autolevel preprocessing
log=0				# log scaling (preprocessing) value as power of 10; integer>=0
window=12.5			# space window amount; float>0
gvals="60,60,60"	# gaussian redist values; comma separated integers
colorproc="none"	# colorspace preprocessing; none; RGB, sRGB

# set directory for temporary files
dir="."    # suggestions are dir="." or dir="/tmp"

# set up functions to report Usage and Usage with Description
PROGNAME=`type $0 | awk '{print $3}'`  # search for executable on path
PROGDIR=`dirname $PROGNAME`            # extract directory of program
PROGNAME=`basename $PROGNAME`          # base name of program
usage1() 
	{
	echo >&2 ""
	echo >&2 "$PROGNAME:" "$@"
	sed >&2 -e '1,/^####/d;  /^###/g;  /^#/!q;  s/^#//;  s/^ //;  4,$p' "$PROGDIR/$PROGNAME"
	}
usage2() 
	{
	echo >&2 ""
	echo >&2 "$PROGNAME:" "$@"
	sed >&2 -e '1,/^####/d;  /^######/g;  /^#/!q;  s/^#*//;  s/^ //;  4,$p' "$PROGDIR/$PROGNAME"
	}


# function to report error messages
errMsg()
	{
	echo ""
	echo $1
	echo ""
	usage1
	exit 1
	}


# function to test for minus at start of value of second part of option 1 or 2
checkMinus()
	{
	test=`echo "$1" | grep -c '^-.*$'`   # returns 1 if match; 0 otherwise
    [ $test -eq 1 ] && errMsg "$errorMsg"
	}

# test for correct number of arguments and get values
if [ $# -eq 0 ]
	then
	# help information
   echo ""
   usage2
   exit 0
elif [ $# -gt 32 ]
	then
	errMsg "--- TOO MANY ARGUMENTS WERE PROVIDED ---"
else
	while [ $# -gt 0 ]
		do
			# get parameter values
			case "$1" in
		     -help)    # help information
					   echo ""
					   usage2
					   exit 0
					   ;;
				-m)    # get  method
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID METHOD SPECIFICATION ---"
					   checkMinus "$1"
					   method=`echo "$1" | tr '[A-Z]' '[a-z]'`
					   case "$method" in 
					   		ramp|r) method=ramp;;
					   		adaptive|a) method=adaptive;;
					   		*) errMsg "--- METHOD=$method IS AN INVALID VALUE ---" 
					   	esac
					   ;;
				-k)    # get  kind
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID KIND SPECIFICATION ---"
					   checkMinus "$1"
					   kind=`echo "$1" | tr '[A-Z]' '[a-z]'`
					   case "$kind" in 
					   		none|n) kind=none;;
					   		equalize|e) kind=equalize;;
					   		gaussian|g) kind=gaussian;;
					   		retinex|r) kind=retinex;;
					   		space|s) kind=space;;
					   		*) errMsg "--- KIND=$kind IS AN INVALID VALUE ---" 
					   	esac
					   ;;
				-t)    # get thresh
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID THRESH SPECIFICATION ---"
					   checkMinus "$1"
					   thresh=`expr "$1" : '\([0-9]*\)'`
					   [ "$thresh" = "" ] && errMsg "--- THRESH=$thresh MUST BE AN INTEGER ---"
					   test1=`echo "$thresh < 0" | bc`
					   test2=`echo "$thresh > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- THRESH=$thresh MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-b)    # get bri
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BRI SPECIFICATION ---"
					   #checkMinus "$1"
					   bri=`expr "$1" : '\([0-9-]*\)'`
					   [ "$bri" = "" ] && errMsg "--- BRI=$bri MUST BE AN INTEGER ---"
					   test1=`echo "$bri < -100" | bc`
					   test2=`echo "$bri > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- BRI=$bri MUST BE AN INTEGER BETWEEN -100 AND 100 ---"
					   ;;
				-c)    # get con
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID CON SPECIFICATION ---"
					   #checkMinus "$1"
					   con=`expr "$1" : '\([0-9-]*\)'`
					   [ "$con" = "" ] && errMsg "--- CON=$con MUST BE AN INTEGER ---"
					   test1=`echo "$con < -100" | bc`
					   test2=`echo "$con > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- CON=$con MUST BE AN INTEGER BETWEEN -100 AND 100 ---"
					   ;;
				-s)    # get sat
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID SAT SPECIFICATION ---"
					   checkMinus "$1"
					   sat=`expr "$1" : '\([.0-9]*\)'`
					   [ "$sat" = "" ] && errMsg "--- SAT=$sat MUST BE A NON-NEGATIVE FLOAT (with no sign) ---"
					   test1=`echo "$sat <= 0" | bc`
					   [ $test1 -eq 1 ] && errMsg "--- SAT=$sat MUST BE A POSITIVE FLOAT ---"
					   ;;
				-e)    # get edge
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID EDGE SPECIFICATION ---"
					   checkMinus "$1"
					   edge=`expr "$1" : '\([.0-9]*\)'`
					   [ "$edge" = "" ] && errMsg "--- EDGE=$edge MUST BE A NON-NEGATIVE FLOAT ---"
 					   ;;
				-r)    # get ramp
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID RAMP SPECIFICATION ---"
					   checkMinus "$1"
					   ramp=`expr "$1" : '\([0-9]*\)'`
					   [ "$ramp" = "" ] && errMsg "--- RAMP=$ramp MUST BE A NON-NEGATIVE INTEGER ---"
 					   ;;
				-B)    # get blur
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BLUR SPECIFICATION ---"
					   checkMinus "$1"
					   blur=`expr "$1" : '\([.0-9]*\)'`
					   [ "$blur" = "" ] && errMsg "--- BLUR=$blur MUST BE A NON-NEGATIVE FLOAT ---"
 					   ;;
				-S)    # get shadows
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID SHADOWS SPECIFICATION ---"
					   checkMinus "$1"
					   shadows=`expr "$1" : '\([0-9]*\)'`
					   [ "$shadows" = "" ] && errMsg "--- SHADOWS=$shadows MUST BE AN INTEGER ---"
					   test1=`echo "$shadows < 0" | bc`
					   test2=`echo "$shadows > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- SHADOWS=$shadows MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-H)    # get highlights
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID HIGHLIGHTS SPECIFICATION ---"
					   checkMinus "$1"
					   highlights=`expr "$1" : '\([0-9]*\)'`
					   [ "$highlights" = "" ] && errMsg "--- HIGHLIGHTS=$highlights MUST BE AN INTEGER ---"
					   test1=`echo "$highlights < 0" | bc`
					   test2=`echo "$highlights > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- HIGHLIGHTS=$highlights MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-w)    # get window
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID WINDOW SPECIFICATION ---"
					   checkMinus "$1"
					   window=`expr "$1" : '\([.0-9]*\)'`
					   [ "$window" = "" ] && errMsg "--- WINDOW=$window MUST BE A NON-NEGATIVE FLOAT (with no sign) ---"
					   test1=`echo "$window <= 0" | bc`
					   [ $test1 -eq 1 ] && errMsg "--- WINDOW=$window MUST BE A POSITIVE FLOAT ---"
					   ;;
				-g)    # get gvals
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID GVALS SPECIFICATION ---"
					   checkMinus "$1"
					   gvals=`expr "$1" : '\([0-9]*,[0-9]*,[0-9]*\)'`
					   [ "$gvals" = "" ] && errMsg "--- GVALS=$gvals MUST BE THREE COMMA SEPARATED NON-NEGATIVE INTEGERS (with no sign) ---"
					   ;;
				-l)    # get log
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID LOG SPECIFICATION ---"
					   checkMinus "$1"
					   log=`expr "$1" : '\(.[0-9]*\)'`
					   [ "$log" = "" ] && errMsg "--- LOG=$log MUST BE A NON-NEGATIVE FLOAT ---"
 					   ;;
				-A)    # get  aproc
					   alevel="yes"
					   ;;
				-C)    # get  colorproc
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID COLORPROC SPECIFICATION ---"
					   checkMinus "$1"
					   colorproc=`echo "$1" | tr '[A-Z]' '[a-z]'`
					   case "$colorproc" in 
					   		none) colorproc=none;;
					   		rgb) colorproc=RGB;;
					   		srgb) colorproc=sRGB;;
					   		*) errMsg "--- COLORPROC=$colorproc IS AN INVALID VALUE ---" 
					   	esac
					   ;;
			 	-)    # STDIN and end of arguments
					   break
					   ;;
				-*)    # any other - argument
					   errMsg "--- UNKNOWN OPTION ---"
					   ;;
		     	 *)    # end of arguments
					   break
					   ;;
			esac
			shift   # next option
	done
	#
	# get infile and outfile
	infile="$1"
	outfile="$2"
fi

# test that infile provided
[ "$infile" = "" ] && errMsg "NO INPUT FILE SPECIFIED"

# test that outfile provided
[ "$outfile" = "" ] && errMsg "NO OUTPUT FILE SPECIFIED"

# setup temp files
tmpA1="$dir/tonemap4_1_$$.mpc"
tmpB1="$dir/tonemap4_1_$$.cache"
tmpA2="$dir/tonemap4_2_$$.mpc"
tmpB2="$dir/tonemap4_2_$$.cache"
tmpA3="$dir/tonemap4_3_$$.mpc"
tmpB3="$dir/tonemap4_3_$$.cache"
tmpA4="$dir/tonemap4_4_$$.mpc"
tmpB4="$dir/tonemap4_4_$$.cache"
tmpM1="$dir/tonemap4_MS_$$.mpc"
tmpM2="$dir/tonemap4_MS_$$.cache"
tmpM3="$dir/tonemap4_MH_$$.mpc"
tmpM4="$dir/tonemap4_MH_$$.cache"
tmpV1="$dir/tonemap4_VS_$$.mpc"
tmpV2="$dir/tonemap4_VS_$$.cache"
tmpV3="$dir/tonemap4_VH_$$.mpc"
tmpV4="$dir/tonemap4_VH_$$.cache"
trap "rm -f $tmpA1 $tmpB1 $tmpA2 $tmpB2 $tmpA3 $tmpB3 $tmpA4 $tmpB4 $tmpM1 $tmpM2 $tmpM3 $tmpM4 $tmpV1 $tmpV2 $tmpV3 $tmpV4;" 0
trap "rm -f $tmpA1 $tmpB1 $tmpA2 $tmpB2 $tmpA3 $tmpB3 $tmpA4 $tmpB4 $tmpM1 $tmpM2 $tmpM3 $tmpM4 $tmpV1 $tmpV2 $tmpV3 $tmpV4; exit 1" 1 2 3 15
#trap "rm -f $tmpA1 $tmpB1 $tmpA2 $tmpB2 $tmpA3 $tmpB3 $tmpA4 $tmpB4 $tmpM1 $tmpM2 $tmpM3 $tmpM4 $tmpV1 $tmpV2 $tmpV3 $tmpV4; exit 1" ERR

# get im_version
im_version=`convert -list configure | \
	sed '/^LIB_VERSION_NUMBER */!d; s//,/;  s/,/,0/g;  s/,0*\([0-9][0-9]\)/\1/g' | head -n 1`
	
# colorspace RGB and sRGB swapped between 6.7.5.5 and 6.7.6.7 
# though probably not resolved until the latter
# then -colorspace gray changed to linear between 6.7.6.7 and 6.7.8.2 
# then -separate converted to linear gray channels between 6.7.6.7 and 6.7.8.2,
# though probably not resolved until the latter
# so -colorspace HSL/HSB -separate and -colorspace gray became linear
# but we need to use -set colorspace RGB before using them at appropriate times
# so that results stay as in original script
# The following was determined from various version tests using redist.
# Note: bug in 6.7.6.6 HSL/HSB bad, 6.7.7.0 HSL/HSB/RGB bad, 6.7.7.8 & 6.7.7.9 HSL/HSB bad, 6.7.8.1 HSB very bad
# Note: for notch and other auto thresholding scripts, some (small?) differences between 6.7.5.10 and 6.7.7.0 inclusive
if [ "$im_version" -lt "06070606" -o "$im_version" -gt "06070707" ]; then
	cspace="RGB"
else
	cspace="sRGB"
fi
#echo "cspace=$cspace"
if [ "$im_version" -lt "06070607" -o "$im_version" -gt "06070707" ]; then
	setcspace="-set colorspace RGB"
else
	setcspace=""
fi
# no need for setcspace for grayscale or channels after 6.8.5.4
if [ "$im_version" -gt "06080504" ]; then
	setcspace="-set colorspace sRGB"
	cspace="sRGB"
fi
#echo "setcspace=$setcspace"

: <<COMMENT
# set up cproc processing -- old method works if -C none
if [ "$colorproc" = "none" ]; then
	cproc=""
else
	cproc="-set colorspace $colorproc"
fi
#echo "cproc=$cproc"
COMMENT

# set up cproc processing -- new method
if [ "$colorproc" = "none" ]; then
	cproc=""
else
	cproc="-set colorspace $colorproc"
fi
# from trial and error using 6.7.2.0/6.7.4.10, 6.7.6.10 and 6.7.8.2/6.7.8.3
# the following is needed for tonemap2 and tonemap3 when using -C colorproc != none, i.e. for .hdr images after 6.7.7.7
if [ "$im_version" -lt "06070607" ]; then
	if [ "$colorproc" = "sRGB" ]; then
		setcspace="-set colorspace RGB"
		cspace="RGB"
	elif [ "$colorproc" = "RGB" ]; then
		setcspace="-set colorspace sRGB"
		cspace="sRGB"
	fi
else
	if [ "$colorproc" = "sRGB" ]; then
		setcspace="-set colorspace sRGB"
		cspace="sRGB"
	elif [ "$colorproc" = "RGB" ]; then
		setcspace="-set colorspace RGB"
		cspace="RGB"
	fi
fi
#echo "cproc=$cproc"

# set up autolevel processing
if [ "$alevel" = "yes" ]; then
	aproc="-auto-level"
else
	aproc=""
fi
#echo "aproc=$aproc"

if [ "$log" != "0" ]; then
	log=`convert xc: -format "%[fx:pow(10,$log)]" info:`
	proc0="-evaluate log $log"
else
	proc0=""
fi
#echo "proc0=$proc0"



computeGammas()
	{
	img=$1
	mask=$2
		# get mean of mask
		meanm=`convert $mask -format "%[fx:mean]" info:`
		
		# get mean of shadows
		means=`convert $img \( $mask -negate \) \
			-compose multiply -composite -format "%[fx:mean/(1-$meanm)]" info:`
			
		# get mean of highlights
		meanh=`convert $img $mask \
			-compose multiply -composite -format "%[fx:mean/$meanm]" info:`

		sgamma=`convert xc: -format "%[fx:log($means)/log($shadows/100)]" info:`
		tests=`convert xc: -format "%[fx:$sgamma<=0?1:0]" info:`
		[ $tests -eq 1 ] && sgamma=`convert xc: -format "%[fx:log(255*$meanh)/log(255*$shadows/100)]" info:`

		hgamma=`convert xc: -format "%[fx:log($meanh)/log($highlights/100)]" info:`
		testh=`convert xc: -format "%[fx:$hgamma<=0?1:0]" info:`
		[ $testh -eq 1 ] && hgamma=`convert xc: -format "%[fx:log(255*$meanh)/log(255*$highlights/100)]" info:`
		
		echo "sgamma=$sgamma"
		echo "hgamma=$hgamma"
		echo ""
#echo "meanm=$meanm; means=$means; meanh=$meanh; sgamma=$sgamma; hgamma=$hgamma; tests=$tests; testh=$testh"
	}

# test input image
# clamp after autolevel(aproc) to avoid black patches
convert -quiet "$infile" -alpha off $setcspace $cproc $aproc -evaluate max 0 $proc0 +repage "$tmpA1" ||
	errMsg "--- FILE $infile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE ---"


# change colorspace to HSB and separate
convert $tmpA1 -colorspace HSB -separate $tmpA1

# find threshold in intensity channel
if [ "$thresh" = "" ]; then
	thresh=`convert $tmpA1[2] -format "%[fx:100*mean]" info:`
fi
echo ""
#echo "thresh=$thresh%"


# set up for ramping transition
if [ "$ramp" != "0" -a "$method" = "ramp" ]; then
	ramping="-blur ${ramp}x65000"
else
	ramping=""
fi
#echo "ramping=$ramping"


# setup adaptive blurring
blurring="-blur 0x${blur}"
#echo "blurring=$blurring"


# setup extra processing
if [ "$kind" = "none" ]; then
	tproc=""
elif [ "$kind" = "equalize" ]; then
	tproc="convert $tmpA2 -equalize $tmpA2"
elif [ "$kind" = "space" ]; then
	tproc="space -m 0 -w $window -g 5 $tmpA2 $tmpA2"
elif [ "$kind" = "retinex" ]; then
	tproc="retinex $tmpA2 $tmpA2"
elif [ "$kind" = "gaussian" ]; then
	tproc="redist $gvals $tmpA2 $tmpA2"
fi
#echo "tproc=$tproc"

# compute mask
# create mask to separate image at midpoint and blur
convert $tmpA1[2] -threshold ${thresh}% $ramping $tmpA2

# compute gammas
computeGammas $tmpA1[2] $tmpA2


# apply gammas
convert $tmpA1[2] -gamma $sgamma $tmpA3
convert $tmpA1[2] -gamma $hgamma $tmpA4


if [ "$method" = "ramp" ]; then
	convert $tmpA3 $tmpA4 $tmpA2 -compose over -composite $tmpA2
	
	# apply extra processing
	$tproc

elif [ "$method" = "adaptive" ]; then
	# compute local means and variances images
	convert $tmpA3 $blurring $tmpM1
	convert $tmpA4 $blurring $tmpM3
	convert \( $tmpA3 $tmpA3 -compose multiply -composite $blurring \) \
		\( $tmpM1 $tmpM1 -compose multiply -composite \) \
		+swap -compose minus -composite $tmpV1
	convert \( $tmpA4 $tmpA4 -compose multiply -composite $blurring \) \
		\( $tmpM3 $tmpM3 -compose multiply -composite \) \
		+swap -compose minus -composite $tmpV3
		
	# blend gamma corrected images using variances
	convert $tmpA3 $tmpA4 $tmpV1 $tmpV3 \
	\( -clone 0 -clone 2 -compose multiply -composite \) \
	\( -clone 1 -clone 3 -compose multiply -composite \) \
	\( -clone 4 -clone 5 -compose plus -composite \) \
	\( -clone 2 -clone 3 -compose plus -composite -evaluate max 1.0e-9 \) \
	-delete 0-5 +swap -compose divide -composite \
	$tmpA2

	# apply extra processing
	$tproc
fi

# recombine channels and convert to RGB
convert $tmpA1[0] \
\( $tmpA1[1] -evaluate multiply $sat \) \
\( $tmpA2 -brightness-contrast $bri,$con -sharpen 0x$edge \) \
-set colorspace HSB -combine -colorspace $cspace \
"$outfile"


exit 0
