A bit dodgy, but moved all I could to server-side. To be improved still.