Slightly modified and cleaner logic.