Fix sending wrong keys when using multiple keyboard layouts

Note: Make a very careful review. Or rewrite all of this yourself, please. I'm new to C. I'm not sure what to do and what not to do in C programming.

This patch fixes following bugs.
https://code.google.com/p/semicomplete/issues/detail?id=13
https://code.google.com/p/semicomplete/issues/detail?id=21
https://code.google.com/p/semicomplete/issues/detail?id=41#c1
https://code.google.com/p/semicomplete/issues/detail?id=76