Refactoring: move finding the topmost class to its own method. Made it more functional.