tools.py: the big cleanup
tools.py contained quite some things that need a big cleanup.
See the individual commits for details and more readable diffs.
Note: This MR "only" does cleanups and some refactoring. It does not change the (user-visible) behaviour of the code.