refactored hierarchy function