Modularize code by abstracting connection handling stuff into separate function. Put other stuff in main.