I guess at some point this logic should be split out into a reusable library, but this looks okay for now.