Massive refactor and generic fixes