#!/bin/sh
scriptname=$(basename $0)
help ()
{
	echo "Search png images not fitting in a hex"
	echo
	echo "$scriptname [option] [directory1 directory2 ...]"
	echo "-m, --mask file      choose which image use as mask"
	echo "                       (default = alphamask.png)"
	echo "-a, --anim           skip most animations images (containing:"
	echo "                       -attack -defend -melee -ranged -magic -idle"
	echo "                       -die -dying -death -healing -flying -leading)"
	echo "-s, --suffix         skip images with directional or numerical suffix"
	echo "-r, --regex REG      skip images matching the case-insensitive"
    echo "                       regular expression REG (posix-extended)"
	echo "-f, --format         skip images which are not in 72x72 format"
	echo "-q, --quiet          only display results"
	echo
	echo "return numbers of pixels out of the hex for each filename"
	echo "(-1 if the image is not a standard 72x72 image and -f was not used"
}

mask="$(dirname $0)/alphamask.png"
format=0
quiet=0

regex=""
suffix=".*(-n|-s|-w|-e|-ne|-nw|-sw|-se|-[0-9]+)(-|[.]).*"
anim=".*-attack.*|.*-defend.*|.*-melee.*|.*-ranged.*|.*-magic.*|.*-idle.*|.*-die.*|.*-dying.*|.*-death.*|.*-flying.*|.*-leading.*|.*-healing.*"

until [ -z "$1" ]
do
	case $1 in
		-h|--help)
			help
			exit;;
		-m|--mask)
			shift
			mask="$1"
			shift
			continue;;
		-r|--regex)
			shift
			regex="$regex|$1"
			shift
			continue;;
		-a|--anim)
			regex="$regex|$anim"
			shift
			continue;;
		-s|--suffix)
			regex="$regex|$suffix"
			shift
			continue;;
		-f|--format)
			format=1
			shift
			continue;;
		-q|--quiet)
			quiet=1
			shift
			continue;;
	esac

	# record all given directories
	dir="$dir $1"
	shift

done

# if no directory, use current
if [ "$dir" = "" ]
then
	dir='.'
fi

if [ ! -r $mask ]
then
	echo "$scriptname: cannot access $mask: No such file or directory"
	exit 1
fi


if [ "$quiet" = 0 ]
then
	echo "Search 72x72 images not fitting in a hex"
	echo "in directories: $dir"
	echo "Using alphamask image: $mask"
	echo "Skipping files matching regex: $regex"
	echo "Pixels out of hex : filename"
fi

test_img()
{
	if [ `identify -format "%wx%h" $img` != '72x72' ]
	then
		if [ $format = 0 ]
		then
			px=-1
		else
			# mark as ok, because user want to skip bad format
			px=0 
		fi
	else
		px=`composite $mask $img /tmp/tmp_result.png && compare -channel alpha -metric AE $mask /tmp/tmp_result.png /dev/null 2>&1 `
	fi

	if [ "$px" != 0 ]
	then
		echo "$px	: $img"
	fi
}

find $dir -regextype posix-extended -name '*.png' -and -not -iregex "$regex" \
		-print | sort | while read img; do test_img; done

rm -f /tmp/tmp_result.png
exit
