/*
 * wc [file ...]
 */
#include <stdio.h>

int	tw	= 0;
int	tl	= 0;

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

	tf = 0;
	if(argc < 2) {
		++tf;
		count(stdin, 0);
	} else
		for(i=1; i<argc; ++i) {
			if((fp=fopen(argv[i], "r")) == NULL)
				error("%s: cannot open\n", argv[i]);
			++tf;
			count(fp, argv[i]);
			fclose(fp);
		}
	if(tf > 1)
		output(tw, tl, "total");
}

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

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

output(w, l, fn)
char *fn;
{
	printf("%6d word%c %6d line%c", w, plural(w), l, plural(l));
	if(fn)
		printf(" %s", fn);
	printf("\n");
}

plural(n)
{
	if(n == 1)
		return(' ');
	return('s');
}
