Final refactor. The code can be improved in a few parts, but now it works