#!/bin/bash
#
# txt2png - convert a text input file to one or more PNG files
#
this_version="Version 0.1"
#
# Version   0.1 written by Wolfgang Wershofen (mailto: itconsult at wershofen.de)
#
# See TOOLS in the dvdwizard tarball for info about needed tools and programs
#
usage()
{
 cat <<EOF
Usage:	`basename $0` [options] text-file
	`basename $0` -h|--help
	`basename $0` -v|--version

currently supported options:
----------------------------
-o | --output	Basename of Output files. Will be appended by .png, if only
		one png file is created, else appended by <n>.png, where <n>
		is a two digit number starting with '01'.
		If omitted, defaults to "txt2png_out"
-s | --size	Defines the size of the output png(s) in pixels, e.g. -s 300x400.
		If ommited, defaults to "500x500".
-t | --fonttype Defines the font type to be used (see convert -list type
		for possible values for your system)
-f | --fontsize Defines the size of the font to be used (in Points)
		Default: 16 Point
-c | --color 	Font-Color to be used, valid Image-Magick Color-Code
		(e.g. white, black, rgb(255,128,127)), Default: black
-v | --version	print version information
-h | --help	print this lot out

EOF
exit 1
}

# ------------------------------
# Main Processing
#
#
# Is help wanted?
#
case "$1" in
  	-h|--help)
   	    usage
  	;;
  	-v|--version)
 	    echo "`basename $0` $this_version" 
        exit 0
  	;;
esac

# We need some sub-routines from dvdwizardrc
# This file must reside in the same directory as the called script
# Should maybe go into a directory like /usr/local/share/dvdwizard
# but this would require an installation procedure - maybe in some
# later version.
#
rcfile="`dirname $0`/dvdwizardrc"
if [ -e "$rcfile" -a -r "$rcfile" ]; then
	. "$rcfile"
else
	echo "dvdwizardrc not found or is not readable. Aborting" >&2
    exit 1
fi

#
# Ok, first define some default values
#
opat="txt2png_out"
size="500x500"
fontsize=$MFONTSIZE
fontcolor="$TEXTCOLOR"
fonttype="$MFONTTYPE"
txtfile=""
[ -z $TMPDIR ] && TMPDIR="/tmp"

#
# Check for needed tools
#
check_tools

#
# Now deal with command line arguments
#
while [ -n "$*" ]; do
    case "$1" in
		-o|--output)
 	    	shift
	    	opat="$1"
	    	shift
  		;;
  		-s|--size)
	    	shift
   	    	size="$1"
   	    	shift
 	 	;;
  		-t|--fonttype)
	    	shift
   	    	fonttype="$1"
   	    	shift
 	 	;;
  		-f|--fontsize)
	    	shift
   	    	fontsize="$1"
   	    	shift
 	 	;;
  		-c|--color)
	    	shift
   	    	fontcolor="$1"
   	    	shift
 	 	;;
  		*)
		    txtfile="$1"
   	    	shift
	  	;;
    esac
done

#
# Check, if input file is valid
#
if [ -z "$txtfile" ]; then
	echo "No input file specified. Aborting"
    echo "See $thisscript -h for more infos"
    exit 1
else
	if [ -r "$txtfile" -a ! -d "$txtfile" ]; then
		:
	else
		echo "Input file $txtfile is a directory or is not readable. Aborting"
        echo "See $thisscript -h for more infos"
        exit 1
	fi 
fi >&2

#
# Define some dimensions
#
[ ! -z $fonttype ] && fonttype="-font $fonttype"
tmpindex=0
maxwidth=$(echo $size | cut -d'x' -f1)
let "maxwidth-=5"
maxHeight=$(echo $size | cut -d'x' -f2)
let "maxHeight-=5"
charWidth=$(convert -size $size xc:none -fill $fontcolor $fonttype -pointsize $fontsize \
			-gravity center -annotate +0+0 "m" \
			-trim -border 2 png:- | identify -format %w -)
charHeight=$(convert -size $size xc:none -fill $fontcolor $fonttype -pointsize $fontsize \
			-gravity center -annotate +0+0 "Tg" \
			-trim -border 1 png:- | identify -format %h -)
let "maxChars=$maxwidth/$charWidth"
let "spaceheight=$charHeight/2"

#
# Build empty canvas
#
rm -f "$opat"[0-9][0-9].png # 2>/dev/null
cnum=1
[ $cnum -lt 10 ] && thispng="${opat}0$cnum.png" || thispng="${opat}$cnum.png"
convert -size $size xc:none "$thispng"
linepos=1

#
# Okay, lets read the textfile line by line
# Wordwrap long lines, ignore empty lines, add additional space after each
# line break
#
while read inline; do
	outline=""
	wordnum=$(echo "$inline" | wc -w)
	# Omit blank lines
	if [ $wordnum -ne 0 ]; then 
		
		for w in $(seq 1 $wordnum); do
			word=$(echo "$inline" | cut -d' ' -f$w)	
			[ -z "$outline" ] && newline=$word || newline="$outline $word"
			newChars=$(echo "$newline" | wc -c)
			let "newChars-=1"
			
			if [ $newChars -ge $maxChars ]; then
				thiswidth=$(convert -size $size xc:none -fill $fontcolor $fonttype -pointsize $fontsize \
							-gravity northwest -annotate +0+0 "$newline" \
							-trim -bordercolor white -border 5 png:- | \
							identify -format %w -)
				if [ $thiswidth -le $maxwidth ]; then
					outline="$newline"
				else
					[ -z "$outline" ] && outline="$newline"
					mogrify -fill $fontcolor $fonttype -pointsize $fontsize \
						-gravity northWest -annotate +1+$linepos "$outline" "$thispng"
					[ "$outline" == "$newline" ] && outline="" || outline="$word"
					let "linepos+=charHeight"
					let nextpos="$linepos+$charHeight"
					if [ $nextpos -gt $maxHeight ]; then
						let "cnum+=1"	
						[ $cnum -lt 10 ] && thispng="${opat}0$cnum.png" || thispng="${opat}$cnum.png"
						convert -size $size xc:none "$thispng"
						linepos=1
					fi
				fi
			else
				outline="$newline"
			fi
		done			
		if [ ! -z "$outline" ]; then
			mogrify -fill $fontcolor $fonttype -pointsize $fontsize \
				-gravity northWest -annotate +1+$linepos "$outline" "$thispng"
			[ "$outline" == "$newline" ] && outline="" || outline="$word"
			let "linepos+=charHeight"
			let nextpos="$linepos+$charHeight"
			if [ $nextpos -gt $maxHeight ]; then
				let "cnum+=1"	
				[ $cnum -lt 10 ] && thispng="${opat}0$cnum.png" || thispng="${opat}$cnum.png"
				convert -size $size xc:none "$thispng"
				linepos=1
			fi
		fi	
		[ $linepos -gt 1 ] && let "linepos+=$spaceheight"
		let nextpos="$linepos+$charHeight"
		if [ $nextpos -gt $maxHeight ]; then
			let "cnum+=1"
			[ $cnum -lt 10 ] && thispng="${opat}0$cnum.png" || thispng="${opat}$cnum.png"
			convert -size $size xc:none "$thispng"
			linepos=1
		fi
	fi
done <"$txtfile"

#
# Wenn leeres Bild erzeugt wurde
#
[ $linepos -eq 1 ] && rm -f "$thispng"

#
# Add shadow underneath text
#
for i in "$opat"[0-9][0-9].png; do
	convert "$i" -negate "$i" \
		-gravity southeast -geometry +1+1 -composite "$i"
done

exit 0
