/*
 * Translate *.act files into HTML document
 * Author: Piotr Fusik <fox@scene.pl>
 */

#include <stdio.h>

int main(int argc, char *argv[])
{
	int i;
	FILE* f;
	unsigned char act[768];
	int x;
	int y;
	int cols = 1;
	int c = 0;

	if (argc < 2) {
		fprintf(stderr, "Usage: act2html [--columns <n>] file1.act file2.act ... >file.html\n");
		return 0;
	}
	printf("<HTML><HEAD><TITLE>Generated by act2html</TITLE></HEAD><BODY><CENTER>\n");
	i = 1;
	if (argc >= 4 && strcmp(argv[1], "--columns") == 0
	 && argv[2][0] >= '1' && argv[2][0] <= '9' && argv[2][1] == '\0') {
		cols = argv[2][0] - '0';
		i = 3;
		printf("<TABLE WIDTH=100%%>\n");
	}
	for (; i < argc; i++) {
		f = fopen(argv[i], "rb");
		if (f == NULL) {
			fprintf(stderr, "Can't open %s\n", argv[i]);
			continue;
		}
		if (fread(act, 1, 768, f) != 768) {
			fprintf(stderr, "Error reading %s\n", argv[i]);
			fclose(f);
			continue;
		}
		fclose(f);
		if (cols > 1) {
			if (c % cols == 0)
				printf("<TR>\n");
			printf("<TD WIDTH=%d%% ALIGN=center>\n", 100 / cols);
		}
		printf("<P>%s</P><P><TABLE WIDTH=100%%><TR><TD></TD>\n", argv[i]);
		for (x = 0; x < 16; x++)
			printf("<TD WIDTH=6%% ALIGN=center>%X</TD>\n", x);
		for (y = 0; y < 16; y++) {
			printf("</TR><TR><TD ALIGN=center>%X</TD>\n", y);
			for (x = 0; x < 16; x++) {
				printf("<TD BGCOLOR=#%02X%02X%02X></TD>\n",
				 act[(16 * y + x) * 3], act[(16 * y + x) * 3 + 1], act[(16 * y + x) * 3 + 2]);
			}
		}
		printf("</TR></TABLE></P><HR>\n");
		if (cols > 1) {
			printf("</TD>");
			c++;
			if (c % cols == 0)
				printf("</TR>");
		}
		
	}
	if (cols > 1) {
		if (c % cols) {
			while (c % cols)
				printf("<TD></TD>");
			printf("</TR>");
		}
		printf("</TABLE>\n");
	}
	printf("</CENTER></BODY></HTML>\n");
	return 0;
}
