Reordered code and split out some functionaliry.