Massive refactoring, typo fix