These functions all seem to share a lot of logic, can we factor out what they have in common?