Since your task is quite confusing, I'm suggest you try to depict the graphic schema (plan) in the form of a picture of what you would like to get as a result from the work of the created script.
Perhaps this will be clearer and understandable in any language, to be able to help you.

         [Linked Image from]

🅸🆁🅲 - 𝔦'𝔱𝔰 𝔸 𝕂𝖎ɴ𝙙 ᴏ𝙛 𝕄𝙖𝖌𝙞𝙘