#include <stdio.h>

/*
 * Program to interpret the H19 444-37 "KEYB" encoder ROM image
 * in the context of the MM5740 as used in the H19.
 *
 * Dump the data is five columns,
 * 1 is the key cap description,
 * 2 ("UN") is the unmodified key code (no SHIFT or CTRL)
 * 3 ("SH") is the SHIFT code
 * 4 ("CT") is the CTRL code
 * 5 ("SC") is the SHIFT+CTRL code
 *
 */

#include "h19keyb.h"
// struct mm5740_s h19_mm5740[10][11]

#include "h19_444_37.h"
// unsigned char h19_444_37[]

/*
 * The H19 schematic shows SHIFT and CTRL inverted *into* the MM5740,
 * and the datasheet implies that is wrong.
 * But the ROM data suggests otherwise.
 */
static void do_keys(struct mm5740_s *key, int adr) {
	if (!key->key) {
		return;
	}
	// NOTE: B1-B9 are inverted...
	if (!key->b1) adr |= 0x001;
	if (!key->b2) adr |= 0x002;
	if (!key->b3) adr |= 0x004;
	if (!key->b4) adr |= 0x008;
	if (!key->b9) adr |= 0x040;
	printf("%10s = ", key->key);
	// now go thru shift/ctrl/etc...

	int au = adr;
	if (!key->u_b5) au |= 0x010;
	if (!key->u_b6) au |= 0x020;
	if (!key->u_b7) au |= 0x080;
	if (!key->u_b8) au |= 0x100;

	int as = adr;
	if (!key->s_b5) as |= 0x010;
	if (!key->s_b6) as |= 0x020;
	if (!key->s_b7) as |= 0x080;
	if (!key->s_b8) as |= 0x100;

	int ac = adr;
	if (!key->c_b5) ac |= 0x010;
	if (!key->c_b6) ac |= 0x020;
	if (!key->c_b7) ac |= 0x080;
	if (!key->c_b8) ac |= 0x100;

	int asc = adr;
	if (!key->sc_b5) asc |= 0x010;
	if (!key->sc_b6) asc |= 0x020;
	if (!key->sc_b7) asc |= 0x080;
	if (!key->sc_b8) asc |= 0x100;

	printf(" %02x %02x %02x %02x\n",
		h19_444_37[au],
		h19_444_37[as],
		h19_444_37[ac],
		h19_444_37[asc]);
}

int main(int argc, char **argv) {
	int x, y;
	int a9a10 = 0;

	/*
	 * Could look at argv for jumpers JP31 (1,2,3) and JP32 (1,2,3)
	 * settings and modify address bits A9,A10 for do_keys().
	 * Current ROM image is only 512 bytes, though.
	 */
	// if (jp31 == 1) a9a10 |= (1 << 9);
	// if (jp32 == 1) a9a10 |= (1 << 10);
	printf("%10s    UN SH CT SC\n", "key cap");
	// Go through scan lines X1-X9 and Y1-Y10 and decode keys.
	for (x = 1; x <= 9; ++x) {
		for (y = 1; y <= 10; ++y) {
			do_keys(&h19_mm5740[x][y], a9a10);
		}
	}
}
