A lot of refactoring, some fixes

I've kept separated commits so that the review is easier.

I've changed the code to make it easier to follow, it might be a matter of personal prefs though. If this is the case please pin-point the commit and the modif so that I can revert.

Tests are passing as well as before: there is one remaining issue with the last test in `test_client.html`.