This function is brain meltingly complicated, well done.