#!/bin/bash
#
# Developed by Fred Weinhaus 4/5/2010 .......... revised 4/25/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: dog [-s smallfilt] [-l largefilt] [-m mode] [-t thresh] [-b brighten] infile outfile
# USAGE: dog [-h or -help]
# 
# OPTIONS:
# 
# -s      smallfilt         size of small gaussian filter; float>0; default=1
# -l      largefilt         size of large gaussian filter; float>0; default=2
# -m      mode              mode of subtraction; choices are 1 (larger-smaller) 
#                           and 2 (smaller - larger); default=1
# -t      thresh            edge tresholding value; 0<=integer<=100; The default
#                           is no thresholding; a value=0 is all edges thresholded
# -b      brighten          edge brightening factor; float>=1; default=1 is 
#                           no brightening
# 
###
# 
# NAME: DOG 
# 
# PURPOSE: To create an edge extracted image using the difference of two
# gaussian blurs.
# 
# DESCRIPTION: DOG creates an edge extracted image using the difference of two
# gaussian blurs of different sizes.
# 
# 
# ARGUMENTS: 
# 
# -s smallfilt ... SMALLFILT is the size of the smaller gaussian blur filter. 
# Values are floats>0. The default=1
# 
# -l largefilt ... LARGEFILT is the size of the larger gaussian blur filter. 
# Values are floats>0. The default=1
# 
# -m mode ... MODE determines the order of the subtraction. Choices are: 
# 1 for (larger - smaller) or 2 for (smaller - larger). The default=1.
# 
# -t thresh ... THRESH is the optional thresholding applied to the edge image 
# to make the edges binary white on a black background. Values are 
# 0<=integer<=100. The default indicates no thresholding. A value of 0 means 
# threshold to get all edges. 
# 
# -b brighten ... BRIGHTEN is the brightening factor for the edges. Values 
# are floats>=1. The default=1 indicates no brightening.
# 
# 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
smallfilt=1			#size of small gaussian blur filter
largefilt=2			#size of large gaussian blur filter
thresh=""			#edge thresholding; "" is unthreshold; 0 is all thresholded
brighten=1			#brightening edges
mode=1				#subtraction mode

# 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 12 ]
	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
					   ;;
				-s)    # get  smallfilt
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID SMALLFILT SPECIFICATION ---"
					   checkMinus "$1"
					   smallfilt=`expr "$1" : '\([.0-9]*\)'`
					   [ "$smallfilt" = "" ] && errMsg "--- SMALLFILT=$smallfilt MUST BE A NON-NEGATIVE FLOAT (with no sign) ---"
					   test=`echo "$smallfilt <= 0" | bc`
					   [ $test -eq 1 ] && errMsg "--- SMALLFILT=$smallfilt MUST BE A POSITIVE FLOAT (with no sign) ---"
					   ;;
				-l)    # get  largefilt
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID LARGEFILT SPECIFICATION ---"
					   checkMinus "$1"
					   largefilt=`expr "$1" : '\([.0-9]*\)'`
					   [ "$largefilt" = "" ] && errMsg "--- LARGEFILT=$largefilt MUST BE A NON-NEGATIVE FLOAT (with no sign) ---"
					   test=`echo "$largefilt <= 0" | bc`
					   [ $test -eq 1 ] && errMsg "--- LARGEFILT=$largefilt MUST BE A POSITIVE FLOAT (with no sign) ---"
					   ;;
				-m)    # get mode
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID MODE SPECIFICATION ---"
					   checkMinus "$1"
					   mode=`expr "$1" : '\([0-9]*\)'`
					   [ "$mode" = "" ] && errMsg "--- MODE=$mode MUST BE A NON-NEGATIVE INTEGER ---"
					   [ $mode -ne 1 -a $mode -ne 2 ] && errMsg "--- MODE=$mode MUST BE EITHER 1 OR 2 ---"
					   ;;
				-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 A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   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  brighten
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BRIGHTEN SPECIFICATION ---"
					   checkMinus "$1"
					   brighten=`expr "$1" : '\([.0-9]*\)'`
					   [ "$brighten" = "" ] && errMsg "--- BRIGHTEN=$brighten MUST BE A NON-NEGATIVE FLOAT (with no sign) ---"
					   test=`echo "$brighten < 1" | bc`
					   [ $test -eq 1 ] && errMsg "--- BRIGHTEN=$brighten MUST BE A FLOAT GREATER THAN OR EQUAL TO 1 ---"
					   ;;
				 -)    # 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"


# test if smallfilt < largefilt
test=`convert xc: -format "%[fx:$smallfilt<$largefilt?1:0]" info:`
[ $test -eq 0 ] && errMSG "--- SMALLFILT MUST BE LESS THAN LARGEFILT ---"

# setup temporary images and auto delete upon exit
tmpA1="$dir/dog_1_$$.mpc"
tmpB1="$dir/dog_1_$$.cache"
trap "rm -f $tmpA1 $tmpB1;" 0
trap "rm -f $tmpA1 $tmpB1; exit 1" 1 2 3 15
trap "rm -f $tmpA1 $tmpB1; exit 1" ERR

# test for minimum 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 dog.
# with IM 6.7.4.10, 6.7.6.10, 6.7.8.7
# Note: added $setcspace before thresholding
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=""
fi


# read the input image and filter image into the temp files and test validity.
convert -quiet "$infile" +repage "$tmpA1" ||
	errMsg "--- FILE $infile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE  ---"


# set up thresholding
if [ "$thresh" != "" ]; then
	thresholding=" $setcspace -threshold ${thresh}%"
else
	thresholding=""
fi

# set up stretch
# 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`
if [ "$im_version" -lt "06050501" ]; then
	stretch="-contrast-stretch 0"
else
	stretch="-auto-level"
fi

# set up bgmode
if [ $brighten -eq 0 ]; then
	bright=""
else
	bright="-evaluate multiply ${brighten}"
fi

# set up mode
if [ "$mode" = "1" ]; then
	swapmode="+swap"
else
	swapmode=""
fi

# create thresholded gradient edge image
convert $tmpA1 \
	\( -clone 0 -blur 0x$largefilt \) \
	\( -clone 0 -blur 0x$smallfilt \) \
	-delete 0 $swapmode -compose minus -composite \
	$stretch $bright $thresholding "$outfile"



