Major refactoring of the backend code for better structure