Refactor rough code from server to here. Split into separate files.