Refactored polling.

The original patch is polished and tweaked by Rolf Ahrenberg.