#!/bin/sh

if [ -z $OUTPUTS ]; then
    OUTPUTS=outputs
fi

if [ -d ../.git ]; then
    revision=$(git describe --tags)
    revision="$revision""$TEST_SUFFIX"

    echo "Generating images for revision $revision"
fi

# A dir specific for outputs
mkdir -p "$OUTPUTS"

total=0
for f in "$@"; do
    echo "Running $f";

    if [ "$revision" ]; then
	output="$OUTPUTS"/${f%%.sh}-$revision
    else
	output="$OUTPUTS"/${f%%.sh}
    fi
    basepdf=${f%%.sh}

    export CT_ADD="--name ${basepdf}-%03d"
    NOXPDF=1 sh $f
    if [ -r ${basepdf}-000.pdf ]; then
        nb=0
        for f in ${basepdf}-*.pdf; do
            pp=${f%%.pdf}.ppm
            pdftoppm $f > $pp
            total=$(($total + 1))
            nb=$(($nb+1))
        done

        echo "$nb PDF files were generated"
	echo " -> producing montage outputs"

	if [ -z $BIG ]; then
	    geometry=340x340+4+4
	    density=150
	else
	    geometry=500x500+4+4
	    density=250
	fi
	montage -label %f -frame 5 -background '#336699' \
	    -geometry $geometry -density $density ${basepdf}-*.ppm ${output}.png
	if [ -z $KEEP ]; then
	    echo " -> removing PDF files"
	    rm -f ${basepdf}-*.pdf
	    rm -f ${basepdf}-*.ppm
	fi
	display ${output}.png &
    fi
done

echo "Generated a total of $total PDF files"
