#!/usr/bin/env bash
#
#   txt2png 
#     - convert a text input file to one or more PNG files
#
#   Copyright (c) 2004-2008 W. Wershofen <itconsult at wershofen.de>
#   Copyright (c) 2009,2012 Joo Martin <joomart2009 at users.sf.net>
#   Copyright (c) 2010-2011 Joo Martin & Markus Kohm <kohm at users.sf.net>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This package is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Changes:
#
#   2004-01-26  Wolfgang Wershofen
#               * initial version
#   2010-06-21  Markus Kohm
#               * renamed dvdwizardrc into dvdwizard_common
#               * usage of gettext features for multilanguage ui
#                 -several `echo' replaced by `printf'
#
# -------------------------------------------------------------------------

#
# i18n
#
export TEXTDOMAIN=dvdwizard
export TEXTDOMAINDIR="@LOCALEDIR@"

# We need some sub-routines from dvdwizard_common.
# This file must be found at PATH.
#
. dvdwizard_common || {
    echo $"FATAL ERROR: could not execute common function file \`dvdwizard_common'!
You have to install \`dvdwizard_common' somewhere at PATH." >&2
    exit 1
}

# Usage message
#
usagetext=$"
Usage:	${thisscript} [options] text-file
	${thisscript} -h|--help
	${thisscript} -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'.       [\`txt2png_out']
-s | --size	Defines the size of the output png(s) in pixels, 
		e.g. -s 300x400.                                      [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 point)   [16 point]
-c | --color 	Font-Color to be used, valid Image-Magick Color-Code
		(e.g. white, black, rgb(255,128,127))                   [black]
-v | --version	print version information
-h | --help	print this lot out
"

# ------------------------------
# Main Processing
#
#
# Is help wanted?
#
test_versionhelp "$@"

#
# 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
    error_help $"No input file specified."
else
    if [ -r "$txtfile" -a ! -d "$txtfile" ]; then
	:
    else
	error_help $"Input file \`%s' is a directory or is not readable." \
	    "$txtfile"
    fi 
fi

#
# 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"

#
# If we have created an empty image
#
[ $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
