#!/bin/bash
#
# Developed by Fred Weinhaus 2/25/2013 .......... revised 8/12/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: vintage1 [-b brightness] [-c contrast] [-s vignetteshape] 
# [-r vignetterounding] [-l vignettelighten] [-N noiseamount] 
# [-L verticallines] [-B verticalbands] [-S backgroundmix] [-T bordertype] 
# [-W borderwidth] [ -R borderrounding] [-C bordercolor] 
# infile [backgroundfile] outfile 
# 
# USAGE: vintage1 [-h or -help]
# 
# OPTIONS:
# 
# -b     brightness           vintage brightness; -100<=integer<=100; 
#                             default=10
# -c     contrast             vintage contrast; -100<=integer<=100; 
#                             default=-20
# -s     vignetteshape        vignette shape; choices are: roundrectangle, 
#                             horizontal, vertical or none; 
#                             default=roundrectangle
# -r     vignetterounding     vignette rounding percent for roundrectangle  
#                             only; 0<=integer<=50; default=50 for 
#                             roundrectangle and default=20 otherwise
# -l     vignettelighten      vignette ligntening; 0<=integer<=100; default=0
# -N     noiseamount          noise amount; 0<=integer<=100; default=30 
# -L     verticallines        intensity of vertical lines; 0<=integer<=100; 
#                             default=25 
# -B     verticalbands        intensity of vertical bands;  0<=integer<=100; 
#                             default=30 
# -M     backgroundmix        background mixing; 0<=integer<=100; 
#                             default=65
# -T     bordertype           border type; choices are: none, torn, rounded; 
#                             default=none
# -W     borderwidth          border width only for bordertype=torn or rounded; 
#                             integer>=0; default=5
# -R     borderrounding       border rounding percent only for 
#                             bordertype=rounded; 0<=integer<=50; default=10
# -C     bordercolor          border color; default=white
# 
# The backgroundfile is any texture image that is as large or larger than 
# the image to be processed. Typically the backgroundfile should be converted 
# to grayscale before using.
# 
###
# 
# NAME: VINTAGE1 
# 
# PURPOSE: To apply a classic vintage effect to an image.
# 
# DESCRIPTION: VINTAGE1 applies a classic blue-green vintage effect to an 
# image. The vintage effect includes: noise, lines, various vignette types 
# and various border types.
# 
# 
# ARGUMENTS: 
# 
# -b brightness ... BRIGHTNESS is the vintage brightness. Values are integers 
# between -100 and 100. The default=10.
# 
# -c contrast ... CONTRAST is the vintage contrast. Values are integers 
# between -100 and 100. The default=-20.
# 
# -s vignetteshape ... VIGNETTESHAPE is the vignette shape. Choices are: 
# roundrectangle (r), horizontal (h), vertical (v) or none (n). The 
# default=roundrectangle.
# 
# -r vignetterounding ... VIGNETTEROUNDING is the vignette rounding percent 
# for the roundrectangle shape only. Values are integers between 0 and 50. 
# The default=50.
# 
# -l vignettelighten ... VIGNETTELIGHTEN is the vignette ligntening. Values 
# are integers between 0 and 100. The default=0.
# 
# -N noiseamt ... NOISEAMT is the amount of noise added. Values are integers 
# between 0 and 100. The default=30.
# 
# -L verticallines ... VERTICALLINES is the intensity of vertical lines added. 
# Values are integers between 0 and 100. The default=25.
# 
# -B verticalbands ... VERTICALBANDS is the intensity of vertical bands added. 
# Values are integers between 0 and 100. The default=30.
# 
# -M backgroundmix ... BACKGROUNDMIX is the amount of background mixing with 
# the image. Values are integers between 0 and 100. The default=65.
# 
# -T bordertype ... BORDERTYPE is the image border type. The choices are: 
# none (n), torn (t) or rounded (r). The default=none.
# 
# -W borderwidth ... BORDERWIDTH is the image border width only for 
# bordertype=torn or rounded. Values are integers between 0 and 100. 
# The default=5.
# 
# -R borderrounding ... BORDERROUNDING is the image border rounding percent 
# only for bordertype=rounded.  Values are integers between 0 and 50. The 
# default=10. 
# 
# -C bordercolor ... BORDERCOLOR is the image border color. Any valid IM color 
# is allowed. The default=white.
# 
# REFERENCES:
# http://www.photoshop-plus.co.uk/2011/03/15/vintage-photo-effects-using-adobe-photoshop/
# http://aceinfowayindia.com/blog/2009/12/how-to-create-vintage-photo-effect-photoshop-tutorial/
# 
# BACKGROUNDS:
# http://www.flickr.com/photos/borealnz/sets/72157610307314214/with/3495540187/
# --- http://www.flickr.com/photos/borealnz/3495540187/in/set-72157610307314214
# --- http://www.flickr.com/photos/borealnz/3124030212/in/set-72157610307314214
# http://lostandtaken.com/
# --- http://www.unsigneddesign.com/LT_AntiquePaper.zip
# --- http://www.unsigneddesign.com/LT_MicroscopicGrit.zip
# 
# 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

