Big refactoring for a more DRY and correct code.