#!/bin/sh

# Warning! Probably broken.

# Generates a sequence of images by spinning and scaling an input
# image. Images must be in Portable aNyMap (pnm) format. You will need
# to modify the variables at the top to produce the effect you want.

# This script depends on python, netpbm, and a handful of standard
# unix utilities. The python dependancy can be replaced by any other
# program that can do floating point math and modular arithmatic (but
# you'll need to edit the script).


############ Variables to modify ############
INFILE=slackware.pnm # input file
NUM=40               # number of output images to generate
MIN=0.0              # minimum scale factor (must be one notch lower
				 # than actual desired minimum scale factor)
MAX=1.6              # maximum scale factor
OUTPUT=transformed   # directory to output transformed images (must
				 # exist and be empty)

############ Functions ############
calc() { echo print "$@" | python; }
scalenum() { calc "$MIN + ($I) * (($MAX-$MIN) / ($NUM))"; }
scaleangle() { calc "360.0 / $NUM * $I"; }

dorotate()
{
    echo Rotated $1 degrees. >&2
    pnmflip -r`calc int\($1 - \($1 % 90\)\)` | pnmrotate `calc $1 % 90`
}

############ Main code ############

trap exit 2 # exit script on ctrl-c

# Generate rotated files
for I in `seq -w $NUM`; do
    FILE="$OUTPUT/${I}.pnm"
    I=`expr $I + 0` # strip leading zero
    cat $INFILE | dorotate `scaleangle $I` | pnmscale `scalenum $I` \
	   > $FILE
done


# Calculates height and width of output images

pnmfile $OUTPUT/* | cut -f2 | cut -d" " -f3,5 | awk '
BEGIN { w=0; h=0; }
{ if ($1 > w) w = $1; if ($2 > h) h = $2; }
END { printf("%d %d\n", w, h); } ' | read DW DH

# Pads all images to same size
for I in $OUTPUT/*; do
    W=`pnmfile $I | cut -f2 | cut -d" " -f3`
    H=`pnmfile $I | cut -f2 | cut -d" " -f5`
    LEFT=`expr "(" $DW - $W ")" / 2`
    RIGHT=`expr $DW - $W - $LEFT`
    TOP=`expr "(" $DH - $H ")" / 2`
    BOTTOM=`expr $DH - $H - $TOP`
    cat $I | pnmpad -left $LEFT -right $RIGHT -top $TOP -bottom $BOTTOM \
	   > ${I}.new
    mv ${I}.new $I
done

