Full refactoring and 2 bugs corrected