Need help in surface script

Hello. I am working on the definition of one minimal surface.
I think that I have a pretty good result for the moment.

But there are some things I cant get now:

I need to have a closed tight surface.
But now I have a combination of closed and open surfaces.
1. (29.6 KB)
I marked red light the places that are not correct. Blue one is what I need to have.
Can someone explain to me what is wrong?