Refactored event loop.

This allows large numbers of events to be handled in bulk, but without
the program eating up CPU when idle.