#!/bin/sh
#
#	This script is part of rtfdtohtml.
#	Copyright (c) 1996  Elmar Ludwig - Universitaet Osnabrueck
#
#	Convert tiff to gif or png (needs ImageMagick, tiffutils, tiff2png?).

gamma=${RTFDGAMMA:-2.2}

if [ $IMG_TYPE = gif ]; then
    convert_opts="-interlace LINE +comment"
else
    convert_opts="+matte -interlace NONE -gamma $gamma +comment"
fi

[ "$EPS" ] && exec convert $convert_opts TIFF:"${1-"-"}" $IMG_TYPE:-

tmp=/tmp/$$
trap 'rm -f $tmp.tiff $tmp.tif ${tmp}_*.tif $tmp.png $tmp.info; exit 2' 1 2 3 15

cat ${1+"$1"} >$tmp.tiff
tiffcp -c none $tmp.tiff $tmp.tif
tiffinfo $tmp.tif >$tmp.info

dir=
if [ "`sed -n -e '/^TIFF Directory/x' -e //p $tmp.info`" ]; then
    dir=`sed -n 's/^  Samples\/Pixel: //p' $tmp.info | grep -n . |
    sed -e 's/\([^:]*\):\(.*\)/\2:\1/' -e 'y/123456789/abcdefghi/' |
    sort -r | sed -n '1s/^.*://p'`
fi

alpha=
fgrep '<assoc-alpha>' $tmp.info >/dev/null && alpha=1

if [ "$dir" ]; then
    tiffsplit $tmp.tif ${tmp}_
    if [ "$alpha" ]; then
	tiff2png -gamma $gamma ${tmp}_a$dir.tif $tmp.png
    else
	mv ${tmp}_a$dir.tif $tmp.tif
    fi
else
    [ "$alpha" ] && tiff2png -gamma $gamma $tmp.tif $tmp.png
fi

if [ -z "$alpha" ]; then
    convert $convert_opts $tmp.tif $IMG_TYPE:-
    result=$?
elif [ $IMG_TYPE = gif ]; then
    montage $convert_opts +geometry +shadow +label +frame -background White\
    -compose over $tmp.png GIF:-
    result=$?
else
    montage +compress +geometry +shadow +label +frame -background White\
    -compose over $tmp.png PNG:- | convert $convert_opts PNG:- PNG:-
    result=$?
fi

rm -f $tmp.tiff $tmp.tif ${tmp}_*.tif $tmp.png $tmp.info
exit $result
