#include <lnp/lnp.h>
#include <string.h>
#include <conio.h>
#include <dsound.h>

#define LISTEN_PORT 1

char address_buf[255];
int buf_len = 0;
char sender;

note_t notes_wait[] = { { PITCH_E4, EIGHTH },
			{ PITCH_D4, EIGHTH },
			{ PITCH_C4, EIGHTH },
			{ PITCH_END, EIGHTH } };

note_t notes_recv[] = { { PITCH_C4, EIGHTH },
			{ PITCH_A4, EIGHTH },
			{ PITCH_F4, EIGHTH },
			{ PITCH_END, EIGHTH } };



static 
void 
port_handler(const unsigned char *data,
		unsigned char length,
		unsigned char src)
{
	memcpy(address_buf, data, length);
	sender = src;
	buf_len = length;
}

static 
wakeup_t 
havepack(wakeup_t w)
{
	return buf_len;
}

int 
read_from_ir(char *data, unsigned char *src)
{
	int ret;
	wait_event(havepack, 0);
	memcpy(data, address_buf, buf_len);
	ret = buf_len;
	buf_len = 0;
	if (src) *src = sender;
	return ret;
}

int 
main(int argc, char *argv[])
{
	char buf[256];
	unsigned char msg_sender;
	int len;

	lnp_addressing_set_handler(LISTEN_PORT, port_handler);

	dsound_play(notes_wait);

	msleep(1000);

	while(1)
	{
		cputs("wait");
		len = read_from_ir(buf, &msg_sender);
		lcd_int(msg_sender);
		msleep(500);
		lcd_int(len);
		msleep(500);
		dsound_play(notes_recv);
		cputs(buf);

		msleep(1000);
		cls();
	}  

	return 0;
}
