Complete redo for backend logic. Reorganized code and made more reliable