Just wrote the ugliest code in the history of the world, but it works