should work

I think it's working now. Please have a look when you get the chance. I know the code is ugly, I'll refactor it if it's working.