Refactor/cleanup

Contains the consolidated output of #758, #746, #742, #748, #747 

Moves code into places where it is most appropriate, depending on whether it's client-side, server-side or shared across both.

In theory all of the code in this PR has been reviewed as part of the PRs above.