Messy code. But it works