#! /bin/sh

if [ -z "$1" ] || [ -n "$2" ]; then
       echo >&2 Usage: ${0##*/} \(percent border to add\)
       echo >&2 Adds specified amount of border to PPM image.
       echo >&2 Adds additional border if necessary to get 3:2 or 2:3 aspect ratio.
       exit 0
       fi
BorderPercent=$1
cat > AddBorder-Temp.ppm
Dims=$(pnmfile AddBorder-Temp.ppm)
Dims=${Dims##*, }
Dims=${Dims%% max*}
InputWidth=${Dims% by*}
InputHeight=${Dims#*by }
if [ $(expr 2 \* $InputHeight) -gt $(expr 3 \* $InputWidth) ]; then
       OutputWidth=$(expr \( \( $InputHeight \* \( 100 + $BorderPercent \) + 50 \) / 100 + 2 \) / 3 \* 2)
       OutputHeight=$(expr \( \( $InputHeight \* \( 100 + $BorderPercent \) + 50 \) / 100 + 2 \) / 3 \* 3)
elif [ $InputHeight -gt $InputWidth ]; then
       OutputWidth=$(expr \( \( $InputWidth \* \( 100 + $BorderPercent \) + 50 \) / 100 + 1 \) / 2 \* 2)
       OutputHeight=$(expr \( \( $InputWidth \* \( 100 + $BorderPercent \) + 50 \) / 100 + 1 \) / 2 \* 3)
elif [ $(expr 2 \* $InputWidth) -gt $(expr 3 \* $InputHeight) ]; then
       OutputWidth=$(expr \( \( $InputWidth \* \( 100 + $BorderPercent \) + 50 \) / 100 + 2 \) / 3 \* 3)
       OutputHeight=$(expr \( \( $InputWidth \* \( 100 + $BorderPercent \) + 50 \) / 100 + 2 \) / 3 \* 2)
else
       OutputWidth=$(expr \( \( $InputHeight \* \( 100 + $BorderPercent \) + 50 \) / 100 + 1 \) / 2 \* 3)
       OutputHeight=$(expr \( \( $InputHeight \* \( 100 + $BorderPercent \) + 50 \) / 100 + 1 \) / 2 \* 2)
       fi
echo >&2 ${0##*/}: Padding $InputWidth\*$InputHeight to $OutputWidth\*$OutputHeight
ppmmake rgb:C8/C8/C8 $OutputWidth $OutputHeight \
       | pnmpaste AddBorder-Temp.ppm \
       $(expr \( $OutputWidth - $InputWidth \) / 2) $(expr \( $OutputHeight - $InputHeight \) / 2)
rm AddBorder-Temp.ppm