server code (much) tidier and commented