Refactor and get working on server side