factored out some code, looks slightly less scary