De-globalfied the key handling.

The code is getting very big. It would be nice to be able to break it up
into libraries and so forth, but the tutorial code relies heavily on
globals, to the extent that I don't think that's even possible in its
present state.

So I'm slowly working on 'de-globalfying' the whole thing in the hopes
of creating a more reliable standard style more accepting of future
refactoring.