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: