Really big refactoring for multiple fixes