A much-needed refactor of the entire program.

This was done with an eye to future unit-testing, but also to account for potential upcoming changes to the master protocol.