#!/bin/bash
#
# Developed by Fred Weinhaus 8/26/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: tonemap3 [-k kind] [-a amount] [-t type] [-c colormode] [-s shadows] [-h highlights] [-e edge] [-w window] [-S saturation] [-C colorspace] [-A] infile outfile
# USAGE: tonemap3 [-help]
#
# OPTIONS:
#
# -k     kind      	    apply non-linear enhancement; log or gamma; default=log
# -a     amount     	amount of non-linear enhancement; float>0; default=4
# -t     type           type of extra processing; none (n), retinex (r), 
#                       or space (s); default=retinex
# -c     colormode		colormode; OHTA, YUV, YIQ, YCbCr, Rec709YCbCr; 
#                       default=OHTA
# -s     shadows      	increase/decrease percent brightness in shadows;
#                       positive or negative integer; default=0
# -h     highlights		increase/decrease percent brightness in highlights;
#                       positive or negative integer; default=0
# -e     edge           edge sharpening amount; float>=0; nominally 0 to 2;
#                       default=1
# -w     window       	window parameter for type=space; float>0; default=12.5 
# -S     saturation     saturation percent change; positive or negative integer; 
#                       default=50
# -C     colorproc      preprocessing to change colorspace to: RGB, sRGB;
#                       default is no change
# -A                    preprocessing to apply autolevel stretch; default is
#                       not to apply autolevel stretch
# 
#
###
#
# NAME: TONEMAP3 
# 
# PURPOSE: Enhances the shadows and/or highlight regions in an image using a 
# non-linear log or gamma function plus an extra processing function.
# 
# DESCRIPTION: TONEMAP3 enhances the shadows and/or highlight regions in
# an image using a non-linear log or gamma function plus an extra
# processing function, which can be either: a multiresolution retinex or
# space (spatially adaptive contrast enhancement). The a copy of the image
# is first processed by the non-linear function. Then it is converted to
# the desired colorspace and the channels separate. Then the channels are
# processed to enhance the saturation. Next a copy of the input image is
# converted to the same colorspace and the intensity (luminance) image is
# separate. The non-linear function is applied to it followed by the extra
# processing function and by the shadow/highlight enhancement and . edge
# sharpening. This last image is used to replace the intensity channel
# from the first processing of original image. Finally the 3 channels are
# recombined and converted back to RGB.
# 
# 
# OPTIONS: 
# 
# -k kind ... KIND of non-linear enhancement. Choices are log (l) or gamma (g).
# The log function is a scaled log whose scaling function is 10^amount. 
# The gamma function is a power law whose exponent is the amount.  
# The default=log
# 
# -a amount ... AMOUNT of non-linear enhancement. Values are float>0. Note  
# that kind=gamma can process dark image with amounts greater than 1 or bright 
# images with amounts less than 1. Whereas kind=log can only process dark images.   
# The log amounts are exponents for a power of 10. For example a log amount of 3  
# is equivalent to 1000. Nominal amounts for the log are about 3 to 4. Nominal 
# equivalent amounts for gamma are about twice those for the log, i.e. 6 to 8. 
# The default=4
# 
# -t type ... TYPE of extra processing. The choices are: none (n), retinex (r) 
# or space (s). Space is a spatially adaptive contrast enhancement and retinex 
# is multiscale enhancement. Note that equalize was tested, but did not work well.
# Generally retinex works well with fewer artifacts. Space can work better for 
# some images, but has more potential for ringing artifacts near high contrast 
# edges. The default=retinex.
# 
# -c colormode ... COLORMODE is the colorspace in which processing is done. 
# Values are OHTA, YUV, YIQ, YCbCr or Rec709YCbCr. There is some small difference 
# between OHTA and the others, but very little if any between those others.
# OHTA is an approximation for a principle components analysis (PCA) also known
# as Karhunen Loeve transformation (KLT). The default=OHTA
# 
# -s shadows ... SHADOWS is the increase/decrease percent brightness in the 
# shadows. Values are in range -100<=integer<=100. The default=0
# 
# -h highlights ... HIGHLIGHTS is the increase/decrease percent brightness in 
# the highlights. Values are in range -100<=integer<=100. The default=0
#
# -e edge ... EDGE is the edge sharpening amount. Values are floats>=0. 
# Nominal values are between 0 and 2. The default=1
#
# -w window ... WINDOW is the moving window percentage of image size for 
# type=space. Values are floats>0 and are nominally between 5 and 20. 
# Larger or smaller values can mitigate the ringing. Larger values 
# narrow the ringing and smaller values broaden or diffues the ringing.
# The default=12.5
# # 
# -S saturation ... SATURATION is the saturation percentage increase/decrease. 
# Values are positive or negatative integers.  The default=50
#
# -C colorproc ... COLORPROC is an optional preprocessing step to convert 
# the input image from some other colorspace to either 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.
# 
# -A ... Optional AUTOLEVEL preprocessing step. Generally this will not be 
# needed, especially for HDR image with very high dynamic range that require 
# processing in IM HDRI mode. Using it on such images generally cause changes 
# in color or causes the images to become dark.
#
# REQUIREMENTS: space and retinex scripts. Also IM 6.5.9-0 to support the 
# -brightness-contrast function.
# 
# NOTE: type=retinex will be slow due to the use of -fx for IM less 
# than 6.4.2-1. type=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/tonemap3/tonemap_tests.txt 
# 
# Reference:
# http://biblion.epfl.ch/EPFL/theses/2006/3588/EPFL_TH3588.pdf (see page 33)
# http://en.wikipedia.org/wiki/Principal_component_analysis
# http://www.sciencedirect.com/science/article/pii/0146664X80900477
#
# 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
kind="log"			# kind of non-linear enhancement; log or gamma
amount="4"			# amount of non-linear enhancement; log ~ 10^amount; float
type="retinex"		# type of extra processing; none, space, retinex
colormode="OHTA"	# OHTA, YUV, YIQ, YCbCr, Rec709YCbCr 
shadows=0			# increase/decrease percent of brightness in shadows; integer
highlights=0		# increase/decrease percent of brightness in highlights; integer
edge=1				# edge enhancement sharpening sigma; float>=0
sat=50				# saturation percent increase/decrease;
window=12.5			# space window paramter; float>0; defaul=12.5
colorproc="none"		# colorspace preprocessing; none; RGB, sRGB
alevel="no"			# auto-level preprocessing; yes or no

