Big refactorization. Now it works!