#!/bin/bash

# Uppercase First Letter of Each Word.bash
# Sun Jul 11 17:40:58 PDT 2010
# Chieh Cheng
# http://www.CynosureX.com/

# GNU General Public License (GPL) Version 2, June 1991

  scriptDir=`dirname "$0"`
  scriptName=`basename "$0"`

function _cap ()
{
  _upr "$1"
  _CAP=$_UPR${1#?}
}

function _capwords ()
{
  unset _CAPWORDS
  set -f
  for word in $*
  do
    _cap "$word"
    _CAPWORDS="$_CAPWORDS${_CAPWORDS:+ }$_CAP"
  done
}

function _upr ()
{
    _UPR=
    case $1 in
        a*) _UPR=A ;;        b*) _UPR=B ;;
        c*) _UPR=C ;;        d*) _UPR=D ;;
        e*) _UPR=E ;;        f*) _UPR=F ;;
        g*) _UPR=G ;;        h*) _UPR=H ;;
        i*) _UPR=I ;;        j*) _UPR=J ;;
        k*) _UPR=K ;;        l*) _UPR=L ;;
        m*) _UPR=M ;;        n*) _UPR=N ;;
        o*) _UPR=O ;;        p*) _UPR=P ;;
        q*) _UPR=Q ;;        r*) _UPR=R ;;
        s*) _UPR=S ;;        t*) _UPR=T ;;
        u*) _UPR=U ;;        v*) _UPR=V ;;
        w*) _UPR=W ;;        x*) _UPR=X ;;
        y*) _UPR=Y ;;        z*) _UPR=Z ;;
         *) _UPR=${1%${1#?}} ;;
    esac
}

function process ()
{
  string="$1"

  echo "${string}" | tr " " "\n" | awk ' { out = out" "toupper(substr($0,1,1))substr($0,2) } END{ print substr(out,2) } '
}

function usage ()
{
  echo "  Usage:   \"${scriptName}\" \"string\""
  echo
  echo "             Use a '-' in place of the string to read"
  echo "             from standard input (pipe)."
}

  if [ $# -eq 1 ]
  then
    string="$1"

    if [ "${string}" = "-" ]
    then
      while read line
      do
        process "${line}"
      done
    else
      process "${string}"
    fi
  else
    usage
  fi