# 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 23 ]
	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
					   ;;
				-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 
					   		log|l) kind=log;;
					   		gamma|g) kind=gamma;;
					   		*) errMsg "--- KIND=$kind IS AN INVALID VALUE ---" 
					   	esac
					   ;;
				-a)    # get amount
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID AMOUNT SPECIFICATION ---"
					   checkMinus "$1"
					   amount=`expr "$1" : '\([.0-9]*\)'`
					   [ "$amount" = "" ] && errMsg "--- AMOUNT=$amount MUST BE A NON-NEGATIVE FLOAT (with no sign) ---"
					   test1=`echo "$amount <= 0" | bc`
					   [ $test1 -eq 1 ] && errMsg "--- AMOUNT=$amount MUST BE A POSITIVE FLOAT ---"
					   ;;
				-t)    # get  type
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID TYPE SPECIFICATION ---"
					   checkMinus "$1"
					   type=`echo "$1" | tr '[A-Z]' '[a-z]'`
					   case "$type" in 
					   		none|n) type=none;;
					   		space|s) type=space;;
					   		retinex|r) type=retinex;;
					   		*) errMsg "--- TYPE=$type IS AN INVALID VALUE ---" 
					   	esac
					   ;;
				-c)    # get  colormode
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID COLORMODE SPECIFICATION ---"
					   checkMinus "$1"
					   colormode=`echo "$1" | tr '[A-Z]' '[a-z]'`
					   case "$colormode" in 
					   		ohta) colormode=OHTA;;
					   		yuv) colormode=YUV;;
					   		yiq) colormode=YIQ;;
					   		ycbcr) colormode=YCbCr;;
					   		rec709ycbcr) colormode=Rec709YCbCr;;
					   		*) errMsg "--- COLORMODE=$colormode IS AN INVALID VALUE ---" 
					   	esac
					   ;;
				-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 < -100" | bc`
					   test2=`echo "$shadows > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- SHADOWS=$shadows MUST BE AN INTEGER BETWEEN -100 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 < -100" | bc`
					   test2=`echo "$highlights > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- HIGHLIGHTS=$highlights MUST BE AN INTEGER BETWEEN -100 AND 100 ---"
					   ;;
				-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=$blur MUST BE A NON-NEGATIVE FLOAT ---"
 					   ;;
				-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 ---"
					   ;;
				-S)    # get sat
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID SATURATION SPECIFICATION ---"
					   #checkMinus "$1"
					   sat=`expr "$1" : '\([-0-9]*\)'`
					   [ "$sat" = "" ] && errMsg "--- SATURATION=$sat MUST BE AN INTEGER ---"
					   test1=`echo "$sat < -100" | bc`
					   test2=`echo "$sat > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- v=$sat MUST BE AN INTEGER BETWEEN -100 AND 100 ---"
					   ;;
				-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
					   ;;
				-A)    # get  aproc
					   alevel="yes"
					   ;;
			 	-)    # 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/tonemap2_A_$$.mpc"
