Refactored the main server code. Added several comments explaining the purpose of each function