This is one gnarly piece piece of code.