General clean up and refactor

Cleaned up and refactored the server side code.