fix connection problems

had problems running the code when run in a for-loop. Changed the code structure a bit to make it work.