#!/bin/bash
#
# Developed by Fred Weinhaus 12/21/2007 .......... 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: flicker [-d delay] [ -r resize] [-f] [-l] infile1 infile2 ...
# USAGE: flicker [-h or -help]
#
# OPTIONS:
#
# -d     delay        time delay per frame (ms); delay >= 0; default=50
# -r     resize       image resize percentage; resize > 0; 
#                     default=100 (unchanged)
# -l                  disables the labeling of the images
# -f                  saves the animation to file animation.gif
#
###
#
# NAME: FLICKER
# 
# PURPOSE: To display and optionally save an animation of the input images.
# 
# DESCRIPTION: FLICKER automatically displays an animation of the supplied 
# input images and optionally saves the animation to a file. At least two 
# images must be supplied. The main purpose of the script is to make a 
# visual comparison of two (or more) images by rapidly alternating the 
# display of each.
# 
# 
# OPTIONS: 
# 
# 
# -d delay ... DELAY is the time delay in msec between frames in the animation. 
# Values are integers greater than or equal to zero. The default=50. Note that 
# the animation will be created to loop forever. Delay is ignored if a single 
# frame output is to be generated.
# 
# -r resize ... RESIZE allows the animation to made larger or smaller than 
# the input image size. The values are integers greater than 0 representing the 
# resize percentage. The default=100 which leaves the animation the same size as 
# the input image.
# 
# -l ... Disables the labeling of the images.
# 
# -f ... Specifies that the animation is to be saved to a file called animation.gif
# 
# 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
delay=50    # time delay for animation
resize=""   # resize
label="yes" # enables the labeling of the images
save="no"   # save animation to file animation.gif

# 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
else
	while [ $# -gt 0 ]
		do
			# get parameter values
			case "$1" in
		  -h|-help)    # help information
					   echo ""
					   usage2
					   exit 0
					   ;;
				-d)    # delay
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID DELAY SPECIFICATION ---"
					   checkMinus "$1"
					   delay="$1"
					   delaytest=`expr "$delay" : '^[0-9][0-9]*$'`
		   			   delaytestA=`echo "$delay < 1" | bc`
		   			   [ $delaytest -eq 0 ] && errMsg "--- DELAY=$delay MUST BE AN INTEGER ---"
					   [ $delaytestA -eq 1 ] && errMsg "--- DELAY=$delay MUST BE GREATER THAN 0 ---"
					   ;;
				-r)    # resize
					   shift  # to get the next parameter
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID RESIZE SPECIFICATION ---"
					   checkMinus "$1"
					   resize="$1"
					   resizetest=`expr "$resize" : '^[0-9][0-9]*$'`
		   			   resizetestA=`echo "$resize < 1" | bc`
		   			   [ $resizetest -eq 0 ] && errMsg "--- RESIZE=$resize MUST BE AN INTEGER ---"
					   [ $resizetestA -eq 1 ] && errMsg "--- RESIZE=$resize MUST BE GREATER THAN 0 ---"
					   resize="-resize $1%"
					   ;;
				-l)    # label
					   label="no"
					   ;;
				-f)    # save to file
					   save="yes"
					   ;;
				 -)    # STDIN and end of arguments
					   break
					   ;;
				-*)    # any other - argument
					   errMsg "--- UNKNOWN OPTION ---"
					   ;;
				 *)    # end of arguments
					   break
					   ;;
			esac
			shift   # next option
	done
fi


# setup temporary images and auto delete upon exit
tmp0="$dir/flicker_0_$$.miff"
trap "rm -f $tmp0; exit 0" 0
trap "rm -f $tmp0; exit 1" 1 2 3 15

if [ "$label" = "no" ]
	then
	label=""
else
	label="-label %f"
fi

if [ $# -lt 2 ]
	then
	errMsg "--- AT LEAST TWO INPUT IMAGES MUST BE PROVIDED ---"
else
	convert $label "$1" $resize miff:- |\
		montage - -geometry +0+0 -tile 1x1 $tmp0
	shift
	while [ $# -gt 0 ]
		do
		convert $label "$1" $resize miff:- |\
	  		montage - -geometry +0+0 -tile 1x1 miff:- |\
			convert -delay $delay $tmp0 -page +0+0 - -page +0+0 $tmp0
		shift
	done
	if [ "$save" = "yes" ]
		then
		convert $tmp0 -loop 0 animation.gif
	fi
		animate $tmp0
fi
exit 0
