#!/bin/bash
#
# Developed by Fred Weinhaus 1/3/2008 .......... revised 5/7/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: whitebalance [x,y] [-c color] [-r refcolor] infile outfile
# USAGE: whitebalance [-h or -help]
#
# OPTIONS:
#
# x,y                    x,y coordinate in the image to get color to 
#                        transform to pure white
# -c      color          color to transform to pure white;
#                        may be specified in any standard IM notation
# -r      refcolor       reference color to which to match;
#                        may be specified in any standard IM notation
#                        default=white i.e. rgb(255,255,255)
#
###
#
# NAME: WHITEBALANCE 
# 
# PURPOSE: To transform an image's overall color balance according to a desired 
# change in a specified white point color.
# 
# DESCRIPTION: WHITEBALANCE transforms an image's overall color balance according 
# to a desired change in a specified white point color. The white point color may 
# be specified by selecting a pixel coordinate (position) to extract the color or 
# by specifying the color that should be transformed to pure white. One or the 
# other must be specified, but not both. The white point color values (actually  
# any color value as an r,g,b triple in the range of 0 to 255) may be specified.
# 
# 
# OPTIONS: 
# 
# x,y ... x,y are the coordinates in the image where the color is to be 
# extracted and transformed to pure white.
# 
# -c color ... COLOR is the color to be used to transform to pure white. 
# Any IM color specification is valid. Be sure to enclose it in double quotes. 
# 
# One or the other of the above must be provided, but not both.
#
# -r refcolor ... REFCOLOR is the reference color to which to match. 
# Any IM color specification is valid. Be sure to enclose it in double quotes. 
# The default="white".
# 
# 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
coords=""
usercolor=""
refcolor="white"

# 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 6 ]
	then
	errMsg "--- TOO MANY ARGUMENTS WERE PROVIDED ---"
else
	while [ $# -gt 0 ]
		do
			# get parameter values
			case "$1" in
		  -h|-help)    # help information
					   echo ""
					   usage2
					   exit 0
					   ;;
				-c)    # get user color
					   shift  # to get the next parameter - lineval
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID COLOR SPECIFICATION ---"
					   checkMinus "$1"
					   usercolor="$1"
					   ;;
				-r)    # get reference (white) color
					   shift  # to get the next parameter - lineval
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID REFERENCE COLOR SPECIFICATION ---"
					   checkMinus "$1"
					   refcolor="$1"
					   ;;
				 -)    # STDIN and end of arguments
					   break
					   ;;
				-*)    # any other - argument
					   errMsg "--- UNKNOWN OPTION ---"
					   ;;
	 [0-9]*,[0-9]*)    # Values supplied for coordinates
		   			   coords="$1"
					   ;;
		   	 .*,.*)    # Bogus Values supplied
		   	   		   errMsg "--- COORDINATES ARE NOT VALID ---"
		   	   		   ;;
		     	 *)    # 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"

tmpA="$dir/whitebalance_$$.mpc"
tmpB="$dir/whitebalance_$$.cache"
tmp0="$dir/whitebalance_0_$$.png"
trap "rm -f $tmpA $tmpB $tmp0;" 0
trap "rm -f $tmpA $tmpB $tmp0; exit 1" 1 2 3 15
trap "rm -f $tmpA $tmpB $tmp0; exit 1" ERR

if convert -quiet "$infile" +repage "$tmpA"
	then
	: ' Do Nothing '
else
	errMsg "--- FILE $infile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE ---"
fi

[ "$coords" = "" -a "$usercolor" = "" ] && errMsg "--- EITHER A COORDINATE OR A COLOR MUST BE SPECIFIED ---"

# get user color from coordinates
if [ "$coords" != "" ]
	then
	ured=`convert $tmpA -format "%[fx:255*u.p{$coords}.r]" info:`
	ugreen=`convert $tmpA -format "%[fx:255*u.p{$coords}.g]" info:`
	ublue=`convert $tmpA -format "%[fx:255*u.p{$coords}.b]" info:`
fi

# convert user color from color specification
if [ "$usercolor" != "" ]
	then
	convert -size 1x1 xc:"$usercolor" $tmp0
	ured=`convert $tmp0 -format "%[fx:255*u.p{0,0}.r]" info:`
	ugreen=`convert $tmp0 -format "%[fx:255*u.p{0,0}.g]" info:`
	ublue=`convert $tmp0 -format "%[fx:255*u.p{0,0}.b]" info:`
fi

echo ""
echo "user specified color triplet"
echo "$ured,$ugreen,$ublue"

# convert reference color
convert -size 1x1 xc:"$refcolor" $tmp0
rred=`convert $tmp0 -format "%[fx:255*u.p{0,0}.r]" info:`
rgreen=`convert $tmp0 -format "%[fx:255*u.p{0,0}.g]" info:`
rblue=`convert $tmp0 -format "%[fx:255*u.p{0,0}.b]" info:`

echo ""
echo "reference color triplet"
echo "$rred,$rgreen,$rblue"
echo ""

# compute color ratio and trap for divide by zero
if [ $ured -eq 0 ]
	then 
	redfrac=255
else 
	redfrac=`echo "scale=3; $rred / $ured" | bc`
fi
if [ $ugreen -eq 0 ]
	then 
	greenfrac=255
else 
	greenfrac=`echo "scale=3; $rgreen / $ugreen" | bc`
fi
if [ $ublue -eq 0 ]
	then 
	bluefrac=255
else 
	bluefrac=`echo "scale=3; $rblue / $ublue" | bc`
fi

# 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`

# set up -recolor or -color-matrix
if [ "$im_version" -lt "06060100" ]; then
	process="-recolor"
else
	process="-color-matrix"
fi

# transform image color
convert $tmpA $process "$redfrac 0 0 0 $greenfrac 0 0 0 $bluefrac" "$outfile"
exit 0


