refactoring a bit and making sure sockets are closed cleanly b efore exit