Fix memory leaks
Rework code responsible for establishing connection