#!/bin/sh
#
# Example script to sum the first N positive integers
#
# Author: Bill Slough
#

function usage()
{
    # Display proper usage on the standard error file
    cat 1>&2 << EOF
Usage: $PROGRAM n
EOF
}


function usage_and_exit()
{
    # The function name says it all!
    usage
    exit $1
}


function bad_input_and_exit()
{
    # Display error message on the standard error file and quit
    echo "$PROGRAM: non-negative argument expected." 1>&2
    exit 1
}


function summation()
{
    # Determines the sum 1 + 2 + ... + $1, placing the sum in RESULT 
    sum=0
    if [ $1 -ge 1 ]; then
	for i in `jot - 1 $1`; do
	    sum=`echo "$sum + $i" | bc`
	done
    fi
    RESULT=$sum
}


function is_integer()
{
    # Does $1 meet the requirements of an unsigned integer?
    # Returns 0 if yes; 1 if no
    echo "$1" | grep -Eq "^[0-9]+$"
    return $?

}

# Determine the script name
PROGRAM=`basename $0`

# Was exactly one command-line argument given?
if [ $# -ne 1 ]; then
    usage_and_exit 1
fi

# Looks good so far; is the argument a non-negative integer?
if $(is_integer $1); then
    # OK; everything looks good ... compute the sum
    summation $1
    echo "The sum of the first $1 positive integers is $RESULT"
    exit 0    
else
    # Bad argument: non-negative integer argument expected
    bad_input_and_exit
fi