factored out networking code

Mostly factored out the networking code. Not everything is done and
there is some extraneous stuff in there, but I am going to start on the
higher level stuff and complete as I go.