Refactored to handle task hierarchies