#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <exec/types.h>
#if defined __SASC
	#include <proto/dos.h>
#else
	#include <clib/dos_protos.h>
#endif
#include "LeoLib.h"


static char *Version="$VER:Wc 1.0"
#if defined __SASC
	" "	"(21.11.94)" /*__AMIGADATE__*/ " ©1994 Leopold-Soft"
#endif
	;


static BOOL Wc(const char *Name);



#define TRUE 1
#define FALSE 0

#define AP_LEN	1024

static ULONG Lines = 0, Words = 0, Chars = 0;

#define F_LINES 	1
#define F_WORDS 	2
#define F_CHARS 	4
#define F_TOTALONLY	8

int main(int argc, char **argv) {
	int CurrArg = 0;
	BOOL Flags = F_LINES|F_WORDS|F_CHARS;
	ULONG TotalLines = 0, TotalWords = 0, TotalChars = 0;
	struct AnchorPath *AP;

	if (!(AP = calloc(1, sizeof(struct AnchorPath) + AP_LEN))) return 30;
	AP->ap_Strlen = AP_LEN;

	while(++CurrArg < argc) {
		if (!strcmp(argv[CurrArg],"-l")) {
			Flags &= ~(F_LINES | F_WORDS | F_CHARS);
			Flags |= F_LINES;
		} else if (!strcmp(argv[CurrArg],"-w")) {
			Flags &= ~(F_LINES | F_WORDS | F_CHARS);
			Flags |= F_WORDS;
		} else if (!strcmp(argv[CurrArg],"-c")) {
			Flags &= ~(F_LINES | F_WORDS | F_CHARS);
			Flags |= F_CHARS;
		} else if (!strcmp(argv[CurrArg],"-t")) {
			Flags |= F_TOTALONLY;
		} else if (!strcmp(argv[CurrArg],"-h") || !strcmp(argv[CurrArg], "?")) {
			printf("Wc 1.0 by Henrik Herranen " __DATE__ "\n\n"
					"Usage: %s [?|-h] | [-l] | [-w] | [-c] | [-t] | files...\n\n",
					argv[0]);
		} else {
			if (MatchFirst(argv[CurrArg], AP)) {
				fprintf(stderr, "%s: Couldn't find %s!\n", argv[0], argv[CurrArg]);
			} else {
				do {
					if (AP->ap_Info.fib_DirEntryType < 0) {
						if (!Wc(AP->ap_Buf)) {
							fprintf(stderr, "%s: Couldn't read %s!\n", argv[0], AP->ap_Buf);
						} else {
							TotalLines += Lines;
							TotalWords += Words;
							TotalChars += Chars;
							if (!(Flags & F_TOTALONLY)) {
								printf("%-24s", AP->ap_Buf);
								if (Flags & F_CHARS) printf(" %7ld", Chars);
								if (Flags & F_WORDS) printf(" %6ld", Words);
								if (Flags & F_LINES) printf(" %5ld", Lines);
								printf("\n");
							}
						}
					} else {
						fprintf(stderr,"%s: Skipping directory \"%s\"\n", argv[0], AP->ap_Buf);
					}
				} while (!(MatchNext(AP)));
				MatchEnd(AP);
			}
		}
	}

	if (!(Flags & F_TOTALONLY)) printf("\n%-24s", "GRAND TOTAL");
	if (Flags & F_CHARS) printf(" %7ld", TotalChars);
	if (Flags & F_WORDS) printf(" %6ld", TotalWords);
	if (Flags & F_LINES) printf(" %5ld", TotalLines);
	printf("\n");

	return 0;
}





static BOOL Wc(const char *Name) {
	FILE *InFile;
	BOOL Inside = FALSE;
	int InC;

	Lines = Words = Chars = 0;
	if (!(InFile = fopen(Name, "r"))) return FALSE;

	while ((InC = getc(InFile)) != EOF) {
		if (InC == '\n') Lines++;
		if (IsAlnum(InC)) {
			if (!Inside) {
				Inside = TRUE;
				Words++;
			}
		} else {
			Inside = FALSE;
		}
		Chars++;
	}

	if (Inside) Words++;
	fclose(InFile);

	return TRUE;
 }
