/*
 * wc [file ...]
 */

/*)BUILD	$(TKBOPTIONS) = {
			TASK	= ...WCX
		}
*/

#ifdef	DOCUMENTATION

title	wc	Word Count
index		Count Words, Lines, and Bytes in Files

synopsis

	wc [name ...]

description

	Count the number of bytes, words, and lines in one or more files.
	wc accepts wild-card file name arguments.

diagnostics

	.lm +8
	.s.i -8;"file name": cannot open
	.s.i -8;"file name": illegal file name
	.lm -8

author

	Martin Minow

bugs

#endif

#include <stdio.h>

long	tw	= 0;
long	tl	= 0;
long	tb	= 0;
#ifndef	vms
char	file_name[81];
#endif

main(argc, argv)
char *argv[];
{
	register int	i, tf;
	register FILE	*fp;
	int		gotcha;

	tf = 0;
	if(argc < 2) {
		++tf;
		count(stdin, 0);
	} else
#ifdef vms
		for (i = 1; i < argc; ++i) {
			if ((fp = fopen(argv[i], "r")) == NULL) {
				fprintf(stderr, "\"%s\": cannot open\n",
						argv[i]);
				continue;
			}
			++tf;
			count(fp, argv[i]);
			fclose(fp);
		}
#else
		for (i = 1; i < argc; ++i) {
			if ((fp = fwild(argv[i], "r")) == NULL) {
				fprintf(stderr, "\"%s\": illegal file name\n",
					argv[i]);
				continue;
			}
			for (gotcha = 0; fnext(fp) != NULL; gotcha++) {
				++tf;
				fgetname(fp, file_name);
				count(fp, file_name);
			}
			if (gotcha == 0)
				fprintf(stderr, "\"%s\": cannot open\n",
					argv[i]);
		}
#endif
	if (tf > 1)
		output(tw, tl, tb, "total");
}

count(fp, fn)
FILE *fp;
char *fn;
{
	register int c, inword;
	long w;
	long l;
	long b;

	l = 0;
	w = 0;
	b = 0;
	inword = 0;
	while((c=getc(fp)) != EOF) {
		++b;
		if(c==' ' || c=='\t' || c=='\n') {
			inword = 0;
			if(c == '\n')
				++l;
		} else if(!inword) {
			++inword;
			++w;
		}
	}
	tw += w;
	tl += l;
	tb += b;
	output(w, l, b, fn);
}

output(w, l, b, fn)
long	w;
long	l;
long	b;
char *fn;
{
	printf("%8ld word%c %8ld line%c %8ld byte%c",
		w, plural(w), l, plural(l), b, plural(b));
	if(fn)
		printf(" %s", fn);
	printf("\n");
}

plural(n)
long	n;
{
	return((n == 1) ? ' ' : 's');
}

