#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <asm/types.h>
#include <linux/input.h>
#include <linux/uinput.h>

/* table to convert ascii => input event code */
unsigned char keymapz[256] =
/*      0       1       2       3       4       5       6       7       8       9 */
{/*0*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*10*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*20*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*30*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*40*/	0,	0,	0,	0,	0,	0,	0,	0,	11,	2,
/*50*/	3,	4,	5,	6,	7,	8,	9,	10,	0,	0,
/*60*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*70*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*80*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*90*/	0,	0,	0,	0,	0,	0,	0,	30,	48,	46,
/*100*/	32,	18,	33,	34,	35,	23,	36,	37,	38,	50,
/*110*/	49,	24,	25,	16,	19,	31,	20,	22,	47,	17,
/*120*/	45,	21,	44,	0,	0,	0,	0,	0,	0,	0,
/*130*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*140*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*150*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*160*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*170*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*180*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*190*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*200*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*210*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*220*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*230*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*240*/	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,
/*250*/	0,	0,	0,	0,	0,	0
};
	

int main(int argn, char *argv[])
{
	struct uinput_user_dev	device;
	struct input_event	event;
	int			fd;
	unsigned char		aux;
	char buff[80];

	/* open uinput device file */
	fd = open("/dev/input/uinput", O_RDWR);
	if (fd < 0) {
		perror("open");
		return fd;
	}

	/* sets the name of our device */
	strcpy(device.name, "test keyboard");

	/* its bus */
	device.idbus = BUS_USB;

	/* and vendor id/product id/version */
	device.idvendor = 2;
	device.idproduct = 3;
	device.idversion = 4;

	/* inform that we'll generate key events */
	ioctl(fd, UI_SET_EVBIT, EV_KEY);

	/* set key events we can generate (in this case, all) */
	for (aux = 1; aux < 207; cnt ++)
		ioctl(fd, UI_SET_KEYBIT, cnt);


	/* write down information for creating a new device */
	if (write(fd, &device, sizeof(struct uinput_user_dev)) < 0) {
		perror("write");
		close(fd);
		return 1;
	}

	/* actually creates the device */
	ioctl(fd, UI_DEV_CREATE);

	/* loop reading stdin */
	while (1) {
		memset(buff, 0, 80);
		scanf("%s", buff); 
		for (aux = 0; buff[aux] != 0; aux++) {
			/* the code of event is different from ascii code */
			event.code = keymapz[buff[aux]];
			/* type of event is key */
			event.type = EV_KEY;
			/* key pressed */
			event.value = 1;
			/* write event */
			write(fd, &event, sizeof(struct input_event));
			/* key released */
			event.value = 0;
			/* write event */
			write(fd, &event, sizeof(struct input_event));
		}
		/* when finished, press 'enter' key */
		event.code = KEY_ENTER;
		event.value = 1;
		write(fd, &event, sizeof(struct input_event));
		event.value = 0;
		write(fd, &event, sizeof(struct input_event));
	}

	close(fd);
	
	return 0;
}

