#!/bin/bash
#
# Developed by Fred Weinhaus 11/2/2015 .......... revised 6/21/2017
#
# ------------------------------------------------------------------------------
# 
# 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: toon [-m method] [-g gain] [-c compose] [-b blur] [-s saturation] 
# [-B brightness] [-S smoothing] infile outfile
# USAGE: toon [-help]
#
# OPTIONS:
#
# -m     method         method=1 or 2; default=1
# -g     gain           edge gain (i.e. strength); float>=0; default=5
# -c     compose        optional compose type for method=1; default no compose
# -b     blur           blur amount for method=2; float>=0; default=5
# -s     saturation     color saturation; integer>=0; default=100 (no change)
# -B     brightness     brightness; integer>=0; default=100 (no change)
# -S     smoothing      smoothing; 0<=integer<=100; default=0 for method=1  
#                       and default=30 for method=2
#
###
#
# NAME: TOON 
# 
# PURPOSE: To apply a cartoon-like effect to an image.
# 
# DESCRIPTION: TOON applies a cartoon-like effect to an image.
# 
# OPTIONS: 
# 
# -g  gain ... GAIN is the edge gain (i.e. strength or intensity). 
# Values are floats>=0. The default=5.
# 
# -m method ... METHOD. The choices are: 1 or 2. The default=1.
# 
# -c compose ... optional COMPOSE type for method=1. The choices are: 
# overlay, multiply, bumpmap, hardlight, softlight, pegtoplight, pinlight, 
# linearlight, vividlight, linearburn, colorburn. The default is no compose.
# 
# -b blur ... BLUR amount for method=2. Values are floats>=0. The default=5.
# 
# -s saturation ... color SATURATION. Values are integers>=0. The default=100 
# (no change). 0 is grayscale and 200 is twice the saturation
# 
# -B brightness ... BRIGHTNESS. Values are integers>=0. The default=100 
# (no change).
# 
# -S smoothing ... SMOOTHING. Values are 0<=integer<=100. The default=0 for 
# method=1 and the default=30 for method=2.
# 
# REQUIREMENTS: IM 6.6.2.2 due to the use of rotated kernels in -morphology 
# convolve.
# 
# 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
gain=5				# edge gain
method="1"			# cartoon type
blur=5				# blur amount
compose=""			# compose type
saturation=100		# color saturation
brightness=100		# brightness

# 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 16 ]
	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 
					   		1) ;;
					   		2) ;;
					   		*) errMsg "--- METHOD=$method IS AN INVALID VALUE ---"  ;;
					   esac
					   ;;
				-g)    # get gain
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID GAIN SPECIFICATION ---"
					   checkMinus "$1"
					   gain=`expr "$1" : '\([.0-9]*\)'`
					   [ "$gain" = "" ] && errMsg "--- GAIN=$gain MUST BE A NON-NEGATIVE FLOAT ---"
					   ;;
				-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 ---"
					   ;;
				-c)    # get  compose
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID COMPOSE SPECIFICATION ---"
					   checkMinus "$1"
					   compose=`echo "$1" | tr '[A-Z]' '[a-z]'`
					   case "$compose" in 
					   		overlay) ;;
					   		multiply) ;;
					   		bumpmap) ;;
					   		hardlight) ;;
					   		softlight) ;;
					   		pegtoplight) ;;
					   		pinlight) ;;
					   		linearlight) ;;
					   		vividlight) ;;
					   		linearburn) ;;
					   		colorburn) ;;
					   		*) errMsg "--- COMPOSE=$compose IS AN INVALID VALUE ---"  ;;
					   esac
					   ;;
				-s)    # get saturation
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID SATURATION SPECIFICATION ---"
					   checkMinus "$1"
					   saturation=`expr "$1" : '\([0-9]*\)'`
					   [ "$saturation" = "" ] && errMsg "--- SATURATION=$saturation MUST BE A NON-NEGATIVE INTEGER ---"
					   ;;
				-B)    # get brightness
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BRIGHTNESS SPECIFICATION ---"
					   checkMinus "$1"
					   brightness=`expr "$1" : '\([0-9]*\)'`
					   [ "$brightness" = "" ] && errMsg "--- BRIGHTNESS=$brightness MUST BE A NON-NEGATIVE INTEGER ---"
					   ;;
				-S)    # get smoothing
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID SMOOTHING SPECIFICATION ---"
					   checkMinus "$1"
					   smoothing=`expr "$1" : '\([0-9]*\)'`
					   [ "$smoothing" = "" ] && errMsg "--- SMOOTHING=$smoothing MUST BE A NON-NEGATIVE INTEGER ---"
					   test=`echo "$smoothing > 100" | bc`
					   [ $test -eq 1 ] && errMsg "--- SMOOTHING=$smoothing MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				 -)    # 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"


# set directory for temporary files
tmpdir="$dir"

dir="$tmpdir/SOFTFOCUS.$$"

mkdir "$dir" || errMsg "--- FAILED TO CREATE TEMPORARY FILE DIRECTORY ---"
trap "rm -rf $dir;" 0
trap "rm -rf $dir; exit 1" 1 2 3 15
trap "rm -rf $dir; exit 1" ERR

# read input image into temporary memory mapped (mpc) format image
convert -quiet "$infile" +repage $dir/tmpI.mpc ||
	echo  "--- FILE $thefile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE  ---"

# 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 for saturation
if [ "$saturation" != "100" -o "$brightness" != "100" ]; then
	modulating="-modulate $brightness,$saturation,100"
else
	modulating=""
fi

# set up for smoothing
if [ "$smoothing" = "" -a $method -eq 1 ]; then
	smoothing=0
elif [ "$smoothing" = "" -a $method -eq 2 ]; then
	smoothing=30
fi

# set up for -sigmoidal-contrast depending upon version
# below 6.7.9.5, it would make a black result if value was 0, so use value of 1
# alternate is to just disable sigmoidal contrast setting contrasting="" if 
# smoothing=0; otherwise contrasting="-sigmoidal-contrast $smoothing"
test=`convert xc: -format "%[fx:($smoothing<0.0001)?1:0]" info:`
if [ "$im_version" -lt "06070905" -a $method -eq 1 -a $test -eq 1 ]; then
	smoothing=1
fi

# set up for extra compose for method=1
if [ "$compose" != "" ]; then
	composing="$dir/tmpI.mpc +swap -compose $compose -composite"
else
	composing=""
fi

# process image
if [ $method -eq 1 ]; then
	convert $dir/tmpI.mpc \
		\( -clone 0 -colorspace gray -define convolve:scale='!' \
		-define morphology:compose=Lighten \
		-morphology Convolve  'Sobel:>' \
		-negate -evaluate pow $gain -sigmoidal-contrast $smoothing,50% \) \
		+swap -compose colorize -composite \
		$composing $modulating \
		"$outfile"
elif [ $method -eq 2 ]; then
	convert $dir/tmpI.mpc \
		\( -clone 0 -blur 0x$blur \) \
		\( -clone 0 -fill black -colorize 100 \) \
		\( -clone 0 -define convolve:scale='!' \
		-define morphology:compose=Lighten \
		-morphology Convolve  'Sobel:>' \
		-negate -evaluate pow $gain -negate -level ${smoothing}x100% \) \
		-delete 0 -compose over -composite \
		$modulating \
		"$outfile"
fi

exit 0