#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>

#define ICHING_PATH "/var/www/htdocs/ching/ching.html"

void cast(char *question, char *hexagram)
{
	int sum, i;

	sum = 0;
	if (question) while (*question) sum += *question++;
	srandom(sum + getuid() + getgid() + getpid() + time(0));
	for (i = 0; i < 6; i++) {
		sum = 2 + ((random() >> 15) & 1);
		sum += 2 + ((random() >> 15) & 1);
		sum += 2 + ((random() >> 15) & 1);
		hexagram[i] = '0' + sum;
	}
}

int changing(char *hexagram)
{
	int i;

	for (i = 0; i < 6; i++) if (hexagram[i] == '6' || hexagram[i] == '9') return 1;
	return 0;
}

void change(char *hexagram)
{
	int i;

	for (i = 0; i < 6; i++) {
		if (hexagram[i] == '6') hexagram[i] = '7';
		if (hexagram[i] == '9') hexagram[i] = '8';
	}
}

int number(char *hexagram)
{
	int i, h = 0;
	static char hnum[64] = {
		  2, 24,  7, 19, 15, 36, 46, 11,
		 16, 51, 40, 54, 62, 55, 32, 34,
		  8,  3, 29, 60, 39, 63, 48,  5,
		 45, 17, 47, 58, 31, 49, 28, 43,
		 23, 27,  4, 41, 52, 22, 18, 26,
		 35, 21, 64, 38, 56, 30, 50, 14,
		 20, 42, 59, 61, 53, 37, 57,  9,
		 12, 25,  6, 10, 33, 13, 44,  1
	};

	for (i = 0; i < 6; i++) if (hexagram[i] == '7' || hexagram[i] == '9') h += 1 << i;
	return hnum[h];
}

void print(char *hexagram)
{
	FILE *text;
	char line[80], top[8];
	int i = -3, echo = 0;

	if ((text = fopen(ICHING_PATH, "r")) == 0) return;

	sprintf(top, "%d.  ", number(hexagram));
	fputs("\n", stdout);
	while (fgets(line, sizeof(line), text) != 0) {
		if (*line == '\f') *line = '\n';
		if (i == -3) {
			if (strstr(line, top) != 0 && strstr(line, " / ") != 0) echo = 1, i++;
		}
		else if (i == -2) {
			if (strstr(line, "The Lines") != 0)
				if (!changing(hexagram)) break;
				else i++;
		}
		else {
			if (*line == '\n') i++;
			if (i < 6) echo = (hexagram[i] == '6' || hexagram[i] == '9');
			else if (memcmp(hexagram, "666666", 6) && memcmp(hexagram, "999999", 6) || i > 6) break;
		}
		if (echo) fputs(line, stdout);
	}
	fclose(text);
}

int main(int argc, char *argv[])
{
	char *question;
	char hexagram[6];

	if (argc > 1) question = argv[1];
	else question = getenv("WWW_question");
	if (question && strlen(question) == 6 && strspn(question, "6789") == 6) {
		memcpy(hexagram, question, 6);
		question = 0;
	}
	else cast(question, hexagram);
	fputs("Content-type: text/html\n\n", stdout);
	fputs("<html><head><title>Your I Ching reading</title></head><body>\n", stdout);
	if (question) {
		fputs("<p>Your question was:<br>\n", stdout);
		fputs(question, stdout);
		fputs("\n</p>\n<p>The sage answers:</p>\n", stdout);
	}
	print(hexagram);
	if (changing(hexagram)) {
		change(hexagram);
		print(hexagram);
	}
	fputs("</body></html>\n", stdout);
	return 0;
}
