Merging Boxes/Voxels

I am trying to optimise a voxelised structure such that small voxels combine into together into larger ones in areas where they repeat. For example, if say 4 voxels (blue) stack together on the same plane, they could combine into one module (4 times larger than the standard unit). Or say if a voxel is surrounded by other voxels on all sides, it could combine into one module the size of 9 units (see attached image).

I am able to list the boxes which are surrounded by other boxes on all faces, and at these points I can create these larger 9 unit modules, but then of course there are many overlapping boxes. So I am wondering if there is a way to optimise/cull boxes so that there aren’t any overlaps. Or if there is another/better logic for merging voxels together. If it’s easier to do this with 2D squares/curves this would also be helpful.

Thanks for any advice!

Merging Voxels.3dm (2.2 MB)