# primary parameters
brightness=10
contrast=-20
vignetteshape="roundrectangle"
vignetterounding=20
vignettelighten=0
noiseamt=30
verticalnoiseamt=25
bandingamt=30
backgroundamt=65
bordertype="none"
bordercolor="white"
borderwidth=5
borderrounding=10


# ancillary
bandingwidth=15
vignettesize=85
tintcolor="#0000FF"
tintamt=30
colorizecolor="#DCEE"
green2blueamt="6"				# 2 to 9; nominal 6
colorizecolor="${colorizecolor}${green2blueamt}${green2blueamt}"
colorizeamt=65
blackcolor="#111842"
blackcoloramt="40"
torndensity=1
torncurviness=5
tornroughness=1
tornpad=2
noiseseed=100
vertnoiseseed=100
bandseed=40
tornseed=100

# 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 29 ]
	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
					   ;;
				-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 VALUE (with no sign) ---"
					   test1=`echo "$brightness < -100" | bc`
					   test2=`echo "$brightness > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- BRIGHTNESS=$brightness MUST BE AN INTEGER BETWEEN -100 AND 100 ---"
					   ;;
				-c)    # get contrast
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID CONTRAST SPECIFICATION ---"
					   #checkMinus "$1"
					   contrast=`expr "$1" : '\([-0-9]*\)'`
					   [ "$contrast" = "" ] && errMsg "--- CONTRAST=$contrast MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$contrast < -100" | bc`
					   test2=`echo "$contrast > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- CONTRAST=$contrast MUST BE AN INTEGER BETWEEN -100 AND 100 ---"
					   ;;
				-s)    # get  vignetteshape
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID VIGNETTESHAPE SPECIFICATION ---"
					   checkMinus "$1"
					   vignetteshape=`echo "$1" | tr '[A-Z]' '[a-z]'`
					   case "$vignetteshape" in 
					   		roundrectangle|r) vignetteshape=roundrectangle ;;
					   		horizontal|h) vignetteshape=horizontal;;
					   		vertical|v) vignetteshape=vertical;;
					   		none|n) vignetteshape=none;;
					   		*) errMsg "--- VIGNETTESHAPE=$vignetteshape IS AN INVALID VALUE ---"  ;;
					   esac
					   ;;
				-r)    # get vignetterounding
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID VIGNETTEROUNDING SPECIFICATION ---"
					   checkMinus "$1"
					   vignetterounding=`expr "$1" : '\([0-9]*\)'`
					   [ "$vignetterounding" = "" ] && errMsg "--- VIGNETTEROUNDING=$vignetterounding MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$vignetterounding < 0" | bc`
					   test2=`echo "$vignetterounding > 50" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- VIGNETTEROUNDING=$vignetterounding MUST BE AN INTEGER BETWEEN 0 AND 50 ---"
					   ;;
				-l)    # get vignettelighten
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID VIGNETTELIGHTEN SPECIFICATION ---"
					   checkMinus "$1"
					   vignettelighten=`expr "$1" : '\([0-9]*\)'`
					   [ "$vignettelighten" = "" ] && errMsg "--- VIGNETTELIGHTEN=$vignettelighten MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$vignettelighten < 0" | bc`
					   test2=`echo "$vignettelighten > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- VIGNETTELIGHTEN=$vignettelighten MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-N)    # get noiseamt
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID NOISEAMOUNT SPECIFICATION ---"
					   checkMinus "$1"
					   noiseamt=`expr "$1" : '\([0-9]*\)'`
					   [ "$noiseamt" = "" ] && errMsg "--- NOISEAMOUNT=$noiseamt MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$noiseamt < 0" | bc`
					   test2=`echo "$noiseamt > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- NOISEAMOUNT=$noiseamt MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-L)    # get verticalnoiseamt
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID VERTICALLINES SPECIFICATION ---"
					   checkMinus "$1"
					   verticalnoiseamt=`expr "$1" : '\([0-9]*\)'`
					   [ "$verticalnoiseamt" = "" ] && errMsg "--- VERTICALLINES=$verticalnoiseamt MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$verticalnoiseamt < 0" | bc`
					   test2=`echo "$verticalnoiseamt > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- VERTICALLINES=$verticalnoiseamt MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-B)    # get bandingamt
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID VERTICALBANDS SPECIFICATION ---"
					   checkMinus "$1"
					   bandingamt=`expr "$1" : '\([0-9]*\)'`
					   [ "$bandingamt" = "" ] && errMsg "--- VERTICALBANDS=$bandingamt MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$bandingamt < 0" | bc`
					   test2=`echo "$bandingamt > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- VERTICALBANDS=$bandingamt MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-M)    # get backgroundamt
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BACKGROUNDMIX SPECIFICATION ---"
					   checkMinus "$1"
					   backgroundamt=`expr "$1" : '\([0-9]*\)'`
					   [ "$backgroundamt" = "" ] && errMsg "--- BACKGROUNDMIX=$backgroundamt MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$backgroundamt < 0" | bc`
					   test2=`echo "$backgroundamt > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- BACKGROUNDMIX=$backgroundamt MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-T)    # get  bordertype
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BORDERTYPE SPECIFICATION ---"
					   checkMinus "$1"
					   bordertype=`echo "$1" | tr '[A-Z]' '[a-z]'`
					   case "$bordertype" in 
					   		none|n) bordertype=none ;;
					   		torn|t) bordertype=torn;;
					   		round|rounded|r) bordertype=round;;
					   		*) errMsg "--- BORDERTYPE=$bordertype IS AN INVALID VALUE ---"  ;;
					   esac
					   ;;
				-W)    # get borderwidth
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BORDERWIDTH SPECIFICATION ---"
					   checkMinus "$1"
					   borderwidth=`expr "$1" : '\([0-9]*\)'`
					   [ "$borderwidth" = "" ] && errMsg "--- BORDERWIDTH=$borderwidth MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$borderwidth < 0" | bc`
					   test2=`echo "$borderwidth > 100" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- BORDERWIDTH=$borderwidth MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-R)    # get borderrounding
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BORDERROUNDING SPECIFICATION ---"
					   checkMinus "$1"
					   borderrounding=`expr "$1" : '\([0-9]*\)'`
					   [ "$borderrounding" = "" ] && errMsg "--- BORDERROUNDING=$borderrounding MUST BE A NON-NEGATIVE INTEGER VALUE (with no sign) ---"
					   test1=`echo "$borderrounding < 0" | bc`
					   test2=`echo "$borderrounding > 50" | bc`
					   [ $test1 -eq 1 -o $test2 -eq 1 ] && errMsg "--- BORDERROUNDING=$borderrounding MUST BE AN INTEGER BETWEEN 0 AND 50 ---"
					   ;;
				-C)    # get bordercolor
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID BORDERCOLOR SPECIFICATION ---"
					   checkMinus "$1"
					   bordercolor="$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
	if [ $# -eq 3 ]; then
		infile="$1"
		backgroundfile="$2"
		outfile="$3"
	elif [ $# -eq 2 ]; then
		infile="$1"
		outfile="$2"
		backgroundfile=""
	else
		backgroundfile=""
	fi
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/vintage1_1_$$.mpc"
tmpB1="$dir/vintage1_1_$$.cache"
tmpA2="$dir/vintage1_2_$$.mpc"
tmpB2="$dir/vintage1_2_$$.cache"
trap "rm -f $tmpA1 $tmpB1 $tmpA2 $tmpB2;" 0
trap "rm -f $tmpA1 $tmpB1 $tmpA2 $tmpB2; exit 1" 1 2 3 15
trap "rm -f $tmpA1 $tmpB1 $tmpA2 $tmpB2; 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 vintage1
# with IM 6.7.4.10, 6.7.6.10, 6.8.3.3, 6.8.3.8 6.8.3.9 6.8.4.3 6.8.4.6
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
# but to keep the same look, must use colorspace rec601luma via -intensity, since now colorspace gray is rec709luma
# also correct for -tint
if [ "$im_version" -gt "06080504" ]; then
	setcspace="-intensity rec601luma"
	setcspace2="-set colorspace sRGB"
	graycorrect="-intensity rec601luma"
else
	setcspace=""
	setcspace2=""
	graycorrect=""
fi


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

ww=`identify -ping -format "%w" $tmpA1`
hh=`identify -ping -format "%h" $tmpA1`
mindim=`convert xc: -format "%[fx:min($ww,$hh)]" info:`


if [ "$backgroundfile" != "" ]; then
	convert -quiet -regard-warnings "$backgroundfile" +repage "$tmpA2" ||
		errMsg "--- FILE $backgroundfile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO SIZE ---"
fi

# process for color change
convert \( $tmpA1 -fill "$tintcolor" $graycorrect -tint $tintamt +level 0x90% \) \
	\( -clone 0 -fill "$colorizecolor" -colorize 100% -alpha set -channel A -evaluate set $colorizeamt% +channel \) \
	-compose multiply -composite \
	\( -clone 0 -fill "$blackcolor" -colorize 100% -channel A -evaluate set $blackcoloramt% +channel \) \
	-compose lighten -composite -brightness-contrast ${brightness}x${contrast} \
	$tmpA1


# add noise
if [ "$noiseamt" != "0" ]; then
	noiseamt=`convert xc: -format "%[fx:$noiseamt/100]" info:`
	convert $tmpA1 -seed $noiseseed -attenuate $noiseamt +noise gaussian $tmpA1
fi

# add vertical noise
if [ "$verticalnoiseamt" != "0" ]; then
	# note need to use non-linear (rather than linear) gray image to avoid 
	# (bug driven) lower contrast results from versions 6.8.3.10 through 6.8.4.4
	# could have used gray50, but decided to keep gray(50%) and add -colorspoce sRGB
	# which does not seem to alter results prior to 6.7.7.7
	convert $tmpA1 \
		\( -size ${ww}x1 xc:"gray(50%)" $setcspace2 \
			-seed $vertnoiseseed -attenuate 15 +noise uniform \
			$setcspace -colorspace gray -resize ${ww}x${hh}\! \
			-alpha set -channel A -evaluate set $verticalnoiseamt% +channel \) \
		-compose overlay -composite \
	$tmpA1
fi

# add banding
if [ "$bandingamt" != "0" ]; then
	convert $tmpA1 \
		\( -size ${ww}x1 -seed $bandseed plasma:fractal \
			$setcspace -colorspace gray -blur 0x$bandingwidth -resize ${ww}x${hh}\! \
			-auto-level -alpha set -channel A -evaluate set $bandingamt% +channel \) \
		-compose overlay -composite \
	$tmpA1
fi
	
	
# add background image
if [ "$backgroundfile" != "" ]; then
	convert $tmpA1 \
		\( $tmpA2 -resize ${ww}x${hh}\! -alpha set -channel A -evaluate set $backgroundamt% +channel \) \
		-compose overlay -composite \
	$tmpA1
fi


# setup vignette
if [ "$vignetteshape" = "vertical" ]; then
	convert -size ${ww}x${hh} xc:black -crop 100x${vignettesize}+0+0% +repage \
		-background white -gravity center -extent ${ww}x${hh} \
		-morphology distance euclidean:4 -auto-level -negate $tmpA2
elif [ "$vignetteshape" = "horizontal" ]; then
	convert -size ${ww}x${hh} xc:black -crop ${vignettesize}x100+0+0% +repage \
		-background white -gravity center -extent ${ww}x${hh} \
		-morphology distance euclidean:4 -auto-level -negate $tmpA2
elif [ "$vignetteshape" = "roundrectangle" ]; then
	xc=`convert xc: -format "%[fx:$ww/2]" info:`
	yc=`convert xc: -format "%[fx:$hh/2]" info:`
	ww2=`convert xc: -format "%[fx:($vignettesize/100)*($ww/2)]" info:`
	hh2=`convert xc: -format "%[fx:($vignettesize/100)*($hh/2)]" info:`
	round=`convert xc: -format "%[fx:min($ww,$hh)*$vignetterounding/100]" info:`
	args="-$ww2,-$hh2 $ww2,$hh2 $round,$round"
	convert -size ${ww}x${hh} xc:white -fill black \
		-draw "translate $xc,$yc roundrectangle $args" -alpha off \
		-morphology Distance Euclidean:4 -auto-level -negate $tmpA2
fi


# add vignette
if [ "$vignetteshape" != "none" ]; then
	convert $tmpA1 \( $tmpA2 +level ${vignettelighten}x100% -blur 0x5 \)  -compose multiply -composite $tmpA1
fi


# add border/frame
if [ "$bordertype" = "torn" ]; then
	psize=$((borderwidth+tornpad))
	# see disperse script
		# create bordercolor image for compositing at the end
		# create white image with black around the inside of the edges
		# create random image, blur, apply sin/cos to RG channel (for GB) and previous image (for R), displace around border, add slight spread for tornroughness
		# composite backgroundcolor original image and dispersed border
	convert $tmpA1 \
		\( -clone 0 -fill "$bordercolor" -colorize 100% \) \
		\( -clone 0 -fill white -colorize 100% -shave ${psize}x${psize} -bordercolor black -border $psize \) \
		\( -clone 0 -seed $tornseed +noise Random -blur 0x$torncurviness \
			$setcspace -colorspace gray -auto-level $setcspace2 \
			-channel R -evaluate sine $torndensity \
			-channel G -evaluate cosine $torndensity \
			-channel RG -separate -clone 2 -insert 0 \
			-define compose:args=${borderwidth}x${borderwidth} \
			-compose displace -composite -interpolate bilinear -spread $tornroughness -blur 0x0.7 \) \
		-delete 2 -swap 0,1 -compose over -composite -trim +repage \
		-gravity center -background "$bordercolor" -extent ${ww}x${hh} \
		$tmpA1

elif [ "$bordertype" = "round" ]; then
	# need special processing for IM before 6.7.6.8 to set up the alpha channel so that it is white before addding black cornerss 
	if [ "$im_version" -lt "06070608" ]; then
		# either of the following work
		# aproc="-matte -channel A -evaluate set 0%"
		aproc="+matte -channel A -evaluate set 100%"
	else
		aproc="-alpha set -channel A"
	fi
	round=`convert xc: -format "%[fx:min($ww,$hh)*$borderrounding/100]" info:`
	convert $tmpA1 \( -clone 0 $aproc -separate +channel \
		\( -size ${round}x${round} xc:black -draw "fill white circle ${round},${round} ${round},0" -write mpr:arc +delete \) \
		\( mpr:arc \) -gravity northwest -composite \
		\( mpr:arc -flip \) -gravity southwest -composite \
		\( mpr:arc -flop \) -gravity northeast -composite \
		\( mpr:arc -rotate 180 \) -gravity southeast -composite \) \
		\( -clone 0 -clone 1 -alpha off -compose copy_opacity -composite \
		-background "$bordercolor" -compose over -flatten \
		-compose over -bordercolor "$bordercolor" -border $borderwidth \) \
		-delete 0,1 $tmpA1

fi


convert $tmpA1 "$outfile"

exit 0
