Some refactoring. Added tests for hierarchy.