cleaned up the code and fixed the ping management bug

I have cleaned up the code and fixed the bug that resulted in some connection exceptions.