Minor code refactoring. Fixes issue 4128
Simplifying top frame search. Fixes issue 5576