#!/bin/sh
#
# ppmmargin - add a margin to a PNM image
#
# Copyright (C) 1991 by Jef Poskanzer.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted, provided
# that the above copyright notice appear in all copies and that both that
# copyright notice and this permission notice appear in supporting
# documentation.  This software is provided "as is" without express or
# implied warranty.

color=""
plainopt=""

# Parse args.
while true ; do
    case "$1" in
        -version|--version )
        pnmpad --version; exit $?;
        ;;
        -p|-pl|-pla|-plai|-plain )
        plainopt="-plain"
        shift
        ;;
        -w|-wh|-whi|-whit|-white )
        color="rgbi:1/1/1"
        shift
        ;;
        -b|-bl|-bla|-blac|-black )
        color="rgbi:0/0/0"
        shift
        ;;
        -c|-co|-col|-colo|-color )
        shift
        if [ ! ${1-""} ] ; then
            echo "-color requires a value" 1>&2
            exit 1
        fi
        color="$1"
        shift
        ;;
        -* )
        echo "unrecognized option '$1'.  Valid options are -color, -white, and -black" 1>&2
        exit 1
        ;;
        * )
        break
        ;;
    esac
done

if [ ! ${1-""} ] ; then
    echo "missing size argument" 1>&2
    exit 1
fi
size="$1"
shift

case $size in
    ''|*[!0-9]*)
        echo "Size argument '$size' is not a whole number" 1>&2
        exit 1
        ;;
esac

if [ ${2-""} ] ; then
    echo "too many arguments" 1>&2
    exit 1
fi

# TODO: This code does not consider the case when the input file is specified
# and there is also input coming in from a pipe.

if [ $size -eq 0 ] ; then
    # Zero margin; just copy input to output
    pamtopnm $plainopt $@;
else
    if test "$color" = ''; then
        pnmpad $plainopt -detect-background \
            -left=$size -right=$size -top=$size -bottom=$size $@
    else
        pnmpad $plainopt -color $color \
            -left=$size -right=$size -top=$size -bottom=$size $@
    fi
fi



