Smooth old code.

Rename functions and variable, refactor, introduce generators and
exception catching, write a main function, etc.