#!/bin/sh

# program number
# script to add line numbers to a file

FLAG=false
DELIMIT=')'
OUT='1'
IFS=''     # do not lose leading whitespace

while getopts ":d:o:" INPUT
do
    case $INPUT in
        d) DELIMIT=$OPTARG;;
        o) FLAG=true; OUT='4'; FILE=$OPTARG;;
        *) echo "Error bad option $INPUT" >&2 ;exit -1;;
    esac
done

# remove the command line options
shift $(( OPTIND - 1 ))

if [ $# -lt 1 ]
then
    echo "Usage: number [-o outfile] [-d 'delimiter'] file" >&2
    exit 1
fi

LINENUM=1

# open the file(s)
exec 3< $1
if [ $FLAG = true ]
then
    exec 4> $FILE
fi

# loop thru the file and build line numbers
while read LINEIN <&3
do
    #  where do we print it?
    if [ $FLAG = true ]
    then
        printf "%3d%s %s\n" ${LINENUM} ${DELIMIT} "${LINEIN}" >> $FILE
    else
        printf "%3d%s %s\n" ${LINENUM} ${DELIMIT} "${LINEIN}"
    fi 
    LINENUM=$(( $LINENUM + 1 ))
done

# now let's close the files
exec 3<&-
if [ $FLAG = true ]
then
    exec 4>&-
fi
exit 0     
