/***************
*
* g:\exe\txl\src\txlcraft.c
*/
#include "txl.h"

int craftbf(char *basename, FILE *fw)
{
	FILE *fp;
	char *token;
	int ret = 1, i;
	int kind = 0, num = 0;

	for (i = 1; i <= 2; i++) {
		switch (basename[strlen(basename) - i]) {
		case '~':
		case '&':
			num = 10;
		case '_':
		case '%':
			kind = 1;	/* MES */
			if (i == 2) {
				if (basename[strlen(basename) - 1] == 'A') {
					num += 10;
				}
				else if (basename[strlen(basename) - 1] <= '9') {
					num += basename[strlen(basename) - 1] - '0';
				}
				else {
					num = 0;
				}
			}
			break;
		case '$':
			num = 10;
		case '#':
			kind = 2;	/* DLL */
			if (i == 2) {
				if (basename[strlen(basename) - 1] == 'A') {
					num += 10;
				}
				else {
					num += basename[strlen(basename) - 1] - '0';
				}
			}
			break;
		}
		if (kind) {
			if (kind == 1) {
				sprintf(line3, "mes=%d;", num);
			}
			else if (kind == 2) {
				sprintf(line3, "lib=%d;", num);
			}
			basename[strlen(basename) - i] = NUL;
			break;
		}
	}

	if ((fp = fopen(txfsetfile, "rt")) == NULL) {
		return (1);	/* fapxtxf.set は存在しない */
	}
	while (!feof(fp)) {
		fgets(line1, 80, fp);
		if (*line1 != '$') {
			continue;
		}
		if ((token = strchr(line1, '\n')) != NULL) {
			*token = NUL;
		}
		if ((token = strchr(line1, '=')) == NULL) {
			continue;
		}
		if (strncmp(token+1, basename, strlen(basename)) == 0) {
			*token = NUL;
			if (strlen(line1 + 1) > 8) {
				if (matchstr("***%%%%%HP", line1+1)) {
					*(line1 + 9) = NUL;
					sprintf(line2, "hp=%s;", line1+1);
				}
				else if (matchstr("***%%%%%PT", line1+1)) {
					*(line1 + 9) = NUL;
					sprintf(line2, "patio=%s;", line1+1);
				}
				else {
					continue;
				}
			}
			else {
				sprintf(line2, "forum=%s;", line1+1);
			}
			if (num) {
				strcat(line2, line3);
			}
			fputs(line2, fw);
			ret = 0;
			break;
		}
	}
	fclose(fp);
	return (ret);
}

int craftfb(char *forumname, FILE *fw)
{
	FILE *fp;
	char *token;
	int ret = 1;

	if ((fp = fopen(txfsetfile, "rt")) == NULL) {
		return (1);	/* fapxtxf.set は存在しない */
	}
	while (!feof(fp)) {
		fgets(line1, 80, fp);
		if (*line1 != '$') {
			continue;
		}
		if ((token = strchr(line1, '\n')) != NULL) {
			*token = NUL;
		}
		if (strncmp(line1+1, forumname, strlen(forumname)) == 0) {
			if ((token = strchr(line1, '=')) == NULL) {
				break;
			}
			fputs(token + 1, fw);
			ret = 0;
			break;
		}
	}
	fclose(fp);
	return (ret);
}

void craftname(char *val[], int (*func)(char *name, FILE *fw))
{
	FILE *fw = NULL;

	fprintf(stderr, "TXL: craftname\n");

	outputfile = val[1];	/* outputfile		*/
	if (*outputfile != NUL) {
		fw = fopen(outputfile, "w");
	}
	if (fw == NULL) {
		Exit(1);
	}
	if ((*func)(val[0], fw)) {
		fputs("not found", fw);
	}
	fclose(fw);
	Exit(0);
}
