I'm not happy with how there is some duplicated code here, perhaps it could be improved.