Added a network connection check, cleaned up code