Massive refactor (more readable and fixes bugs