Refactored logic, much more cleaner.