Refactor to simplify and clean up codebase

This does a little cleanup in coding style and extracts common parts
from the two scripts into an extra file.

Documentation is amended a tiny bit.