Major refactoring. NOT TESTED