massive refactoring and readability improvement