Refactoring server logic
some refactoring