refactor main.py, flesh out functions from main function

@stdweird, @wpoely86: please review?

The diff is going to look a bit messy, maybe you want to look at the actual new `main.py` instead...
ok, reworked

I didn't insert the keys via a loop though (constants should be defined hard, not generated in some way), but organised things better