Restructure server code a little bit

Makes the structure a little bit neater and uses less global variables