Refactor rescan logic and fix bugs