/***************
*
* g:\exe\txf\src\txflcx.c
*/
#include "txf.h"

/**************** in line LCX module ************************/

char *get_filename(char *wildcard)
{
	static struct find_t filedata;
	static char wc[76] = "";
	static char fullpath[80];
	char *npos;
	int ret;

	if (strcmp(wc, wildcard) != 0) {
		strcpy(wc, wildcard);
		ret = _dos_findfirst(wc, _A_ARCH | _A_NORMAL | _A_RDONLY, &filedata);
	}
	else {
		ret = _dos_findnext(&filedata);
	}

	if (ret == 0) {
		strcpy(fullpath, wildcard);
		if ((npos = jstrrchr(fullpath, '\\')) != NULL) {
			strcpy(npos + 1, filedata.name);
		}
		else if ((npos = jstrchr(fullpath, ':')) != NULL) {
			strcpy(npos + 1, filedata.name);
		}
		else {
			strcpy(fullpath, filedata.name);
		}
		if (strstr(fullpath, ".BAK") != NULL) {
			return (get_filename(wildcard));
		}
		return (fullpath);
	}
	else {
		return (NULL);
	}
}

void lcx (char *lcxinputfile)
{
	int chr = NUL,type = CT_ANK;
	long int size = 0, clum = 0, ret = 0, retx = 0;

	if (lcxinputfile != NULL) {
		input = fopen(lcxinputfile, "rb");
	}
	else {
		errexit("Cannot open inputfile.");
	}
	if (input == NULL) {
		fprintf(stderr, "Error:cannot open input file\n");
		exit(1);
	}

	while(chr != EOF) {
		chr = getc(input);
		type = chkctype(chr, type);
		size++;
		clum++;
		if (chr == 0x0a) {
			ret++;
			retx++;
			clum = 0;
		}
		if (((clum == 80) && (type == CT_KJ1)) || (clum > 80)) {
			clum = 0;
			retx++;
		}
	}
/*
	if (input == stdin) {
		size += ret;
	}
*/
	size--;

	printf("%10ld%10ld%10ld ", ret, size, retx);
	if (*lcxinputfile != NUL) {
		printf("%s", lcxinputfile);
	}

	totalret += ret;
	totalretx += retx;
	totalsize += size;
	putc(RET, stdout);

	fclose(input);

}

void lcxdriver(char far **param)
{
	int fileno = 0,i;
	char *filename;

	fprintf(stderr, "TXF inline module LCX Ver1.20\n     Lines     Bytes ViewLines Filename\n");

	if (*param == NUL) {
		fileno++;
		lcx(NULL);
	}
	else {
		for (i = 0; *(param+i) != NULL; i++) {
			do {
				filename = get_filename(nrcpy(*(param+i)));
				if (filename != NULL) {
					lcx(filename);
					fileno++;
				}
			} while(filename != NULL);
		}
	}
	if (fileno > 1) {
		fprintf(stderr, "----------+---------+---------+------------------------\n");
		printf("%10ld%10ld%10ld TOTAL\n",
			totalret, totalsize, totalretx);
	}
	exit(0);

}

/***************end of LCX*********************/

