There's a lot of duplicated code here; better to use a helper function or something?