Ok, this is pretty ugly to read, but it works.