Make scan find the outmost element more robustly. Fixes #156