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.
Example:
![[Linked Image from i.ibb.co]](https://i.ibb.co/Bsy3mct/17.jpg)