Rewrite and refactor.

Rewrite of some parts to be more elegant and compact. Split more
sections to their own scripts.