This is not particularly pretty, so just let me know if there's a better way to do it.