Major reorganisation of code to move out of client html