I think you should consider using a Script (and consequently ask on the Photoshop Scripting Forum).
If you do so please provide an exemplary file (in the original state and one intended result) or at least screenshots with the Layers Panel visible so that it will be clear how one could approach the issue.