I'm not terribly happy with this code, but it works.