This is kind of nuts. Maybe move it to a library?