minor cleanup
change to catch keydown instead of keypress
Optimize trace flushing.

Rather than flushing at every function exit, we periodically
flush on some timing interval, set by the variable FLUSH_INTERVAL.