/*
 * I Ching:
 *              phx [ hexagram ]
 *
 * Reconstructed from pdp11 object file
 */

#include <stdio.h>

FILE    *hexfile;


main(argc, argv)
char **argv;
{
	char    buf[8];

	if ((hexfile = fopen("hexagrams", "r")) == NULL) {
		fprintf(stderr, "Can't find hexagrams\n");
		exit(1);
	}

	if (argc > 1)
		printhex(argv[1]);
	else if (fgets(buf, sizeof buf, stdin) != NULL)
		printhex(buf);
}

printhex(s)
register char   *s;
{
	int     hexagram = 0;
	int     moving_lines = 0;
	register int    bit_on = 1;
	register int    nlines;

	for (nlines = 6; nlines; nlines--) {
		switch(*s++) {
			case '6':       moving_lines |= bit_on;
					hexagram |= bit_on;
					break;

			case '7':       break;

			case '8':       hexagram |= bit_on;
					break;

			case '9':       moving_lines |= bit_on;
					break;

			default:        return(0);
		}
		bit_on <<= 1;
	}

	if (!phx(hexagram, moving_lines))
		return(0);
	if (moving_lines)
		return(phx(hexagram ^ moving_lines, 0));
	return(1);
}

char hexmap[64] = {
	000, 077, 056, 035, 050, 005, 075, 057,
	010, 004, 070, 007, 002, 020, 073, 067,
	046, 031, 074, 017, 026, 032, 037, 076,
	006, 030, 036, 041, 055, 022, 043, 061,
	003, 060, 027, 072, 012, 024, 053, 065,
	034, 016, 040, 001, 047, 071, 045, 051,
	042, 021, 066, 033, 013, 064, 062, 023,
	011, 044, 015, 054, 014, 063, 052, 025,
};

phx(hex, moving)
{
	char line[128];
	int     number;
	register int    copying;


	if (moving == 077)
		moving = 0177;

	rewind(hexfile);
	while (fgets(line, sizeof line, hexfile) != NULL) {
		if (line[0] == '.' && line[1] == 'H') {
			number = atoi(&line[3]);
			if (hexmap[number-1] == hex) {
				fputs(line, stdout);
				copying = 1;
				while (fgets(line, sizeof line, hexfile) != NULL) {
					if (line[0] == '.') {
						if (line[1] == 'H')
							return(1);
						if (line[1] == 'L') {
							copying = moving & 01;
							moving >>= 1;
						}
					}
					if (copying)
						fputs(line, stdout);
				}
				return(1);
			}
		}
	}
	return(0);
}
