moved network code and generalized to reduce repetition.