/***************
*
* g:\exe\txl\src\txllcx.c
*/
#include "txl.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;
	FILE *input;

	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--;

	fprintf(fpmes, "%10ld%10ld%10ld ", ret, size, retx);
	if (*lcxinputfile != NUL) {
		fprintf(fpmes, "%s", lcxinputfile);
	}

	totalret += ret;
	totalretx += retx;
	totalsize += size;
	putc(RET, fpmes);

	fclose(input);

}

void lcxdriver(char *param[])
{
	int fileno = 0,i;
	char *filename;
	char *fence = "----------+---------+---------+------------------------\n";

	fprintf(stderr, "TXL inline module LCX Ver1.20\n");
	fprintf(fpmes,  "     Lines     Bytes ViewLines Filename\n");
	fprintf(fpmes, fence);

	if (param[0][0] == NUL) {
		fileno++;
		lcx(NULL);
	}
	else {
		for (i = 0; param[i] != NULL; i++) {
			do {
				filename = get_filename(param[i]);
				if (filename != NULL) {
					lcx(filename);
					fileno++;
				}
			} while(filename != NULL);
		}
	}
	if (fileno > 1) {
		fprintf(fpmes, fence);
		fprintf(fpmes, "%10ld%10ld%10ld TOTAL\n",
			totalret, totalsize, totalretx);
	}
	Exit(0);

}

/***************end of LCX*********************/

