Stacking by Type & Multiple Rows in Stack Viewer

My module has a couple types of Army units that’d I’d like to allow to stack together, but only with the same unit. So if a region has 2 Elites, 8 Regulars, and 3 Leaders, I’d end up with 3 distinct stacks that can’t combine with each other. Right now as soon as I toggle stacking for a piece, it stacks with anything willy-nilly, even units stacking with cards. I’ve seen an Advanced Squad Leader module do this, but I can’t figure out how to implement it.

In the same ASL module, the mouse-over stack viewer popup wraps into multiple lines if the stack contains more than 9 units. This is also something I want to try and recreate in my module, though wrapping at 5 units.

My module was saved in 3.4.12, though I’ve since updated that to 3.5.0. The Advanced Squad Leader module is 3.4.6.