#!/bin/ksh
#
# $Revision: 1.4 $ $Date: 2012-07-26 17:11:47-04 $
# $Source: /home/vogelke/bin/RCS/center,v $
# $Host: sys7.com $
# $UUID: 25cff5a4-839f-332d-8ba0-c5f46756f991 $
#
# http://www.zazzybob.com/bin/center_string.html
#<center: center a string in a terminal window.
# Usage:
#       center width symbol "string"
# e.g.  center 20 "-" "< TEST >"
# gives ------< TEST >------

PATH=/bin:/usr/bin:/usr/local/bin; export PATH
PROGNAME=$(basename $0)

validate_width() {
   echo "${WIDTH}" | egrep "^[0-9]+$" >/dev/null 2>&1
   if [ "$?" -ne "0" ]; then
     echo "Error: width must be an integer!" >&2
     exit 2
   fi 
}

calculate() {
   STRINGLENGTH=${#STRING}
   TOTALSPACE=$(( WIDTH - STRINGLENGTH ))
   if [ "${STRINGLENGTH}" -gt "${WIDTH}" ]; then
      echo "Error: string longer than width!" >&2
      exit 2
   fi
   HALFSPACE=$(( TOTALSPACE / 2 ))
   if [ "$(( ${TOTALSPACE} % 2 ))" -ne "0" ]; then
       # odd
       LHS=$(( HALFSPACE + 1 ))
   else
       LHS=${HALFSPACE}
   fi
   RHS=${HALFSPACE}
}

print_string() {
   # Are you kidding?  Just do the whole thing in perl...
   LHSYM=$(perl -e "print "%s", '${SYMBOL}'x${LHS};")
   RHSYM=$(perl -e "print "%s", '${SYMBOL}'x${RHS};")
   echo "${LHSYM}${STRING}${RHSYM}"
}

if [ "$#" -ne "3" ]; then
   echo "Usage: ${PROGNAME} width symbol string" >&2
   exit 1
fi

WIDTH="$1"
SYMBOL="$2"
STRING="$3"

validate_width
calculate
print_string

exit 0
