#!/bin/bash
#
# Developed by Fred Weinhaus 2/19/2013 .......... revised 5/3/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: thermography [-l lowpt] [-h highpt] infile outfile
# USAGE: thermography [-help]
#
# OPTIONS:
#
# -l     lowpt      low point value on color table; float; 0<=integer<=100; 
#                   default=0
# -h     highpt     hight point value on color table; float; 0<=integer<=100; 
#                   default=100
#
###
#
# NAME: THERMOGRAPHY 
# 
# PURPOSE: To simulate a picture taken with a thermal imaging camera.
# 
# DESCRIPTION: THERMOGRAPHY simulates a picture taken with a thermal imaging 
# camera. The low point and high point can be used to shift and scale the  
# color spectrum table.
# 
# OPTIONS: 
# 
# -l lowpt ... LOWPT is the low point on the color table (violet end) to use  
# to stretch and/or scale the color spectrum used. Values are integers between 
# 0 and 100. The default=0 (full violet).
# 
# -h highpt ... HIGHPT is the high point on the color table (red end) to use  
# to stretch and/or scale the color spectrum used. Values are integers between 
# 0 and 100. The default=100 (full red).
# 
# 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
lowpt=0			# low point percent; 0<=integer<=100; default=0
highpt=100		# high point percent 0<=integer<=100; default=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 6 ]
	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
					   ;;
				-l)    # get lowpt
					   shift  # to get the next parameter - radius,sigma
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID LOWPT SPECIFICATION ---"
					   checkMinus "$1"
					   lowpt=`expr "$1" : '\([0-9]*\)'`
					   [ "$lowpt" = "" ] && errMsg "--- LOWPT=$lowpt MUST BE A NON-NEGATIVE INTEGER ---"
					   testA=`echo "$lowpt < 0" | bc`
					   testB=`echo "$lowpt > 100" | bc`
					   [ $testA -eq 1 -o $testB -eq 1 ] && errMsg "--- LOWPT=$lowpt MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				-h)    # get highpt
					   shift  # to get the next parameter - radius,sigma
					   # test if parameter starts with minus sign 
					   errorMsg="--- INVALID HIGHPT SPECIFICATION ---"
					   checkMinus "$1"
					   highpt=`expr "$1" : '\([0-9]*\)'`
					   [ "$highpt" = "" ] && errMsg "--- HIGHPT=$highpt MUST BE A NON-NEGATIVE INTEGER ---"
					   testA=`echo "$highpt < 0" | bc`
					   testB=`echo "$highpt > 100" | bc`
					   [ $testA -eq 1 -o $testB -eq 1 ] && errMsg "--- HIGHPT=$highpt MUST BE AN INTEGER BETWEEN 0 AND 100 ---"
					   ;;
				 -)    # 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/thermography_1_$$.mpc"
tmpB1="$dir/thermography_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

# 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 followpting was determined from various version tests using thermography.
# with IM 6.7.4.10, 6.7.6.10, 6.8.3.2
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 into the temporary cached image and test if valid
convert -quiet "$infile" $setcspace -colorspace gray +repage "$tmpA1" ||
	errMsg "--- FILE $infile DOES NOT EXIST OR IS NOT AN ORDINARY FILE, NOT READABLE OR HAS ZERO size  ---"

#convert lowpt and highpt to range and offset
range=`convert xc: -format "%[fx:round(1000*($highpt-$lowpt)/100)]" info:`
offset=`convert xc: -format "%[fx:round(1000*$lowpt/100)]" info:`

# note added $setcspace before -clut to fix bug between 6.8.4.0 and 6.8.4.10
convert $tmpA1 \
	\( -size 1x1 xc:blueviolet xc:blue xc:cyan xc:green1 xc:yellow xc:orange xc:red \
		+append -filter Cubic -resize 1000x1! -crop ${range}x${range}+${offset}+0 +repage \
		-resize 1000x1! \) \
	$setcspace -clut "$outfile"


exit 0

	