tmpA2="$dir/tonemap2_A_$$.cache"
tmpS1="$dir/tonemap2_S_$$.mpc"
tmpS2="$dir/tonemap2_S_$$.cache"
tmpI1="$dir/tonemap2_I_$$.mpc"
tmpI2="$dir/tonemap2_I_$$.cache"
trap "rm -f $tmpA1 $tmpA2 $tmpS1 $tmpS2 $tmpI1 $tmpI2;" 0
trap "rm -f $tmpA1 $tmpA2 $tmpS1 $tmpS2 $tmpI1 $tmpI2; exit 1" 1 2 3 15
trap "rm -f $tmpA1 $tmpA2 $tmpS1 $tmpS2 $tmpI1 $tmpI2; 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 "06070607" -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"

# set up clamp due its removal for HDRI somewhere after IM 6.6.0.10, 
# so that neg values do not cause problems with -evaluate log.
# clamping added to log in IM 6.7.7.6
if [ "$im_version" -lt "06070706" -a "$im_version" -gt "06060010" -a "$kind" = "log" -a "$amount" != "0" ]; then
	clamp="-evaluate max 0"
else
	clamp=""
fi
#echo "clamp=$clamp"

# test input image
convert -quiet "$infile" -alpha off $cproc $aproc $clamp +repage "$tmpA1" ||
	errMsg "--- FILE $infile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE ---"



# set up log factor
if [ "$kind" = "log" ]; then
	amount=`convert xc: -format "%[fx:10^$amount]" info:`
	proc0="-evaluate log $amount"
elif [ "$kind" = "gamma" ]; then
	proc0="-gamma $amount"
fi
#echo "amount=$amount; proc0=$proc0"


# setup shadows and hightlights level values
ssign=`convert xc: -format "%[fx:sign($shadows)==-1?1:0]" info:`
hsign=`convert xc: -format "%[fx:sign($highlights)==-1?1:0]" info:`
#echo "ssign=$ssign; hsign=$hsign"

mlo=0
mhi=100
plo=0
phi=100
if [ "$shadows" != "0" -a $ssign -eq 1 ]; then
	mlo=$((-shadows))
elif [ "$shadows" != "0" -a $ssign -eq 0 ]; then
	plo=$shadows
fi
if [ "$highlights" != "0" -a $hsign -eq 1 ]; then
	phi=$((100+highlights))
elif [ "$highlights" != "0" -a $hsign -eq 0 ]; then
	mhi=$((100-highlights))
fi

if [ $mlo -eq 0 -a $mhi -eq 100 ]; then
	proc1=""
else
	proc1="-level $mlo,$mhi%"
fi

if [ $plo -eq 0 -a $phi -eq 100 ]; then
	proc2=""
else
	proc2="+level $plo,$phi%"
fi
#echo "mlo=$mlo; mhi=$mhi; plo=$plo; phi=$phi; proc1=$proc1; proc2=$proc2"


# set up saturation processing
if [ "$sat" = "0" ]; then
	saturation=""
else
	saturation="-brightness-contrast 0,$sat"
fi
#echo "saturation=$saturation"


# set up edge sharpening
if [ "$edge" = "0" ]; then
	eproc=""
else
	eproc="-sharpen 0x$edge"
fi
#echo "eproc=$eproc"


# set up for type
if [ "$type" = "none" ]; then
	tproc=""
elif [ "$type" = "space" ]; then
	tproc="space -m 0 -w $window -g 5"
elif [ "$type" = "retinex" ]; then
	tproc="retinex"
fi
#echo "tproc=$tproc"


if [ "$type" = "none" ]; then
	convert $tmpA1 \
		\( -clone 0 $proc0 $setcspace -colorspace $colormode -separate +channel $saturation \) \
		\( -clone 0 $proc0 $setcspace -colorspace $colormode -channel R -separate +channel $tproc $proc1 $proc2 $eproc \) \
		-delete 0,1 -insert 0 -set colorspace $colormode -combine -colorspace $cspace \
		"$outfile"

elif [ "$type" = "space" -o "$type" = "retinex" ]; then
	convert $tmpA1 $proc0 $setcspace -colorspace $colormode -separate +channel $saturation $tmpS1
	convert $tmpA1 $setcspace -colorspace $colormode -channel R -separate +channel $proc0 $tmpI1
	$tproc $tmpI1 $tmpI1
	convert \( $tmpI1 $proc1 $proc2 $eproc \) $tmpS1[1] $tmpS1[2] \
		-set colorspace $colormode -combine -colorspace $cspace \
		"$outfile"
fi

exit 0