Rewrite code in a less monolythic style, improve output