refactoring the scan logic. This is more flexible