#!/bin/bash
#
# Developed by Fred Weinhaus 10/3/2013 .......... 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: centertrim [-f fuzzval] infile outfile
# USAGE: centertrim [-help]
#
# OPTIONS:
#
# -f     fuzzval      fuzz value (color tolerance) percent for trimming;
#                     float>=0; default=0
#
###
#
# NAME: CENTERTRIM
# 
# PURPOSE: To trim an image so as to preserve the image center.
# 
# DESCRIPTION: CENTERTRIM trims an image so as to preserve the image center 
# based upon the most distant trimmed corner from the center.
# 
# OPTIONS: 
# 
# -f fuzzval ... FUZZVAL is fuzz value (color tolerance) percent associated  
# with trimming. Values are floats greater than or equal to zero. The default=0
# 
# 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
fuzzval=0


# 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 4 ]
	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
					   ;;
				-f)    # fuzzval
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID FUZZVAL SPECIFICATION ---"
					   checkMinus "$1"
					   fuzzval=`expr "$1" : '\([.0-9]*\)'`
					   [ "$fuzzval" = "" ] && errMsg "--- FUZZVAL=$fuzzval MUST BE A NON-NEGATIVE FLOATING POINT VALUE (with no sign) ---"
					   test=`echo "$fuzzval < 0" | bc`
					   [ $test -eq 1 ] && errMsg "--- FUZZVAL=$fuzzval MUST BE A NON-NEGATIVE FLOATING POINT VALUE ---"
					   ;;
				 -)    # 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 temporary images
tmpA1="$dir/centertrim_1_$$.mpc"
tmpA2="$dir/centertrim_1_$$.cache"
trap "rm -f $tmpA1 $tmpA2;" 0
trap "rm -f $tmpA1 $tmpA2; exit 1" 1 2 3 15
trap "rm -f $tmpA1 $tmpA2; exit 1" ERR


# read the input image 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  ---"


# get width, height and center of image
ww=`convert -ping "$infile" -format "%w" info:`
hh=`convert -ping "$infile" -format "%h" info:`
cx=`convert xc: -format "%[fx:($ww/2)]" info:`
cy=`convert xc: -format "%[fx:($hh/2)]" info:`

# get trim information
triminfo=`convert "$infile" -fuzz $fuzzval% -format "%@" info:`
#echo "triminfo=$triminfo"
wt=`echo "$triminfo" | cut -d+ -f1 | cut -dx -f1`
ht=`echo "$triminfo" | cut -d+ -f1 | cut -dx -f2`
xoff=`echo "$triminfo" | cut -d+ -f2`
yoff=`echo "$triminfo" | cut -d+ -f3`
#echo "ww=$ww; hh=$hh; cx=$cx; cy=$cy; wt=$wt; ht=$ht; xoff=$xoff; yoff=$yoff"

# get distances from image center to trimmed corners
d1x=`convert xc: -format "%[fx:(abs($xoff-$cx))]" info:`
d1y=`convert xc: -format "%[fx:(abs($yoff-$cy))]" info:`
d2x=`convert xc: -format "%[fx:(abs($xoff+$wt-$cx))]" info:`
d2y=`convert xc: -format "%[fx:(abs($yoff-$cy))]" info:`
d3x=`convert xc: -format "%[fx:(abs($xoff+$wt-$cx))]" info:`
d3y=`convert xc: -format "%[fx:(abs($yoff+$ht-$cy))]" info:`
d4x=`convert xc: -format "%[fx:(abs($xoff-$cx))]" info:`
d4y=`convert xc: -format "%[fx:(abs($yoff+$ht-$cy))]" info:`
d1=`convert xc: -format "%[fx:(hypot($d1x,$d1y))]" info:`
d2=`convert xc: -format "%[fx:(hypot($d2x,$d2y))]" info:`
d3=`convert xc: -format "%[fx:(hypot($d3x,$d3y))]" info:`
d4=`convert xc: -format "%[fx:(hypot($d4x,$d4y))]" info:`

# get max distance
dmax=`convert xc: -format "%[fx:max(max(max($d1,$d2),$d3),$d4)]" info:`
#echo "d1=$d1; d2=$d2; d3=$d3; d4=$d4; dmax=$dmax"

# set up crop arguments
if [ "$d1" = "$dmax" ]; then 
	wd=`convert xc: -format "%[fx:2*$d1x]" info:`
	ht=`convert xc: -format "%[fx:2*$d1y]" info:`
	xo=`convert xc: -format "%[fx:($xoff)]" info:`
	yo=`convert xc: -format "%[fx:($yoff)]" info:`
elif [ "$d2" = "$dmax" ]; then 
	wd=`convert xc: -format "%[fx:2*$d2x]" info:`
	ht=`convert xc: -format "%[fx:2*$d2y]" info:`
	xo=`convert xc: -format "%[fx:($cx-$d2x)]" info:`
	yo=`convert xc: -format "%[fx:($yoff)]" info:`
elif [ "$d3" = "$dmax" ]; then 
	wd=`convert xc: -format "%[fx:2*$d3x]" info:`
	ht=`convert xc: -format "%[fx:2*$d3y]" info:`
	xo=`convert xc: -format "%[fx:($cx-$d3x)]" info:`
	yo=`convert xc: -format "%[fx:($cy-$d3y)]" info:`
elif [ "$d4" = "$dmax" ]; then 
	wd=`convert xc: -format "%[fx:2*$d4x]" info:`
	ht=`convert xc: -format "%[fx:2*$d4y]" info:`
	xo=`convert xc: -format "%[fx:($xoff)]" info:`
	yo=`convert xc: -format "%[fx:($cy-$d4y)]" info:`
fi
#echo "wd=$wd; ht=$ht; xo=$xo; yo=$yo;"

# crop image
convert $infile -crop ${wd}x${ht}+${xo}+${yo} +repage "$outfile"

exit 0