Customizing Filter 'PatternRecursive' - Plugin Development

I am creating a new Piwik Plugin for our company’s use. In short, I need to have individual widgets that show stats for all pages within each department. I’ve got the widget pulling in all the data site-wide that I want, I’m just stuck at the Filter functionality. Here is an example of the hierarchical setup of my results:

[ul]
[li]+Department1
[/li] [list]
[li]└Folder1
[/li] [list]
[li]└Page1
[/li] [li]└Page2
[/li] [li]└Page3
[/li] [/ul]
[li]└Folder2
[/li] [ul]
[li]└Page4
[/li] [li]└Page5
[/li] [/ul]
[/list]
[li]+Department2
[/li] [ul]
[li]└Folder3
[/li] [list]
[li]└Page6
[/li] [/ul]
[li]└Page7
[/li] [/list]
[li]etc…
[/li][/list]

As you can see, each department has multiple scenarios of pages, folders, sub-folders, and so on. So, my filter needs to work so that, Department1 has its own widget showing everything within the Department1 section. Same for each department.

Currently, I started with the PatternRecursive function, copied it to my own, and started attempted to manipulate it to my needs. I am using each department name as the keyword, and ‘label’ as the column to filter by. The problem that I am discovering is that as it cycles through each row, it is including the rows that are within each expandable folder, and looking for the keyword in each row’s label. But I want to filter only by the top level. I can’t seem to figure out how to get it to bypass the row if it is not the top level.

In the example above, I only want the filter to cycle through the rows Department1, Department2, Department3, etc… If the keyword is not in the label of that top level, then delete it and all of its child-rows. If it IS in that top level label, then keep that row along with all rows that belong to it.

Hope this makes sense! Thanks for your help!