Heavy refactoring and typo fixing