This looks like a lot of code duplication from @arrbee's PR. Is there any way this could be refactored?