Rather elaborate refactor…

I'm not sure if this is actually better. It's certainly more 'structural', but I didn't think about it enough to make it *really* elegant. I also skimped on error handling, and the output is basically useless now. So might want to fix that if you accept my 'pull request'! :)