#!/bin/ash
# rustique wc (6/11/00 by A. Costa)
# writes a temp file to count stdIO chars, uses awk and ls...

# Functions

Help()
{
echo "Usage: wc [-clw | -a] [filename]"
exit
}

CleanUp()	# get rid of temp files if necessary
{ 
[ -w "$stdIOfile" ]  &&  rm $stdIOfile 2>/dev/null 
}

Bail()
{
CleanUp
exit 2
}

ShowLine()	# syntax: Showline lines# words# chars# filename
{ 
printf "%7s%10s%12s   %s" "$1" "$2" "$3" "$4"
echo
}

CheckHyphen()
{
if [ $hyphen ]		# Chastise user?...
then
	echo "error: only one stdIO hyphen allowed." >& 2
	Bail
fi
hyphen="-"
}

#Parse options...

for b in "$@"	# Pass 1, get options, wherever they are...
do
	case "Z$b" in
		Z-) CheckHyphen;;
		Z-d) set -x ;;			# debug mode
		Z-a) c=0 lines=0 w=0;;
	        Z-c) c=0;;
		Z-w) w=0;;
		Z-l) lines=0;;
		Z-cw|Z-wc) c=0 w=0;;
		Z-cl|Z-lc) c=0 lines=0;;
		Z-lw|Z-wl) lines=0 w=0;;
		Z-h|Z-?*) Help ;;
		Z*) ;;
	esac
done

# no flagged options?  Then set 'em to default...
[ -z "$c$w$lines" ]  &&  c=0 lines=0 w=0

for b in "$@"	# Pass 2, remove all options from command line...
do
	case "Z$b" in
		Z-?*) ;;
		Z*) opts="$opts"" "\""$b"\" ;;	# for vfat filenames with spaces
	esac
done

# 'eval' is needed to parse $opts.  If $opts is null, make it a hyphen.
eval set dummyoption ${opts:--}
shift

unset opts
for b in "$@"	# Pass 3, replace hyphen, proofread filenames
do
	case "Z$b" in
		Z-)	trap 'Bail' 1 2 3 15
			stdIOfile=/tmp/$$RusticWc.tmp
			cat > $stdIOfile || Bail	# if 'cat' fails, quit.
			b=$stdIOfile ;;
		Z*)	if [ ! -r "$b" ] 		# is the file readable?
			then
				echo "error: can't read \"$b\" " >& 2
				Bail
			fi
			[ -d "$b" ] && continue ;;	# skip any directories...
	esac
	opts="$opts"" "\""$b"\"
done

eval set $opts

# get list of char counts?  Kludge to call 'ls' only once.
# 'ls' may output multiple lines, which are churned into a
# single line by a 'while' loop, using 'read' and 'echo -n'.
[ "$c" ]  &&  \
	charlist=`ls -Uo "$@" | while read x1 x2 x3 x4 x5; do ; echo -n $x4" " ; done`

for f in "$@"
do
	if [ "$f" = "$stdIOfile" ]	# stdIO?
	then	filename=$hyphen	# display a hyphen or not?
	else	filename="$f"
	fi

	if [ $c ]			# get how many chars it is?
	then
		c=`(set $charlist ; echo $1)`
		cSum=`expr "$cSum" + $c`
		charlist=`(set $charlist ; shift ; echo "$@")`
	fi

	# check words and lines.  The first "if-then" is a wrapper,
	# so 'awk' is only called once per file.
	if [ $w$lines ]
	then
		TmpWL=`awk 'BEGIN { w=0 } { w+=NF } END  { print NR, w }' < "$f"`

		if [ $w ]
		then
			w=`(set $TmpWL ; echo $2)`
			wSum=`expr "$wSum" + $w`
		fi

		if [ $lines ]
		then
			lines=`(set $TmpWL ; echo  $1)`
			linesSum=`expr "$linesSum" + $lines`
		fi
	fi
 
	ShowLine "$lines" "$w" "$c" "$filename"
	n=`expr "$n" + 1`
done

[ "$n" -gt "1" ]  &&  ShowLine "$linesSum" "$wSum" "$cSum" total

CleanUp
