Refactor

Moved lots out of server.js. Could do with a sanity check and code review!