Lot's of copy-pasted code here, refactor to a function?