Rearranged code so that it's better looking. Closed connection at the end