Worst code I have ever written. But it works.