Big refactoring and bug-fixing