/*
 *   keyboard.c
 *
 *   This file is part of Emu48
 *
 *   Copyright (C) 1995 Sebastien Carlier
 *
 */
#include "pch.h"
#include "Emu48.h"

WORD Keyboard_GetIR()
{
	WORD r = 0;
	
	if (Chipset.out==0) return 0;
	if (Chipset.out&0x001) r|=Chipset.Keyboard_Row[0];
	if (Chipset.out&0x002) r|=Chipset.Keyboard_Row[1];
	if (Chipset.out&0x004) r|=Chipset.Keyboard_Row[2];
	if (Chipset.out&0x008) r|=Chipset.Keyboard_Row[3];
	if (Chipset.out&0x010) r|=Chipset.Keyboard_Row[4];
	if (Chipset.out&0x020) r|=Chipset.Keyboard_Row[5];
	if (Chipset.out&0x040) r|=Chipset.Keyboard_Row[6];
	if (Chipset.out&0x080) r|=Chipset.Keyboard_Row[7];
	if (Chipset.out&0x100) r|=Chipset.Keyboard_Row[8];
	return r;
}

VOID ScanKeyboard()
{
	WORD IR = Keyboard_GetIR();

	Chipset.in = IR | Chipset.IR15X;

	if (Chipset.IR15X)
	{
		if (Chipset.inte)
		{
//			PatBlt(hWindowDC,0,0,8,8,DSTINVERT);
			Chipset.SoftInt = TRUE;
			bInterrupt = TRUE;
		}
		if (Chipset.Shutdn)
		{
//			PatBlt(hWindowDC,8,0,8,8,DSTINVERT);
			Chipset.Shutdn = FALSE; // Prevent another ResumeThread
			ResumeThread(hThread);
		}
	}

	if (IR != 0)
	{
		if ((Chipset.inte) && (Chipset.intk))
		{
//			PatBlt(hWindowDC,0,8,8,8,DSTINVERT);
			Chipset.SoftInt = TRUE;
			bInterrupt = TRUE;
		}
		if (Chipset.Shutdn)
		{
//			PatBlt(hWindowDC,8,8,8,8,DSTINVERT);
			Chipset.Shutdn = FALSE; // Prevent another ResumeThread
			ResumeThread(hThread);
		}
	}

	return;
}

VOID KeyboardEvent(BOOL bPress, UINT out, UINT in)
{
	if (nState != 0)
		return;
	if (in == 0x8000)
	{
		Chipset.IR15X = bPress?0x8000:0x0000;
	}
	else
	{
		_ASSERT(out<9);
		if (bPress)
		{
			if (((Chipset.Keyboard_Row[out]&in) == 0) && (Chipset.inte==FALSE) && (Chipset.intk))
					Chipset.intd = TRUE;
			Chipset.Keyboard_Row[out] |= in;
		}
		else
			Chipset.Keyboard_Row[out] &= (~in);
	}
	ScanKeyboard();
	return;
}
